├── LICENSE ├── README.md ├── adc_accelerometer.py ├── adc_scaled.py ├── adc_test.py ├── adc_tmp36.py ├── buzzer.py ├── charlieplexing.py ├── cheerlights.py ├── coin_count.py ├── coin_count_pi_cam.py ├── cpu_temp.py ├── cpu_temp_float.py ├── detect_motion.py ├── displayotron_ip.py ├── esp8266_webserver └── esp8266_webserver.ino ├── explorer_blink.py ├── faces.jpg ├── gps_test.py ├── gui_sensor_reading.py ├── gui_slider.py ├── gui_sliderRGB.py ├── gui_switch.py ├── ifttt_cpu_temp.py ├── interrupts.py ├── keypad.py ├── keys_pygame.py ├── keys_sys.py ├── led_blink.py ├── led_blink_safe.py ├── led_brightness.py ├── led_strip.py ├── minecraft_stairs.py ├── motor_control.py ├── mouse_pygame.py ├── ocr_example.png ├── ocr_example.tiff ├── oled_clock.py ├── photoresistor_step.py ├── pot_step.py ├── ranger.py ├── rotary_encoder.py ├── rotary_encoder_test.py ├── rover.py ├── send_tweet.py ├── sense_hat_clock.py ├── sense_hat_compass.py ├── sense_hat_magnet.py ├── sense_hat_orientation.py ├── sense_hat_taster.py ├── servo.py ├── servo_blaster.py ├── servo_module.py ├── sleep_test.py ├── small_image.png ├── small_image.xcf ├── stepper.py ├── stepper_hat.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 ├── thermistor.py ├── thingspeak_data.py ├── thread_test.py ├── twitter_trigger.py ├── web_control.py ├── web_control_test.py └── web_sensor ├── justgage.1.0.1.min.js ├── main.html ├── raphael.2.1.0.min.js └── web_sensor.py /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015 Simon Monk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # raspberrypi_cookbook_ed2 2 | The source code to accompany the SECOND EDITION of the book [The Raspberry Pi Cookbook](https://www.amazon.com/Raspberry-Pi-Cookbook-Software-Solutions/dp/1491939109) by Simon Monk. 3 | 4 | ![The Raspberry Pi Cookbook](https://images-na.ssl-images-amazon.com/images/I/51ycAEEVGgL._SX379_BO1,204,203,200_.jpg) 5 | -------------------------------------------------------------------------------- /adc_accelerometer.py: -------------------------------------------------------------------------------- 1 | import spidev, time 2 | 3 | spi = spidev.SpiDev() 4 | spi.open(0,0) 5 | 6 | def analog_read(channel): 7 | r = spi.xfer2([1, (8 + channel) << 4, 0]) 8 | adc_out = ((r[1]&3) << 8) + r[2] 9 | return adc_out 10 | 11 | while True: 12 | x = analog_read(0) 13 | y = analog_read(1) 14 | z = analog_read(2) 15 | print("X=%d\tY=%d\tZ=%d" % (x, y, z)) 16 | time.sleep(1) -------------------------------------------------------------------------------- /adc_scaled.py: -------------------------------------------------------------------------------- 1 | import spidev 2 | 3 | R1 = 10000.0 4 | R2 = 3300.0 5 | 6 | spi = spidev.SpiDev() 7 | spi.open(0,0) 8 | 9 | def analog_read(channel): 10 | r = spi.xfer2([1, (8 + channel) << 4, 0]) 11 | adc_out = ((r[1]&3) << 8) + r[2] 12 | return adc_out 13 | 14 | reading = analog_read(0) 15 | voltage_adc = reading * 3.3 / 1024 16 | voltage_actual = voltage_adc / (R2 / (R1 + R2)) 17 | print("Battery Voltage=" + str(voltage_actual)) -------------------------------------------------------------------------------- /adc_test.py: -------------------------------------------------------------------------------- 1 | import spidev, time 2 | 3 | spi = spidev.SpiDev() 4 | spi.open(0,0) 5 | 6 | def analog_read(channel): 7 | r = spi.xfer2([1, (8 + channel) << 4, 0]) 8 | adc_out = ((r[1]&3) << 8) + r[2] 9 | return adc_out 10 | 11 | while True: 12 | reading = analog_read(0) 13 | voltage = reading * 3.3 / 1024 14 | print("Reading=%d\tVoltage=%f" % (reading, voltage)) 15 | time.sleep(1) -------------------------------------------------------------------------------- /adc_tmp36.py: -------------------------------------------------------------------------------- 1 | import spidev, time 2 | 3 | spi = spidev.SpiDev() 4 | spi.open(0,0) 5 | 6 | def analog_read(channel): 7 | r = spi.xfer2([1, (8 + channel) << 4, 0]) 8 | adc_out = ((r[1]&3) << 8) + r[2] 9 | return adc_out 10 | 11 | while True: 12 | reading = analog_read(0) 13 | voltage = reading * 3.3 / 1024 14 | temp_c = voltage * 100 - 50 15 | temp_f = temp_c * 9.0 / 5.0 + 32 16 | print("Temp C=%f\t\tTemp f=%f" % (temp_c, temp_f)) 17 | time.sleep(1) -------------------------------------------------------------------------------- /buzzer.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | buzzer_pin = 18 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | 8 | def buzz(pitch, duration): 9 | period = 1.0 / pitch 10 | delay = period / 2 11 | cycles = int(duration * pitch) 12 | for i in range(cycles): 13 | GPIO.output(buzzer_pin, True) 14 | time.sleep(delay) 15 | GPIO.output(buzzer_pin, False) 16 | time.sleep(delay) 17 | 18 | 19 | while True: 20 | pitch_s = raw_input("Enter Pitch (200 to 2000): ") 21 | pitch = float(pitch_s) 22 | duration_s = raw_input("Enter Duration (seconds): ") 23 | duration = float(duration_s) 24 | buzz(pitch, duration) -------------------------------------------------------------------------------- /charlieplexing.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | 3 | pins = [18, 23, 24] 4 | 5 | pin_led_states = [ 6 | [1, 0, -1], # A 7 | [0, 1, -1], # B 8 | [-1, 1, 0], # C 9 | [-1, 0, 1], # D 10 | [1, -1, 0], # E 11 | [0, -1, 1] # F 12 | ] 13 | 14 | GPIO.setmode(GPIO.BCM) 15 | 16 | def set_pin(pin_index, pin_state): 17 | if pin_state == -1: 18 | GPIO.setup(pins[pin_index], GPIO.IN) 19 | else: 20 | GPIO.setup(pins[pin_index], GPIO.OUT) 21 | GPIO.output(pins[pin_index], pin_state) 22 | 23 | def light_led(led_number): 24 | for pin_index, pin_state in enumerate(pin_led_states[led_number]): 25 | set_pin(pin_index, pin_state) 26 | 27 | set_pin(0, -1) 28 | set_pin(1, -1) 29 | set_pin(2, -1) 30 | 31 | while True: 32 | x = int(raw_input("Pin (0 to 5):")) 33 | light_led(x) 34 | -------------------------------------------------------------------------------- /cheerlights.py: -------------------------------------------------------------------------------- 1 | from squid import * 2 | import urllib, time 3 | 4 | squid = Squid(18, 23, 24) 5 | cheerlights_url = "http://api.thingspeak.com/channels/1417/field/2/last.txt" 6 | 7 | 8 | try: 9 | while True: 10 | try: 11 | cheerlights = urllib.urlopen(cheerlights_url) 12 | c = cheerlights.read() 13 | cheerlights.close() 14 | print(c) 15 | squid.set_color_rgb(c) 16 | except: 17 | print('Error') 18 | time.sleep(2) 19 | 20 | finally: 21 | GPIO.cleanup() 22 | -------------------------------------------------------------------------------- /coin_count.py: -------------------------------------------------------------------------------- 1 | from SimpleCV import * 2 | 3 | c = Camera() 4 | 5 | while True: 6 | i = c.getImage().invert() 7 | coins = i.findCircle(canny=100, thresh=70, distance=15) 8 | print(len(coins)) -------------------------------------------------------------------------------- /coin_count_pi_cam.py: -------------------------------------------------------------------------------- 1 | import picamera 2 | from SimpleCV import * 3 | 4 | def get_camera_image(): 5 | with picamera.PiCamera() as camera: 6 | camera.capture('tmp.jpg') 7 | return Image('tmp.jpg') 8 | 9 | while True: 10 | i = get_camera_image().invert() 11 | coins = i.findCircle(canny=100, thresh=70, distance=15) 12 | print(len(coins)) -------------------------------------------------------------------------------- /cpu_temp.py: -------------------------------------------------------------------------------- 1 | import os, time 2 | 3 | while True: 4 | dev = os.popen('/opt/vc/bin/vcgencmd measure_temp') 5 | cpu_temp = dev.read() 6 | print(cpu_temp) 7 | time.sleep(1) -------------------------------------------------------------------------------- /cpu_temp_float.py: -------------------------------------------------------------------------------- 1 | import os, time 2 | 3 | while True: 4 | dev = os.popen('/opt/vc/bin/vcgencmd measure_temp') 5 | cpu_temp_s = dev.read()[5:-3] # top and tail string 6 | cpu_temp = float(cpu_temp_s) 7 | print(cpu_temp) 8 | time.sleep(1) -------------------------------------------------------------------------------- /detect_motion.py: -------------------------------------------------------------------------------- 1 | from SimpleCV import * 2 | 3 | MIN_BLOG_SIZE = 1000 4 | 5 | c = Camera() 6 | 7 | old_image = c.getImage() 8 | 9 | while True: 10 | new_image = c.getImage() 11 | diff = new_image - old_image 12 | blobs = diff.findBlobs(minsize=MIN_BLOG_SIZE) 13 | if blobs : 14 | print("Movement detected") 15 | old_image = new_image 16 | print('.') -------------------------------------------------------------------------------- /displayotron_ip.py: -------------------------------------------------------------------------------- 1 | import dothat.lcd as lcd 2 | import dothat.backlight as backlight 3 | import time 4 | from datetime import datetime 5 | import subprocess 6 | 7 | while True: 8 | lcd.clear() 9 | backlight.rgb(0, 255, 0) 10 | try: 11 | hostname = subprocess.check_output(['hostname']).split()[0] 12 | ip = subprocess.check_output(['hostname', '-I']).split()[0] 13 | t = '{:%H:%M:%S}'.format(datetime.now()) 14 | lcd.write(hostname) 15 | lcd.set_cursor_position(0, 1) 16 | lcd.write(ip) 17 | lcd.set_cursor_position(0, 2) 18 | lcd.write(t) 19 | except: 20 | backlight.rgb(255, 0, 0) 21 | time.sleep(1) -------------------------------------------------------------------------------- /esp8266_webserver/esp8266_webserver.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * This sketch demonstrates how to set up a simple HTTP-like server. 3 | * The server will set a GPIO pin depending on the request 4 | * http://server_ip/gpio/0 will set the GPIO2 low, 5 | * http://server_ip/gpio/1 will set the GPIO2 high 6 | * server_ip is the IP address of the ESP8266 module, will be 7 | * printed to Serial when the module is connected. 8 | */ 9 | 10 | #include 11 | 12 | const char* ssid = "Linda-and-Simon"; 13 | const char* password = "EP8KQG9D"; 14 | 15 | // Create an instance of the server 16 | // specify the port to listen on as an argument 17 | WiFiServer server(80); 18 | 19 | void setup() { 20 | Serial.begin(115200); 21 | delay(10); 22 | 23 | // prepare GPIO2 24 | pinMode(2, OUTPUT); 25 | digitalWrite(2, 0); 26 | 27 | // Connect to WiFi network 28 | Serial.println(); 29 | Serial.println(); 30 | Serial.print("Connecting to "); 31 | Serial.println(ssid); 32 | 33 | WiFi.begin(ssid, password); 34 | 35 | while (WiFi.status() != WL_CONNECTED) { 36 | delay(500); 37 | Serial.print("."); 38 | } 39 | Serial.println(""); 40 | Serial.println("WiFi connected"); 41 | 42 | // Start the server 43 | server.begin(); 44 | Serial.println("Server started"); 45 | 46 | // Print the IP address 47 | Serial.println(WiFi.localIP()); 48 | } 49 | 50 | void loop() { 51 | // Check if a client has connected 52 | WiFiClient client = server.available(); 53 | if (!client) { 54 | return; 55 | } 56 | 57 | // Wait until the client sends some data 58 | Serial.println("new client"); 59 | while(!client.available()){ 60 | delay(1); 61 | } 62 | 63 | // Read the first line of the request 64 | String req = client.readStringUntil('\r'); 65 | Serial.println(req); 66 | client.flush(); 67 | 68 | // Match the request 69 | int val; 70 | if (req.indexOf("/gpio/0") != -1) 71 | val = 0; 72 | else if (req.indexOf("/gpio/1") != -1) 73 | val = 1; 74 | else { 75 | Serial.println("invalid request"); 76 | client.stop(); 77 | return; 78 | } 79 | 80 | // Set GPIO2 according to the request 81 | digitalWrite(2, val); 82 | 83 | client.flush(); 84 | 85 | // Prepare the response 86 | String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n\r\n\r\nGPIO is now "; 87 | s += (val)?"high":"low"; 88 | s += "\n"; 89 | 90 | // Send the response to the client 91 | client.print(s); 92 | delay(1); 93 | Serial.println("Client disonnected"); 94 | 95 | // The client will actually be disconnected 96 | // when the function returns and 'client' object is detroyed 97 | } 98 | 99 | -------------------------------------------------------------------------------- /explorer_blink.py: -------------------------------------------------------------------------------- 1 | import explorerhat, time 2 | 3 | while True: 4 | explorerhat.light.red.on() 5 | time.sleep(0.5) 6 | explorerhat.light.red.off() 7 | time.sleep(0.5) 8 | -------------------------------------------------------------------------------- /faces.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonmonk/raspberrypi_cookbook_ed2/3872e93059627533d0a509d3692ec28a7bd29991/faces.jpg -------------------------------------------------------------------------------- /gps_test.py: -------------------------------------------------------------------------------- 1 | from gps import * 2 | session = gps() 3 | session.stream(WATCH_ENABLE|WATCH_NEWSTYLE) 4 | 5 | while True: 6 | report = session.next() 7 | if report.keys()[0] == 'epx' : 8 | lat = float(report['lat']) 9 | lon = float(report['lon']) 10 | print("lat=%f\tlon=%f\ttime=%s" % (lat, lon, report['time'])) 11 | time.sleep(0.5) -------------------------------------------------------------------------------- /gui_sensor_reading.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | trigger_pin = 18 6 | echo_pin = 23 7 | 8 | GPIO.setmode(GPIO.BCM) 9 | GPIO.setup(trigger_pin, GPIO.OUT) 10 | GPIO.setup(echo_pin, GPIO.IN) 11 | 12 | def send_trigger_pulse(): 13 | GPIO.output(trigger_pin, True) 14 | time.sleep(0.0001) 15 | GPIO.output(trigger_pin, False) 16 | 17 | def wait_for_echo(value, timeout): 18 | count = timeout 19 | while GPIO.input(echo_pin) != value and count > 0: 20 | count = count - 1 21 | 22 | def get_distance(): 23 | send_trigger_pulse() 24 | wait_for_echo(True, 10000) 25 | start = time.time() 26 | wait_for_echo(False, 10000) 27 | finish = time.time() 28 | pulse_len = finish - start 29 | distance_cm = pulse_len / 0.000058 30 | distance_in = distance_cm / 2.5 31 | return (distance_cm, distance_in) 32 | 33 | class App: 34 | 35 | def __init__(self, master): 36 | self.master = master 37 | frame = Frame(master) 38 | frame.pack() 39 | label = Label(frame, text='Distance (inches)', font=("Helvetica", 32)) 40 | label.grid(row=0) 41 | self.reading_label = Label(frame, text='12.34', font=("Helvetica", 110)) 42 | self.reading_label.grid(row=1) 43 | self.update_reading() 44 | 45 | def update_reading(self): 46 | cm, inch = get_distance() 47 | reading_str = "{:.2f}".format(inch) 48 | self.reading_label.configure(text=reading_str) 49 | self.master.after(500, self.update_reading) 50 | 51 | 52 | root = Tk() 53 | root.wm_title('Range Finder') 54 | app = App(root) 55 | root.geometry("400x300+0+0") 56 | root.mainloop() 57 | 58 | -------------------------------------------------------------------------------- /gui_slider.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | pwm = GPIO.PWM(18, 500) 8 | pwm.start(100) 9 | 10 | class App: 11 | 12 | def __init__(self, master): 13 | frame = Frame(master) 14 | frame.pack() 15 | scale = Scale(frame, from_=0, to=100, 16 | orient=HORIZONTAL, command=self.update) 17 | scale.grid(row=0) 18 | 19 | 20 | def update(self, duty): 21 | pwm.ChangeDutyCycle(float(duty)) 22 | 23 | root = Tk() 24 | root.wm_title('PWM Power Control') 25 | app = App(root) 26 | root.geometry("200x50+0+0") 27 | root.mainloop() 28 | 29 | -------------------------------------------------------------------------------- /gui_sliderRGB.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | GPIO.setup(23, GPIO.OUT) 8 | GPIO.setup(24, GPIO.OUT) 9 | 10 | pwmRed = GPIO.PWM(18, 500) 11 | pwmRed.start(100) 12 | 13 | pwmGreen = GPIO.PWM(23, 500) 14 | pwmGreen.start(100) 15 | 16 | pwmBlue = GPIO.PWM(24, 500) 17 | pwmBlue.start(100) 18 | 19 | class App: 20 | 21 | def __init__(self, master): 22 | frame = Frame(master) 23 | frame.pack() 24 | Label(frame, text='Red').grid(row=0, column=0) 25 | Label(frame, text='Green').grid(row=1, column=0) 26 | Label(frame, text='Blue').grid(row=2, column=0) 27 | scaleRed = Scale(frame, from_=0, to=100, 28 | orient=HORIZONTAL, command=self.updateRed) 29 | scaleRed.grid(row=0, column=1) 30 | scaleGreen = Scale(frame, from_=0, to=100, 31 | orient=HORIZONTAL, command=self.updateGreen) 32 | scaleGreen.grid(row=1, column=1) 33 | scaleBlue = Scale(frame, from_=0, to=100, 34 | orient=HORIZONTAL, command=self.updateBlue) 35 | scaleBlue.grid(row=2, column=1) 36 | 37 | 38 | def updateRed(self, duty): 39 | pwmRed.ChangeDutyCycle(float(duty)) 40 | 41 | def updateGreen(self, duty): 42 | pwmGreen.ChangeDutyCycle(float(duty)) 43 | 44 | def updateBlue(self, duty): 45 | pwmBlue.ChangeDutyCycle(float(duty)) 46 | 47 | root = Tk() 48 | root.wm_title('RGB LED Control') 49 | app = App(root) 50 | root.geometry("200x150+0+0") 51 | root.mainloop() -------------------------------------------------------------------------------- /gui_switch.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | 8 | class App: 9 | 10 | def __init__(self, master): 11 | frame = Frame(master) 12 | frame.pack() 13 | self.check_var = BooleanVar() 14 | check = Checkbutton(frame, text='Pin 18', 15 | command=self.update, 16 | variable=self.check_var, onvalue=True, offvalue=False) 17 | check.grid(row=1) 18 | 19 | def update(self): 20 | GPIO.output(18, self.check_var.get()) 21 | 22 | root = Tk() 23 | root.wm_title('On / Off Switch') 24 | app = App(root) 25 | root.geometry("200x50+0+0") 26 | root.mainloop() 27 | -------------------------------------------------------------------------------- /ifttt_cpu_temp.py: -------------------------------------------------------------------------------- 1 | import time, os, urllib, urllib2 2 | 3 | MAX_TEMP = 37.0 4 | MIN_T_BETWEEN_WARNINGS = 60 # Minutes 5 | 6 | EVENT = 'cpu_too_hot' 7 | BASE_URL = 'https://maker.ifttt.com/trigger/' 8 | KEY = 'cyR3vPNFlP9K32W4NZB9cd' 9 | 10 | def send_notification(temp): 11 | data = urllib.urlencode({'value1' : str(temp)}) 12 | url = BASE_URL + EVENT + '/with/key/' + KEY 13 | response = urllib2.urlopen(url=url, data=data) 14 | print(response.read()) 15 | 16 | 17 | def cpu_temp(): 18 | dev = os.popen('/opt/vc/bin/vcgencmd measure_temp') 19 | cpu_temp = dev.read()[5:-3] 20 | return float(cpu_temp) 21 | 22 | while True: 23 | temp = cpu_temp() 24 | print("CPU Temp (C): " + str(temp)) 25 | if temp > MAX_TEMP: 26 | print("CPU TOO HOT!") 27 | send_notification(temp) 28 | print("No more notifications for: " + str(MIN_T_BETWEEN_WARNINGS) + " mins") 29 | time.sleep(MIN_T_BETWEEN_WARNINGS * 60) 30 | time.sleep(1) 31 | -------------------------------------------------------------------------------- /interrupts.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | def my_callback(channel): 7 | print('You pressed the button') 8 | 9 | GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.add_event_detect(18, GPIO.FALLING, callback=my_callback) 11 | 12 | i = 0 13 | while True: 14 | i = i + 1 15 | print(i) 16 | time.sleep(1) 17 | -------------------------------------------------------------------------------- /keypad.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | rows = [17, 25, 24, 23] 7 | cols = [27, 18, 22] 8 | keys = [ 9 | ['1', '2', '3'], 10 | ['4', '5', '6'], 11 | ['7', '8', '9'], 12 | ['*', '0', '#']] 13 | 14 | for row_pin in rows: 15 | GPIO.setup(row_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 16 | 17 | for col_pin in cols: 18 | GPIO.setup(col_pin, GPIO.OUT) 19 | 20 | def get_key(): 21 | key = 0 22 | for col_num, col_pin in enumerate(cols): 23 | GPIO.output(col_pin, 1) 24 | for row_num, row_pin in enumerate(rows): 25 | if GPIO.input(row_pin): 26 | key = keys[row_num][col_num] 27 | GPIO.output(col_pin, 0) 28 | return key 29 | 30 | while True: 31 | key = get_key() 32 | if key : 33 | print(key) 34 | time.sleep(0.3) 35 | -------------------------------------------------------------------------------- /keys_pygame.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | from pygame.locals import * 4 | 5 | pygame.init() 6 | screen = pygame.display.set_mode((640, 480)) 7 | pygame.mouse.set_visible(0) 8 | 9 | while True: 10 | for event in pygame.event.get(): 11 | if event.type == QUIT: 12 | sys.exit() 13 | if event.type == KEYDOWN: 14 | print("Code: " + str(event.key) + " Char: " + chr(event.key)) -------------------------------------------------------------------------------- /keys_sys.py: -------------------------------------------------------------------------------- 1 | import sys, tty, termios 2 | 3 | def read_ch(): 4 | fd = sys.stdin.fileno() 5 | old_settings = termios.tcgetattr(fd) 6 | try: 7 | tty.setraw(sys.stdin.fileno()) 8 | ch = sys.stdin.read(1) 9 | finally: 10 | termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 11 | return ch 12 | 13 | while True: 14 | ch = read_ch() 15 | if ch == 'x': 16 | break 17 | print("key is: " + ch) 18 | -------------------------------------------------------------------------------- /led_blink.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | GPIO.setup(18, GPIO.OUT) 6 | 7 | while (True): 8 | GPIO.output(18, True) 9 | time.sleep(0.5) 10 | GPIO.output(18, False) 11 | time.sleep(0.5) 12 | -------------------------------------------------------------------------------- /led_blink_safe.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | GPIO.setup(18, GPIO.OUT) 6 | 7 | try: 8 | while (True): 9 | GPIO.output(18, True) 10 | time.sleep(0.5) 11 | GPIO.output(18, False) 12 | time.sleep(0.5) 13 | finally: 14 | print("Cleaning Up!") 15 | GPIO.cleanup() -------------------------------------------------------------------------------- /led_brightness.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | 3 | led_pin = 18 4 | GPIO.setmode(GPIO.BCM) 5 | GPIO.setup(led_pin, GPIO.OUT) 6 | 7 | pwm_led = GPIO.PWM(led_pin, 500) 8 | pwm_led.start(100) 9 | 10 | while True: 11 | duty_s = raw_input("Enter Brightness (0 to 100):") 12 | duty = int(duty_s) 13 | pwm_led.ChangeDutyCycle(duty) 14 | 15 | -------------------------------------------------------------------------------- /led_strip.py: -------------------------------------------------------------------------------- 1 | import time 2 | from neopixel import * 3 | 4 | # LED strip configuration: 5 | LED_COUNT = 10 # Number of LED pixels. 6 | LED_PIN = 18 # GPIO pin connected to the pixels (must support PWM!). 7 | LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz) 8 | LED_DMA = 5 # DMA channel to use for generating signal (try 5) 9 | LED_BRIGHTNESS = 255 # Set to 0 for darkest and 255 for brightest 10 | LED_INVERT = False # True to invert the signal (when using NPN transistor level shift) 11 | 12 | RED = Color(255, 0, 0) 13 | NO_COLOR = Color(0, 0, 0) 14 | 15 | strip = Adafruit_NeoPixel(LED_COUNT, LED_PIN, LED_FREQ_HZ, LED_DMA, LED_INVERT, LED_BRIGHTNESS) 16 | strip.begin() 17 | 18 | def clear(): 19 | for i in range(0, LED_COUNT): 20 | strip.setPixelColor(i, NO_COLOR) 21 | strip.show() 22 | 23 | i = 0 24 | while True: 25 | clear() 26 | strip.setPixelColor(i, RED) 27 | strip.show() 28 | time.sleep(1) 29 | i += 1 30 | if i >= LED_COUNT: 31 | i = 0 -------------------------------------------------------------------------------- /minecraft_stairs.py: -------------------------------------------------------------------------------- 1 | from mcpi import minecraft, block 2 | mc = minecraft.Minecraft.create() 3 | 4 | mc.postToChat("Lets Build a Staircase!") 5 | 6 | x, y, z = mc.player.getPos() 7 | 8 | for xy in range(1, 50): 9 | mc.setBlock(x + xy, y + xy, z, block.STONE) -------------------------------------------------------------------------------- /motor_control.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | enable_pin = 18 5 | in1_pin = 23 6 | in2_pin =24 7 | 8 | GPIO.setmode(GPIO.BCM) 9 | GPIO.setup(enable_pin, GPIO.OUT) 10 | GPIO.setup(in1_pin, GPIO.OUT) 11 | GPIO.setup(in2_pin, GPIO.OUT) 12 | 13 | pwm = GPIO.PWM(enable_pin, 500) 14 | pwm.start(0) 15 | 16 | def clockwise(): 17 | GPIO.output(in1_pin, True) 18 | GPIO.output(in2_pin, False) 19 | 20 | def counter_clockwise(): 21 | GPIO.output(in1_pin, False) 22 | GPIO.output(in2_pin, True) 23 | 24 | while True: 25 | cmd = raw_input("Command, f/r 0..9, E.g. f5 :") 26 | direction = cmd[0] 27 | if direction == "f": 28 | clockwise() 29 | else: 30 | counter_clockwise() 31 | speed = int(cmd[1]) * 10 32 | pwm.ChangeDutyCycle(speed) 33 | 34 | -------------------------------------------------------------------------------- /mouse_pygame.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | import sys 3 | from pygame.locals import * 4 | 5 | pygame.init() 6 | screen = pygame.display.set_mode((640, 480)) 7 | pygame.mouse.set_visible(0) 8 | 9 | while True: 10 | for event in pygame.event.get(): 11 | if event.type == QUIT: 12 | sys.exit() 13 | if event.type == MOUSEMOTION: 14 | print("Mouse: (%d, %d)" % event.pos) -------------------------------------------------------------------------------- /ocr_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonmonk/raspberrypi_cookbook_ed2/3872e93059627533d0a509d3692ec28a7bd29991/ocr_example.png -------------------------------------------------------------------------------- /ocr_example.tiff: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonmonk/raspberrypi_cookbook_ed2/3872e93059627533d0a509d3692ec28a7bd29991/ocr_example.tiff -------------------------------------------------------------------------------- /oled_clock.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from oled.device import ssd1306 4 | from oled.render import canvas 5 | from PIL import ImageFont 6 | import time 7 | from datetime import datetime 8 | 9 | # Setup Display 10 | device = ssd1306(port=1, address=0x3C) 11 | font_file = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf' 12 | small_font = ImageFont.truetype('FreeSans.ttf', 12, filename=font_file) 13 | large_font = ImageFont.truetype('FreeSans.ttf', 33, filename=font_file) 14 | 15 | # Display a message on 3 lines, first line big font 16 | def display_message(top_line, line_2): 17 | global device 18 | with canvas(device) as draw: 19 | draw.text((0, 0), top_line, font=large_font, fill=255) 20 | draw.text((0, 50), line_2, font=small_font, fill=255) 21 | 22 | while True: 23 | now = datetime.now() 24 | date_message = '{:%d %B %Y}'.format(now) 25 | time_message = '{:%H:%M:%S}'.format(now) 26 | display_message(time_message, date_message) 27 | time.sleep(0.1) -------------------------------------------------------------------------------- /photoresistor_step.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | 7 | pin = 18 8 | 9 | def discharge(): 10 | GPIO.setup(pin, GPIO.OUT) 11 | GPIO.output(pin, False) 12 | time.sleep(0.1) 13 | 14 | 15 | # return the time taken for the capacitor to go HIGH 16 | # than means around 1.65V 17 | def charge_time(): 18 | t1 = time.time() 19 | GPIO.setup(pin, GPIO.IN) 20 | while not GPIO.input(pin): 21 | # charge for 1ms 22 | GPIO.setup(pin, GPIO.OUT) 23 | GPIO.output(pin, True) 24 | time.sleep(0.001) 25 | # set to input to test again 26 | GPIO.setup(pin, GPIO.IN) 27 | time.sleep(0.001) 28 | t2 = time.time() 29 | return (t2 - t1) * 1000000 30 | 31 | # Take an analog reading as the time taken to charge C 32 | def analog_read(): 33 | discharge() 34 | return charge_time() 35 | 36 | 37 | while True: 38 | print(analog_read()) 39 | time.sleep(0.5) -------------------------------------------------------------------------------- /pot_step.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time, math 3 | 4 | C = 0.33 # uF 5 | R1 = 1000 # Ohms 6 | 7 | GPIO.setmode(GPIO.BCM) 8 | 9 | # Pin a charges the capacitor through a fixed 1k resistor and the thermistor in series 10 | # pin b discharges the capacitor through a fixed 1k resistor 11 | a_pin = 18 12 | b_pin = 23 13 | 14 | # empty the capacitor ready to start filling it up 15 | def discharge(): 16 | GPIO.setup(a_pin, GPIO.IN) 17 | GPIO.setup(b_pin, GPIO.OUT) 18 | GPIO.output(b_pin, False) 19 | time.sleep(0.1) 20 | 21 | # return the time taken (uS) for the voltage on the capacitor to count as a digital input HIGH 22 | # than means around 1.65V 23 | def charge_time(): 24 | GPIO.setup(b_pin, GPIO.IN) 25 | GPIO.setup(a_pin, GPIO.OUT) 26 | GPIO.output(a_pin, True) 27 | t1 = time.time() 28 | while not GPIO.input(b_pin): 29 | pass 30 | t2 = time.time() 31 | return (t2 - t1) * 1000000 32 | 33 | # Take an analog reading as the time taken to charge after first discharging the capacitor 34 | def analog_read(): 35 | discharge() 36 | t = charge_time() 37 | discharge() 38 | return t 39 | 40 | # Convert the time taken to charge the cpacitor into a value of resistance 41 | # To reduce errors, do it 100 times and take the average. 42 | def read_resistance(): 43 | n = 10 44 | total = 0; 45 | for i in range(1, n): 46 | total = total + analog_read() 47 | t = total / float(n) 48 | T = t * 0.632 * 3.3 49 | r = (T / C) - R1 50 | return r 51 | try: 52 | while True: 53 | print(read_resistance()) 54 | time.sleep(0.5) 55 | finally: 56 | GPIO.cleanup() 57 | -------------------------------------------------------------------------------- /ranger.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | trigger_pin = 18 5 | echo_pin = 23 6 | 7 | GPIO.setmode(GPIO.BCM) 8 | GPIO.setup(trigger_pin, GPIO.OUT) 9 | GPIO.setup(echo_pin, GPIO.IN) 10 | 11 | def send_trigger_pulse(): 12 | GPIO.output(trigger_pin, True) 13 | time.sleep(0.0001) 14 | GPIO.output(trigger_pin, False) 15 | 16 | def wait_for_echo(value, timeout): 17 | count = timeout 18 | while GPIO.input(echo_pin) != value and count > 0: 19 | count = count - 1 20 | 21 | def get_distance(): 22 | send_trigger_pulse() 23 | wait_for_echo(True, 10000) 24 | start = time.time() 25 | wait_for_echo(False, 10000) 26 | finish = time.time() 27 | pulse_len = finish - start 28 | distance_cm = pulse_len / 0.000058 29 | distance_in = distance_cm / 2.5 30 | return (distance_cm, distance_in) 31 | 32 | 33 | while True: 34 | print("cm=%f\tinches=%f" % get_distance()) 35 | time.sleep(1) -------------------------------------------------------------------------------- /rotary_encoder.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | input_A = 18 7 | input_B = 23 8 | 9 | GPIO.setup(input_A, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(input_B, GPIO.IN, pull_up_down=GPIO.PUD_UP) 11 | 12 | 13 | old_a = True 14 | old_b = True 15 | 16 | def get_encoder_turn(): 17 | # return -1, 0, or +1 18 | global old_a, old_b 19 | result = 0 20 | new_a = GPIO.input(input_A) 21 | new_b = GPIO.input(input_B) 22 | if new_a != old_a or new_b != old_b : 23 | if old_a == 0 and new_a == 1 : 24 | result = (old_b * 2 - 1) 25 | elif old_b == 0 and new_b == 1 : 26 | result = -(old_a * 2 - 1) 27 | old_a, old_b = new_a, new_b 28 | time.sleep(0.001) 29 | return result 30 | 31 | x = 0 32 | 33 | while True: 34 | change = get_encoder_turn() 35 | if change != 0 : 36 | x = x + change 37 | print(x) 38 | -------------------------------------------------------------------------------- /rotary_encoder_test.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | input_A = 18 7 | input_B = 23 8 | 9 | GPIO.setup(input_A, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(input_B, GPIO.IN, pull_up_down=GPIO.PUD_UP) 11 | 12 | a = True 13 | b = True 14 | 15 | while True: 16 | new_a = GPIO.input(input_A) 17 | new_b = GPIO.input(input_B) 18 | if new_a != a or new_b != b : 19 | print('a=' + str(a) + ' b=' + str(b)) 20 | a, b = new_a, new_b -------------------------------------------------------------------------------- /rover.py: -------------------------------------------------------------------------------- 1 | # 08_manual_robot.py 2 | # Use the arrow keys to direct the robot 3 | 4 | from rrb3 import * 5 | import sys 6 | import tty 7 | import termios 8 | 9 | rr = RRB3(9.0, 6.0) # battery, motor 10 | 11 | UP = 0 12 | DOWN = 1 13 | RIGHT = 2 14 | LEFT = 3 15 | 16 | print("Use the arrow keys to move the robot") 17 | print("Press CTRL-c to quit the program") 18 | 19 | # These functions allow the program to read your keyboard 20 | def readchar(): 21 | fd = sys.stdin.fileno() 22 | old_settings = termios.tcgetattr(fd) 23 | try: 24 | tty.setraw(sys.stdin.fileno()) 25 | ch = sys.stdin.read(1) 26 | finally: 27 | termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) 28 | if ch == '0x03': 29 | raise KeyboardInterrupt 30 | return ch 31 | 32 | def readkey(getchar_fn=None): 33 | getchar = getchar_fn or readchar 34 | c1 = getchar() 35 | if ord(c1) != 0x1b: 36 | return c1 37 | c2 = getchar() 38 | if ord(c2) != 0x5b: 39 | return c1 40 | c3 = getchar() 41 | return ord(c3) - 65 # 0=Up, 1=Down, 2=Right, 3=Left arrows 42 | 43 | # This will control the movement of your robot and display on your screen 44 | try: 45 | while True: 46 | keyp = readkey() 47 | if keyp == UP: 48 | rr.forward(1) 49 | print 'forward' 50 | elif keyp == DOWN: 51 | rr.reverse(1) 52 | print 'backward' 53 | elif keyp == RIGHT: 54 | rr.right(1) 55 | print 'clockwise' 56 | elif keyp == LEFT: 57 | rr.left(1) 58 | print 'anti clockwise' 59 | elif keyp == LEFT: 60 | rr.left(1) 61 | print 'anti clockwise' 62 | elif ord(keyp) == 3: 63 | break 64 | 65 | except KeyboardInterrupt: 66 | GPIO.cleanup() 67 | 68 | -------------------------------------------------------------------------------- /send_tweet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time, os, urllib, urllib2 4 | 5 | MAX_TEMP = 37.0 6 | MIN_T_BETWEEN_WARNINGS = 60 # Minutes 7 | 8 | BASE_URL = 'https://api.thingspeak.com/apps/thingtweet/1/statuses/update/' 9 | KEY = '68LZC4LBMXLO6YDY' 10 | 11 | def send_notification(temp): 12 | status = 'Raspberry Pi getting hot. CPU temp=' + temp 13 | data = urllib.urlencode({'api_key' : KEY, 'status': status}) 14 | response = urllib2.urlopen(url=BASE_URL, data=data) 15 | print(response.read()) 16 | 17 | def cpu_temp(): 18 | dev = os.popen('/opt/vc/bin/vcgencmd measure_temp') 19 | cpu_temp = dev.read()[5:-3] 20 | return cpu_temp 21 | 22 | while True: 23 | temp = cpu_temp() 24 | print("CPU Temp (C): " + str(temp)) 25 | if temp > MAX_TEMP: 26 | print("CPU TOO HOT!") 27 | send_notification(temp) 28 | print("No more notifications for: " + str(MIN_T_BETWEEN_WARNINGS) + " mins") 29 | time.sleep(MIN_T_BETWEEN_WARNINGS * 60) 30 | time.sleep(1) 31 | -------------------------------------------------------------------------------- /sense_hat_clock.py: -------------------------------------------------------------------------------- 1 | from sense_hat import SenseHat 2 | from datetime import datetime 3 | import time 4 | 5 | hat = SenseHat() 6 | time_color = (0, 255, 0) 7 | date_color = (255, 0, 0) 8 | 9 | while True: 10 | now = datetime.now() 11 | date_message = '{:%d %B %Y}'.format(now) 12 | time_message = '{:%H:%M:%S}'.format(now) 13 | 14 | hat.show_message(date_message, text_colour=date_color) 15 | hat.show_message(time_message, text_colour=time_color) 16 | -------------------------------------------------------------------------------- /sense_hat_compass.py: -------------------------------------------------------------------------------- 1 | from sense_hat import SenseHat 2 | 3 | sense = SenseHat() 4 | 5 | while True: 6 | bearing = sense.get_compass() 7 | print('Bearing: {:.0f} to North'.format(bearing)) -------------------------------------------------------------------------------- /sense_hat_magnet.py: -------------------------------------------------------------------------------- 1 | from sense_hat import SenseHat 2 | import time 3 | 4 | hat = SenseHat() 5 | fill = (255, 0, 0) 6 | 7 | while True: 8 | reading = int(hat.get_compass_raw()['z']) 9 | if reading > 200: 10 | hat.clear(fill) 11 | time.sleep(0.2) 12 | else: 13 | hat.clear() -------------------------------------------------------------------------------- /sense_hat_orientation.py: -------------------------------------------------------------------------------- 1 | from sense_hat import SenseHat 2 | 3 | sense = SenseHat() 4 | 5 | sense.set_imu_config(True, True, True) 6 | 7 | while True: 8 | o = sense.get_orientation() 9 | print("p: {:.0f}, r: {:.0f}, y: {:.0f}".format(o['pitch'], o['roll'], o['yaw'])) -------------------------------------------------------------------------------- /sense_hat_taster.py: -------------------------------------------------------------------------------- 1 | from sense_hat import SenseHat 2 | import time 3 | 4 | hat = SenseHat() 5 | 6 | red = (255, 0, 0) 7 | 8 | hat.load_image('small_image.png') 9 | time.sleep(1) 10 | hat.set_rotation(90) 11 | time.sleep(1) 12 | hat.set_rotation(180) 13 | time.sleep(1) 14 | hat.set_rotation(270) 15 | time.sleep(1) 16 | 17 | hat.clear() 18 | hat.set_rotation(0) 19 | for xy in range(0, 8): 20 | hat.set_pixel(xy, xy, red) 21 | hat.set_pixel(xy, 7-xy, red) -------------------------------------------------------------------------------- /servo.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | GPIO.setup(18, GPIO.OUT) 7 | pwm = GPIO.PWM(18, 100) 8 | pwm.start(5) 9 | 10 | class App: 11 | 12 | def __init__(self, master): 13 | frame = Frame(master) 14 | frame.pack() 15 | scale = Scale(frame, from_=0, to=180, 16 | orient=HORIZONTAL, command=self.update) 17 | scale.grid(row=0) 18 | 19 | 20 | def update(self, angle): 21 | duty = float(angle) / 10.0 + 2.5 22 | pwm.ChangeDutyCycle(duty) 23 | 24 | root = Tk() 25 | root.wm_title('Servo Control') 26 | app = App(root) 27 | root.geometry("200x50+0+0") 28 | root.mainloop() 29 | -------------------------------------------------------------------------------- /servo_blaster.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | import os 3 | import time 4 | 5 | servo_min = 500 # uS 6 | servo_max = 2500 # uS 7 | 8 | servo = 2 # GPIO 18 9 | 10 | def map(value, from_low, from_high, to_low, to_high): 11 | from_range = from_high - from_low 12 | to_range = to_high - to_low 13 | scale_factor = float(from_range) / float(to_range) 14 | return to_low + (value / scale_factor) 15 | 16 | 17 | def set_angle(angle): 18 | pulse = int(map(angle, 0, 180, servo_min, servo_max)) 19 | command = "echo {}={}us > /dev/servoblaster".format(servo, pulse) 20 | os.system(command) 21 | 22 | 23 | class App: 24 | 25 | def __init__(self, master): 26 | frame = Frame(master) 27 | frame.pack() 28 | scale = Scale(frame, from_=0, to=180, 29 | orient=HORIZONTAL, command=self.update) 30 | scale.grid(row=0) 31 | 32 | 33 | def update(self, angle): 34 | set_angle(float(angle)) 35 | 36 | root = Tk() 37 | root.wm_title('Servo Control') 38 | app = App(root) 39 | root.geometry("200x50+0+0") 40 | root.mainloop() -------------------------------------------------------------------------------- /servo_module.py: -------------------------------------------------------------------------------- 1 | from Tkinter import * 2 | from Adafruit_PWM_Servo_Driver import PWM 3 | import time 4 | 5 | pwm = PWM(0x40) 6 | pwm.setPWMFreq(50) 7 | 8 | class App: 9 | 10 | def __init__(self, master): 11 | frame = Frame(master) 12 | frame.pack() 13 | scale = Scale(frame, from_=0, to=180, 14 | orient=HORIZONTAL, command=self.update) 15 | scale.grid(row=0) 16 | 17 | 18 | def update(self, angle): 19 | pulse_len = int(float(angle) * 500.0 / 180.0) + 110 20 | pwm.setPWM(0, 0, pulse_len) 21 | pwm.setPWM(1, 0, pulse_len) 22 | 23 | root = Tk() 24 | root.wm_title('Servo Control') 25 | app = App(root) 26 | root.geometry("200x50+0+0") 27 | root.mainloop() 28 | -------------------------------------------------------------------------------- /sleep_test.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | x = 0 4 | while True: 5 | print(x) 6 | time.sleep(1) 7 | x += 1 8 | -------------------------------------------------------------------------------- /small_image.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonmonk/raspberrypi_cookbook_ed2/3872e93059627533d0a509d3692ec28a7bd29991/small_image.png -------------------------------------------------------------------------------- /small_image.xcf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonmonk/raspberrypi_cookbook_ed2/3872e93059627533d0a509d3692ec28a7bd29991/small_image.xcf -------------------------------------------------------------------------------- /stepper.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | coil_A_1_pin = 18 7 | coil_A_2_pin = 23 8 | coil_B_1_pin = 24 9 | coil_B_2_pin = 17 10 | 11 | GPIO.setup(coil_A_1_pin, GPIO.OUT) 12 | GPIO.setup(coil_A_2_pin, GPIO.OUT) 13 | GPIO.setup(coil_B_1_pin, GPIO.OUT) 14 | GPIO.setup(coil_B_2_pin, GPIO.OUT) 15 | 16 | forward_seq = ['1010', '0110', '0101', '1001'] 17 | reverse_seq = list(forward_seq) # to copy the list 18 | reverse_seq.reverse() 19 | 20 | def forward(delay, steps): 21 | for i in range(steps): 22 | for step in forward_seq: 23 | set_step(step) 24 | time.sleep(delay) 25 | 26 | def backwards(delay, steps): 27 | for i in range(steps): 28 | for step in reverse_seq: 29 | set_step(step) 30 | time.sleep(delay) 31 | 32 | 33 | def set_step(step): 34 | GPIO.output(coil_A_1_pin, step[0] == '1') 35 | GPIO.output(coil_A_2_pin, step[1] == '1') 36 | GPIO.output(coil_B_1_pin, step[2] == '1') 37 | GPIO.output(coil_B_2_pin, step[3] == '1') 38 | 39 | while True: 40 | set_step('0000') 41 | delay = raw_input("Delay between steps (milliseconds)?") 42 | steps = raw_input("How many steps forward? ") 43 | forward(int(delay) / 1000.0, int(steps)) 44 | set_step('0000') 45 | steps = raw_input("How many steps backwards? ") 46 | backwards(int(delay) / 1000.0, int(steps)) 47 | -------------------------------------------------------------------------------- /stepper_hat.py: -------------------------------------------------------------------------------- 1 | 2 | from Adafruit_MotorHAT import Adafruit_MotorHAT 3 | import time 4 | 5 | HAT = Adafruit_MotorHAT 6 | stepper_hat = Adafruit_MotorHAT() 7 | 8 | stepper = stepper_hat.getStepper(200, 1) # 200 steps/rev, port 1 (M1, M2) 9 | 10 | try: 11 | while True: 12 | speed = input("Enter stepper speed (rpm) ") 13 | stepper.setSpeed(speed) 14 | steps_forward = input("Steps forward ") 15 | stepper.step(steps_forward, HAT.FORWARD, HAT.SINGLE) 16 | steps_forward = input("Steps reverse ") 17 | stepper.step(steps_forward, HAT.BACKWARD, HAT.SINGLE) 18 | 19 | finally: 20 | print("cleaning up") 21 | stepper_hat.getMotor(1).run(HAT.RELEASE) -------------------------------------------------------------------------------- /stepper_rrb.py: -------------------------------------------------------------------------------- 1 | from rrb3 import * 2 | import time 3 | 4 | rr = RRB3(12.0, 12.0) # battery, motor 5 | 6 | try: 7 | while True: 8 | delay = raw_input("Delay between steps (milliseconds)?") 9 | steps = raw_input("How many steps forward? ") 10 | rr.step_forward(int(delay) / 1000.0, int(steps)) 11 | steps = raw_input("How many steps backwards? ") 12 | rr.step_reverse(int(delay) / 1000.0, int(steps)) 13 | 14 | finally: 15 | GPIO.cleanup() -------------------------------------------------------------------------------- /switch.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | GPIO.setup(18, GPIO.IN, pull_up_down=GPIO.PUD_UP) 7 | 8 | while True: 9 | input_state = GPIO.input(18) 10 | if input_state == False: 11 | print('Button Pressed') 12 | time.sleep(0.2) -------------------------------------------------------------------------------- /switch_3_pos.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | top_input = 18 7 | bottom_input = 23 8 | 9 | GPIO.setup(top_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(bottom_input, GPIO.IN, pull_up_down=GPIO.PUD_UP) 11 | 12 | switch_position = "unknown" 13 | 14 | while True: 15 | top_state = GPIO.input(top_input) 16 | bottom_state = GPIO.input(bottom_input) 17 | new_switch_position = "unknown" 18 | if top_state == False: 19 | new_switch_position = "up" 20 | elif bottom_state == False: 21 | new_switch_position = "down" 22 | else: 23 | new_switch_position = "center" 24 | if new_switch_position != switch_position: 25 | switch_position = new_switch_position 26 | print(switch_position) -------------------------------------------------------------------------------- /switch_on_off.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | switch_pin = 18 7 | led_pin = 23 8 | 9 | GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(led_pin, GPIO.OUT) 11 | 12 | led_state = False 13 | old_input_state = True # pulled-up 14 | 15 | while True: 16 | new_input_state = GPIO.input(switch_pin) 17 | if new_input_state == False and old_input_state == True: 18 | led_state = not led_state 19 | old_input_state = new_input_state 20 | GPIO.output(led_pin, led_state) -------------------------------------------------------------------------------- /switch_on_off_no_bounce.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | switch_pin = 18 7 | led_pin = 23 8 | 9 | GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 10 | GPIO.setup(led_pin, GPIO.OUT) 11 | 12 | led_state = False 13 | old_input_state = True # pulled-up 14 | 15 | while True: 16 | new_input_state = GPIO.input(switch_pin) 17 | if new_input_state == False and old_input_state == True: 18 | led_state = not led_state 19 | time.sleep(0.2) 20 | old_input_state = new_input_state 21 | GPIO.output(led_pin, led_state) -------------------------------------------------------------------------------- /temp_DS18B20.py: -------------------------------------------------------------------------------- 1 | import glob, time 2 | 3 | base_dir = '/sys/bus/w1/devices/' 4 | device_folder = glob.glob(base_dir + '28*')[0] 5 | device_file = device_folder + '/w1_slave' 6 | 7 | def read_temp_raw(): 8 | f = open(device_file, 'r') 9 | lines = f.readlines() 10 | f.close() 11 | return lines 12 | 13 | def read_temp(): 14 | lines = read_temp_raw() 15 | while lines[0].strip()[-3:] != 'YES': 16 | time.sleep(0.2) 17 | lines = read_temp_raw() 18 | equals_pos = lines[1].find('t=') 19 | if equals_pos != -1: 20 | temp_string = lines[1][equals_pos+2:] 21 | temp_c = float(temp_string) / 1000.0 22 | temp_f = temp_c * 9.0 / 5.0 + 32.0 23 | return temp_c, temp_f 24 | 25 | while True: 26 | print("temp C=%f\ttemp F=%f" % read_temp()) 27 | time.sleep(1) -------------------------------------------------------------------------------- /temp_log.py: -------------------------------------------------------------------------------- 1 | import os, glob, time, datetime 2 | 3 | log_period = 10 # seconds 4 | 5 | logging_folder = glob.glob('/media/*')[0] 6 | dt = datetime.datetime.now() 7 | file_name = "temp_log_{:%Y_%m_%d}.csv".format(dt) 8 | logging_file = logging_folder + '/' + file_name 9 | 10 | os.system('modprobe w1-gpio') 11 | os.system('modprobe w1-therm') 12 | 13 | base_dir = '/sys/bus/w1/devices/' 14 | device_folder = glob.glob(base_dir + '28*')[0] 15 | device_file = device_folder + '/w1_slave' 16 | 17 | def read_temp_raw(): 18 | f = open(device_file, 'r') 19 | lines = f.readlines() 20 | f.close() 21 | return lines 22 | 23 | def read_temp(): 24 | lines = read_temp_raw() 25 | while lines[0].strip()[-3:] != 'YES': 26 | time.sleep(0.2) 27 | lines = read_temp_raw() 28 | equals_pos = lines[1].find('t=') 29 | if equals_pos != -1: 30 | temp_string = lines[1][equals_pos+2:] 31 | temp_c = float(temp_string) / 1000.0 32 | temp_f = temp_c * 9.0 / 5.0 + 32.0 33 | return temp_c, temp_f 34 | 35 | def log_temp(): 36 | temp_c, temp_f = read_temp() 37 | dt = datetime.datetime.now() 38 | f = open(logging_file, 'a') 39 | f.write('\n"{:%H:%M:%S}",'.format(dt)) 40 | f.write(str(temp_c)) 41 | f.close() 42 | 43 | print("Logging to: " + logging_file) 44 | while True: 45 | log_temp() 46 | time.sleep(log_period) -------------------------------------------------------------------------------- /thermistor.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time, math 3 | 4 | C = 0.33 # uF 5 | R1 = 1000 # Ohms 6 | B = 3800.0 # The thermistor constant - change this for a different thermistor 7 | R0 = 1000.0 # The resistance of the thermistor at 25C -change for different thermistor 8 | 9 | GPIO.setmode(GPIO.BCM) 10 | 11 | # Pin a charges the capacitor through a fixed 1k resistor and the thermistor in series 12 | # pin b discharges the capacitor through a fixed 1k resistor 13 | a_pin = 18 14 | b_pin = 23 15 | 16 | # empty the capacitor ready to start filling it up 17 | def discharge(): 18 | GPIO.setup(a_pin, GPIO.IN) 19 | GPIO.setup(b_pin, GPIO.OUT) 20 | GPIO.output(b_pin, False) 21 | time.sleep(0.1) 22 | 23 | # return the time taken (uS) for the voltage on the capacitor to count as a digital input HIGH 24 | # than means around 1.65V 25 | def charge_time(): 26 | GPIO.setup(b_pin, GPIO.IN) 27 | GPIO.setup(a_pin, GPIO.OUT) 28 | GPIO.output(a_pin, True) 29 | t1 = time.time() 30 | while not GPIO.input(b_pin): 31 | pass 32 | t2 = time.time() 33 | return (t2 - t1) * 1000000 34 | 35 | # Take an analog reading as the time taken to charge after first discharging the capacitor 36 | def analog_read(): 37 | discharge() 38 | t = charge_time() 39 | discharge() 40 | return t 41 | 42 | # Convert the time taken to charge the cpacitor into a value of resistance 43 | # To reduce errors, do it 100 times and take the average. 44 | def read_resistance(): 45 | n = 10 46 | total = 0; 47 | for i in range(1, n): 48 | total = total + analog_read() 49 | t = total / float(n) 50 | T = t * 0.632 * 3.3 51 | r = (T / C) - R1 52 | return r 53 | 54 | def read_temp_c(): 55 | R = read_resistance() 56 | t0 = 273.15 # 0 deg C in K 57 | t25 = t0 + 25.0 # 25 deg C in K 58 | # Steinhart-Hart equation - Google it 59 | inv_T = 1/t25 + 1/B * math.log(R/R0) 60 | T = (1/inv_T - t0) 61 | return T * 9.0 / 5.0 + 32.0 # convert C to F 62 | 63 | try: 64 | while True: 65 | print(read_temp_c()) 66 | time.sleep(0.5) 67 | finally: 68 | GPIO.cleanup() 69 | -------------------------------------------------------------------------------- /thingspeak_data.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import time, os, urllib, urllib2 4 | 5 | PERIOD = 60 # Seconds 6 | 7 | BASE_URL = 'https://api.thingspeak.com/update.json' 8 | KEY = 'DYHHDDKKLU8OV58T' 9 | 10 | def send_data(temp): 11 | data = urllib.urlencode({'api_key' : KEY, 'field1': temp}) 12 | response = urllib2.urlopen(url=BASE_URL, data=data) 13 | print(response.read()) 14 | 15 | def cpu_temp(): 16 | dev = os.popen('/opt/vc/bin/vcgencmd measure_temp') 17 | cpu_temp = dev.read()[5:-3] 18 | return cpu_temp 19 | 20 | while True: 21 | temp = cpu_temp() 22 | print("CPU Temp (C): " + str(temp)) 23 | send_data(temp) 24 | time.sleep(PERIOD) 25 | -------------------------------------------------------------------------------- /thread_test.py: -------------------------------------------------------------------------------- 1 | import thread, time, random 2 | 3 | def annoy(message): 4 | while True: 5 | time.sleep(random.randint(1, 3)) 6 | print(message) 7 | 8 | 9 | thread.start_new_thread(annoy, ('BOO !!',)) 10 | 11 | x = 0 12 | while True: 13 | print(x) 14 | x += 1 15 | time.sleep(1) -------------------------------------------------------------------------------- /twitter_trigger.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | import time 3 | import dweepy 4 | import RPi.GPIO as GPIO 5 | 6 | KEY = 'tweet_about_me' 7 | OUTPUT_PIN = 18 8 | OUTPUT_DURATION = 10 9 | 10 | 11 | GPIO.setmode(GPIO.BCM) 12 | GPIO.setup(OUTPUT_PIN, GPIO.OUT) 13 | 14 | while True: 15 | try: 16 | for dweet in dweepy.listen_for_dweets_from(KEY): 17 | print('Tweet: ' + dweet['content']['text']) 18 | GPIO.output(OUTPUT_PIN, True) 19 | time.sleep(OUTPUT_DURATION) 20 | GPIO.output(OUTPUT_PIN, False) 21 | except Exception: 22 | pass 23 | -------------------------------------------------------------------------------- /web_control.py: -------------------------------------------------------------------------------- 1 | from bottle import route, run 2 | import RPi.GPIO as GPIO 3 | 4 | host = '192.168.1.8' 5 | 6 | GPIO.setmode(GPIO.BCM) 7 | led_pins = [18, 23, 24] 8 | led_states = [0, 0, 0] 9 | switch_pin = 25 10 | 11 | GPIO.setup(led_pins[0], GPIO.OUT) 12 | GPIO.setup(led_pins[1], GPIO.OUT) 13 | GPIO.setup(led_pins[2], GPIO.OUT) 14 | GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 15 | 16 | def switch_status(): 17 | state = GPIO.input(switch_pin) 18 | if state: 19 | return 'Up' 20 | else: 21 | return 'Down' 22 | 23 | def html_for_led(led): 24 | l = str(led) 25 | result = " " 26 | return result 27 | 28 | def update_leds(): 29 | for i, value in enumerate(led_states): 30 | GPIO.output(led_pins[i], value) 31 | 32 | @route('/') 33 | @route('/') 34 | def index(led="n"): 35 | print(led) 36 | if led != "n": 37 | led_num = int(led) 38 | led_states[led_num] = not led_states[led_num] 39 | update_leds() 40 | response = "" 46 | 47 | response += '

GPIO Control

' 48 | response += '

Button=' + switch_status() + '

' 49 | response += '

LEDs

' 50 | response += html_for_led(0) 51 | response += html_for_led(1) 52 | response += html_for_led(2) 53 | return response 54 | 55 | run(host=host, port=80) -------------------------------------------------------------------------------- /web_control_test.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | 4 | GPIO.setmode(GPIO.BCM) 5 | 6 | led_pin_1 = 18 7 | led_pin_2 = 23 8 | led_pin_3 = 24 9 | switch_pin = 25 10 | 11 | GPIO.setup(led_pin_1, GPIO.OUT) 12 | GPIO.setup(led_pin_2, GPIO.OUT) 13 | GPIO.setup(led_pin_3, GPIO.OUT) 14 | GPIO.setup(switch_pin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 15 | 16 | GPIO.output(led_pin_1, 1) 17 | time.sleep(1) 18 | GPIO.output(led_pin_2, 1) 19 | time.sleep(1) 20 | GPIO.output(led_pin_3, 1) 21 | time.sleep(1) 22 | GPIO.output(led_pin_1, 0) 23 | time.sleep(1) 24 | GPIO.output(led_pin_2, 0) 25 | time.sleep(1) 26 | GPIO.output(led_pin_3, 0) 27 | time.sleep(1) 28 | 29 | while True: 30 | print(GPIO.input(switch_pin)) 31 | time.sleep(1) -------------------------------------------------------------------------------- /web_sensor/justgage.1.0.1.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * JustGage - a handy JavaScript plugin for generating and animating nice & clean dashboard gauges. 3 | * Copyright (c) 2012 Bojan Djuricic - pindjur(at)gmail(dot)com | http://www.madcog.com 4 | * Licensed under MIT. 5 | * Date: 31/07/2012 6 | * @author Bojan Djuricic (@Toorshia) 7 | * @version 1.0 8 | * 9 | * http://www.justgage.com 10 | */ 11 | 12 | JustGage=function(x){if(!x.id){alert("Missing id parameter for gauge!");return false}if(!document.getElementById(x.id)){alert('No element with id: "'+x.id+'" found!');return false}this.config={id:x.id,title:(x.title)?x.title:"Title",titleFontColor:(x.titleFontColor)?x.titleFontColor:"#999999",value:(x.value)?x.value:0,valueFontColor:(x.valueFontColor)?x.valueFontColor:"#010101",min:(x.min)?x.min:0,max:(x.max)?x.max:100,showMinMax:(x.showMinMax!=null)?x.showMinMax:true,gaugeWidthScale:(x.gaugeWidthScale)?x.gaugeWidthScale:1,gaugeColor:(x.gaugeColor)?x.gaugeColor:"#edebeb",label:(x.label)?x.label:"",showInnerShadow:(x.showInnerShadow!=null)?x.showInnerShadow:true,shadowOpacity:(x.shadowOpacity)?x.shadowOpacity:0.2,shadowSize:(x.shadowSize)?x.shadowSize:5,shadowVerticalOffset:(x.shadowVerticalOffset)?x.shadowVerticalOffset:3,levelColors:(x.levelColors)?x.levelColors:percentColors,levelColorsGradient:(x.levelColorsGradient!=null)?x.levelColorsGradient:true,labelFontColor:(x.labelFontColor)?x.labelFontColor:"#b3b3b3",startAnimationTime:(x.startAnimationTime)?x.startAnimationTime:700,startAnimationType:(x.startAnimationType)?x.startAnimationType:">",refreshAnimationTime:(x.refreshAnimationTime)?x.refreshAnimationTime:700,refreshAnimationType:(x.refreshAnimationType)?x.refreshAnimationType:">"};if(x.value>this.config.max){this.config.value=this.config.max}if(x.value1.25){c=1.25*q;l=q}else{c=d;l=d/1.25}var i=(d-c)/2;var g=(q-l)/2;var s=((l/8)>10)?(l/10):10;var n=i+c/2;var m=g+l/6.5;var k=((l/6.4)>16)?(l/6.4):16;var r=i+c/2;var p=g+l/1.4;var b=((l/16)>10)?(l/16):10;var f=i+c/2;var e=p+k/2+6;var j=((l/16)>10)?(l/16):10;var w=i+(c/10)+(c/6.666666666666667*this.config.gaugeWidthScale)/2;var v=g+l/1.126760563380282;var h=((l/16)>10)?(l/16):10;var u=i+c-(c/10)-(c/6.666666666666667*this.config.gaugeWidthScale)/2;var t=g+l/1.126760563380282;this.params={canvasW:d,canvasH:q,widgetW:c,widgetH:l,dx:i,dy:g,titleFontSize:s,titleX:n,titleY:m,valueFontSize:k,valueX:r,valueY:p,labelFontSize:b,labelX:f,labelY:e,minFontSize:j,minX:w,minY:v,maxFontSize:h,maxX:u,maxY:t};this.canvas.customAttributes.pki=function(K,L,N,E,O,F,D,y){var B=(1-(K-L)/(N-L))*Math.PI,G=E/2-E/10,J=G-E/6.666666666666667*y,C=E/2+F,A=O/1.25+D,H=E/2+F+G*Math.cos(B),P=O-(O-A)+D-G*Math.sin(B),M=E/2+F+J*Math.cos(B),z=O-(O-A)+D-J*Math.sin(B),I;I+="M"+(C-J)+","+A+" ";I+="L"+(C-G)+","+A+" ";I+="A"+G+","+G+" 0 0,1 "+H+","+P+" ";I+="L"+M+","+z+" ";I+="A"+J+","+J+" 0 0,0 "+(C-J)+","+A+" ";I+="z ";return{path:I}};this.gauge=this.canvas.path().attr({stroke:"none",fill:this.config.gaugeColor,pki:[this.config.max,this.config.min,this.config.max,this.params.widgetW,this.params.widgetH,this.params.dx,this.params.dy,this.config.gaugeWidthScale]});this.gauge.id=this.config.id+"-gauge";this.level=this.canvas.path().attr({stroke:"none",fill:getColorForPercentage((this.config.value-this.config.min)/(this.config.max-this.config.min),this.config.levelColors,this.config.levelColorsGradient),pki:[this.config.min,this.config.min,this.config.max,this.params.widgetW,this.params.widgetH,this.params.dx,this.params.dy,this.config.gaugeWidthScale]});this.level.id=this.config.id+"-level";this.txtTitle=this.canvas.text(this.params.titleX,this.params.titleY,this.config.title);this.txtTitle.attr({"font-size":this.params.titleFontSize,"font-weight":"bold","font-family":"Arial",fill:this.config.titleFontColor,"fill-opacity":"1"});this.txtTitle.id=this.config.id+"-txttitle";this.txtValue=this.canvas.text(this.params.valueX,this.params.valueY,this.originalValue);this.txtValue.attr({"font-size":this.params.valueFontSize,"font-weight":"bold","font-family":"Arial",fill:this.config.valueFontColor,"fill-opacity":"0"});this.txtValue.id=this.config.id+"-txtvalue";this.txtLabel=this.canvas.text(this.params.labelX,this.params.labelY,this.config.label);this.txtLabel.attr({"font-size":this.params.labelFontSize,"font-weight":"normal","font-family":"Arial",fill:this.config.labelFontColor,"fill-opacity":"0"});this.txtLabel.id=this.config.id+"-txtlabel";this.txtMin=this.canvas.text(this.params.minX,this.params.minY,this.config.min);this.txtMin.attr({"font-size":this.params.minFontSize,"font-weight":"normal","font-family":"Arial",fill:this.config.labelFontColor,"fill-opacity":(this.config.showMinMax==true)?"1":"0"});this.txtMin.id=this.config.id+"-txtmin";this.txtMax=this.canvas.text(this.params.maxX,this.params.maxY,this.config.max);this.txtMax.attr({"font-size":this.params.maxFontSize,"font-weight":"normal","font-family":"Arial",fill:this.config.labelFontColor,"fill-opacity":(this.config.showMinMax==true)?"1":"0"});this.txtMax.id=this.config.id+"-txtmax";var a=this.canvas.canvas.childNodes[1];var o="http://www.w3.org/2000/svg";if(ie<9){onCreateElementNsReady(function(){this.generateShadow()})}else{this.generateShadow(o,a)}this.level.animate({pki:[this.config.value,this.config.min,this.config.max,this.params.widgetW,this.params.widgetH,this.params.dx,this.params.dy,this.config.gaugeWidthScale]},this.config.startAnimationTime,this.config.startAnimationType);this.txtValue.animate({"fill-opacity":"1"},this.config.startAnimationTime,this.config.startAnimationType);this.txtLabel.animate({"fill-opacity":"1"},this.config.startAnimationTime,this.config.startAnimationType)};JustGage.prototype.refresh=function(b){originalVal=b;if(b>this.config.max){b=this.config.max}if(b",b[0]){}return a>4?a:c}()); -------------------------------------------------------------------------------- /web_sensor/main.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 23 | 24 | 25 | 26 |
27 | 28 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /web_sensor/raphael.2.1.0.min.js: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/simonmonk/raspberrypi_cookbook_ed2/3872e93059627533d0a509d3692ec28a7bd29991/web_sensor/raphael.2.1.0.min.js -------------------------------------------------------------------------------- /web_sensor/web_sensor.py: -------------------------------------------------------------------------------- 1 | import os, time 2 | from bottle import route, run, template 3 | 4 | def cpu_temp(): 5 | dev = os.popen('/opt/vc/bin/vcgencmd measure_temp') 6 | cpu_temp = dev.read()[5:-3] 7 | return cpu_temp 8 | 9 | @route('/temp') 10 | def temp(): 11 | return cpu_temp() 12 | 13 | @route('/') 14 | def index(): 15 | return template('main.html') 16 | 17 | @route('/raphael') 18 | def index(): 19 | return template('raphael.2.1.0.min.js') 20 | 21 | @route('/justgage') 22 | def index(): 23 | return template('justgage.1.0.1.min.js') 24 | 25 | run(host='0.0.0.0', port=80) --------------------------------------------------------------------------------