写一段stm32用oled显示屏显示温湿度和水位代码
时间: 2023-10-12 12:05:01 浏览: 91
好的,以下是一段 STM32F103 上使用 OLED 显示屏显示温湿度和水位的代码:
```C
#include "stm32f10x.h"
#include "delay.h"
#include "i2c.h"
#define OLED_ADDRESS 0x78
#define I2C_CHANNEL I2C1
void oled_write_byte(uint8_t cmd, uint8_t dat);
void oled_clear();
void oled_show_string(uint8_t x, uint8_t y, char *str);
int main(void)
{
// 初始化延时、I2C、OLED 屏幕
delay_init();
i2c_init(I2C_CHANNEL, GPIOB, GPIO_Pin_6, GPIO_Pin_7);
oled_write_byte(0xAE, 0x00); // 关闭显示
oled_write_byte(0x20, 0x00); // 设置内存地址模式
oled_write_byte(0x10, 0x00); // 设置水平方向的寻址模式
oled_write_byte(0xB0, 0x00); // 设置显示起始行
oled_write_byte(0xC8, 0x00); // 设置COM输出扫描方向
oled_write_byte(0x00, 0x10); // 设置低列地址
oled_write_byte(0x40, 0x00); // 设置高列地址
// 读取温度、湿度、水位等传感器数据
float temperature = 25.0;
float humidity = 35.0;
float water_level = 50.0;
// 在 OLED 显示屏幕上显示温湿度和水位
oled_clear();
char buf[16];
sprintf(buf, "Temp: %.1f", temperature);
oled_show_string(0, 0, buf);
sprintf(buf, "Humidity: %.1f", humidity);
oled_show_string(0, 1, buf);
sprintf(buf, "Water Level: %.1f", water_level);
oled_show_string(0, 2, buf);
while(1);
}
void oled_write_byte(uint8_t cmd, uint8_t dat)
{
uint8_t buf[2] = {cmd, dat};
i2c_write(I2C_CHANNEL, OLED_ADDRESS, buf, 2);
}
void oled_clear()
{
for(int page = 0; page < 8; page++)
{
oled_write_byte(0xB0 + page, 0x00);
oled_write_byte(0x00, 0x10);
oled_write_byte(0x00, 0x00);
for(int col = 0; col < 128; col++)
{
oled_write_byte(0x40, 0x00);
}
}
}
void oled_show_string(uint8_t x, uint8_t y, char *str)
{
uint8_t page = y;
uint8_t col = x * 8;
while(*str)
{
char chr = *str;
oled_write_byte(0xB0 + page, col & 0x0F);
oled_write_byte(((col & 0xF0) >> 4) | 0x10, 0x00);
oled_write_byte(((chr - ' ') * 16) | 0x01, 0x00);
for(int i = 0; i < 8; i++)
{
oled_write_byte(0x40, 0xFF);
}
col += 8;
str++;
}
}
```
阅读全文