TolpuddleSartre:
Is it critical to get rid of the very short blocking delayMicroseconds?
In fact, those delays are almost certainly shorter than pulseIn
i dont know i have alot of other timers in the background this is just a small part of code that im going to integrate into my main sketch. so far i have come up with this,
unsigned long WaterWait = 4000;
unsigned long Waterdelay =0;
unsigned long WaterWait2 = 10;
unsigned long Waterdelay2 =0;
unsigned long Waterdelay3 =0;
int trig = 12;
int echo = 11;
void setup()
{
Serial.begin(9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
void loop()
{
if (millis() - Waterdelay > WaterWait) {
long t = 0, h = 0, hp = 0;
digitalWrite(trig, LOW);
if (millis() - Waterdelay2 > WaterWait2) {
digitalWrite(trig, HIGH);
if (millis() - Waterdelay3 > WaterWait2) {
digitalWrite(trig, LOW);
t = pulseIn(echo, HIGH);
h = t / 45;
h = h - 5; // offset correction
h = 35 - h; // water height, 0 - 50 cm
hp = 2.7 * h; // distance in %, 0-100 %
Waterdelay2 = millis();
Waterdelay2 = millis();
Waterdelay = millis();
Serial.print(hp);
Serial.println(F("%"));
}
}
}
}
Two things: you cannot delay for 2 microseconds or 10 microseconds.
The off-the-shelf micros() function has a resolution of 1/256th of about a millisecond, so pick 4, 8 or 12.
Usually for non-blocking you would mark the time and carry on, returning from time to time, via the loop, to see if a prescribed period has passed. You would do it with micros() the same way you would do it with millis(). In reality though how far are you going to get through your code before your time runs out? Is it worth it? Or just stick with your delays?
amazing that you dont even need to run the code to debug it. i have been running it like this and its been working but ill take your word with the delaymicroseconds and im only going to be calling it every 30 seconds anyways i just didnt know if it was a bad idea. ive been running it without delaymicroseconds or any delay besides the 30 seconds delay and its been working. does it really need the delay? what was the point of using it?
unsigned long WaterWait = 30000;
unsigned long Waterdelay = 0;
int trig = 12;
int echo = 11;
void setup()
{
Serial.begin(9600);
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
}
void loop()
{
long t = 0, h = 0, hp = 0;
digitalWrite(trig, LOW);
if (millis() - Waterdelay > WaterWait) {
digitalWrite(trig, HIGH);
digitalWrite(trig, LOW);
t = pulseIn(echo, HIGH);
h = t / 45;
h = h - 5; // offset correction
h = 35 - h; // water height, 0 - 50 cm
hp = 2.7 * h; // distance in %, 0-100 %
Waterdelay = millis();
Serial.print(F("The Water Level Is At "));
Serial.print(hp);
Serial.println(F("%"));
}
}
The point of not using delay is that it allows your sketch to do other things instead of locking up the processor, twiddling its metaphoric thumbs.
This is fine on the order of tens of milliseconds to seconds or even hours, but at the level of small numbers of microseconds, it doesn't make much sense.