关于上位机以及arm的串口编程,网上的资料很多,不过两者代码同时给出的资料却很少,本菜鸟经过几天时间的煎熬,终于实现了用自己编写的上位机软件传输文件到arm板上。上位机使用的是C#,arm上使用的是Linux C,使用的文件传输协议为XModem。关于XModem协议的格式可以参考我前面转的一篇博客,这里就不细说了。
下面首先贴出代码:
/******ARM上的应用程序******/
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <termios.h>
#include <signal.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
unsigned char buf[132];
int debug_buf[132];
int i;
//打印出接收到的数据(调试时用)
void print_data_package()
{
printf("received package:\n");
for(i=0;i<132;i++)
{
debug_buf[i]=buf[i];
printf("%d ",buf[i]);
}
printf("\n");
printf("\n");
}
//初始化串口
void uart_init()
{
struct termios tmp_term;
int fd;
if( (fd = open("/dev/ttyS1", O_RDWR)) < 0 ) {
printf("Error: cannot open file /dev/ttyS1");
exit(1);
}
if(isatty(fd) == 0) {
printf("Error: /dev/ttyS1 is not a tty\n");
close(fd);
exit(1);
}
if(tcgetattr(fd, &tmp_term) < 0) {
printf("Error: get termios failed\n");
close(fd);
exit(1);
}
tmp_term.c_cflag = CS8|CREAD|HUPCL|CLOCAL;
tmp_term.c_oflag = 0;
tmp_term.c_iflag = IXANY|IGNBRK|IGNPAR;
tmp_term.c_lflag = 0;
tmp_term.c_cc[VMIN]=132; //read函数最少读到132字节数据才返回,否则保持阻塞,以此保证数据包的完整性
tmp_term.c_cc[VTIME]=0;
cfsetispeed(&tmp_term,B115200);