In this video lesson we connect the Arduino to a DHT11 temperature and humidity sensor. We show how to wire the device up, and then how to code the Arduino. The data is passed from the Arduino to python. We then create a live 3D thermometer model that updates as the temperature changes.
On the arduino side, this is the code which we use:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | #include "DHT.h" #define DHTPIN 2 #define DHTTYPE DHT11 float tempF; float tempC; float humidity; int setTime=500; int dt=1000; DHT TH(DHTPIN,DHTTYPE); void setup() { // put your setup code here, to run once: Serial.begin(115200); TH.begin(); delay(setTime); } void loop() { // put your main code here, to run repeatedly: tempC=TH.readTemperature(); tempF=TH.readTemperature(true); humidity=TH.readHumidity(); Serial.print(tempF); Serial.print(","); Serial.println(humidity); delay(dt); } |
Then on the python side, we use the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | import time import serial from vpython import * arduinoData=serial.Serial('com3',115200) time.sleep(.5) digValue=label(text='50',height=20,box=False,pos=vector(0,-2.5,2)) bulb=sphere(radius=1,color=color.red,pos=vector(0,-3,0)) cyl=cylinder(radius=.6,color=color.red,axis=vector(0,1,0),length=6,pos=vector(0,-3,0)) bulbGlass=sphere(radius=1.2,color=color.white,opacity=.25,pos=vector(0,-3,0)) cylGlass=cylinder(radius=.8,color=color.white,axis=vector(0,1,0),opacity=.25,length=6,pos=vector(0,-3,0)) for temp in range(0,115,10): tickPos=4.5/115*temp+1.5 tick=cylinder(radius=.7,color=color.black,length=.1,axis=vector(0,1,0),pos=vector(0,tickPos-3,0)) label=text(text=str(temp),color=color.white,pos=vector(-2,tickPos-3,0),height=.3) while True: while arduinoData.in_waiting==0: pass dataPacket=arduinoData.readline() dataPacket=str(dataPacket,'utf-8') dataPacket=dataPacket.strip('\r\n') dataPacket=dataPacket.split(',') temp=float(dataPacket[0]) hum=float(dataPacket[1]) len=(4.5/115)*temp+1.5 cyl.length=len digValue.text=str(temp) |