Hello there,
I am new to Arduino and find it very hard to diagnose the issue I'm having with a simple application of interrupts.
The background of the project is:
I am looking to alternate the switching on and off of two LEDs, so when one turns on the other turns off, every time an input analog pulse width signal is high. I am currently generating an analog signal with an external device and software (Waveforms and Discovery kit if that information is needed) and connecting it to the interrupt pin (pin 2) to trigger the interrupt. However, that was not working and the LEDS were not flickering in sync with the period of the pulse width being generated. Therefore, I switched the input source to be the 5V source from the Arduino with a button to see if that would work better.
when the button is pressed and the 5V is able to be read by the pin, the LEDs will switch. Printing to the serial port, there is "1" being printed, but, when the button isn't pressed, there's a bunch of sporatic 1 and 0 being inputted and then printed to the serial monitor and the LEDs are flickering
like crazy even though there is not supposed to be any voltage going to the pin.
So, basically:
How can I use interrupts with an analog input pulse width signal of 5V to identify and change LEDs alternatingly?
I will note also that LEDs are connected in series with 1k resistors, to pins 7 and 8, they were originally connected to pins 5 and 6 PWM if that makes any difference
my current code:
const byte redLEDPin = 7; // set red led output to 5 (PWM pin, not sure if that is goingto beb necessary since its a logical output
const byte greenLEDPin = 8; // set green led to 6 (PWM pin)
volatile bool redLEDState; // initial state of led, let us know if the circuit is on
volatile bool greenLEDState;
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(redLEDPin, OUTPUT);
pinMode(greenLEDPin, OUTPUT);
pinMode(2, INPUT);
redLEDState = true;
greenLEDState = false;
digitalWrite(redLEDPin, redLEDState);
digitalWrite(greenLEDPin, greenLEDState);
attachInterrupt(0, PulseISR, FALLING);
}
void loop() {
Serial.print(digitalRead(2));
}
void PulseISR() {
if (redLEDState) {
redLEDState = false;
greenLEDState = true;
digitalWrite(redLEDPin, redLEDState);
digitalWrite(greenLEDPin, greenLEDState);
}
else if (greenLEDPin) {
redLEDState = true;
greenLEDState = false;
digitalWrite(redLEDPin, redLEDState);
digitalWrite(greenLEDPin, greenLEDState);
}
else {
Serial.print("error");
}
}
