Open 4.1Temperature detection.py and click .
'''
* Filename : Temperature detection
* Thonny : Thonny 4.1.4
* Auther : http//www.keyestudio.com
'''
from machine import Pin
import machine
import onewire
import ds18x20
import time
# motor pins
INA = Pin(14, Pin.OUT) #INA corresponds to IN+
INB = Pin(15, Pin.OUT) #INB corresponds to IN-
# connect DS18B20 to IO22
ds18b20_pin = machine.Pin(22)
ds18b20_sensor = ds18x20.DS18X20(onewire.OneWire(ds18b20_pin))
roms = ds18b20_sensor.scan()
temp = 0
while True:
# delay 1s to wait for the stablization of DS18B20 sensor
time.sleep(1)
if roms:
rom = roms[0]
res = ds18b20_sensor.convert_temp()
time.sleep(0.1)
temp = ds18b20_sensor.read_temp(rom)
print(temp)
else:
print("No DS18B20 sensor found!")
if temp > 30:
INA.value(0)
INB.value(1)
else:
INA.value(0)
INB.value(0)
Conceive:
Initialization: set the pins of DS18B20 temperature sensor and 130 motor.
Loop:
DS18B20 sensor reads the temperature value and outputs it.
Determine whether the temperature value is greater than 30 (this threshold is adjustable according to needs).
temperature > 30: the fan rotates to cool down.
temperature <= 30: the fan does not work.