基于stc12c560s2单片机 收集到土壤湿度传感器的数据并且通过PCF8951转换芯片,显示在 lcd1602的代码
时间: 2024-02-06 07:12:15 浏览: 137
以下是一个基于STC12C560S2单片机的土壤湿度传感器数据采集和显示代码,您可以根据自己的需求进行修改和适配:
```c
#include <reg52.h>
#include <intrins.h>
#define LCD1602_DB P0
sbit LCD1602_RS = P2^0;
sbit LCD1602_RW = P2^1;
sbit LCD1602_E = P2^2;
#define PCF8951_ADDR 0x90
sbit SDA=P1^1;
sbit SCL=P1^0;
void DelayMs(unsigned int ms) {
unsigned int i, j;
for (i = 0; i < ms; i++) {
for (j = 0; j < 110; j++);
}
}
void I2CStart() {
SDA = 1;
SCL = 1;
_nop_();
_nop_();
_nop_();
SDA = 0;
_nop_();
_nop_();
_nop_();
SCL = 0;
}
void I2CStop() {
SDA = 0;
SCL = 1;
_nop_();
_nop_();
_nop_();
SDA = 1;
_nop_();
_nop_();
_nop_();
}
void I2CAck() {
SDA = 0;
_nop_();
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
SCL = 0;
_nop_();
_nop_();
_nop_();
SDA = 1;
}
void I2CNack() {
SDA = 1;
_nop_();
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
SCL = 0;
_nop_();
_nop_();
_nop_();
SDA = 1;
}
unsigned char I2CWriteByte(unsigned char dat) {
unsigned char mask;
for (mask = 0x80; mask != 0; mask >>= 1) {
if ((mask & dat) == 0) {
SDA = 0;
} else {
SDA = 1;
}
_nop_();
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
SCL = 0;
}
SDA = 1;
_nop_();
_nop_();
_nop_();
SCL = 1;
_nop_();
_nop_();
_nop_();
if (SDA == 0) {
SCL = 0;
return 0;
} else {
SCL = 0;
return 1;
}
}
unsigned char I2CReadByte() {
unsigned char mask;
unsigned char dat = 0;
SDA = 1;
_nop_();
_nop_();
_nop_();
for (mask = 0x80; mask != 0; mask >>= 1) {
SCL = 1;
_nop_();
_nop_();
_nop_();
if (SDA == 1) {
dat |= mask;
}
SCL = 0;
_nop_();
_nop_();
_nop_();
}
SDA = 1;
_nop_();
_nop_();
_nop_();
return dat;
}
void LCD1602WriteCmd(unsigned char cmd) {
LCD1602_RS = 0;
LCD1602_RW = 0;
LCD1602_DB = cmd;
LCD1602_E = 1;
_nop_();
_nop_();
_nop_();
LCD1602_E = 0;
DelayMs(2);
}
void LCD1602WriteData(unsigned char dat) {
LCD1602_RS = 1;
LCD1602_RW = 0;
LCD1602_DB = dat;
LCD1602_E = 1;
_nop_();
_nop_();
_nop_();
LCD1602_E = 0;
DelayMs(2);
}
void LCD1602Init() {
LCD1602WriteCmd(0x38);
LCD1602WriteCmd(0x0c);
LCD1602WriteCmd(0x06);
LCD1602WriteCmd(0x01);
DelayMs(5);
}
void PCF8951Init() {
I2CStart();
I2CWriteByte(PCF8951_ADDR);
I2CWriteByte(0x01);
I2CWriteByte(0x84);
I2CStop();
}
unsigned int PCF8951Read() {
unsigned char high, low;
unsigned int val;
I2CStart();
I2CWriteByte(PCF8951_ADDR);
I2CWriteByte(0x00);
I2CStart();
I2CWriteByte(PCF8951_ADDR | 0x01);
high = I2CReadByte();
I2CAck();
low = I2CReadByte();
I2CNack();
I2CStop();
val = ((unsigned int)high << 8) | low;
return val;
}
void main() {
unsigned int val;
unsigned char str[6] = {0};
LCD1602Init();
PCF8951Init();
while (1) {
val = PCF8951Read();
sprintf(str, "%u", val);
LCD1602WriteCmd(0x01);
LCD1602WriteCmd(0x80);
LCD1602WriteData('H');
LCD1602WriteData(':');
LCD1602WriteData(str[0]);
LCD1602WriteData(str[1]);
LCD1602WriteData(str[2]);
LCD1602WriteData(str[3]);
LCD1602WriteData(str[4]);
DelayMs(1000);
}
}
```
以上是一个简单的例程,具体的细节和修改可以根据实际需求进行调整。
阅读全文