Go Down

Topic: 2 sensors millis(). Need help, please. (Read 517 times) previous topic - next topic


Aug 01, 2018, 12:56 pm Last Edit: Aug 01, 2018, 12:59 pm by NikIPT
Good afternoon, i need to calculate the travel time between two different optical sensors, at the moment ive written a sketch, but the problem is this: The sensors have 2 modes. When its the presence mode, the time is counted by the signal level application on one of them. If both sensors are clamped, then the print displays 0. If one sensor is clamped and you close and open the second one, then the time is counted. It means it shows the time that occurs between the closing and opening of one sensor, the readings of the second are not important - it is either closed or open. Do I understand it correctly: initially both sensors fix liquid i.e. HIGH, then the liquid goes away, the state of the first sensor becomes LOW - the countdown starts, then the second sensor becomes LOW - the calculation is finished. I do not know how to fix this. The sensors are connected as shown in the diagram.
Code: [Select]

unsigned long startTime;
unsigned long endTime;
unsigned long duration;
const int sensor1 = 12;
const int sensor2 = 13;

bool sensor1_worked = false;
bool sensor2_worked = false;
void setup()
  pinMode(sensor1, INPUT);
  pinMode(sensor2, INPUT);
void loop(){
  if (!sensor1_worked && digitalRead(sensor1) == HIGH){
    startTime = millis();
    sensor1_worked = true;
  else if (!sensor2_worked && digitalRead(sensor2) == HIGH){
    endTime = millis();
    duration = endTime - startTime;
    Serial.print ("liquid travel time: ");
    Serial.println (duration);
    sensor1_worked = false;
    sensor2_worked = false;


The Arduino is missing from your schematic, so it is difficult to see how that circuit is connected to the Arduino. I suspect that you have floating pin problems, where the pin is not consistently HIGH or LOW.
The art of getting good answers lies in asking good questions.


From your description, it sounds like the program will start with liquid in front of both sensors, and then the liquid will go away from the first sensor, and later it will go away from the second sensor. It also sounds like your sensors read HIGH when there is liquid in front of them and LOW when there is not, and you are expecting them to start seeing liquid, and then to not.

However, your code is waiting for the first sensor to read HIGH, and then timing how long it is until the second sensor to read HIGH. This would cause the program to print a steady stream of "0"s initially (when liquid is in front of both sensors, and they both read HIGH) and then to stop printing anything at all (because neither sensor will have liquid in front of them, and you will never set sensor1_worked to true, let alone sensor2_worked). Is this what you see happening?

Go Up