Hackster is hosting Hackster Holidays, Ep. 7: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Friday!Stream Hackster Holidays, Ep. 7 on Friday!
Published © GPL3+

Temperature controlled fan

Control a fan using a relay at a specific temperature threshold.

IntermediateFull instructions provided15,418
Temperature controlled fan

Things used in this project

Hardware components

Raspberry Pi 1 Model B+
Raspberry Pi 1 Model B+
×1
5V Relay module 220v
×1
DHT11 Temperature & Humidity Sensor (4 pins)
DHT11 Temperature & Humidity Sensor (4 pins)
Took the one i had in stock. A better choice would be a more accurate sensor that does not measure air moisture.
×1
Fractal Design Silent Series R3 80mm
×1
12v dc adapter
×1

Story

Read more

Schematics

Complete system diagram

Code

Read temperature sensor values

C/C++
This example is borrowed from uugear. For more information check the link in the credits section.
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#define MAXTIMINGS	85
#define DHTPIN		4
int dht11_dat[5] = { 0, 0, 0, 0, 0 };
float read_dht11_dat()
{
	uint8_t laststate	= HIGH;
	uint8_t counter		= 0;
	uint8_t j		= 0, i;
 	float result = -1;
	dht11_dat[0] = dht11_dat[1] = dht11_dat[2] = dht11_dat[3] = dht11_dat[4] = 0;

	/* pull pin down for 18 milliseconds */
	pinMode( DHTPIN, OUTPUT );
	digitalWrite( DHTPIN, LOW );
	delay( 18 );

	/* then pull it up for 40 microseconds */
	digitalWrite( DHTPIN, HIGH );
	delayMicroseconds( 40 );

	/* prepare to read the pin */
	pinMode( DHTPIN, INPUT );

	/* detect change and read data */
	for ( i = 0; i < MAXTIMINGS; i++ )
	{
		counter = 0;
		while ( digitalRead( DHTPIN ) == laststate )
		{
			counter++;
			delayMicroseconds( 1 );
			if ( counter == 255 )
			{
				break;
			}
		}
		laststate = digitalRead( DHTPIN );
 
		if ( counter == 255 )
			break;

		/* ignore first 3 transitions */
		if ( (i >= 4) && (i % 2 == 0) )
		{
			/* shove each bit into the storage bytes */
			dht11_dat[j / 8] <<= 1;
			if ( counter > 16 )
				dht11_dat[j / 8] |= 1;
			j++;
		}
	}

	/*
	 * check that we read 40 bits & verify checksum in the last byte.
	 */
	if ( (j >= 40) &&
	     (dht11_dat[4] == ( (dht11_dat[0] + dht11_dat[1] + dht11_dat[2] + dht11_dat[3]) & 0xFF) ) )
	{
		result = (1.0 * dht11_dat[2]) + ((float)dht11_dat[3]/10.0);
	}
	return result;
}

Relay control

C/C++
Check the temperature with the threshold value and activate/deactivate the relay.
The state-variable is used to prevent the relay from flickering on and off when the temperature is close to the threshold.
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define RELAYPIN	2
#define TEMPMAX		30

int state = 0;
void controlRelay(float avg_t){
	pinMode( RELAYPIN, OUTPUT );
	if(avg_t > TEMPMAX-state){
		digitalWrite( RELAYPIN, HIGH );
		state = 1;
	}
	else{
		digitalWrite( RELAYPIN, LOW );
		state = 0;
	}
}

Credits

Thanks to UUGear.

Comments