Raspberry pi – First experiments

Raspberry pi – First experiments

Finally got ‘round to documenting some of my first experiments on the raspberry pi.

i’ve done some temperature logging with an ds18b20 sensor, used a button and lit some leds.

Raspberry pi with ds18b20 sensor, button and some LEDs

Raspberry pi with ds18b20 sensor, button and some LEDs

some python code I used to blink the LED 5 times when i press the button:

[sourcecode language=”python”]
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# button is connected to gpio #23
GPIO.setup(23, GPIO.IN)
# set up GPIO output channel for the LED
GPIO.setup(18, GPIO.OUT)
# blinking function
def blink(pin):
GPIO.output(pin,GPIO.HIGH)
time.sleep(1)
GPIO.output(pin,GPIO.LOW)
time.sleep(1)
return
while True:
if ( GPIO.input(23) == False ):
# blink LED 5 times
for i in range(0,5):
blink(18)
[/sourcecode]

Reading the temperature sensor
[sourcecode]
import os
import glob
import time

os.system(‘modprobe w1-gpio’)
os.system(‘modprobe w1-therm’)

base_dir = ‘/sys/bus/w1/devices/’
device_folder = glob.glob(base_dir + ’10*’)[0]
print device_folder
device_file = device_folder + ‘/w1_slave’

def read_temp_raw():
f = open(device_file, ‘r’)
lines = f.readlines()
f.close()
return lines

def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != ‘YES’:
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find(‘t=’)
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c

while True:
print read_temp()
time.sleep(1)
[/sourcecode]

The Two Combined: When you press the button, the led blinks five times and each time it probe the sensor for the current temperature:
[sourcecode]
import RPi.GPIO as GPIO
import os
import glob
import time

# blinking function
GPIO.setmode(GPIO.BCM)
GPIO.setup(23, GPIO.IN)
# set up GPIO output channel
GPIO.setup(18, GPIO.OUT)
os.system(‘modprobe w1-gpio’)
os.system(‘modprobe w1-therm’)

base_dir = ‘/sys/bus/w1/devices/’
device_folder = glob.glob(base_dir + ’10*’)[0]
print device_folder
device_file = device_folder + ‘/w1_slave’

def read_temp_raw():
f = open(device_file, ‘r’)
lines = f.readlines()
f.close()
return lines

def read_temp():
lines = read_temp_raw()
while lines[0].strip()[-3:] != ‘YES’:
time.sleep(0.2)
lines = read_temp_raw()
equals_pos = lines[1].find(‘t=’)
if equals_pos != -1:
temp_string = lines[1][equals_pos+2:]
temp_c = float(temp_string) / 1000.0
temp_f = temp_c * 9.0 / 5.0 + 32.0
return temp_c

def blink(pin):
GPIO.output(pin,GPIO.HIGH)
time.sleep(1)
GPIO.output(pin,GPIO.LOW)
time.sleep(1)
return

while True:
if ( GPIO.input(23) == False ):
# blink GPIO17 50 times
for i in range(0,5):
blink(18)
print read_temp()
time.sleep(1)

[/sourcecode]

About the Author

Bert administrator

Comments Are Closed!!!
%d bloggers liken dit: