linux java读取串口_无法读取linux中的串口

我需要学习如何读写串口 . 出于测试目的,我将传输线连接到接收线并通过示波器检查信号行为 . 我可以看到写入正常:1个数据字节从Tx传输到Rx . 但函数 read(fd, &rcv_val, 1) 返回-1 .

使用了不同的端口:“/ dev / ttyUSB0”,“/ dev / ttyS5” .

我在这个网站上看到了类似的问题,但它并没有帮我解决问题 .

码:

int res = 0;

int fd; /* File descriptor for the port */

int snd_val, rcv_val;

fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);

if (fd == -1){//Could not open the port.

fprintf(stderr, "open_port: Unable to open /dev/ttyUSB0 - %s\n", strerror(errno));

return fd;

}

speed_t baud = B38400;

struct termios settings;

tcgetattr(fd, &settings);

cfsetispeed(&settings, baud); // baud rate

cfsetospeed(&settings, baud); // baud rate

settings.c_cflag &= ~PARENB; // no parity

settings.c_cflag &= ~CSTOPB; // 1 stop bit

settings.c_cflag &= ~CSIZE;

settings.c_cc[VMIN] = 1;

settings.c_cc[VTIME] = 0;

settings.c_cflag |= (CS8 | CLOCAL | CREAD);

tcflush(fd, TCOFLUSH | TCIFLUSH);

tcsetattr(fd, TCSANOW, &settings);// apply the settings

snd_val = 0xA5;

write(fd, &snd_val, 1);

if (res < 0){

printf("Err wr\n");

return res;

}

else printf("send ok\n");

res = read(fd, &rcv_val, 1);

if (res < 0){

printf("Err rd\n");

return res;

}else printf("rcv_val = 0x%02X\n", rcv_val);

return res;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值