jiangdou 发表于 2015-5-22 19:02:23

一直有人在问如何UART接收数据,最近很忙,抱歉

本帖最后由 jiangdou 于 2015-5-22 19:09 编辑

不多说,上代码

图片为证
A10A20A31 A80RK3188RK3288都可以用
/*
*file jiangdou_passwd.c
*time 2015-05-01
*
*author by jiangdou QQ:344283973
*
*/



#include "jiangdou_passwd.h"



#include <dirent.h>

#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <errno.h>

#include <ctype.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <math.h>
#include <semaphore.h>
#include <pthread.h>
#include <termios.h>
#include <signal.h>

#include <linux/kd.h>
#include <linux/fb.h>

#include <sys/time.h>
#include <sys/ipc.h>
//#include <sys/msg.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/un.h>
//#include <sys/shm.h>
#include <sys/socket.h>
#include <sys/un.h>



pthread_t thread;
pthread_mutex_t mut;
int fd =0;
int IsReceve = 0;
unsigned char msg;
char buff;

time_t now;
struct tm *tm_now;
char *datetime;



int Set_Port(int fd,int baud_rate,int data_bits,char parity,int stop_bits)
{
      struct termios newtio,oldtio; //
      
      //fprintf(stdout,"The Fucntion Set_Port() Begin!\n");
      
      if( tcgetattr(fd,&oldtio) !=0 )
      {
                perror("Setup Serial:");
                return -1;
      }
      
      bzero(&newtio,sizeof(newtio));
      
      newtio.c_cflag |= CLOCAL | CREAD;
      newtio.c_cflag &= ~CSIZE;
      
      //Set BAUDRATE
      
      switch(baud_rate)
      {
                case 2400:
                        cfsetispeed(&newtio,B2400);
                        cfsetospeed(&newtio,B2400);
                        break;
                case 4800:
                        cfsetispeed(&newtio,B4800);
                        cfsetospeed(&newtio,B4800);
                        break;
                case 9600:
                        cfsetispeed(&newtio,B9600);
                        cfsetospeed(&newtio,B9600);
                        break;
                case 19200:
                        cfsetispeed(&newtio,B19200);
                        cfsetospeed(&newtio,B19200);
                        break;      
                case 38400:
                        cfsetispeed(&newtio,B38400);
                        cfsetospeed(&newtio,B38400);
                        break;
                case 115200:
                        cfsetispeed(&newtio,B115200);
                        cfsetospeed(&newtio,B115200);
                        break;                                                                                                                              
                default:
                        cfsetispeed(&newtio,B9600);
                        cfsetospeed(&newtio,B9600);
                        break;
               
      }
      
      //Set databits upon 7 or 8
      switch(data_bits)
      {
                case 7:
                        newtio.c_cflag |= CS7;
                        break;
                case 8:
                default:
                        newtio.c_cflag |= CS8;
      }
      
      switch(parity)
      {
                default:
                case 'N':
                case 'n':
                {
                        newtio.c_cflag &= ~PARENB;
                        newtio.c_iflag &= ~INPCK;
                }
                break;
               
                case 'o':
                case 'O':
                {
                        newtio.c_cflag |= (PARODD|PARENB);
                        newtio.c_iflag |= INPCK;
                }
                break;
               
                case 'e':
                case 'E':
                {
                        newtio.c_cflag |= PARENB;
                        newtio.c_cflag &= ~PARODD;
                        newtio.c_iflag |= INPCK;
                }
                break;
               
               
                case 's':
                case 'S':
                {
                        newtio.c_cflag &= ~PARENB;
                        newtio.c_cflag &= ~CSTOPB;
                        
                }
                break;
      }
      
      //Set STOPBITS 1 or 2
      switch(stop_bits)
      {
                default:
                case 1:
                {
                        newtio.c_cflag &= ~CSTOPB;
                }
                break;
               
                case 2:
                {
                        newtio.c_cflag |= CSTOPB;
                }
                break;
               
      }
      
      newtio.c_cc= 1;
      newtio.c_cc      = 255;      //Read Comport Buffer when the bytes in Buffer is more than VMIN bytes!
      
      tcflush(fd,TCIFLUSH);
      
      if(( tcsetattr(fd,TCSANOW,&newtio))!=0 )
      {
                perror("Com set error");
                return -1;
      }
      
      //fprintf(stdout,"The Fucntion Set_Port() End!\n");
      
      return 0;
}
int Open_Port(int com_port)
{
      int fd = 0;
      
      //fprintf(stdout,"Function Open_Port Begin!\n");
               
      char *dev[] = { "/dev/ttyS0","/dev/ttyS1","/dev/ttyS2","/dev/ttyS3","/dev/ttyS4","/dev/ttyS5","/dev/ttyS6"};
               
      if( (com_port < 0) || (com_port >6) )
      {
                perror("The port is out range:");
                return -1;
      }
      
      //Open the port      
      //fd = open(dev,O_RDWR|O_NOCTTY|O_NDELAY);
      fd = open("/dev/ttyS3",O_RDWR|O_NOCTTY|O_NDELAY);      
      if( fd<0 )
      {
                perror("Open serial port:");
                return -1;
      }
      
      if( fcntl(fd,F_SETFL,0)<0 )
      {
                perror("fcntl F_SETFL:");
                return -1;
      }
      
      if( isatty(fd) ==0 )
      {
                perror("isatty is not a terminal device");
                return -1;
      }
      
      return fd;
}




int StrToInt(char *str)
{
         int value= 0;
         int sign   = 1;
         int result = 0;
         if(NULL == str)
         {
                return -1;
         }
         if('-' == *str)
         {
                  sign = -1;
                  str++;
         }
         while(*str)
         {
                  value = value * 10 + *str - '0';
                  str++;
         }
         result = sign * value;
         return result;
}




jiangdou 发表于 2015-5-22 19:04:03

本帖最后由 jiangdou 于 2015-5-22 19:08 编辑

A10A20A31 A80RK3188RK3288都可以用

接上页void read_port(void)
{
      fd_set rd;
      int nread,retval;

      struct timeval timeout;
      FD_ZERO(&rd);
      FD_SET(fd,&rd);
      timeout.tv_sec = 3;
      timeout.tv_usec = 0;
      while(IsReceve == 1);
      retval = select(fd+1,&rd,NULL,NULL,&timeout);
      switch(retval)
      {
      case 0:
                //printf("No data input within 1 seconds.\n");
                break;
      case -1:
                perror("select:");
                break;
      default:
                if( (nread = read(fd,msg,1024))>0 )
                {
                        IsReceve =1;
                        //printf("%sReceiveMessage: %s\n",msg,datetime);
                        //printf("\n%sReceive %d bytes,Message is:\n%s\n",datetime,nread,msg);
                        sprintf(buff, "%s", msg);//warning   去掉unsigned char buff ->char buff
                        memset(msg,0,80);
                }
                break;               
      }//end of switch

}




void create_thread(void)
{
      int temp;
      memset(thread,0,sizeof(thread));
      if((temp = pthread_create(&thread,NULL,(void *)read_port,NULL)) != 0)
                printf("Create recv_thread failed!\n");
      
}

void wait_thread(void)
{

      if(thread != 0)
      {
                pthread_join(thread,NULL);//等待线程结束
                //printf("recev_thread end\n");

      }
}

//
int rk3288_shut_down()//关机
{
      
      show_error_logo();//显示SYSTEM ERROR!!
      sleep(6);//延时2S
      //xxx_xx();//关机命令
      //write(fd,"dou:shut#",9);//关机命令======="dou:shut#"
      for(;;){//死循环
                sleep(3);
      }
      return 1;
}
//


#define HOST_PORT 0

//void keyID_parse()
int main(void)
{
      int j = 0;

      if((fd = Open_Port(HOST_PORT)) == -1)
      {
                perror("Open port");
                return -1;
      }
      
      if( Set_Port(fd,9600,8,'N',1) == -1)
      {
                perror("Set_Port");
                return -1;
      }
      
      //Serial_SendStr(fd,"Hello This is from Ubuntu\n");

      pthread_mutex_init(&mut,NULL);
//###########################################################
//取随机数,发送到MCUMCU解析dou:1234   a=1234//keyID = (a * 2) - 3   send keyID to rk3288
      unsigned char x;
      unsigned int i;
      char buf;
      int local_ID;
      char read_buf;
      char *pp = read_buf;
      char *ppp = buff;// ->unsigned
      srand(time(0));
      i = rand();//取随机数
      x = (char)((i >> 8) & 0xff);//16bit_height
      //printf("x =%xxsize = %d\n", x, sizeof(x));
      x = (char)((i >> 24) & 0xff);//16bit_height
      //printf("x =%xxsize = %d\n", x, sizeof(x));
      sprintf(buf, "dou:%d#\r", ((x << 8) | x) & 0xffff);//sprintf(s, "", ,)//(((x << 8) | x) & 0xffff)

//###########################################################
      while(1)//####
      {
                whi++;
                send_dou++;
                time(&now);
                tm_now = localtime(&now);
                datetime=asctime(tm_now);
               
                create_thread();
      wait_thread();//等待线程结束
               
                //printf("jiangdou while\n");
                //write(fd,"while...",8);
                usleep(3000);//毫秒延时
                write(fd,buf,strlen(buf));//key_id = "dou:1234#"
                if( IsReceve ==1)//表示有recv数据
      {
                        //printf("Message is:%s\n",buff);//recv "dou:65151"
                        //write(fd,"ifif...",7);
                        
                        bb = strstr(ppp, "dou:");//recv str = "dou:65151"
                        if(bb != NULL){
                              
                              bb = strstr(ppp, ":");
                              sprintf(read_buf, "%s",(bb + 1));
                              key_id = StrToInt(pp);//key_id = 65151;
                                 
                              
                              
                              if(reve_id == local_ID){
                              //if(key_id == 2135){////"dou:2135\r\n");//收到KEY_ID
                                       
                                        goto go_on;// passwd success!!
                                       
                              }else{
                                        //close(fd);
                                        ;
                                        if(send_dou > 5){
                                                rk3288_shut_down();//关机
                                           // passwd fali!!!
                                       
                                        }
                                       
                              }
                        }
                        
                        
                        IsReceve = 0;
                        
                        
                }
               
                        
                if(whi > 5){
                         // fali!!!time out 5S!!
                        whi = 0;
                        //close(fd);
                        rk3288_shut_down();//关机      
                }
   

      }
go_on:      
      close(fd);
      
      return 0;

}

lin 发表于 2015-5-25 14:41:17

{:soso_e166:}

hhyytt 发表于 2015-5-26 09:35:17

:):)
不错的教程。

soloforce 发表于 2015-6-28 19:56:37

很好的串口操作实例,精华之:lol

lisgo 发表于 2015-11-27 09:22:14

:lol:lol:lol:lol 详细 码风也好。

北冥 发表于 2016-4-13 11:40:21

来研究研究

wty123 发表于 2016-7-26 10:33:10

<P>said, longchamp outletfirst toms shoesof lululemon outletall designer handbagsI can coach outlet onlinenot swim, polo ralph lauren outletI prada outletwill find hogana lululemon australiarelatively shallow northfacefulcrum, gucci beltsmake ray banevery mcm bagseffort to tory burch shoessave swarovski jewelryhis cheap basketball shoeswife, michael kors v?skoruntil cheap oakley sunglasseshis nike free shoeswife new balanceout hollisterof pumathe oakley outlet onlinewater, and secondly, baseball jerseysI converse shoeswould tommy hilfigerlove nfl bearshandles red bottomsthrow mother, beats by drebecause the tory burch salemother replica rolexYear Great, toronto raptorsmore experienced, ralph lauren outletwill jimmy chooswim a toms shoes outletlittle, timberland bootsso chanel pursesadd nfl titansspare mont blanc penstire, pandora ringsI believe tory burch shoesswim burberry handbagsout ralph laurenof asicsthe puma outlet storewater raybanjust longchamp taschena hilfiger outletmatter nike airof bottega venetatime.Besides, supra footwearnot coach factory outlet onlineif, lunette ray ban pas cherbut nfl azcardinalsrather raybantogether burberrywith juicy couture clothingsefforts toms outletmade kate spade outletto barbour mens jacketssave, moncler outlet onlineeither nfl chargersthey ralph lauren ukwill vans schuhenot michael kors outlet onlineswim, encounter maccosmetics.comthis michael kors handbagskind nfl lionsof burberrything, ray ban sunglassesthe hollister online shop deutschlandshot will the north face outletbe.We michael korslook supra men shoesat nike.dethe new balanceforeigners chanel sunglassessay, michael kors bagsthe north face outletsame adidas shoesproblem gucci shoescan woolrich clearanceonly nfl saintssave huarachesone, free runthen, after air max shoesa silence cheap glassesforeigner bos jerseyanswer: nike.seThis is thomas sabo uka nfl dolphinscruel nfl steelersquestion, if ed hardy clothingI vans shoeshad nike outlet storeto choose, timberland shoesI tiffanysaved ray ban sunglassesmy nfl cowboyswife. Ask air jordan retrowhy. He montre pas chersaid: nike rosheFirst swarovski crystalof coach outletall, philadelphia 76ers jerseymy north facemother had uggaustralia.coma nfl patriotsbig nfl 49ersyear bcbg dresses(75 years soccer shoesold). nfl buccaneersMost cheap nike shoesof burberry outlet onlineher life polo outlet onlinehas mcm handbagsbeen finished, tommy hilfiger outlet storesbut free runningmy wife iphone 4s caseswas lululemonstill air jordanyoung. toms outletSecondly, ralph lauren outlet onlineif we ugg australiahave designer handbagschildren new balanceto oakley sunglasses cheapsupport, the roshesmore cheap michael korsI nfl pantherswill lunette oakley pas chernot hesitate to nfl raiderssave nike huarachehis wife. nike free runThe nike air max 2015children nike air forcecan tommy hilfigernot ralph lauren outletdo pandorawithout nike.comher polo ralph laurenmother. watchesMoreover, coach bagseven ralph laurenif uggs outletmy rolex replicaown cheap eyeglassesmother hermes birkinwill long champlet washington wizardsme burberry salesave his michael kors purseswife, jordans for salenot toms.comto asics gelsave ray ban sunglassesher, nfl broncoshe pandorawill nfl chiefsdefinitely michael kors outletbe kate spade outlet onlineto save his christian louboutinwife.From nike onlinethe adidas.deInternet coco chanelto coach outletsee burberry ukthis nfl texansthree ray ban outletstory, bottegalet ray bansme lululemon canadadeep converseemotion.The ugg bootsfirst ralph lauren ukstory: san antonio spursread goosesthe mia jerseyunmarried married air max 90again, timberland outletmarried louboutinthe burberry outlet onlineknow tory burch sandalshow nfl falconsto tiffany jewelryunderstand ray ban zonnebrilthe Nike Free Shoesbusiness gsw jerseysof nfl billsmarriage, chaneldo milwaukee bucksnot uggsunderstand you abercrombiecan hollister clothing storenot get relojes especialesmarried. nike rosheThey love ralph lauren onlinethe insanity calendarstory of clothing websitesa rolexthree-year, ready los angeles clippersto get nike mercurial vapormarried. Before ugg boots clearancemarriage a nike mercurialmonth adidas neohe nfl ravensdisappeared, barbour outletleaving nike.dkbehind tiffany and coa adidas.senote: beats by dreI'm abercrombiesorry, giuseppe zanottiso salomon schuheI good nike outletenough louboutinwhen wedding dressesI nike outletmarry you. reebokHer burberry handbagsgrief hermes bagstear strip.Two years zapatillas nikelater, lulu lemonhe p90x workout schedulewas wearing burberry online shopa the north facesuit polo ralph lauren outlet onlineand driving chicago bullsa nets jerseylimited nfl ramsedition ray ban sunglasses outletsports adidascar swarovski australiaback, utah jazzbut celine handbagsfound ray banthat she softball batshad michaelkors.commarried oakley outletan ordinary michael kors outletworker pandoraand toms outlethave nike huaracheshad nike air maxchildren. pradaHe true religion jeans womenwas a new balance storebit angry, you tiffany and cowould polo ralph laurenrather marry pandora braceletsa coach outletsuch kate spadea orlando magicnothing replica watchesof north face jacketswhat nike shoes outletpeople tommy hilfiger online shopare longchamp handbagsnot flat ironwilling pistons jerseyto north face pas cherwait burberry handbagsfor nfl jaguarsme. coach factory outlet onlineWoman smiled nfl bengalsgently, polo ralph lauren outletwe do knicks jerseysnot baseball batsneed anything, love swarovskiis calvin kleinenough! uggsMan mcm handbagssuddenly longchampunderstood.The second story: air maxthe nfl packersboy cheap ray banon fake rolexhis gucci outletwife nfl coltsafter marriage oakleythan air jordan shoesbefore michael kors outletmarriage abercrombie and fitchbetter. A nop jerseysgathering of friends levis outlet storelaughed coach bagsat him: portland trail blazershow jordan release datesmarried michael kors handbagsalso so tired. oakley sunglasses outletSamsam ralph lauren shirtssmile nba jerseyshe prada outletsaid: prada handbags"Before ray-ban sunglassesmarriage, dre beatsa michael kors outlet onlinelot occhiali oakleyof michael kors australiathe boys michael kors bagswant ugg australiato giuseppe shoesgo toms outletafter gucci shoes outlether, abercrombieshe would cheap oakley sunglasseshave ralph lauren factory storea beats audiolot burberry outletof louboutinsgood ray ban sunglassesboys, burberry handbagsI jimmy choo shoesonly hair straightenerbetter hermes outletfor her cheap true religionto coach outlet onlinecatch cheap oakleyher; jordan shoesmarried www.tommyhilfiger.nlto her less michael kors bagsand uggless oakleygood burberry outlet onlineboys, mcm backpack outletI tiffany and coonly air max 90better for chi hairher minnesota timberwolvesto guccilet her ralph laurenloss. gucci handbagsI swarovskijust air max 2014did coach factory outleteverything ray ban wayfarerto make her oakleyhappy. ferragamo shoes"Then, coach outlet saleall new balance shoespresent juicy couturefriends are oakley sunglasses outletsilent, polo ralph laurenno abercrombie fitchridicule, michael korsonly uggs outletadmiration.The memphis grizzliesthird michael kors handbagsstory: longchamp outletthe canada gooses outlethusband air max 95care about cheap oakleyto moncler women jacketsgive prada sunglassesbirth nike storeat the uggsbedside ray banof true religionhis wife. suns jerseysWife: ferragamo"Do ray ban outletyou want nfl redskinsa shoes on saleboy ghd hair straighternersor a swarovskigirl?" air max 2015Husband: beats audio"If it michael kors outlet onlineis a nike air max 2014boy, wedding dresses ukwe kobe bryant jerseyYeliang true religion jeans outletprotect you; the north faceif polo ralphyou are michael kors outlet online salea longchampgirl, oakley prescriptionI wholesale handbagsNiangliang tiffany und coprotect you."Say that marriage michael korsis toms shoesthe nike free 5.0tomb mizuno running shoesof timberland hommelove. nba jerseysIt nba jerseysturned out to nfl eaglesbe gucci shoesa good nike air maxwoman to coach handbags outletmarry nike outletthe uggwrong Lang! burberry bags outletLove marc jacobs handbagsis hollister conot wealth, uggsbut to uhreneach michael kors bagsother. christian louboutin shoesThe marriage is converse chucksa oakley sunglasseshappy michael kors bagsthing, instyler ionic styleras long cleveland cavaliers jerseysas abercrombie and fitch kidsyou sac jerseyswill iphone 5 casestreasure married man.Then nfl seahawksyour mcm outlethouse, you sleep adidas superstarjust oakley sunglassesa coach factory outlet onlinebed; cheap oakley sunglassesno louboutin outletmatter nfl brownshow michael kors outlet onlinegood katespade outletthe ralph lauren polocar, nfl jetsspeeding gucci mens shoestickets nike huarachesor nfl vikingseat; pandora jewellerythen your coach pursesbag, only michael kors outlet online salea michael kors canadashow denver nuggets off their coach factory onlinewealth ugg australiamore indiana pacersfeatures than adidas sneakersplastic houston rocketsbags.Not valentino shoes outletto the north facepursue mac cosmeticsnot, replica handbagsforgetting air maxtheir dallas mavericks jerseyexisting bcbg max azriahappiness, air jordanscontentment!Choose the wedding dresses ukperson coach outlet storeyou love, babylissor nfl giantschoose to russell westbrook jerseylove vans outletyou, thomas sabohow roche runto choose nike airlove, michael korschoose what hollister kidskind of happiness, charlotte hornets jerseythe mcm bagschoice is converse outleta roshe runpermanent roshe runproposition, salvatore ferragamochoose the north face outletwhat, nike air maxor what is selected, wedding dressessometimes, michael kors purseswe omega watchesneed abercrombie.comto rayban sunglasseskeep nike tn requina cool head, uggswe replica watchesneed marc jacobs outletto north face backpacksmake nfl jerseyshard replica watcheschoice, coach factory outlet onlinebut gafas oakleythere jerseys from chinais hilfigera coach purseshappiness for scarpe hogan</P>
页: [1]
查看完整版本: 一直有人在问如何UART接收数据,最近很忙,抱歉