- #include <reg52.h>
- #include <intrins.h>
- #define uchar unsigned char
- #define uint unsigned int
- // 定义独立按键连接引脚,这里假设连接到P3^2,可根据实际调整
- sbit key = P3^2;
- // LCD1602控制引脚定义
- sbit RS = P2^0;
- sbit RW = P2^1;
- sbit E = P2^2;
- // 要发送给PC机的8个数据
- uchar data_to_send[8] = {0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38};
- // 用于缓存接收自PC机的数据
- uchar received_data[16];
- // 记录接收数据的个数
- uchar received_count = 0;
- // 软件延时函数,用于产生一定时间的延时
- void delay(uint ms) {
- uint i, j;
- for (i = ms; i > 0; i--)
- for (j = 110; j > 0; j--);
- }
- // 向LCD1602写入命令
- void LCD_WriteCmd(uchar cmd) {
- RS = 0;
- RW = 0;
- P0 = cmd;
- E = 1;
- _nop_();
- E = 0;
- delay(5);
- }
- // 向LCD1602写入数据
- void LCD_WriteData(uchar dat) {
- RS = 1;
- RW = 0;
- P0 = dat;
- E = 1;
- _nop_();
- E = 0;
- delay(5);
- }
- // 初始化LCD1602
- void LCD_Init() {
- LCD_WriteCmd(0x38); // 设置16*2显示,5*7点阵,8位数据接口
- LCD_WriteCmd(0x0C); // 显示开,光标关,光标不闪烁
- LCD_WriteCmd(0x06); // 文字不动,地址自动+1
- LCD_WriteCmd(0x01); // 清屏
- delay(5);
- }
- // 在LCD1602上显示给定缓冲区中的数据
- void LCD_Display(uchar dat_buf[], uchar length) {
- uchar i;
- for (i = 0; i < length; i++) {
- LCD_WriteData(dat_buf[i]);
- }
- }
- // 初始化串口
- void UART_Init() {
- SCON = 0x50; // 设置串口工作模式1,8位数据,1位停止位
- TMOD = 0x20; // 设置定时器1为模式2,自动重装
- TH1 = 0xFD; // 波特率9600bps,晶振11.0592MHz
- TL1 = 0xFD;
- TR1 = 1; // 启动定时器1
- ES = 1; // 使能串口中断
- EA = 1; // 使能总中断
- }
- // 通过串口发送一个字节的数据
- void UART_Send(uchar dat) {
- SBUF = dat; // 发送数据
- while (!TI); // 等待发送完成
- TI = 0; // 清除发送标志
- }
- // 串口中断服务函数,用于接收数据
- void UART_ISR() interrupt 4 {
- if (RI) {
- RI = 0; // 清除接收标志
- received_data[received_count++] = SBUF; // 接收数据到缓存数组
- if (received_count >= 16) {
- received_count = 0; // 防止缓存溢出,重置计数
- }
- }
- }
- void main() {
- uchar i;
- UART_Init(); // 初始化串口
- LCD_Init(); // 初始化LCD1602
- while (1) {
- if (key == 0) { // 检测按键是否按下
- for (i = 0; i < 8; i++) {
- UART_Send(data_to_send[i]); // 循环发送8个数据给PC机
- }
- while (key == 0); // 等待按键释放
- }
- if (received_count > 0) { // 如果有接收到的数据
- LCD_WriteCmd(0x80); // 设置LCD显示位置为第一行
- LCD_Display(received_data, received_count); // 在LCD上显示接收的数据
- received_count = 0; // 清空接收缓存计数,准备下次接收
- }
- }
- }
复制代码
|