Motor Shield V2 with Interrupts/Encoders

Adafruit Ethernet, Motor, Proto, Wave, Datalogger, GPS Shields - etc!

Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.
Locked
User avatar
jeffreyjene
 
Posts: 2
Joined: Thu Oct 21, 2021 4:43 pm

Motor Shield V2 with Interrupts/Encoders

Post by jeffreyjene »

I have a small test I'm doing with a V2 motor shield, a small motor, and a rotary encoder. I run the motor, and after 100 rises of the interrupt pin the motor should stop. The motor runs but never stops or exits the WHILE loop after it enters, even though my output shows more than 100 pulses from the encoder. I tried as a test running the motor, delaying 3 seconds and then stopping, but like before the motor never stops after the 3 seconds is up. Ive tried with UNO's interrupt pins 2 and 3 and with all the interrupt pins of a Mega with the same results. (SCL/SDA the motor doesn't run at all of course, as that I assume is used by the shield). If I remove the interrupt in the code, the motor stops and starts fine. I'm not really sure what is happening here, but it seems as though you can't use motor encoders with interrupts at all! I've found nothing in searches or docs regarding this subject. Here's the code:

Code: Select all

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"

Adafruit_MotorShield AFMS = Adafruit_MotorShield(); 
Adafruit_DCMotor *motor = AFMS.getMotor(1);

unsigned int counter = 0;

void ISR_count1()  
{
  counter++;  // increment Motor 1 counter value
  Serial.print("Counter: "); 
  Serial.println(counter); 

}

void Move(){

  delay(3000);
  counter = 0;
  
  while ( (counter < 100)) {
    motor->setSpeed(100);
    motor->run(FORWARD);
  }
  
  Serial.println("Goal reached!"); 
  motor->setSpeed(0); 
  delay(3000);
}

void setup() {
  AFMS.begin();
  
  attachInterrupt(digitalPinToInterrupt (3), ISR_count1, RISING); 

  Serial.begin(9600);

  Move();

}

void loop() {

}

User avatar
adafruit_support_bill
 
Posts: 88093
Joined: Sat Feb 07, 2009 10:11 am

Re: Motor Shield V2 with Interrupts/Encoders

Post by adafruit_support_bill »

I'd start by removing all serial I/O from the ISR. Serial I/O requires interrupts and doing serial I/O from within an ISR when interrupts are disabled is a recipe for problems.

User avatar
jeffreyjene
 
Posts: 2
Joined: Thu Oct 21, 2021 4:43 pm

Re: Motor Shield V2 with Interrupts/Encoders

Post by jeffreyjene »

Yes, that did the trick. Thank you.

User avatar
adafruit_support_bill
 
Posts: 88093
Joined: Sat Feb 07, 2009 10:11 am

Re: Motor Shield V2 with Interrupts/Encoders

Post by adafruit_support_bill »

Good to hear that fixed it. Thanks for the follow-up.

Locked
Please be positive and constructive with your questions and comments.

Return to “Arduino Shields from Adafruit”