生成一个用C52单片机,超声波测距,oled屏幕
时间: 2023-05-29 14:03:09 浏览: 235
基于51单片机的超声波测距、OLED显示_51单片机_C#_oled_超声波测距
5星 · 资源好评率100%
显示距离的程序
首先,我们需要连接超声波传感器和OLED显示屏到C52单片机上。超声波传感器需要连接到P1口(触发引脚)和P2口(接收引脚),而OLED显示屏需要连接到I2C总线(SCL和SDA引脚)。
接下来,我们可以编写以下程序:
#include <reg52.h>
#include <intrins.h>
#define SDA P1_0
#define SCL P1_1
#define TRIG P1_2
#define ECHO P1_3
typedef unsigned char uchar;
typedef unsigned int uint;
void delay_us(uint n)
{
while(n--)
{
_nop_();
}
}
void i2c_start()
{
SDA = 1;
SCL = 1;
delay_us(2);
SDA = 0;
delay_us(2);
SCL = 0;
}
void i2c_stop()
{
SDA = 0;
SCL = 1;
delay_us(2);
SDA = 1;
delay_us(2);
}
void i2c_write(uchar dat)
{
uchar i;
for(i = 0; i < 8; i++)
{
SDA = (dat & 0x80) >> 7;
dat <<= 1;
SCL = 1;
delay_us(2);
SCL = 0;
delay_us(2);
}
SDA = 1;
SCL = 1;
delay_us(2);
SCL = 0;
}
void oled_init()
{
i2c_start();
i2c_write(0x78);
i2c_write(0xAE); // display off
i2c_write(0xD5); // set display clock divide ratio/oscillator frequency
i2c_write(0x80);
i2c_write(0xA8); // set multiplex ratio
i2c_write(0x3F);
i2c_write(0xD3); // set display offset
i2c_write(0x00);
i2c_write(0x40); // set display start line
i2c_write(0x8D); // set charge pump
i2c_write(0x14);
i2c_write(0x20); // set memory mode
i2c_write(0x00);
i2c_write(0xA1); // set segment remap
i2c_write(0xC8); // set com output scan direction
i2c_write(0xDA); // set com pins hardware configuration
i2c_write(0x12);
i2c_write(0x81); // set contrast control
i2c_write(0xCF);
i2c_write(0xD9); // set pre-charge period
i2c_write(0xF1);
i2c_write(0xDB); // set vcomh deselect level
i2c_write(0x40);
i2c_write(0xA4); // set entire display on/off
i2c_write(0xA6); // set normal/inverse display
i2c_write(0xAF); // display on
i2c_stop();
}
void oled_clear()
{
uchar i, j;
for(i = 0; i < 8; i++)
{
i2c_start();
i2c_write(0x78);
i2c_write(0x00);
i2c_write(0xB0 + i);
i2c_write(0x00);
i2c_write(0x10);
for(j = 0; j < 128; j++)
{
i2c_write(0x00);
}
i2c_stop();
}
}
void oled_show_num(uint num)
{
uchar i, j, k;
uchar buf[4];
buf[0] = num / 1000;
buf[1] = (num / 100) % 10;
buf[2] = (num / 10) % 10;
buf[3] = num % 10;
for(i = 0; i < 8; i += 2)
{
i2c_start();
i2c_write(0x78);
i2c_write(0x00);
i2c_write(0xB0 + i);
i2c_write(0x00);
i2c_write(0x10);
for(j = 0; j < 4; j++)
{
for(k = 0; k < 8; k++)
{
if((oled_font_5x8[buf[j]][k] >> i) & 0x01)
{
i2c_write(0xFF);
}
else
{
i2c_write(0x00);
}
}
}
i2c_stop();
}
}
uint get_distance()
{
uint distance;
TRIG = 0;
delay_us(2);
TRIG = 1;
delay_us(10);
TRIG = 0;
while(!ECHO);
TMOD = 0x09;
TH0 = 0;
TL0 = 0;
while(ECHO);
TR0 = 1;
while(!ECHO);
TR0 = 0;
distance = (TH0 * 256 + TL0) / 58;
return distance;
}
void main()
{
oled_init();
oled_clear();
while(1)
{
uint distance = get_distance();
oled_show_num(distance);
delay_ms(500);
}
}
在此程序中,我们定义了一些常量和变量,包括超声波传感器的触发和接收引脚、OLED屏幕的SDA和SCL引脚,以及显示距离的变量。
我们还定义了一些函数,包括延迟函数、I2C总线操作函数、OLED显示初始化函数、清除OLED显示屏幕函数、显示距离的函数和获取距离的函数。
在主函数中,我们初始化OLED显示屏幕、清除屏幕并循环执行获取距离并显示的操作。
以上就是一个用C52单片机、超声波传感器和OLED显示屏幕实现距离测量的程序。
阅读全文