Save the time an event happens then each time through loop() check whether the required period has elapsed since the event. If not then go round loop() again reading inputs etc. If the period has elapsed then take the required action.
const int analogPin = A0;
void setup() {
pinMode(12, OUTPUT);
Serial.begin(9600);
}
void loop() {
int analogValue = analogRead(analogPin);
if (analogValue > 900 && analogValue < 1000) {
digitalWrite(12, HIGH); // turn the LED on (HIGH is the voltage level) case1
delayMicroseconds (20);
digitalWrite(12, LOW); // turn the LED off by making the voltage LOW
delayMicroseconds (20);
digitalWrite(12, HIGH); // turn the LED on (HIGH is the voltage level)
delayMicroseconds (100);
digitalWrite(12, LOW); // turn the LED off by making the voltage LOW
delay (100);
}
if (analogValue > 500 && analogValue < 900) {
digitalWrite(12, HIGH); // turn the LED on (HIGH is the voltage level) case2
delayMicroseconds (40);
digitalWrite(12, LOW); // turn the LED off by making the voltage LOW
delayMicroseconds (40);
digitalWrite(12, HIGH); // turn the LED on (HIGH is the voltage level)
delayMicroseconds (60);
digitalWrite(12, LOW); // turn the LED off by making the voltage LOW
delay (100);
}
else {
digitalWrite(12, HIGH); // turn the LED on (HIGH is the voltage level) case3
delayMicroseconds (60);
digitalWrite(12, LOW); // turn the LED off by making the voltage LOW
delayMicroseconds (60);
digitalWrite(12, HIGH); // turn the LED on (HIGH is the voltage level)
delayMicroseconds (20);
digitalWrite(12, LOW); // turn the LED off by making the voltage LOW
delay (100);
}
}
It works if I just use case1 and else, but one I add more than one case, it stops working and just outputs what’s in the else brackets.
Wow, how did you manage to mangle the layout/indentation that much! The IDE really tries to help so it really takes effort to do this. Hit Ctrl + t for fun.
And still, where do you need those pulses for!? They are precise it almost sounds like you try to do something weird like generation a protocol or something. Maybe the Arduino has already a hardware solution for it but you don't really tell what you want to do.
And ever heard of variables? 12 is as clear as 42 (Answer to the Ultimate Question of Life, the Universe, and Everything). And now we're there, heard of else if() ?