Skip to content

Instantly share code, notes, and snippets.

@johnwargo
Last active October 29, 2023 15:45
Show Gist options
  • Save johnwargo/601a38c913dabb006f3412c93c276f6e to your computer and use it in GitHub Desktop.
Save johnwargo/601a38c913dabb006f3412c93c276f6e to your computer and use it in GitHub Desktop.
An better version of the Arduino random smoke generator
#define SMOKE_PIN A0
#define MIN_TIME 1000
#define MAX_TIME 5000
bool isSmoking = false;
int timerDuration = 0;
unsigned long startTime;
void setup() {
// configure the output pin to control the smoke generator
pinMode(SMOKE_PIN, OUTPUT);
// Enable the Arduino device's onboard LED
pinMode(LED_BUILTIN, OUTPUT);
// start making smoke. You can do this later based
// on some other trigger if you want
startSmoke();
}
void loop() {
// ===
// do some stuff
// ===
checkSmokeTimer();
// ===
// do some other stuff
// ===
}
void startSmoke() {
// turn the smoke machine on
digitalWrite(SMOKE_PIN, HIGH);
digitalWrite(LED_BUILTIN, HIGH);
isSmoking = true;
startTime = millis(); // capture when we started the timer
// figure out how long it generates smoke (randomly)
timerDuration = (int)random(MIN_TIME, MAX_TIME); // milliseconds
}
void startDelay() {
// turn the smoke machine off, then wait a while
digitalWrite(SMOKE_PIN, LOW);
digitalWrite(LED_BUILTIN, LOW);
isSmoking = false;
startTime = millis(); // capture when we started the timer
// figure out how long it waits between generating smoke (random duration)
timerDuration = (int)random(MIN_TIME, MAX_TIME); // milliseconds
}
void checkSmokeTimer() {
// Set `timerDuration` to 0 to stop this process (no smoke)
if (timerDuration > 0) {
// check to see if enough time's passed since the timer started
if ((millis() - startTime) > timerDuration) {
// timer expired, so time to switch modes
if (!isSmoking) {
// we're not smoking, so start the smoke
startSmoke();
} else {
// we're smoking, so switch to delay
startDelay();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment