Question

I have a light sensor that prints the value of its input to the Serial monitor. It's pretty much a trip wire but when an object is in its way, it prints the value every 1 millisecond. If I add a delay it won;t trigger the second sensor until the delay is done. How would I get it to only print once, without any disturbance or interference with the other sensors?

void loop() {
  if (analogRead(sensor1) == 0) {     
    timer.start ();
    tStop = false;
    //Serial.println (timer.elapsed());
    Serial.println ("Start Time = 0");
  }
Was it helpful?

Solution 2

I managed to make an int before the void setup and then used a while loop. with in the if statement.

int i = 1;

if (analogRead(sensor1) == 0) {     
  timer.start ();
  tStop = false;

while (i == 1) {
  Serial.println ("Start Time = 0");
  i++;
 }    
}

OTHER TIPS

This is quite an interesting problem, in the normal world of computers we would solve this via threading. However as you are running without an OS we have to do one of two things, implement coroutines (fake threading without an OS) or use asynchronous code and interrupts.

My understanding is that you print something when an object first comes into the way of your sensor, as the arduino uno as opposed to the due is not easy to implement coroutines on we shall try the interrupt route.

First you will likely be interested in this library http://playground.arduino.cc/Code/Timer1 It allows you to add an interrupt service routine to run on a timer. Use the attachInterrupt(function, period) function in the library for this.

In your interrupt service routine you will want to check the sensor, set a variable to say how long ago since it was last triggered and print the message if appropriate. This means your main loop is completely free to run other code and will not block your other sensors.

For example:

void TimFun()
{
    static int LastRead;
    if(LastRead && (0 == analogRead(sensor1))
    {
        Serial.println("SensorTrip");
    }
    LastRead = analogRead(sensor1);
}

void loop()
{
    // Do other stuff here
}

void setup()
{
    Timer1.initialize(100000);
    Timer1.attachInterrupt(TimFun);
    // Rest of setup Here
}

You probably should use an if instead of a while loop that will never execute more than once.

bool tripped = false;

void setup(){
    //setup stuff here
}

void loop() {
    if ( analogRead(sensor1) == 0 ) 
    {     
        timer.start ();
        tStop = false;

        if ( tripped == false ) 
        {
            Serial.println ("Start Time = 0");
            tripped = true;
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top