51单片机使用MQ-135的驱动程序
时间: 2024-05-07 13:19:16 浏览: 106
以下是51单片机使用MQ-135的驱动程序参考代码:
```
#include <reg52.h>
#include <stdio.h>
#define ADC_POWER 0x80
#define ADC_FLAG 0x10
#define ADC_START 0x08
#define ADC_SPEED 0x04
sbit ADC_CS = P1^0;
sbit ADC_CLK = P1^1;
sbit ADC_DIO = P1^2;
unsigned char code table[100]= {0x00,0x17,0x2E,0x45,0x5C,0x73,0x8A,0xA1,0xB8,
0xCF,0xE6,0xFD,0xFF};
void Delay1ms(unsigned int cnt)
{
unsigned int i,j;
for(i=0; i<cnt; i++)
for(j=0; j<110; j++);
}
void ADC_Init(void)
{
ADC_CS = 1;
ADC_CLK = 0;
ADC_DIO = 1;
Delay1ms(10);
}
void ADC_Write(unsigned char dat)
{
unsigned char i;
for(i=0; i<8; i++)
{
if(dat & 0x80)
ADC_DIO = 1;
else
ADC_DIO = 0;
dat <<= 1;
ADC_CLK = 1;
ADC_CLK = 0;
}
}
unsigned char ADC_Read(void)
{
unsigned char i,dat = 0;
for(i=0; i<8; i++)
{
dat <<= 1;
ADC_CLK = 1;
ADC_CLK = 0;
if(ADC_DIO)
dat |= 0x01;
}
return dat;
}
unsigned char MQ135_Read(void)
{
unsigned char i;
unsigned char dat1,dat2;
unsigned char res;
ADC_CS = 0;
ADC_Write(ADC_POWER | ADC_SPEED | ADC_START);
for(i=0; i<200; i++)
{
if(ADC_CS)
break;
Delay1ms(1);
}
ADC_Write(0x00);
dat1 = ADC_Read();
dat2 = ADC_Read();
res = dat1 * 256 + dat2;
ADC_CS = 1;
return res/1024;
}
void main()
{
unsigned char value;
ADC_Init();
while(1)
{
value = MQ135_Read();
if(value > 100)
value = 100;
printf("MQ135 value: %d\r\n", table[value]);
Delay1ms(500);
}
}
```
这段代码通过51单片机读取MQ-135传感器的模拟信号,通过AD转换后将结果输出到串口,可以根据输出的MQ135值来判断空气中有害气体的浓度程度。需要注意的是,这段代码中的数据校准和MQ-135传感器的电路连接需要根据实际情况进行调整。
阅读全文