Chinaunix首页 | 论坛 | 博客
  • 博客访问: 847414
  • 博文数量: 286
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1980
  • 用 户 组: 普通用户
  • 注册时间: 2014-05-04 16:41
文章分类

全部博文(286)

文章存档

2020年(2)

2018年(5)

2017年(95)

2016年(69)

2015年(15)

2014年(100)

我的朋友

分类: C/C++

2016-10-11 16:52:27

原文地址:Linux下通过串口读数据 作者:soloforce

通过串口读数据的代码。串口连接了Arduino + MPU6050传感器模块,返回来的数据是逗号分割的加速度和角速度值。


  1. #include <stdio.h> /* Standard input/output definitions */
  2. #include <string.h> /* String function definitions */
  3. #include <unistd.h> /* UNIX standard function definitions */
  4. #include <fcntl.h> /* File control definitions */
  5. #include <errno.h> /* Error number definitions */
  6. #include <termios.h> /* POSIX terminal control definitions */

  7. /*
  8.  * @brief Open serial port with the given device name
  9.  *
  10.  * @return The file descriptor on success or -1 on error.
  11.  */
  12. int open_port(char *port_device)
  13. {
  14.     int fd; /* File descriptor for the port */

  15.     fd = open(port_device, O_RDWR | O_NOCTTY | O_NDELAY);
  16.     if (fd == -1)
  17.     {
  18.         perror("open_port: Unable to open /dev/ttyS0 - ");
  19.     }
  20.     else
  21.         fcntl(fd, F_SETFL, 0);

  22.     return (fd);
  23. }

  24. int main()
  25. {
  26.     struct termios options;

  27.     int fd=open_port("/dev/ttyACM0");
  28.     if(fd==-1){
  29.         return -1;
  30.     }

  31.     tcgetattr(fd, &options);


  32.     //Set the baud rates to 38400...
  33.     cfsetispeed(&options, B38400);
  34.     cfsetospeed(&options, B38400);


  35.     //Enable the receiver and set local mode...
  36.     options.c_cflag |= (CLOCAL | CREAD);
  37.     options.c_cflag &= ~CSIZE; /* Mask the character size bits */
  38.     options.c_cflag |= CS8; /* Select 8 data bits */

  39.     //No parity
  40.     options.c_cflag &= ~PARENB;
  41.     options.c_cflag &= ~CSTOPB;
  42.     options.c_cflag &= ~CSIZE;
  43.     options.c_cflag |= CS8;


  44.     //Set the new options for the port...
  45.     tcsetattr(fd, TCSANOW, &options);

  46.     int ax,ay,az,gx,gy,gz;
  47.     char buf[1024];
  48.     char* pos=buf;

  49.     while(1){
  50.         ssize_t n=read(fd, pos, 1);
  51.         if(n==1){
  52.             if(*pos=='\n' ){
  53.                 *(pos+1)=0;
  54.                 sscanf(buf,"%d,%d,%d,%d,%d,%d", &ax, &ay, &az, &gx, &gy, &gz);
  55.                 printf("acc/gyro: %d %d %d %d %d %d\n", ax, ay, az, gx, gy, gz);
  56.                 pos=buf;
  57.             }else{
  58.                 pos++;
  59.             }
  60.         }
  61.     }


  62.     close(fd);
  63. }

阅读(904) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~