佚名通过本文主要向大家介绍了小白求助,编程小白学python,小白学编程,编程小白的第一本,小白编程等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
问题: 串口编程 小白求助。
描述:
系统:ubuntu。
我没有串口编程的经验。遇到的问题是:收到的数据乱码,就算打印收到字符的ascii码也不对。
求高手帮我看看代码有什么问题:
这是发送的代码:
下面是接收的代码:
这两个ttyUSB是通过zigbee透传设备组网连接到一起的。
1.使用官网上的测试工具,两个串口之间可以正常通讯,所以是设备问题的几率应该不大。
2. 我用java rxtx写的代码收发也是不一样。
3. 在ubuntu中使用两个cutecom,相互发送,收发不一样。
4. 发送端使用我的代码,接收端使用cutecom,收发也不一样。
这个东西我看了一个多星期了,找不到解决办法或排错办法。跪求大神指点!!!
描述:
本帖最后由 dagewxw 于 2016-06-11 11:20:25 编辑
串口通讯
目的:两个串口之间的数据收发。系统:ubuntu。
我没有串口编程的经验。遇到的问题是:收到的数据乱码,就算打印收到字符的ascii码也不对。
求高手帮我看看代码有什么问题:
这是发送的代码:
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
#include<termios.h>
int open_port(void){
int fd;
fd = open("/dev/ttyUSB1", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("unable to open port /dev/ttyUSB1");
} else {
fcntl(fd, F_SETFL, 0);
}
return fd;
}
int main(void) {
int fd = open_port();
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_cflag |= CNEW_RTSCTS;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
tcsetattr(fd, TCSANOW, &options);
int n = write(fd, "a", 1);
if (n < 0)
fputs("write() of 4 bytes failed!\n", stderr);
close(fd);
return 0;
}
下面是接收的代码:
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
#include<termios.h>
int open_port(void){
int fd;
fd = open("/dev/ttyUSB0", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("unable to open port /dev/ttyUSB0");
} else {
fcntl(fd, F_SETFL, 0);
}
return fd;
}
int main(void) {
int fd = open_port();
struct termios options;
tcgetattr(fd, &options);
cfsetispeed(&options, B9600);
cfsetospeed(&options, B9600);
options.c_cflag |= (CLOCAL | CREAD);
options.c_cflag &= ~PARENB;
options.c_cflag &= ~CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);
options.c_oflag &= ~OPOST;
tcsetattr(fd, TCSANOW, &options);
char buffer[1024];
int len;
int nbyte;
while (1) {
while((nbyte = read(fd, buffer, 1024)) > 0) {
buffer[nbyte+1] = '\0';
printf("\n%s", buffer);
}
}
close(fd);
return 0;
}
这两个ttyUSB是通过zigbee透传设备组网连接到一起的。
1.使用官网上的测试工具,两个串口之间可以正常通讯,所以是设备问题的几率应该不大。
2. 我用java rxtx写的代码收发也是不一样。
3. 在ubuntu中使用两个cutecom,相互发送,收发不一样。
4. 发送端使用我的代码,接收端使用cutecom,收发也不一样。
这个东西我看了一个多星期了,找不到解决办法或排错办法。跪求大神指点!!!