设为首页收藏本站淘宝杂货铺

从F到0 - From F to 0

 找回密码
 注册已关闭
搜索
查看: 1355|回复: 2
收起左侧

STC15F104W 8脚单片机 定时器中断实现软件模拟串口(软串口) 460800高波特率数据发送

[复制链接]
发表于 2021-10-30 18:07:46 | 显示全部楼层 |阅读模式
本帖最后由 GPIO 于 2021-10-30 19:14 编辑
该型号无内置硬件串口,由定时器中断实现高波特率软串口向上位机发送字符串。
单片机型号:STC15F104W、STC15W104 (不支持104E) 晶振频率:33.1776Mhz 波特率:460800 (晶振误差导致误码属于正常现象)

1.png
  1. #include "STC15F104E.h"
  2. #include "intrins.h"
  3. #define u8 unsigned char
  4. #define u16 unsigned int
  5. #define u32 unsigned long
  6. sbit txd = P3 ^ 1;
  7. void InitTimer0(){
  8.     TMOD = 0x01;
  9.     TH0 = 0xFF;
  10.     TL0 = 0xD0;
  11.     EA = 1;
  12.     ET0 = 1;
  13. }

  14. void Delay1ms(){                //@33.1776MHz
  15.     u8 i, j;
  16.     i = 33;
  17.     j = 66;
  18.     do
  19.     {
  20.         while (--j);
  21.     } while (--i);
  22. }


  23. u8 bdata TXD_dat;       //串口数据 (可位寻址)
  24. sbit tx = TXD_dat ^ 0;

  25. void TXD_Byte(u8 dat) {         //串口发送1字节
  26.     TXD_dat = dat;
  27.     TR0 = 1;
  28.     while (TR0);
  29. }

  30. void TXD_Text(u8* text) {      //串口发送字符串
  31.     for (; *text; text++) {
  32.         TXD_Byte(*text);
  33.     }
  34. }

  35. void main(){
  36.     AUXR |= 0x80;
  37.     InitTimer0();
  38.     while (1) {
  39.         Delay1ms();
  40.         TXD_Text("Hello World! 中文字符串测试 0123456789\r\n");
  41.         
  42.     }
  43. }

  44. void Timer0Interrupt() interrupt 1 {
  45.     static u8 a = 0;
  46.     TH0 = 0xFF;
  47.     TL0 = 0xD0;
  48.     switch (a++) {
  49.         case 0: {       //起始位
  50.             txd = 0;
  51.             return;
  52.         }

  53.         case 9: {       //停止位
  54.             txd = 1;
  55.             a = 0;
  56.             TR0 = 0;
  57.             return;
  58.         }

  59.         default: {      //数据位
  60.             txd = tx;
  61.             TXD_dat >>= 1;
  62.             return;
  63.         }
  64.     }
  65.    

  66. }
复制代码

相关帖子

您需要登录后才可以回帖 登录 | 注册已关闭

本版积分规则

QQ|手机版|Archiver|从F到0 ( 蒙ICP备17002595号-1 )
蒙公网安备15010402000325号

腾讯云安全认证

GMT+8, 2024-4-27 01:32 , Processed in 0.991057 second(s), 22 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表