2013-01-20 41 views
9

Tôi đang cố gắng đọc dữ liệu từ Arduino UNO đến Raspberry Pi với mô-đun python python. Tài liệu duy nhất tôi có thể tìm thấy trên mô-đun smbus là here. Tôi không chắc chắn những gì cmd có nghĩa là trong mô-đun. Tôi có thể sử dụng ghi để gửi dữ liệu đến Arduino. Tôi đã viết hai chương trình đơn giản một cho đọc và một cho ghiLàm thế nào để đọc dữ liệu từ Arduino với Raspberry Pi với I2C

Một cho ghi

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

Một cho đọc

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

Mã Arduino là

#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"); 
} 

Khi tôi chạy chương trình đọc nó trả về "33" mỗi lần. Arduino trả về rằng hàm sendData được gọi.

Tôi đang sử dụng Data Level Shifter và mô tả cho biết có thể hơi chậm chạp.

Có ai đã làm việc này không?

Trả lời

10

Tôi đã quản lý để bắt đầu liên lạc giữa Arduino và Raspberry Pi. Cả hai được kết nối bằng cách sử dụng hai điện trở kéo 5k (xem này page). Arduino viết một byte trên bus i2c cho mỗi yêu cầu. Trên Raspberry Pi, hello được in mỗi giây. đang

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

Python mã trên 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); 

On Raspberry Pi của tôi, xe buýt I2C là 1. Sử dụng lệnh i2c-detect -y 0 hoặc i2c-detect -y 1 để xác minh nếu Raspberry của bạn Pi phát hiện Arduino của bạn.

Các vấn đề liên quan