uartTool.c
#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 ;
default:
return -2 ;
}
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 ;
}
int serialSendString (const int fd, const char *s)
{
int nwrite;
nwrite = write (fd, s, strlen (s));
if (nwrite < 0)
printf("Serial Puts Error\n");
int nwrite;
}
int serialGetString (const int fd,char *buffer)
{
int nread;
nread=read(fd,buffer,32);
return nread;
}
uartTool.h
int serialOpen (const char *device, const int baud);
int serialSendString (const int fd, const char *s);
int serialGetString (const int fd,char *buffer);
uartTest.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <wiringPi.h>
#include <stdlib.h>
#include <unistd.h>
#include "uartTool.h"
int fd;
void *sendHandler()
{
char *sendBuf;
sendBuf = (char *)malloc(32*sizeof(char));
while(1){
memset(sendBuf,'\0',32);
scanf("%s",sendBuf);
serialSendString(fd,sendBuf);
}
}
void *revHandler()
{
char buffer[32];
while(1){
memset(buffer,'\0',sizeof(buffer));
serialGetString(fd,buffer);
printf("GET->%s\n",buffer);
}
}
int main()
{
pthread_t idSend;
pthread_t idRev;
fd = serialOpen("/dev/ttyS5",115200);
if(fd<0){
printf("open serail failed\n");
return 1;
}
pthread_create(&idSend,NULL,sendHandler,NULL);
pthread_create(&idRev,NULL,revHandler,NULL);
wiringPiSetup();
while(1){
sleep(10);
}
printf("\n");
return 0;
}
编译执行:
gcc serialTest.c uartTool.c -lpthread -lwiringPi
sudo ./a.out