串口通信
串口通信的原理,在这里我不进行多的赘述,想了解的自行百度。
串口通信三步骤
串口通信总结下来就三个步骤,打开串口,往串口写数据,串口读数据。(实际操作其实也是这三步)直接上代码验证!
二、示例代码
main.c
int fd;
void* read_handler()
{
char buffer[32];
while(1){
memset(buffer,'\0',sizeof(buffer));
serial_read(fd,buffer);
printf("Get->%s\n",buffer);
}
}
void* write_handler()
{
char buffer[32];
while(1){
memset(buffer,'\0',sizeof(buffer));
scanf("%s",buffer);
serial_write(fd,buffer);
}
}
int main(int argc,char* argv[])
{
pthread_t readthread;
pthread_t writethread;
char deviceName[32];
int S_ret;
int pth_ret;
if(argc<2){
printf("Do you want to open /dev/ttyS?\n");
return -1;
}
strcpy(deviceName,argv[1]);
fd=serialOpen(deviceName,115200);
if(fd==-1){
printf("open failed锛乗n");
return -1;
}
pthread_create(&readthread,NULL,read_handler,NULL);
pthread_create(&writethread,NULL,write_handler,NULL);
while(1){
sleep(10);
}
return 0;
}
自定义头文件
int serialOpen (const char *device, const int baud);
void serial_write (const int fd, const char *s);
int serial_read (const int fd,char* buffer);
函数的实现
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "wiringSerial.h"
int serialOpen (const char *device, const int baud)
{
struct termios options ;
speed_t myBaud ;
int status, fd ;
switch (baud){
case 9600: myBaud = B9600 ; break ;
case 115200: myBaud = B115200 ; break ;
}
if ((fd = open (device, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK)) == -1)
return -1 ;
fcntl (fd, F_SETFL, O_RDWR) ;
// Get and modify current options:
tcgetattr (fd, &options) ;
cfmakeraw (&options) ;
cfsetispeed (&options, myBaud) ;
cfsetospeed (&options, myBaud) ;
options.c_cflag |= (CLOCAL | CREAD) ;
options.c_cflag &= ~PARENB ;
options.c_cflag &= ~CSTOPB ;
options.c_cflag &= ~CSIZE ;
options.c_cflag |= CS8 ;
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG) ;
options.c_oflag &= ~OPOST ;
options.c_cc [VMIN] = 0 ;
options.c_cc [VTIME] = 100 ; // Ten seconds (100 deciseconds)
tcsetattr (fd, TCSANOW, &options) ;
ioctl (fd, TIOCMGET, &status);
status |= TIOCM_DTR ;
status |= TIOCM_RTS ;
ioctl (fd, TIOCMSET, &status);
usleep (10000) ; // 10mS
return fd ;
}
void serial_write (const int fd, const char *s){
int ret;
ret = write (fd, s, strlen (s));
if (ret < 0)
printf("Serial Puts Error\n");
}
int serial_read (const int fd,char* buffer){
int n_read;
n_read=read(fd,buffer,32);
return n_read;
}
二、文件的执行
二、说明
要完整执行,还需在windows环境下,下载一个串口调试助手,才可以实时的看到串口数据的收发!