Dear all, greetings of the day!
Hope this message finds everyone in good health. I am writing this message becasue I need some assistance with a project I am working on. The below code is going to turn ON and OFF a 24 V motor that is connected through 2 relay modules to a power supply. +24 V turns the motor in forward direction and -24 in reverse. I am using Arduino MKR 1310 WAN and three hall sensors.
Hall sensor 1 would start moving the motor when a magnet comes in front of it. The motor continues to move even if I take off the magnet and the motor would continue to move until I bring a magnet to sensor no. 2 that would stop the motor forward movement. I repeated it several times and I face no problem.
But when I check the reverse motion, sometimes it works, sometimes not, sometimes the motor gives forward movement. For instance, with the command [ if (digitalRead(BUTTON) == HIGH && !stopped) ] in which I actually give a pulse from arduino, because right now I am not using a button. So, I give a pulse from Vcc to pin 9 and the motor would start reverse rotation. But when I try to stop it by bringing the magnet to the sensor 3, sometimes it would stop and sometimes it will make the motor start moving in forward direction rather than stopping it. Can some please assist me that what am I doing wrong?
P.S: Today, I used the same code to run on Arduino UNO and I was surprised to see that when I brought the magnet to sensor 1 it started the motor and when I got it away it stopped the motor which should not have happened. I didn't see this issue on MKR 1300 board.
Your kind suggestion would highly be appreciated. Thank you very much
Bilal
#define hallSensor1 3 // digital pin 3 as input
#define hallSensor2 4 // digital pin 4 as input
#define hallSensor3 2 // digital pin 2 as input
#define relayPin1 6
#define relayPin2 7
#define BUTTON 9
int state1 = 0, state2 = 0, state3 = 0;
bool stopped = false;
bool cycleRelease = false;
void setup() {
pinMode(relayPin1, OUTPUT);
pinMode(relayPin2, OUTPUT);
pinMode(hallSensor1, INPUT);
pinMode(hallSensor2, INPUT);
pinMode(hallSensor3, INPUT);
pinMode(BUTTON, INPUT);
}
void loop(){
state1 = digitalRead(hallSensor1);
state2 = digitalRead(hallSensor2);
state3 = digitalRead(hallSensor3);
if (state1 == 0 && !cycleRelease) {
digitalWrite(relayPin1, HIGH); // motor forward ON
}
if (state2 == 0) {
digitalWrite(relayPin1, LOW); // motor turns OFF
}
if (digitalRead(BUTTON) == HIGH && !stopped){
digitalWrite(relayPin2, HIGH); // start motor in reverse direction
stopped = true;
}
if (state3 == 0 && stopped) {
digitalWrite(relayPin2, LOW); // turn motor OFF
stopped = false;
cycleRelease = true;
}
if (state1 == 1){
cycleRelease = false;
}
}
