【发布时间】:2014-03-02 22:34:16
【问题描述】:
设置:
主设备:Raspberry Pi Model B REV_2
从设备:Arduino Uno REV_3
问题:
每当我在命令行中输入“r”时,它都会返回一个完全不应该的数字。例如,当我将跳线连接到最高 5V 的模拟引脚 A0 并在命令行上按“r”时,它应该返回 5 伏。嗯,它返回 255。当我将跳线连接到 3.3V 引脚时,它返回 169。
注意:
编写此代码的人确实注意到了一些我认为可能与此问题相关的内容。他的话如下......
“然后,Arduino 中的 setup 函数设置了两个将使用的回调函数。函数 processMessage 将在 on Receive 事件发生时被调用。这将是每当从 Raspberry Pi 发送命令时。另一个回调函数, sendAnalogReading, 与 onRequest 事件相关联。当 Raspberry Pi 请求数据并读取模拟值除以 4 以使其适合单个字节,然后将其发送回 Raspberry Pi 时,就会发生这种情况。”
我不知道他将值除以使其适合单个字节是什么意思。这就是为什么我会得到奇怪的数字吗?有人可以解释一下吗。
只是为了让这个线程更清楚,这里是我的设置和发出多个命令时显示的输出。
sudo python ardu_pi_i2c.py //运行我的程序
第一种情况,我将跳线从引脚 A0 连接到 arduino 上的 GRD。然后我选择了“r”选项,它给了我“0”
第二种情况,我将跳线从 arduino 上的引脚 A0 连接到 5V。然后我选择“r”,它给了我“255”
第三种情况我将跨接线从引脚 A0 连接到 3.3V。它给了我 171。
第四种情况,我将跨接线从引脚 A0 连接到 LED 的负极,它给了我“0”
第五种情况,我将跳线从引脚 A0 连接到 LED 的正极,它给了我“105”。
由于第一个和第四个场景似乎很顺利,我很好奇为什么其他数字会偏离,以及它们是否对它们有一些实际意义。
伪代码:
//Creates instance of SMBus called bus
//Prompts user for command "l" (toggles led) or "r" (reads from Analog pin 0)
//if command is l it writes it to arduino and causes onReceive handler(processmessage)
//if command is r then request_reading function will be called
//this will call read_byte in SMBus library that causes the on Request event to be invoked.
Python 程序
import smbus
import time
bus = smbus.SMBus(1)
SLAVE_ADDRESS = 0x04
def request_reading():
reading = int(bus.read_byte(SLAVE_ADDRESS))
print(reading)
while True:
command = raw_input("Enter command: l - toggle LED, r - read A0 ")
if command == 'l' :
bus.write_byte(SLAVE_ADDRESS, ord('l'))
elif command == 'r' :
request_reading()
ARDUINO 程序
#include <Wire.h>
int SLAVE_ADDRESS = 0x04;
int ledPin = 13;
int analogPin = A0;
boolean ledOn = false;
void setup()
{
pinMode(ledPin, OUTPUT);
Wire.begin(SLAVE_ADDRESS);
Wire.onReceive(processMessage);
Wire.onRequest(sendAnalogReading);
Serial.begin(9600);
}
void loop()
{
}
void processMessage(int n){
Serial.println("In processMessage");
char ch = Wire.read();
if (ch == 'l'){
toggleLED();}}
void toggleLED(){
ledOn = ! ledOn;
digitalWrite(ledPin, ledOn);}
void sendAnalogReading(){
Serial.println("In sendAnalogReading");
int reading = analogRead(analogPin);
Wire.write(reading >> 2);}
【问题讨论】:
标签: python arduino raspberry-pi i2c