a20 uart0 test demo

来源:互联网 发布:2016年双十一销售数据 编辑:程序博客网 时间:2024/06/01 09:00
#include <stdio.h>#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <stdlib.h>#include <unistd.h>#include <termios.h>#include <errno.h>#include <pthread.h>//char *dev_path = "/dev/ttyS0";int uart0_fd;  //串口配置://端口(ttyS0)+ 波特率(115200)+ 数据位(8)//+ 停止位(1)+效验位(none) + 流控制(none)int set_opt(int fd){struct termios old_cfg, new_cfg;printf("uart0: set_opt fn.\n");//stage#1//保存原先串口配置//tcgetattr(fd, &old_cfg);tcgetattr(fd, &new_cfg);//stage#2//激活选项有CLOCAL和CREAD,用于本地连接和接收使用new_cfg.c_cflag |= (CLOCAL | CREAD);//设置波特率:115200cfsetispeed(&new_cfg, B115200);//输入波特率cfsetospeed(&new_cfg, B115200);//输出波特率//设置数据位,需使用掩码设置//设置数据位数:8位new_cfg.c_cflag &= ~CSIZE;new_cfg.c_cflag |= CS8;//设置奇偶校验:无校验(none)new_cfg.c_cflag &= ~PARENB;//设置停止位:1位new_cfg.c_cflag &= ~CSTOPB;//设置最少字符和等待时间new_cfg.c_cc[VTIME] = 0;new_cfg.c_cc[VMIN] = 0;//处理要写入的引用对象tcflush(fd,TCIFLUSH);//stage#3//激活配置tcsetattr(fd, TCSANOW, &new_cfg);return 0;}/*thread*/char write_buf;void *thread_uart0_write(void *arg){printf("write thread.\n");write_buf = 'a';while (1) {printf("write loop: ");printf("fd = %d; write_buf = %c.\n", uart0_fd, write_buf);write(uart0_fd, &write_buf, 1);}return NULL;}#if 1char read_buf;void *thread_uart0_read(void *arg){printf("read thread.\n");while (1) {printf("read loop: ");read(uart0_fd, &read_buf, 1);printf("fd = %d; read_buf = %c.\n", uart0_fd, read_buf);}return NULL;}#endif/*main*/void main(int argc, char **argv){int ret;pthread_t write_pthread;pthread_t read_pthread;    /*open*/    uart0_fd = open(dev_path, (O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK));    printf("uart0 open; fd = %d.\n", uart0_fd);#if 0ret = fcntl(uart0_fd, F_SETFL, 0);if (ret < 0) {printf("uart0: fcntl fail.\n");}#endif    /*setting*///ttyS0: 115200+8+1+none+none;set_opt(uart0_fd);#if 1    printf("posix thread write.\n");pthread_create(&read_pthread, NULL, thread_uart0_read, NULL);pthread_create(&write_pthread, NULL, thread_uart0_write, NULL);/*pthread_join*/pthread_join(read_pthread, NULL);pthread_join(write_pthread, NULL);#elsechar buf;int i;printf("read.\n");for (i = 0; i <1000; i++) {printf("i = %d.\n", i);//ret = read(uart0_fd, &buf, 1);write(uart0_fd, 'a', 1);//printf("read: ret = %d; buf = %c.\n", ret, buf);}#endif    /*close*/    close(uart0_fd);    printf("uart0 close.\n");    return;}/*EOF*/


LOCAL_PATH:= $(call my-dir)include $(CLEAR_VARS)LOCAL_C_INCLUDES:= external/uart0-test/LOCAL_SRC_FILES:= uart0-test.cLOCAL_MODULE := uart0-testLOCAL_SHARED_LIBRARIES:= libcutils libutils LOCAL_MODULE_TAGS := optionalinclude $(BUILD_EXECUTABLE)











0 0
原创粉丝点击