Linux下串口编程(一)
相关内容:
1、设置串口波特率
stty -F /dev/ttyPS1 speed 115200
dmesg | grep ttyS* //查串口设备
echo 232 >> /dev/ttyPS1 //查看串口是否可用
2、测试代码
//可串口调试助手进行测试,可通过stty设置串口波特率
#include <stdio.h> /*标准输入输出定义*/ #include <stdlib.h> /*标准函数库定义*/ #include <unistd.h> /*Unix 标准函数定义*/ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> /*文件控制定义*/ #include <termios.h> /*PPSIX 终端控制定义*/ #include <errno.h> /*错误号定义*/
#include <string.h>
int main(void)
{
int fd;
char buf[50]={0};
char buf111[12]={0x01,0x09,0x30,0x34,0x35,0x44,0x42,0x35,0x33,0x41,0x46,0x0D};
char buf123[200]={0};
int len = 0;
int len1 = 0;
int i = 0;
int count =0;
struct termios termios_p;
fd = open("/dev/ttyPS1", O_RDWR | O_NOCTTY);
tcgetattr(fd, &termios_p);
termios_p.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
termios_p.c_oflag &= ~OPOST;
termios_p.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
termios_p.c_cflag &= ~(CSIZE | PARENB);
termios_p.c_cflag |= CS8;
tcsetattr(fd, TCSANOW, &termios_p);
printf("Line %d\n", __LINE__);
while(1)
{
sleep(2);
write(fd, buf111, 12);
// goto out;
memset(buf, 0, sizeof(buf));
len =0;
len1 = 0;
while(len1 < 20)
{
len = read(fd, buf, 10);
if (len <= 0)
{
printf("read failed %d 0x%02x\n", len, buf[0]);
//exit(-1);
continue;
}
memcpy(buf123+len1, buf, len);
len1 += len;
for(i =0; i< len; i++)
printf("%02x ", buf[i]);
}
printf("count %d \n", count++);
out:
usleep(1000000);
}
}