使用RS232连接和C代码从Arduino串口读取

时间:2013-10-18 13:30:55

标签: c serial-port arduino

我有一个运行以下代码的Arduino Uno:

byte data;

void setup(){
   Serial.begin(9600);
}

void loop(){

  data = 0xAA;
  Serial.write(data);
  delay(1000);
}

这很简单,只需每秒将0xAA的值写入串行TX引脚。

我已将串行TX引脚连接到DB9分支电缆的引脚3,并将分支电缆的引脚5连接到Arduino上的接地。然后将串行电缆插入连接到笔记本电脑USB端口的USB串行转换器。根据以往的经验,我知道USB串行转换器是可靠的,不会扭曲数据。

在我的笔记本电脑上,我正在运行下面的代码,我希望每秒都能看到AA打印到屏幕上,但是,我看到的值是15。我的代码有什么问题,或者这是由不同的电压水平引起的?

 void dump_packet(void* packet, int len)
 {
u_int8_t* bytes = (u_int8_t*)packet;
int i = 0;  

while (i < len){
    if (i == len-1){
        printf("%02X-", bytes[i++]);
    }
    else{
        printf("%d", bytes[i++]);
        }
}   
 }

 int ttySetRaw(int fd, struct termios *prevTermios)
 {
 struct termios t;
 if (tcgetattr(fd, &t) == -1)
  return -1;
 if (prevTermios != NULL)
 *prevTermios = t;
 t.c_lflag &= ~(ICANON | ISIG | IEXTEN | ECHO);
 t.c_iflag &= ~(BRKINT | ICRNL | IGNBRK | IGNCR | INLCR |
 INPCK | ISTRIP | IXON | PARMRK);
 t.c_oflag &= ~OPOST; /* Disable all output processing */
 t.c_cc[VMIN] = 1; /* Character-at-a-time input */
 t.c_cc[VTIME] = 0; /* with blocking */
 if (tcsetattr(fd, TCSAFLUSH, &t) == -1)
   return -1;
 return 0;
 }

 int main()
 {
   struct termios  tty;
   struct termios  savetty;
   speed_t     spd;
   unsigned int    sfd;
   unsigned char   buf[12];
   int reqlen = 79;
   int     rc;
   int     rdlen;
   int success;

   sfd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NONBLOCK);
   rc = tcgetattr(sfd, &tty);
   if (rc < 0) {
    printf("failed to get attr: %d, %s", rc, strerror(errno));
    exit (-2);
   }
   savetty = tty;    /* preserve original settings for restoration */

   success = ttySetRaw(sfd, &tty);
   spd = B9600;
   cfsetospeed(&tty, (speed_t)spd);
   cfsetispeed(&tty, (speed_t)spd);

   if (sfd > 0 && success == 0){
printf("TTY set up ready to Read:\n\n");
   }

   memset(&buf[0], 0, sizeof(buf));

   do {
    rdlen = read(sfd, buf, reqlen);
  if (rdlen != -1){
    printf("Read %d bytes\n", rdlen);
    dump_packet( buf, rdlen);
   }

   } while (1);

   tcsetattr(sfd, TCSANOW, &savetty);
   close(sfd);
   exit (0);

   return 0;
   }

0 个答案:

没有答案