23,131
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
using namespace std;
int m_handle = 0;
unsigned char startcmd01[4] = { 0x01, 0x80, 0x33, 0xfe };
void set_com(int fd) {
struct termios tm;
tcgetattr(fd, &tm);
cfmakeraw(&tm);
tcflush(fd, TCIOFLUSH);
tcsetattr(fd, TCSANOW, &tm);
tcflush(fd, TCIOFLUSH);
if (tcgetattr(fd, &tm) != 0) {
cout << "获取tm2失败" << endl;
return;
}
tm.c_cflag = B4800 | CRTSCTS | CS8 | CLOCAL | CREAD;
tm.c_iflag &= ~IGNPAR;
tm.c_cc[VTIME] = 150;
tm.c_cc[VMIN] = 6;
if (tcsetattr(fd, TCSANOW, &tm) != 0) {
cout << "设置tm2失败" << endl;
return;
}
tcflush(fd, TCIFLUSH);
}
int main() {
printf("---\n");
m_handle = open("/dev/ttyUSB0", O_RDWR);
if (m_handle == -1) {
return -1;
}
//printf("---\n");
//set_com(m_handle);
int count = write(m_handle, startcmd01, 4);
if (!count) {
cout << "write failed!" << endl;
return 0;
}
cout << "count:" << count << endl;
unsigned char readbuf[6] = { 0 };
printf("---\n");
read(m_handle, readbuf, 6);
printf("%d\n", readbuf[0]);
close(m_handle);
return 0;
}
tm.c_cflag &= ~HUPCL;
tm.c_iflag &= ~INPCK;
tm.c_iflag |= IGNBRK;
tm.c_iflag &= ~ICRNL;
tm.c_iflag &= ~IXON;
tm.c_lflag &= ~IEXTEN;
tm.c_lflag &= ~ECHOK;
tm.c_lflag &= ~ECHOCTL;
tm.c_lflag &= ~ECHOKE;
tm.c_oflag &= ~ONLCR;
就正确了 应该是串口设置不正确导致的。。。 但是还是不明白为什么会出现拔了硬件再插上就正确了。。。