2013-01-20 10 views
9

Próbuję odczytać dane z Arduino UNO do Raspberry Pi z modułem python smbus. Jedyną dokumentacją, jaką mogłem znaleźć na module smbus, była here. Nie jestem pewien, co oznacza cmd w module. Mogę użyć zapisu do wysłania danych do Arduino. Pisałem dwa proste programy jeden do odczytu i jeden do zapisuJak odczytać dane z Arduino z Raspberry Pi z I2C

Jeden do zapisu

import smbus 
b = smbus.SMBus(0) 
while (0==0): 
    var = input("Value to Write:") 
    b.write_byte_data(0x10,0x00,int(var)) 

jeden dla czytać

import smbus 
bus = smbus.SMBus(0) 
var = bus.read_byte_data(0x10,0x00) 
print(var) 

Kod Arduino jest

#include <SoftwareSerial.h> 
#include <LiquidCrystal.h> 
#include <Wire.h> 
LiquidCrystal lcd(8,9,4,5,6,7); 

int a = 7; 

void setup() 
{ 
    Serial.begin(9600); 
    lcd.begin(16,2); 
    // define slave address (0x2A = 42) 
    #define SLAVE_ADDRESS 0x10 

    // initialize i2c as slave 
    Wire.begin(SLAVE_ADDRESS); 

    // define callbacks for i2c communication 
    Wire.onReceive(receiveData); 
    Wire.onRequest(sendData); 
} 
void loop(){ 
} 

// callback for received data 
void receiveData(int byteCount) 
{ 
Serial.println(byteCount); 
    for (int i=0;i <= byteCount;i++){ 
    char c = Wire.read(); 
    Serial.println(c); 
} 
} 

// callback for sending data 
void sendData() 
{ 
    Wire.write(67); 
    lcd.println("Send Data"); 
} 

Kiedy uruchomię program czytający, za każdym razem zwraca "33". Arduino zwraca, że ​​wywoływana jest funkcja sendData.

Używam Data Level Shifter, a opis mówi, że może być trochę powolny.

Czy ktoś to zrobił?

Odpowiedz

10

Udało mi się zainicjować komunikację pomiędzy Arduino i Raspberry Pi. Dwa są połączone za pomocą dwóch rezystorów 5k pullup (patrz: page). Arduino zapisuje bajt na magistrali i2c dla każdego żądania. Na Raspberry Pi, hello jest drukowana co sekundę. Kod

Arduino:

#include <Wire.h> 
#define SLAVE_ADDRESS 0x2A 

void setup() { 
    // initialize i2c as slave 
    Wire.begin(SLAVE_ADDRESS); 
    Wire.onRequest(sendData); 
} 

void loop() { 
} 

char data[] = "hello"; 
int index = 0; 

// callback for sending data 
void sendData() { 
    Wire.write(data[index]); 
    ++index; 
    if (index >= 5) { 
     index = 0; 
    } 
} 

kod Python na Raspberry Pi:

#!/usr/bin/python 

import smbus 
import time 
bus = smbus.SMBus(1) 
address = 0x2a 

while True: 
    data = "" 
    for i in range(0, 5): 
      data += chr(bus.read_byte(address)); 
    print data 
    time.sleep(1); 

Na moim Raspberry Pi, magistrali I2C to 1. Użyj komendy i2c-detect -y 0 lub i2c-detect -y 1 Aby sprawdzić, czy Malina Pi wykrywa twoje Arduino.