Comunicação i2C entre o Arduino e o Raspberry Pi, ou outro Arduino.
Bloco de código para teste da comunicação i2C entre o Arduino e o Raspberry Pi. Tambem pode ser usado para comunicar com outro Arduino
Raspberry Pi: master
Arduino: slave
Bloco para o Arduino em C++
i2c_slave_mod1_v1
/*
* I2C comunication demo 1
*
* Arduino Slave to Raspberry Pi Master
*
* I2C slave
* Receive a byte (1-255) from Raspberry Pi or Arduino and send it back
* If byte is 1 toogle the internal led
*
*/
#include <Wire.h>
#define LEDPIN 13
#define SLAVE_ADDRESS 0x07
byte received = 0;
boolean ledState = false;
unsigned long loopTimeStart;
void setup() {
// init Serial
Serial.begin(115200); // start serial for output
// init i2c as slave
Wire.begin(SLAVE_ADDRESS);
// define i2c callbacks
Wire.onReceive(receiveData);
Wire.onRequest(sendData);
// init ledPin
pinMode(LEDPIN, OUTPUT);
Serial.println("Ready!");
}
void loop() {
if(received) {
Serial.print("Rx: ");
Serial.print(received); Serial.print("\t");
Serial.println(millis() - loopTimeStart);
loopTimeStart = millis();
}
}
// callback for received data
void receiveData(int byteCount){
while(Wire.available()) {
received = Wire.read();
if (received == 1){
if (!ledState){
digitalWrite(LEDPIN, HIGH); // set the LED on
ledState = true;
} else {
digitalWrite(LEDPIN, LOW); // set the LED off
ledState = false;
}
}
}
}
// callback for sending data
void sendData(){
Wire.write(received);
received = 0;
}
Para funcionar é necessário usar o programa no arduino disponivel em:
Comunicações I2C entre Arduino e Raspberry Pi – Codigo teste para o Raspberry
