uart使用Sample Code
-
可以复用做uart的GPIO,请参考:drivers/sstar/serial/infinity6b0/uart_pads.c的ms_uart_get_padmux函数。
-
修改dtsi里的uart1(对应ttyS1)和fuart(对应ttyS2)节点选择复用的GPIO。
-
编译以下sample code即可操作。
sample code:
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <errno.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <termios.h> #include <stdlib.h> #include <pthread.h> int fd=-1; pthread_t RX_pthread=NULL; pthread_t TX_pthread=NULL; char exit_flag=0; void display_help() { printf("Usage: ./test_ttyS0 [-n number] [-b baudrate] [-h]\n\n"); printf("\t-h: Display help info\n"); printf("\t-b: select baudrate\n"); printf("\t\t0:4800, 1:9600, 2:115200\n"); printf("\t-n: select tty port\n"); printf("\t\t0:ttyS0, 1:ttyS1, 2:ttyS2\n"); } void open_uart(char *file) { fd =open(file,O_RDWR|O_NOCTTY|O_NDELAY); if(fd==-1){ printf("Benis:open %s fail\n",file); return; } if(fcntl(fd,F_SETFL,0)<0){ printf("Benis:fcntl faild!\n"); } isatty(STDIN_FILENO); } void init_uart(int baudrate_cmd) { struct termios opt; tcgetattr(fd,&opt); switch(baudrate_cmd) { case 0: cfsetispeed(&opt,B4800); cfsetospeed(&opt,B4800); printf("Benis:baudrate = 4800 \n"); break; case 1: cfsetispeed(&opt,B9600); cfsetospeed(&opt,B9600); printf("Benis:baudrate = 9600 \n"); break; case 2: cfsetispeed(&opt,B115200); cfsetospeed(&opt,B115200); printf("Benis:baudrate = 115200 \n"); break; } opt.c_cflag &= ~CSIZE; opt.c_cflag |= CS8; opt.c_cflag |= CLOCAL|CREAD; opt.c_cflag &= ~PARENB; opt.c_iflag &= ~INPCK; opt.c_cflag &= ~CSTOPB; opt.c_cc[VTIME]=0; opt.c_cc[VMIN]=0; tcflush(fd,TCIOFLUSH); tcsetattr(fd,TCSANOW,&opt); } void close_uart(){ if(fd!=-1) close(fd); } void * rx_func(void * argv) { char rec_buf[64]; while(exit_flag!=1) { memset(rec_buf,0,sizeof(rec_buf)); if(read(fd,rec_buf,sizeof(rec_buf))>0) printf("Benis rec:%s",rec_buf); } return; } void * tx_func(void * argv) { char ch; char tx_buf[2]; while((ch = getchar()) != 'Q') { sprintf(tx_buf,"%c",ch); write(fd,tx_buf,1); } exit_flag=1; return; } int main(int argc , char *argv[]) { int result; int baudrate_opt=-1,tty_port=-1; char file_name[20]; while((result=getopt(argc,argv,"hn:b:"))!=-1) { switch(result) { case 'n': tty_port=atoi(optarg); if(tty_port>2) { printf("tty port argument error!\n"); return -1 ; } break; case 'b': baudrate_opt=atoi(optarg); if(baudrate_opt>2) { printf("baudrate argument error!\n"); return -1 ; } break; case 'h': display_help(); return 0; break; default: display_help(); return 0; break; } } memset(file_name,0,sizeof(file_name)); sprintf(file_name,"%s%d","/dev/ttyS",tty_port); printf("Benis:file name is %s\n",file_name); open_uart(file_name); init_uart(baudrate_opt); write(fd,"Benis:uart0 send ......\n",25); pthread_create(&RX_pthread,NULL,rx_func,NULL); pthread_create(&TX_pthread,NULL,tx_func,NULL); pthread_join(RX_pthread,NULL); pthread_join(TX_pthread,NULL); close_uart(); return 0; }