使用I2C从arduino上的模拟引脚读取值并将其发送到raspberry pi。它返回奇怪的数字,如122或255

时间:2014-03-02 22:34:17

标签: python arduino raspberry-pi i2c

SETUP:

MASTER DEVICE:Raspberry Pi Model B REV_2

SLAVE DEVICE:Arduino Uno REV_3

问题:

每当我在命令行中输入“r”时,它会返回一个完全偏离它的数字。例如,当我将跳线连接到模拟引脚A0高达5V并在命令行上按“r”时,它应返回5伏。好吧,它返回255.当我将jumber线连接到3.3V引脚时,它返回169.

注:

编写此代码的人确实注意到了我认为可能与此问题相关的内容。他的话如下......

“Arduino中的setup函数然后设置两个将被使用的回调函数。每当on Receive事件发生时,函数processMessage将被调用。这将是从Raspberry Pi发送命令的时候。另一个回调函数sendAnalogReading与onRequest事件相关联。当Raspberry Pi请求数据并将读取模拟值除以4以使其适合单个字节,然后将其发送回Raspberry Pi时,就会发生这种情况。“

我不知道他的意思是将值除以使其适合单个字节。这是为什么我会收到奇怪的数字?有人可以解释一下吗。

只是为了使这个线程更加清晰,这是我的设置和发出多个命令时显示的输出。

sudo python ardu_pi_i2c.py //运行我的程序

首先,我将跳线连接到arduino上的引脚A0到GRD。然后我选择了“r”选项,它给了我“0”

第二种情况我将跳线连接到arduino上的引脚A0到5V。然后我选择“r”,它给了我“255”

第三种情况我将跳线从引脚A0连接到3.3V。它给了我171.

第四种情况我将跳线从A0引脚连接到LED的负极,它给了我“0”

第五种情况我将跳线从引脚A0连接到LED的正极,它给了我“105”。

由于第一个和第四个场景似乎有点工作,我很好奇为什么其他数字离开了,如果它们对它们有一些实际意义。

enter image description here

PSUEDO代码:

//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);}

1 个答案:

答案 0 :(得分:2)

我认为输出是0到255范围内的数字(所有适合一个字节的值),对应的范围是0到5伏。因此,为了将读取的数字转换为电压,您可以

voltage = number * 5.0 / 255.

您会发现number = 255voltage = 5.0;
对于number = 171,您获得voltage = 3.35

听起来对我不错。这意味着LED + ve侧的电压为

105 * 5.0 / 255 = 2.05 V

这不是一个疯狂的价值。

相关问题