簡體   English   中英

Raspberry Pi 是否可以通過 I2C 讀取從 Arduino 發送的數據?

[英]Is there a way for a Raspberry Pi to read data being sent from the Arduino with I2C?

我正在嘗試使用 Python smbus 模塊將數據從 Arduino 讀取到 Raspberry Pi。 我試圖讓 Pi 讀取的數據只是數字,例如 200、100 490 等,基本上類似於向 Pi 報告其狀態的狀態代碼。 但是,我無法在網上找到 smbus 文檔,只找到了一塊拼圖,即bus.read_byte僅從Arduino 接收到的數據中讀取一個字節。

因此,當前代碼在運行時只能顯示 0(或一些神秘框):

藍色字是發給Arduino的數據,0框是接收到的數據

這是全面了解實際情況的主要代碼:

import time
from smbus import SMBus

clientAddr = 0x08
bus = SMBus(1)

def i2cWrite(msg): # Main Issue
  for c in msg:
    bus.write_byte(clientAddr, ord(c))
  return -1

def main():
  print("Send message to Arduino") 
  while True:
    print(bus.read_byte(clientAddr)) # Part that deals with printing messages from arduino on to python terminal
    msg = input("> ")
    print("...")
    i2cWrite(msg)
    

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print("Program Terminated Manually")

我試圖從我的 Arduino 發送的信息是來自電位器的 output,它正常運行並輸出其當前值,只是它沒有出現在 Pi 側。

Arduino 代碼主要部分:

// Function that executes whenever data is received from master
void receiveEvent(int howMany) {
  while (Wire.available()) { // loop through all but the last
    // receive byte as a character, char converts unicode to character and add these characters into string
    received_str += (char)Wire.read();
  }
}

// Function that sends data to Master (Pi)
void sendData(int msg)
{
  Wire.write(msg);
}

void loop() {
  delay(100);
  int sensorValue = analogRead(A0);
  Serial.println(sensorValue);
  sendData(sensorValue);
  int n = received_str.toInt();
  //Serial.print(n);
  analogWrite(ENA, 255); //for H bridge PWM
  if (n > 0) {
    Serial.print(received_str);
    Serial.println();
    received_str = "";
  } else {
    received_str = "";
  }
}

Serial Monitor Output:實際工作的電位器串行監視器

所以據我了解,Arduino 端沒有問題,但它只是不想在嘗試從 Arduino 接收數據到 Pi 時按需要工作。 我應該使用read_byte以外的東西嗎? 如果是這樣,哪個?

編輯實際上導致框出現的是代碼的這一部分:

def i2cRead():
    data = ""
    for i in range(0, 5):
            data += chr(bus.read_byte(clientAddr));
    print(data)
    time.sleep(0.5);

這只是添加以查看它是否會修復錯誤,但不幸的是,它沒有

想通了這個問題,結果發現 Arduino 代碼在設置部分需要一個onRequest(event)來基本上注冊一個 function 以便在主機請求數據時調用。

python 上的主碼也被處理,成功地將 arduino 的數據打印到 Pi

def i2cRead():
    data = bus.read_byte(clientAddr)

暫無
暫無

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

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