-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpi2c.py
88 lines (67 loc) · 2.86 KB
/
rpi2c.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python
#
# RPi2c - test i2c communication between an Arduino and a Raspberry Pi.
#
# Copyright (c) 2013 Carlos Rodrigues <cefrodrigues@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
from __future__ import division
from __future__ import print_function
import RPi.GPIO as GPIO
import smbus
import time
import sys
I2C_BUS = 1
I2C_SLAVE = 0x03
INTERRUPT_PIN = 17
def interpolate(value, a1, a2, b1, b2):
# Normalize the value into a 0..1 interval...
n = float(value - a1) / float(a2 - a1)
# Scale the normalized value to the target interval...
return b1 + (n * (b2 - b1))
if __name__ == '__main__':
# Initialize the interrupt pin...
GPIO.setmode(GPIO.BCM)
GPIO.setup(INTERRUPT_PIN, GPIO.IN)
# Initialize the RPi I2C bus...
i2c = smbus.SMBus(I2C_BUS)
while 1:
try:
# Wait until the Arduino triggers the interrupt...
GPIO.wait_for_edge(INTERRUPT_PIN, GPIO.RISING)
try:
# Get the sensor value from the Arduino (signed 16bit little-endian)...
sensor_value = i2c.read_word_data(I2C_SLAVE, 0x00)
sys.stdout.write("sensor: %d" % sensor_value)
except IOError:
sys.stderr.write("*** error: receiving sensor value ***\n")
continue
sys.stdout.write(" / ")
try:
# Map the sensor value to a [0, 255] interval...
led_value = int(interpolate(sensor_value, 0, 1023, 0, 255))
sys.stdout.write("led: %d\n" % led_value)
# Send the PWM value for the LED to the Arduino...
i2c.write_byte_data(I2C_SLAVE, 0x01, led_value)
except IOError:
sys.stderr.write("*** error: sending led value ***\n")
except KeyboardInterrupt:
GPIO.cleanup()
# vim: set expandtab ts=4 sw=4: