嵌入式Linux操作UART实例
1
引言
1
引言
2
环境介绍
2
环境介绍
3
Busybox生成microcom命令
3
Busybox生成microcom命令
4
内核配置
4
内核配置
5
UART操作
5
UART操作
int main (int argc, char *argv[])
{
int fd;
int len, i,ret;
char buf[] = "Hello TopSemic! \n";
fd = open(DEV_NAME, O_RDWR | O_NOCTTY);
if(fd < 0)
{
perror(DEV_NAME);
return -1;
}
len = write(fd, buf, sizeof(buf));
if (len < 0)
{
printf("write data error \n");
}
memset(buf,0x00,sizeof(buf));
len = read(fd, buf, sizeof(buf));
if (len < 0)
{
printf("read error \n");
return -1;
}
printf("%s", buf);
return(0);
}
int main (int argc, char *argv[])
{
int fd;
int len, i,ret;
char buf[] = "Hello TopSemic! \n";
fd = open(DEV_NAME, O_RDWR | O_NOCTTY|O_NDELAY);
if(fd < 0)
{
perror(DEV_NAME);
return -1;
}
len = write(fd, buf, sizeof(buf));
if (len < 0)
{
printf("write data error \n");
}
while(1)
{
memset(buf,0x00,sizeof(buf));
len = read(fd, buf, sizeof(buf));
printf("len:%d \n",len);
if(len>0)
printf("%s", buf);
usleep(100000);
}
}
static struct termios newtios,oldtios; /*termianal settings */
static int saved_portfd=-1; /*serial port fd */
static void reset_tty_atexit(void)
{
if(saved_portfd != -1)
{
tcsetattr(saved_portfd,TCSANOW,&oldtios);
}
}
/*cheanup signal handler */
static void reset_tty_handler(int signal)
{
if(saved_portfd != -1)
{
tcsetattr(saved_portfd,TCSANOW,&oldtios);
}
_exit(EXIT_FAILURE);
}
static set_port_attr (int portfd,int baudrate)
{
struct sigaction sa;
/*get serial port parnms,save away */
tcgetattr(portfd,&newtios);
memcpy(&oldtios,&newtios,sizeof newtios);
/* configure new values */
cfmakeraw(&newtios); /*see man page */
newtios.c_iflag |=IGNPAR; /*ignore parity on input */
newtios.c_oflag &= ~(OPOST | ONLCR | OLCUC | OCRNL | ONOCR | ONLRET | OFILL);
newtios.c_cc[VMIN]=1; /* block until 1 char received */
newtios.c_cc[VTIME]=0; /*no inter-character timer */
switch(baudrate) {
case 9600:
cfsetispeed(&newtios,B9600);
cfsetospeed(&newtios,B9600);
break;
case 19200:
cfsetispeed(&newtios,B19200);
cfsetospeed(&newtios,B19200);
break;
case 38400:
cfsetispeed(&newtios,B38400);
cfsetospeed(&newtios,B38400);
break;
case 115200:
cfsetispeed(&newtios,B115200);
cfsetospeed(&newtios,B115200);
break;
}
/* register cleanup stuff */
atexit(reset_tty_atexit);
memset(&sa,0,sizeof sa);
sa.sa_handler = reset_tty_handler;
sigaction(SIGHUP,&sa,NULL);
sigaction(SIGINT,&sa,NULL);
sigaction(SIGPIPE,&sa,NULL);
sigaction(SIGTERM,&sa,NULL);
/*apply modified termios */
saved_portfd=portfd;
tcflush(portfd,TCIFLUSH);
tcsetattr(portfd,TCSADRAIN,&newtios);
return portfd;
}
int main (int argc, char *argv[])
{
int fd;
int len, i,ret;
char buf[] = "Hello TopSemic! \n";
fd = open(DEV_NAME, O_RDWR | O_NOCTTY|O_NDELAY);
if(fd < 0)
{
perror(DEV_NAME);
return -1;
}
set_port_attr (fd,115200);
len = write(fd, buf, sizeof(buf));
if (len < 0)
{
printf("write data error \n");
}
while(1)
{
memset(buf,0x00,sizeof(buf));
len = read(fd, buf, sizeof(buf));
printf("len:%d \n",len);
if(len>0)
printf("%s", buf);
usleep(100000);
}
return 0;
}
6
结束语
6
结束语
评论