VM7.1 下Ubuntu10.10 与 51单片机的串口通信实验
linux端程序(接收):
本文引用地址://m.amcfsurvey.com/article/201611/318297.htm#include51端(使用keil2)发送:/*标准输入输出定义*/#include /*标准函数库定义*/#include /*Unix 标准函数定义*/#include #include #include /*文件控制定义*/#include /*PPSIX 终端控制定义*/#include /*错误号定义*/#define BAUDRATE B9600 #define MODEMDEVICE "/dev/ttyS1"int main(){int fd,c=0,res;struct termios oldtio,newtio;int ch;static char s1[20],buf[19];printf("start ...n");/*打开PC的COM1口*/fd = open(MODEMDEVICE,O_RDWR|O_NOCTTY);if (fd == -1 ){perror(MODEMDEVICE);exit(1);}printf("open...n");/*将旧的通讯参数存入oldtio结构*/tcgetattr(fd,&oldtio);/*初始化新的newtio */bzero((char*)&newtio,sizeof(newtio));/*8N1*/newtio.c_cflag = BAUDRATE|CS8|CLOCAL|CREAD;newtio.c_iflag = IGNPAR;newtio.c_oflag = 0;/*正常模式*//*newtio.c_lflag = ICANON;*//*非正常模式*/newtio.c_lflag = 0;newtio.c_cc[VTIME] = 0;newtio.c_cc[VMIN] = 10;tcflush(fd,TCIFLUSH);/*新的temios作为通讯端口参数*/tcsetattr(fd,TCSANOW,&newtio);printf("writing...n");res = read(fd,buf,10);printf("%sn",buf);printf("close...n");/*还原旧参数*/tcsetattr(fd,TCSANOW,&oldtio);close(fd);return 0;}
#include#define uchar unsigned char#define uint unsigned intuchar code trdata[]={R,I,C,H,M,C,U,R,Z,-,5,1,V,2,.,0,0x0d,0x0a,0x00};sbit K1=P3^2; //对应开发板K1按键/*-------------------------------------------------------------*///串口初始化void UART_Init(void){SCON = 0x40; //串口工作方式为1TMOD = 0x20; //定时器1 工作在方式2//PCON = 0x80; //SMOD = 1; 波特率加倍TH1 = 0xfd; //波特率 9600bps fosc="11".0592MHzTL1 = 0xfd;TR1 = 1; //允许定时器1工作EA = 1; //开总中断}void delay1ms(uint i){uchar j;while(i--){for(j=0;j<115;j++) //1ms基准延时程序;}}/*-------------------------------------------------------------*///串口发送一个字符串void Uart_SendString(){ uchar i=0;while(trdata!=0x00){ SBUF=trdata;while(!TI);TI=0;i++;}}/*-------------------------------------------------------------*///主函数void main(void){UART_Init(); //初始化串口while(1){if(K1==0){delay1ms(20);if(K1==0){Uart_SendString(); //发送数据while(!K1); //等待按键释放}}}}
linux发 51接收的差不多,只是51端要多出一个中断处理程序。
评论