I'm passing particles by a photoresistor, and I'm trying to measure the amount of time the resistor is blocked in order to gauge particle size. I tried to do it with a for loop. I tried to write it so that if the sensor value was low, count would increment, and then it would return to checking the sensor value again... until a high enough value was measured, at which time I would get a println of total times a low sensor value was measured. I would calibrate after (i.e. 5 = 1mm). On my serial monitor I get a lot of zeroes, then when the sensor is triggered they stop and nothing is printed. I've tried a number of iterations of my code, but I can't seem to figure it out for myself. Maybe a for loop isn't even what I need? Anyway, here's my code at present:
const int sensorPinOne = A0;
int sensorValueOne = 0;
int countOne = 0;
void setup() {
Serial.begin(9600);}
void loop() {
sensorValueOne = analogRead(sensorPinOne);
for (; sensorValueOne < 500; sensorValueOne)
{countOne++;}
Serial.println(countOne);
}
wanasurf:
I'm trying to measure the amount of time the resistor is blocked in order to gauge particle size.
Strictly speaking, once you have got this code working it will give you a value proportional to the time but not the actual time. You would need to either calibrate it (by measuring particles of a known size), or replace the simple counting code with something that measures the actual time. Subtracting the value of micros() before and after the resistor was blocked would give you the actual time in microseconds.
A "for" loop is intended to repeat something a pre-determined number of times. A "while" loop is intended to loop an indefinite number of times until something changes.
You need something like this
loop() {
count = 0;
detectedValue = analogRead(somePin); // read the initial value
while (detectedValue > someValue) {
count ++;
detectedValue = analogRead(somePin); // continue to read until the value fails the test
}
if (count > 0) { // only prints if you have detected something
Serial.print(count);
}
}
count = 0;
detectedValue = analogRead(somePin); // read the initial value
while (detectedValue > someValue) {
count ++;
detectedValue = analogRead(somePin); // continue to read until the value fails the test
}
Thank you so much Robin2 and AWOL! I went with the while loop and it does exactly what I want. I literally spent hours trying to figure it out on my own. You were a huge help!