The goal of my project is to be able to control two steppers with 4 buttons. Steppers are connected to Adafruit Motor shield(the older one) which is stacked on Arduino UNO, buttons are connected to Arduino NANO. I'm using I2C between the two Arduinos. However, if I push a button, the steppers won't rotate, only vibrate, but if I'm using only Arduino UNO with the motor shield stacked on it, button connected directly to the motor shield, it's working well. Arduino UNO is Master Reader, while NANO is Slave Writer. There is a fritzing image of the circuit. I don't know where's the problem, if it's in the circuit, if it's because of my battery(i bought it like 10 minutes ago) or the code. Any help is apreciated.
Master code:
#include <Wire.h>
#include <AFMotor.h>
//define steppers
AF_Stepper motor1(48, 2);
AF_Stepper motor2(48, 1);
//define variables
int x = 0;
int y = 0;
void setup()
{
Wire.begin(5); //begin i2c communication
Wire.onReceive(receiveEvent);
motor1.setSpeed(200); // 10 rpm
motor2.setSpeed(200); // 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 code:
#include <Wire.h>
//define buttons
const int button1 = 2;
const int button2 = 3;
const int button3 = 8;
const int button4 = 7;
//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();
}
}
int
are 2 bytes, butWire.write()
transmits only a byte at a time.