ID photo of Ciro Santilli taken in 2013 right eyeCiro Santilli OurBigBook logoOurBigBook.com  Sponsor 中国独裁统治 China Dictatorship 新疆改造中心、六四事件、法轮功、郝海东、709大抓捕、2015巴拿马文件 邓家贵、低端人口、西藏骚乱
This example attempts to keep temperature to a fixed point by turning on a fan when a thermistor gets too hot.
You can test it easily if you are not in a place that is too hot by holding the thermistor with your finger to turn on the fan.
You can use a simple LED to represent the fan if you don't have one handy.
In Ciro's ASCII art circuit diagram notation:
            +----------FAN-----------+
            |                        |
            |                        |
RPI_PICO_W__gnd__gpio26Adc__3.3V@36__gpio2
            |    |          |
            |    |          |
            |    |          |
            |    +-THERMISTOR
            |    |
            |    |
            R_10-+
rpi-pico-w/upython/thermistor_fan_control.py
from math import log

from machine import ADC, Pin, PWM, UART
from time import sleep

# Thermistor parameter found on its datasheet.
T_R25 = 10000
T_BETA = 3950
# Resistance of the other fixed resistor of the thermistor voltage divider.
# We select it to match the thermistor at 25%.
T_R_OTHER = 10000
T0 = 273.15
TARGET_C = 29

U16MAX = 2 ** 16 - 1

led = Pin('LED', Pin.OUT)
adc = ADC(Pin(26))
uart0 = UART(0, baudrate=9600, tx=Pin(0), rx=Pin(1))
pwm = PWM(Pin(2))
pwm.freq(1000)
while True:
    v_other_frac = max(adc.read_u16(),1)/(U16MAX + 1)
    # Thermistor resistance
    # R_other = V_other/I = V_other / (5v / (R_other + R_thermistor)) =
    #        V_other (R_other + R_thermistor)) / 5v =>
    # R_thermistor = (R_other * 5v / V_other) - R_other = R_other * (5v/V_other - 1)
    tr = T_R_OTHER  * (1/v_other_frac - 1)
    # Temperature.
    # https://en.wikipedia.org/wiki/Thermistor#B_or_%CE%B2_parameter_equation
    temp_c = 1/(1/(T0 + 25) + (1/T_BETA)*log(tr/T_R25)) - T0
    sleep(0.2)
    led.toggle()
    duty = min(U16MAX, int(U16MAX * max(temp_c - TARGET_C, 0)/5))
    s = 'temp_c={} tr={} duty={}'.format(temp_c, tr, duty)
    print(s)
    uart0.write(s + '\r\n')
    pwm.duty_u16(duty)

Ancestors (16)

  1. Raspberry Pi Pico W MicroPython example
  2. Program Raspberry Pi Pico W with MicroPython
  3. Program Raspberry Pi Pico W with X
  4. Raspberry Pi Pico W
  5. Raspberry Pi Pico variant
  6. Raspberry Pi Pico
  7. Raspberry Pi
  8. Raspberry Pi Foundation project
  9. Raspberry Pi Foundation
  10. Computer manufacturer
  11. Computer hardware
  12. Computer
  13. Information technology
  14. Area of technology
  15. Technology
  16. Home