[英]Using I2C to read value from analog pin on arduino and sending it to raspberry pi. It returns weird numbers like 122 or 255
设定:
MASTER DEVICE:Raspberry Pi Model B REV_2
奴役装置: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”。
由于第一个和第四个场景似乎有点工作,我很好奇为什么其他数字离开了,如果它们对它们有一些实际意义。
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);}
我相信输出是0到255范围内的数字(所有值都适合一个字节),对应的范围是0到5伏。 因此,为了将读取的数字转换为电压,您可以
voltage = number * 5.0 / 255.
你会发现,对于number = 255
,你得到voltage = 5.0
;
number = 171
, voltage = 3.35
听起来对我来说。 这意味着LED的+ ve侧的电压为
105 * 5.0 / 255 = 2.05 V
这不是一个疯狂的价值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.