IoT Tutorial-11 Solutions
IoT Tutorial-11 Solutions
Raspberry Pi. It covers resistive sensors, light sensors, voltage measurement, CPU temperature
monitoring, and distance measurement. Each section includes theoretical insights, wiring
temperature and movement. Examples include thermistors, potentiometers, and strain gauges.
Below is an example of using a thermistor with a voltage divider circuit. The output voltage is
import spidev
import time
spi = spidev.SpiDev()
spi.open(0, 0)
def read_adc(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
value = ((adc[1] & 3) << 8) + adc[2]
return value
try:
while True:
value = read_adc(0) # Thermistor on Channel 0
print(f"Thermistor Value: {value}")
time.sleep(1)
except KeyboardInterrupt:
spi.close()
spi = spidev.SpiDev()
spi.open(0, 0)
def read_light(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
value = ((adc[1] & 3) << 8) + adc[2]
return value
try:
while True:
light_value = read_light(0)
print(f"Light Intensity: {light_value}")
time.sleep(1)
except KeyboardInterrupt:
spi.close()
import spidev
spi = spidev.SpiDev()
spi.open(0, 0)
def read_voltage(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
value = ((adc[1] & 3) << 8) + adc[2]
voltage = (value * 3.3) / 1023 # Convert to voltage
return voltage
try:
while True:
voltage = read_voltage(1)
print(f"Measured Voltage: {voltage:.2f} V")
except KeyboardInterrupt:
spi.close()
def get_cpu_temp():
with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
temp = int(f.read()) / 1000 # Convert millidegrees to Celsius
return temp
try:
while True:
temp = get_cpu_temp()
print(f"CPU Temperature: {temp:.2f} °C")
time.sleep(1)
except KeyboardInterrupt:
pass
takes to bounce back. The following code demonstrates how to measure the distance using GPIO
pins.
GPIO.setmode(GPIO.BCM)
TRIG = 23
ECHO = 24
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
def measure_distance():
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
start = time.time()
while GPIO.input(ECHO) == 1:
end = time.time()
try:
while True:
dist = measure_distance()
print(f"Distance: {dist:.2f} cm")
time.sleep(1)
except KeyboardInterrupt:
GPIO.cleanup()