蓝桥杯单片机_简化代码

张开发
2026/4/6 8:42:59 15 分钟阅读

分享文章

蓝桥杯单片机_简化代码
1、按键注static uint count 0;是int类型不要char类型if (count 2 count 100)不要写等于以免和上面代码冲突count 0; 判断完后 再赋值清零void loop(uchar *key) { static uchar now, last; static uint count 0; // 核心增加一个计数器 uchar t 0; // --- 保持你原有的矩阵扫描逻辑 --- P421;P441;P30xff;P300; if(P440) t7; else if(P420) t11; else if(P350) t15; else if(P340) t19; P421;P441;P30xff;P310; if(P440) t6; else if(P420) t10; else if(P350) t14; else if(P340) t18; P421;P441;P30xff;P320; if(P440) t5; else if(P420) t9; else if(P350) t13; else if(P340) t17; P421;P441;P30xff;P330; if(P440) t4; else if(P420) t8; else if(P350) t12; else if(P340) t16; // --- 修改后的逻辑处理 --- last now; now t; if (now) // 按键正被按下 { count; // 只要按着计数器就一直加 if (count 100) // 【长按触发】在还没松开时如果计数值到了100约1秒 *key now 100; // 给键值加100用来区分长按。比如长按S4返回104 } else // now 0说明按键松开了 { if (count 2 count 100) // 【短按触发】松开瞬间如果计数器此之间防抖非长按 *key last; // 返回原始键值比如短按S4返回4 count 0; // 只要松开计数器一定要清零 } }2、串口发送//在main函数中 #include stdio.h char putchar(char c) { SBUFc; while(TI0); TI0; return c; } void main() { printf(Temp: %bd,%bd C \n, 25, 5);//注意是%bd Delay500ms(); }3、超声波开始之前记得清0TL1 0; //设置定时初始值TH1 0; //设置定时初始值void Send_Wave(void) { unsigned char i; for(i 0; i 8; i) // 发送8个脉冲 { TX 1; _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); TX 0; _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); _nop_(); } } while(1) { Delay500ms(); TL1 0; //设置定时初始值 TH1 0; //设置定时初始值 Send_Wave(); TR11; while(TF10 RX1); TR10; if(TF1) { TF10; juli999; } else { juli(TH18)|TL1;juli*0.017; TH10;TL10; } buff[0]juli/100; buff[1]juli/10%10; buff[2]juli%10; }4、ADC_DAC实现ADC的采集和DAC的输出unsigned char ADC_DAC(char chan,char dac) { unsigned char adc0; EA0; I2CStart(); I2CSendByte(0x90);I2CWaitAck(); I2CSendByte(0x40chan);I2CWaitAck(); I2CSendByte(dac);I2CWaitAck(); I2CStop(); I2CStart(); I2CSendByte(0x91);I2CWaitAck(); adcI2CReceiveByte(); I2CSendAck(1); I2CStop(); EA1; return adc; }

更多文章