这下面是完整的linux 标准串口通信程序
在这里插入代码片
int g_fpUart = 0;
static unsigned char gau8CmdBufRev[UART_BUFFER_SIZE] = {0};
static int _UartGetChar(void)
{
unsigned char buf;
if (g_fpUart == 0)
{
g_fpUart = open("/dev/ttyS1", O_RDWR | O_NOCTTY );
if (g_fpUart != 0)
{
struct termios tty;
tcgetattr(g_fpUart, &tty);
// In/Out no flow ctrl
tty.c_iflag = 0;
tty.c_oflag = 0;
tty.c_lflag = 0;
tty.c_line = 0;
// config: 115200,8,N,1
cfsetispeed(&tty, B115200);
cfsetospeed(&tty, B115200);
tty.c_cflag &= ~(PARENB); // Clear parity bit, disabling parity (most common)
tty.c_cflag &= ~(CSTOPB); // Clear stop field, only one stop bit used in communication (most common)
tty.c_cflag &= ~(CSIZE); // Clear all bits that set the data size
tty.c_cflag |= (CS8); // 8 bits per byte (most common)
tty.c_cflag &= ~(CRTSCTS); // Disable RTS/CTS hardware flow control (most common)
tty.c_cflag |= (CREAD | CLOCAL); // Turn on READ & ignore ctrl lines (CLOCAL = 1)
tty.c_cflag &= ~(HUPCL); // disable 'hang up on last close'
tty.c_cc[VMIN] = 1;
tty.c_cc[VTIME] = 0;
if (tcsetattr(g_fpUart, TCSANOW, &tty) != 0)
{
printf("Error from tcsetattr\n");
}
}
}
if (g_fpUart)
{
if (read(g_fpUart, &buf, 1) > 0)
return buf;
}
return EOF;
}
int main(int argc, char * argv[])
{
int idx;
int count=0;
static int datalen=UART_BUFFER_SIZE;
bool sucess=0;
int cmd=0;
while (1)
{
int ch = EOF;
while ((ch = _UartGetChar()) == EOF);
gau8CmdBufRev[count] = ch;
datalen=gau8CmdBufRev[UART_DATA_4]+9;
cmd =gau8CmdBufRev[UART_DATA_2]*256+gau8CmdBufRev[UART_DATA_3];
printf("BufRev[%d]=%x,len=%d,cmd=%x\n",count,ch,datalen,cmd);
count++;
if(ch==0xFB)
{
if(count==datalen)
{
count=0;
sucess=1;
}
else if(count>datalen)
{
count=0;
}
}
if(count>UART_BUFFER_SIZE)
{
count=0;
}
if(sucess==true)
{
printf("get xor recv=%x\n",gau8CmdBufRev[datalen-2]);
DEBUG_PRINTF("get xor recv=%x\n",gau8CmdBufRev[datalen-2]);
if(xorOperation(gau8CmdBufRev[UART_DATA_4]+6,&gau8CmdBufRev[1])!=gau8CmdBufRev[datalen-2])
{
printf("check xor sum diff return\n");
DEBUG_PRINTF("check xor sum diff return\n");
sucess=false;
RecvCmdDataRest();
datalen=0;
continue;
}
ProssesCmd(cmd);
sucess=false;
RecvCmdDataRest();
datalen=0;
}
}
return 0;
}
[学习linux链接](https://edu.csdn.net/learn/29105/640331?spm=3001.4143)
[模块购买链接](https://h5.m.taobao.com/awp/core/detail.htm?directUrl=https://h5.m.taobao.com/awp/core/detail.htm?ft=t&id=789989529796&from=qianniuAndroid&id=789989529796&version=9.8.250&ttid=700145@tbsellerworkbench_android_9.8.250&ft=t)