VM7.1 下Ubuntu10.10 與 51單片機的串口通信實驗
linux端程序(接收):
本文引用地址:http://butianyuan.cn/article/201611/318297.htm#include51端(使用keil2)發(fā)送:/*標準輸入輸出定義*/#include /*標準函數(shù)庫定義*/#include /*Unix 標準函數(shù)定義*/#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");/*將舊的通訊參數(shù)存入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作為通訊端口參數(shù)*/tcsetattr(fd,TCSANOW,&newtio);printf("writing...n");res = read(fd,buf,10);printf("%sn",buf);printf("close...n");/*還原舊參數(shù)*/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; //對應開發(fā)板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基準延時程序;}}/*-------------------------------------------------------------*///串口發(fā)送一個字符串void Uart_SendString(){ uchar i=0;while(trdata!=0x00){ SBUF=trdata;while(!TI);TI=0;i++;}}/*-------------------------------------------------------------*///主函數(shù)void main(void){UART_Init(); //初始化串口while(1){if(K1==0){delay1ms(20);if(K1==0){Uart_SendString(); //發(fā)送數(shù)據(jù)while(!K1); //等待按鍵釋放}}}}
linux發(fā) 51接收的差不多,只是51端要多出一個中斷處理程序。
評論