標題: 51單片機模擬串口收發(fā)數(shù)據(jù)的方法 附程序 [打印本頁]

作者: diyue    時間: 2024-1-2 20:30
標題: 51單片機模擬串口收發(fā)數(shù)據(jù)的方法 附程序
標準51單片機,比如STC89C52RC只有一個串口,當我們需要多串口通信時就有些捉襟見肘了,在不贈加成本的基礎上最好的辦法就是模擬一個串口;在這個項目中我們采用的單片機型號為STC12C5A60S2,晶振為11.0592MHZ,12倍頻,同樣適用于STC89C52RC,大家如果有興趣可以自己下載源碼應用,以下是工程源碼:
  1. #include<stc12c5a60s2.h>
  2. #define uchar unsigned char
  3. #define uint unsigned int

  4. sbit RXD=P3^2;
  5. sbit TXD=P3^1;
  6. sbit led=P1^0;

  7. uchar buf;


  8. void delayms(unsigned int ms)
  9. {
  10.       unsigned int De_Cnt;
  11.       while( (ms--) != 0)
  12.        {
  13.         for(De_Cnt = 0; De_Cnt < 950; De_Cnt++);
  14.        }            
  15. }

  16. void T0_init(void)
  17. {
  18.     TMOD|=0x01;
  19.     TH0=0XFF;
  20.     TL0=0XA0;
  21.     IE|=0X81;
  22.     TF0=0;
  23.     IT0=1;
  24.     TR1=1 ;
  25. }

  26. void waitTF0()
  27. {
  28.     while(!TF0);
  29.     TF0=0;
  30.     TH0=0XFF;
  31.     TL0=0XA0;
  32. }

  33. uchar readbyte()
  34. {
  35.     uchar output=0;
  36.     uchar i=8;
  37.     TR0=1;
  38.     TH0=0XFF;
  39.     TL0=0XA0;
  40.     TF0=0;
  41.     waitTF0();
  42.     while(i--)
  43.     {
  44.    output>>=1 ;
  45.    if(RXD) output|=0x80;
  46.    waitTF0();
  47.     }
  48.     TR0=0;
  49.     return output;
  50. }


  51. void int0() interrupt 0
  52. {
  53.     EX0=0;
  54.     buf=readbyte();
  55.     IE0=0;
  56.     EX0=1;
  57. }


  58. void main()
  59. {
  60.   T0_init();
  61.     while(1)
  62.     {   
  63.         delayms(300);
  64.         if(buf=='A') led=0;
  65.         else  led=1;
  66.     }
  67. }
復制代碼

原理圖: 無
仿真: 無
Keil代碼: 程序.7z (20.16 KB, 下載次數(shù): 19)






歡迎光臨 (http://www.torrancerestoration.com/bbs/) Powered by Discuz! X3.1