打开设备
TTL下载器插在USB接口上,在终端输入“ls/dev/tty”
代码如下:
1 # include <stdio.h>
2 # include <assert.h> //测试函数
3 # include <string.h>
4 # include "Picustom.h" //自定义头文件
5 # define uint8 unsigned char //宏定义
6 # define N 124
7
8 struct serial_port{
9 char device[32]; //设备路径
10 unsigned long baud; //波特率
11 int fd; //设备描述符
12 unsigned char dates[1024]; //文件转存
13 unsigned char temp; //字符缓存
14 int len; //长度
15 };
16
17 //字符串cp函数
18 char * my_strcpy(char *dest, const char *src){ //将源字符串加const,表明其为输入参数,起到相应的保护作用
19 assert(src != NULL&&dest != NULL); //对源地址和目的地址加非0断言
20 char *ret = dest;
21 while ((*dest++ = *src++));
22 return ret; //引用返回地址,方便链式操作!!
23 }
24 //清空serial
25 int clean_serial_port(struct serial_port *serial){
26 memset(serial->dates,0,1024);
27 serial->len = 0;
28 printf("\n");
29 return 0;
30 }
31 //字段尾部加0
32 int set_serial_dates_end(struct serial_port *serial){
33 if('\n' == serial->temp){
34 printf("\n");
35 serial->dates[serial->len--]='\0';
36 }
37 return 0;
38 }
39
40 //打印调试
41 int printf_serial_dates(struct serial_port *serial){
42 int i = 0;
43 if('\n' == serial->temp){
44 for(i = 0;i<=serial->len;i++){
45 printf(" %d---%x",i,serial->dates[i]);
46 }
47 }
48 return 0;
49 }
50
51 //读取完成清空缓存0
52 int clean_serial(struct serial_port *serial){
53 if('\n' == serial->temp){
54 clean_serial_port(serial);
55 }
56 return 0;
57 }
58
59
60 int main(void){
61 struct serial_port serial;
62 wiringPi(0,0); //wiringPi初始化
63 serial.fd = init_serial_port("/dev/ttyUSB0",9600); //通过树莓派函数打开
64 while(1){
65 serial.temp = Serial_data_read_char_10(serial.fd);
66 printf("%x\t",serial.temp);
67 if(((0xff > serial.temp)&&(0x80 < serial.temp))||(serial.temp == '\r')||(serial.temp == '\n')){
68 serial.dates[serial.len++] = serial.temp;
69 set_serial_dates_end(&serial); //尾部加0
70 //printf_serial_dates(&serial); //打印
71
72 clean_serial(&serial); //读取完成清空缓存0
73 }
74 else{ //出错清空缓存
75 clean_serial_port(&serial);
76 }
77 }
78 return 0;
79 }