串口接口在硬件上 直接上代码
#include <fcntl.h> #include <sys/stat.h> #include <unistd.h> #include <termios.h> #include <stdio.h> #include <stdlib.h> #include <string.h> //打开串口文件 static int open_uart(char *dev) {
long vdisable; int fd; fd = open(dev, O_RDWR|O_NOCTTY|O_NDELAY);//注意您的设备名称 if (-1 == fd) {
perror("Can't Open Serial Port"); return(-1); } return fd; } //配置串口参数 波特率 数据位 校验位 停止位 static int set_opt(int fd,int nSpeed, int nBits, char nEvent, int nStop) {
struct termios newtio, oldtio; if ( tcgetattr( fd,&oldtio) != 0) {
printf("SetupSerial 1"); return -1;
}
bzero( &newtio, sizeof( newtio ) );
newtio.c_cflag |= CLOCAL | CREAD;
newtio.c_cflag &= ~CSIZE;
switch( nBits )
{
case 7:
newtio.c_cflag |= CS7;
break;
case 8:
newtio.c_cflag |= CS8;
break;
}
switch( nEvent )
{
case 'O':
newtio.c_cflag |= PARENB;
newtio.c_cflag |= PARODD;
newtio.c_iflag |= (INPCK | ISTRIP);
break;
case 'E':
newtio.c_iflag |= (INPCK | ISTRIP);
newtio.c_cflag |= PARENB;
newtio.c_cflag &= ~PARODD;
break;
case 'N':
newtio.c_cflag &= ~PARENB;
break;
}
switch( nSpeed )
{
case 2400:
cfsetispeed(&newtio, B2400);
cfsetospeed(&newtio, B2400);
break;
case 4800:
cfsetispeed(&newtio, B4800);
cfsetospeed(&newtio, B4800);
break;
case 9600:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
case 115200:
cfsetispeed(&newtio, B115200);
cfsetospeed(&newtio, B115200);
break;
default:
cfsetispeed(&newtio, B9600);
cfsetospeed(&newtio, B9600);
break;
}
if ( nStop == 1 )
{
newtio.c_cflag &= ~CSTOPB;
}
else if ( nStop == 2 )
{
newtio.c_cflag |= CSTOPB;
}
newtio.c_cc[VTIME] = 0;
newtio.c_cc[VMIN] = 0;
tcflush(fd,TCIFLUSH);
if ((tcsetattr(fd,TCSANOW,&newtio))!=0)
{
printf("com set error");
return -1;
}
return 0;
}
static int fd;
int tf_luba_init()
{
fd = open_uart("/dev/ttyS1");//打开串口
set_opt(fd,115200,8,'N',1);//配置串口参数 波特率 数据位8 校验无 停止位1位
if(fd != 0)
printf("serial opened,wait rcv\n");//打印提示语
return 0;
}
int rf_lunua_read(unsigned int *l,unsigned int *strength,unsigned int *tempreture)
{
char buffer[256]={
0};
unsigned int tmp = 0;
memset(buffer,0,256);//接收数组清零
while (read(fd,buffer,sizeof(buffer)) == 0);//等待电脑串口调试助手发送数据
printf("%x %x %x %x %x %x %x %x %x\n",buffer[0],buffer[1],buffer[2],buffer[3],buffer[4],buffer[5],buffer[6],buffer[7],buffer[8]);
if(buffer[0] == 0x59 && buffer[1] == 0x59)
{
tmp = buffer[2] + buffer[3] * 256;
*l = tmp;
tmp = buffer[4] + buffer[5] * 256;
*strength = tmp;
tmp = buffer[6] + buffer[7] * 256;
*tempreture = tmp/8 - 256;
return 0;
}
return -1;
}
int tf_close(void)
{
close(fd);//关闭串口
return 0;
}