编写一个含有main函数的c文件
uartTest.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <pthread.h>
#include <wiringPi.h>
#include <wiringSerial.h>
int fd;
void *whandler()
{
char buf[32];
while(1){
memset(buf,'\0',32);
scanf("%s",buf);
putString(fd,buf);
}
}
void *rhandler()
{
char buf[32];
while(1){
memset(buf,'\0',32);
printf ("%s", getString (fd ,buf)) ;
fflush (stdout) ;
}
}
int main ()
{
pthread_t wdata;
pthread_t rdata;
if ((fd = serialOpen ("/dev/ttyS5", 115200)) < 0)
{
fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno)) ;
return 1 ;
}
pthread_create(&wdata,NULL,whandler,NULL);
pthread_create(&rdata,NULL,rhandler,NULL);
while(1);
return 0 ;
}
再写一个用来封装函数的c文件
uartTool.c
#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"
/*
* serialOpen:
* Open and initialise the serial port, setting all the right
* port parameters - or as many as are required - hopefully!
*********************************************************************************
*/
int mySerialOpen (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 ;
}
/*
* putString :
* Send a string to the serial port
*********************************************************************************
*/
void putString (const int fd, const char *s)
{
int ret;
ret = write (fd, s, strlen (s));
if (ret < 0)
printf("Serial Puts Error\n");
}
/*
* getString :
* Get a string from the serial device.
*********************************************************************************
*/
int getString (const int fd ,char *buf)
{
int ret;
ret = read (fd, buf, 32);
if (ret < 0)
printf("Serial Read Error\n");
}
最后写一个uartTool.h文件
uartTool.h
编译:
两个文件要联合编译,如果代码中没有使用多线程,-pthread
可以去掉。