I hooked up a raspberry pi 2 B model with an arduino uno through a bi-directional level shift.
Raspberry pi GND ---------- GND Arduino 3.3v ---------- 5v SCL ---------- A5 SDA ---------- A4
I hope my I2C connection is correct?
and my Arduino is connected to an 8 channel relay board.
Now I have written code in which I can control the Raspberry pi relay board. For ex if I Press '1', relay 1 will be high.
Now I want to send data from arduino to raspberry pi, to cross-check whether Relay 1 is really high or not, if Relay 1 is high, then it should send some data back to Raspberry pi or not.
My rpi code
import smbus import time # for RPI version 1, use "bus = smbus.SMBus(0)" bus = smbus.SMBus(1) # This is the address we setup in the Arduino Program address = 0x04 def writeNumber(value): bus.write_byte(address, value) # bus.write_byte_data(address, 0, value) return -1 def readNumber(): number = bus.read_byte(address) # number = bus.read_byte_data(address, 1) return number while True: var = input("") if not var: continue writeNumber(var) number = readNumber()
My Arduino Code:
#include <Wire.h> #define SLAVE_ADDRESS 0x04 #define RELAY1 9 int number = 0; int state = 0; void setup() { pinMode(RELAY1, OUTPUT); Serial.begin(9600); // start serial for output // initialize i2c as slave Wire.begin(SLAVE_ADDRESS); // define callbacks for i2c communication Wire.onReceive(receiveData); Wire.onRequest(sendData); Serial.println("Ready!"); } void loop() { delay(100); } // callback for received data void receiveData(int byteCount){ while(Wire.available()) { number = Wire.read(); Serial.print("data received: "); Serial.println(number); if (number == 1){ if (state == 0){ digitalWrite(RELAY1, HIGH); // set the LED on state = 1; } else{ digitalWrite(RELAY1, LOW); // set the LED off state = 0; } } } } // callback for sending data void sendData(){ Wire.write(number); }
Now, if I dial 1 and due to some loose connection, relay 1 does not get high, so in this case I want arduino to receive data from the relay board and send it to raspberry pi each time.
It will be great if someone can also explain how this works.
Hope I could explain the problem. I did a lot of research, but could not find the answer.
I am a beginner in python, so please help me out.
Thanks in advance.