I am sending distance measurements from the Master Arduino to the Slave using I2C, to control the motors on the Slave.
The Slave Arduino is receiving the data, but I cannot figure out how to use the value in the void loop.
The following code returns the correct value in Serial Monitor, but I suspect the value changes in the void loop.
If I move the Serial.println(x); from the void receiveEvent(int howMany), to the void loop, the value prints as -1 in Serial Monitor.
How do I use the value received from the Master in the void loop?
// buddybotmotors.ino
// -*- mode: C++ -*-
#include <Wire.h>
#include <AccelStepper.h>
#include <MultiStepper.h>
// connect to stepper drivers and the pins they use
// stepper1: step pin = 2 dir pin = 3
// stepper2: step pin = 4 dir pin = 5
AccelStepper stepper1(AccelStepper::DRIVER, 2, 3);
AccelStepper stepper2(AccelStepper::DRIVER, 4, 5);
// initial Motor position values
int pos1 = 0;
int pos2 = 600000000000;
// initial Wire Slave_receiver value
int x = 0; // give a value to the varable to be changed
void setup() {
//stepper setup
stepper1.setMaxSpeed(9000);
stepper1.setSpeed(9000);
stepper1.setAcceleration(1000);
stepper1.setCurrentPosition(pos1);
stepper1.moveTo(pos2);
stepper2.setMaxSpeed(9000);
stepper2.setSpeed(9000);
stepper2.setAcceleration(1000);
stepper2.setCurrentPosition(pos1);
stepper2.moveTo(pos2);
//Wire Slave_receiver
Wire.begin(8); // join i2c bus with address #8
Wire.onReceive(receiveEvent); // register event
Serial.begin(9600); // start serial for output
} //end of setup
void loop()
{
if ((x)> 10) // If the distance is greater than 10cm, run the motors, else stop the motors
{
if (stepper1.distanceToGo() == 0)
stepper1.moveTo(-stepper1.currentPosition());
if (stepper2.distanceToGo() == 0)
stepper2.moveTo(-stepper2.currentPosition());
stepper1.run();
stepper2.run();
}
else {
stepper1.stop();
stepper2.stop();
}
}
//Wire Slave_receiver
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
while (1 < Wire.available())
{
}
int x = Wire.read(); // receive byte as an integer
Serial.println(x); // print the integer
}