I am using Arduino cloud to create alexa controlled devices. I have 3 switch variables in the program nd it is working so far. However, if I have the switch on, I want the switch to automatically turn off after a few seconds. All the examples I find are for constant toggling or for delays before turning on. Any guidance would be great.
If I turn on an LED with MKR 1010, how can I get it to automatically turn off after a couple seconds
Keep track of when you turned the switch on
unsigned long onTime = millis();
Then in loop keep checking to see if 3 seconds has elapsed
if(millis() - onTime > 3000)
{
// Turn switch off
}
Lok at the blink without delay example in the IDE examples (File, Examples)
Looked at that example but it blinks on and off repeatedly. I want it to turn off until I tell it to turn on again.
If you're referring to the "blink without delay" example, the intention is that you learn from that example and next apply what you learned to your scenario.
Here is the code I am working on:
#include "thingProperties.h"
//#include <SafeString.h>
#include <millisDelay.h>
// constants won't change. Used here to set a pin number:
const int greenPin = 0;// the number of the LED pin
const int redPin = 1;
const int otherPin = 2;
// Variables will change:
int greenState = LOW; // ledState used to set the LED
int redState = LOW;
int otherState = LOW;
unsigned long onTime = millis();
void setup() {
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without blocking if none is found
delay(1500);
// set the digital pin as output:
pinMode(greenPin, OUTPUT);
pinMode(redPin, OUTPUT);
pinMode(otherPin, OUTPUT);
// Defined in thingProperties.h
initProperties();
// Connect to Arduino IoT Cloud
ArduinoCloud.begin(ArduinoIoTPreferredConnection);
/*
The following function allows you to obtain more information
related to the state of network and IoT Cloud connection and errors
the higher number the more granular information you’ll get.
The default is 0 (only errors).
Maximum is 4
*/
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
}
void loop() {
ArduinoCloud.update();
// Your code here
}
void onUpChange() {
if (up) {
if (greenState == LOW) {
greenState = HIGH;
}
}
else {
Serial.println("Lamp Off");
greenState = LOW;
}
digitalWrite(greenPin, greenState);
}
void onDownChange() {
// Add your code here to act upon Reddy change
if (down) {
if (redState == LOW) {
redState = HIGH;
}
}
else {
Serial.println("Lamp Off");
redState = LOW;
}
digitalWrite(redPin, redState);
}
void onStopChange() {
// Add your code here to act upon Stop change
if (stop) {
if (otherState == LOW) {
otherState = HIGH;
}
}
else {
Serial.println("Lamp Off");
otherState = LOW;
}
digitalWrite(otherPin, otherState);
}
When it turns ON, store the millis & set a flag. In the main loop, check if the flag is set and now - stored millis is greater or equal to the time period needed, turn off the LED & set flag to false.
Thanks. I will have to do some studying since that is something completely new to me.
A couple more good millis() timing tutorials.
Beginner's guide to millis(). I liked this one.
Several things at a time.
I showed how to do it in post #2.
Well the classical BWD-example is medium hard to understand.
@red_car
The de-facto easier to understand code will be used.
here is a demo-code - which I believe - is easier to undestand and easier to adapt than the classical BWD-example for two reasons:
- much more comments that explain what the lines of code do
- more compact non-blocking timing-function (than the scatters around variables of the classical BWD-example)
open the serial monitor activate time-stamp and adjust baudrate to 115200
The serial monitor shows additional information what the code is doing
// In this code two things must "work together":
// updating a variable used as a timestamp WHEN the LED is swichted ON
// a flag-variable must be set true to enable time-checking
// the flag-variable must be set to false to DIS-able time-checking
unsigned long LED_Switched_ON_Time = 0; // Timer-variables MUST be of type unsigned long
unsigned long MyButtonPressSimulationTimer = 0; // Timer-variables MUST be of type unsigned long
const byte OnBoard_LED = 13;
boolean LED_shall_be_ON = false; // initialise variable named "LED_shall_be_ON" with false
//helper-function for easy use of non-blocking timing
boolean TimePeriodIsOver (unsigned long &expireTime, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - expireTime >= TimePeriod ) {
expireTime = currentMillis; // set new expireTime
return true; // more time than TimePeriod) has elapsed since last time if-condition was true
}
else return false; // not expired
}
void setup() {
Serial.begin(115200);
Serial.println("Setup-Start wait 20 seconds until LED is switched on");
digitalWrite(OnBoard_LED, LOW);
pinMode(OnBoard_LED, OUTPUT);
}
void loop() {
// once every 20 seconds "simulate" a buttonpress
// that switches on the LED
if ( TimePeriodIsOver(MyButtonPressSimulationTimer, 20000) ) {
Serial.println("Simulate buttonpress switching LED ON");
Serial.println("and set LED_shall_be_ON = true ");
digitalWrite(OnBoard_LED, HIGH); // switch LED on
LED_shall_be_ON = true; // set flag-variable to true
LED_Switched_ON_Time = millis(); // assign timestamp of that time when LED is switched on
}
// the flag-variable named "LED_shall_be_ON" is checked prior to the timimg
// the result is the time-checking is only done when flagvariable is true
if (LED_shall_be_ON == true) { // only if LED is switched on
// check how much time has passed by since LED was switched on
if ( TimePeriodIsOver(LED_Switched_ON_Time, 8000) ) {
// if 8 seconds HAVE passed by
Serial.println("8 second are over switching LED OFF");
digitalWrite(OnBoard_LED, LOW); // switch LED off
LED_shall_be_ON = false; // set flag to false
}
}
}
best regards Stefan
Not sure that is true... your code still contains the BWD code... if the OP doesn't understand that then your code just adds another layer of abstraction to confuse them even further.
Umm.. yeah sure, unless you mean comments like this that add nothing.
So far I have been trying different ways but I learned that if I add anything in the loop function in addition to ArduinoCloud.update();
the the program just wont work. Then I tried finding a way to add a timer within the up function and it just stops as well. Not quite sure how to proceed on this but I will try to figure it out over the next week.
Hi,
if you post your code there is a pretty high chance that analysing your code can explain why it did not yet work and further on how it can be made working.
best regards Stefan
Hi,
I don't have Arduino IoT. This means I can not compile your code.
I added the code for "one-shot"-timers that should realise the functionality
If it does not compile post the complete compiler-message as a code-section.
If you want others to check your code if your code compiles you have to provide your thingProperties.h-file
If you have additional questions just post them
here is the modified code.
I decided to not argue any more. I concentrate on a suggestion for the TO.
Posting a modified and commented code as a suggestion is inside the forum-rules.
law of usability:
if there are multiple suggestions how the code must be changed to get a certain functionality that suggestion which is easier to understand and / or easier to apply will be used because this suggestion has the highest usability.
#include "thingProperties.h"
//#include <SafeString.h>
#include <millisDelay.h>
// switching OFF something automatically after some time needs two things:
// 1. remembering the time WHEN the on-switching did happen
// 2. enabling checking how much time has passed by since the LAST on-switching
// this requires TWO additional variables
// 1. one variable for the time-stamp
// 2. one variable for enabling / dis-abling the time-checking
// these two variables are needed for EVERY "channel"
// in your case green, red and others
// constants won't change. Used here to set a pin number:
const int greenPin = 0;// the number of the LED pin
const int redPin = 1;
const int otherPin = 2;
// Variables will change:
int greenState = LOW; // ledState used to set the LED
int redState = LOW;
int otherState = LOW;
unsigned long onTime = millis();
unsigned long green_switched_on = 0; // variable for timestamp WHEN was green LED witched on
boolean check_green = false; // boolean variable acting as a flag for check timing / don't check timing
unsigned long red_switched_on = 0; // variable for timestamp WHEN was red LED witched on
boolean check_red = false; // boolean variable acting as a flag for check timing / don't check timing
unsigned long other_switched_on = 0; // variable for timestamp WHEN was other LED witched on
boolean check_other = false; // boolean variable acting as a flag for check timing / don't check timing
//helper-function for easy use of non-blocking timing
boolean TimePeriodIsOver (unsigned long &expireTime, unsigned long TimePeriod) {
unsigned long currentMillis = millis();
if ( currentMillis - expireTime >= TimePeriod ) {
expireTime = currentMillis; // set new expireTime
return true; // more time than TimePeriod) has elapsed since last time if-condition was true
}
else return false; // not expired
}
void handle_oneshot_Timers() {
// only if time-checking for GREEN is enabled
if (check_green == true) {
if ( TimePeriodIsOver (green_switched_on, 5000) ) {
// if more than 5 seconds since switching ON have passed by
greenState = LOW; // set state to LOW
digitalWrite(greenPin, greenState); // switch LED to state LOW
check_green = false; // DIS-able time-checking
}
}
// only if time-checking for RED is enabled
if (check_red == true) {
if ( TimePeriodIsOver (red_switched_on, 5000) ) {
// if more than 5 seconds since switching ON have passed by
redState = LOW; // set state to LOW
digitalWrite(redPin, redState); // switch LED to state LOW
check_red = false; // DIS-able time-checking
}
}
// only if time-checking for OTHER is enabled
if (check_other == true) {
if ( TimePeriodIsOver (other_switched_on, 5000) ) {
// if more than 5 seconds since switching ON have passed by
otherState = LOW; // set state to LOW
digitalWrite(redPin, redState); // switch LED to state LOW
check_other = false; // DIS-able time-checking
}
}
}
void setup() {
// Initialize serial and wait for port to open:
Serial.begin(9600);
// This delay gives the chance to wait for a Serial Monitor without blocking if none is found
delay(1500);
// set the digital pin as output:
pinMode(greenPin, OUTPUT);
pinMode(redPin, OUTPUT);
pinMode(otherPin, OUTPUT);
// Defined in thingProperties.h
initProperties();
// Connect to Arduino IoT Cloud
ArduinoCloud.begin(ArduinoIoTPreferredConnection);
/*
The following function allows you to obtain more information
related to the state of network and IoT Cloud connection and errors
the higher number the more granular information you’ll get.
The default is 0 (only errors).
Maximum is 4
*/
setDebugMessageLevel(2);
ArduinoCloud.printDebugInfo();
}
void loop() {
handle_oneshot_Timers();
ArduinoCloud.update();
// Your code here
}
void onUpChange() {
if (up) {
if (greenState == LOW) {
greenState = HIGH;
green_switched_on = millis(); // store timestamp into variable at the moment the LED is switched on
check_green = true; // activate time-checking through flag-variable
}
}
else {
Serial.println("Lamp Off");
greenState = LOW;
}
digitalWrite(greenPin, greenState);
}
void onDownChange() {
// Add your code here to act upon Reddy change
if (down) {
if (redState == LOW) {
redState = HIGH;
red_switched_on = millis(); // store timestamp into variable at the moment the LED is switched on
check_red = true; // activate time-checking through flag-variable
}
}
else {
Serial.println("Lamp Off");
redState = LOW;
}
digitalWrite(redPin, redState);
}
void onStopChange() {
// Add your code here to act upon Stop change
if (stop) {
if (otherState == LOW) {
otherState = HIGH;
other_switched_on = millis(); // store timestamp into variable at the moment the LED is switched on
check_other = true; // activate time-checking through flag-variable
}
}
else {
Serial.println("Lamp Off");
otherState = LOW;
}
digitalWrite(otherPin, otherState);
}
best regards Stefan
I hope you didn't feel like I was trying to argue with you. Nevertheless, I am thankful for your time. I input the code you posted and it works perfectly. Thank you for providing it because it is something that I wasn't able to get to on my own. Now I learned something because I understand everything that you put in the code. It will be great for my future reference and applications.
This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.