23,217
社区成员




#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#define BAUDRATE B115200
open_port(void)
{
int fd,speed;
struct termios newtio;
fd = open("/dev/ttyS0",O_RDWR|O_NOCTTY|O_NDELAY);
if(fd==-1)
{
perror("open_port:Unable to open /dev/ttyS0");
}
tcgetattr(fd,&newtio);
bzero(&newtio,sizeof(newtio));
//setting c_cflag
newtio.c_cflag |= (CLOCAL|CREAD);
newtio.c_cflag &=~PARENB;
newtio.c_cflag &=~PARODD;
newtio.c_cflag &=~CSTOPB;
newtio.c_cflag &=~CSIZE;
newtio.c_cflag |=CS8;
newtio.c_oflag|=OPOST;
//setting c_iflag
newtio.c_iflag &=~(IXON|IXOFF|IXANY);
cfsetispeed(&newtio,BAUDRATE);
cfsetospeed(&newtio,BAUDRATE);
printf("speed=%d\n",BAUDRATE);
tcflush(fd, TCIFLUSH);
tcsetattr(fd,TCSANOW,&newtio);
return(fd);
}
main()
{
int fd,n,i;
unsigned char buff[256];
fd = open_port();
while(1){
n = read(fd,buff,256);
if(n>0){
printf("n=%d\n",n);
for(i=0;i<n;i++)
printf("%02X:",buff[i]);
//printf("%c",buff[i]);
printf("\n");
}
}
close(fd);
}