Hi guys,
I'm working on a project where I have a DC motor rotating approximately 180 degrees back-and-forth. It should change direction every time it hits an end-switch.
I'm using interruptions, with both pin 2 and pin 3 having FALLING-interruptions. So, every time the switch is pushed down, an interruption is triggered which changes the direction of the motor.
This works perfectly with the switch connected to pin 2. However, the switch on pin 3 is giving me a headache. Every time it is pushed down, the motor completely stops, and continues moving only after the switch is released. This behaviour is obviously not suitable for my purpose. The problem seems not to be on the switch, since I've used both on both pins, and the problem seems to be pin-related.
I'm also tracking the rotation direction with an enumeration, to filter out some error interruptions.
Here's my code:
enum Direction{FORWARDS, BACKWARDS};
enum Direction dir;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(12, OUTPUT); // motor A direction
pinMode(9, OUTPUT); // motor A break
pinMode(2, INPUT_PULLUP); // switch 1 input with pull-up
pinMode(3, INPUT_PULLUP); // switch 2 input with pull-up
dir = FORWARDS;
attachInterrupt(digitalPinToInterrupt(3), dir_change2, FALLING);
attachInterrupt(digitalPinToInterrupt(2), dir_change1, FALLING);
}
void loop() {
}
void dir_change1() {
if (dir == FORWARDS) {
digitalWrite(9, HIGH); // engage break for channel A
digitalWrite(12, LOW); // backward direction channel A
digitalWrite(9, LOW); // disengage break for channel A
dir = BACKWARDS;
}
}
void dir_change2() {
if (dir == BACKWARDS) {
digitalWrite(9, HIGH); // engage break for channel A
digitalWrite(12, HIGH); // forward direction channel A
digitalWrite(9, LOW); // disengage break for channel A
dir = FORWARDS;
}
}
I'm using the Arduino Motor Shield V3 (with Arduino Uno).
If any of you have some tips how to solve this issue, I would be very thankful.