三、linux下的UART试验
由于linux下所有的设备都可以看做一个文件,因此对串口的打开、读、写等操作,都可以对串口对应的设备文件进行操作.比如打开串口使用open()函数进行操作,读串口可以使用read()函数等.
试验原理:UART_LED.exe是PC端的串口工具,依据此工具发送命令后串口接收,并按每一位的状态控制8个LED.
#include <stdio.h>
#include <unistd.h>
#include <termios.h>
#include <fcntl.h>
#include "gpio.h"
#include <sys/ioctl.h>
int main(void)
{
int fd1,fd2;
int nread,nwrite;
int ret;
int value=0x01,led=0;
struct termios options;
fd1 = open("/dev/gpgdriver",O_RDWR); //打开GPIO设备文件
if(fd1<0)
perror("error");
ret = ioctl(fd1,GPIO_SET_MULTI_PIN_OUT,0x07); //设置3个引脚(GPG0、GPG1、GPG2)为输出状态
if(ret<0)
perror("error");
fd2 = open("/dev/s3c2410_serial0",O_RDWR); //打开串口设备文件
if(fd2<0)
perror("error");
tcgetattr(fd,&options); //获取串口设备的相关属性
cfsetispeed(&options,B115200); //设置串口的输入波特率为115200
cfsetospeed(&options,B115200); //设置串口的输出波特率为115200
options.c_cflag &= ~PARENB;
options.c_cflag |= CSTOPB;
options.c_cflag &= ~CSIZE;
options.c_cflag |= CS8;
options.c_lflag &= (~ICANON);
options.c_lflag &= (~ECHO);
tcsetattr(fd,TCSANOW,&options); //设置串口设备的相关属性
while(1)
{
led = value;
nread = read(fd2,&ret,1);
//从串口设备文件中读数据,并将该数据存入ret内
if(nread<0)
perror("read error");
nwrite = write(fd1,&ret,1); //向GPIO设备文件中写数据
if(nwrite<0)
printf("error");
return 0;
}
}
