LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 2777|回复: 2

急!!linux下串口通讯编程,read()不能读数据的原因?

[复制链接]
发表于 2008-12-29 09:44:55 | 显示全部楼层 |阅读模式
急!!linux下串口通讯编程,read()不能读数据的原因?
!!本人菜鸟一个,刚编写了一段串口通讯程序,但是只能发送数据,不能接收数据,这是什么原因啊?请个位大侠不吝赐教,万分感谢!!
主函数代码如下:
volatile int STOP=FALSE;  
int main(void)
{       int i;
        int fd;
        char send_buff[8]="OPEn";
        int send_length;
        int byteswrite;

        char rcv_buff[8];
        int rcv_length;
        int bytesread;

        char *dev = "/dev/ttyS1";
        fd = OpenDev(dev);  // fd= open("/dev/ttyS1",O_RDWR | O_NOCTTY);
        
        set_speed(fd,2400);  //波特率2400
        if(set_Parity(fd,8,1,'N') == FALSE) //设置8,1,n
        {
                printf("Set Parity Error\n") ;
                exit(0);
        }
         
       bzero(rcv_buff,sizeof(rcv_buff));

       //发送数据,这里功能正常,能发送出数据“OPEn”
        for(i=0;i<10;i++)
        byteswrite=write(fd,send_buff,8 ) ; //成功返回写入数据的字节数,该值通常等于length,如果写入失败返回-1
        if(byteswrite==-1)
        {
                printf("write device %s error\n",*dev);
        }
               
        //读取数据!!这里的功能不能实现!!
        while (STOP==FALSE)
        {   
                    bytesread =read(fd,rcv_buff,8 ) ; //读操作成功读取返回读取的字节数,失败则返回-1
                    rcv_buff[bytesread+1]='\0';        /* 设定字串终止字元, 所以我们能用 printf */
                    printf("%s,%d\n",rcv_buff, bytesread);
                    if (rcv_buff[0]=='z')
                                STOP=TRUE;
        }

                     
        if(close(fd)!=0)
        {
                printf("close device %s error",*dev);
        }
        return;
} 
发表于 2009-1-16 19:15:59 | 显示全部楼层
while (STOP==FALSE)
{
bytesread =read(fd,rcv_buff,8 ) ; //读操作成功读取返回读取的字节数,失败则返回-1 此處讀了8個??
rcv_buff[bytesread+1]='\0'; /* 设定字串终止字元, 所以我们能用 printf */如果再寫\0是不是9個了???超範圍了
printf("%s,%d\n",rcv_buff, bytesread);
if (rcv_buff[0]=='z')
STOP=TRUE;
}
回复 支持 反对

使用道具 举报

发表于 2009-3-8 18:30:05 | 显示全部楼层

A Linux serial port test program

引用于:www.2beanet.com
A Linux serial port test program


Below is a Linux serial test program which requires the command parameters to be entered on the command line when the program is started. This program will send output typed on the computer keyboard after the program is started, through the serial port specified.


  1. #include <termios.h>
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <sys/signal.h>
  6. #include <sys/types.h>
  7. #define BAUDRATE B38400
  8. #define MODEMDEVICE "/dev/ttyS1"
  9. #define _POSIX_SOURCE 1  //POSIX compliant source
  10. #define FALSE 0
  11. #define TRUE 1
  12. volatile int STOP=FALSE;
  13. void signal_handler_IO (int status);//definition of signal handler
  14. int wait_flag=TRUE;     //TRUE while no signal received
  15. char devicename[80];
  16. long Baud_Rate = 38400;    //default Baud Rate (110 through 38400)
  17. long BAUD;       //derived baud rate from command line
  18. long DATABITS;
  19. long STOPBITS;
  20. long PARITYON;
  21. long PARITY;
  22. int Data_Bits = 8;     //Number of data bits
  23. int Stop_Bits = 1;     //Number of stop bits
  24. int Parity = 0;      //Parity as follows:
  25.                   //00 = NONE, 01 = Odd, 02 = Even, 03 = Mark, 04 = Space
  26. int Format = 4;
  27. FILE *input;
  28. FILE *output;
  29. int status;
  30. main(int Parm_Count, char *Parms[])
  31. {
  32.    char version[80] = "POSIX compliant Communications test program version 1.00 4-25-1999\r\n";
  33.    char version1[80] = "Copyright(C) Mark Zehner/Peter Baumann 1999\r\n";
  34.    char version2[80] = "This code is based on a DOS based test program by Mark Zehner and a Serial\r\n";
  35.    char version3[80] = "Programming POSIX howto by Peter Baumann, integrated by Mark Zehner\r\n";
  36.    char version4[80] = "This program allows you to send characters out the specified port by typing\r\n";
  37.    char version5[80] = "on the keyboard.  Characters typed will be echoed to the console, and \r\n";
  38.    char version6[80] = "characters received will be echoed to the console.\r\n";
  39.    char version7[80] = "The setup parameters for the device name, receive data format, baud rate\r\n";
  40.    char version8[80] = "and other serial port parameters must be entered on the command line \r\n";
  41.    char version9[80] = "To see how to do this, just type the name of this program. \r\n";
  42.    char version10[80] = "This program is free software; you can redistribute it and/or modify it\r\n";
  43.    char version11[80] = "under the terms of the GNU General Public License as published by the \r\n";
  44.    char version12[80] = "Free Software Foundation, version 2.\r\n";
  45.    char version13[80] = "This program comes with ABSOLUTELY NO WARRANTY.\r\n";
  46.    char instr[100] ="\r\nOn the command you must include six items in the following order, they are:\r\n";
  47.    char instr1[80] ="   1.  The device name      Ex: ttyS0 for com1, ttyS1 for com2, etc\r\n";
  48.    char instr2[80] ="   2.  Baud Rate            Ex: 38400 \r\n";
  49.    char instr3[80] ="   3.  Number of Data Bits  Ex: 8 \r\n";
  50.    char instr4[80] ="   4.  Number of Stop Bits  Ex: 0 or 1\r\n";
  51.    char instr5[80] ="   5.  Parity               Ex: 0=none, 1=odd, 2=even\r\n";
  52.    char instr6[80] ="   6.  Format of data received:  1=hex, 2=dec, 3=hex/asc, 4=dec/asc, 5=asc\r\n";
  53.    char instr7[80] =" Example command line:  com ttyS0 38400 8 0 0 4 \r\n";
  54.    char Param_strings[7][80];
  55.    char message[90];
  56.    int fd, tty, c, res, i, error;
  57.    char In1, Key;
  58.    struct termios oldtio, newtio;       //place for old and new port settings for serial port
  59.    struct termios oldkey, newkey;       //place tor old and new port settings for keyboard teletype
  60.    struct sigaction saio;               //definition of signal action
  61.    char buf[255];                       //buffer for where data is put
  62.    input = fopen("/dev/tty", "r");      //open the terminal keyboard
  63.    output = fopen("/dev/tty", "w");     //open the terminal screen
  64.    if (!input || !output)
  65.    {
  66.       fprintf(stderr, "Unable to open /dev/tty\n");
  67.       exit(1);
  68.    }
  69.    error=0;
  70.    fputs(version,output);               //display the program introduction
  71.    fputs(version1,output);
  72.    fputs(version2,output);
  73.    fputs(version3,output);
  74.    fputs(version4,output);
  75.    fputs(version5,output);
  76.    fputs(version6,output);
  77.    fputs(version7,output);
  78.    fputs(version8,output);
  79.    fputs(version9,output);
  80.    fputs(version10,output);
  81.    fputs(version11,output);
  82.    fputs(version12,output);
  83.    fputs(version13,output);
  84.    //read the parameters from the command line
  85.    if (Parm_Count==7)  //if there are the right number of parameters on the command line
  86.    {
  87.       for (i=1; i<Parm_Count; i++)  // for all wild search parameters
  88.       {
  89.          strcpy(Param_strings,Parms);
  90.       }
  91.       i=sscanf(Param_strings[0],"%s",devicename);
  92.       if (i != 1) error=1;
  93.       i=sscanf(Param_strings[1],"%li",&Baud_Rate);
  94.       if (i != 1) error=1;
  95.       i=sscanf(Param_strings[2],"%i",&Data_Bits);
  96.       if (i != 1) error=1;
  97.       i=sscanf(Param_strings[3],"%i",&Stop_Bits);
  98.       if (i != 1) error=1;
  99.       i=sscanf(Param_strings[4],"%i",&Parity);
  100.       if (i != 1) error=1;
  101.       i=sscanf(Param_strings[5],"%i",&Format);
  102.       if (i != 1) error=1;
  103.    //output the received setup parameters
  104.       sprintf(message,"Device=%s, Baud=%li\r\n",devicename, Baud_Rate);
  105.       fputs(message,output);
  106.       sprintf(message,"Data Bits=%i  Stop Bits=%i  Parity=%i  Format=%i\r\n",
  107.     Data_Bits, Stop_Bits, Parity, Format);
  108.       fputs(message,output);
  109.    }  //end of if param_count==7
  110.    if ((Parm_Count==7) && (error==0))  //if the command line entries were correct
  111.    {                                    //run the program
  112.       tty = open("/dev/tty", O_RDWR | O_NOCTTY | O_NONBLOCK);//set the user console port up
  113.       tcgetattr(tty,&oldkey); // save current port settings
  114.    //so commands are interpreted right for this program
  115.       //set new port settings for non-canonical input processing  //must be NOCTTY
  116.       newkey.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
  117.       newkey.c_iflag = IGNPAR;
  118.       newkey.c_oflag = 0;
  119.       newkey.c_lflag = 0;       //ICANON;
  120.       newkey.c_cc[VMIN]=1;
  121.       newkey.c_cc[VTIME]=0;
  122.       tcflush(tty, TCIFLUSH);
  123.       tcsetattr(tty,TCSANOW,&newkey);
  124.       switch (Baud_Rate)
  125.       {
  126.          case 38400:
  127.          default:
  128.             BAUD = B38400;
  129.             break;
  130.          case 19200:
  131.             BAUD  = B19200;
  132.             break;
  133.          case 9600:
  134.             BAUD  = B9600;
  135.             break;
  136.          case 4800:
  137.             BAUD  = B4800;
  138.             break;
  139.          case 2400:
  140.             BAUD  = B2400;
  141.             break;
  142.          case 1800:
  143.             BAUD  = B1800;
  144.             break;
  145.          case 1200:
  146.             BAUD  = B1200;
  147.             break;
  148.          case 600:
  149.             BAUD  = B600;
  150.             break;
  151.          case 300:
  152.             BAUD  = B300;
  153.             break;
  154.          case 200:
  155.             BAUD  = B200;
  156.             break;
  157.          case 150:
  158.             BAUD  = B150;
  159.             break;
  160.          case 134:
  161.             BAUD  = B134;
  162.             break;
  163.          case 110:
  164.             BAUD  = B110;
  165.             break;
  166.          case 75:
  167.             BAUD  = B75;
  168.             break;
  169.          case 50:
  170.             BAUD  = B50;
  171.             break;
  172.       }  //end of switch baud_rate
  173.       switch (Data_Bits)
  174.       {
  175.          case 8:
  176.          default:
  177.             DATABITS = CS8;
  178.             break;
  179.          case 7:
  180.             DATABITS = CS7;
  181.             break;
  182.          case 6:
  183.             DATABITS = CS6;
  184.             break;
  185.          case 5:
  186.             DATABITS = CS5;
  187.             break;
  188.       }  //end of switch data_bits
  189.       switch (Stop_Bits)
  190.       {
  191.          case 1:
  192.          default:
  193.             STOPBITS = 0;
  194.             break;
  195.          case 2:
  196.             STOPBITS = CSTOPB;
  197.             break;
  198.       }  //end of switch stop bits
  199.       switch (Parity)
  200.       {
  201.          case 0:
  202.          default:                       //none
  203.             PARITYON = 0;
  204.             PARITY = 0;
  205.             break;
  206.          case 1:                        //odd
  207.             PARITYON = PARENB;
  208.             PARITY = PARODD;
  209.             break;
  210.          case 2:                        //even
  211.             PARITYON = PARENB;
  212.             PARITY = 0;
  213.             break;
  214.       }  //end of switch parity
  215.       //open the device(com port) to be non-blocking (read will return immediately)
  216.       fd = open(devicename, O_RDWR | O_NOCTTY | O_NONBLOCK);
  217.       if (fd < 0)
  218.       {
  219.          perror(devicename);
  220.          exit(-1);
  221.       }
  222.       //install the serial handler before making the device asynchronous
  223.       saio.sa_handler = signal_handler_IO;
  224.       sigemptyset(&saio.sa_mask);   //saio.sa_mask = 0;
  225.       saio.sa_flags = 0;
  226.       saio.sa_restorer = NULL;
  227.       sigaction(SIGIO,&saio,NULL);
  228.       // allow the process to receive SIGIO
  229.       fcntl(fd, F_SETOWN, getpid());
  230.       // Make the file descriptor asynchronous (the manual page says only
  231.       // O_APPEND and O_NONBLOCK, will work with F_SETFL...)
  232.       fcntl(fd, F_SETFL, FASYNC);
  233.       tcgetattr(fd,&oldtio); // save current port settings
  234.       // set new port settings for canonical input processing
  235.       newtio.c_cflag = BAUD | CRTSCTS | DATABITS | STOPBITS | PARITYON | PARITY | CLOCAL | CREAD;
  236.       newtio.c_iflag = IGNPAR;
  237.       newtio.c_oflag = 0;
  238.       newtio.c_lflag = 0;       //ICANON;
  239.       newtio.c_cc[VMIN]=1;
  240.       newtio.c_cc[VTIME]=0;
  241.       tcflush(fd, TCIFLUSH);
  242.       tcsetattr(fd,TCSANOW,&newtio);
  243.       // loop while waiting for input. normally we would do something useful here
  244.       while (STOP==FALSE)
  245.       {
  246.          status = fread(&Key,1,1,input);
  247.          if (status==1)  //if a key was hit
  248.          {
  249.             switch (Key)
  250.             { /* branch to appropiate key handler */
  251.                case 0x1b: /* Esc */
  252.                   STOP=TRUE;
  253.                   break;
  254.                default:
  255.                   fputc((int) Key,output);
  256. //                  sprintf(message,"%x ",Key);  //debug
  257. //                  fputs(message,output);
  258.                   write(fd,&Key,1);          //write 1 byte to the port
  259.                   break;
  260.             }  //end of switch key
  261.          }  //end if a key was hit
  262.          // after receiving SIGIO, wait_flag = FALSE, input is available and can be read
  263.          if (wait_flag==FALSE)  //if input is available
  264.          {
  265.             res = read(fd,buf,255);
  266.             if (res?)
  267.             {
  268.                for (i=0; i<res; i++)  //for all chars in string
  269.                {
  270.                   In1 = buf;
  271.                   switch (Format)
  272.                   {
  273.                      case 1:         //hex
  274.                         sprintf(message,"%x ",In1);
  275.                         fputs(message,output);
  276.                         break;
  277.                      case 2:         //decimal
  278.                         sprintf(message,"%d ",In1);
  279.                         fputs(message,output);
  280.                         break;
  281.                      case 3:         //hex and asc
  282.                         if ((In1?) || (In1?))
  283.                         {
  284.                            sprintf(message,"%x",In1);
  285.                            fputs(message,output);
  286.                         }
  287.                         else fputc ((int) In1, output);
  288.                         break;
  289.                      case 4:         //decimal and asc
  290.                      default:
  291.                         if ((In1?) || (In1?))
  292.                         {
  293.                            sprintf(message,"%d",In1);
  294.                            fputs(message,output);
  295.                         }
  296.                         else fputc ((int) In1, output);
  297.                         break;
  298.                      case 5:         //asc
  299.                         fputc ((int) In1, output);
  300.                         break;
  301.                   }  //end of switch format
  302.                }  //end of for all chars in string
  303.             }  //end if res?
  304. //            buf[res]=0;
  305. //            printf(":%s:%d\n", buf, res);
  306. //            if (res==1) STOP=TRUE; /* stop loop if only a CR was input */
  307.             wait_flag = TRUE;      /* wait for new input */
  308.          }  //end if wait flag == FALSE
  309.       }  //while stop==FALSE
  310.       // restore old port settings
  311.       tcsetattr(fd,TCSANOW,&oldtio);
  312.       tcsetattr(tty,TCSANOW,&oldkey);
  313.       close(tty);
  314.       close(fd);        //close the com port
  315.    }  //end if command line entrys were correct
  316.    else  //give instructions on how to use the command line
  317.    {
  318.       fputs(instr,output);
  319.       fputs(instr1,output);
  320.       fputs(instr2,output);
  321.       fputs(instr3,output);
  322.       fputs(instr4,output);
  323.       fputs(instr5,output);
  324.       fputs(instr6,output);
  325.       fputs(instr7,output);
  326.    }
  327.    fclose(input);
  328.    fclose(output);
  329. }  //end of main
  330. /***************************************************************************
  331. * signal handler. sets wait_flag to FALSE, to indicate above loop that     *
  332. * characters have been received.                                           *
  333. ***************************************************************************/
  334. void signal_handler_IO (int status)
  335. {
  336. //    printf("received SIGIO signal.\n");
  337.    wait_flag = FALSE;
  338. }
复制代码

An example invocation of this program
This program will allow a user to communicate from one computer to another using two serial lines. It is intended only as a test for the serial connection allowing any possible serial setting. This program is named com when compiled. To use it, the following is an example command line:

  1. com /dev/ttyS0 38400 8 1 0 4
复制代码

This line works for com1 at 38400 baud, 8 data bits. I make it a file, call it "fcom1" and put it in my system path and invoke it as a script program.
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表