Nodelay + serial

From Interaction Station Wiki
Revision as of 14:27, 6 June 2024 by Annasa (talk | contribs) (Created page with "<syntaxhighlight lang="c"> // Define the number of actions (you can adjust this as needed) const int numActions = 6; // Define the durations for each action (in milliseconds...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

<syntaxhighlight lang="c"> // Define the number of actions (you can adjust this as needed) const int numActions = 6;

// Define the durations for each action (in milliseconds) const unsigned long actionDurations[] = {3000, 2000, 3000, 4000, 1000, 1000}; // 3s, 2s, 3s, 4s, 1s

// Action variables int currentAction = 0; unsigned long previousMillis = 0; bool restartSequence = true; // Flag to track sequence restart

// LED pins const int led[] = {3, 4, 5, 6, 7}; // Example pin numbers for LEDs

void setup() {

 Serial.begin(9600);
 // Initialize LED pins
 for (int i = 0; i < numActions; i++) {
   pinMode(led[i], OUTPUT);
   digitalWrite(led[i], LOW);
 }

}

void performAction() {

 unsigned long currentMillis = millis();
 // Check if it's time to switch to the next action
 if (currentMillis - previousMillis >= actionDurations[currentAction]) {
   previousMillis = currentMillis;
   // Execute the current action
   switch (currentAction) {
     case 0:
       // Action 1
       digitalWrite(led[0], HIGH);
       break;
     case 1:
       // Action 2
       digitalWrite(led[0], LOW);
       digitalWrite(led[1], HIGH);
       break;
     case 2:
       // Action 3
       digitalWrite(led[1], LOW);
       digitalWrite(led[2], HIGH);
       break;
     case 3:
       // Action 4
       digitalWrite(led[2], LOW);
       digitalWrite(led[3], HIGH);
       break;
     case 4:
       // Action 5
       digitalWrite(led[3], LOW);
       digitalWrite(led[4], HIGH);
       break;
     case 5:
       // Action 5
       digitalWrite(led[4], HIGH);
       break;
   }
   // Move to the next action or restart sequence
   if (restartSequence) {
     currentAction = 0; // Start from the beginning
     restartSequence = false; // Reset the flag
   } else {
     currentAction = (currentAction + 1) % numActions; // Continue normally
   }
 }

}

void loop() {

 // Check if we received a serial message
 if (Serial.available() > 0) {
   int incomingByte = Serial.read();
   if (incomingByte == 1) {
     // Trigger the animating light function
     performAction();
   } else if (incomingByte == 2) {
     // Turn off all the lights
     for (int i = 0; i < numActions; i++) {
       digitalWrite(led[i], LOW);
     }
     // Restart the sequence from the beginning
     currentAction = 0;
     restartSequence = true;
   }
 }

} </syntaxhighlight lang="c">