First of all, I'm new to arduino. Check the EDIT line below the two codes.
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.
EDIT5: I deleted the messy previous codes, the question was answered. However, I cant get the steppers to rotate(they only vibrate). Any advice is appreciated. The code right now is:
Master
#include <Wire.h>
#include <AFMotor.h>
//define steppers
AF_Stepper motor1(48, 1);
AF_Stepper motor2(48, 2);
//define variables
int x = 0;
int y = 0;
void setup()
{
Wire.begin(5); //begin i2c communication
Wire.onReceive(receiveEvent);
motor1.setSpeed(10); // 10 rpm
motor2.setSpeed(10); // 10 rpm
motor1.release();
motor2.release();
delay(1000);
}
void loop()
{
delay(500); // wait 0.5 second
}
void receiveEvent(int howMany)
{
//read x,y from slave
x = Wire.read();
y = Wire.read();
if (x == 1) //stepper1 rotate forward
{
motor1.step(100, FORWARD, SINGLE);
}
else if (x == 2) //stepper1 rotate backward
{
motor1.step(100, BACKWARD, SINGLE);
}
else if (y == 1) //stepper2 rotate forward
{
motor2.step(100, BACKWARD, SINGLE);
}
else if (y == 2) //stepper2 rotate backward
{
motor2.step(100, BACKWARD, SINGLE);
}
}
Slave
#include <Wire.h>
//define buttons
const int button1 = 2;
const int button2 = 3;
const int button3 = 4;
const int button4 = 5;
//define state of buttons
int buttonState1 = 0;
int buttonState2 = 0;
int buttonState3 = 0;
int buttonState4 = 0;
//define variables
int x = 0;
int y = 0;
void setup()
{
//start i2c communication
Wire.begin();
}
void loop()
{
//read state of buttons
buttonState1 = digitalRead(button1);
buttonState2 = digitalRead(button2);
buttonState3 = digitalRead(button3);
buttonState4 = digitalRead(button4);
//if button1 is pressed,send x to master
if(buttonState1 == HIGH){
x = 1;
Wire.beginTransmission(5);
Wire.write(x);
Wire.endTransmission();
}
//if button2 is pressed,send x to master
else if(buttonState2 == HIGH)
{
x = 2;
Wire.beginTransmission(5);
Wire.write(x);
Wire.endTransmission();
}
//if button3 is pressed,send y to master
if(buttonState3 == HIGH){
y = 1;
Wire.beginTransmission(5);
Wire.write(y);
Wire.endTransmission();
}
//if button4 is pressed,send y to master
else if(buttonState4 == HIGH)
{
y = 2;
Wire.beginTransmission(5);
Wire.write(y);
Wire.endTransmission();
}
}