51单片机驱动sht20代码
时间: 2023-11-09 07:07:56 浏览: 141
以下是51单片机驱动SHT20温湿度传感器的基本代码:
```
#include<reg52.h>
sbit SHT20_SCL=P3^6;
sbit SHT20_SDA=P3^7;
void delay_us(unsigned int t)
{
while(t--);
}
void delay_ms(unsigned int t)
{
while(t--)
{
delay_us(1000);
}
}
void IIC_Start(void)
{
SHT20_SCL=1;
SHT20_SDA=1;
delay_us(4);
SHT20_SDA=0;
delay_us(4);
SHT20_SCL=0;
}
void IIC_Stop(void)
{
SHT20_SCL=0;
SHT20_SDA=0;
delay_us(4);
SHT20_SCL=1;
delay_us(4);
SHT20_SDA=1;
}
unsigned char IIC_SendByte(unsigned char dat)
{
unsigned char i;
unsigned char ack_bit;
for(i=0;i<8;i++)
{
SHT20_SCL=0;
if(dat&0x80)
{
SHT20_SDA=1;
}
else
{
SHT20_SDA=0;
}
dat<<=1;
delay_us(4);
SHT20_SCL=1;
delay_us(4);
}
SHT20_SCL=0;
SHT20_SDA=1;
delay_us(4);
SHT20_SCL=1;
ack_bit=SHT20_SDA;
delay_us(4);
SHT20_SCL=0;
return ack_bit;
}
unsigned char IIC_ReadByte(unsigned char ack)
{
unsigned char i;
unsigned char dat=0;
SHT20_SCL=0;
SHT20_SDA=1;
delay_us(4);
for(i=0;i<8;i++)
{
SHT20_SCL=1;
delay_us(4);
dat<<=1;
if(SHT20_SDA)
{
dat|=0x01;
}
SHT20_SCL=0;
delay_us(4);
}
if(ack)
{
SHT20_SDA=0;
}
else
{
SHT20_SDA=1;
}
delay_us(4);
SHT20_SCL=1;
delay_us(4);
SHT20_SCL=0;
SHT20_SDA=1;
return dat;
}
void SHT20_Reset(void)
{
IIC_Start();
IIC_SendByte(0x80);
IIC_Stop();
delay_ms(50);
}
unsigned char SHT20_CheckCRC(unsigned char *data,unsigned char len,unsigned char crc)
{
unsigned char i,j;
for(i=0;i<len;i++)
{
crc^=data[i];
for(j=0;j<8;j++)
{
if(crc&0x80)
{
crc=(crc<<1)^0x31;
}
else
{
crc<<=1;
}
}
}
return crc;
}
void SHT20_StartMeasure(unsigned char mode)
{
IIC_Start();
IIC_SendByte(0x80);
IIC_SendByte(mode);
}
unsigned char SHT20_ReadMeasure(unsigned char *data,unsigned char len)
{
unsigned char i;
unsigned char crc;
for(i=0;i<len;i++)
{
data[i]=IIC_ReadByte(i==(len-1)?0:1);
}
crc=SHT20_CheckCRC(data,len-1,data[len-1]);
return crc;
}
void main()
{
unsigned char data[3];
unsigned char crc;
SHT20_Reset();
SHT20_StartMeasure(0xF5);
delay_ms(50);
crc=SHT20_ReadMeasure(data,3);
if(crc==data[2])
{
//温度值 data[0]
//湿度值 data[1]
}
}
```
注意,这只是基本的驱动代码,具体应用时还需要根据实际情况进行相应的修改和调整。
阅读全文