0

I was trying to make a code which did something every time a light dependent resistor was covered up by using interrupts so I could be running a different code at the same time. This was my finalised code:

#define LIGHT 2

void setup() {
    Serial.begin(9600);
    pinMode(LIGHT, INPUT);
    attachInterrupt(digitalPinToInterrupt(LIGHT), fall, FALLING);
}

void loop() {
    Serial.print("Hello");
    Serial.println();
    delay(1000);
}

void fall(){
    Serial.print("Light Covered!");
    Serial.println();
}

I have tested my ldr circuit (5V into the ldr with a 10k pulldown resistor) and it reliably sits over the digital read boundary so I don't need to use analog read. It also seems to have no bounce as if I read it by outputting a message every time it reads it as high and then waiting until it goes low it only reads once every time I cover it and uncover it. However for some reason the code above which uses interrupts seems to print light covered 3-7 times every time I cover it. I am quite new to arduinos and C although I have used python for a while so sorry if it is a silly noob mistake.

  • Don't use an interrupt. The arduino environment is not the same as an embedded system. Interrupts can often be avoided. Read the analog value in the loop. Add hysteresis. Do you want to detect a certain fixed value or a change in the value? – Jot Mar 5 at 21:02
  • do minimum amount of work inside an ISR ...... raise a flag only ...... print the message inside the loop() block whenever the flag is raised – jsotola Mar 5 at 21:08
  • @Jot I want to detect when the signal gets below a certain bound and the reason I want to use an interrupt is because then I can be monitoring serial while also detecting and doing something every time the signal falls – 13ros27 Mar 5 at 21:08
  • @jsotola But surely then the code inside the loop() still has to be checking to see if the flag has been raised so if it is doing something like continually checking serial it would not check it as often if it is checking the flag – 13ros27 Mar 5 at 21:11
  • i think that you have a misconception about how fast the arduino operates – jsotola Mar 5 at 21:15

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.