生成一个用C52单片机,超声波测距,要求:(1)测量距离范围0-3米,液晶显示距离信息(厘米),测量误差小于5%;(2)液晶显示内容及形式可以自定,但必须包括测量距离信息,设置警戒距离;动态更新测量结果,更新时间小于0.5秒; (3)通过按键设定警戒距离,当距离小于1米,蜂鸣器报警;oled屏幕,鸣蜂器管脚:feng=p2^0;k1=p2^7;k2=p2^6;k3=p2^5;超声波管脚:Trig=p3^6;Echo=p3^7;OLED管脚p10p11
时间: 2023-05-29 17:03:35 浏览: 110
#include <reg52.h>
#include <intrins.h>
#include "OLED12864.h"
#define uint unsigned int
#define uchar unsigned char
sbit Trig = P3^6;
sbit Echo = P3^7;
sbit feng = P2^0;
sbit k1 = P2^7;
sbit k2 = P2^6;
sbit k3 = P2^5;
void delay_us(uint t) {
while(t--);
}
void delay_ms(uint t) {
while(t--) {
delay_us(245);
delay_us(245);
delay_us(245);
delay_us(245);
}
}
void init() {
TMOD = 0x01;
TH0 = 0x3C;
TL0 = 0xB0;
TR0 = 1;
ET0 = 1;
EA = 1;
OLED_Init();
OLED_CLS();
OLED_P6x8Str(20, 2, "Ultrasonic Ranging");
OLED_P6x8Str(20, 4, "Distance:");
OLED_P6x8Str(20, 6, "Warning:");
}
void send_pulse() {
Trig = 1;
delay_us(10);
Trig = 0;
}
uint measure_distance() {
uint distance = 0;
while(!Echo);
TR0 = 1;
while(Echo) {
if(TF0) {
distance = 0xFFFF;
break;
}
}
TR0 = 0;
distance = (TH0 << 8) | TL0;
distance = distance / 58;
return distance;
}
void update_display(uint distance, uint warning_distance) {
char buffer[6];
OLED_CLS();
OLED_P6x8Str(20, 2, "Ultrasonic Ranging");
OLED_P6x8Str(20, 4, "Distance:");
OLED_P6x8Str(80, 4, "cm");
OLED_P6x8Str(20, 6, "Warning:");
OLED_P6x8Str(80, 6, "cm");
sprintf(buffer, "%d", distance);
OLED_P6x8Str(60, 4, buffer);
sprintf(buffer, "%d", warning_distance);
OLED_P6x8Str(60, 6, buffer);
if(distance < warning_distance) {
feng = 1;
} else {
feng = 0;
}
}
void main() {
uint distance = 0;
uint warning_distance = 100;
init();
while(1) {
send_pulse();
distance = measure_distance();
if(distance > 300) {
distance = 300;
}
update_display(distance, warning_distance);
delay_ms(100);
if(k1 == 0) {
warning_distance = 50;
} else if(k2 == 0) {
warning_distance = 100;
} else if(k3 == 0) {
warning_distance = 200;
}
}
}
void timer0_isr() interrupt 1 {
TH0 = 0x3C;
TL0 = 0xB0;
TF0 = 0;
}
阅读全文