Arduino · 2015年5月7日 1

基于Arduino的根据温度自动开关空调

家有龙猫,那玩意儿太怕热,夏天就要来了,以前都是上班的时候就要把空调打开,琢磨着太费电,于是有了这个小玩意儿。 uno只有一个5v输出口,所以我把温度传感器的供电放在3.3V上,经过测试没有问题,可以正常使用。 需要: arduino uno 温度传感器DS18B20模块 红外发射模块 9V电池 代码如下:

/**
 * 根据温度自动开关空调
 * @author 废墟
 */
#include <avr/sleep.h>
#include <avr/wdt.h>
#include <IRremote.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#define ONE_WIRE_BUS 2

volatile byte count = 0;
volatile byte stat = 0;

unsigned int raw_AC_open[74] = {8950, 4350, 700, 1600, 700, 500, 650, 550, 650, 1600, 700, 500, 650, 550, 650, 500, 650, 550, 650, 500, 650, 1600, 700, 500, 700, 1550, 700, 500, 700, 500, 650, 500, 700, 500, 650, 550, 650, 500, 650, 500, 700, 500, 700, 450, 700, 500, 700, 500, 650, 500, 700, 500, 650, 550, 650, 450, 700, 550, 650, 1550, 700, 550, 650, 1550, 700, 500, 700, 500, 700, 1550, 700, 500, 700};

unsigned int raw_AC_close[74] = {9000, 4350, 700, 1600, 650, 500, 700, 500, 650, 500, 700, 500, 700, 450, 700, 550, 650, 500, 650, 500, 700, 1600, 700, 450, 700, 1600, 700, 450, 700, 500, 700, 450, 700, 500, 700, 450, 750, 500, 650, 500, 700, 450, 700, 500, 700, 500, 650, 500, 700, 500, 650, 500, 700, 500, 650, 550, 650, 450, 750, 1550, 700, 500, 700, 1550, 700, 500, 700, 450, 700, 1600, 700, 450, 700};

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);

IRsend  irsend;

float maxTemperature = 32.00;
float minTemperature = 27.00;

void setup() {
	pinMode(13,OUTPUT);
	sensors.begin();
	Setup_watchdog(9);
	// 0=16ms, 1=32ms,2=64ms,3=128ms,4=250ms,5=500ms
	// 6=1 sec,7=2 sec, 8=4 sec, 9= 8sec
	ACSR |= _BV(ACD); //OFF ACD
	ADCSRA = 0; //OFF ADC
	Sleep_avr();//Sleep_Mode
}

void Setup_watchdog(byte time) {
	byte w_time;
	if (time > 9 ) time = 9;
	w_time = time & 7;
	if (time > 7) w_time |= (1 << 5);
	w_time |= (1 << WDCE);

	MCUSR &= ~(1 << WDRF);
	// start timed sequence
	WDTCSR |= (1 << WDCE) | (1 << WDE);
	// set new watchdog timeout value
	WDTCSR = w_time;
	WDTCSR |= _BV(WDIE);
}

ISR(WDT_vect) {
	++count;
}

void Sleep_avr() {
	set_sleep_mode(SLEEP_MODE_PWR_DOWN); // sleep mode is set here
	sleep_enable();
	sleep_mode();                        // System sleeps here
}

void loop()
{
	if (count >= 2) {
		count = 0;
//-------------------------------
		digitalWrite(13, HIGH);
		delay(100);
		sensors.requestTemperatures();
		if (sensors.getTempCByIndex(0) > maxTemperature) {
			irsend.sendRaw(raw_AC_open, 74, 40);
			stat = 1;
		} else if (sensors.getTempCByIndex(0) < minTemperature && stat == 1) {
			irsend.sendRaw(raw_AC_close, 74, 40);
			stat = 0;
		}
		digitalWrite(13, LOW);
//--------------------------------
		Sleep_avr();
	}
	else {
		Sleep_avr();  //Continue Sleep
	}


}

代码下载:Arduino自动控制空调