├── LICENSE ├── README.md ├── actor-7_2-colors ├── 2colors.py ├── 7colors.py ├── README.md ├── pic1.jpg └── pic2.jpg ├── actor-RGB-LED ├── README.md ├── images │ ├── 1.jpg │ ├── 10.jpg │ ├── 11.jpg │ ├── 12.jpg │ ├── 2.jpg │ ├── 3.jpg │ ├── 4.jpg │ ├── 5.jpg │ ├── 6.jpg │ ├── 7.jpg │ ├── 8.jpg │ └── 9.jpg ├── pic1.jpg ├── pic2.jpg ├── pic3.jpg ├── pic4.jpg ├── rgb.py └── rgbled.jpg ├── actor-alphanumeric-display-board ├── README.md ├── lcd-demo.py └── pic1.JPG ├── actor-graphic-TFT-display ├── README.md ├── pic1.JPG ├── pic2.JPG ├── pic3.JPG └── tft.txt ├── actor-infrared-transmitter ├── README.md ├── images │ └── ky005.JPG └── infrared-send.py ├── actor-led-7segment-4numbers ├── README.md ├── actor-led-7segment-4numbers.zip ├── clock.py ├── display.py ├── displayIP.py ├── pic1.JPG ├── pic2.JPG └── tm1637.py ├── actor-linksprite-OLED-display ├── README.md ├── datasheet_SAS1-9046-B-UG-2864HSWEG01-Univision.pdf ├── pic1.JPG └── textDemo.py ├── actor-linksprite-buzzer ├── README.md ├── buzzer.py ├── pic1.JPG └── pic2.jpg ├── actor-linksprite-led-bar ├── README.md ├── led-bar.py └── pic1.JPG ├── actor-relay ├── README.md ├── images │ └── ky019.jpg └── relay.py ├── doc ├── rpi-demo-asgs.pdf └── tricks.txt ├── example-applications ├── JoystickRainbow │ ├── README.md │ ├── joy.py │ ├── joystick.png │ └── setup.jpg ├── alarm_project │ ├── buzzer.py │ ├── flame.py │ ├── main.py │ ├── observer.py │ ├── rotary.py │ ├── sensor.py │ ├── stoppable.py │ └── temperature.py ├── analogInMqttOut-demo.py ├── analogInputDemo.py ├── mqttListener.py ├── mqttSender.py ├── presenter.py └── sensor1.py ├── extension-board ├── README.md ├── analogIn.py ├── analogInputDemo.py ├── images │ ├── boardv1.JPG │ ├── boardv2.jpg │ ├── description.png │ ├── ky051.JPG │ ├── ky053.JPG │ ├── schema.jpg │ ├── schema2.jpg │ ├── sensor1.JPG │ ├── sensor10.jpg │ ├── sensor11.jpg │ ├── sensor12.jpg │ ├── sensor13.jpg │ ├── sensor14.jpg │ ├── sensor15.jpg │ ├── sensor16.jpg │ ├── sensor2.JPG │ ├── sensor3.JPG │ ├── sensor4.JPG │ ├── sensor5.jpg │ ├── sensor6.jpg │ ├── sensor7.jpg │ ├── sensor8.jpg │ └── sensor9.jpg ├── ky051 │ └── README.md └── ky053 │ ├── Adafruit_ADS1x15.py │ ├── Adafruit_I2C.py │ ├── Adafruit_License_MIT.txt │ ├── KY-053_RPi_AnalogDigitalConverter.py │ └── README.md ├── sensor-HD-camera ├── README.md ├── cam-test.py ├── pic1.JPG └── pic2.JPG ├── sensor-button ├── README.md ├── button.py ├── images │ ├── ky004_0.jpg │ ├── ky004_1.jpg │ ├── lkbutton.jpg │ └── pic1.JPG └── lkbutton.py ├── sensor-flame ├── README.md ├── flame.py └── images │ ├── flameon.jpg │ └── ky026.jpg ├── sensor-infrared-receiver ├── README.md ├── images │ └── ky022.JPG └── infrared-recv.py ├── sensor-magnet ├── README.md └── images │ ├── pic1.jpg │ ├── pic2.jpg │ ├── pic3.jpg │ └── pic4.jpg ├── sensor-obstacle ├── README.md ├── images │ ├── ky032.jpg │ └── ky033.JPG ├── obstacle.py └── tracking.py ├── sensor-rotary-encoder ├── README.md ├── images │ └── rotary.jpg └── rotary.py ├── sensor-temperature ├── README.md ├── images │ ├── ky013.JPG │ ├── ky015.JPG │ ├── ky028.JPG │ └── ky052.JPG ├── ky013.py ├── ky015.py └── ky028.py ├── sensor-thumb-joystick ├── README.md ├── calibration.py ├── images │ ├── above.jpg │ ├── below.jpg │ ├── ky023.jpg │ ├── ky023connection.jpg │ └── rear.jpg ├── ky023.py └── thumbjoystick.py ├── sensor-tilt ├── README.md ├── images │ ├── ky017.jpg │ └── ky020.jpg └── tilt.py ├── sensor-touch ├── README.md ├── images │ └── ky036.jpg └── touch.py ├── sensor-ultrasonic-distance ├── README.md ├── datasheet_HCSR04.pdf ├── pic1.JPG ├── ultrasonic-distance.c └── ultrasonic-distance.py ├── sensor-vibration ├── README.md ├── images │ └── ky002.jpg └── vibration.py └── setup-raspberrypi ├── README.md ├── images ├── noobfiles.png ├── raspinstall.png ├── sdresetformatsize.png └── sdresetoption.png └── right_click.png /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2015, 2016 Tim Waizenegger at the University of Stuttgart Institute of Parallel and Distributed Systems 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 | # Uni Stuttgart IPVS/AS IoT examples 2 | This repo contains example code for various RPi Sensors/Actors used in IoT projects at the University of Stuttgart, IPVS/AS 3 | 4 | Each Folder contains an example script, picture, and additional information about one device 5 | 6 | ## System setup 7 | [Setup tutorials](setup-raspberrypi) contains information for installing, updating, reseting and issue solving on the OS Raspbian. 8 | 9 | ## List of devices 10 | 11 | ### Extension board 12 | * [Linksprite analog converter](extension-board) for data about the board and reading data from analog sensors linke: 13 | * [temperature, humidity and pressure](sensor-temperature), 14 | * light, 15 | * noise, 16 | * acceleration, 17 | * moisture, 18 | * potentiometer, 19 | * magnet, 20 | * heartbeat, 21 | * magic light cup, 22 | * knock, 23 | * photocell 24 | * [AD Converter](extension-board/ky053) 25 | * [Level Shifter](extension-board/ky051) 26 | 27 | ### Sensors 28 | * [Buttons](sensor-button) 29 | * [Thumb joystick](sensor-thumb-joystick) 30 | * [Ultrasonic distance sensor](sensor-ultrasonic-distance) 31 | * [HD camera](sensor-HD-camera) 32 | * [Touch](sensor-touch) 33 | * [Flame](sensor-flame) 34 | * [Obstacle Avoidance and Tracking](sensor-obstacle) 35 | * [Vibration](sensor-vibration) 36 | * [Tilt](sensor-tilt) 37 | * [Magnet](sensor-magnet) 38 | * [Infrared Receiver](sensor-infrared-receiver) 39 | * [Temperature, humidity and pressure](sensor-temperature) 40 | 41 | ### Actors 42 | * [Linksprite dumb buzzer](actor-linksprite-buzzer) 43 | * [Linksprite LED-Bar](actor-linksprite-led-bar) 44 | * [Linksprite 7-segment 4-number LED display](actor-led-7segment-4numbers) 45 | * [HD color TFT display](actor-graphic-TFT-display) 46 | * [Alphanumeric display board with 4 buttons](actor-alphanumeric-display-board) 47 | * [Linksprite 128x64 blue OLED display](actor-linksprite-OLED-display) 48 | * [RGB-LED](actor-RGB-LED) 49 | * [7 and 2 colors Led](actor-7_2-colors) 50 | * [Infrared Transmitter](actor-infrared-transmitter) 51 | 52 | 53 | 54 | ## Example applications 55 | [example-applications](example-applications/) contains some scripts that "actually do something" 56 | -------------------------------------------------------------------------------- /actor-7_2-colors/2colors.py: -------------------------------------------------------------------------------- 1 | # Benoetigte Module werden importiert und eingerichtet 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | 7 | # Hier werden die Ausgangs-Pin deklariert, an dem die LEDs angeschlossen sind. 8 | LED_ROT = 5 9 | LED_GRUEN = 4 10 | GPIO.setup(LED_ROT, GPIO.OUT, initial= GPIO.LOW) 11 | GPIO.setup(LED_GRUEN, GPIO.OUT, initial= GPIO.LOW) 12 | 13 | print "LED-Test [druecken Sie STRG+C, um den Test zu beenden]" 14 | 15 | # Hauptprogrammschleife 16 | try: 17 | while True: 18 | print("LED ROT 3 Sekunden an") 19 | GPIO.output(LED_ROT,GPIO.HIGH) #LED wird eingeschaltet 20 | GPIO.output(LED_GRUEN,GPIO.LOW) #LED wird eingeschaltet 21 | time.sleep(3) # Wartemodus fuer 4 Sekunden 22 | print("LED GRUEN 3 Sekunden an") 23 | GPIO.output(LED_ROT,GPIO.LOW) #LED wird eingeschaltet 24 | GPIO.output(LED_GRUEN,GPIO.HIGH) #LED wird eingeschaltet 25 | time.sleep(3) #Wartemodus fuer weitere zwei Sekunden, in denen die LED Dann ausgeschaltet ist 26 | 27 | # Aufraeumarbeiten nachdem das Programm beendet wurde 28 | except KeyboardInterrupt: 29 | GPIO.cleanup() 30 | -------------------------------------------------------------------------------- /actor-7_2-colors/7colors.py: -------------------------------------------------------------------------------- 1 | # Benoetigte Module werden importiert und eingerichtet 2 | import RPi.GPIO as GPIO 3 | import time 4 | 5 | GPIO.setmode(GPIO.BCM) 6 | 7 | # Hier wird der Eingangs-Pin deklariert, an dem der Sensor angeschlossen ist. Zusaetzlich wird auch der PullUP Widerstand am Eingang aktiviert 8 | LED_PIN = 24 9 | GPIO.setup(LED_PIN, GPIO.OUT, initial= GPIO.LOW) 10 | 11 | print "LED-Test [druecken Sie STRG+C, um den Test zu beenden]" 12 | 13 | # Hauptprogrammschleife 14 | try: 15 | while True: 16 | print("LED 4 Sekunden an") 17 | GPIO.output(LED_PIN,GPIO.HIGH) #LED wird eingeschaltet 18 | time.sleep(4) #Wartemodus fuer 4 Sekunden 19 | print("LED 2 Sekunden aus") 20 | GPIO.output(LED_PIN,GPIO.LOW) #LED wird ausgeschaltet 21 | time.sleep(2) #Wartemodus fuer weitere zwei Sekunden, in denen die LED Dann ausgeschaltet ist 22 | 23 | # Aufraeumarbeiten nachdem das Programm beendet wurde 24 | except KeyboardInterrupt: 25 | GPIO.cleanup() 26 | -------------------------------------------------------------------------------- /actor-7_2-colors/README.md: -------------------------------------------------------------------------------- 1 | ##7 Colors Led 2 | ![image](pic2.jpg) 3 | 4 | Example code [here](7colors.py) 5 | 6 | ##2 Colors Led 7 | 8 | ![image](pic1.jpg) 9 | Example code [here](2colors.py) 10 | 11 | 12 | ###Reference [here](http://sensorkit.joy-it.net/index.php?title=Hauptseite) 13 | -------------------------------------------------------------------------------- /actor-7_2-colors/pic1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-7_2-colors/pic1.jpg -------------------------------------------------------------------------------- /actor-7_2-colors/pic2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-7_2-colors/pic2.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/README.md: -------------------------------------------------------------------------------- 1 | ##KY-016 RGB 5mm LED / KY-009 RGB LED SMD 2 | ![image](pic3.jpg) 3 | ![image](pic4.jpg) 4 | 5 | Example code [here](rgb.py) 6 | 7 | ### Code Colors 8 | Based on the raspberry code of [sensorkit.joy-it.net](http://sensorkit.joy-it.net/index.php?title=KY-016_RGB_5mm_LED_Modul) 9 | 10 | . |. | . 11 | ------------ | ------------- | ------- 12 | ![red](images/1.jpg) | ![red](images/2.jpg) | ![red](images/3.jpg) 13 | LED_Farbe(100,0,0,1) - **RED** | LED_Farbe(100,50,0,1) - **ORANGE** | LED_Farbe(100,100,0,1) - **YELLOW** 14 | ![red](images/4.jpg) | ![red](images/5.jpg) | ![red](images/6.jpg) 15 | LED_Farbe(50,100,0,1) - **LIGHT GREEN** | LED_Farbe(0,100,0,1) - **GREEN** | LED_Farbe(0,100,50,1) - **AQUA** 16 | ![red](images/7.jpg) | ![red](images/8.jpg) | ![red](images/9.jpg) 17 | LED_Farbe(0,100,100,1) - **CYAN** | LED_Farbe(0,50,100,1) - **LIGHT BLUE** | LED_Farbe(0,0,100,1) - **BLUE** 18 | ![red](images/10.jpg)| ![red](images/11.jpg) | ![red](images/12.jpg) 19 | LED_Farbe(50,0,100,1) - **PURPLE** | LED_Farbe(100,0,100,1) - **MAGENTA** | LED_Farbe(100,0,50,1) - **PINK** 20 | 21 | ##Linker-Kit RGB Led 22 | 23 | ![image](rgbled.jpg) 24 | 25 | * RGB 26 | * 8mm 27 | * Chipset WS2812 28 | * Working voltage: 3 V ~ 5 V 29 | 30 | 31 | ## get it running 32 | 33 | Connect the RGB led on pin 12: 34 | 35 | ![image](pic2.jpg) 36 | 37 | Then: 38 | 39 | git clone https://github.com/jgarff/rpi_ws281x.git 40 | cd rpi_ws281x.git 41 | sudo apt-get install scons swig 42 | sudo scons 43 | cd python 44 | sudo python ez_setup.py 45 | sudo python setup.py install 46 | 47 | cd examples 48 | python strandtest.py 49 | 50 | 51 | 52 | ![image](pic1.jpg) 53 | -------------------------------------------------------------------------------- /actor-RGB-LED/images/1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/1.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/10.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/11.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/11.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/12.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/12.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/2.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/3.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/4.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/5.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/6.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/7.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/8.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/images/9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/images/9.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/pic1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/pic1.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/pic2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/pic2.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/pic3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/pic3.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/pic4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/pic4.jpg -------------------------------------------------------------------------------- /actor-RGB-LED/rgb.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | 3 | GPIO.setmode(GPIO.BCM) 4 | 5 | GPIO.setup(14, GPIO.OUT) #red 6 | GPIO.output(14,1) 7 | GPIO.setup(13, GPIO.OUT) #green 8 | GPIO.output(13,1) 9 | GPIO.setup(12, GPIO.OUT) #blue 10 | GPIO.output(12,1) 11 | 12 | try: 13 | while(True): 14 | request = raw_input("RGB-->") 15 | if (len(request) == 3): 16 | GPIO.output(14, int(request[0])) 17 | GPIO.output(13, int(request[1])) 18 | GPIO.output(12, int(request[2])) 19 | except KeyboardInterrupt: 20 | GPIO.cleanup() 21 | -------------------------------------------------------------------------------- /actor-RGB-LED/rgbled.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-RGB-LED/rgbled.jpg -------------------------------------------------------------------------------- /actor-alphanumeric-display-board/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ![image of device](pic1.JPG) 4 | -------------------------------------------------------------------------------- /actor-alphanumeric-display-board/lcd-demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | this script demos the graphic character LCD with 4 Buttons. 5 | it requires the RPLCD module. install with: 6 | sudo pip install RPLCD 7 | 8 | """ 9 | 10 | from __future__ import print_function, division, absolute_import, unicode_literals 11 | 12 | import sys 13 | 14 | from RPLCD import CharLCD 15 | from RPLCD import Alignment, CursorMode, ShiftMode 16 | from RPLCD import cursor, cleared 17 | import RPi.GPIO as GPIO 18 | import time 19 | 20 | 21 | try: 22 | input = raw_input 23 | except NameError: 24 | pass 25 | 26 | try: 27 | unichr = unichr 28 | except NameError: 29 | unichr = chr 30 | 31 | 32 | def initButtons(): 33 | GPIO.setmode(GPIO.BCM) 34 | GPIO.setup(4, GPIO.IN, pull_up_down=GPIO.PUD_UP) 35 | GPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP) 36 | GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_UP) 37 | GPIO.setup(9, GPIO.IN, pull_up_down=GPIO.PUD_UP) 38 | 39 | def checkSwitch(): 40 | v0 = not GPIO.input(4) 41 | v1 = not GPIO.input(23) 42 | v2 = not GPIO.input(10) 43 | v3 = not GPIO.input(9) 44 | return v3, v0, v1, v2 45 | #return v0, v1, v2, v3 46 | 47 | 48 | 49 | #lcd = CharLCD(cols=16, rows=2) 50 | #lcd = CharLCD(pin_rs=15, pin_rw=18, pin_e=16, pins_data=[21, 22, 23, 24], numbering_mode=GPIO.BOARD, cols=20, rows=4, dotsize=8) 51 | lcd = CharLCD(pin_rs=7, pin_e=8, pins_data=[17, 18, 27, 22], numbering_mode=GPIO.BCM, cols=16, rows=2, dotsize=8) 52 | 53 | lcd.write_string('Hi :)') 54 | lcd.home() 55 | 56 | 57 | initButtons() 58 | 59 | while (True): 60 | #print(checkSwitch()) 61 | v = checkSwitch() 62 | time.sleep(0.5) 63 | lcd.home() 64 | lcd.clear() 65 | lcd.write_string(str(v)) 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | """ 83 | input('Display should be blank. ') 84 | 85 | lcd.cursor_mode = CursorMode.blink 86 | input('The cursor should now blink. ') 87 | 88 | lcd.cursor_mode = CursorMode.line 89 | input('The cursor should now be a line. ') 90 | 91 | lcd.write_string('Hello world!') 92 | input('"Hello world!" should be on the LCD. ') 93 | 94 | assert lcd.cursor_pos == (0, 12), 'cursor_pos should now be (0, 12)' 95 | 96 | lcd.cursor_pos = (0, 15) 97 | lcd.write_string('1') 98 | lcd.cursor_pos = (1, 15) 99 | lcd.write_string('2') 100 | assert lcd.cursor_pos == (0, 0), 'cursor_pos should now be (0, 0)' 101 | input('Lines 1 and 2 should now be labelled with the right numbers on the right side. ') 102 | 103 | lcd.clear() 104 | input('Display should now be clear, cursor should be at initial position. ') 105 | 106 | lcd.cursor_pos = (0, 5) 107 | lcd.write_string('12345') 108 | input('The string should have a left offset of 5 characters. ') 109 | 110 | lcd.write_shift_mode = ShiftMode.display 111 | lcd.cursor_pos = (1, 5) 112 | lcd.write_string('12345') 113 | input('Both strings should now be at column 0. ') 114 | 115 | lcd.write_shift_mode = ShiftMode.cursor 116 | lcd.cursor_pos = (1, 5) 117 | lcd.write_string(lcd.write_shift_mode.name) 118 | input('The string "cursor" should now be on the second row, column 0. ') 119 | 120 | lcd.home() 121 | input('Cursor should now be at initial position. Everything should be shifted to the right by 5 characters. ') 122 | 123 | with cursor(lcd, 1, 15): 124 | lcd.write_string('X') 125 | input('The last character on the LCD should now be an "X"') 126 | 127 | lcd.display_enabled = False 128 | input('Display should now be blank. ') 129 | 130 | with cleared(lcd): 131 | lcd.write_string('Eggs, Ham\n\rand Spam') 132 | lcd.display_enabled = True 133 | input('Display should now show "Eggs, Ham and Spam" with a line break after "Ham". ') 134 | 135 | lcd.shift_display(4) 136 | input('Text should now be shifted to the right by 4 characters. ') 137 | lcd.shift_display(-4) 138 | input('Shift should now be undone. ') 139 | 140 | lcd.text_align_mode = Alignment.right 141 | lcd.write_string(' Spam') 142 | input('The word "Spam" should now be inverted. ') 143 | 144 | lcd.text_align_mode = Alignment.left 145 | lcd.write_string(' Wurscht') 146 | input('The word "mapS" should now be replaced with "Wurscht". ') 147 | 148 | lcd.clear() 149 | lcd.write_string('1\n') 150 | lcd.write_string('2\n') 151 | lcd.cursor_pos = (0, 2) 152 | lcd.write_string('3\n') 153 | lcd.write_string('4') 154 | lcd.cursor_pos = (0, 4) 155 | lcd.write_string('5\n') 156 | lcd.write_string('6') 157 | input('The numbers 1-6 should now be displayed in a zig zag line starting in the top left corner. ') 158 | 159 | lcd.clear() 160 | lcd.write_string('This will wrap around both lines') 161 | input('Text should nicely wrap around lines. ') 162 | 163 | lcd.clear() 164 | lcd.cursor_mode = CursorMode.hide 165 | lcd.write_string('Paris: 21{deg}C\n\rZ{uuml}rich: 18{deg}C'.format(deg=unichr(176), uuml=unichr(129))) 166 | print('Text should now show "Paris: 21°C, Zürich: 18°C" without any encoding issues.', end='') 167 | input() 168 | 169 | # Test custom chars 170 | lcd.clear() 171 | happy = (0b00000, 0b01010, 0b01010, 0b00000, 0b10001, 0b10001, 0b01110, 0b00000) 172 | sad = (0b00000, 0b01010, 0b01010, 0b00000, 0b01110, 0b10001, 0b10001, 0b00000) 173 | lcd.create_char(0, sad) 174 | lcd.write_string(unichr(0)) 175 | lcd.create_char(1, happy) 176 | lcd.write_string(unichr(1)) 177 | input('You should now see a sad and a happy face next to each other. ') 178 | lcd.create_char(0, happy) 179 | lcd.home() 180 | lcd.write_string(unichr(0)) 181 | input('Now both faces should be happy. ') 182 | """ 183 | 184 | 185 | print('done.') 186 | 187 | -------------------------------------------------------------------------------- /actor-alphanumeric-display-board/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-alphanumeric-display-board/pic1.JPG -------------------------------------------------------------------------------- /actor-graphic-TFT-display/README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ![image of device](pic1.JPG) 4 | ![image of device](pic2.JPG) 5 | ![image of device](pic3.JPG) 6 | -------------------------------------------------------------------------------- /actor-graphic-TFT-display/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-graphic-TFT-display/pic1.JPG -------------------------------------------------------------------------------- /actor-graphic-TFT-display/pic2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-graphic-TFT-display/pic2.JPG -------------------------------------------------------------------------------- /actor-graphic-TFT-display/pic3.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-graphic-TFT-display/pic3.JPG -------------------------------------------------------------------------------- /actor-graphic-TFT-display/tft.txt: -------------------------------------------------------------------------------- 1 | # configuration for the SAINSMART LCD/TFT display 2 | 3 | # sudo modprobe fbtft_device name=sainsmart18 4 | # sudo fbi -noverbose -T 1 -a -d /dev/fb1 /usr/share/icons/gnome/256x256/status/dialog-* 5 | 6 | 7 | # connection to RPI: 8 | # TFT-->RPI 9 | # 1 1 (VCC 3.3V) 10 | # 2 6 (GND) 11 | # 3 23 (SPI_CLK) 12 | # 4 19 (SPI_MOSI) 13 | # 5 18 (GPIO_GEN5) 14 | # 6 22 (GPIO_GEN6) 15 | # 7 24 (SPI_CE0_N) 16 | 17 | -------------------------------------------------------------------------------- /actor-infrared-transmitter/README.md: -------------------------------------------------------------------------------- 1 | ## Actor KY-005: Infrared Transmitter 2 | 3 | This actor was tested together with the [sensor infrared receiver](../sensor-infrared-receiver). 4 | 5 | ![ky005](images/ky005.JPG) 6 | 7 | The pins for the extension board, where (`sensor: board`) - following the [example code](infrared-send.py): 8 | * -: G 9 | * (middle pin): V 10 | * S: D16 11 | -------------------------------------------------------------------------------- /actor-infrared-transmitter/images/ky005.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-infrared-transmitter/images/ky005.JPG -------------------------------------------------------------------------------- /actor-infrared-transmitter/infrared-send.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | import binascii as ba 4 | import sys 5 | 6 | sendPin = 16 7 | bittime = 1 8 | 9 | GPIO.setmode(GPIO.BCM) 10 | GPIO.setup(sendPin, GPIO.OUT) 11 | 12 | while True: 13 | GPIO.output(sendPin, GPIO.HIGH) 14 | time.sleep(bittime) 15 | GPIO.output(sendPin, GPIO.LOW) 16 | time.sleep(bittime) -------------------------------------------------------------------------------- /actor-led-7segment-4numbers/README.md: -------------------------------------------------------------------------------- 1 | tm1637.py is a driver library; display.py, displayIP.py, and clock.py all show its use 2 | 3 | ###Pins connection 4 | 5 | | Board Pin | Name | Remarks | RPi Pin | RPi Function | 6 | |----------:|:-----|:------------|--------:|-------------------| 7 | | 1 | GND | Ground | 2 | 5V0 | 8 | | 2 | VCC | +5V Power | 6 | GND | 9 | | 3 | DIN | Data In | 38 | GPIO 20 | 10 | | 4 | CLK | Clock | 40 | GPIO 21 | 11 | 12 | ![image of device](pic1.JPG) 13 | 14 | ![image of another clock](pic2.JPG) 15 | 16 | 17 | 18 | *Note: Most GPIO pins will work in place of the above pins (Such as DIN - GPIO 24 & CLK- GPIO 23)* 19 | -------------------------------------------------------------------------------- /actor-led-7segment-4numbers/actor-led-7segment-4numbers.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-led-7segment-4numbers/actor-led-7segment-4numbers.zip -------------------------------------------------------------------------------- /actor-led-7segment-4numbers/clock.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from time import sleep 5 | import tm1637 6 | 7 | try: 8 | import thread 9 | except ImportError: 10 | import _thread as thread 11 | 12 | # Initialize the clock (GND, VCC=3.3V, Example Pins are DIO-20 and CLK21) 13 | Display = tm1637.TM1637(CLK=21, DIO=20, brightness=1.0) 14 | 15 | try: 16 | print "Starting clock in the background (press CTRL + C to stop):" 17 | Display.StartClock(military_time=False) 18 | print 'Continue Python script and tweak Display!' 19 | sleep(5) 20 | Display.ShowDoublepoint(False) 21 | sleep(5) 22 | loops = 3 23 | while loops > 0: 24 | for i in range(0, 10): 25 | Display.SetBrightness(i / 10.0) 26 | sleep(0.5) 27 | loops -= 1 28 | Display.StopClock() 29 | thread.interrupt_main() 30 | except KeyboardInterrupt: 31 | print "Properly closing the clock and open GPIO pins" 32 | Display.cleanup() 33 | -------------------------------------------------------------------------------- /actor-led-7segment-4numbers/display.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | from time import sleep 5 | import tm1637 6 | 7 | # Initialize the display (GND, VCC=3.3V, Example Pins are DIO-20 and CLK21) 8 | Display = tm1637.TM1637(CLK=21, DIO=20, brightness=1.0) 9 | 10 | # Basic Display Update: 11 | digits = [1, 2, 3, 4] 12 | Display.Show(digits) 13 | print "1234 - Working? (Press Key)" 14 | scrap = raw_input() 15 | 16 | # Update Individual Digits: 17 | print "Updating one digit at a time:" 18 | Display.Clear() 19 | Display.Show1(1, 3) 20 | sleep(0.5) 21 | Display.Show1(2, 2) 22 | sleep(0.5) 23 | Display.Show1(3, 1) 24 | sleep(0.5) 25 | Display.Show1(0, 4) 26 | print "4321 - (Press Key)" 27 | scrap = raw_input() 28 | 29 | # The ":" 30 | print "Add double point\n" 31 | Display.ShowDoublepoint(True) 32 | sleep(0.2) 33 | 34 | # Vary the brightness: 35 | print "Brightness Off" 36 | Display.SetBrightness(0) 37 | sleep(0.5) 38 | print "Full Brightness" 39 | Display.SetBrightness(1) 40 | sleep(0.5) 41 | print "30% Brightness" 42 | Display.SetBrightness(0.3) 43 | sleep(0.3) 44 | 45 | print('done.') 46 | Display.cleanup() 47 | -------------------------------------------------------------------------------- /actor-led-7segment-4numbers/displayIP.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import time 5 | import tm1637 6 | import socket 7 | 8 | # Initialize the display (GND, VCC=3.3V, Example Pins are DIO-20 and CLK21) 9 | Display = tm1637.TM1637(CLK=21, DIO=20, brightness=0.3) 10 | 11 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 12 | s.connect(("gmail.com", 80)) 13 | IP = s.getsockname()[0] 14 | 15 | s.close() 16 | 17 | print "IP of RasPi is" 18 | print IP 19 | 20 | # Separate on comma. 21 | numbers = IP.split(".") 22 | 23 | # Loop and print each city name. 24 | loops = 3 25 | while loops > 0: 26 | for number in numbers: 27 | Display.ShowInt(number) 28 | time.sleep(2) 29 | loops -= 1 30 | Display.Clear() 31 | time.sleep(2) 32 | 33 | print('done.') 34 | Display.cleanup() 35 | -------------------------------------------------------------------------------- /actor-led-7segment-4numbers/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-led-7segment-4numbers/pic1.JPG -------------------------------------------------------------------------------- /actor-led-7segment-4numbers/pic2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-led-7segment-4numbers/pic2.JPG -------------------------------------------------------------------------------- /actor-led-7segment-4numbers/tm1637.py: -------------------------------------------------------------------------------- 1 | import math 2 | import RPi.GPIO as IO 3 | import threading 4 | from time import sleep, localtime 5 | # from tqdm import tqdm 6 | 7 | # IO.setwarnings(False) 8 | IO.setmode(IO.BCM) 9 | 10 | HexDigits = [0x3f, 0x06, 0x5b, 0x4f, 0x66, 0x6d, 0x7d, 11 | 0x07, 0x7f, 0x6f, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71] 12 | 13 | ADDR_AUTO = 0x40 14 | ADDR_FIXED = 0x44 15 | STARTADDR = 0xC0 16 | # DEBUG = False 17 | 18 | 19 | class TM1637: 20 | __doublePoint = False 21 | __Clkpin = 0 22 | __Datapin = 0 23 | __brightness = 1.0 # default to max brightness 24 | __currentData = [0, 0, 0, 0] 25 | 26 | def __init__(self, CLK, DIO, brightness): 27 | self.__Clkpin = CLK 28 | self.__Datapin = DIO 29 | self.__brightness = brightness 30 | IO.setup(self.__Clkpin, IO.OUT) 31 | IO.setup(self.__Datapin, IO.OUT) 32 | 33 | def cleanup(self): 34 | """Stop updating clock, turn off display, and cleanup GPIO""" 35 | self.StopClock() 36 | self.Clear() 37 | IO.cleanup() 38 | 39 | def Clear(self): 40 | b = self.__brightness 41 | point = self.__doublePoint 42 | self.__brightness = 0 43 | self.__doublePoint = False 44 | data = [0x7F, 0x7F, 0x7F, 0x7F] 45 | self.Show(data) 46 | # Restore previous settings: 47 | self.__brightness = b 48 | self.__doublePoint = point 49 | 50 | def ShowInt(self, i): 51 | s = str(i) 52 | self.Clear() 53 | for i in range(0, len(s)): 54 | self.Show1(i, int(s[i])) 55 | 56 | def Show(self, data): 57 | for i in range(0, 4): 58 | self.__currentData[i] = data[i] 59 | 60 | self.start() 61 | self.writeByte(ADDR_AUTO) 62 | self.br() 63 | self.writeByte(STARTADDR) 64 | for i in range(0, 4): 65 | self.writeByte(self.coding(data[i])) 66 | self.br() 67 | self.writeByte(0x88 + int(self.__brightness)) 68 | self.stop() 69 | 70 | def Show1(self, DigitNumber, data): 71 | """show one Digit (number 0...3)""" 72 | if(DigitNumber < 0 or DigitNumber > 3): 73 | return # error 74 | 75 | self.__currentData[DigitNumber] = data 76 | 77 | self.start() 78 | self.writeByte(ADDR_FIXED) 79 | self.br() 80 | self.writeByte(STARTADDR | DigitNumber) 81 | self.writeByte(self.coding(data)) 82 | self.br() 83 | self.writeByte(0x88 + int(self.__brightness)) 84 | self.stop() 85 | 86 | def SetBrightness(self, percent): 87 | """Accepts percent brightness from 0 - 1""" 88 | max_brightness = 7.0 89 | brightness = math.ceil(max_brightness * percent) 90 | if (brightness < 0): 91 | brightness = 0 92 | if(self.__brightness != brightness): 93 | self.__brightness = brightness 94 | self.Show(self.__currentData) 95 | 96 | def ShowDoublepoint(self, on): 97 | """Show or hide double point divider""" 98 | if(self.__doublePoint != on): 99 | self.__doublePoint = on 100 | self.Show(self.__currentData) 101 | 102 | def writeByte(self, data): 103 | for i in range(0, 8): 104 | IO.output(self.__Clkpin, IO.LOW) 105 | if(data & 0x01): 106 | IO.output(self.__Datapin, IO.HIGH) 107 | else: 108 | IO.output(self.__Datapin, IO.LOW) 109 | data = data >> 1 110 | IO.output(self.__Clkpin, IO.HIGH) 111 | 112 | # wait for ACK 113 | IO.output(self.__Clkpin, IO.LOW) 114 | IO.output(self.__Datapin, IO.HIGH) 115 | IO.output(self.__Clkpin, IO.HIGH) 116 | IO.setup(self.__Datapin, IO.IN) 117 | 118 | while(IO.input(self.__Datapin)): 119 | sleep(0.001) 120 | if(IO.input(self.__Datapin)): 121 | IO.setup(self.__Datapin, IO.OUT) 122 | IO.output(self.__Datapin, IO.LOW) 123 | IO.setup(self.__Datapin, IO.IN) 124 | IO.setup(self.__Datapin, IO.OUT) 125 | 126 | def start(self): 127 | """send start signal to TM1637""" 128 | IO.output(self.__Clkpin, IO.HIGH) 129 | IO.output(self.__Datapin, IO.HIGH) 130 | IO.output(self.__Datapin, IO.LOW) 131 | IO.output(self.__Clkpin, IO.LOW) 132 | 133 | def stop(self): 134 | IO.output(self.__Clkpin, IO.LOW) 135 | IO.output(self.__Datapin, IO.LOW) 136 | IO.output(self.__Clkpin, IO.HIGH) 137 | IO.output(self.__Datapin, IO.HIGH) 138 | 139 | def br(self): 140 | """terse break""" 141 | self.stop() 142 | self.start() 143 | 144 | def coding(self, data): 145 | if(self.__doublePoint): 146 | pointData = 0x80 147 | else: 148 | pointData = 0 149 | 150 | if(data == 0x7F): 151 | data = 0 152 | else: 153 | data = HexDigits[data] + pointData 154 | return data 155 | 156 | def clock(self, military_time): 157 | """Clock script modified from: 158 | https://github.com/johnlr/raspberrypi-tm1637""" 159 | self.ShowDoublepoint(True) 160 | while (not self.__stop_event.is_set()): 161 | t = localtime() 162 | hour = t.tm_hour 163 | if not military_time: 164 | hour = 12 if (t.tm_hour % 12) == 0 else t.tm_hour % 12 165 | d0 = hour // 10 if hour // 10 else 0 166 | d1 = hour % 10 167 | d2 = t.tm_min // 10 168 | d3 = t.tm_min % 10 169 | digits = [d0, d1, d2, d3] 170 | self.Show(digits) 171 | # # Optional visual feedback of running alarm: 172 | # print digits 173 | # for i in tqdm(range(60 - t.tm_sec)): 174 | for i in range(60 - t.tm_sec): 175 | if (not self.__stop_event.is_set()): 176 | sleep(1) 177 | 178 | def StartClock(self, military_time=True): 179 | # Stop event based on: http://stackoverflow.com/a/6524542/3219667 180 | self.__stop_event = threading.Event() 181 | self.__clock_thread = threading.Thread( 182 | target=self.clock, args=(military_time,)) 183 | self.__clock_thread.start() 184 | 185 | def StopClock(self): 186 | try: 187 | print 'Attempting to stop live clock' 188 | self.__stop_event.set() 189 | except: 190 | print 'No clock to close' 191 | 192 | 193 | if __name__ == "__main__": 194 | """Confirm the display operation""" 195 | display = TM1637(CLK=21, DIO=20, brightness=1.0) 196 | 197 | display.Clear() 198 | 199 | digits = [1, 2, 3, 4] 200 | display.Show(digits) 201 | print "1234 - Working? (Press Key)" 202 | scrap = raw_input() 203 | 204 | print "Updating one digit at a time:" 205 | display.Clear() 206 | display.Show1(1, 3) 207 | sleep(0.5) 208 | display.Show1(2, 2) 209 | sleep(0.5) 210 | display.Show1(3, 1) 211 | sleep(0.5) 212 | display.Show1(0, 4) 213 | print "4321 - (Press Key)" 214 | scrap = raw_input() 215 | 216 | print "Add double point\n" 217 | display.ShowDoublepoint(True) 218 | sleep(0.2) 219 | print "Brightness Off" 220 | display.SetBrightness(0) 221 | sleep(0.5) 222 | print "Full Brightness" 223 | display.SetBrightness(1) 224 | sleep(0.5) 225 | print "30% Brightness" 226 | display.SetBrightness(0.3) 227 | sleep(0.3) 228 | 229 | # See clock.py for how to use the clock functions! 230 | -------------------------------------------------------------------------------- /actor-linksprite-OLED-display/README.md: -------------------------------------------------------------------------------- 1 | linksprite OLED board 2 | 3 | * 128x64 pixel 4 | * Communication interface: IIC 5 | * Driver IC: SSD1306 6 | * Working voltage: 3.3 V ~ 5.5 V 7 | * Working temperature: – 30 ℃ ~ 70 ℃ 8 | * Display color: mono color (blue) 9 | 10 | 11 | 12 | ## get it running 13 | 14 | use "raspi-config" to enable I2C interface 15 | 16 | 17 | git clone https://github.com/adafruit/Adafruit_Python_SSD1306.git 18 | cd Adafruit_Python_SSD1306 19 | sudo python setup.py install 20 | sudo apt-get install build-essential libi2c-dev i2c-tools python-dev libffi-dev 21 | sudo pip install smbus-cffi 22 | 23 | cd examples 24 | python image.py 25 | 26 | 27 | 28 | ![image](pic1.JPG) 29 | -------------------------------------------------------------------------------- /actor-linksprite-OLED-display/datasheet_SAS1-9046-B-UG-2864HSWEG01-Univision.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-linksprite-OLED-display/datasheet_SAS1-9046-B-UG-2864HSWEG01-Univision.pdf -------------------------------------------------------------------------------- /actor-linksprite-OLED-display/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-linksprite-OLED-display/pic1.JPG -------------------------------------------------------------------------------- /actor-linksprite-OLED-display/textDemo.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import math 3 | import time 4 | 5 | import Adafruit_GPIO.SPI as SPI 6 | import Adafruit_SSD1306 7 | 8 | from PIL import Image 9 | from PIL import ImageFont 10 | from PIL import ImageDraw 11 | 12 | 13 | # Raspberry Pi pin configuration: 14 | RST = 24 15 | # Note the following are only used with SPI: 16 | DC = 23 17 | SPI_PORT = 0 18 | SPI_DEVICE = 0 19 | 20 | disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST) 21 | 22 | 23 | # Initialize library. 24 | disp.begin() 25 | 26 | 27 | # Get display width and height. 28 | width = disp.width 29 | height = disp.height 30 | 31 | # Clear display. 32 | disp.clear() 33 | disp.display() 34 | 35 | # Create image buffer. 36 | # Make sure to create image with mode '1' for 1-bit color. 37 | image = Image.new('1', (width, height)) 38 | 39 | # Load default font. 40 | #font = ImageFont.load_default(fontsize=100) 41 | font = ImageFont.truetype("/usr/share/fonts/truetype/freefont/FreeSans.ttf", 50) 42 | 43 | # Create drawing object. 44 | draw = ImageDraw.Draw(image) 45 | 46 | 47 | text= "Juhuu!" 48 | 49 | 50 | # draw the text 51 | draw.rectangle((0,0,width,height), outline=0, fill=0) 52 | 53 | draw.text((0, 0), text, font=font, fill=255) 54 | 55 | disp.image(image) 56 | disp.display() 57 | 58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /actor-linksprite-buzzer/README.md: -------------------------------------------------------------------------------- 1 | this is the manual/dumb buzzer. it's only a speaker so you need to feed it a waveform 2 | 3 | ![image of device](pic1.JPG) 4 | 5 | Below we have the Active and Passive Buzzer 6 | 7 | ![image of device](pic2.jpg) 8 | 9 | The passive works like the LK-buzzer, just plug the ground (black), vcc (red) and the data (yellow) cables and it will work. 10 | 11 | The active works with the same configuration, but you will need some code modifications because it inicial state is to do noise. 12 | -------------------------------------------------------------------------------- /actor-linksprite-buzzer/buzzer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | 9 | 10 | 11 | pd = 27 #DATA PIN 12 | 13 | 14 | 15 | 16 | # freq in Hz 17 | def buzz(duration, freq): 18 | GPIO.output(pd, 0) 19 | for i in range(1,duration): 20 | GPIO.output(pd, 1) 21 | time.sleep(0.001) 22 | GPIO.output(pd, 0) 23 | time.sleep(1.0/freq) 24 | 25 | GPIO.output(pd, 0) 26 | 27 | 28 | 29 | def setup(): 30 | GPIO.setwarnings(False) 31 | GPIO.setmode(GPIO.BCM) 32 | GPIO.setup(pd, GPIO.OUT) 33 | GPIO.output(pd, 0) 34 | 35 | 36 | 37 | def buzzPwm(duration, freq): 38 | p = GPIO.PWM(pd,freq) 39 | p.start(50) 40 | time.sleep(float(duration)/1000) 41 | p.stop() 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | setup() 57 | while(True): 58 | for i in range(100,10000,100): 59 | buzz(10,i) 60 | #for i in reversed(range(100,10000,100)): 61 | # buzz(10,i) 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | print('done.') 70 | 71 | -------------------------------------------------------------------------------- /actor-linksprite-buzzer/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-linksprite-buzzer/pic1.JPG -------------------------------------------------------------------------------- /actor-linksprite-buzzer/pic2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-linksprite-buzzer/pic2.jpg -------------------------------------------------------------------------------- /actor-linksprite-led-bar/README.md: -------------------------------------------------------------------------------- 1 | shows a bar of multiple red LEDs 2 | 3 | ![image of device](pic1.JPG) 4 | -------------------------------------------------------------------------------- /actor-linksprite-led-bar/led-bar.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | 6 | import RPi.GPIO as GPIO 7 | import time 8 | 9 | 10 | 11 | 12 | pd = 17 #DATA IN 13 | pc = 18 #CLK IN 14 | 15 | CmdMode = 0x0000 # Work on 8-bit mode 16 | ON = 0x00ff # 8-bit 1 data 17 | OFF = 0x0000 # 8-bit 0 data 18 | 19 | 20 | def isBitSet(x, n): 21 | return (x & n**2) != 0 22 | 23 | def sendData(d): 24 | clk = True 25 | GPIO.output(pc,0) 26 | time.sleep(0.0005) 27 | for i in range(1,17): 28 | GPIO.output(pc,clk) 29 | GPIO.output(pd,isBitSet(d,i)) 30 | clk = not clk 31 | time.sleep(0.00001) 32 | GPIO.output(pc,0) 33 | time.sleep(0.0005) 34 | 35 | def latchData(): 36 | l = False 37 | GPIO.output(pd,0) 38 | time.sleep(0.0005) 39 | for i in range(1,9): 40 | GPIO.output(pd,l) 41 | l = not l 42 | time.sleep(0.0005) 43 | 44 | 45 | 46 | 47 | def setup(): 48 | GPIO.setwarnings(False) 49 | GPIO.setmode(GPIO.BCM) 50 | GPIO.setup(pd, GPIO.OUT) 51 | GPIO.setup(pc, GPIO.OUT) 52 | GPIO.output(pd,0) 53 | GPIO.output(pc,0) 54 | #sendData(CmdMode) 55 | for i in range(1,13): 56 | sendData(OFF) 57 | latchData() 58 | 59 | def sendLedArray(l): 60 | #sendData(CmdMode) 61 | for i in l: 62 | if i: 63 | sendData(ON) 64 | else: 65 | sendData(OFF) 66 | latchData() 67 | 68 | 69 | 70 | def pattern_countUp(): 71 | sendLedArray([1,0,0,0,0,0,0,0,0,0,0,0]) 72 | time.sleep(0.1) 73 | sendLedArray([1,1,0,0,0,0,0,0,0,0,0,0]) 74 | time.sleep(0.1) 75 | sendLedArray([1,1,1,0,0,0,0,0,0,0,0,0]) 76 | time.sleep(0.1) 77 | sendLedArray([1,1,1,1,0,0,0,0,0,0,0,0]) 78 | time.sleep(0.1) 79 | sendLedArray([1,1,1,1,1,0,0,0,0,0,0,0]) 80 | time.sleep(0.1) 81 | sendLedArray([1,1,1,1,1,1,0,0,0,0,0,0]) 82 | time.sleep(0.1) 83 | sendLedArray([1,1,1,1,1,1,1,0,0,0,0,0]) 84 | time.sleep(0.1) 85 | sendLedArray([1,1,1,1,1,1,1,1,0,0,0,0]) 86 | time.sleep(0.1) 87 | sendLedArray([1,1,1,1,1,1,1,1,1,0,0,0]) 88 | time.sleep(0.1) 89 | sendLedArray([1,1,1,1,1,1,1,1,1,1,0,0]) 90 | 91 | 92 | def pattern_Kitt(): 93 | sendLedArray([1,0,0,0,0,0,0,0,0,0,0,0]) 94 | time.sleep(0.1) 95 | sendLedArray([0,1,0,0,0,0,0,0,0,0,0,0]) 96 | time.sleep(0.1) 97 | sendLedArray([0,0,1,0,0,0,0,0,0,0,0,0]) 98 | time.sleep(0.1) 99 | sendLedArray([0,0,0,1,0,0,0,0,0,0,0,0]) 100 | time.sleep(0.1) 101 | sendLedArray([0,0,0,0,1,0,0,0,0,0,0,0]) 102 | time.sleep(0.1) 103 | sendLedArray([0,0,0,0,0,1,0,0,0,0,0,0]) 104 | time.sleep(0.1) 105 | sendLedArray([0,0,0,0,0,0,1,0,0,0,0,0]) 106 | time.sleep(0.1) 107 | sendLedArray([0,0,0,0,0,0,0,1,0,0,0,0]) 108 | time.sleep(0.1) 109 | sendLedArray([0,0,0,0,0,0,0,0,1,0,0,0]) 110 | time.sleep(0.1) 111 | sendLedArray([0,0,0,0,0,0,0,0,0,1,0,0]) 112 | time.sleep(0.1) 113 | sendLedArray([0,0,0,0,0,0,0,0,1,0,0,0]) 114 | time.sleep(0.1) 115 | sendLedArray([0,0,0,0,0,0,0,1,0,0,0,0]) 116 | time.sleep(0.1) 117 | sendLedArray([0,0,0,0,0,0,1,0,0,0,0,0]) 118 | time.sleep(0.1) 119 | sendLedArray([0,0,0,0,0,1,0,0,0,0,0,0]) 120 | time.sleep(0.1) 121 | sendLedArray([0,0,0,0,1,0,0,0,0,0,0,0]) 122 | time.sleep(0.1) 123 | sendLedArray([0,0,0,1,0,0,0,0,0,0,0,0]) 124 | time.sleep(0.1) 125 | sendLedArray([0,0,1,0,0,0,0,0,0,0,0,0]) 126 | time.sleep(0.1) 127 | sendLedArray([0,1,0,0,0,0,0,0,0,0,0,0]) 128 | 129 | 130 | 131 | 132 | 133 | setup() 134 | while(True): 135 | #pattern_Kitt() 136 | pattern_countUp() 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | print('done.') 151 | 152 | -------------------------------------------------------------------------------- /actor-linksprite-led-bar/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-linksprite-led-bar/pic1.JPG -------------------------------------------------------------------------------- /actor-relay/README.md: -------------------------------------------------------------------------------- 1 | ## Relay KY-019 2 | 3 | ![ky036](images/ky019.jpg) 4 | 5 | The pin for the extension board, where (`sensor: board`) - following the [example code](relay.py): 6 | * S: D27 7 | * -: G 8 | * +: V 9 | -------------------------------------------------------------------------------- /actor-relay/images/ky019.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/actor-relay/images/ky019.jpg -------------------------------------------------------------------------------- /actor-relay/relay.py: -------------------------------------------------------------------------------- 1 | """ 2 | write state for relay 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | relayPin = 27 # relay connected to D27 9 | 10 | GPIO.setwarnings(False) 11 | GPIO.setmode(GPIO.BCM) 12 | GPIO.setup(relayPin, GPIO.OUT) 13 | 14 | while(True): 15 | GPIO.output(relayPin, GPIO.HIGH) 16 | time.sleep(1) 17 | GPIO.output(relayPin, GPIO.LOW) 18 | time.sleep(1) -------------------------------------------------------------------------------- /doc/rpi-demo-asgs.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/doc/rpi-demo-asgs.pdf -------------------------------------------------------------------------------- /doc/tricks.txt: -------------------------------------------------------------------------------- 1 | update the linux software with 2 | >sudo apt-get update 3 | >sudo apt-get dist-upgrade 4 | 5 | update the firmware with 6 | >sudo rpi-update 7 | 8 | 9 | enable HDMI signal boost for longer cables: 10 | set in /boot/config.txt: 11 | config_hdmi_boost=6 12 | values between 0 and 7 (4 is default) 13 | -------------------------------------------------------------------------------- /example-applications/JoystickRainbow/README.md: -------------------------------------------------------------------------------- 1 | ## Change RGB Led color using a joystick 2 | 3 | Setup: 4 | Connect the joystick in an Analog port (A0,A1) and the RGB LED (SMD) like in [here](../../actor-RGB-LED) 5 | 6 | ![setup](setup.jpg) 7 | 8 | Run the [joy.py](joy.py) file. Do any changes as you need. 9 | 10 | ## How it works 11 | 12 | ![image](joystick.png) 13 | 14 | Using the joy stick you can change the value of each channel R, G or B. First you select the channel you want to change: UP for RED, LEFT for GREEN and RIGHT for BLUE. After each click on the joystick increments the value of the channel in 10 units, in a interval between 0 to 100. By increment a 100 value it turn up in 0 again. 15 | 16 | You can select DOWN to acces 12 default [colors](../../actor-RGB-LED#code-colors) and choose between one of them. After, if you want to change any value from the selected color, you just need to select a channel again and increment. 17 | -------------------------------------------------------------------------------- /example-applications/JoystickRainbow/joy.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | import spidev 4 | 5 | xPin = 0 # joystick x connected to A0 6 | yPin = 1 # joystick y connected to A1 7 | 8 | tolerancevalue = 10 9 | xZero = 512 10 | yZero = 512 11 | 12 | spi = spidev.SpiDev() 13 | spi.open(0,0) 14 | 15 | def readadc(adcnum): 16 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 17 | if ((adcnum > 3) or (adcnum < 0)): 18 | return -1 19 | r = spi.xfer2([1,8 + adcnum << 4, 0]) 20 | #print(r) 21 | adcout = ((r[1] &3) << 8) + r[2] 22 | return adcout 23 | 24 | def position(adcnum, zerovalue): 25 | return readadc(adcnum) - zerovalue 26 | #Colors setup 27 | GPIO.setmode(GPIO.BCM) 28 | 29 | LED_Rot = 14 30 | LED_Gruen = 13 31 | LED_Blau = 12 32 | 33 | GPIO.setup(LED_Rot, GPIO.OUT) 34 | GPIO.setup(LED_Gruen, GPIO.OUT) 35 | GPIO.setup(LED_Blau, GPIO.OUT) 36 | 37 | Freq = 100 #Hz 38 | 39 | 40 | ROT = GPIO.PWM(LED_Rot, Freq) 41 | GRUEN = GPIO.PWM(LED_Gruen, Freq) 42 | BLAU = GPIO.PWM(LED_Blau, Freq) 43 | ROT.start(0) 44 | GRUEN.start(0) 45 | BLAU.start(0) 46 | 47 | def LED_Farbe(Rot, Gruen,Blau): 48 | ROT.ChangeDutyCycle(Rot) 49 | GRUEN.ChangeDutyCycle(Gruen) 50 | BLAU.ChangeDutyCycle(Blau) 51 | 52 | select = 0 53 | change = 0 54 | red = 0 55 | green = 0 56 | blue = 0 57 | increment = 10 58 | c = 0 59 | rainbow = [(100,0,0),(100,50,0),(100,100,0),(50,100,0),(0,100,0),(0,100,50),(0,100,100),(0$ 60 | try: 61 | while True: 62 | xPos = position(xPin, xZero) 63 | yPos = position(yPin, yZero) 64 | 65 | 66 | if (xPos > (500)) and (abs(yPos) < tolerancevalue): #change value 67 | change = change + 1 68 | print "change value" 69 | elif (xPos > 100) and (abs(yPos) < tolerancevalue) and select != 1: 70 | c = 0 71 | print "Selected RED" 72 | print (xPos,yPos) 73 | elif (yPos > 100)and (abs(xPos) < tolerancevalue) and select != 2: 74 | select = 2 75 | c = 0 76 | print "Selected GREEN" 77 | elif (yPos < -100) and (abs(xPos) < tolerancevalue) and select != 3: 78 | select = 3 79 | c = 0 80 | print "Selected BLUE" 81 | elif (xPos < -100)and (abs(yPos) < tolerancevalue) and select != 4: 82 | select = 4 83 | print "Selected RAINBOW" 84 | 85 | 86 | while change > 0: 87 | print select 88 | if select == 1 and change == 1: 89 | red = red + increment 90 | if red > 100: 91 | red = 0 92 | elif select == 2 and change == 1: 93 | green = green + increment 94 | if green > 100: 95 | green = 0 96 | elif select == 3 and change == 1: 97 | blue = blue + increment 98 | if blue > 100: 99 | blue = 0 100 | elif select == 4 and change == 1: 101 | LED_Farbe(rainbow[c][0],rainbow[c][1],rainbow[c][2]) 102 | c = c + 1 103 | if c > 11: 104 | c = 0 105 | red = rainbow[c][0] 106 | green = rainbow[c][1] 107 | blue = rainbow[c][2] 108 | time.sleep(0.5) 109 | 110 | print (red,green,blue, increment) 111 | LED_Farbe(red,green,blue) 112 | time.sleep(0.5) 113 | change = 0 114 | 115 | except KeyboardInterrupt: 116 | GPIO.cleanup() 117 | 118 | 119 | -------------------------------------------------------------------------------- /example-applications/JoystickRainbow/joystick.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/example-applications/JoystickRainbow/joystick.png -------------------------------------------------------------------------------- /example-applications/JoystickRainbow/setup.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/example-applications/JoystickRainbow/setup.jpg -------------------------------------------------------------------------------- /example-applications/alarm_project/buzzer.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | import RPi.GPIO as GPIO 4 | import spidev 5 | 6 | 7 | class ActorBuzzer (): 8 | def __init__(self, pin=27, frequency=1000, duration=100): 9 | self.pin = pin 10 | self.frequency = frequency 11 | self.duration = duration 12 | 13 | GPIO.setwarnings(False) 14 | GPIO.setmode(GPIO.BCM) 15 | GPIO.setup(pin, GPIO.OUT) 16 | 17 | def buzz(self): 18 | p = GPIO.PWM(self.pin, self.frequency) 19 | p.start(50) 20 | time.sleep(float(self.duration)/1000) 21 | p.stop() 22 | -------------------------------------------------------------------------------- /example-applications/alarm_project/flame.py: -------------------------------------------------------------------------------- 1 | import time 2 | from datetime import datetime 3 | from queue import Queue 4 | import random as rd 5 | 6 | import RPi.GPIO as GPIO 7 | import spidev 8 | 9 | from sensor import SensorBase 10 | 11 | def random_bin(): 12 | return rd.randint(0, 1) 13 | 14 | 15 | class FlameSensor (SensorBase): 16 | 17 | def __init__(self, thread_id, notification_queue, sleeptime, pin = 27): 18 | super().__init__(thread_id, notification_queue, sleeptime) # python 3 syntax only 19 | self.pin = pin 20 | GPIO.setwarnings(False) 21 | GPIO.setmode(GPIO.BCM) 22 | GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 23 | 24 | def _getSensorValue(self): 25 | #return random_bin() 26 | return GPIO.input(self.pin) 27 | 28 | -------------------------------------------------------------------------------- /example-applications/alarm_project/main.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import signal 3 | import sys 4 | import time 5 | import operator 6 | from queue import Queue 7 | from datetime import datetime 8 | 9 | from temperature import TemperatureSensor 10 | from flame import FlameSensor 11 | from rotary import RotarySensor 12 | from observer import Observer 13 | from buzzer import ActorBuzzer 14 | 15 | 16 | threads = [] 17 | sleeptime = 0.1 18 | temperature_threshold = 60 19 | 20 | def signal_handler(signal, frame): 21 | print ("Closing all threads...") 22 | for t in threads: 23 | if t.isAlive(): 24 | t.stop() 25 | '''for t in threads: 26 | if t.isAlive(): 27 | t.join()''' 28 | print ("Finished.") 29 | sys.exit(0) 30 | 31 | signal.signal(signal.SIGINT, signal_handler) 32 | 33 | queue_ = Queue(100) 34 | obs = Observer(queue_) 35 | 36 | temp_sensor = TemperatureSensor("temp", queue_, sleeptime, pin = 0) 37 | flame_sensor = FlameSensor("flame", queue_, sleeptime, pin = 27) 38 | #rotary_sensor = RotarySensor(thread_id="rotary", queue_, sleeptime) 39 | 40 | buzzer = ActorBuzzer(15) 41 | 42 | def tempAlarm(*args, **kwargs): 43 | print ("HIGH TEMPERATURE: %s" % str(kwargs["value"])) 44 | buzzer.buzz() 45 | obs.addSensor("temp", temperature_threshold, operator.ge, tempAlarm) 46 | 47 | def flameAlarm(*args, **kwargs): 48 | print ("ON FIRE!!!") 49 | buzzer.buzz() 50 | obs.addSensor("flame", 0, operator.eq, flameAlarm) 51 | 52 | #obs.addSensor(thread_id="rotary_sensor", -1, action) # -1 for any positive value (0 and 1 as binary) 53 | 54 | threads.append(obs) 55 | threads.append(temp_sensor) 56 | threads.append(flame_sensor) 57 | #threads.append(rotary_sensor) 58 | 59 | for t in threads: 60 | t.start() 61 | 62 | while (True): 63 | pass 64 | -------------------------------------------------------------------------------- /example-applications/alarm_project/observer.py: -------------------------------------------------------------------------------- 1 | import operator 2 | 3 | from stoppable import StoppableThread 4 | 5 | class Observer (StoppableThread): # Observer pattern (observer) 6 | 7 | def __init__(self, notification_queue, thread_id="observer"): 8 | super(Observer, self).__init__() 9 | self.__notification_queue = notification_queue 10 | self.__thread_id = thread_id 11 | self.sensors = {} 12 | 13 | def run(self): 14 | print ("Thread %s started!" % str(self.__thread_id)) 15 | while (not self.stopped()): 16 | recv = self.__notification_queue.get(block=True) 17 | print (recv) 18 | id_ = recv["id"] 19 | if id_ in self.sensors: 20 | sensor = self.sensors[id_] 21 | 22 | if (sensor["operator"](recv["value"], sensor["threshold"])): 23 | sensor["action"](value = recv["value"], recv = recv) 24 | 25 | def addSensor(self, sensor_id, threshold, operator=operator.ge, action=None): 26 | self.sensors[sensor_id] = { 27 | "threshold": threshold, 28 | "operator": operator, 29 | "action": action, 30 | } 31 | 32 | def defaultAction(): 33 | raise NotImplementedError("Needs an action attributed to the sensor.") -------------------------------------------------------------------------------- /example-applications/alarm_project/rotary.py: -------------------------------------------------------------------------------- 1 | import time 2 | from datetime import datetime 3 | from queue import Queue 4 | 5 | import random as rd 6 | 7 | from sensor import SensorBase 8 | 9 | def random_bin(): 10 | return rd.randint(0, 1) 11 | 12 | 13 | class RotarySensor (SensorBase): 14 | 15 | def __init__(self, thread_id, notification_queue, sleeptime, aPin = 1, bPin = 1): 16 | super().__init__(thread_id, notification_queue, sleeptime) # python 3 only 17 | self.__thread_id = thread_id 18 | self.__notification_queue = notification_queue 19 | self.__sleeptime = sleeptime 20 | # GPIO.add_event_detect(aPin, GPIO.BOTH, bouncetime = 200, callback = __eventRotary) 21 | 22 | def run(self): 23 | print ("Thread %s started!" % str(self.__thread_id)) 24 | while (not self.stopped()): 25 | time.sleep(self.__sleeptime) 26 | 27 | def __eventRotary(self): 28 | #if (GPIO.input(bPin) != GPIO.input(aPin)): # a changed before b 29 | # self.notify_observers(0) # Rotating clockwise 30 | #else: 31 | # self.notify_observers(1) # Rotating counterclockwise 32 | return 33 | 34 | def notify_observers(self, value): 35 | dict_ = { 36 | "id": self.__thread_id, 37 | "time": datetime.now(), 38 | "value": value, 39 | } 40 | self.__notification_queue.put_nowait(dict_) -------------------------------------------------------------------------------- /example-applications/alarm_project/sensor.py: -------------------------------------------------------------------------------- 1 | import abc 2 | import time 3 | from datetime import datetime 4 | from queue import Queue 5 | 6 | import spidev 7 | 8 | from stoppable import StoppableThread 9 | 10 | def readadc(adcnum): 11 | spi = spidev.SpiDev() 12 | spi.open(0,0) 13 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 14 | if ((adcnum > 3) or (adcnum < 0)): 15 | return-1 16 | r = spi.xfer2([1,8+adcnum <<4,0]) 17 | #print(r) 18 | adcout = ((r[1] &3) <<8)+r[2] 19 | return adcout 20 | 21 | 22 | class SensorBase (StoppableThread): # Observer pattern (observable) 23 | __metaclass__ = abc.ABCMeta 24 | 25 | def __init__(self, thread_id, notification_queue, sleeptime): 26 | super().__init__() # python 3 only 27 | self.__thread_id = thread_id 28 | self.__notification_queue = notification_queue 29 | self.__sleeptime = sleeptime 30 | 31 | def run(self): 32 | ''' reads sensor value and adds to queue ''' 33 | while (not self.stopped()): 34 | value = self._getSensorValue() 35 | self.notify_observers(value) 36 | time.sleep(self.__sleeptime) 37 | 38 | @abc.abstractmethod 39 | def _getSensorValue(self): 40 | # CODE TO GET SENSOR VALUE 41 | return 42 | 43 | def notify_observers(self, value): 44 | ''' adds value to the queue ''' 45 | dict_ = { 46 | "id": self.__thread_id, 47 | "time": datetime.now(), 48 | "value": value, 49 | } 50 | self.__notification_queue.put_nowait(dict_) -------------------------------------------------------------------------------- /example-applications/alarm_project/stoppable.py: -------------------------------------------------------------------------------- 1 | import threading 2 | 3 | class StoppableThread(threading.Thread): 4 | """Thread class with a stop() method. The thread itself has to check 5 | regularly for the stopped() condition.""" 6 | 7 | def __init__(self): 8 | super(StoppableThread, self).__init__() 9 | self._stop = threading.Event() 10 | 11 | def stop(self): 12 | self._stop.set() 13 | 14 | def stopped(self): 15 | return self._stop.is_set() -------------------------------------------------------------------------------- /example-applications/alarm_project/temperature.py: -------------------------------------------------------------------------------- 1 | import time 2 | from datetime import datetime 3 | from queue import Queue 4 | import random as rd 5 | 6 | import RPi.GPIO as GPIO 7 | import spidev 8 | 9 | from sensor import SensorBase 10 | from sensor import readadc 11 | 12 | def random_temp(midvalue=60): 13 | return rd.randint(midvalue - 20, midvalue + 10) 14 | 15 | 16 | class TemperatureSensor (SensorBase): 17 | 18 | def __init__(self, thread_id, notification_queue, sleeptime, pin = 0): 19 | super().__init__(thread_id, notification_queue, sleeptime) # python 3 syntax only 20 | self.pin = pin 21 | self.spi = spidev.SpiDev() 22 | self.spi.open(0,0) 23 | 24 | def _getSensorValue(self): 25 | #return random_temp() 26 | value = readadc(self.pin) 27 | volts = (value * 5.0) / 1024.0 28 | temp = (volts - 0.5) * 100 29 | return temp -------------------------------------------------------------------------------- /example-applications/analogInMqttOut-demo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | import json 5 | 6 | import paho.mqtt.client as mqtt 7 | 8 | import RPi.GPIO as GPIO 9 | import time 10 | import spidev 11 | 12 | """ 13 | mqtt connection data 14 | """ 15 | 16 | mq_org = "" 17 | mq_type = "RPi" 18 | mq_id = "sensor1" 19 | mq_authtoken = "" 20 | mq_topic = "iot-2/evt/sensordata/fmt/json" 21 | 22 | mq_clientId = "d:"+mq_org+":"+mq_type+":"+mq_id 23 | client = mqtt.Client(client_id=mq_clientId, clean_session=True, userdata=None, protocol=mqtt.MQTTv311) 24 | client.username_pw_set(username="use-token-auth", password=mq_authtoken) 25 | 26 | 27 | # The callback for when the client receives a CONNACK response from the server. 28 | def on_connect(client, userdata, flags, rc): 29 | print("Connected with result code "+str(rc)) 30 | isConnected = True 31 | 32 | #client.disconnect() 33 | 34 | 35 | # The callback for when a PUBLISH message is received from the server. 36 | def on_message(client, userdata, msg): 37 | print("message: ") 38 | print(msg.topic+" "+str(msg.payload)) 39 | 40 | 41 | def sendMessage(msg): 42 | client.publish(topic=mq_topic, payload=msg, qos=1, retain=False) 43 | 44 | 45 | 46 | client.on_connect = on_connect 47 | client.on_message = on_message 48 | 49 | client.connect("qa64ya.messaging.internetofthings.ibmcloud.com", 1883, 60) 50 | client.loop_start() 51 | 52 | 53 | """ 54 | Analog in (on linker-base ADC) 55 | 0: JP1 connector, 56 | 2: JP2 connector 57 | """ 58 | pd = 0 59 | 60 | 61 | spi = spidev.SpiDev() 62 | spi.open(0,0) 63 | 64 | def readadc(adPin): 65 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 66 | if ((adPin > 3) or (adPin < 0)): 67 | return-1 68 | r = spi.xfer2([1,8+adPin <<4,0]) 69 | #print(r) 70 | adcout = ((r[1] &3) <<8)+r[2] 71 | return adcout 72 | 73 | def getLevel(adPin): 74 | value=readadc(adPin) 75 | volts=(value*3.3)/1024 76 | 77 | return (volts, value) 78 | 79 | 80 | while True: 81 | v0 = getLevel(0) 82 | v1 = getLevel(2) 83 | 84 | light = v1[1] 85 | temp = (((v0[0] * 1000) - 500)/10) 86 | print(light, temp) 87 | msg = { 'light': light, 88 | 'temp':temp} 89 | sendMessage(json.dumps(msg)) 90 | time.sleep(60) 91 | 92 | 93 | client.loop_stop() 94 | client.disconnect() 95 | print('done.') 96 | 97 | -------------------------------------------------------------------------------- /example-applications/analogInputDemo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | 6 | import RPi.GPIO as GPIO 7 | import time 8 | import spidev 9 | 10 | 11 | 12 | spi = spidev.SpiDev() 13 | spi.open(0,0) 14 | 15 | def readadc(adcnum): 16 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 17 | if ((adcnum > 3) or (adcnum < 0)): 18 | return-1 19 | r = spi.xfer2([1,8+adcnum <<4,0]) 20 | #print(r) 21 | adcout = ((r[1] &3) <<8)+r[2] 22 | return adcout 23 | 24 | 25 | def buildBar(num): 26 | b = int((float(num)*20.0)/1024) 27 | s = b*"#" + (20-b)*"_" 28 | return s 29 | 30 | 31 | while True: 32 | v0=readadc(0) 33 | v1=readadc(1) 34 | v2=readadc(2) 35 | v3=readadc(3) 36 | 37 | print("%s(%i) \t %s(%i) \t %s(%i) \t %s(%i)" % (buildBar(v0), v0, buildBar(v1), v1, buildBar(v2), v2, buildBar(v3), v3)) 38 | 39 | 40 | #volts=(value*3.3)/1024 41 | #print("%4d/1023 => %5.3f V" % (value, volts)) 42 | 43 | time.sleep(0.05) 44 | 45 | 46 | print('done.') 47 | 48 | -------------------------------------------------------------------------------- /example-applications/mqttListener.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import paho.mqtt.client as mqtt 4 | import sys, json 5 | import subprocess 6 | 7 | 8 | mq_org = "xx" 9 | mq_type = "xx" 10 | mq_id = "xx" 11 | mq_authtoken = "xx" 12 | 13 | 14 | topic = "iot-2/cmd/media_output/fmt/json" 15 | 16 | # The callback for when the client receives a CONNACK response from the server. 17 | def on_connect(client, userdata, flags, rc): 18 | print("Connected with result code "+str(rc)) 19 | 20 | #client.publish(topic="iot-2/evt/switch_speakers/fmt/json", payload=msg, qos=1, retain=False) 21 | #client.disconnect() 22 | 23 | 24 | # Subscribing in on_connect() means that if we lose the connection and 25 | # reconnect then subscriptions will be renewed. 26 | client.subscribe(topic) 27 | 28 | 29 | 30 | 31 | 32 | 33 | # The callback for when a PUBLISH message is received from the server. 34 | def on_message(client, userdata, msg): 35 | print("message: ") 36 | print(msg.topic+" - "+str(msg.payload)) 37 | if (msg.topic == topic): 38 | pl = json.loads(msg.payload.decode(encoding='utf-8', errors='strict')) 39 | print(json.dumps(pl)) 40 | if(pl['media_output'] in ('tv', 'dt', 'bm')): 41 | print("switching output") 42 | subprocess.Popen(["/home/tim/bin/enigma_display-control.sh", pl['media_output']]) 43 | subprocess.Popen(["/home/tim/bin/enigma_sound-control.sh", pl['media_output']]) 44 | 45 | 46 | mq_clientId = "d:"+mq_org+":"+mq_type+":"+mq_id 47 | 48 | client = mqtt.Client(client_id=mq_clientId, clean_session=True, userdata=None, protocol=mqtt.MQTTv311) 49 | client.username_pw_set(username="use-token-auth", password=mq_authtoken) 50 | 51 | client.on_connect = on_connect 52 | client.on_message = on_message 53 | 54 | client.connect("qa64ya.messaging.internetofthings.ibmcloud.com", 1883, 60) 55 | 56 | # Blocking call that processes network traffic, dispatches callbacks and 57 | # handles reconnecting. 58 | # Other loop*() functions are available that give a threaded interface and a 59 | # manual interface. 60 | client.loop_forever() 61 | #m:publish("iot-2/evt/t1/fmt/string","hello",0,0, function(conn) print("sent") end) 62 | 63 | -------------------------------------------------------------------------------- /example-applications/mqttSender.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | import paho.mqtt.client as mqtt 4 | import sys 5 | 6 | mq_org = "xx" 7 | mq_type = "xx" 8 | mq_id = "xx" 9 | mq_authtoken = "xx" 10 | 11 | 12 | messages = dict() 13 | # [(topic, message), ...] 14 | messages['dt'] = [('iot-2/evt/switch_speakers/fmt/json', '{"channel_a":1, "channel_b":0}'), 15 | ('iot-2/evt/switch_power1/fmt/json', '{"channel_a":0}'), 16 | ('iot-2/evt/sendir/fmt/string', 'rcvr_pwr_toggle')] 17 | messages['tv'] = [('iot-2/evt/switch_speakers/fmt/json', '{"channel_a":0, "channel_b":1}'), 18 | ('iot-2/evt/switch_power1/fmt/json', '{"channel_a":1}'), 19 | ('iot-2/evt/sendir/fmt/string', 'rcvr_pwr_toggle')] 20 | messages['bm'] = [('iot-2/evt/switch_speakers/fmt/json', '{"channel_a":1, "channel_b":1}'), 21 | ('iot-2/evt/switch_power1/fmt/json', '{"channel_a":0}'), 22 | ('iot-2/evt/sendir/fmt/string', 'rcvr_pwr_toggle')] 23 | 24 | message = [] 25 | 26 | if ('tv' == sys.argv[1]): 27 | message = messages['tv'] 28 | elif('dt' == sys.argv[1]): 29 | message = messages['dt'] 30 | elif('bm' == sys.argv[1]): 31 | message = messages['bm'] 32 | 33 | 34 | # The callback for when the client receives a CONNACK response from the server. 35 | def on_connect(client, userdata, flags, rc): 36 | print("Connected with result code "+str(rc)) 37 | for m in message: 38 | client.publish(topic=m[0], payload=m[1], qos=1, retain=False) 39 | client.disconnect() 40 | 41 | 42 | # Subscribing in on_connect() means that if we lose the connection and 43 | # reconnect then subscriptions will be renewed. 44 | #client.subscribe("$SYS/#") 45 | 46 | 47 | 48 | 49 | # The callback for when a PUBLISH message is received from the server. 50 | def on_message(client, userdata, msg): 51 | print("message: ") 52 | print(msg.topic+" "+str(msg.payload)) 53 | 54 | mq_clientId = "d:"+mq_org+":"+mq_type+":"+mq_id 55 | 56 | client = mqtt.Client(client_id=mq_clientId, clean_session=True, userdata=None, protocol=mqtt.MQTTv311) 57 | client.username_pw_set(username="use-token-auth", password=mq_authtoken) 58 | 59 | client.on_connect = on_connect 60 | client.on_message = on_message 61 | 62 | client.connect("qa64ya.messaging.internetofthings.ibmcloud.com", 1883, 60) 63 | 64 | # Blocking call that processes network traffic, dispatches callbacks and 65 | # handles reconnecting. 66 | # Other loop*() functions are available that give a threaded interface and a 67 | # manual interface. 68 | client.loop_forever() 69 | #m:publish("iot-2/evt/t1/fmt/string","hello",0,0, function(conn) print("sent") end) 70 | 71 | -------------------------------------------------------------------------------- /example-applications/presenter.py: -------------------------------------------------------------------------------- 1 | """ 2 | this script uses XAutomation, i.e. the xte command. install it with: 3 | >sudo apt-get install xautomation 4 | 5 | """ 6 | import RPi.GPIO as GPIO 7 | import subprocess 8 | import time 9 | 10 | 11 | btnPin1 = 27 12 | btnPin2 = 22 13 | 14 | 15 | GPIO.setwarnings(False) 16 | GPIO.setmode(GPIO.BCM) 17 | GPIO.setup(btnPin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 18 | GPIO.setup(btnPin2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 19 | 20 | 21 | 22 | 23 | def sendKey(key): 24 | subprocess.Popen(['xte', 'key %s' % (key)]) 25 | 26 | 27 | def eventRight(e): 28 | print("Right") 29 | print(e) 30 | sendKey("Right") 31 | 32 | def eventLeft(e): 33 | print("Left") 34 | print(e) 35 | sendKey("Left") 36 | 37 | 38 | 39 | GPIO.add_event_detect(btnPin1, GPIO.RISING, bouncetime=200, callback=eventRight) 40 | GPIO.add_event_detect(btnPin2, GPIO.RISING, bouncetime=200, callback=eventLeft) 41 | 42 | 43 | 44 | while(True): 45 | time.sleep(0.1) 46 | 47 | 48 | -------------------------------------------------------------------------------- /example-applications/sensor1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | 6 | import RPi.GPIO as GPIO 7 | import time 8 | import spidev 9 | 10 | import tm1637 11 | 12 | 13 | pd = 2 #Analog in (on linker-base ADC) 14 | 15 | 16 | spi = spidev.SpiDev() 17 | spi.open(0,0) 18 | 19 | def readadc(adcnum): 20 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 21 | if ((adcnum > 3) or (adcnum < 0)): 22 | return-1 23 | r = spi.xfer2([1,8+adcnum <<4,0]) 24 | #print(r) 25 | adcout = ((r[1] &3) <<8)+r[2] 26 | return adcout 27 | 28 | Display = tm1637.TM1637(23,24,tm1637.BRIGHT_TYPICAL) 29 | 30 | while True: 31 | value=readadc(pd) 32 | volts=(value*3.3)/1024 33 | #print("%4d/1023 => %5.3f V" % (value, volts)) 34 | Display.ShowInt(value) 35 | time.sleep(0.1) 36 | 37 | 38 | print('done.') 39 | 40 | -------------------------------------------------------------------------------- /extension-board/README.md: -------------------------------------------------------------------------------- 1 | This contains info about: 2 | * [Shield w/ ADC Interface](#shield) 3 | * [List of analog sensors](#analog-sensors) 4 | * [AD converter](ky053) 5 | * [Level shifter](ky051) 6 | 7 | ## Shield 8 | 9 | To read analog values, you need to enable SPI. 10 | 11 | You can find how to in [this README](../setup-raspberrypi/README.md). 12 | 13 | Two version of the board have been used: 14 | * [First version](#first-used-board-version) 15 | * [Second version](#second-used-board-version) 16 | 17 | ## First used board version 18 | 19 | ![image of device](images/boardv1.JPG) 20 | 21 | The linksprite board has a 4-channel analog-to-digital converter. You need to use this to read values from analog sensors since the RaspberryPi doesn't have analog inputs. 22 | 23 | *Note* that the board has a jumper to set VCC to 3.3V or 5V. Some devices will not work if it's the wrong setting... 24 | 25 | ## Second used board version 26 | ![boardv2](images/boardv2.jpg) 27 | 28 | ![schema](images/schema.jpg) 29 | 30 | The numbers disposed in the schema above are needed to inform to a given program where the sensor/actor is connected. 31 | 32 | ![schema](images/schema2.jpg) 33 | ![schema](images/description.png) 34 | 35 | ## Analog Sensors 36 | * [temperature](../sensor-temperature) 37 | * light (see [linksprite documentation](http://linksprite.com/wiki/index.php5?title=LDR_Module)) 38 | * noise level 39 | * 3-axis accelerometer 40 | * Rotary Potentiometer 41 | * Magnet modul 42 | * Heartbeat 43 | * Magic light cup 44 | * knock 45 | * photocell 46 | 47 | For the temperature sensor, use this python code to convert raw values to degrees celsius: 48 | 49 | temp = (((value * 1000) - 500)/10) 50 | 51 | 52 | * [`analogIn.py`](analogIn.py) shows how to read the values 53 | * [`analogInputDemo`](analogInputDemo.py) display all 4 values in real time; useful for test/debug 54 | 55 | ![image of device](images/sensor1.JPG) 56 | ![image of device](images/sensor2.JPG) 57 | ![image of device](images/sensor3.JPG) 58 | ![image of device](images/sensor4.JPG) 59 | ![image of device](images/sensor6.jpg) 60 | ![image of device](images/sensor7.jpg) 61 | ![image of device](images/sensor5.jpg) 62 | ![image of device](images/sensor8.jpg) 63 | ![image of device](images/sensor9.jpg) 64 | ![image of device](images/sensor10.jpg) 65 | ![image of device](images/sensor11.jpg) 66 | ![image of device](images/sensor12.jpg) 67 | ![image of device](images/sensor13.jpg) 68 | ![image of device](images/sensor14.jpg) 69 | ![image of device](images/sensor16.jpg) 70 | ![image of device](images/sensor15.jpg) 71 | -------------------------------------------------------------------------------- /extension-board/analogIn.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | needs spidev installed 5 | http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/ 6 | ''' 7 | import sys 8 | 9 | 10 | import RPi.GPIO as GPIO 11 | import time 12 | import spidev 13 | 14 | 15 | 16 | pd = 0 #Analog in (on linker-base ADC) 17 | 18 | 19 | spi = spidev.SpiDev() 20 | spi.open(0,0) 21 | 22 | def readadc(adcnum): 23 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 24 | if ((adcnum > 3) or (adcnum < 0)): 25 | return-1 26 | r = spi.xfer2([1,8+adcnum <<4,0]) 27 | #print(r) 28 | adcout = ((r[1] &3) <<8)+r[2] 29 | return adcout 30 | 31 | 32 | while True: 33 | value=readadc(pd) 34 | volts=(value*3.3)/1024 35 | print("%4d/1023 => %5.3f V" % (value, volts)) 36 | #temp = (((value * 1000) - 500)/10) 37 | #print temp 38 | time.sleep(0.1) 39 | 40 | 41 | print('done.') 42 | 43 | -------------------------------------------------------------------------------- /extension-board/analogInputDemo.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | needs spidev installed 5 | http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/ 6 | ''' 7 | import sys 8 | 9 | 10 | import RPi.GPIO as GPIO 11 | import time 12 | import spidev 13 | 14 | 15 | 16 | spi = spidev.SpiDev() 17 | spi.open(0,0) 18 | 19 | def readadc(adcnum): 20 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 21 | if ((adcnum > 3) or (adcnum < 0)): 22 | return-1 23 | r = spi.xfer2([1,8+adcnum <<4,0]) 24 | #print(r) 25 | adcout = ((r[1] &3) <<8)+r[2] 26 | return adcout 27 | 28 | 29 | def buildBar(num): 30 | b = int((float(num)*20.0)/1024) 31 | s = b*"#" + (20-b)*"_" 32 | return s 33 | 34 | 35 | while True: 36 | v0=readadc(0) 37 | v1=readadc(1) 38 | v2=readadc(2) 39 | v3=readadc(3) 40 | 41 | print("%s(%i) \t %s(%i) \t %s(%i) \t %s(%i)" % (buildBar(v0), v0, buildBar(v1), v1, buildBar(v2), v2, buildBar(v3), v3)) 42 | 43 | 44 | #volts=(value*3.3)/1024 45 | #print("%4d/1023 => %5.3f V" % (value, volts)) 46 | 47 | time.sleep(0.05) 48 | 49 | 50 | print('done.') 51 | 52 | -------------------------------------------------------------------------------- /extension-board/images/boardv1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/boardv1.JPG -------------------------------------------------------------------------------- /extension-board/images/boardv2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/boardv2.jpg -------------------------------------------------------------------------------- /extension-board/images/description.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/description.png -------------------------------------------------------------------------------- /extension-board/images/ky051.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/ky051.JPG -------------------------------------------------------------------------------- /extension-board/images/ky053.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/ky053.JPG -------------------------------------------------------------------------------- /extension-board/images/schema.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/schema.jpg -------------------------------------------------------------------------------- /extension-board/images/schema2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/schema2.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor1.JPG -------------------------------------------------------------------------------- /extension-board/images/sensor10.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor10.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor11.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor11.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor12.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor12.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor13.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor13.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor14.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor14.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor15.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor15.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor16.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor16.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor2.JPG -------------------------------------------------------------------------------- /extension-board/images/sensor3.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor3.JPG -------------------------------------------------------------------------------- /extension-board/images/sensor4.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor4.JPG -------------------------------------------------------------------------------- /extension-board/images/sensor5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor5.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor6.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor7.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor7.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor8.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor8.jpg -------------------------------------------------------------------------------- /extension-board/images/sensor9.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/extension-board/images/sensor9.jpg -------------------------------------------------------------------------------- /extension-board/ky051/README.md: -------------------------------------------------------------------------------- 1 | ![ky051](../images/ky051.JPG) 2 | 3 | This is based on this guide: 4 | [sensorkit.joy-it.net/index.php?title=KY-051_Voltage_Translator_/_Level_Shifter](http://sensorkit.joy-it.net/index.php?title=KY-051_Voltage_Translator_/_Level_Shifter) 5 | 6 | This is a [Level shifter](https://en.wikipedia.org/wiki/Logic_level), not to be confused with a [Voltage Regulator](https://en.wikipedia.org/wiki/Voltage_regulator). 7 | >"A level shifter connects one digital circuit that uses one logic level to another digital circuit that uses another logic level." 8 | 9 | You can use the [`analogIn.py`](../analogIn.py) to test the values output. 10 | 11 | The KY-051 follows the ratio 3,3V:5V (A:B). 12 | You should connect a 3,3V VCC into VCCa and a 5V VCC into VCCb. 13 | 14 | Now, for every input connected to Bx (B1-B4) that uses 5V as VCC, you will have the translated value as a 3,3V max on Ax (A1-A4). 15 | 16 | For instance: 17 | If we put a digital HIGH on B1, we should have a digital HIGH on A1. That means we will have 5V on B1 and 3,3V on A1, as it is translated. 18 | 19 | 20 | The connections should be (`ky051: board`): 21 | * VCCa : V (input 3,3V) 22 | * VCCb : V (input 5V) 23 | * GND : G 24 | * OE : G 25 | * A1-A4 : 3,3V input/output 26 | * B1-B4 : 5V output/input (the opposite of Ax for Bx) -------------------------------------------------------------------------------- /extension-board/ky053/Adafruit_ADS1x15.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | import time 4 | import smbus 5 | from Adafruit_I2C import Adafruit_I2C 6 | 7 | # =========================================================================== 8 | # ADS1x15 Class 9 | # 10 | # Originally written by K. Townsend, Adafruit (https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code/tree/master/Adafruit_ADS1x15) 11 | # Updates and new functions implementation by Pedro Villanueva, 03/2013. 12 | # The only error in the original code was in line 57: 13 | # __ADS1015_REG_CONFIG_DR_920SPS = 0x0050 14 | # should be 15 | # __ADS1015_REG_CONFIG_DR_920SPS = 0x0060 16 | # 17 | # NOT IMPLEMENTED: Conversion ready pin, page 15 datasheet. 18 | # =========================================================================== 19 | 20 | class ADS1x15: 21 | i2c = None 22 | 23 | # IC Identifiers 24 | __IC_ADS1015 = 0x00 25 | __IC_ADS1115 = 0x01 26 | 27 | # Pointer Register 28 | __ADS1015_REG_POINTER_MASK = 0x03 29 | __ADS1015_REG_POINTER_CONVERT = 0x00 30 | __ADS1015_REG_POINTER_CONFIG = 0x01 31 | __ADS1015_REG_POINTER_LOWTHRESH = 0x02 32 | __ADS1015_REG_POINTER_HITHRESH = 0x03 33 | 34 | # Config Register 35 | __ADS1015_REG_CONFIG_OS_MASK = 0x8000 36 | __ADS1015_REG_CONFIG_OS_SINGLE = 0x8000 # Write: Set to start a single-conversion 37 | __ADS1015_REG_CONFIG_OS_BUSY = 0x0000 # Read: Bit = 0 when conversion is in progress 38 | __ADS1015_REG_CONFIG_OS_NOTBUSY = 0x8000 # Read: Bit = 1 when device is not performing a conversion 39 | 40 | __ADS1015_REG_CONFIG_MUX_MASK = 0x7000 41 | __ADS1015_REG_CONFIG_MUX_DIFF_0_1 = 0x0000 # Differential P = AIN0, N = AIN1 (default) 42 | __ADS1015_REG_CONFIG_MUX_DIFF_0_3 = 0x1000 # Differential P = AIN0, N = AIN3 43 | __ADS1015_REG_CONFIG_MUX_DIFF_1_3 = 0x2000 # Differential P = AIN1, N = AIN3 44 | __ADS1015_REG_CONFIG_MUX_DIFF_2_3 = 0x3000 # Differential P = AIN2, N = AIN3 45 | __ADS1015_REG_CONFIG_MUX_SINGLE_0 = 0x4000 # Single-ended AIN0 46 | __ADS1015_REG_CONFIG_MUX_SINGLE_1 = 0x5000 # Single-ended AIN1 47 | __ADS1015_REG_CONFIG_MUX_SINGLE_2 = 0x6000 # Single-ended AIN2 48 | __ADS1015_REG_CONFIG_MUX_SINGLE_3 = 0x7000 # Single-ended AIN3 49 | 50 | __ADS1015_REG_CONFIG_PGA_MASK = 0x0E00 51 | __ADS1015_REG_CONFIG_PGA_6_144V = 0x0000 # +/-6.144V range 52 | __ADS1015_REG_CONFIG_PGA_4_096V = 0x0200 # +/-4.096V range 53 | __ADS1015_REG_CONFIG_PGA_2_048V = 0x0400 # +/-2.048V range (default) 54 | __ADS1015_REG_CONFIG_PGA_1_024V = 0x0600 # +/-1.024V range 55 | __ADS1015_REG_CONFIG_PGA_0_512V = 0x0800 # +/-0.512V range 56 | __ADS1015_REG_CONFIG_PGA_0_256V = 0x0A00 # +/-0.256V range 57 | 58 | __ADS1015_REG_CONFIG_MODE_MASK = 0x0100 59 | __ADS1015_REG_CONFIG_MODE_CONTIN = 0x0000 # Continuous conversion mode 60 | __ADS1015_REG_CONFIG_MODE_SINGLE = 0x0100 # Power-down single-shot mode (default) 61 | 62 | __ADS1015_REG_CONFIG_DR_MASK = 0x00E0 63 | __ADS1015_REG_CONFIG_DR_128SPS = 0x0000 # 128 samples per second 64 | __ADS1015_REG_CONFIG_DR_250SPS = 0x0020 # 250 samples per second 65 | __ADS1015_REG_CONFIG_DR_490SPS = 0x0040 # 490 samples per second 66 | __ADS1015_REG_CONFIG_DR_920SPS = 0x0060 # 920 samples per second 67 | __ADS1015_REG_CONFIG_DR_1600SPS = 0x0080 # 1600 samples per second (default) 68 | __ADS1015_REG_CONFIG_DR_2400SPS = 0x00A0 # 2400 samples per second 69 | __ADS1015_REG_CONFIG_DR_3300SPS = 0x00C0 # 3300 samples per second (also 0x00E0) 70 | 71 | __ADS1115_REG_CONFIG_DR_8SPS = 0x0000 # 8 samples per second 72 | __ADS1115_REG_CONFIG_DR_16SPS = 0x0020 # 16 samples per second 73 | __ADS1115_REG_CONFIG_DR_32SPS = 0x0040 # 32 samples per second 74 | __ADS1115_REG_CONFIG_DR_64SPS = 0x0060 # 64 samples per second 75 | __ADS1115_REG_CONFIG_DR_128SPS = 0x0080 # 128 samples per second 76 | __ADS1115_REG_CONFIG_DR_250SPS = 0x00A0 # 250 samples per second (default) 77 | __ADS1115_REG_CONFIG_DR_475SPS = 0x00C0 # 475 samples per second 78 | __ADS1115_REG_CONFIG_DR_860SPS = 0x00E0 # 860 samples per second 79 | 80 | __ADS1015_REG_CONFIG_CMODE_MASK = 0x0010 81 | __ADS1015_REG_CONFIG_CMODE_TRAD = 0x0000 # Traditional comparator with hysteresis (default) 82 | __ADS1015_REG_CONFIG_CMODE_WINDOW = 0x0010 # Window comparator 83 | 84 | __ADS1015_REG_CONFIG_CPOL_MASK = 0x0008 85 | __ADS1015_REG_CONFIG_CPOL_ACTVLOW = 0x0000 # ALERT/RDY pin is low when active (default) 86 | __ADS1015_REG_CONFIG_CPOL_ACTVHI = 0x0008 # ALERT/RDY pin is high when active 87 | 88 | __ADS1015_REG_CONFIG_CLAT_MASK = 0x0004 # Determines if ALERT/RDY pin latches once asserted 89 | __ADS1015_REG_CONFIG_CLAT_NONLAT = 0x0000 # Non-latching comparator (default) 90 | __ADS1015_REG_CONFIG_CLAT_LATCH = 0x0004 # Latching comparator 91 | 92 | __ADS1015_REG_CONFIG_CQUE_MASK = 0x0003 93 | __ADS1015_REG_CONFIG_CQUE_1CONV = 0x0000 # Assert ALERT/RDY after one conversions 94 | __ADS1015_REG_CONFIG_CQUE_2CONV = 0x0001 # Assert ALERT/RDY after two conversions 95 | __ADS1015_REG_CONFIG_CQUE_4CONV = 0x0002 # Assert ALERT/RDY after four conversions 96 | __ADS1015_REG_CONFIG_CQUE_NONE = 0x0003 # Disable the comparator and put ALERT/RDY in high state (default) 97 | 98 | 99 | # Dictionaries with the sampling speed values 100 | # These simplify and clean the code (avoid the abuse of if/elif/else clauses) 101 | spsADS1115 = { 102 | 8:__ADS1115_REG_CONFIG_DR_8SPS, 103 | 16:__ADS1115_REG_CONFIG_DR_16SPS, 104 | 32:__ADS1115_REG_CONFIG_DR_32SPS, 105 | 64:__ADS1115_REG_CONFIG_DR_64SPS, 106 | 128:__ADS1115_REG_CONFIG_DR_128SPS, 107 | 250:__ADS1115_REG_CONFIG_DR_250SPS, 108 | 475:__ADS1115_REG_CONFIG_DR_475SPS, 109 | 860:__ADS1115_REG_CONFIG_DR_860SPS 110 | } 111 | spsADS1015 = { 112 | 128:__ADS1015_REG_CONFIG_DR_128SPS, 113 | 250:__ADS1015_REG_CONFIG_DR_250SPS, 114 | 490:__ADS1015_REG_CONFIG_DR_490SPS, 115 | 920:__ADS1015_REG_CONFIG_DR_920SPS, 116 | 1600:__ADS1015_REG_CONFIG_DR_1600SPS, 117 | 2400:__ADS1015_REG_CONFIG_DR_2400SPS, 118 | 3300:__ADS1015_REG_CONFIG_DR_3300SPS 119 | } 120 | # Dictionariy with the programable gains 121 | pgaADS1x15 = { 122 | 6144:__ADS1015_REG_CONFIG_PGA_6_144V, 123 | 4096:__ADS1015_REG_CONFIG_PGA_4_096V, 124 | 2048:__ADS1015_REG_CONFIG_PGA_2_048V, 125 | 1024:__ADS1015_REG_CONFIG_PGA_1_024V, 126 | 512:__ADS1015_REG_CONFIG_PGA_0_512V, 127 | 256:__ADS1015_REG_CONFIG_PGA_0_256V 128 | } 129 | 130 | 131 | # Constructor 132 | def __init__(self, address=0x48, ic=__IC_ADS1015, debug=False): 133 | # Depending on if you have an old or a new Raspberry Pi, you 134 | # may need to change the I2C bus. Older Pis use SMBus 0, 135 | # whereas new Pis use SMBus 1. If you see an error like: 136 | # 'Error accessing 0x48: Check your I2C address ' 137 | # change the SMBus number in the initializer below! 138 | self.i2c = Adafruit_I2C(address) 139 | self.address = address 140 | self.debug = debug 141 | 142 | # Make sure the IC specified is valid 143 | if ((ic < self.__IC_ADS1015) | (ic > self.__IC_ADS1115)): 144 | if (self.debug): 145 | print "ADS1x15: Invalid IC specfied: %h" % ic 146 | return -1 147 | else: 148 | self.ic = ic 149 | 150 | # Set pga value, so that getLastConversionResult() can use it, 151 | # any function that accepts a pga value must update this. 152 | self.pga = 6144 153 | 154 | 155 | def readADCSingleEnded(self, channel=0, pga=6144, sps=250): 156 | "Gets a single-ended ADC reading from the specified channel in mV. \ 157 | The sample rate for this mode (single-shot) can be used to lower the noise \ 158 | (low sps) or to lower the power consumption (high sps) by duty cycling, \ 159 | see datasheet page 14 for more info. \ 160 | The pga must be given in mV, see page 13 for the supported values." 161 | 162 | # With invalid channel return -1 163 | if (channel > 3): 164 | if (self.debug): 165 | print "ADS1x15: Invalid channel specified: %d" % channel 166 | return -1 167 | 168 | # Disable comparator, Non-latching, Alert/Rdy active low 169 | # traditional comparator, single-shot mode 170 | config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \ 171 | self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \ 172 | self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW | \ 173 | self.__ADS1015_REG_CONFIG_CMODE_TRAD | \ 174 | self.__ADS1015_REG_CONFIG_MODE_SINGLE 175 | 176 | # Set sample per seconds, defaults to 250sps 177 | # If sps is in the dictionary (defined in init) it returns the value of the constant 178 | # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! 179 | if (self.ic == self.__IC_ADS1015): 180 | config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) 181 | else: 182 | if ( (sps not in self.spsADS1115) & self.debug): 183 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps 184 | config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) 185 | 186 | # Set PGA/voltage range, defaults to +-6.144V 187 | if ( (pga not in self.pgaADS1x15) & self.debug): 188 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps 189 | config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) 190 | self.pga = pga 191 | 192 | # Set the channel to be converted 193 | if channel == 3: 194 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_3 195 | elif channel == 2: 196 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_2 197 | elif channel == 1: 198 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_1 199 | else: 200 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_0 201 | 202 | # Set 'start single-conversion' bit 203 | config |= self.__ADS1015_REG_CONFIG_OS_SINGLE 204 | 205 | # Write config register to the ADC 206 | bytes = [(config >> 8) & 0xFF, config & 0xFF] 207 | self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) 208 | 209 | # Wait for the ADC conversion to complete 210 | # The minimum delay depends on the sps: delay >= 1/sps 211 | # We add 0.1ms to be sure 212 | delay = 1.0/sps+0.0001 213 | time.sleep(delay) 214 | 215 | # Read the conversion results 216 | result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) 217 | if (self.ic == self.__IC_ADS1015): 218 | # Shift right 4 bits for the 12-bit ADS1015 and convert to mV 219 | return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*pga/2048.0 220 | else: 221 | # Return a mV value for the ADS1115 222 | # (Take signed values into account as well) 223 | val = (result[0] << 8) | (result[1]) 224 | if val > 0x7FFF: 225 | return (val - 0xFFFF)*pga/32768.0 226 | else: 227 | return ( (result[0] << 8) | (result[1]) )*pga/32768.0 228 | 229 | 230 | def readADCDifferential(self, chP=0, chN=1, pga=6144, sps=250): 231 | "Gets a differential ADC reading from channels chP and chN in mV. \ 232 | The sample rate for this mode (single-shot) can be used to lower the noise \ 233 | (low sps) or to lower the power consumption (high sps) by duty cycling, \ 234 | see data sheet page 14 for more info. \ 235 | The pga must be given in mV, see page 13 for the supported values." 236 | 237 | # Disable comparator, Non-latching, Alert/Rdy active low 238 | # traditional comparator, single-shot mode 239 | config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \ 240 | self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \ 241 | self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW | \ 242 | self.__ADS1015_REG_CONFIG_CMODE_TRAD | \ 243 | self.__ADS1015_REG_CONFIG_MODE_SINGLE 244 | 245 | # Set channels 246 | if ( (chP == 0) & (chN == 1) ): 247 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_1 248 | elif ( (chP == 0) & (chN == 3) ): 249 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_3 250 | elif ( (chP == 2) & (chN == 3) ): 251 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_2_3 252 | elif ( (chP == 1) & (chN == 3) ): 253 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_1_3 254 | else: 255 | if (self.debug): 256 | print "ADS1x15: Invalid channels specified: %d, %d" % (chP, chN) 257 | return -1 258 | 259 | # Set sample per seconds, defaults to 250sps 260 | # If sps is in the dictionary (defined in init()) it returns the value of the constant 261 | # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! 262 | if (self.ic == self.__IC_ADS1015): 263 | config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) 264 | else: 265 | if ( (sps not in self.spsADS1115) & self.debug): 266 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps 267 | config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) 268 | 269 | # Set PGA/voltage range, defaults to +-6.144V 270 | if ( (pga not in self.pgaADS1x15) & self.debug): 271 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps 272 | config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) 273 | self.pga = pga 274 | 275 | # Set 'start single-conversion' bit 276 | config |= self.__ADS1015_REG_CONFIG_OS_SINGLE 277 | 278 | # Write config register to the ADC 279 | bytes = [(config >> 8) & 0xFF, config & 0xFF] 280 | self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) 281 | 282 | # Wait for the ADC conversion to complete 283 | # The minimum delay depends on the sps: delay >= 1/sps 284 | # We add 0.1ms to be sure 285 | delay = 1.0/sps+0.0001 286 | time.sleep(delay) 287 | 288 | # Read the conversion results 289 | result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) 290 | if (self.ic == self.__IC_ADS1015): 291 | # Shift right 4 bits for the 12-bit ADS1015 and convert to mV 292 | val = ((result[0] << 8) | (result[1] & 0xFF)) >> 4 293 | # (Take signed values into account as well) 294 | if val >> 11: 295 | val = val - 0xfff 296 | return val*pga/2048.0 297 | else: 298 | # Return a mV value for the ADS1115 299 | # (Take signed values into account as well) 300 | val = (result[0] << 8) | (result[1]) 301 | if val > 0x7FFF: 302 | return (val - 0xFFFF)*pga/32768.0 303 | else: 304 | return ( (result[0] << 8) | (result[1]) )*pga/32768.0 305 | 306 | 307 | def readADCDifferential01(self, pga=6144, sps=250): 308 | "Gets a differential ADC reading from channels 0 and 1 in mV\ 309 | The sample rate for this mode (single-shot) can be used to lower the noise \ 310 | (low sps) or to lower the power consumption (high sps) by duty cycling, \ 311 | see data sheet page 14 for more info. \ 312 | The pga must be given in mV, see page 13 for the supported values." 313 | return self.readADCDifferential(0, 1, pga, sps) 314 | 315 | 316 | def readADCDifferential03(self, pga=6144, sps=250): 317 | "Gets a differential ADC reading from channels 0 and 3 in mV \ 318 | The sample rate for this mode (single-shot) can be used to lower the noise \ 319 | (low sps) or to lower the power consumption (high sps) by duty cycling, \ 320 | see data sheet page 14 for more info. \ 321 | The pga must be given in mV, see page 13 for the supported values." 322 | return self.readADCDifferential(0, 3, pga, sps) 323 | 324 | 325 | def readADCDifferential13(self, pga=6144, sps=250): 326 | "Gets a differential ADC reading from channels 1 and 3 in mV \ 327 | The sample rate for this mode (single-shot) can be used to lower the noise \ 328 | (low sps) or to lower the power consumption (high sps) by duty cycling, \ 329 | see data sheet page 14 for more info. \ 330 | The pga must be given in mV, see page 13 for the supported values." 331 | return self.__readADCDifferential(1, 3, pga, sps) 332 | 333 | 334 | def readADCDifferential23(self, pga=6144, sps=250): 335 | "Gets a differential ADC reading from channels 2 and 3 in mV \ 336 | The sample rate for this mode (single-shot) can be used to lower the noise \ 337 | (low sps) or to lower the power consumption (high sps) by duty cycling, \ 338 | see data sheet page 14 for more info. \ 339 | The pga must be given in mV, see page 13 for the supported values." 340 | return self.readADCDifferential(2, 3, pga, sps) 341 | 342 | 343 | def startContinuousConversion(self, channel=0, pga=6144, sps=250): 344 | "Starts the continuous conversion mode and returns the first ADC reading \ 345 | in mV from the specified channel. \ 346 | The sps controls the sample rate. \ 347 | The pga must be given in mV, see datasheet page 13 for the supported values. \ 348 | Use getLastConversionResults() to read the next values and \ 349 | stopContinuousConversion() to stop converting." 350 | 351 | # Default to channel 0 with invalid channel, or return -1? 352 | if (channel > 3): 353 | if (self.debug): 354 | print "ADS1x15: Invalid channel specified: %d" % channel 355 | return -1 356 | 357 | # Disable comparator, Non-latching, Alert/Rdy active low 358 | # traditional comparator, continuous mode 359 | # The last flag is the only change we need, page 11 datasheet 360 | config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \ 361 | self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \ 362 | self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW | \ 363 | self.__ADS1015_REG_CONFIG_CMODE_TRAD | \ 364 | self.__ADS1015_REG_CONFIG_MODE_CONTIN 365 | 366 | # Set sample per seconds, defaults to 250sps 367 | # If sps is in the dictionary (defined in init()) it returns the value of the constant 368 | # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! 369 | if (self.ic == self.__IC_ADS1015): 370 | config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) 371 | else: 372 | if ( (sps not in self.spsADS1115) & self.debug): 373 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps 374 | config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) 375 | 376 | # Set PGA/voltage range, defaults to +-6.144V 377 | if ( (pga not in self.pgaADS1x15) & self.debug): 378 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps 379 | config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) 380 | self.pga = pga 381 | 382 | # Set the channel to be converted 383 | if channel == 3: 384 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_3 385 | elif channel == 2: 386 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_2 387 | elif channel == 1: 388 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_1 389 | else: 390 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_0 391 | 392 | # Set 'start single-conversion' bit to begin conversions 393 | # No need to change this for continuous mode! 394 | config |= self.__ADS1015_REG_CONFIG_OS_SINGLE 395 | 396 | # Write config register to the ADC 397 | # Once we write the ADC will convert continously 398 | # we can read the next values using getLastConversionResult 399 | bytes = [(config >> 8) & 0xFF, config & 0xFF] 400 | self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) 401 | 402 | # Wait for the ADC conversion to complete 403 | # The minimum delay depends on the sps: delay >= 1/sps 404 | # We add 0.5ms to be sure 405 | delay = 1.0/sps+0.0005 406 | time.sleep(delay) 407 | 408 | # Read the conversion results 409 | result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) 410 | if (self.ic == self.__IC_ADS1015): 411 | # Shift right 4 bits for the 12-bit ADS1015 and convert to mV 412 | return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*pga/2048.0 413 | else: 414 | # Return a mV value for the ADS1115 415 | # (Take signed values into account as well) 416 | val = (result[0] << 8) | (result[1]) 417 | if val > 0x7FFF: 418 | return (val - 0xFFFF)*pga/32768.0 419 | else: 420 | return ( (result[0] << 8) | (result[1]) )*pga/32768.0 421 | 422 | def startContinuousDifferentialConversion(self, chP=0, chN=1, pga=6144, sps=250): 423 | "Starts the continuous differential conversion mode and returns the first ADC reading \ 424 | in mV as the difference from the specified channels. \ 425 | The sps controls the sample rate. \ 426 | The pga must be given in mV, see datasheet page 13 for the supported values. \ 427 | Use getLastConversionResults() to read the next values and \ 428 | stopContinuousConversion() to stop converting." 429 | 430 | # Disable comparator, Non-latching, Alert/Rdy active low 431 | # traditional comparator, continuous mode 432 | # The last flag is the only change we need, page 11 datasheet 433 | config = self.__ADS1015_REG_CONFIG_CQUE_NONE | \ 434 | self.__ADS1015_REG_CONFIG_CLAT_NONLAT | \ 435 | self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW | \ 436 | self.__ADS1015_REG_CONFIG_CMODE_TRAD | \ 437 | self.__ADS1015_REG_CONFIG_MODE_CONTIN 438 | 439 | # Set sample per seconds, defaults to 250sps 440 | # If sps is in the dictionary (defined in init()) it returns the value of the constant 441 | # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! 442 | if (self.ic == self.__IC_ADS1015): 443 | config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) 444 | else: 445 | if ( (sps not in self.spsADS1115) & self.debug): 446 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps 447 | config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) 448 | 449 | # Set PGA/voltage range, defaults to +-6.144V 450 | if ( (pga not in self.pgaADS1x15) & self.debug): 451 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % sps 452 | config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) 453 | self.pga = pga 454 | 455 | # Set channels 456 | if ( (chP == 0) & (chN == 1) ): 457 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_1 458 | elif ( (chP == 0) & (chN == 3) ): 459 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_3 460 | elif ( (chP == 2) & (chN == 3) ): 461 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_2_3 462 | elif ( (chP == 1) & (chN == 3) ): 463 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_1_3 464 | else: 465 | if (self.debug): 466 | print "ADS1x15: Invalid channels specified: %d, %d" % (chP, chN) 467 | return -1 468 | 469 | # Set 'start single-conversion' bit to begin conversions 470 | # No need to change this for continuous mode! 471 | config |= self.__ADS1015_REG_CONFIG_OS_SINGLE 472 | 473 | # Write config register to the ADC 474 | # Once we write the ADC will convert continously 475 | # we can read the next values using getLastConversionResult 476 | bytes = [(config >> 8) & 0xFF, config & 0xFF] 477 | self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) 478 | 479 | # Wait for the ADC conversion to complete 480 | # The minimum delay depends on the sps: delay >= 1/sps 481 | # We add 0.5ms to be sure 482 | delay = 1.0/sps+0.0005 483 | time.sleep(delay) 484 | 485 | # Read the conversion results 486 | result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) 487 | if (self.ic == self.__IC_ADS1015): 488 | # Shift right 4 bits for the 12-bit ADS1015 and convert to mV 489 | return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*pga/2048.0 490 | else: 491 | # Return a mV value for the ADS1115 492 | # (Take signed values into account as well) 493 | val = (result[0] << 8) | (result[1]) 494 | if val > 0x7FFF: 495 | return (val - 0xFFFF)*pga/32768.0 496 | else: 497 | return ( (result[0] << 8) | (result[1]) )*pga/32768.0 498 | 499 | 500 | def stopContinuousConversion(self): 501 | "Stops the ADC's conversions when in continuous mode \ 502 | and resets the configuration to its default value." 503 | # Write the default config register to the ADC 504 | # Once we write, the ADC will do a single conversion and 505 | # enter power-off mode. 506 | config = 0x8583 # Page 18 datasheet. 507 | bytes = [(config >> 8) & 0xFF, config & 0xFF] 508 | self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) 509 | return True 510 | 511 | def getLastConversionResults(self): 512 | "Returns the last ADC conversion result in mV" 513 | # Read the conversion results 514 | result = self.i2c.readList(self.__ADS1015_REG_POINTER_CONVERT, 2) 515 | if (self.ic == self.__IC_ADS1015): 516 | # Shift right 4 bits for the 12-bit ADS1015 and convert to mV 517 | return ( ((result[0] << 8) | (result[1] & 0xFF)) >> 4 )*self.pga/2048.0 518 | else: 519 | # Return a mV value for the ADS1115 520 | # (Take signed values into account as well) 521 | val = (result[0] << 8) | (result[1]) 522 | if val > 0x7FFF: 523 | return (val - 0xFFFF)*self.pga/32768.0 524 | else: 525 | return ( (result[0] << 8) | (result[1]) )*self.pga/32768.0 526 | 527 | 528 | def startSingleEndedComparator(self, channel, thresholdHigh, thresholdLow, \ 529 | pga=6144, sps=250, \ 530 | activeLow=True, traditionalMode=True, latching=False, \ 531 | numReadings=1): 532 | "Starts the comparator mode on the specified channel, see datasheet pg. 15. \ 533 | In traditional mode it alerts (ALERT pin will go low) when voltage exceeds \ 534 | thresholdHigh until it falls below thresholdLow (both given in mV). \ 535 | In window mode (traditionalMode=False) it alerts when voltage doesn't lie\ 536 | between both thresholds.\ 537 | In latching mode the alert will continue until the conversion value is read. \ 538 | numReadings controls how many readings are necessary to trigger an alert: 1, 2 or 4.\ 539 | Use getLastConversionResults() to read the current value (which may differ \ 540 | from the one that triggered the alert) and clear the alert pin in latching mode. \ 541 | This function starts the continuous conversion mode. The sps controls \ 542 | the sample rate and the pga the gain, see datasheet page 13. " 543 | 544 | # With invalid channel return -1 545 | if (channel > 3): 546 | if (self.debug): 547 | print "ADS1x15: Invalid channel specified: %d" % channel 548 | return -1 549 | 550 | # Continuous mode 551 | config = self.__ADS1015_REG_CONFIG_MODE_CONTIN 552 | 553 | if (activeLow==False): 554 | config |= self.__ADS1015_REG_CONFIG_CPOL_ACTVHI 555 | else: 556 | config |= self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW 557 | 558 | if (traditionalMode==False): 559 | config |= self.__ADS1015_REG_CONFIG_CMODE_WINDOW 560 | else: 561 | config |= self.__ADS1015_REG_CONFIG_CMODE_TRAD 562 | 563 | if (latching==True): 564 | config |= self.__ADS1015_REG_CONFIG_CLAT_LATCH 565 | else: 566 | config |= self.__ADS1015_REG_CONFIG_CLAT_NONLAT 567 | 568 | if (numReadings==4): 569 | config |= self.__ADS1015_REG_CONFIG_CQUE_4CONV 570 | elif (numReadings==2): 571 | config |= self.__ADS1015_REG_CONFIG_CQUE_2CONV 572 | else: 573 | config |= self.__ADS1015_REG_CONFIG_CQUE_1CONV 574 | 575 | # Set sample per seconds, defaults to 250sps 576 | # If sps is in the dictionary (defined in init()) it returns the value of the constant 577 | # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! 578 | if (self.ic == self.__IC_ADS1015): 579 | if ( (sps not in self.spsADS1015) & self.debug): 580 | print "ADS1x15: Invalid sps specified: %d, using 1600sps" % sps 581 | config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) 582 | else: 583 | if ( (sps not in self.spsADS1115) & self.debug): 584 | print "ADS1x15: Invalid sps specified: %d, using 250sps" % sps 585 | config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) 586 | 587 | # Set PGA/voltage range, defaults to +-6.144V 588 | if ( (pga not in self.pgaADS1x15) & self.debug): 589 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % pga 590 | config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) 591 | self.pga = pga 592 | 593 | # Set the channel to be converted 594 | if channel == 3: 595 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_3 596 | elif channel == 2: 597 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_2 598 | elif channel == 1: 599 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_1 600 | else: 601 | config |= self.__ADS1015_REG_CONFIG_MUX_SINGLE_0 602 | 603 | # Set 'start single-conversion' bit to begin conversions 604 | config |= self.__ADS1015_REG_CONFIG_OS_SINGLE 605 | 606 | # Write threshold high and low registers to the ADC 607 | # V_digital = (2^(n-1)-1)/pga*V_analog 608 | if (self.ic == self.__IC_ADS1015): 609 | thresholdHighWORD = int(thresholdHigh*(2048.0/pga)) 610 | else: 611 | thresholdHighWORD = int(thresholdHigh*(32767.0/pga)) 612 | bytes = [(thresholdHighWORD >> 8) & 0xFF, thresholdHighWORD & 0xFF] 613 | self.i2c.writeList(self.__ADS1015_REG_POINTER_HITHRESH, bytes) 614 | 615 | if (self.ic == self.__IC_ADS1015): 616 | thresholdLowWORD = int(thresholdLow*(2048.0/pga)) 617 | else: 618 | thresholdLowWORD = int(thresholdLow*(32767.0/pga)) 619 | bytes = [(thresholdLowWORD >> 8) & 0xFF, thresholdLowWORD & 0xFF] 620 | self.i2c.writeList(self.__ADS1015_REG_POINTER_LOWTHRESH, bytes) 621 | 622 | # Write config register to the ADC 623 | # Once we write the ADC will convert continously and alert when things happen, 624 | # we can read the converted values using getLastConversionResult 625 | bytes = [(config >> 8) & 0xFF, config & 0xFF] 626 | self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) 627 | 628 | 629 | def startDifferentialComparator(self, chP, chN, thresholdHigh, thresholdLow, \ 630 | pga=6144, sps=250, \ 631 | activeLow=True, traditionalMode=True, latching=False, \ 632 | numReadings=1): 633 | "Starts the comparator mode on the specified channel, see datasheet pg. 15. \ 634 | In traditional mode it alerts (ALERT pin will go low) when voltage exceeds \ 635 | thresholdHigh until it falls below thresholdLow (both given in mV). \ 636 | In window mode (traditionalMode=False) it alerts when voltage doesn't lie\ 637 | between both thresholds.\ 638 | In latching mode the alert will continue until the conversion value is read. \ 639 | numReadings controls how many readings are necessary to trigger an alert: 1, 2 or 4.\ 640 | Use getLastConversionResults() to read the current value (which may differ \ 641 | from the one that triggered the alert) and clear the alert pin in latching mode. \ 642 | This function starts the continuous conversion mode. The sps controls \ 643 | the sample rate and the pga the gain, see datasheet page 13. " 644 | 645 | # Continuous mode 646 | config = self.__ADS1015_REG_CONFIG_MODE_CONTIN 647 | 648 | if (activeLow==False): 649 | config |= self.__ADS1015_REG_CONFIG_CPOL_ACTVHI 650 | else: 651 | config |= self.__ADS1015_REG_CONFIG_CPOL_ACTVLOW 652 | 653 | if (traditionalMode==False): 654 | config |= self.__ADS1015_REG_CONFIG_CMODE_WINDOW 655 | else: 656 | config |= self.__ADS1015_REG_CONFIG_CMODE_TRAD 657 | 658 | if (latching==True): 659 | config |= self.__ADS1015_REG_CONFIG_CLAT_LATCH 660 | else: 661 | config |= self.__ADS1015_REG_CONFIG_CLAT_NONLAT 662 | 663 | if (numReadings==4): 664 | config |= self.__ADS1015_REG_CONFIG_CQUE_4CONV 665 | elif (numReadings==2): 666 | config |= self.__ADS1015_REG_CONFIG_CQUE_2CONV 667 | else: 668 | config |= self.__ADS1015_REG_CONFIG_CQUE_1CONV 669 | 670 | # Set sample per seconds, defaults to 250sps 671 | # If sps is in the dictionary (defined in init()) it returns the value of the constant 672 | # othewise it returns the value for 250sps. This saves a lot of if/elif/else code! 673 | if (self.ic == self.__IC_ADS1015): 674 | if ( (sps not in self.spsADS1015) & self.debug): 675 | print "ADS1x15: Invalid sps specified: %d, using 1600sps" % sps 676 | config |= self.spsADS1015.setdefault(sps, self.__ADS1015_REG_CONFIG_DR_1600SPS) 677 | else: 678 | if ( (sps not in self.spsADS1115) & self.debug): 679 | print "ADS1x15: Invalid sps specified: %d, using 250sps" % sps 680 | config |= self.spsADS1115.setdefault(sps, self.__ADS1115_REG_CONFIG_DR_250SPS) 681 | 682 | # Set PGA/voltage range, defaults to +-6.144V 683 | if ( (pga not in self.pgaADS1x15) & self.debug): 684 | print "ADS1x15: Invalid pga specified: %d, using 6144mV" % pga 685 | config |= self.pgaADS1x15.setdefault(pga, self.__ADS1015_REG_CONFIG_PGA_6_144V) 686 | self.pga = pga 687 | 688 | # Set channels 689 | if ( (chP == 0) & (chN == 1) ): 690 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_1 691 | elif ( (chP == 0) & (chN == 3) ): 692 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_0_3 693 | elif ( (chP == 2) & (chN == 3) ): 694 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_2_3 695 | elif ( (chP == 1) & (chN == 3) ): 696 | config |= self.__ADS1015_REG_CONFIG_MUX_DIFF_1_3 697 | else: 698 | if (self.debug): 699 | print "ADS1x15: Invalid channels specified: %d, %d" % (chP, chN) 700 | return -1 701 | 702 | # Set 'start single-conversion' bit to begin conversions 703 | config |= self.__ADS1015_REG_CONFIG_OS_SINGLE 704 | 705 | # Write threshold high and low registers to the ADC 706 | # V_digital = (2^(n-1)-1)/pga*V_analog 707 | if (self.ic == self.__IC_ADS1015): 708 | thresholdHighWORD = int(thresholdHigh*(2048.0/pga)) 709 | else: 710 | thresholdHighWORD = int(thresholdHigh*(32767.0/pga)) 711 | bytes = [(thresholdHighWORD >> 8) & 0xFF, thresholdHighWORD & 0xFF] 712 | self.i2c.writeList(self.__ADS1015_REG_POINTER_HITHRESH, bytes) 713 | 714 | if (self.ic == self.__IC_ADS1015): 715 | thresholdLowWORD = int(thresholdLow*(2048.0/pga)) 716 | else: 717 | thresholdLowWORD = int(thresholdLow*(32767.0/pga)) 718 | bytes = [(thresholdLowWORD >> 8) & 0xFF, thresholdLowWORD & 0xFF] 719 | self.i2c.writeList(self.__ADS1015_REG_POINTER_LOWTHRESH, bytes) 720 | 721 | # Write config register to the ADC 722 | # Once we write the ADC will convert continously and alert when things happen, 723 | # we can read the converted values using getLastConversionResult 724 | bytes = [(config >> 8) & 0xFF, config & 0xFF] 725 | self.i2c.writeList(self.__ADS1015_REG_POINTER_CONFIG, bytes) 726 | 727 | -------------------------------------------------------------------------------- /extension-board/ky053/Adafruit_I2C.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | import re 3 | import smbus 4 | 5 | # =========================================================================== 6 | # Adafruit_I2C Class 7 | # =========================================================================== 8 | 9 | class Adafruit_I2C(object): 10 | 11 | @staticmethod 12 | def getPiRevision(): 13 | "Gets the version number of the Raspberry Pi board" 14 | # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History 15 | try: 16 | with open('/proc/cpuinfo', 'r') as infile: 17 | for line in infile: 18 | # Match a line of the form "Revision : 0002" while ignoring extra 19 | # info in front of the revsion (like 1000 when the Pi was over-volted). 20 | match = re.match('Revision\s+:\s+.*(\w{4})$', line) 21 | if match and match.group(1) in ['0000', '0002', '0003']: 22 | # Return revision 1 if revision ends with 0000, 0002 or 0003. 23 | return 1 24 | elif match: 25 | # Assume revision 2 if revision ends with any other 4 chars. 26 | return 2 27 | # Couldn't find the revision, assume revision 0 like older code for compatibility. 28 | return 0 29 | except: 30 | return 0 31 | 32 | @staticmethod 33 | def getPiI2CBusNumber(): 34 | # Gets the I2C bus number /dev/i2c# 35 | return 1 if Adafruit_I2C.getPiRevision() > 1 else 0 36 | 37 | def __init__(self, address, busnum=-1, debug=False): 38 | self.address = address 39 | # By default, the correct I2C bus is auto-detected using /proc/cpuinfo 40 | # Alternatively, you can hard-code the bus version below: 41 | # self.bus = smbus.SMBus(0); # Force I2C0 (early 256MB Pi's) 42 | # self.bus = smbus.SMBus(1); # Force I2C1 (512MB Pi's) 43 | self.bus = smbus.SMBus(busnum if busnum >= 0 else Adafruit_I2C.getPiI2CBusNumber()) 44 | self.debug = debug 45 | 46 | def reverseByteOrder(self, data): 47 | "Reverses the byte order of an int (16-bit) or long (32-bit) value" 48 | # Courtesy Vishal Sapre 49 | byteCount = len(hex(data)[2:].replace('L','')[::2]) 50 | val = 0 51 | for i in range(byteCount): 52 | val = (val << 8) | (data & 0xff) 53 | data >>= 8 54 | return val 55 | 56 | def errMsg(self): 57 | print "Error accessing 0x%02X: Check your I2C address" % self.address 58 | return -1 59 | 60 | def write8(self, reg, value): 61 | "Writes an 8-bit value to the specified register/address" 62 | try: 63 | self.bus.write_byte_data(self.address, reg, value) 64 | if self.debug: 65 | print "I2C: Wrote 0x%02X to register 0x%02X" % (value, reg) 66 | except IOError, err: 67 | return self.errMsg() 68 | 69 | def write16(self, reg, value): 70 | "Writes a 16-bit value to the specified register/address pair" 71 | try: 72 | self.bus.write_word_data(self.address, reg, value) 73 | if self.debug: 74 | print ("I2C: Wrote 0x%02X to register pair 0x%02X,0x%02X" % 75 | (value, reg, reg+1)) 76 | except IOError, err: 77 | return self.errMsg() 78 | 79 | def writeRaw8(self, value): 80 | "Writes an 8-bit value on the bus" 81 | try: 82 | self.bus.write_byte(self.address, value) 83 | if self.debug: 84 | print "I2C: Wrote 0x%02X" % value 85 | except IOError, err: 86 | return self.errMsg() 87 | 88 | def writeList(self, reg, list): 89 | "Writes an array of bytes using I2C format" 90 | try: 91 | if self.debug: 92 | print "I2C: Writing list to register 0x%02X:" % reg 93 | print list 94 | self.bus.write_i2c_block_data(self.address, reg, list) 95 | except IOError, err: 96 | return self.errMsg() 97 | 98 | def readList(self, reg, length): 99 | "Read a list of bytes from the I2C device" 100 | try: 101 | results = self.bus.read_i2c_block_data(self.address, reg, length) 102 | if self.debug: 103 | print ("I2C: Device 0x%02X returned the following from reg 0x%02X" % 104 | (self.address, reg)) 105 | print results 106 | return results 107 | except IOError, err: 108 | return self.errMsg() 109 | 110 | def readU8(self, reg): 111 | "Read an unsigned byte from the I2C device" 112 | try: 113 | result = self.bus.read_byte_data(self.address, reg) 114 | if self.debug: 115 | print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % 116 | (self.address, result & 0xFF, reg)) 117 | return result 118 | except IOError, err: 119 | return self.errMsg() 120 | 121 | def readS8(self, reg): 122 | "Reads a signed byte from the I2C device" 123 | try: 124 | result = self.bus.read_byte_data(self.address, reg) 125 | if result > 127: result -= 256 126 | if self.debug: 127 | print ("I2C: Device 0x%02X returned 0x%02X from reg 0x%02X" % 128 | (self.address, result & 0xFF, reg)) 129 | return result 130 | except IOError, err: 131 | return self.errMsg() 132 | 133 | def readU16(self, reg, little_endian=True): 134 | "Reads an unsigned 16-bit value from the I2C device" 135 | try: 136 | result = self.bus.read_word_data(self.address,reg) 137 | # Swap bytes if using big endian because read_word_data assumes little 138 | # endian on ARM (little endian) systems. 139 | if not little_endian: 140 | result = ((result << 8) & 0xFF00) + (result >> 8) 141 | if (self.debug): 142 | print "I2C: Device 0x%02X returned 0x%04X from reg 0x%02X" % (self.address, result & 0xFFFF, reg) 143 | return result 144 | except IOError, err: 145 | return self.errMsg() 146 | 147 | def readS16(self, reg, little_endian=True): 148 | "Reads a signed 16-bit value from the I2C device" 149 | try: 150 | result = self.readU16(reg,little_endian) 151 | if result > 32767: result -= 65536 152 | return result 153 | except IOError, err: 154 | return self.errMsg() 155 | 156 | if __name__ == '__main__': 157 | try: 158 | bus = Adafruit_I2C(address=0) 159 | print "Default I2C bus is accessible" 160 | except: 161 | print "Error accessing default I2C bus" 162 | -------------------------------------------------------------------------------- /extension-board/ky053/Adafruit_License_MIT.txt: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2016 Adafruit Industries 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. -------------------------------------------------------------------------------- /extension-board/ky053/KY-053_RPi_AnalogDigitalConverter.py: -------------------------------------------------------------------------------- 1 | # 2 | #!/usr/bin/python 3 | # coding=utf-8 4 | 5 | ############################################################################################################# 6 | ### Copyright by Joy-IT 7 | ### Published under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License 8 | ### Commercial use only after permission is requested and granted 9 | ### 10 | ### KY-053 Analog Digital Converter - Raspberry Pi Python Code Example 11 | ### 12 | ############################################################################################################# 13 | 14 | 15 | # Dieser Code nutzt die ADS1115 und die I2C Python Library fuer den Raspberry Pi 16 | # Diese ist unter folgendem Link unter der BSD Lizenz veroeffentlicht 17 | # [https://github.com/adafruit/Adafruit-Raspberry-Pi-Python-Code] 18 | from Adafruit_ADS1x15 import ADS1x15 19 | from time import sleep 20 | 21 | # Weitere benoetigte Module werden importiert und eingerichtet 22 | import time, signal, sys, os 23 | import RPi.GPIO as GPIO 24 | GPIO.setmode(GPIO.BCM) 25 | GPIO.setwarnings(False) 26 | 27 | # Benutzte Variablen werden initialisiert 28 | delayTime = 0.5 # in Sekunden 29 | 30 | # Adresszuweisung ADS1x15 ADC 31 | 32 | ADS1015 = 0x00 # 12-bit ADC 33 | ADS1115 = 0x01 # 16-bit 34 | 35 | # Verstaerkung (Gain) wird ausgewaehlt 36 | gain = 4096 # +/- 4.096V 37 | # gain = 2048 # +/- 2.048V 38 | # gain = 1024 # +/- 1.024V 39 | # gain = 512 # +/- 0.512V 40 | # gain = 256 # +/- 0.256V 41 | 42 | # Abtasterate des ADC (SampleRate) wird ausgewaehlt 43 | # sps = 8 # 8 Samples pro Sekunde 44 | # sps = 16 # 16 Samples pro Sekunde 45 | # sps = 32 # 32 Samples pro Sekunde 46 | sps = 64 # 64 Samples pro Sekunde 47 | # sps = 128 # 128 Samples pro Sekunde 48 | # sps = 250 # 250 Samples pro Sekunde 49 | # sps = 475 # 475 Samples pro Sekunde 50 | # sps = 860 # 860 Samples pro Sekunde 51 | 52 | # ADC-Channel (1-4) wird ausgewaehlt 53 | adc_channel_0 = 0 # Channel 0 54 | adc_channel_1 = 1 # Channel 1 55 | adc_channel_2 = 2 # Channel 2 56 | adc_channel_3 = 3 # Channel 3 57 | 58 | # Hier wird der ADC initialisiert - beim KY-053 verwendeten ADC handelt es sich um einen ADS1115 Chipsatz 59 | adc = ADS1x15(ic=ADS1115) 60 | 61 | Button_PIN = 24 62 | GPIO.setup(Button_PIN, GPIO.IN, pull_up_down = GPIO.PUD_UP) 63 | 64 | ############################################################################################################# 65 | 66 | # ######## 67 | # Hauptprogrammschleife 68 | # ######## 69 | # Das Programm liest die aktuellen Werte der Eingang-Pins 70 | # und gibt diese in der Konsole aus 71 | 72 | try: 73 | while True: 74 | #Aktuelle Werte werden aufgenommen 75 | adc0 = adc.readADCSingleEnded(adc_channel_0, gain, sps) 76 | adc1 = adc.readADCSingleEnded(adc_channel_1, gain, sps) 77 | adc2 = adc.readADCSingleEnded(adc_channel_2, gain, sps) 78 | adc3 = adc.readADCSingleEnded(adc_channel_3, gain, sps) 79 | 80 | # Ausgabe auf die Konsole 81 | print "Messwert Channel 0:", adc0, "mV " 82 | print "Messwert Channel 1:", adc1, "mV " 83 | print "Messwert Channel 2:", adc2, "mV " 84 | print "Messwert Channel 3:", adc3, "mV " 85 | print "---------------------------------------" 86 | 87 | # Reset + Delay 88 | button_pressed = False 89 | time.sleep(delayTime) 90 | 91 | 92 | 93 | except KeyboardInterrupt: 94 | GPIO.cleanup() -------------------------------------------------------------------------------- /extension-board/ky053/README.md: -------------------------------------------------------------------------------- 1 | ![ky053](../images/ky053.JPG) 2 | 3 | This is based on this guide: 4 | 5 | [sensorkit.joy-it.net/index.php?title=KY-053_Analog_Digital_Converter](http://sensorkit.joy-it.net/index.php?title=KY-053_Analog_Digital_Converter) 6 | 7 | Steps to get running: 8 | 9 | * Open this file: 10 | ``` 11 | sudo nano /boot/config.txt 12 | ``` 13 | 14 | * Uncomment the line: 15 | ``` 16 | dtparam=i2c_arm=on 17 | ``` 18 | 19 | * Reboot 20 | 21 | * Install 22 | ``` 23 | sudo apt-get install python-smbus i2c-tools -y 24 | ``` 25 | 26 | * Run the [example code](KY-053_RPi_AnalogDigitalConverter.py) (needs the other .py files from this folder also). 27 | ``` 28 | sudo python KY-053_RPi_AnalogDigitalConverter.py 29 | ``` 30 | 31 | The connections should be (`ky053: board`): 32 | * VDD : V [Pin 01] 33 | * GND : G 34 | * SCL : SCL (top left of the shield board) 35 | * SDA : SDA (top left of the shield board) 36 | * ADDR : No Connection [-] 37 | * ALRT : No Connection [-] 38 | * A0 : Any Analog Input 39 | * A1 : Any Analog Input 40 | * A2 : Any Analog Input 41 | * A3 : Any Analog Input -------------------------------------------------------------------------------- /sensor-HD-camera/README.md: -------------------------------------------------------------------------------- 1 | start a python console: `python` 2 | then enter the commands found in cam-test.py 3 | 4 | this shows a preview window. the used library also allows capturing images/video 5 | 6 | ![image of device](pic1.JPG) 7 | ![image of device](pic2.JPG) 8 | -------------------------------------------------------------------------------- /sensor-HD-camera/cam-test.py: -------------------------------------------------------------------------------- 1 | # this has to be run in an interactive python console, otherwise the preview window won't show up 2 | 3 | import picamera 4 | p = picamera.PiCamera() 5 | p.start_preview() -------------------------------------------------------------------------------- /sensor-HD-camera/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-HD-camera/pic1.JPG -------------------------------------------------------------------------------- /sensor-HD-camera/pic2.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-HD-camera/pic2.JPG -------------------------------------------------------------------------------- /sensor-button/README.md: -------------------------------------------------------------------------------- 1 | This contains info about several buttons: 2 | * [linksprite button (dual)](#linksprite-button) 3 | * [LK button (single)](#lk-button) 4 | * [KY-004 Taster-Modul (single)](#ky004-taster-modul) 5 | 6 | ## Linksprite Button 7 | 8 | Code example [here](button.py). 9 | 10 | ![image of device](images/pic1.JPG) 11 | 12 | ## LK Button 13 | 14 | Code example [here](lk-button.py). 15 | 16 | ![LK-Button](images/lkbutton.jpg) 17 | 18 | 19 | ## KY-004 Taster-Modul 20 | 21 | This button can use the [same code](lk-button.py) as the LK button. 22 | This button has only 3 pins: 23 | 24 | ![KY004](images/ky004_0.jpg) 25 | 26 | ![Board Connection](images/ky004_1.jpg) 27 | 28 | The pins should match for the extension board connection: 29 | * - to G (sensor to board) 30 | * middle pin to V (sensor to board) 31 | * S to D27 - or any D pin you want to use, modifying the number used on the code (sensor to board) -------------------------------------------------------------------------------- /sensor-button/button.py: -------------------------------------------------------------------------------- 1 | """ 2 | read state from buttons using callback functions 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | 7 | 8 | btnPin1 = 27 9 | btnPin2 = 22 10 | 11 | 12 | GPIO.setwarnings(False) 13 | GPIO.setmode(GPIO.BCM) 14 | GPIO.setup(btnPin1, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 15 | GPIO.setup(btnPin2, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 16 | 17 | 18 | 19 | 20 | def eventB1(e): 21 | print("Button 1 pressed") 22 | print(e) 23 | 24 | def eventB2(e): 25 | print("Button 1 pressed") 26 | print(e) 27 | 28 | 29 | 30 | GPIO.add_event_detect(btnPin1, GPIO.RISING, bouncetime=200, callback=eventB1) 31 | GPIO.add_event_detect(btnPin2, GPIO.RISING, bouncetime=200, callback=eventB2) 32 | 33 | 34 | 35 | while(True): 36 | time.sleep(0.1) 37 | 38 | 39 | -------------------------------------------------------------------------------- /sensor-button/images/ky004_0.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-button/images/ky004_0.jpg -------------------------------------------------------------------------------- /sensor-button/images/ky004_1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-button/images/ky004_1.jpg -------------------------------------------------------------------------------- /sensor-button/images/lkbutton.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-button/images/lkbutton.jpg -------------------------------------------------------------------------------- /sensor-button/images/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-button/images/pic1.JPG -------------------------------------------------------------------------------- /sensor-button/lkbutton.py: -------------------------------------------------------------------------------- 1 | """ 2 | read state from button using callback functions 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | lkbuttonPin = 27 # button connected to D26/D27 9 | 10 | GPIO.setwarnings(False) 11 | GPIO.setmode(GPIO.BCM) 12 | GPIO.setup(lkbuttonPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 13 | 14 | def eventLKButton(e): 15 | print("LK-Button pressed") 16 | print(e) 17 | 18 | GPIO.add_event_detect(lkbuttonPin, GPIO.RISING, bouncetime = 200, callback = eventLKButton) 19 | 20 | while(True): 21 | time.sleep(0.1) -------------------------------------------------------------------------------- /sensor-flame/README.md: -------------------------------------------------------------------------------- 1 | ## Sensor KY-026: Flame sensor 2 | 3 | ![ky036](images/ky026.jpg) 4 | ![flame](images/flameon.jpg) 5 | 6 | The *pins need to be remaped* for the extension board, where (`sensor: board`) - following the [example code](flame.py): 7 | * A0: D16 8 | * G: G 9 | * +: V 10 | * D0: D15 11 | 12 | 13 | * A0 – inverted signal 14 | * G – should be connected to ground 15 | * + – should be connected to 5V power supply 16 | * D0 – flame signal 17 | -------------------------------------------------------------------------------- /sensor-flame/flame.py: -------------------------------------------------------------------------------- 1 | """ 2 | read state from flame sensor using callback functions 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | flamePin = 15 # D0 connected to D15 9 | flameInvPin = 16 # A0 connected to D16 10 | 11 | GPIO.setwarnings(False) 12 | GPIO.setmode(GPIO.BCM) 13 | GPIO.setup(flamePin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 14 | 15 | def eventFlameSensor(e): 16 | print("Flame detected!") 17 | print(e) 18 | 19 | GPIO.add_event_detect(flamePin, GPIO.RISING, bouncetime = 200, callback = eventFlameSensor) 20 | 21 | while(True): 22 | time.sleep(0.1) -------------------------------------------------------------------------------- /sensor-flame/images/flameon.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-flame/images/flameon.jpg -------------------------------------------------------------------------------- /sensor-flame/images/ky026.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-flame/images/ky026.jpg -------------------------------------------------------------------------------- /sensor-infrared-receiver/README.md: -------------------------------------------------------------------------------- 1 | ## Sensor KY-005: Infrared Receiver 2 | 3 | This sensor was tested together with the [actor infrared transmitter](../actor-infrared-transmitter). 4 | 5 | ![ky022](images/ky022.JPG) 6 | 7 | The pins for the extension board, where (`sensor: board`) - following the [example code](infrared-recv.py): 8 | * -: G 9 | * (middle pin): V 10 | * S: D27 11 | -------------------------------------------------------------------------------- /sensor-infrared-receiver/images/ky022.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-infrared-receiver/images/ky022.JPG -------------------------------------------------------------------------------- /sensor-infrared-receiver/infrared-recv.py: -------------------------------------------------------------------------------- 1 | import RPi.GPIO as GPIO 2 | import time 3 | import binascii as ba 4 | import sys 5 | 6 | recvPin = 27 7 | bittime = 1 8 | 9 | GPIO.setmode(GPIO.BCM) 10 | GPIO.setup(recvPin, GPIO.IN) 11 | 12 | while True: 13 | value = GPIO.input(recvPin) 14 | print ('Received: ' + str(value)) 15 | time.sleep(bittime) -------------------------------------------------------------------------------- /sensor-magnet/README.md: -------------------------------------------------------------------------------- 1 | These sensor can be used with the same code as [LK-Button](/sensor-button/lkbutton.py). 2 | 3 | ![HallMagnet](images/pic1.jpg) 4 | ![HallMagnet](images/pic4.jpg) 5 | ![HallMagnet](images/pic2.jpg) 6 | ![HallMagnet](images/pic3.jpg) 7 | -------------------------------------------------------------------------------- /sensor-magnet/images/pic1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-magnet/images/pic1.jpg -------------------------------------------------------------------------------- /sensor-magnet/images/pic2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-magnet/images/pic2.jpg -------------------------------------------------------------------------------- /sensor-magnet/images/pic3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-magnet/images/pic3.jpg -------------------------------------------------------------------------------- /sensor-magnet/images/pic4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-magnet/images/pic4.jpg -------------------------------------------------------------------------------- /sensor-obstacle/README.md: -------------------------------------------------------------------------------- 1 | This contains info about: 2 | * [Sensor KY-032: Obstacle avoidance sensor](#sensor-ky-032) 3 | * [Sensor KY-033: Tracking sensor](#sensor-ky-033) 4 | 5 | 6 | ## Sensor KY-032 7 | 8 | ![ky032](images/ky032.jpg) 9 | 10 | The *pins need to be remaped* for the extension board, where (`sensor: board`) - following the [example code](obstacle.py): 11 | * GND: G 12 | * +: V 13 | * out: D15 14 | * EN: D16 15 | 16 | Pins: 17 | * GND – should be connected to ground 18 | * + – should be connected to 5V power supply 19 | * out – obstacle signal 20 | * EN – no use found 21 | 22 | ## Sensor KY-033 23 | 24 | ![ky033](images/ky033.JPG) 25 | 26 | Theoretically this is made for tracking lines, though, through tests, it detects any close object (obstacle detection). 27 | 28 | Calibrate it through the potentiometer. It may make a great difference on results. 29 | 30 | **Works best in the dark.** 31 | 32 | 33 | The pin connection for the extension board, where (`sensor: board`) - following the [example code](tracking.py): 34 | * S: D27 35 | * (middle pin): V 36 | * -: G 37 | -------------------------------------------------------------------------------- /sensor-obstacle/images/ky032.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-obstacle/images/ky032.jpg -------------------------------------------------------------------------------- /sensor-obstacle/images/ky033.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-obstacle/images/ky033.JPG -------------------------------------------------------------------------------- /sensor-obstacle/obstacle.py: -------------------------------------------------------------------------------- 1 | """ 2 | read state from obstacle avoidance sensor using callback functions 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | outPin = 15 # out connected to D15 9 | enPin = 16 # EN connected to D16 10 | 11 | GPIO.setwarnings(False) 12 | GPIO.setmode(GPIO.BCM) 13 | GPIO.setup(outPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 14 | 15 | def eventObstacleSensor(e): 16 | print("Obstacle found!") 17 | print(e) 18 | 19 | GPIO.add_event_detect(outPin, GPIO.FALLING, bouncetime = 200, callback = eventObstacleSensor) 20 | 21 | while(True): 22 | time.sleep(0.1) -------------------------------------------------------------------------------- /sensor-obstacle/tracking.py: -------------------------------------------------------------------------------- 1 | """ 2 | read state from button using callback functions 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | trackPin = 27 # button connected to D26/D27 9 | 10 | GPIO.setwarnings(False) 11 | GPIO.setmode(GPIO.BCM) 12 | GPIO.setup(trackPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 13 | 14 | def eventTrack(e): 15 | print("Tracked!") 16 | while(GPIO.input(e) == GPIO.HIGH): # waits until signal is off 17 | pass 18 | 19 | GPIO.add_event_detect(trackPin, GPIO.RISING, bouncetime = 200, callback = eventTrack) 20 | 21 | while(True): 22 | time.sleep(0.1) -------------------------------------------------------------------------------- /sensor-rotary-encoder/README.md: -------------------------------------------------------------------------------- 1 | ![rotary](images/rotary.jpg) 2 | 3 | In the [example code](rotary.py), the pins were connected on the extension board: 4 | * CLK: D26 5 | * DT: D15 6 | * SW: D16 7 | * +: V 8 | * GND: G 9 | 10 | More info about the sensor can be found [here](http://henrysbench.capnfatz.com/henrys-bench/arduino-sensors-and-input/keyes-ky-040-arduino-rotary-encoder-user-manual/). 11 | -------------------------------------------------------------------------------- /sensor-rotary-encoder/images/rotary.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-rotary-encoder/images/rotary.jpg -------------------------------------------------------------------------------- /sensor-rotary-encoder/rotary.py: -------------------------------------------------------------------------------- 1 | """ 2 | read state from rotary encoder using callback function 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | aPin = 26 # CLK pin 9 | bPin = 15 # DT pin 10 | swPin = 16 # SW pin 11 | 12 | GPIO.setwarnings(False) 13 | GPIO.setmode(GPIO.BCM) 14 | 15 | GPIO.setup(aPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 16 | GPIO.setup(bPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 17 | GPIO.setup(swPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 18 | 19 | def eventRotary(e): 20 | if (GPIO.input(bPin) != GPIO.input(aPin)): # a changed before b 21 | print('Rotating clockwise') 22 | #position -= 1 23 | else: 24 | print('Rotating counterclockwise') 25 | #position += 1 26 | 27 | GPIO.add_event_detect(aPin, GPIO.BOTH, bouncetime = 200, callback = eventRotary) 28 | 29 | position = 0 30 | while(True): 31 | time.sleep(0.1) -------------------------------------------------------------------------------- /sensor-temperature/README.md: -------------------------------------------------------------------------------- 1 | This contains info about several temperature sensors: 2 | * [KY-013 Temperature (analog)](#ky-013) 3 | * [KY-028 Temperature (analog and digital)](#ky-028) 4 | * [KY-015 Temperature and Humidity (digital)](#ky-015) 5 | * [KY-015 Temperature and Pressure (analog)](#ky-052) 6 | 7 | ## KY-013 8 | 9 | ![ky013](images/ky013.JPG) 10 | 11 | The value-temperature formula used in this sensor code might need to be calibrated. 12 | To do that, just use the [example code](ky013.py) and read the real values, relating them to the temperature witha a thermometer. 13 | The pins for the extension board, where (`sensor: board`) - following the [example code](ky013.py): 14 | * -: G 15 | * (middle pin): V 16 | * S: A0 17 | 18 | 19 | ## KY-028 20 | 21 | ![ky028](images/ky028.JPG) 22 | 23 | The value-temperature formula used in this sensor code might need to be calibrated. 24 | To do that, just use the [example code](ky013.py) and read the real values, relating them to the temperature witha a thermometer. 25 | The pins for the extension board, where (`sensor: board`) - following the [example code](ky028.py): 26 | * -: G 27 | * +: V 28 | * A0: A0 29 | * D0: D27 30 | 31 | ## KY-015 32 | 33 | ![ky015](images/ky015.JPG) 34 | 35 | There is a library build for this sensor. It already contains an example of use. Get it here: 36 | 37 | [github.com/szazo/DHT11_Python](https://github.com/szazo/DHT11_Python) 38 | 39 | 40 | You can also try this code without the library (not recommended): 41 | 42 | ky015.py(ky015/ky015.py) 43 | 44 | * -: G 45 | * (middle pin): V 46 | * S: D14 47 | 48 | ## KY-052 49 | 50 | ![ky052](images/ky052.JPG) -------------------------------------------------------------------------------- /sensor-temperature/images/ky013.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-temperature/images/ky013.JPG -------------------------------------------------------------------------------- /sensor-temperature/images/ky015.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-temperature/images/ky015.JPG -------------------------------------------------------------------------------- /sensor-temperature/images/ky028.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-temperature/images/ky028.JPG -------------------------------------------------------------------------------- /sensor-temperature/images/ky052.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-temperature/images/ky052.JPG -------------------------------------------------------------------------------- /sensor-temperature/ky013.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | needs spidev installed 5 | http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/ 6 | ''' 7 | import sys 8 | 9 | import RPi.GPIO as GPIO 10 | import time 11 | import spidev 12 | 13 | pd = 0 # S connected to A0 14 | 15 | spi = spidev.SpiDev() 16 | spi.open(0,0) 17 | 18 | def readadc(adcnum): 19 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 20 | if ((adcnum > 3) or (adcnum < 0)): 21 | return-1 22 | r = spi.xfer2([1,8+adcnum <<4,0]) 23 | #print(r) 24 | adcout = ((r[1] &3) <<8)+r[2] 25 | return adcout 26 | 27 | tolerance = 0.5 # degrees 28 | value = readadc(pd) 29 | # calibrate the formula with a termometer 30 | lasttemp = 125.315 - 0.175529 * value # temperature formula made through Wolfram Alpha: 'linear function (0,125);(720,0);(1023,-55)', where (readvalue, temperature) 31 | print('Temperature: %5.2fC (input: %3d)' % (lasttemp, value)) 32 | while True: 33 | value = readadc(pd) 34 | temp = 125.315 - 0.175529 * value # temperature formula 35 | if ((temp > lasttemp + tolerance) or (temp < lasttemp - tolerance)): # if temperature changed more than the tolerance 36 | print('New temperature: %5.2fC (input: %3d)' % (temp, value)) 37 | lasttemp = temp 38 | time.sleep(0.1) 39 | 40 | print('done.') -------------------------------------------------------------------------------- /sensor-temperature/ky015.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | read temperature and humidity from KY-015 5 | 6 | """ 7 | import RPi.GPIO as GPIO 8 | import time 9 | 10 | def bin2dec(string_num): 11 | return str(int(string_num, 2)) 12 | 13 | tempPin = 14 # S connected to D14 14 | 15 | def read_data(pin): 16 | data = 0 17 | for i in range(8): 18 | if (GPIO.input(pin) == GPIO.LOW): 19 | while (GPIO.input(pin) == GPIO.LOW): # wait for 50us 20 | pass 21 | time.sleep(30 * 1e-6) # determine the duration of the high level to determine the data is '0 'or '1' 22 | if (GPIO.input(pin) == GPIO.HIGH): 23 | data |= (1 << (7-i)) # high front and low in the post 24 | while (GPIO.input(pin) == GPIO.HIGH): # data '1 ', wait for the next one receiver 25 | pass 26 | return data 27 | 28 | GPIO.setwarnings(False) 29 | GPIO.setmode(GPIO.BCM) 30 | GPIO.setup(tempPin, GPIO.OUT) 31 | 32 | while True: 33 | GPIO.output(tempPin, GPIO.LOW); # bus down, send start signal 34 | time.sleep(30 * 1e-6); # delay greater than 18ms, so DHT11 start signal can be detected 35 | 36 | GPIO.output(tempPin, GPIO.HIGH); 37 | time.sleep(40 * 1e-6); # Wait for DHT11 response 38 | 39 | GPIO.setup(tempPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 40 | 41 | while (GPIO.input(tempPin) == GPIO.HIGH): 42 | pass 43 | time.sleep(80 * 1e-6) # DHT11 response, pulled the bus 80us 44 | if (GPIO.input(tempPin) == GPIO.LOW): # copied from C version (???) 45 | pass 46 | time.sleep(80 * 1e-6); # DHT11 80us after the bus pulled to start sending data 47 | 48 | dat = [] 49 | for i in range(4): # receive temperature and humidity data, the parity bit is not considered 50 | dat[i] = read_data(tempPin) 51 | 52 | GPIO.setup(tempPin, GPIO.OUT) 53 | GPIO.output(tempPin, GPIO.HIGH); # send data once after releasing the bus, wait for the host to open the next Start signal 54 | 55 | # print results 56 | print('Current humidity: %3d.%d' % (dat[0], dat[1])) 57 | print('Current temperature: %3d.%dC' % (dat[2], dat[3])) 58 | time.sleep(1) -------------------------------------------------------------------------------- /sensor-temperature/ky028.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | needs spidev installed 5 | http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/ 6 | ''' 7 | import sys 8 | 9 | import RPi.GPIO as GPIO 10 | import time 11 | import spidev 12 | 13 | analogPin = 0 # A0 connected to A0 14 | digitalPin = 27 # D0 connected to A1 - not needed 15 | 16 | spi = spidev.SpiDev() 17 | spi.open(0,0) 18 | 19 | GPIO.setwarnings(False) 20 | GPIO.setmode(GPIO.BCM) 21 | GPIO.setup(digitalPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 22 | 23 | def readadc(adcnum): 24 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 25 | if ((adcnum > 3) or (adcnum < 0)): 26 | return-1 27 | r = spi.xfer2([1,8+adcnum <<4,0]) 28 | #print(r) 29 | adcout = ((r[1] &3) <<8)+r[2] 30 | return adcout 31 | 32 | tolerance = 0.5 # degrees 33 | value = readadc(analogPin) 34 | # calibrate the formula with a termometer 35 | lasttemp = 125.315 - 0.175529 * value # formula made through Wolfram Alpha: 'linear function (0,125);(720,0);(1023,-55)', where (readvalue, temperature) 36 | print('Temperature: %5.2f' % lasttemp) 37 | while True: 38 | value = readadc(analogPin) 39 | digital = GPIO.input(digitalPin) 40 | temp = 125.315 - 0.175529 * value 41 | if ((temp > lasttemp + tolerance) or (temp < lasttemp - tolerance)): # if temperature changed more than the tolerance 42 | print('New temperature: %5.2fC (input: a: %3d, d: %3d)' % (temp, value, digital)) 43 | lasttemp = temp 44 | time.sleep(0.1) 45 | 46 | print('done.') -------------------------------------------------------------------------------- /sensor-thumb-joystick/README.md: -------------------------------------------------------------------------------- 1 | * [Linksprite Thumb Joystick](linksprite-thumb-joystick) 2 | 3 | * [KY-023 Joystick Modul](ky-023-joystick) 4 | 5 | 6 | ## Linksprite Thumb Joystick 7 | 8 | [Example code](thumbjoystick.py). 9 | 10 | ![Above View](images/above.jpg) 11 | 12 | ![Rear View](images/rear.jpg) 13 | 14 | ![Below View](images/below.jpg) 15 | 16 | 17 | ## KY-023 Joystick 18 | 19 | [Example code](ky023.py) (very similar to the linksprite one - only the switch has an additional pin). 20 | This sensor has 5 pins, each one specified on the hardware itself. 21 | For the example code, the pins are (`sensor: extension board`): 22 | * x: A0 23 | * y: A1 24 | * sw: D27 (notice the yellow cable on the images below) 25 | * +5V: V 26 | * GND: G 27 | 28 | ![KY023](images/ky023.jpg) 29 | 30 | ![Board Connection](images/ky023connection.jpg) -------------------------------------------------------------------------------- /sensor-thumb-joystick/calibration.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | reads position from thumb-joystick 5 | needs spidev installed 6 | http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/ 7 | """ 8 | import RPi.GPIO as GPIO 9 | import time 10 | import spidev 11 | 12 | xPin = 0 # joystick x connected to A0 13 | yPin = 1 # joystick y connected to A1 14 | 15 | xzero = 512 16 | yzero = 512 17 | 18 | spi = spidev.SpiDev() 19 | spi.open(0,0) 20 | 21 | def readadc(adcnum): 22 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 23 | if ((adcnum > 3) or (adcnum < 0)): 24 | return -1 25 | r = spi.xfer2([1,8 + adcnum << 4, 0]) 26 | print(r) 27 | adcout = ((r[1] &3) << 8) + r[2] 28 | return adcout 29 | 30 | def position(value, zerovalue): 31 | return value - zerovalue 32 | 33 | while True: 34 | value = readadc(xPin) 35 | posx = position(value, xzero) 36 | print("x: %4d/1023 => %5d" % (value, posx)) 37 | value = readadc(yPin) 38 | posy = position(value, yzero) 39 | print("y: %4d/1023 => %5d" % (value, posy)) 40 | 41 | if (posx > (1023 * 3/4)): 42 | print("Button pressed!") 43 | print("") 44 | time.sleep(0.5) 45 | 46 | 47 | 48 | print('done.') -------------------------------------------------------------------------------- /sensor-thumb-joystick/images/above.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-thumb-joystick/images/above.jpg -------------------------------------------------------------------------------- /sensor-thumb-joystick/images/below.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-thumb-joystick/images/below.jpg -------------------------------------------------------------------------------- /sensor-thumb-joystick/images/ky023.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-thumb-joystick/images/ky023.jpg -------------------------------------------------------------------------------- /sensor-thumb-joystick/images/ky023connection.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-thumb-joystick/images/ky023connection.jpg -------------------------------------------------------------------------------- /sensor-thumb-joystick/images/rear.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-thumb-joystick/images/rear.jpg -------------------------------------------------------------------------------- /sensor-thumb-joystick/ky023.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | reads position from thumb-joystick 5 | needs spidev installed 6 | http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/ 7 | """ 8 | import RPi.GPIO as GPIO 9 | import time 10 | import spidev 11 | 12 | xPin = 0 # joystick x connected to A0 13 | yPin = 1 # joystick y connected to A1 14 | swPin = 27 # sw connected to D27 15 | 16 | GPIO.setwarnings(False) 17 | GPIO.setmode(GPIO.BCM) 18 | GPIO.setup(swPin, GPIO.IN, pull_up_down=GPIO.PUD_UP) 19 | 20 | tolerancevalue = 10 21 | xZero = 512 22 | yZero = 512 23 | 24 | spi = spidev.SpiDev() 25 | spi.open(0,0) 26 | 27 | def readadc(adcnum): 28 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 29 | if ((adcnum > 3) or (adcnum < 0)): 30 | return -1 31 | r = spi.xfer2([1,8 + adcnum << 4, 0]) 32 | print(r) 33 | adcout = ((r[1] &3) << 8) + r[2] 34 | return adcout 35 | 36 | def position(adcnum, zerovalue): 37 | return readadc(adcnum) - zerovalue 38 | 39 | 40 | def eventSWButton(e): 41 | print("SW from joystick pressed") 42 | print(e) 43 | 44 | # using the callback is optional 45 | GPIO.add_event_detect(swPin, GPIO.FALLING, bouncetime = 200, callback = eventSWButton) 46 | 47 | while True: 48 | xPos = position(xPin, xZero) 49 | yPos = position(yPin, yZero) 50 | 51 | # in case you don't want to use the callback 52 | #if (GPIO.input(swPin) == 0): 53 | # print("Button pressed!") 54 | 55 | if (abs(xPos) < tolerancevalue): 56 | print("Not moving in X.") 57 | elif (xPos > 0): 58 | print("Moving ahead.") 59 | print("X intensity: %5d" % abs(xPos)) 60 | else: 61 | print("Moving backwards.") 62 | print("X intensity: %5d" % abs(xPos)) 63 | 64 | if (abs(yPos) < tolerancevalue): 65 | print("Not moving in Y.") 66 | elif (yPos > 0): 67 | print("Moving left.") 68 | print("Y intensity: %5d" % abs(yPos)) 69 | else: 70 | print("Moving right.") 71 | print("Y intensity: %5d" % abs(yPos)) 72 | 73 | print("") 74 | time.sleep(0.5) 75 | 76 | print('done.') -------------------------------------------------------------------------------- /sensor-thumb-joystick/thumbjoystick.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | reads position from thumb-joystick 5 | needs spidev installed 6 | http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/ 7 | """ 8 | import RPi.GPIO as GPIO 9 | import time 10 | import spidev 11 | 12 | xPin = 0 # joystick x connected to A0 13 | yPin = 1 # joystick y connected to A1 14 | 15 | tolerancevalue = 10 16 | xZero = 512 17 | yZero = 512 18 | 19 | spi = spidev.SpiDev() 20 | spi.open(0,0) 21 | 22 | def readadc(adcnum): 23 | # read SPI data from MCP3004 chip, 4 possible adc’s (0 thru 3) 24 | if ((adcnum > 3) or (adcnum < 0)): 25 | return -1 26 | r = spi.xfer2([1,8 + adcnum << 4, 0]) 27 | print(r) 28 | adcout = ((r[1] &3) << 8) + r[2] 29 | return adcout 30 | 31 | def position(adcnum, zerovalue): 32 | return readadc(adcnum) - zerovalue 33 | 34 | while True: 35 | xPos = position(xPin, xZero) 36 | yPos = position(yPin, yZero) 37 | 38 | if (xPos > (1023 * 3/4)): 39 | print("Button pressed!") 40 | elif (abs(xPos) < tolerancevalue): 41 | print("Not moving in X.") 42 | elif (xPos > 0): 43 | print("Moving ahead.") 44 | print("X intensity: %5d" % abs(xPos)) 45 | else: 46 | print("Moving backwards.") 47 | print("X intensity: %5d" % abs(xPos)) 48 | 49 | if (abs(yPos) < tolerancevalue): 50 | print("Not moving in Y.") 51 | elif (yPos > 0): 52 | print("Moving left.") 53 | print("Y intensity: %5d" % abs(yPos)) 54 | else: 55 | print("Moving right.") 56 | print("Y intensity: %5d" % abs(yPos)) 57 | 58 | print("") 59 | time.sleep(0.5) 60 | 61 | print('done.') -------------------------------------------------------------------------------- /sensor-tilt/README.md: -------------------------------------------------------------------------------- 1 | ## Sensor KY-017 and KY-020: Tilt switch sensor 2 | Tilt sensors are used to detect orientation or inclination. 3 | 4 | KY-017 5 | ![ky017](images/ky017.jpg) 6 | 7 | KY-020 8 | ![ky020](images/ky020.jpg) 9 | 10 | Valid for both sensors: 11 | The pins for the extension board, where (`sensor: board`) - following the [example code](tilt.py): 12 | * -: G 13 | * (middle pin): V 14 | * S: D15 15 | -------------------------------------------------------------------------------- /sensor-tilt/images/ky017.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-tilt/images/ky017.jpg -------------------------------------------------------------------------------- /sensor-tilt/images/ky020.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-tilt/images/ky020.jpg -------------------------------------------------------------------------------- /sensor-tilt/tilt.py: -------------------------------------------------------------------------------- 1 | """ 2 | read state from tilt switch sensor using callback functions 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | tiltPin = 15 # S connected to D15 9 | 10 | GPIO.setwarnings(False) 11 | GPIO.setmode(GPIO.BCM) 12 | GPIO.setup(tiltPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 13 | 14 | lastState = GPIO.input(tiltPin) 15 | 16 | def eventTiltSwitch(e): 17 | print("Tilted!") 18 | 19 | GPIO.add_event_detect(tiltPin, GPIO.BOTH, bouncetime = 200, callback = eventTiltSwitch) 20 | 21 | while(True): 22 | time.sleep(0.1) 23 | #print(GPIO.input(tiltPin)) -------------------------------------------------------------------------------- /sensor-touch/README.md: -------------------------------------------------------------------------------- 1 | ## Sensor KY-036: Touch sensor 2 | 3 | ![ky036](images/ky036.jpg) 4 | 5 | The *pins need to be remaped* for the extension board, where (`sensor: board`) - following the [example code](touch.py): 6 | * A0: D27 7 | * G: G 8 | * +: V 9 | * D0: D26 10 | 11 | 12 | * A0 – inverted signal 13 | * G – should be connected to ground 14 | * + – should be connected to 5V power supply 15 | * D0 – touch signal 16 | -------------------------------------------------------------------------------- /sensor-touch/images/ky036.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-touch/images/ky036.jpg -------------------------------------------------------------------------------- /sensor-touch/touch.py: -------------------------------------------------------------------------------- 1 | """ 2 | read state from touch sensor using callback functions 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | touchPin = 26 # D0 connected to D26 9 | touchInvPin = 27 # A0 connected to D27 10 | 11 | GPIO.setwarnings(False) 12 | GPIO.setmode(GPIO.BCM) 13 | GPIO.setup(touchPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 14 | 15 | def eventTouchSensor(e): 16 | print("Sensor touched!") 17 | print(e) 18 | 19 | GPIO.add_event_detect(touchPin, GPIO.RISING, bouncetime = 200, callback = eventTouchSensor) 20 | 21 | while(True): 22 | time.sleep(0.1) -------------------------------------------------------------------------------- /sensor-ultrasonic-distance/README.md: -------------------------------------------------------------------------------- 1 | This is the HCSR04 sensor, see datasheet for details on operation 2 | 3 | ![image of device](pic1.JPG) 4 | -------------------------------------------------------------------------------- /sensor-ultrasonic-distance/datasheet_HCSR04.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-ultrasonic-distance/datasheet_HCSR04.pdf -------------------------------------------------------------------------------- /sensor-ultrasonic-distance/pic1.JPG: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-ultrasonic-distance/pic1.JPG -------------------------------------------------------------------------------- /sensor-ultrasonic-distance/ultrasonic-distance.c: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * This is not finished, use the python version instead. 4 | *********************************************************************** 5 | */ 6 | 7 | #include 8 | #include 9 | 10 | // LED Pin - wiringPi pin 0 is BCM_GPIO 17. 11 | 12 | #define PTRIG 17 13 | #define PECHO 18 14 | 15 | int timerStart = 0; 16 | 17 | void interruptHandler(void) 18 | { 19 | //printf("interrupt!S"); fflush (stdout); 20 | int now = micros(); 21 | int delay = now - timerStart; 22 | printf("%f\n", delay / 58.0); fflush (stdout); 23 | 24 | //cm = pulseIn(PECHO, HIGH) / 58.0; //Echo time convert to cm 25 | //cm = (int(cm * 100.0)) / 100.0; //Keep two decimal places 26 | } 27 | 28 | 29 | int main(void) 30 | { 31 | printf("Raspberry Pi distance measure\n"); 32 | 33 | wiringPiSetupGpio(); 34 | pinMode(PTRIG, OUTPUT); 35 | //pinMode(PECHO, INPUT); 36 | //pullUpDnControl(PECHO,PUD_DOWN); 37 | wiringPiISR(PECHO, INT_EDGE_RISING, &interruptHandler); 38 | printf("callback registered\n"); 39 | 40 | 41 | 42 | 43 | 44 | for(;;) 45 | { 46 | digitalWrite(PTRIG, LOW); //Send a voltage pulse to TrigPin 47 | delayMicroseconds(2); 48 | digitalWrite(PTRIG, HIGH); 49 | delayMicroseconds(10); 50 | digitalWrite(PTRIG, LOW); 51 | timerStart = micros(); 52 | 53 | delay(200); 54 | 55 | } 56 | 57 | 58 | return 0 ; 59 | } 60 | -------------------------------------------------------------------------------- /sensor-ultrasonic-distance/ultrasonic-distance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | import sys 4 | 5 | 6 | import RPi.GPIO as GPIO 7 | import time 8 | 9 | 10 | ptrig = 26 11 | pecho = 27 12 | 13 | def setup(): 14 | GPIO.setwarnings(False) 15 | GPIO.setmode(GPIO.BCM) 16 | GPIO.setup(pecho, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 17 | GPIO.setup(ptrig, GPIO.OUT) 18 | GPIO.output(ptrig, 0) 19 | 20 | 21 | 22 | def getValue(): 23 | GPIO.output(ptrig, 0) 24 | time.sleep(0.1) 25 | GPIO.output(ptrig, 1) 26 | time.sleep(0.00001) 27 | GPIO.output(ptrig, 0) 28 | 29 | 30 | while(0 == GPIO.input(pecho)): 31 | start = time.time() 32 | while(1 == GPIO.input(pecho)): 33 | end = time.time() 34 | 35 | 36 | delay = (end - start) * 1000 * 1000 37 | time.sleep(0.1) 38 | distance = (delay / 58.0) 39 | if 2 < distance < 400: # working interval 40 | print("distance: %0.1f cm" % distance) 41 | 42 | 43 | setup() 44 | while(True): 45 | getValue() 46 | print('done.') 47 | 48 | -------------------------------------------------------------------------------- /sensor-vibration/README.md: -------------------------------------------------------------------------------- 1 | ## Sensor KY-002: Vibration sensor 2 | 3 | ![ky002](images/ky002.jpg) 4 | 5 | The pins for the extension board, where (`sensor: board`) - following the [example code](vibration.py): 6 | * -: G 7 | * (middle pin): V 8 | * S: D15 9 | -------------------------------------------------------------------------------- /sensor-vibration/images/ky002.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/sensor-vibration/images/ky002.jpg -------------------------------------------------------------------------------- /sensor-vibration/vibration.py: -------------------------------------------------------------------------------- 1 | """ 2 | read state from vibration sensor using callback functions 3 | 4 | """ 5 | import RPi.GPIO as GPIO 6 | import time 7 | 8 | vibPin = 15 # S connected to D15 9 | 10 | GPIO.setwarnings(False) 11 | GPIO.setmode(GPIO.BCM) 12 | GPIO.setup(vibPin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) 13 | 14 | lastState = GPIO.input(vibPin) 15 | 16 | def eventVibration(e): 17 | print("Vibrated!") 18 | 19 | GPIO.add_event_detect(vibPin, GPIO.RISING, bouncetime = 200, callback = eventVibration) 20 | 21 | while(True): 22 | time.sleep(0.1) 23 | #print(GPIO.input(vibPin)) -------------------------------------------------------------------------------- /setup-raspberrypi/README.md: -------------------------------------------------------------------------------- 1 | # List of contents 2 | * [Raspbian (OS) install](#install) 3 | * [Updates](#update) 4 | * [SPI enable](#spi-enable) 5 | * [SSH Access](#ssh-access) 6 | * [SD card reset](#sd-card-reset) 7 | * [SO issue solving](#issue-solving) 8 | * [Eduroam wlan config](#eduroam) 9 | * [VPN IPVS](#vpn-ipvs) 10 | 11 | ## Install 12 | 13 | This guide is also found [here](https://www.raspberrypi.org/documentation/installation/noobs.md). 14 | * [Download NOOBS offline and network install](https://www.raspberrypi.org/downloads/noobs/) 15 | * Format a microSD (at least 4GB) on **FAT32** 16 | * Unzip the content of the downloaded file on the card. The card content should look like: 17 | ![SD card content](images/noobfiles.png) 18 | * Plug the card and plug the power on the Raspberry (in that order) 19 | * When the loading is complete, select the *Raspbian* option and click on Install 20 | ![RASPBIAN INSTALL](images/raspinstall.png) 21 | * Wait until the installation is finished and the OS is ready 22 | 23 | ## Update 24 | 25 | ### SO Update 26 | * Open the terminal (`ctrl + alt + T`) 27 | * Do the following commands (type `y` for the incoming questions after each command): 28 | * `sudo apt-get update` 29 | * `sudo apt-get dist-upgrade` 30 | 31 | ### Firmware Update 32 | * Open the terminal (`ctrl + alt + T`) 33 | * Do the following commands (type `y` for the incoming questions after each command): 34 | * `sudo rpi-update` 35 | * `reboot` 36 | 37 | ## SPI Enable 38 | This guide is also found [here](http://www.raspberrypi-spy.co.uk/2014/08/enabling-the-spi-interface-on-the-raspberry-pi/). 39 | * Run `sudo raspi-config` on the terminal 40 | * Navigate to `9 Advanced Options` 41 | * Navigate to `A5 SPI` 42 | * Select `Enable` 43 | * Select `Yes` when asked about the kernel module 44 | * Select `Yes` when asked to reboot the system 45 | You can check if it's enable through the command on the terminal: 46 | `lsmod | grep spi_` 47 | You should see “spi_bcm2708″ or “spi_bcm2835” 48 | To check if the library is available for python: 49 | `apt-mark showauto | grep spi` 50 | You should see the two python spidev packages listed in the output. 51 | 52 | 53 | 54 | ## SSH Access 55 | 56 | This guide is also found [here](https://www.raspberrypi.org/documentation/remote-access/ssh/). 57 | SSH is already enabled on RaspberryPi by default. 58 | To access, you will need to check the RaspberryPi IP. That can be done through the terminal with on of the following commands (`eth0` stands for your ethernet interface IP and`wlan0` for your wireless interface IP): 59 | * `sudo ifconfig -a` 60 | * `sudo ip addr show` 61 | * `sudo hostname --ip-address` 62 | The default *username* is `pi` and the default *password* is `raspberry`. 63 | If the SSH is **not enabled**, you can enable through: 64 | * Run `sudo raspi-config` on the terminal 65 | * Navigate to `9 Advanced Options` 66 | * Navigate to `A4 SSH` 67 | * Select `Enable` 68 | 69 | ## SD card reset 70 | 71 | This guide is also found [here](http://kb.sandisk.com/app/answers/detail/a_id/14827/~/using-sd-formatter-tool-to-restore-full-capacity-on-sdhc%2Fsdxc-cards). 72 | * [Download SD Formatter Tool](https://www.sdcard.org/downloads/formatter_4/) (scroll to the bottom of the page) 73 | * Install the application 74 | * With the SD card plugged, open the application 75 | * Go to *Option*, change *FORMAT SIZE ADJUSTMENT* to *ON* 76 | ![OPTION BUTTON](images/sdresetoption.png) 77 | ![FORMAT SIZE ADJUSTMENT](images/sdresetformatsize.png) 78 | * Click on *Format* 79 | 80 | ## Issue Solving 81 | 82 | ### Display resolution problem 83 | 84 | This resolution is also found [here](http://weblogs.asp.net/bleroy/getting-your-raspberry-pi-to-output-the-right-resolution). 85 | * Open the terminal (`ctrl + alt + T`) 86 | * Do the following commands (type `y` for the incoming questions after each command): 87 | * `tvservice -d edid` 88 | * `edidparser edid` 89 | * Edit the file `/boot/config.txt` 90 | * `nano /boot/config.txt` 91 | * Uncomment the following lines and put those values (If your mode description from the last command contains “DMT”, the group should be 2, and if it contains “CEA”, it should be 1): 92 | * `hdmi_group=2` 93 | * `hdmi_mode=82` 94 | 95 | ## Eduroam 96 | This resolution is based on this [link](http://www.willprice.org/2014/03/17/eduroam-on-the-raspberry-pi.html) 97 | * Open the terminal (`ctrl + alt + T`) 98 | * Do the following command to stop the network on Raspberry: 99 | * `sudo service networking stop` 100 | * Now acces the file `wpa_supplicant.conf` as administrator: 101 | * You can open it on terminal with the command `sudo leafpad /etc/wpa_supplicant/wpa_supplicant.conf` 102 | * Or you go to the folder `/etc/wpa_supplicant/`, right click on `wpa_supplicant.conf` and choose `Open With`. Change the tab from `Installed Applications` to `Custom Command Line` and write `sudo leafpad`: 103 | 104 | ![Right Click](right_click.png) 105 | 106 | * Then you will find the reference to the eduroam network and change it to : 107 | * 108 | `network={ 109 | identity="ab1234" 110 | password="myUOBpassword" 111 | ca_cert="/etc/ssl/certs/Deutsche_Telekom_Root_CA_2.pem" 112 | eap=PEAP TTLS 113 | anonymous_identity="@" 114 | phase1="peaplabel=0" 115 | phase2="auth=MSCHAPV2" 116 | priority=999 117 | disabled=0 118 | ssid="eduroam" 119 | scan_ssid=0 120 | mode=0 121 | auth_alg=OPEN 122 | proto=WPA RSN 123 | pairwise=CCMP TKIP 124 | key_mgmt=WPA-EAP 125 | proactive_key_caching=1 126 | }` 127 | * Change your identity and password and save the file. 128 | * After, run `sudo wpa_supplicant -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf -B` 129 | * Your connection should work! 130 | 131 | ## VPN IPVS 132 | * [Download Cisco AnyConnect Secure Mobility Client](http://www.cisco.com/c/en/us/support/security/anyconnect-secure-mobility-client/tsd-products-support-series-home.html) 133 | * Install and connect to: `asa1.informatik.uni-stuttgart.de` 134 | * Use your IPVS username/password 135 | -------------------------------------------------------------------------------- /setup-raspberrypi/images/noobfiles.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/setup-raspberrypi/images/noobfiles.png -------------------------------------------------------------------------------- /setup-raspberrypi/images/raspinstall.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/setup-raspberrypi/images/raspinstall.png -------------------------------------------------------------------------------- /setup-raspberrypi/images/sdresetformatsize.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/setup-raspberrypi/images/sdresetformatsize.png -------------------------------------------------------------------------------- /setup-raspberrypi/images/sdresetoption.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/setup-raspberrypi/images/sdresetoption.png -------------------------------------------------------------------------------- /setup-raspberrypi/right_click.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/timwaizenegger/raspberrypi-examples/de5f20e6c20fe4eb713f34c7226c9d0d2249afc3/setup-raspberrypi/right_click.png --------------------------------------------------------------------------------