Skip to main content
2 of 8
edited tags

Arduino UNO(master read) + NANO(slave write) i2c buttons+stepper

I have connected motor shield to arduino uno. Connection between the two arduinos are A5 to A5, A4 to A4, 5V to 5V and GND to GND. I have a stepper connected to UNO, and a button connected to nano. However, I cant get to work the communication somehow. Any advice is appreciated.

Master

//master uno, reader
#include <Wire.h>
#include <AFMotor.h>

AF_Stepper motor(48, 2);
int x = 0;
void setup()
{
Serial.begin(9600);
Wire.begin(5);
Wire.onReceive(receiveEvent);
motor.setSpeed(300);  // 10 rpm   
motor.step(500, FORWARD, SINGLE); 
motor.release();
delay(1000);
}
void receiveEvent( int bytes )
{
x = Wire.read();
Wire.endTransmission();
}
void loop()
{
if (x == 1) {
  Serial.println("its actually 1, buttons working");
  motor.step(100, FORWARD, SINGLE);
delay(1000);
}
if (x == 0) {
  Serial.println("button aint pressed");
delay(1000);
}
}

Slave

 //slave nano, sender
#include <Wire.h> // <-- remove spaces
int x =0;
int slaveAddress = 5;
const int button1 = 2; // the number of the pushbutton pin
//const int button2 = 3;
int buttonState1 = 0;
//int buttonState2 = 0; // variable for reading the pushbutton status
void setup()
{
pinMode(button1,INPUT); // initialize the pushbutton pin as an input
//pinMode(button2,INPUT);
Wire.begin(); 
Serial.begin( 9600 );
}
void loop()
{
// read the state of the pushbutton value:
buttonState1 = digitalRead(button1);
// check if the pushbutton is pressed. If it is, the buttonState is HIGH:
if ( buttonState1 == HIGH ){
  x = 1;
  }
else { 
  x = 0;
}
Wire.beginTransmission(5);
Wire.write(x); // sends x
Wire.endTransmission(); // stop transmitting
delay(100);
}