Skip to content

Instantly share code, notes, and snippets.

@todocono
Created March 5, 2024 07:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save todocono/33e4309bf6699d574eb2974d136406e0 to your computer and use it in GitHub Desktop.
Save todocono/33e4309bf6699d574eb2974d136406e0 to your computer and use it in GitHub Desktop.
//Millis example
//Coded during class - Interaction Lab
//NYUSH IMA
//Mar 5 2024
int val;
int prevVal;
long startTime;
int state = 0;
void setup() {
Serial.begin(9600);
pinMode(2, INPUT);
pinMode(8, OUTPUT);
}
void loop() {
if (state == 0) {
state0();
} else if (state == 1) {
state1();
} else if (state == 2) {
state2();
}
delay(10);
}
/* change all these placeholders according to what you need*/
void state0() {
if (millis() < 1000) {
tone(8, 262);
}
if (millis() > 1000 && millis() < 2000) {
tone(8, 330);
}
if (millis() > 2000 && millis() < 3000) {
tone(8, 392);
}
if (millis() > 3000) {
noTone(8);
state = 1;
}
}
void state1() {
tone(8, random(100, 1100));
delay(100);
if (digitalRead(2) == HIGH) {
// transition
state = 2;
}
}
void state2() {
makeNoise();
readButton();
}
/* makeNoise is a function that does beep every sec*/
void makeNoise() {
if (millis() % 1000 < 10) {
//Serial.println("one second passed");
tone(8, 392, 100);
}
if ((millis() % 1000 < 110) && (millis() % 1000 > 100)) {
noTone(8);
}
}
/* readButton is a function that checks the button input*/
void readButton() {
val = digitalRead(2);
if (prevVal == LOW && val == HIGH) {
Serial.println("Pressed");
startTime = millis();
}
if (prevVal == HIGH && val == LOW) {
Serial.print("Released after ");
Serial.println(millis() - startTime);
}
prevVal = val;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment