├── README.md └── code ├── AlaModeShield └── AlaModeShield.ino ├── ArduinoHello └── ArduinoHello.ino ├── ArduinoI2C └── ArduinoI2C.ino ├── ArduinoSerial └── ArduinoSerial.ino ├── adc_accelerometer.py ├── adc_scaled.py ├── adc_test.py ├── adc_tmp36.py ├── ardu_adc.py ├── ardu_flash.py ├── ardu_flash_micro.py ├── ardu_flash_ser.py ├── ardu_gui_slider.py ├── ardu_gui_switch.py ├── ardu_pi_i2c.py ├── ardu_pi_serial.py ├── ardu_pwm.py ├── ardu_servo.py ├── ardu_switch.py ├── bottle_test.py ├── buzzer.py ├── charlieplexing.py ├── gps_test.py ├── gui_sensor_reading.py ├── gui_slider.py ├── gui_sliderRGB.py ├── gui_switch.py ├── interrupts.py ├── keypad.py ├── keys_pygame.py ├── keys_sys.py ├── led_blink.py ├── led_brightness.py ├── motor_control.py ├── mouse_pygame.py ├── pi_lite_message.py ├── pi_lite_rain.py ├── pir.py ├── pot_step.py ├── ranger.py ├── rotary_encoder.py ├── rotary_encoder_test.py ├── rover.py ├── servo.py ├── servo_module.py ├── speed.py ├── stepper.py ├── stepper_rrb.py ├── switch.py ├── switch_3_pos.py ├── switch_on_off.py ├── switch_on_off_no_bounce.py ├── temp_DS18B20.py ├── temp_log.py ├── tilt.py ├── web_control.py └── web_control_test.py /README.md: -------------------------------------------------------------------------------- 1 | raspberrypi_cookbook 2 | ==================== 3 | 4 | The source code from the book 'The Raspberry Pi Cookbook' by Simon Monk. -------------------------------------------------------------------------------- /code/AlaModeShield/AlaModeShield.ino: -------------------------------------------------------------------------------- 1 | 2 | #include 3 | 4 | // pins for Freetronics LCD Shield 5 | 6 | LiquidCrystal lcd(8, 9, 4, 5, 6, 7); 7 | 8 | void setup() 9 | { 10 | lcd.begin(16, 2); 11 | lcd.print("Counting!"); 12 | } 13 | 14 | void loop() 15 | { 16 | lcd.setCursor(0, 1); 17 | lcd.print(millis() / s1000); 18 | } 19 | 20 | -------------------------------------------------------------------------------- /code/ArduinoHello/ArduinoHello.ino: -------------------------------------------------------------------------------- 1 | // ArduinoHello 2 | 3 | void setup() 4 | { 5 | Serial.begin(9600); 6 | } 7 | 8 | void loop() 9 | { 10 | Serial.println("Hello Raspberry Pi"); 11 | delay(1000); 12 | } 13 | -------------------------------------------------------------------------------- /code/ArduinoI2C/ArduinoI2C.ino: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | int SLAVE_ADDRESS = 0x04; 4 | int ledPin = 13; 5 | int analogPin = A0; 6 | 7 | boolean ledOn = false; 8 | 9 | void setup() 10 | { 11 | pinMode(ledPin, OUTPUT); 12 | Wire.begin(SLAVE_ADDRESS); 13 | Wire.onReceive(processMessage); 14 | Wire.onRequest(sendAnalogReading); 15 | Serial.begin(9600); 16 | } 17 | 18 | void loop() 19 | { 20 | } 21 | 22 | void processMessage(int n) 23 | { 24 | Serial.println("In processMessage"); 25 | char ch = Wire.read(); 26 | if (ch == 'l') 27 | { 28 | toggleLED(); 29 | } 30 | } 31 | 32 | void toggleLED() 33 | { 34 | ledOn = ! ledOn; 35 | digitalWrite(ledPin, ledOn); 36 | } 37 | 38 | void sendAnalogReading() 39 | { 40 | Serial.println("In sendAnalogReading"); 41 | int reading = analogRead(analogPin); 42 | Wire.write(reading >> 2); 43 | } 44 | -------------------------------------------------------------------------------- /code/ArduinoSerial/ArduinoSerial.ino: -------------------------------------------------------------------------------- 1 | #include "SoftwareSerial.h" 2 | 3 | int ledPin = 13; 4 | int analogPin = A0; 5 | 6 | SoftwareSerial ser(8, 9); // RX, TX 7 | 8 | boolean ledOn = false; 9 | 10 | void setup() 11 | { 12 | ser.begin(9600); 13 | pinMode(ledPin, OUTPUT); 14 | } 15 | 16 | void loop() 17 | { 18 | if (ser.available()) 19 | { 20 | char ch = ser.read(); 21 | if (ch == 'l') 22 | { 23 | toggleLED(); 24 | } 25 | if (ch == 'r') 26 | { 27 | sendAnalogReading(); 28 | } 29 | } 30 | } 31 | 32 | void toggleLED() 33 | { 34 | ledOn = ! ledOn; 35 | digitalWrite(ledPin, ledOn); 36 | } 37 | 38 | void sendAnalogReading() 39 | { 40 | int reading = analogRead(analogPin); 41 | ser.println(reading); 42 | } 43 | -------------------------------------------------------------------------------- /code/adc_accelerometer.py: -------------------------------------------------------------------------------- 1 | import spidev, time 2 | 3 | spi = spidev.SpiDev() 4 | spi.open(0,0) 5 | 6 | def analog_read(channel): 7 | r = spi.xfer2([1, (8 + channel) << 4, 0]) 8 | adc_out = ((r[1]&3) << 8) + r[2] 9 | return adc_out 10 | 11 | while True: 12 | x = analog_read(0) 13 | y = analog_read(1) 14 | z = analog_read(2) 15 | print("X=%d\tY=%d\tZ=%d" % (x, y, z)) 16 | time.sleep(1) -------------------------------------------------------------------------------- /code/adc_scaled.py: -------------------------------------------------------------------------------- 1 | import spidev 2 | 3 | R1 = 10000.0 4 | R2 = 3300.0 5 | 6 | spi = spidev.SpiDev() 7 | spi.open(0,0) 8 | 9 | def analog_read(channel): 10 | r = spi.xfer2([1, (8 + channel) << 4, 0]) 11 | adc_out = ((r[1]&3) << 8) + r[2] 12 | return adc_out 13 | 14 | reading = analog_read(0) 15 | voltage_adc = reading * 3.3 / 1024 16 | voltage_actual = voltage_adc / (R2 / (R1 + R2)) 17 | print("Battery Voltage=" + str(voltage_actual)) -------------------------------------------------------------------------------- /code/adc_test.py: -------------------------------------------------------------------------------- 1 | import spidev, time 2 | 3 | spi = spidev.SpiDev() 4 | spi.open(0,0) 5 | 6 | def analog_read(channel): 7 | r = spi.xfer2([1, (8 + channel) << 4, 0]) 8 | adc_out = ((r[1]&3) << 8) + r[2] 9 | return adc_out 10 | 11 | while True: 12 | reading = analog_read(0) 13 | voltage = reading * 3.3 / 1024 14 | print("Reading=%d\tVoltage=%f" % (reading, voltage)) 15 | time.sleep(1) -------------------------------------------------------------------------------- /code/adc_tmp36.py: -------------------------------------------------------------------------------- 1 | import spidev, time 2 | 3 | spi = spidev.SpiDev() 4 | spi.open(0,0) 5 | 6 | def analog_read(channel): 7 | r = spi.xfer2([1, (8 + channel) << 4, 0]) 8 | adc_out = ((r[1]&3) << 8) + r[2] 9 | return adc_out 10 | 11 | while True: 12 | reading = analog_read(0) 13 | voltage = reading * 3.3 / 1024 14 | temp_c = voltage * 100 - 50 15 | temp_f = temp_c * 9.0 / 5.0 + 32 16 | print("Temp C=%f\t\tTemp f=%f" % (temp_c, temp_f)) 17 | time.sleep(1) -------------------------------------------------------------------------------- /code/ardu_adc.py: -------------------------------------------------------------------------------- 1 | import pyfirmata 2 | import time 3 | 4 | board = pyfirmata.Arduino('/dev/ttyACM0') 5 | analog_pin = board.get_pin('a:0:i') 6 | it = pyfirmata.util.Iterator(board) 7 | it.start() 8 | analog_pin.enable_reporting() 9 | 10 | while True: 11 | reading = analog_pin.read() 12 | if reading != None: 13 | voltage = reading * 5.0 14 | print("Reading=%f\tVoltage=%f" % (reading, voltage)) 15 | time.sleep(1) -------------------------------------------------------------------------------- /code/ardu_flash.py: -------------------------------------------------------------------------------- 1 | import pyfirmata 2 | import time 3 | 4 | board = pyfirmata.Arduino('/dev/ttyACM0') 5 | led_pin = board.get_pin('d:10:o') 6 | 7 | while True: 8 | led_pin.write(1) 9 | time.sleep(0.5) 10 | led_pin.write(0) 11 | time.sleep(0.5) -------------------------------------------------------------------------------- /code/ardu_flash_micro.py: -------------------------------------------------------------------------------- 1 | import pyfirmata 2 | import time 3 | 4 | board = pyfirmata.Arduino('/dev/ttyACM0') 5 | led_pin = board.get_pin('d:10:o') 6 | 7 | while True: 8 | led_pin.write(1) 9 | time.sleep(0.5) 10 | led_pin.write(0) 11 | time.sleep(0.5) 12 | -------------------------------------------------------------------------------- /code/ardu_flash_ser.py: -------------------------------------------------------------------------------- 1 | import pyfirmata 2 | import time 3 | 4 | board = pyfirmata.Arduino('/dev/ttyAMA0') 5 | led_pin = board.get_pin('d:13:o') 6 | 7 | while True: 8 | led_pin.write(1) 9 | time.sleep(0.5) 10 | led_pin.write(0) 11 | time.sleep(0.5) -------------------------------------------------------------------------------- /code/ardu_gui_slider.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import time 3 | import pyfirmata 4 | 5 | board = pyfirmata.Arduino('/dev/ttyACM0') 6 | led_pin = board.get_pin('d:10:p') 7 | 8 | class App: 9 | 10 | def __init__(self, master): 11 | frame = Frame(master) 12 | frame.pack() 13 | scale = Scale(frame, from_=0, to=100, 14 | orient=HORIZONTAL, command=self.update) 15 | scale.grid(row=0) 16 | 17 | 18 | def update(self, duty): 19 | led_pin.write(float(duty) / 100.0) 20 | 21 | root = Tk() 22 | root.wm_title('PWM Power Control') 23 | app = App(root) 24 | root.geometry("200x50+0+0") 25 | root.mainloop() 26 | 27 | -------------------------------------------------------------------------------- /code/ardu_gui_switch.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import pyfirmata 3 | import time 4 | 5 | board = pyfirmata.Arduino('/dev/ttyACM0') 6 | led_pin = board.get_pin('d:10:o') 7 | 8 | class App: 9 | 10 | def __init__(self, master): 11 | frame = Frame(master) 12 | frame.pack() 13 | self.check_var = BooleanVar() 14 | check = Checkbutton(frame, text='Pin 10', 15 | command=self.update, 16 | variable=self.check_var, onvalue=True, offvalue=False) 17 | check.grid(row=1) 18 | 19 | def update(self): 20 | led_pin.write(self.check_var.get()) 21 | 22 | root = Tk() 23 | root.wm_title('On / Off Switch') 24 | app = App(root) 25 | root.geometry("200x50+0+0") 26 | root.mainloop() 27 | -------------------------------------------------------------------------------- /code/ardu_pi_i2c.py: -------------------------------------------------------------------------------- 1 | import smbus 2 | import time 3 | 4 | # for RPI version 1, use "bus = smbus.SMBus(0)" 5 | bus = smbus.SMBus(1) 6 | 7 | # This must match in the Arduino Sketch 8 | SLAVE_ADDRESS = 0x04 9 | 10 | def request_reading(): 11 | reading = int(bus.read_byte(SLAVE_ADDRESS)) 12 | print(reading) 13 | 14 | 15 | while True: 16 | command = raw_input("Enter command: l - toggle LED, r - read A0 ") 17 | if command == 'l' : 18 | bus.write_byte(SLAVE_ADDRESS, ord('l')) 19 | elif command == 'r' : 20 | request_reading() 21 | -------------------------------------------------------------------------------- /code/ardu_pi_serial.py: -------------------------------------------------------------------------------- 1 | import serial 2 | 3 | ser = serial.Serial('/dev/ttyAMA0', 9600) 4 | 5 | while True: 6 | command = raw_input("Enter command: l - toggle LED, r - read A0 ") 7 | if command == 'l' : 8 | ser.write('l') 9 | elif command == 'r' : 10 | ser.write('r') 11 | print(ser.readline()) -------------------------------------------------------------------------------- /code/ardu_pwm.py: -------------------------------------------------------------------------------- 1 | import pyfirmata 2 | 3 | board = pyfirmata.Arduino('/dev/ttyACM0') 4 | led_pin = board.get_pin('d:10:p') 5 | 6 | while True: 7 | duty_s = raw_input("Enter Brightness (0 to 100):") 8 | duty = int(duty_s) 9 | led_pin.write(duty / 100.0) -------------------------------------------------------------------------------- /code/ardu_servo.py: -------------------------------------------------------------------------------- 1 | import pyfirmata 2 | 3 | board = pyfirmata.Arduino('/dev/ttyACM0') 4 | servo_pin = board.get_pin('d:11:s') 5 | 6 | while True: 7 | angle_s = raw_input("Enter Angle (0 to 180):") 8 | angle = int(angle_s) 9 | servo_pin.write(angle) -------------------------------------------------------------------------------- /code/ardu_switch.py: -------------------------------------------------------------------------------- 1 | import pyfirmata 2 | import time 3 | import sys 4 | 5 | board = pyfirmata.Arduino('/dev/ttyACM0') 6 | switch_pin = board.get_pin('d:4:i') 7 | it = pyfirmata.util.Iterator(board) 8 | it.start() 9 | switch_pin.enable_reporting() 10 | 11 | while True: 12 | input_state = switch_pin.read() 13 | if input_state == False: 14 | print('Button Pressed') 15 | time.sleep(0.2) 16 | 17 | -------------------------------------------------------------------------------- /code/bottle_test.py: -------------------------------------------------------------------------------- 1 | from bottle import route, run, template 2 | from datetime import datetime 3 | 4 | @route('/') 5 | def index(name='time'): 6 | dt = datetime.now() 7 | time = "{:%Y-%m-%d %H:%M:%S}".format(dt) 8 | return template('Pi thinks the date/time is: {{t}}', t=time) 9 | 10 | run(host='192.168.1.16', port=80) -------------------------------------------------------------------------------- /code/buzzer.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | buzzer_pin = 18 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | 8 | def buzz(pitch, duration): 9 | period = 1.0 / pitch 10 | delay = period / 2 11 | cycles = int(duration * pitch) 12 | for i in range(cycles): 13 | GPIO.output(buzzer_pin, True) 14 | time.sleep(delay) 15 | GPIO.output(buzzer_pin, False) 16 | time.sleep(delay) 17 | 18 | 19 | while True: 20 | pitch_s = raw_input("Enter Pitch (200 to 2000): ") 21 | pitch = float(pitch_s) 22 | duration_s = raw_input("Enter Duration (seconds): ") 23 | duration = float(duration_s) 24 | buzz(pitch, duration) -------------------------------------------------------------------------------- /code/charlieplexing.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | 3 | pins = [18, 23, 24] 4 | 5 | pin_led_states = [ 6 | [1, 0, -1], # A 7 | [0, 1, -1], # B 8 | [-1, 1, 0], # C 9 | [-1, 0, 1], # D 10 | [1, -1, 0], # E 11 | [0, -1, 1] # F 12 | ] 13 | 14 | GPIO.setmode(GPIO.BCM) 15 | 16 | def set_pin(pin_index, pin_state): 17 | if pin_state == -1: 18 | GPIO.setup(pins[pin_index], GPIO.IN) 19 | else: 20 | GPIO.setup(pins[pin_index], GPIO.OUT) 21 | GPIO.output(pins[pin_index], pin_state) 22 | 23 | def light_led(led_number): 24 | for pin_index, pin_state in enumerate(pin_led_states[led_number]): 25 | set_pin(pin_index, pin_state) 26 | 27 | set_pin(0, -1) 28 | set_pin(1, -1) 29 | set_pin(2, -1) 30 | 31 | while True: 32 | x = int(raw_input("Pin (0 to 5):")) 33 | light_led(x) 34 | -------------------------------------------------------------------------------- /code/gps_test.py: -------------------------------------------------------------------------------- 1 | from gps import * 2 | session = gps() 3 | session.stream(WATCH_ENABLE|WATCH_NEWSTYLE) 4 | 5 | while True: 6 | report = session.next() 7 | if report.keys()[0] == 'epx' : 8 | lat = float(report['lat']) 9 | lon = float(report['lon']) 10 | print("lat=%f\tlon=%f\ttime=%s" % (lat, lon, report['time'])) 11 | time.sleep(0.5) -------------------------------------------------------------------------------- /code/gui_sensor_reading.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | trigger_pin = 18 6 | echo_pin = 23 7 | 8 | GPIO.setmode(GPIO.BCM) 9 | GPIO.setup(trigger_pin, GPIO.OUT) 10 | GPIO.setup(echo_pin, GPIO.IN) 11 | 12 | def send_trigger_pulse(): 13 | GPIO.output(trigger_pin, True) 14 | time.sleep(0.0001) 15 | GPIO.output(trigger_pin, False) 16 | 17 | def wait_for_echo(value, timeout): 18 | count = timeout 19 | while GPIO.input(echo_pin) != value and count > 0: 20 | count = count - 1 21 | 22 | def get_distance(): 23 | send_trigger_pulse() 24 | wait_for_echo(True, 10000) 25 | start = time.time() 26 | wait_for_echo(False, 10000) 27 | finish = time.time() 28 | pulse_len = finish - start 29 | distance_cm = pulse_len / 0.000058 30 | distance_in = distance_cm / 2.5 31 | return (distance_cm, distance_in) 32 | 33 | class App: 34 | 35 | def __init__(self, master): 36 | self.master = master 37 | frame = Frame(master) 38 | frame.pack() 39 | label = Label(frame, text='Distance (inches)', font=("Helvetica", 32)) 40 | label.grid(row=0) 41 | self.reading_label = Label(frame, text='12.34', font=("Helvetica", 110)) 42 | self.reading_label.grid(row=1) 43 | self.update_reading() 44 | 45 | def update_reading(self): 46 | cm, inch = get_distance() 47 | reading_str = "{:.2f}".format(inch) 48 | self.reading_label.configure(text=reading_str) 49 | self.master.after(500, self.update_reading) 50 | 51 | 52 | root = Tk() 53 | root.wm_title('Range Finder') 54 | app = App(root) 55 | root.geometry("400x300+0+0") 56 | root.mainloop() 57 | 58 | -------------------------------------------------------------------------------- /code/gui_slider.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | pwm = GPIO.PWM(18, 500) 8 | pwm.start(100) 9 | 10 | class App: 11 | 12 | def __init__(self, master): 13 | frame = Frame(master) 14 | frame.pack() 15 | scale = Scale(frame, from_=0, to=100, 16 | orient=HORIZONTAL, command=self.update) 17 | scale.grid(row=0) 18 | 19 | 20 | def update(self, duty): 21 | pwm.ChangeDutyCycle(float(duty)) 22 | 23 | root = Tk() 24 | root.wm_title('PWM Power Control') 25 | app = App(root) 26 | root.geometry("200x50+0+0") 27 | root.mainloop() 28 | 29 | -------------------------------------------------------------------------------- /code/gui_sliderRGB.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | GPIO.setup(23, GPIO.OUT) 8 | GPIO.setup(24, GPIO.OUT) 9 | 10 | pwmRed = GPIO.PWM(18, 500) 11 | pwmRed.start(100) 12 | 13 | pwmGreen = GPIO.PWM(23, 500) 14 | pwmGreen.start(100) 15 | 16 | pwmBlue = GPIO.PWM(24, 500) 17 | pwmBlue.start(100) 18 | 19 | class App: 20 | 21 | def __init__(self, master): 22 | frame = Frame(master) 23 | frame.pack() 24 | Label(frame, text='Red').grid(row=0, column=0) 25 | Label(frame, text='Green').grid(row=1, column=0) 26 | Label(frame, text='Blue').grid(row=2, column=0) 27 | scaleRed = Scale(frame, from_=0, to=100, 28 | orient=HORIZONTAL, command=self.updateRed) 29 | scaleRed.grid(row=0, column=1) 30 | scaleGreen = Scale(frame, from_=0, to=100, 31 | orient=HORIZONTAL, command=self.updateGreen) 32 | scaleGreen.grid(row=1, column=1) 33 | scaleBlue = Scale(frame, from_=0, to=100, 34 | orient=HORIZONTAL, command=self.updateBlue) 35 | scaleBlue.grid(row=2, column=1) 36 | 37 | 38 | def updateRed(self, duty): 39 | pwmRed.ChangeDutyCycle(float(duty)) 40 | 41 | def updateGreen(self, duty): 42 | pwmGreen.ChangeDutyCycle(float(duty)) 43 | 44 | def updateBlue(self, duty): 45 | pwmBlue.ChangeDutyCycle(float(duty)) 46 | 47 | root = Tk() 48 | root.wm_title('RGB LED Control') 49 | app = App(root) 50 | root.geometry("200x150+0+0") 51 | root.mainloop() -------------------------------------------------------------------------------- /code/gui_switch.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | 8 | class App: 9 | 10 | def __init__(self, master): 11 | frame = Frame(master) 12 | frame.pack() 13 | self.check_var = BooleanVar() 14 | check = Checkbutton(frame, text='Pin 18', 15 | command=self.update, 16 | variable=self.check_var, onvalue=True, offvalue=False) 17 | check.grid(row=1) 18 | 19 | def update(self): 20 | GPIO.output(18, self.check_var.get()) 21 | 22 | root = Tk() 23 | root.wm_title('On / Off Switch') 24 | app = App(root) 25 | root.geometry("200x50+0+0") 26 | root.mainloop() 27 | -------------------------------------------------------------------------------- /code/interrupts.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | def my_callback(channel): 7 | print('You pressed the button') 8 | 9 | GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.add_event_detect(18, GPIO.FALLING, callback=my_callback) 11 | 12 | i = 0 13 | while True: 14 | i = i + 1 15 | print(i) 16 | time.sleep(1) 17 | -------------------------------------------------------------------------------- /code/keypad.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | rows = [17, 25, 24, 23] 7 | cols = [27, 18, 22] 8 | keys = [ 9 | ['1', '2', '3'], 10 | ['4', '5', '6'], 11 | ['7', '8', '9'], 12 | ['*', '0', '#']] 13 | 14 | for row_pin in rows: 15 | GPIO.setup(row_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 16 | 17 | for col_pin in cols: 18 | GPIO.setup(col_pin, GPIO.OUT) 19 | 20 | def get_key(): 21 | key = 0 22 | for col_num, col_pin in enumerate(cols): 23 | GPIO.output(col_pin, 1) 24 | for row_num, row_pin in enumerate(rows): 25 | if GPIO.input(row_pin): 26 | key = keys[row_num][col_num] 27 | GPIO.output(col_pin, 0) 28 | return key 29 | 30 | while True: 31 | key = get_key() 32 | if key : 33 | print(key) 34 | time.sleep(0.3) 35 | -------------------------------------------------------------------------------- /code/keys_pygame.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | from pygame.locals import * 4 | 5 | pygame.init() 6 | screen = pygame.display.set_mode((640, 480)) 7 | pygame.mouse.set_visible(0) 8 | 9 | while True: 10 | for event in pygame.event.get(): 11 | if event.type == QUIT: 12 | sys.exit() 13 | if event.type == KEYDOWN: 14 | print("Code: " + str(event.key) + " Char: " + chr(event.key)) -------------------------------------------------------------------------------- /code/keys_sys.py: -------------------------------------------------------------------------------- 1 | import sys, tty, termios 2 | 3 | def read_ch(): 4 | fd = sys.stdin.fileno() 5 | old_settings = termios.tcgetattr(fd) 6 | try: 7 | tty.setraw(sys.stdin.fileno()) 8 | ch = sys.stdin.read(1) 9 | finally: 10 | termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 11 | return ch 12 | 13 | while True: 14 | ch = read_ch() 15 | if ch == 'x': 16 | break 17 | print("key is: " + ch) 18 | -------------------------------------------------------------------------------- /code/led_blink.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | GPIO.setup(18, GPIO.OUT) 6 | 7 | while (True): 8 | GPIO.output(18, True) 9 | time.sleep(0.5) 10 | GPIO.output(18, False) 11 | time.sleep(0.5) 12 | -------------------------------------------------------------------------------- /code/led_brightness.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | 3 | led_pin = 18 4 | GPIO.setmode(GPIO.BCM) 5 | GPIO.setup(led_pin, GPIO.OUT) 6 | 7 | pwm_led = GPIO.PWM(led_pin, 500) 8 | pwm_led.start(100) 9 | 10 | while True: 11 | duty_s = raw_input("Enter Brightness (0 to 100):") 12 | duty = int(duty_s) 13 | pwm_led.ChangeDutyCycle(duty) 14 | 15 | -------------------------------------------------------------------------------- /code/motor_control.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | enable_pin = 18 5 | in1_pin = 23 6 | in2_pin =24 7 | 8 | GPIO.setmode(GPIO.BCM) 9 | GPIO.setup(enable_pin, GPIO.OUT) 10 | GPIO.setup(in1_pin, GPIO.OUT) 11 | GPIO.setup(in2_pin, GPIO.OUT) 12 | 13 | pwm = GPIO.PWM(enable_pin, 500) 14 | pwm.start(0) 15 | 16 | def clockwise(): 17 | GPIO.output(in1_pin, True) 18 | GPIO.output(in2_pin, False) 19 | 20 | def counter_clockwise(): 21 | GPIO.output(in1_pin, False) 22 | GPIO.output(in2_pin, True) 23 | 24 | while True: 25 | cmd = raw_input("Command, f/r 0..9, E.g. f5 :") 26 | direction = cmd[0] 27 | if direction == "f": 28 | clockwise() 29 | else: 30 | counter_clockwise() 31 | speed = int(cmd[1]) * 10 32 | pwm.ChangeDutyCycle(speed) 33 | 34 | -------------------------------------------------------------------------------- /code/mouse_pygame.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | from pygame.locals import * 4 | 5 | pygame.init() 6 | screen = pygame.display.set_mode((640, 480)) 7 | pygame.mouse.set_visible(0) 8 | 9 | while True: 10 | for event in pygame.event.get(): 11 | if event.type == QUIT: 12 | sys.exit() 13 | if event.type == MOUSEMOTION: 14 | print("Mouse: (%d, %d)" % event.pos) -------------------------------------------------------------------------------- /code/pi_lite_message.py: -------------------------------------------------------------------------------- 1 | import serial 2 | 3 | ser = serial.Serial('/dev/ttyAMA0', 9600) 4 | 5 | while True: 6 | message = raw_input("Enter message: ") 7 | ser.write(message) 8 | -------------------------------------------------------------------------------- /code/pi_lite_rain.py: -------------------------------------------------------------------------------- 1 | import serial 2 | import random 3 | 4 | ser = serial.Serial('/dev/ttyAMA0', 9600) 5 | 6 | while True: 7 | col = random.randint(1, 14) 8 | row = random.randint(1, 9) 9 | ser.write("$$$P%d,%d,TOGGLE\r" % (col, row)) 10 | 11 | -------------------------------------------------------------------------------- /code/pir.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | GPIO.setmode(GPIO.BCM) 4 | GPIO.setup(18, GPIO.IN) 5 | 6 | while True: 7 | input_state = GPIO.input(18) 8 | if input_state == True: 9 | print('Motion Detected') 10 | time.sleep(1) 11 | -------------------------------------------------------------------------------- /code/pot_step.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | a_pin = 18 7 | b_pin = 23 8 | 9 | def discharge(): 10 | GPIO.setup(a_pin, GPIO.IN) 11 | GPIO.setup(b_pin, GPIO.OUT) 12 | GPIO.output(b_pin, False) 13 | time.sleep(0.005) 14 | 15 | def charge_time(): 16 | GPIO.setup(b_pin, GPIO.IN) 17 | GPIO.setup(a_pin, GPIO.OUT) 18 | count = 0 19 | GPIO.output(a_pin, True) 20 | while not GPIO.input(b_pin): 21 | count = count + 1 22 | return count 23 | 24 | def analog_read(): 25 | discharge() 26 | return charge_time() 27 | 28 | while True: 29 | print(analog_read()) 30 | time.sleep(1) 31 | -------------------------------------------------------------------------------- /code/ranger.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | trigger_pin = 18 5 | echo_pin = 23 6 | 7 | GPIO.setmode(GPIO.BCM) 8 | GPIO.setup(trigger_pin, GPIO.OUT) 9 | GPIO.setup(echo_pin, GPIO.IN) 10 | 11 | def send_trigger_pulse(): 12 | GPIO.output(trigger_pin, True) 13 | time.sleep(0.0001) 14 | GPIO.output(trigger_pin, False) 15 | 16 | def wait_for_echo(value, timeout): 17 | count = timeout 18 | while GPIO.input(echo_pin) != value and count > 0: 19 | count = count - 1 20 | 21 | def get_distance(): 22 | send_trigger_pulse() 23 | wait_for_echo(True, 10000) 24 | start = time.time() 25 | wait_for_echo(False, 10000) 26 | finish = time.time() 27 | pulse_len = finish - start 28 | distance_cm = pulse_len / 0.000058 29 | distance_in = distance_cm / 2.5 30 | return (distance_cm, distance_in) 31 | 32 | 33 | while True: 34 | print("cm=%f\tinches=%f" % get_distance()) 35 | time.sleep(1) -------------------------------------------------------------------------------- /code/rotary_encoder.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | input_A = 18 7 | input_B = 23 8 | 9 | GPIO.setup(input_A, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(input_B, GPIO.IN, pull_up_down=GPIO.PUD_UP) 11 | 12 | 13 | old_a = True 14 | old_b = True 15 | 16 | def get_encoder_turn(): 17 | # return -1, 0, or +1 18 | global old_a, old_b 19 | result = 0 20 | new_a = GPIO.input(input_A) 21 | new_b = GPIO.input(input_B) 22 | if new_a != old_a or new_b != old_b : 23 | if old_a == 0 and new_a == 1 : 24 | result = (old_b * 2 - 1) 25 | elif old_b == 0 and new_b == 1 : 26 | result = -(old_a * 2 - 1) 27 | old_a, old_b = new_a, new_b 28 | time.sleep(0.001) 29 | return result 30 | 31 | x = 0 32 | 33 | while True: 34 | change = get_encoder_turn() 35 | if change != 0 : 36 | x = x + change 37 | print(x) 38 | -------------------------------------------------------------------------------- /code/rotary_encoder_test.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | input_A = 18 7 | input_B = 23 8 | 9 | GPIO.setup(input_A, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(input_B, GPIO.IN, pull_up_down=GPIO.PUD_UP) 11 | 12 | a = True 13 | b = True 14 | 15 | while True: 16 | new_a = GPIO.input(input_A) 17 | new_b = GPIO.input(input_B) 18 | if new_a != a or new_b != b : 19 | print('a=' + str(a) + ' b=' + str(b)) 20 | a, b = new_a, new_b -------------------------------------------------------------------------------- /code/rover.py: -------------------------------------------------------------------------------- 1 | from raspirobotboard import * 2 | import pygame 3 | from pygame.locals import * 4 | 5 | rr = RaspiRobot() 6 | 7 | pygame.init() 8 | screen = pygame.display.set_mode((640, 480)) 9 | font = pygame.font.SysFont("arial", 64) 10 | 11 | pygame.display.set_caption('RaspiRobot') 12 | pygame.mouse.set_visible(0) 13 | 14 | def update_distance(): 15 | dist = rr.get_range_inch() 16 | if dist > 0 and dist < 10: 17 | rr.stop() 18 | rr.set_led1(False) 19 | rr.set_led2(False) 20 | if dist == 0: 21 | return 22 | message = 'Distance: ' + str(dist) + ' in' 23 | text_surface = font.render(message, True, (127, 127, 127)) 24 | screen.blit(text_surface, (100, 100)) 25 | 26 | w = screen.get_width() - 20 27 | proximity = ((100 - dist) / 100.0) * w 28 | if proximity < 0: 29 | proximity = 0 30 | pygame.draw.rect(screen, (0, 255, 0), Rect((10, 10),(w, 50))) 31 | pygame.draw.rect(screen, (255, 0, 0), Rect((10, 10),(proximity, 50))) 32 | pygame.display.update() 33 | 34 | 35 | while True: 36 | for event in pygame.event.get(): 37 | if event.type == KEYDOWN: 38 | if event.key == K_UP: 39 | rr.forward() 40 | rr.set_led1(True) 41 | rr.set_led2(True) 42 | elif event.key == K_DOWN: 43 | rr.set_led1(True) 44 | rr.set_led2(True) 45 | rr.reverse() 46 | elif event.key == K_RIGHT: 47 | rr.set_led1(False) 48 | rr.set_led2(True) 49 | rr.right() 50 | elif event.key == K_LEFT: 51 | rr.set_led1(True) 52 | rr.set_led2(False) 53 | rr.left() 54 | elif event.key == K_SPACE: 55 | rr.stop() 56 | rr.set_led1(False) 57 | rr.set_led2(False) 58 | screen.fill((255, 255, 255)) 59 | update_distance() 60 | -------------------------------------------------------------------------------- /code/servo.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | pwm = GPIO.PWM(18, 100) 8 | pwm.start(5) 9 | 10 | class App: 11 | 12 | def __init__(self, master): 13 | frame = Frame(master) 14 | frame.pack() 15 | scale = Scale(frame, from_=0, to=180, 16 | orient=HORIZONTAL, command=self.update) 17 | scale.grid(row=0) 18 | 19 | 20 | def update(self, angle): 21 | duty = float(angle) / 10.0 + 2.5 22 | pwm.ChangeDutyCycle(duty) 23 | 24 | root = Tk() 25 | root.wm_title('Servo Control') 26 | app = App(root) 27 | root.geometry("200x50+0+0") 28 | root.mainloop() 29 | -------------------------------------------------------------------------------- /code/servo_module.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | from Adafruit_PWM_Servo_Driver import PWM 3 | import time 4 | 5 | pwm = PWM(0x40) 6 | pwm.setPWMFreq(50) 7 | 8 | class App: 9 | 10 | def __init__(self, master): 11 | frame = Frame(master) 12 | frame.pack() 13 | scale = Scale(frame, from_=0, to=180, 14 | orient=HORIZONTAL, command=self.update) 15 | scale.grid(row=0) 16 | 17 | 18 | def update(self, angle): 19 | pulse_len = int(float(angle) * 500.0 / 180.0) + 110 20 | pwm.setPWM(0, 0, pulse_len) 21 | pwm.setPWM(1, 0, pulse_len) 22 | 23 | root = Tk() 24 | root.wm_title('Servo Control') 25 | app = App(root) 26 | root.geometry("200x50+0+0") 27 | root.mainloop() 28 | -------------------------------------------------------------------------------- /code/speed.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | def factorial(n): 4 | if n == 0: 5 | return 1 6 | else: 7 | return n * factorial(n-1) 8 | 9 | before_time = time.clock() 10 | for i in range(1, 10000): 11 | factorial(200) 12 | after_time = time.clock() 13 | 14 | print(after_time - before_time) -------------------------------------------------------------------------------- /code/stepper.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | coil_A_1_pin = 18 7 | coil_A_2_pin = 23 8 | coil_B_1_pin = 24 9 | coil_B_2_pin = 17 10 | 11 | GPIO.setup(coil_A_1_pin, GPIO.OUT) 12 | GPIO.setup(coil_A_2_pin, GPIO.OUT) 13 | GPIO.setup(coil_B_1_pin, GPIO.OUT) 14 | GPIO.setup(coil_B_2_pin, GPIO.OUT) 15 | 16 | forward_seq = ['1010', '0110', '0101', '1001'] 17 | reverse_seq = list(forward_seq) # to copy the list 18 | reverse_seq.reverse() 19 | 20 | def forward(delay, steps): 21 | for i in range(steps): 22 | for step in forward_seq: 23 | set_step(step) 24 | time.sleep(delay) 25 | 26 | def backwards(delay, steps): 27 | for i in range(steps): 28 | for step in reverse_seq: 29 | set_step(step) 30 | time.sleep(delay) 31 | 32 | 33 | def set_step(step): 34 | GPIO.output(coil_A_1_pin, step[0] == '1') 35 | GPIO.output(coil_A_2_pin, step[1] == '1') 36 | GPIO.output(coil_B_1_pin, step[2] == '1') 37 | GPIO.output(coil_B_2_pin, step[3] == '1') 38 | 39 | while True: 40 | set_step('0000') 41 | delay = raw_input("Delay between steps (milliseconds)?") 42 | steps = raw_input("How many steps forward? ") 43 | forward(int(delay) / 1000.0, int(steps)) 44 | set_step('0000') 45 | steps = raw_input("How many steps backwards? ") 46 | backwards(int(delay) / 1000.0, int(steps)) 47 | -------------------------------------------------------------------------------- /code/stepper_rrb.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | coil_A_1_pin = 17 7 | coil_A_2_pin = 4 8 | coil_B_1_pin = 10 9 | coil_B_2_pin = 25 10 | 11 | GPIO.setup(coil_A_1_pin, GPIO.OUT) 12 | GPIO.setup(coil_A_2_pin, GPIO.OUT) 13 | GPIO.setup(coil_B_1_pin, GPIO.OUT) 14 | GPIO.setup(coil_B_2_pin, GPIO.OUT) 15 | 16 | forward_seq = ['1011', '1111', '1110', '1010'] 17 | reverse_seq = list(forward_seq) # to copy the list 18 | reverse_seq.reverse() 19 | 20 | def forward(delay, steps): 21 | for i in range(steps): 22 | for step in forward_seq: 23 | set_step(step) 24 | time.sleep(delay) 25 | 26 | def backwards(delay, steps): 27 | for i in range(steps): 28 | for step in reverse_seq: 29 | set_step(step) 30 | time.sleep(delay) 31 | 32 | 33 | def set_step(step): 34 | GPIO.output(coil_A_1_pin, step[0] == '1') 35 | GPIO.output(coil_A_2_pin, step[1] == '1') 36 | GPIO.output(coil_B_1_pin, step[2] == '1') 37 | GPIO.output(coil_B_2_pin, step[3] == '1') 38 | 39 | while True: 40 | set_step('0000') 41 | delay = raw_input("Delay between steps (milliseconds)?") 42 | steps = raw_input("How many steps forward? ") 43 | forward(int(delay) / 1000.0, int(steps)) 44 | set_step('0000') 45 | steps = raw_input("How many steps backwards? ") 46 | backwards(int(delay) / 1000.0, int(steps)) 47 | -------------------------------------------------------------------------------- /code/switch.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) 7 | 8 | while True: 9 | input_state = GPIO.input(18) 10 | if input_state == False: 11 | print('Button Pressed') 12 | time.sleep(0.2) -------------------------------------------------------------------------------- /code/switch_3_pos.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | top_input = 18 7 | bottom_input = 23 8 | 9 | GPIO.setup(top_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(bottom_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) 11 | 12 | switch_position = "unknown" 13 | 14 | while True: 15 | top_state = GPIO.input(top_input) 16 | bottom_state = GPIO.input(bottom_input) 17 | new_switch_position = "unknown" 18 | if top_state == False: 19 | new_switch_position = "up" 20 | elif bottom_state == False: 21 | new_switch_position = "down" 22 | else: 23 | new_switch_position = "center" 24 | if new_switch_position != switch_position: 25 | switch_position = new_switch_position 26 | print(switch_position) -------------------------------------------------------------------------------- /code/switch_on_off.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | switch_pin = 18 7 | led_pin = 23 8 | 9 | GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(led_pin, GPIO.OUT) 11 | 12 | led_state = False 13 | old_input_state = True # pulled-up 14 | 15 | while True: 16 | new_input_state = GPIO.input(switch_pin) 17 | if new_input_state == False and old_input_state == True: 18 | led_state = not led_state 19 | old_input_state = new_input_state 20 | GPIO.output(led_pin, led_state) -------------------------------------------------------------------------------- /code/switch_on_off_no_bounce.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | switch_pin = 18 7 | led_pin = 23 8 | 9 | GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(led_pin, GPIO.OUT) 11 | 12 | led_state = False 13 | old_input_state = True # pulled-up 14 | 15 | while True: 16 | new_input_state = GPIO.input(switch_pin) 17 | if new_input_state == False and old_input_state == True: 18 | led_state = not led_state 19 | time.sleep(0.2) 20 | old_input_state = new_input_state 21 | GPIO.output(led_pin, led_state) -------------------------------------------------------------------------------- /code/temp_DS18B20.py: -------------------------------------------------------------------------------- 1 | import os, glob, time 2 | 3 | os.system('modprobe w1-gpio') 4 | os.system('modprobe w1-therm') 5 | 6 | base_dir = '/sys/bus/w1/devices/' 7 | device_folder = glob.glob(base_dir + '28*')[0] 8 | device_file = device_folder + '/w1_slave' 9 | 10 | def read_temp_raw(): 11 | f = open(device_file, 'r') 12 | lines = f.readlines() 13 | f.close() 14 | return lines 15 | 16 | def read_temp(): 17 | lines = read_temp_raw() 18 | while lines[0].strip()[-3:] != 'YES': 19 | time.sleep(0.2) 20 | lines = read_temp_raw() 21 | equals_pos = lines[1].find('t=') 22 | if equals_pos != -1: 23 | temp_string = lines[1][equals_pos+2:] 24 | temp_c = float(temp_string) / 1000.0 25 | temp_f = temp_c * 9.0 / 5.0 + 32.0 26 | return temp_c, temp_f 27 | 28 | while True: 29 | print("temp C=%f\ttemp F=%f" % read_temp()) 30 | time.sleep(1) -------------------------------------------------------------------------------- /code/temp_log.py: -------------------------------------------------------------------------------- 1 | import os, glob, time, datetime 2 | 3 | log_period = 10 # seconds 4 | 5 | logging_folder = glob.glob('/media/*')[0] 6 | dt = datetime.datetime.now() 7 | file_name = "temp_log_{:%Y_%m_%d}.csv".format(dt) 8 | logging_file = logging_folder + '/' + file_name 9 | 10 | os.system('modprobe w1-gpio') 11 | os.system('modprobe w1-therm') 12 | 13 | base_dir = '/sys/bus/w1/devices/' 14 | device_folder = glob.glob(base_dir + '28*')[0] 15 | device_file = device_folder + '/w1_slave' 16 | 17 | def read_temp_raw(): 18 | f = open(device_file, 'r') 19 | lines = f.readlines() 20 | f.close() 21 | return lines 22 | 23 | def read_temp(): 24 | lines = read_temp_raw() 25 | while lines[0].strip()[-3:] != 'YES': 26 | time.sleep(0.2) 27 | lines = read_temp_raw() 28 | equals_pos = lines[1].find('t=') 29 | if equals_pos != -1: 30 | temp_string = lines[1][equals_pos+2:] 31 | temp_c = float(temp_string) / 1000.0 32 | temp_f = temp_c * 9.0 / 5.0 + 32.0 33 | return temp_c, temp_f 34 | 35 | def log_temp(): 36 | temp_c, temp_f = read_temp() 37 | dt = datetime.datetime.now() 38 | f = open(logging_file, 'a') 39 | f.write('\n"{:%H:%M:%S}",'.format(dt)) 40 | f.write(str(temp_c)) 41 | f.close() 42 | 43 | print("Logging to: " + logging_file) 44 | while True: 45 | log_temp() 46 | time.sleep(log_period) -------------------------------------------------------------------------------- /code/tilt.py: -------------------------------------------------------------------------------- 1 | import spidev, time 2 | 3 | spi = spidev.SpiDev() 4 | spi.open(0,0) 5 | 6 | def analog_read(channel): 7 | r = spi.xfer2([1, (8 + channel) << 4, 0]) 8 | adc_out = ((r[1]&3) << 8) + r[2] 9 | return adc_out 10 | 11 | while True: 12 | x = analog_read(0) 13 | y = analog_read(1) 14 | z = analog_read(2) 15 | if x < 450: 16 | print("Left") 17 | elif x > 550: 18 | print("Right") 19 | elif y < 450: 20 | print("Back") 21 | elif y > 550: 22 | print("Forward") 23 | time.sleep(0.2) -------------------------------------------------------------------------------- /code/web_control.py: -------------------------------------------------------------------------------- 1 | from bottle import route, run 2 | import RPi.GPIO as GPIO 3 | 4 | host = '192.168.1.8' 5 | 6 | GPIO.setmode(GPIO.BCM) 7 | led_pins = [18, 23, 24] 8 | led_states = [0, 0, 0] 9 | switch_pin = 25 10 | 11 | GPIO.setup(led_pins[0], GPIO.OUT) 12 | GPIO.setup(led_pins[1], GPIO.OUT) 13 | GPIO.setup(led_pins[2], GPIO.OUT) 14 | GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 15 | 16 | def switch_status(): 17 | state = GPIO.input(switch_pin) 18 | if state: 19 | return 'Up' 20 | else: 21 | return 'Down' 22 | 23 | def html_for_led(led): 24 | l = str(led) 25 | result = " " 26 | return result 27 | 28 | def update_leds(): 29 | for i, value in enumerate(led_states): 30 | GPIO.output(led_pins[i], value) 31 | 32 | @route('/') 33 | @route('/') 34 | def index(led="n"): 35 | print(led) 36 | if led != "n": 37 | led_num = int(led) 38 | led_states[led_num] = not led_states[led_num] 39 | update_leds() 40 | response = "" 46 | 47 | response += '

GPIO Control

' 48 | response += '

Button=' + switch_status() + '

' 49 | response += '

LEDs

' 50 | response += html_for_led(0) 51 | response += html_for_led(1) 52 | response += html_for_led(2) 53 | return response 54 | 55 | run(host=host, port=80) -------------------------------------------------------------------------------- /code/web_control_test.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | led_pin_1 = 18 7 | led_pin_2 = 23 8 | led_pin_3 = 24 9 | switch_pin = 25 10 | 11 | GPIO.setup(led_pin_1, GPIO.OUT) 12 | GPIO.setup(led_pin_2, GPIO.OUT) 13 | GPIO.setup(led_pin_3, GPIO.OUT) 14 | GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 15 | 16 | GPIO.output(led_pin_1, 1) 17 | time.sleep(1) 18 | GPIO.output(led_pin_2, 1) 19 | time.sleep(1) 20 | GPIO.output(led_pin_3, 1) 21 | time.sleep(1) 22 | GPIO.output(led_pin_1, 0) 23 | time.sleep(1) 24 | GPIO.output(led_pin_2, 0) 25 | time.sleep(1) 26 | GPIO.output(led_pin_3, 0) 27 | time.sleep(1) 28 | 29 | while True: 30 | print(GPIO.input(switch_pin)) 31 | time.sleep(1) --------------------------------------------------------------------------------