I want to have my Slave Arduino to send signal to Master after the command was made. But the Slave Arduino does not proceeds to sending the signal after doing the command. What is wrong with my code?
Slave
void receiveEvent(int bytes) {
dir = Wire.read(); // direction
dis = Wire.read(); // distance
spe = Wire.read(); // speed
eStop = Wire.read(); // 1 or 0
Serial.println(dir);
Serial.println(dis);
Serial.println(spe);
mov = true;
}
void loop() {
Wire.onReceive(receiveEvent);
if (dir == 1 && mov == true && eStop == false){
motor.Distance(dis);
motor.Speed(spe);
motor.Forward();
Wire.onRequest(requestEvent);
mov = false;
fin = true;
}
if (dir == 2 && mov == true && eStop == false){
motor.Distance(dis);
motor.Speed(spe);
motor.Reverse();
Wire.onRequest(requestEvent);
mov = false;
fin = true;
}
else{
motor.Stop();
}
}
void requestEvent(){
Wire.write(1);
fin = false;
Serial.println("sent");
}
Master
#include <Wire.h>
const byte interruptPin = 2;
byte dir = 0;
byte dis;
byte spe;
bool upd;
bool state= false;
void setup() {
Wire.begin();
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), emergencyStop, CHANGE);
Serial.begin(9600);
}
void loop() {
if( state == false ){
dir = 1;
dis = 30;
spe = 2;
Wire.beginTransmission(9); // transmit to device #9
Wire.write(dir);
Wire.write(dis);
Wire.write(spe);
Wire.write(0);
Wire.endTransmission(); // stop transmitting
state = true;
}
if (state == true){
if(Wire.available() > 0){
Wire.requestFrom(9,2); //6bytes from slave 9
bool upd = Wire.read();
Serial.println(upd);
}
}
}
void emergencyStop(){ // not working
Wire.beginTransmission(9); // transmit to device #9
Wire.write(0);
Wire.write(0);
Wire.write(0);
Wire.write(1);
Wire.endTransmission(); // stop transmitting
}
Julius
-
Please wdit your question to include the full sketchchrisl– chrisl2019年08月21日 09:46:23 +00:00Commented Aug 21, 2019 at 9:46
-
Typically Wire.onReceive(callbackFunction) is called once in the setup().Mikael Patel– Mikael Patel2019年08月21日 12:21:35 +00:00Commented Aug 21, 2019 at 12:21
-
1Serial print in the callback function can cause issues.Mikael Patel– Mikael Patel2019年08月21日 12:22:25 +00:00Commented Aug 21, 2019 at 12:22
1 Answer 1
found my solution for this. although not verified yet, but i removed Serial print and moved the Wire.onRequest outside of the if loop. and uses a ledPin for checkups
void loop() {
Wire.onReceive(receiveEvent);
Wire.onRequest(requestEvent);
if (dir == 1 && mov == true && eStop == false){
motor.Distance(dis);
motor.Speed(spe);
motor.Forward();
mov = false;
fin = true;
}
if (dir == 2 && mov == true && eStop == false){
motor.Distance(dis);
motor.Speed(spe);
motor.Reverse();
mov = false;
fin = true;
}
else{
motor.Stop();
}
}
void requestEvent(){
if ( fin == true){
Wire.write(1);
fin = false;
digitalWrite(ledPin, HIGH);
}
}
-
Yes, you should not do serial prints inside an interrupt service routine.2020年09月15日 07:03:06 +00:00Commented Sep 15, 2020 at 7:03