master 63bb7ee16789 cached
58 files
29.6 KB
10.4k tokens
68 symbols
1 requests
Download .txt
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 <LiquidCrystal.h>

// 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 <Wire.h>

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('<b>Pi thinks the date/time is: {{t}}</b>', 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 = " <input type='button' onClick='changed(" + l + ")' value='LED " + l + "'/>"
    return result

def update_leds():
    for i, value in enumerate(led_states):
        GPIO.output(led_pins[i], value)

@route('/')
@route('/<led>')
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 = "<script>"
    response += "function changed(led)"
    response += "{"
    response += "  window.location.href='/' + led"
    response += "}"
    response += "</script>"
    
    response += '<h1>GPIO Control</h1>'
    response += '<h2>Button=' + switch_status() + '</h2>'
    response += '<h2>LEDs</h2>'
    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)
Download .txt
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
Download .txt
SYMBOL INDEX (68 symbols across 31 files)

FILE: code/adc_accelerometer.py
  function analog_read (line 6) | def analog_read(channel):

FILE: code/adc_scaled.py
  function analog_read (line 9) | def analog_read(channel):

FILE: code/adc_test.py
  function analog_read (line 6) | def analog_read(channel):

FILE: code/adc_tmp36.py
  function analog_read (line 6) | def analog_read(channel):

FILE: code/ardu_gui_slider.py
  class App (line 8) | class App:
    method __init__ (line 10) | def __init__(self, master):
    method update (line 18) | def update(self, duty):

FILE: code/ardu_gui_switch.py
  class App (line 8) | class App:
    method __init__ (line 10) | def __init__(self, master):
    method update (line 19) | def update(self):

FILE: code/ardu_pi_i2c.py
  function request_reading (line 10) | def request_reading():

FILE: code/bottle_test.py
  function index (line 5) | def index(name='time'):

FILE: code/buzzer.py
  function buzz (line 8) | def buzz(pitch, duration):

FILE: code/charlieplexing.py
  function set_pin (line 16) | def set_pin(pin_index, pin_state):
  function light_led (line 23) | def light_led(led_number):

FILE: code/gui_sensor_reading.py
  function send_trigger_pulse (line 12) | def send_trigger_pulse():
  function wait_for_echo (line 17) | def wait_for_echo(value, timeout):
  function get_distance (line 22) | def get_distance():
  class App (line 33) | class App:
    method __init__ (line 35) | def __init__(self, master):
    method update_reading (line 45) | def update_reading(self):

FILE: code/gui_slider.py
  class App (line 10) | class App:
    method __init__ (line 12) | def __init__(self, master):
    method update (line 20) | def update(self, duty):

FILE: code/gui_sliderRGB.py
  class App (line 19) | class App:
    method __init__ (line 21) | def __init__(self, master):
    method updateRed (line 38) | def updateRed(self, duty):
    method updateGreen (line 41) | def updateGreen(self, duty):
    method updateBlue (line 44) | def updateBlue(self, duty):

FILE: code/gui_switch.py
  class App (line 8) | class App:
    method __init__ (line 10) | def __init__(self, master):
    method update (line 19) | def update(self):

FILE: code/interrupts.py
  function my_callback (line 6) | def my_callback(channel):

FILE: code/keypad.py
  function get_key (line 20) | def get_key():

FILE: code/keys_sys.py
  function read_ch (line 3) | def read_ch():

FILE: code/motor_control.py
  function clockwise (line 16) | def clockwise():
  function counter_clockwise (line 20) | def counter_clockwise():

FILE: code/pot_step.py
  function discharge (line 9) | def discharge():
  function charge_time (line 15) | def charge_time():
  function analog_read (line 24) | def analog_read():

FILE: code/ranger.py
  function send_trigger_pulse (line 11) | def send_trigger_pulse():
  function wait_for_echo (line 16) | def wait_for_echo(value, timeout):
  function get_distance (line 21) | def get_distance():

FILE: code/rotary_encoder.py
  function get_encoder_turn (line 16) | def get_encoder_turn():

FILE: code/rover.py
  function update_distance (line 14) | def update_distance():

FILE: code/servo.py
  class App (line 10) | class App:
    method __init__ (line 12) | def __init__(self, master):
    method update (line 20) | def update(self, angle):

FILE: code/servo_module.py
  class App (line 8) | class App:
    method __init__ (line 10) | def __init__(self, master):
    method update (line 18) | def update(self, angle):

FILE: code/speed.py
  function factorial (line 3) | def factorial(n):

FILE: code/stepper.py
  function forward (line 20) | def forward(delay, steps):
  function backwards (line 26) | def backwards(delay, steps):
  function set_step (line 33) | def set_step(step):

FILE: code/stepper_rrb.py
  function forward (line 20) | def forward(delay, steps):
  function backwards (line 26) | def backwards(delay, steps):
  function set_step (line 33) | def set_step(step):

FILE: code/temp_DS18B20.py
  function read_temp_raw (line 10) | def read_temp_raw():
  function read_temp (line 16) | def read_temp():

FILE: code/temp_log.py
  function read_temp_raw (line 17) | def read_temp_raw():
  function read_temp (line 23) | def read_temp():
  function log_temp (line 35) | def log_temp():

FILE: code/tilt.py
  function analog_read (line 6) | def analog_read(channel):

FILE: code/web_control.py
  function switch_status (line 16) | def switch_status():
  function html_for_led (line 23) | def html_for_led(led):
  function update_leds (line 28) | def update_leds():
  function index (line 34) | def index(led="n"):
Condensed preview — 58 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (35K chars).
[
  {
    "path": "README.md",
    "chars": 115,
    "preview": "raspberrypi_cookbook\n====================\n\nThe source code from the book 'The Raspberry Pi Cookbook' by Simon Monk."
  },
  {
    "path": "code/AlaModeShield/AlaModeShield.ino",
    "chars": 240,
    "preview": "\n#include <LiquidCrystal.h>\n\n// pins for Freetronics LCD Shield\n\nLiquidCrystal lcd(8, 9, 4, 5, 6, 7);\n\nvoid setup() \n{\n "
  },
  {
    "path": "code/ArduinoHello/ArduinoHello.ino",
    "chars": 129,
    "preview": "// ArduinoHello\n\nvoid setup()\n{\n  Serial.begin(9600); \n}\n\nvoid loop()\n{\n  Serial.println(\"Hello Raspberry Pi\");\n  delay("
  },
  {
    "path": "code/ArduinoI2C/ArduinoI2C.ino",
    "chars": 660,
    "preview": "#include <Wire.h>\n\nint SLAVE_ADDRESS = 0x04;\nint ledPin = 13;\nint analogPin = A0;\n\nboolean ledOn = false;\n\nvoid setup() "
  },
  {
    "path": "code/ArduinoSerial/ArduinoSerial.ino",
    "chars": 542,
    "preview": "#include \"SoftwareSerial.h\"\n\nint ledPin = 13;\nint analogPin = A0;\n\nSoftwareSerial ser(8, 9); // RX, TX\n\nboolean ledOn = "
  },
  {
    "path": "code/adc_accelerometer.py",
    "chars": 328,
    "preview": "import spidev, time\n\nspi = spidev.SpiDev()\nspi.open(0,0)\n\ndef analog_read(channel):\n    r = spi.xfer2([1, (8 + channel) "
  },
  {
    "path": "code/adc_scaled.py",
    "chars": 364,
    "preview": "import spidev\n\nR1 = 10000.0\nR2 = 3300.0\n\nspi = spidev.SpiDev()\nspi.open(0,0)\n\ndef analog_read(channel):\n    r = spi.xfer"
  },
  {
    "path": "code/adc_test.py",
    "chars": 338,
    "preview": "import spidev, time\n\nspi = spidev.SpiDev()\nspi.open(0,0)\n\ndef analog_read(channel):\n    r = spi.xfer2([1, (8 + channel) "
  },
  {
    "path": "code/adc_tmp36.py",
    "chars": 405,
    "preview": "import spidev, time\n\nspi = spidev.SpiDev()\nspi.open(0,0)\n\ndef analog_read(channel):\n    r = spi.xfer2([1, (8 + channel) "
  },
  {
    "path": "code/ardu_adc.py",
    "chars": 368,
    "preview": "import pyfirmata\nimport time\n\nboard = pyfirmata.Arduino('/dev/ttyACM0')\nanalog_pin = board.get_pin('a:0:i')\nit = pyfirma"
  },
  {
    "path": "code/ardu_flash.py",
    "chars": 200,
    "preview": "import pyfirmata\nimport time\n\nboard = pyfirmata.Arduino('/dev/ttyACM0')\nled_pin = board.get_pin('d:10:o')\n\nwhile True:\n "
  },
  {
    "path": "code/ardu_flash_micro.py",
    "chars": 201,
    "preview": "import pyfirmata\nimport time\n\nboard = pyfirmata.Arduino('/dev/ttyACM0')\nled_pin = board.get_pin('d:10:o')\n\nwhile True:\n "
  },
  {
    "path": "code/ardu_flash_ser.py",
    "chars": 200,
    "preview": "import pyfirmata\nimport time\n\nboard = pyfirmata.Arduino('/dev/ttyAMA0')\nled_pin = board.get_pin('d:13:o')\n\nwhile True:\n "
  },
  {
    "path": "code/ardu_gui_slider.py",
    "chars": 534,
    "preview": "from Tkinter import *\nimport time\nimport pyfirmata\n\nboard = pyfirmata.Arduino('/dev/ttyACM0')\nled_pin = board.get_pin('d"
  },
  {
    "path": "code/ardu_gui_switch.py",
    "chars": 623,
    "preview": "from Tkinter import *\nimport pyfirmata\nimport time\n\nboard = pyfirmata.Arduino('/dev/ttyACM0')\nled_pin = board.get_pin('d"
  },
  {
    "path": "code/ardu_pi_i2c.py",
    "chars": 457,
    "preview": "import smbus\nimport time\n\n# for RPI version 1, use \"bus = smbus.SMBus(0)\"\nbus = smbus.SMBus(1)\n\n# This must match in the"
  },
  {
    "path": "code/ardu_pi_serial.py",
    "chars": 266,
    "preview": "import serial\n\nser = serial.Serial('/dev/ttyAMA0', 9600)\n\nwhile True:\n    command = raw_input(\"Enter command: l - toggle"
  },
  {
    "path": "code/ardu_pwm.py",
    "chars": 216,
    "preview": "import pyfirmata\n\nboard = pyfirmata.Arduino('/dev/ttyACM0')\nled_pin = board.get_pin('d:10:p')\n\nwhile True:\n    duty_s = "
  },
  {
    "path": "code/ardu_servo.py",
    "chars": 211,
    "preview": "import pyfirmata\n\nboard = pyfirmata.Arduino('/dev/ttyACM0')\nservo_pin = board.get_pin('d:11:s')\n\nwhile True:\n    angle_s"
  },
  {
    "path": "code/ardu_switch.py",
    "chars": 331,
    "preview": "import pyfirmata\nimport time\nimport sys\n\nboard = pyfirmata.Arduino('/dev/ttyACM0')\nswitch_pin = board.get_pin('d:4:i')\ni"
  },
  {
    "path": "code/bottle_test.py",
    "chars": 282,
    "preview": "from bottle import route, run, template\nfrom datetime import datetime\n\n@route('/')\ndef index(name='time'):\n    dt = date"
  },
  {
    "path": "code/buzzer.py",
    "chars": 566,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nbuzzer_pin = 18\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\n\ndef buzz(pitch, du"
  },
  {
    "path": "code/charlieplexing.py",
    "chars": 663,
    "preview": "import RPi.GPIO as GPIO\n\npins = [18, 23, 24]\n\npin_led_states = [\n  [1, 0, -1], # A\n  [0, 1, -1], # B\n  [-1, 1, 0], # C\n "
  },
  {
    "path": "code/gps_test.py",
    "chars": 317,
    "preview": "from gps import *\nsession = gps()\nsession.stream(WATCH_ENABLE|WATCH_NEWSTYLE)\n\nwhile True:\n    report = session.next()\n "
  },
  {
    "path": "code/gui_sensor_reading.py",
    "chars": 1441,
    "preview": "from Tkinter import *\nimport RPi.GPIO as GPIO\nimport time\n\ntrigger_pin = 18\necho_pin = 23\n\nGPIO.setmode(GPIO.BCM)\nGPIO.s"
  },
  {
    "path": "code/gui_slider.py",
    "chars": 550,
    "preview": "from Tkinter import *\nimport RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\npwm = GPIO.PW"
  },
  {
    "path": "code/gui_sliderRGB.py",
    "chars": 1352,
    "preview": "from Tkinter import *\nimport RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\nGPIO.setup(23"
  },
  {
    "path": "code/gui_switch.py",
    "chars": 604,
    "preview": "from Tkinter import *\nimport RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\n\nclass App:\n\t"
  },
  {
    "path": "code/interrupts.py",
    "chars": 301,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\ndef my_callback(channel):\n    print('You pressed the button"
  },
  {
    "path": "code/keypad.py",
    "chars": 704,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\nrows = [17, 25, 24, 23]\ncols = [27, 18, 22]\nkeys = [\n    ['"
  },
  {
    "path": "code/keys_pygame.py",
    "chars": 352,
    "preview": "import pygame\nimport sys\nfrom pygame.locals import *\n\npygame.init()\nscreen = pygame.display.set_mode((640, 480))\npygame."
  },
  {
    "path": "code/keys_sys.py",
    "chars": 378,
    "preview": "import sys, tty, termios\n        \ndef read_ch():\n    fd = sys.stdin.fileno()\n    old_settings = termios.tcgetattr(fd)\n  "
  },
  {
    "path": "code/led_blink.py",
    "chars": 181,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\n\nwhile (True):\n\tGPIO.output(18, Tru"
  },
  {
    "path": "code/led_brightness.py",
    "chars": 282,
    "preview": "import RPi.GPIO as GPIO\n\nled_pin = 18\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(led_pin, GPIO.OUT)\n\npwm_led = GPIO.PWM(led_pin, "
  },
  {
    "path": "code/motor_control.py",
    "chars": 650,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nenable_pin = 18\nin1_pin = 23\nin2_pin =24\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(enable_"
  },
  {
    "path": "code/mouse_pygame.py",
    "chars": 331,
    "preview": "import pygame\nimport sys\nfrom pygame.locals import *\n\npygame.init()\nscreen = pygame.display.set_mode((640, 480))\npygame."
  },
  {
    "path": "code/pi_lite_message.py",
    "chars": 136,
    "preview": "import serial\n\nser = serial.Serial('/dev/ttyAMA0', 9600)\n\nwhile True:\n    message = raw_input(\"Enter message: \")\n    ser"
  },
  {
    "path": "code/pi_lite_rain.py",
    "chars": 197,
    "preview": "import serial\nimport random\n\nser = serial.Serial('/dev/ttyAMA0', 9600)\n\nwhile True:\n    col = random.randint(1, 14)\n    "
  },
  {
    "path": "code/pir.py",
    "chars": 212,
    "preview": "import RPi.GPIO as GPIO\nimport time\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.IN)\n\nwhile True:\n    input_state = GPIO.i"
  },
  {
    "path": "code/pot_step.py",
    "chars": 535,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\na_pin = 18\nb_pin = 23\n\ndef discharge():\n    GPIO.setup(a_pi"
  },
  {
    "path": "code/ranger.py",
    "chars": 798,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\ntrigger_pin = 18\necho_pin = 23\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(trigger_pin, GPIO"
  },
  {
    "path": "code/rotary_encoder.py",
    "chars": 756,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\ninput_A = 18\ninput_B = 23\n\nGPIO.setup(input_A, GPIO.IN, pul"
  },
  {
    "path": "code/rotary_encoder_test.py",
    "chars": 401,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\ninput_A = 18\ninput_B = 23\n\nGPIO.setup(input_A, GPIO.IN, pul"
  },
  {
    "path": "code/rover.py",
    "chars": 1709,
    "preview": "from raspirobotboard import *\nimport pygame\nfrom pygame.locals import *\n\nrr = RaspiRobot()\n\npygame.init()\nscreen = pygam"
  },
  {
    "path": "code/servo.py",
    "chars": 578,
    "preview": "from Tkinter import *\nimport RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(18, GPIO.OUT)\npwm = GPIO.PW"
  },
  {
    "path": "code/servo_module.py",
    "chars": 605,
    "preview": "from Tkinter import *\nfrom Adafruit_PWM_Servo_Driver import PWM\nimport time\n\npwm = PWM(0x40)\npwm.setPWMFreq(50)  \n\nclass"
  },
  {
    "path": "code/speed.py",
    "chars": 224,
    "preview": "import time\n\ndef factorial(n):\n  if n == 0:\n    return 1\n  else:\n    return n * factorial(n-1)\n\nbefore_time = time.clock"
  },
  {
    "path": "code/stepper.py",
    "chars": 1158,
    "preview": "import RPi.GPIO as GPIO\nimport time\n \nGPIO.setmode(GPIO.BCM)\n \ncoil_A_1_pin = 18\ncoil_A_2_pin = 23\ncoil_B_1_pin = 24\ncoi"
  },
  {
    "path": "code/stepper_rrb.py",
    "chars": 1157,
    "preview": "import RPi.GPIO as GPIO\nimport time\n \nGPIO.setmode(GPIO.BCM)\n \ncoil_A_1_pin = 17\ncoil_A_2_pin = 4\ncoil_B_1_pin = 10\ncoil"
  },
  {
    "path": "code/switch.py",
    "chars": 241,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\nwhile Tr"
  },
  {
    "path": "code/switch_3_pos.py",
    "chars": 675,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\ntop_input = 18\nbottom_input = 23\n\nGPIO.setup(top_input, GPI"
  },
  {
    "path": "code/switch_on_off.py",
    "chars": 459,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\nswitch_pin = 18\nled_pin = 23\n\nGPIO.setup(switch_pin, GPIO.I"
  },
  {
    "path": "code/switch_on_off_no_bounce.py",
    "chars": 483,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\nswitch_pin = 18\nled_pin = 23\n\nGPIO.setup(switch_pin, GPIO.I"
  },
  {
    "path": "code/temp_DS18B20.py",
    "chars": 766,
    "preview": "import os, glob, time\n \nos.system('modprobe w1-gpio')\nos.system('modprobe w1-therm')\n \nbase_dir = '/sys/bus/w1/devices/'"
  },
  {
    "path": "code/temp_log.py",
    "chars": 1187,
    "preview": "import os, glob, time, datetime\n\nlog_period = 10 # seconds\n\nlogging_folder = glob.glob('/media/*')[0]\ndt = datetime.date"
  },
  {
    "path": "code/tilt.py",
    "chars": 450,
    "preview": "import spidev, time\n\nspi = spidev.SpiDev()\nspi.open(0,0)\n\ndef analog_read(channel):\n    r = spi.xfer2([1, (8 + channel) "
  },
  {
    "path": "code/web_control.py",
    "chars": 1349,
    "preview": "from bottle import route, run\nimport RPi.GPIO as GPIO\n\nhost = '192.168.1.8'\n\nGPIO.setmode(GPIO.BCM)\nled_pins = [18, 23, "
  },
  {
    "path": "code/web_control_test.py",
    "chars": 583,
    "preview": "import RPi.GPIO as GPIO\nimport time\n\nGPIO.setmode(GPIO.BCM)\n\nled_pin_1 = 18\nled_pin_2 = 23\nled_pin_3 = 24\nswitch_pin = 2"
  }
]

About this extraction

This page contains the full source code of the simonmonk/raspberrypi_cookbook GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 58 files (29.6 KB), approximately 10.4k tokens, and a symbol index with 68 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!