51單片機的串口通訊執行個體

來源:互聯網
上載者:User

Question:以16進位發送一個0-255之間的任一數,當單片機收到後在數位管上動態顯示出來,傳輸速率自定。

#include <reg52.h>#define uchar unsigned char#define uint unsigned intsbit duan =P2^6;sbit wei =P2^7;uchar code table[]={0x3f,0x06,0x5b,0x4f,0x66,0x6d,0x7d,0x07,0x7f,0x6f,0x77,0x7c,0x39,0x5e,0x79,0x71};uchar flag;uchar bai,shi,ge;uint num;void init();void display(uchar bai,char shi,uchar ge);void delay(uint xms){ uint i,j; for(i=0;i<xms;i++)  for(j=0;j<10;j++);}void main(){ init(); while(1) {   if(flag==1)   {    ES=0;    flag=0;    bai=num/100;    shi=num%100/10;    ge=num%10;    /*SBUF=bai;    while(!TI);    TI=0;    SBUF=shi;    while(!TI);    TI=0;    SBUF=ge;    while(!TI);    TI=0;*/    ES=1;       }      display(bai,shi,ge);//如果這個函數寫在了上一個迴圈裡面顯示會出錯,只會顯示個位元字。。。。    }  }void display(uchar bai,uchar shi,uchar ge){    wei=1;    P0=0xfe;    wei=0;    P0=0xff;    duan=1;    P0=table[bai];    duan=0;    P0=0xff;    delay(2);    wei=1;    P0=0xfd;    wei=0;    P0=0xff;    duan=1;    P0=table[shi];    duan=0;    P0=0xff;    delay(2);    wei=1;    P0=0xfb;    wei=0;    P0=0xff;    duan=1;    P0=table[ge];    duan=0;    P0=0xff;    delay(2);}void init(){  TMOD=0x20;  TH1=0xfd;  TL1=0xfd;  SM0=0;  SM1=1;  TR1=1;  REN=1;  EA=1;  ES=1;}void ser() interrupt 4{ num=SBUF; flag=1; RI=0;}

Question:以9600bps從電腦發送任一位元組資料,當單片機收到該資料後,在此資料前加上一序號然後連同此資料一起發送至電腦,當序號超過255時歸零。

#include <reg52.h>#define uchar unsigned char#define uint unsigned intuchar aa;uchar num;uchar flag;void init();void main(){ init(); while(1) {   if(flag==1)   {      flag=0;      ES=0;                   if(num==255)      num=0;      SBUF=num;      while(!TI);      TI=0;      SBUF=aa;      while(!TI);      TI=0;      ES=1;   } }}void init(){ TMOD=0x20; TH1=0xfd; TL1=0xfd; SM0=0; SM1=1; TR1=1; EA=1; ES=1; REN=1; num=0;}void ser() interrupt 4{ flag=1; RI=0; aa=SBUF; num++;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.