Arduino Stack Exchange is a question and answer site for developers of open-source hardware and software that is compatible with Arduino. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I recently got to work with Arduino and I want to get parallel input from 5 LDRs and at the same instance I need to light a LED corresponding to that LDR if the resistance got high.

I read about a finite state machine, but I couldn't understand how it works.

Is it the only way for this type of problem or are there any other way?

share|improve this question
1  
    
For info on state machines, take a look at What kind of problems are state machines good for?. – Greenonline Feb 1 at 6:33

You do not need parallel processing or finite-state machines for that:

// Vector with digital pin numbers for LEDs (with resistor to ground)
const int LED_MAX = 5;
const int LED[LED_MAX] = { 2, 3, 4, 5, 6 };

// Vector with analog pin numbers for LDR (with pullup resistor)
const int LDR_MAX = 5;
const int LDR[LDR_MAX] = { A0, A1, A2, A3, A4 };

// Analog value or lower when to light the LED
const int THRESHOLD = 200;

void setup()
{
   // All LED pins should be digital output pins
   for (int i = 0; i < LED_MAX; i++) 
     pinMode(LED[i], OUTPUT);
}

void loop()
{
   // Read all LDRs and set LED pins according to threshold
   for (int i = 0; i < LDR_MAX; i++)
     digitalWrite(LED[i], analogRead(LDR[i]) < THRESHOLD);
}

But if you really want to describe this as multiple tasks you could use the Simple Scheduler library:

#include <Scheduler.h>

const int THRESHOLD = 200;    

template<int LED> void setup()
{
   pinMode(LED, OUTPUT);
}

template<int LED, int LDR> void loop()
{
   digitalWrite(LED, analogRead(LDR) < THRESHOLD);
   yield();
}

void setup()
{
   Scheduler.start(setup<2>, loop<2, A0>);
   Scheduler.start(setup<3>, loop<3, A1>);
   Scheduler.start(setup<4>, loop<4, A2>);
   Scheduler.start(setup<5>, loop<5, A3>);
   Scheduler.start(setup<6>, loop<6, A4>);
}

void loop()
{
   yield();
}
share|improve this answer
    
Thank you for your time. This was really helpful. – Suranjaya Vishvajith Feb 1 at 17:47

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.