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

GPIO Control

' response += '

Button=' + switch_status() + '

' response += '

LEDs

' response += html_for_led(0) response += html_for_led(1) response += html_for_led(2) return response run(host=host, port=80) ================================================ FILE: code/web_control_test.py ================================================ import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) led_pin_1 = 18 led_pin_2 = 23 led_pin_3 = 24 switch_pin = 25 GPIO.setup(led_pin_1, GPIO.OUT) GPIO.setup(led_pin_2, GPIO.OUT) GPIO.setup(led_pin_3, GPIO.OUT) GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) GPIO.output(led_pin_1, 1) time.sleep(1) GPIO.output(led_pin_2, 1) time.sleep(1) GPIO.output(led_pin_3, 1) time.sleep(1) GPIO.output(led_pin_1, 0) time.sleep(1) GPIO.output(led_pin_2, 0) time.sleep(1) GPIO.output(led_pin_3, 0) time.sleep(1) while True: print(GPIO.input(switch_pin)) time.sleep(1)