SAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD

On command Arduino timer



Well in this post you will know how you can turn on something for certain time and then turn it off, simply by sending some command via serial monitor.

Let's see the sketch first.
The sketch

int led = 4;

void setup() {
  Serial.begin (9600);
  pinMode(led, OUTPUT);

}
String str;

void on(){
  digitalWrite(led, HIGH);
}

void off(){
  digitalWrite(led, LOW);
}

void onesec(){
  digitalWrite(led, HIGH);
  delay(1000); // Change the numbers if you need to.
  digitalWrite(led, LOW);
  Serial.println("The led is off now.");
}

void fivesec(){
  digitalWrite(led, HIGH);
  delay(5000); // Change the numbers if you need to.
  digitalWrite(led, LOW);
  Serial.println("The led is off now."); 
}

void tensec(){
  digitalWrite(led, HIGH);
  delay(10000); // Change the numbers if you need to.
  digitalWrite(led, LOW); 
  Serial.println("The led is off now.");
}


void loop() {
 
if(Serial.available())
{
str = Serial.readStringUntil('\n');

if(str == "1s"){
Serial.println("Led turned on for 1 second.");
onesec();
}
  if(str == "5s"){
Serial.println("Led turned on for 5 seconds.");
fivesec();
  }
 if(str == "10s"){
Serial.println("Led turned on for 10 seconds.");
tensec();
  }
  if(str == "on"){
Serial.println("The Led has been turned on.");
on();
  }
   if(str == "off"){
Serial.println("The led has been turned off.");
off();
  }
 }
}


What are the functions?
  • Turns on the led for 1 second and command is "1s".
  • Turns on the led for 5 seconds and command is "5s".
  • Turns on the led for 10 seconds and command is "10s".
  • Turns on the led and command is "on".
  • Turns off the led  and command is "off".
Note:
The led is just for an example, you can control many other stuff with this sketch or just by changing a bit.

How to set the numbers?
In Arduino there are 1000 miliseconds in a second so you might have to do the math, but here are few examles for you.

1000 = 1 second
10000 = 10 seconds
30000 = 30 Seconds
60000 = 1 minute

900000 = 15 Minutes
1800000 = 30 Minutes
2700000 = 45 Minutes
3600000 = One hour.
36000000 = 10 Hours
And the rest of it I think you can do it by yoursel.

No comments:

Post a Comment



Newly posted:
Reason why rich getting richer and poor getting poorer