51单片机使用MQ-2实时检测烟雾浓度,根据烟雾浓度调节PWM风扇转速并且使用LCD1602显示当前转速和当前烟雾浓度的C语言代码
时间: 2023-11-28 16:50:06 浏览: 131
以下是基于51单片机的使用MQ-2实时检测烟雾浓度,根据烟雾浓度调节PWM风扇转速并且使用LCD1602显示当前转速和当前烟雾浓度的C语言代码:
```c
#include <reg52.h>
#include <intrins.h>
#define uchar unsigned char
#define uint unsigned int
#define LCD_Data_Port P0
sbit LCD_RS = P2^6;
sbit LCD_RW = P2^5;
sbit LCD_EN = P2^7;
sbit MQ2 = P3^2;
sbit FAN = P1^4;
uchar code table[]=" fan speed:";//lcd显示
uchar PWM_val; //PWM占空比
uint smoke_val; //烟雾浓度
void delay(uint xms) //延时函数
{
uint i, j;
for(i = xms; i > 0; i--)
for(j = 110; j > 0; j--);
}
void LCD_Write_Cmd(uchar cmd) //写入命令函数
{
LCD_RS = 0;
LCD_RW = 0;
LCD_Data_Port = cmd;
LCD_EN = 1;
_nop_();
_nop_();
_nop_();
_nop_();
LCD_EN = 0;
delay(5);
}
void LCD_Write_Data(uchar dat) //写入数据函数
{
LCD_RS = 1;
LCD_RW = 0;
LCD_Data_Port = dat;
LCD_EN = 1;
_nop_();
_nop_();
_nop_();
_nop_();
LCD_EN = 0;
delay(5);
}
void LCD_Init() //LCD初始化函数
{
LCD_Write_Cmd(0x38); //开显示,16x2,5x7点阵
LCD_Write_Cmd(0x0c); //开显示不显示光标
LCD_Write_Cmd(0x06); //文字不动,地址加1
LCD_Write_Cmd(0x01); //清屏命令
}
void init_Timer0() //定时器0初始化函数
{
TMOD|=0x01;
TH0=0;
TL0=0;
ET0=1;
TR0=1;
EA=1;
}
void Timer0_ISR() interrupt 1 //定时器0中断服务程序
{
static uint cnt;
if(cnt == 100) //每隔100ms读取一次烟雾浓度
{
cnt = 0;
smoke_val = (ADC_Read(0)>>2); //读取烟雾浓度
}
cnt++;
if(smoke_val > 200) //根据烟雾浓度调节PWM占空比
PWM_val = 255;
else if(smoke_val > 100)
PWM_val = 200;
else if(smoke_val > 50)
PWM_val = 150;
else if(smoke_val > 20)
PWM_val = 100;
else
PWM_val = 0;
FAN = (PWM_val > TH0); //根据PWM占空比调节风扇转速
}
uchar ADC_Read(uchar ch) //ADC读取函数
{
ADC_CONTR = ADC_POWER | ADC_SPEEDLL | ch;
delay(1);
ADC_CONTR |= ADC_START;
while(!(ADC_CONTR & ADC_FLAG));
ADC_CONTR &= ~ADC_FLAG;
return ADC_RES;
}
void main()
{
LCD_Init(); //初始化LCD
init_Timer0(); //初始化定时器0
while(1)
{
LCD_Write_Cmd(0x80); //第一行
for(uchar i=0; i<13; i++)
LCD_Write_Data(table[i]);
LCD_Write_Data((uchar)(PWM_val/10)+'0'); //显示风扇转速
LCD_Write_Data((uchar)(PWM_val%10)+'0');
LCD_Write_Data(' ');
LCD_Write_Data(' ');
LCD_Write_Cmd(0xc0); //第二行
LCD_Write_Data('s');
LCD_Write_Data('m');
LCD_Write_Data('o');
LCD_Write_Data('k');
LCD_Write_Data('e');
LCD_Write_Data(':');
LCD_Write_Data(' ');
LCD_Write_Data((uchar)(smoke_val/100)+'0'); //显示烟雾浓度
LCD_Write_Data((uchar)(smoke_val/10%10)+'0');
LCD_Write_Data((uchar)(smoke_val%10)+'0');
delay(100);
}
}
```
注:本代码仅供参考,具体实现可能因硬件环境等因素而有所不同,使用时请结合实际情况进行修改。
阅读全文