1

My program only works when the following line is added:

Serial.begin(9600);

When this is disabled/removed the program no longer switches output state regular

I'm using an Arduino Mega 2560.

When the line is added:

  • The output is switched ON or OFF regular around every 1sec.

When the line is removed:

  • The output is switched after 1 sec (as expected) but then switched multiple times after around 3 sec.
  • I tried with another Arduino Mega 2560: This time, the output is switched after 1sec (as expected) but then switched multiple times right after (and not after around 3 sec).

What could be the problem?

My code:

byte inputPin2 = 2;
byte inputPin3 = 3;
byte outputPin = 13;
boolean outputPin_HIGH = false;
volatile short angle = -18;

void setup() {
  Serial.begin(9600);      //<----------------------
  pinMode(hallSensorPin, OUTPUT);

  pinMode(inputPin2, INPUT_PULLUP);
  pinMode(inputPin3, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(inputPin2), ISR_addAngle, CHANGE);
  attachInterrupt(digitalPinToInterrupt(inputPin3), ISR_addAngle, CHANGE);
}

void ISR_addAngle() {
  angle = angle + 18;
}

void loop() {
  if (angle == 900) {
    if (outputPin_HIGH) {
      digitalWrite(outputPin, LOW);
      outputPin_HIGH = false;
    } else {
      digitalWrite(outputPin, HIGH);
      outputPin_HIGH = true;
    }
    angle = angle - 900;
  }
}
13
  • 2
    "When this is disabled/removed the program no longer works..." is not very informative. What, exactly, doesn't work? What were you expecting to happen? What happened instead? – JRobert Apr 19 at 18:54
  • When the line is disabled/removed the program no longer receives the regular interrupts and the output therefore no longer switches state. When the line is added: The output is set (switched ON and OFF) regular around every 1sec. When the line is removed: The output is set after 1sec (as expected) but then set multiple times after around 3 sec. – Magnus Apr 19 at 20:04
  • ... or I think that the interrupt works (I can see that a signal is sent to the interrupt pin), but as I can't serial.print a flag, I don't know if it really works... – Magnus Apr 19 at 20:09
  • The program works fine with it, but I want to remove it (it was only for debugging) – Magnus Apr 19 at 20:38
  • you can store the flag values in an array ... when you reach some desired number of values stored, then call a function to do serial.begin and print out the values – jsotola Apr 19 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.