23,125
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <error.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdlib.h>
int fd;
/*
* 打开串口1
*/
int open_ttyS0()
{
//O_RDWR:以读写的方式打开设备
//O_NOCTTY:如果欲打开的文件为终端设备时,则不会将该终端当成当前进程控制终端
//O_NDELAY:以不可阻断的方式打开文件,即无论有无数据读取或等待,都会立即返回进程之中
//fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY); //虚拟机Linux测试
fd = open("/dev/tq2440_serial0", O_RDWR | O_NOCTTY | O_NDELAY); //tq2440 Linux测试
printf("\nfd = %d\n\n", fd);
if(fd < 0) //打开失败
{
return -1;
}
//恢复串口为阻塞状态
if(fcntl(fd, F_SETFL, 0) < 0) //F_SETFL:改变open设置的标志
{
close(fd);
return -2;
}
//测试是否为终端设备
if(0 == isatty(fd)) //isatty:检查设备类型
{
close(fd);
return -3;
}
return fd;
}
/*
* 设置串口1,共9步
* 数据位:8
* 校验位:无
* 波特率:115200
* 停止位:1
*/
int set_ttyS0()
{
struct termios newtio, oldtio;
//1、保存原有串口配置
if(tcgetattr(fd, &oldtio) != 0)
{
return -1;
}
//2、激活本地连接和接受使能
bzero(&newtio, sizeof(newtio)); //使用之前先清空
newtio.c_cflag |= CLOCAL | CREAD;
//3、设置字符大小
newtio.c_cflag &= ~CSIZE; //除去数据位中的位掩码
newtio.c_cflag |= CS8; //设置数据位
//4、设置奇偶校验位:无奇偶校验位
newtio.c_cflag &= ~PARENB; //激活校验位使能标志
//5、设置波特率
cfsetispeed(&newtio, B115200);
cfsetospeed(&newtio, B115200);
//6、设置停止位:1
newtio.c_cflag &= ~CSTOPB;
//7、设置等待时间和最小接收字符
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
//8、处理要写入的引用对象
tcflush(fd, TCIFLUSH); //处理未接收字符串,TCIFLUSH:刷新收到的数据但不读
//9、激活新配置
if(tcsetattr(fd, TCSANOW, &newtio) != 0) //TCSANOW:改变的配置立即生效
{
return -2;
}
return 0;
}
int main()
{
char cmd[] = "ATD 15954179972;\r";
open_ttyS0();
set_ttyS0();
printf("write: %d\n", write(fd, cmd, sizeof(cmd)));
sleep(2);
printf("read: %d\n", read(fd, cmd, sizeof(cmd)));
return 0;
}