c读取计算机串口函数,从C中的串口读取

我正在尝试用XBee从Arduino(不断发送char'4')中读取。

我尝试过从PC写入Arduino,它可以工作,所以连接是正确的。

当我执行de follow代码时,终端没有显示任何内容并且没有完成程序,所以它在阅读时卡住了。

#include // Standard input / output functions

#include

#include // String function definitions

#include // UNIX standard function definitions

#include // File control definitions

#include // Error number definitions

#include // POSIX terminal control definitions

#define XBEE "/dev/ttyUSB0"

#define BAUDRATE B9600

int main(int argc,char** argv)

{

struct termios tio;

struct termios stdio;

struct termios old_stdio;

int tty_fd = open(XBEE , O_RDWR| O_NOCTTY);

cfsetospeed(&tio,BAUDRATE);

cfsetispeed(&tio,BAUDRATE); // Baudrate is declared above

tcsetattr(tty_fd,TCSANOW,&tio);

// for(i;i<5;i++){

// write(tty_fd,&c,1); //If new data is available on the console, send it to the serial port

// write(tty_fd,&o,1); //If new data is available on the console, send it to the serial port

// }

int n=0;

char buf = '\0';

/* Whole response*/

do

{

n = read( tty_fd, &buf, sizeof(char) );

}

while( n > 0);

if (n < 0)

{

printf("ERROR READING");

}

else if (n == 0)

{

printf("Read nothing!");

}

else

{

printf("Response: %c",buf);

}

close(tty_fd);

tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);

return EXIT_SUCCESS;

}

我该如何解决这个问题?

更新

我尝试了其他代码并收到警告:关闭输出刷新然后终端冻结。

#include // Standard input / output functions

#include

#include // String function definitions

#include // UNIX standard function definitions

#include // File control definitions

#include // Error number definitions

#include // POSIX terminal control definitions

#define XBEE "/dev/ttyUSB0"

#define BAUDRATE B9600

int main(int argc,char** argv)

{

struct termios tio;

struct termios stdio;

struct termios old_stdio;

struct termios options;

int tty_fd = open(XBEE , O_RDWR | O_NOCTTY | O_NDELAY);

cfsetospeed(&tio,BAUDRATE);

cfsetispeed(&tio,BAUDRATE); // Baudrate is declared above

tcsetattr(tty_fd,TCSANOW,&tio);

options.c_cflag &= ~PARENB;

options.c_cflag &= ~CSTOPB;

options.c_cflag &= ~CSIZE;

options.c_cflag |= CS8;

// for(i;i<5;i++){

// write(tty_fd,&c,1);//if new data is available on the console, send it to serial port

// write(tty_fd,&o,1);//if new data is available on the console, send it to serial port

// }

int n=0;

char buf = '1';

int i = 1;

/* Whole response*/

while(i==1){

n = read( tty_fd, &buf, sizeof(char) );

if (n < 0)

{

printf("ERROR READING");

}

else if (n == 0)

{

printf("Read nothing!");

}

else

{

printf("Response: %c",buf);

close(tty_fd);

break;

}

}

tcsetattr(STDOUT_FILENO,TCSANOW,&old_stdio);

return EXIT_SUCCESS;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值