簡體   English   中英

使用I2C從arduino上的模擬引腳讀取值並將其發送到raspberry pi。 它返回奇怪的數字,如122或255

[英]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 = 171voltage = 3.35

聽起來對我來說。 這意味着LED的+ ve側的電壓為

105 * 5.0 / 255 = 2.05 V

這不是一個瘋狂的價值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM