Linux系统的一切操作均是以文件的形式,同样地,ARM-Linux对外设的驱动、对串口的驱动也是以文件的形式存在。
输入 cd /dev/指令,就会显示所有外设对应的操作文件,如下图:
继续输入 ls ttyS*指令,就可以筛选显示出串口驱动对应的操作文件,如下图:
如上图,案例使用的开发板有3个串口可以使用,实例代码如下:
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <wiringPi.h>
#include <wiringSerial.h>
#include <stdlib.h>
int fd;
//发送指针函数
void* Sendhandler()
{
char *sendBuf;
sendBuf = (char *)malloc(32*sizeof(32));
while(1){
memset(sendBuf,'\0',32);
scanf("%s",sendBuf);
while(*sendBuf){
serialPutchar (fd, *sendBuf++) ;、
}
}
}
//接受指针函数
void* Revhandler()
{
while(1){
while (serialDataAvail(fd))
{
printf ("%c", serialGetchar(fd)) ;
fflush (stdout) ;
}
}
}
int main ()
{
//int count ;
unsigned int nextTime ;
pthread_t idSend; //发送线程
pthread_t idRev; //接收线程
if ((fd = serialOpen ("/dev/ttyS5", 115200)) < 0)
{
fprintf (stderr, "Unable to open serial device: %s\n", strerror (errno))
;
return 1 ;
}
pthread_create(&idSend, NULL,Sendhandler,NULL);
pthread_create(&idRev, NULL,Revhandler,NULL);
if (wiringPiSetup () == -1)
{
fprintf (stdout, "Unable to start wiringPi: %s\n", strerror (errno)) ;
return 1 ;
}
while(1){sleep(10);}
printf ("\n") ;
return 0 ;
}
运行结果如下: