#include <reg51.h> #define uchar unsigned char #define uint unsigned int

sbit beep=P1^5; sbit led=P1^6; sbit key_add=P3^0; sbit key_minus=P3^1; sbit fan=P2^0; sbit ds=P2^1; sbit st=P2^2; sbit sh=P2^3;

uchar code table[]={ 0x3f, //0 0x06, //1 0x5b, //2 0x4f, //3 0x66, //4 0x6d, //5 0x7d, //6 0x07, //7 0x7f, //8 0x6f, //9 0x77, //A 0x7c, //B 0x39, //C 0x5e, //D 0x79, //E 0x71 //F };

uchar temp_high=30; //上限温度 uchar temp_low=20; //下限温度 uchar temp_set=25; //设定温度 uchar temp_current=0; //当前温度,初始化为0 bit flag_key_add=0; //连加标志 bit flag_key_minus=0; //连减标志

void delay_ms(uint ms) { uint i,j; for(i=0;i<ms;i++) for(j=0;j<110;j++); }

void ds18b20_init() { uchar i; ds=1; delay_ms(1); ds=0; delay_ms(500); ds=1; delay_ms(1); i=ds; delay_ms(500); }

void ds18b20_write_byte(uchar dat) { uchar i; for(i=0;i<8;i++) { ds=0; ds=dat&0x01; delay_ms(1); ds=1; dat>>=1; } }

uchar ds18b20_read_byte() { uchar i,dat=0; for(i=0;i<8;i++) { dat>>=1; ds=0; ds=1; if(ds) dat|=0x80; delay_ms(1); } return dat; }

void ds18b20_start() { ds18b20_init(); ds18b20_write_byte(0xcc); //跳过ROM操作 ds18b20_write_byte(0x44); //启动温度转换 }

uchar ds18b20_read_temp() { uchar temp_l,temp_h; ds18b20_start(); ds18b20_init(); ds18b20_write_byte(0xcc); //跳过ROM操作 ds18b20_write_byte(0xbe); //读取温度数据 temp_l=ds18b20_read_byte(); temp_h=ds18b20_read_byte(); return temp_l+(temp_h<<8)/16; //返回温度值 }

void display_num(uchar num,uchar dot) { sh=0; P0=table[num/10]; sh=1; P0=table[num%10]|dot; sh=0; P0=0xff; }

void display_temp(uchar temp) { uchar temp_int=temp/10; uchar temp_dec=temp%10; display_num(temp_int,0x00); display_num(temp_dec,0x80); }

void alarm() { beep=1; led=1; fan=1; delay_ms(500); beep=0; led=0; fan=0; delay_ms(500); }

void main() { uchar key_add_count=0; //连加计数器 uchar key_minus_count=0; //连减计数器 uchar temp_memory=0; //温度阈值存储 ds18b20_init(); while(1) { temp_current=ds18b20_read_temp(); if(temp_current>temp_high || temp_current<temp_low) alarm(); display_temp(temp_current); if(key_add==0) { delay_ms(10); if(key_add==0) { key_add_count++; if(key_add_count>10) { key_add_count=0; flag_key_add=1; } else { flag_key_add=0; } while(!key_add); } } if(key_minus==0) { delay_ms(10); if(key_minus==0) { key_minus_count++; if(key_minus_count>10) { key_minus_count=0; flag_key_minus=1; } else { flag_key_minus=0; } while(!key_minus); } } if(flag_key_add==1) //连加 { flag_key_add=0; if(temp_set<99) temp_set++; } if(flag_key_minus==1) //连减 { flag_key_minus=0; if(temp_set>0) temp_set--; } if(temp_memory!=temp_set) //温度阈值更新 { temp_memory=temp_set; //将temp_set存入EEPROM中 } delay_ms(100); } }

51单片机温控风扇设计 - 温度控制、报警、按键连加减、阈值记忆

原文地址: https://www.cveoy.top/t/topic/oEKc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录