#include "stc15w4k32s4.h"\n\n#define FOSC 11059200UL // 系统时钟频率,这里假设为11.0592MHz\n#define BAUD 9600 // 串口波特率,这里假设为9600bps\n\nvoid init_uart() {\n // 配置波特率发生器\n unsigned int divisor;\n divisor = FOSC / 4 / BAUD;\n SCON = 0x50; // 设置串口工作模式为8位数据位、可变波特率\n TMOD &= 0x0F; // 清除定时器1设置\n TMOD |= 0x20; // 设置定时器1为模式2(8位自动重装载)\n TH1 = TL1 = 0xFD; // 设置定时器1初值\n TR1 = 1; // 启动定时器1\n PCON |= 0x80; // SM0=0,即串口工作在模式1(8位波特率可变)下\n\n // 配置串口引脚\n P2 = P2 | 0xC0; // P2.6和P2.7设置为推挽输出模式\n P_SW2 &= ~0xC0; // P_SW2.6和P_SW2.7设置为0,使P2.6和P2.7引脚工作在串口模式下\n}\n\nvoid send_char(unsigned char c) {\n SBUF = c;\n while (!TI); // 等待发送完成\n TI = 0; // 清除发送完成标志位\n}\n\nvoid send_string(unsigned char *str) {\n while (*str) {\n send_char(*str++);\n }\n}\n\nvoid receive_string(unsigned char *buf, unsigned int len) {\n unsigned int i;\n for (i = 0; i < len; i++) {\n while (!RI); // 等待接收完成\n RI = 0; // 清除接收完成标志位\n buf[i] = SBUF;\n }\n}\n\nvoid main() {\n unsigned char receive_buf[32];\n init_uart();\n EA = 1; // 允许中断\n while (1) {\n send_string("Please enter a string: ");\n receive_string(receive_buf, sizeof(receive_buf));\n send_string("You entered: ");\n send_string(receive_buf);\n send_string("\r\n");\n }\n}

STC15W4K32S4 串口程序:收发字符串示例

原文地址: https://www.cveoy.top/t/topic/pSkG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录