text:
Toggle button switches through case statements with button debouncing
The overview of my code is that I want a toggle button to be pushed and each button push will move the code to the next case statement. In each case statement, there will be different LED functions. I need help with a few things

I need help with blinking 4 of the LEDs continuously with 100ms pause in case 1. Because it is not in the main loop, I am having trouble getting the 4 LEDs to switch on and off. Normally, I could just have a simple code that turns it on, then compares previous to last and if different, turns it off, and this continues.
I need the code to go back to case 0 once the button has been held for 2 seconds.
I cannot get my button debounce code to work from case 0 to case 1. If I add the debounce code in case 0 how I have it in the rest of the cases, it wont run through the rest of the cases.
Below is the code:

//LED variables for left turn signal OUT
int LED_1 = 2;
int LED_2 = 3;
int LED_3 = 4;
int LED_4 = 5;

//LED variables for right turn signal OUT
int LED_5 = 6;
int LED_6 = 7;
int LED_7 = 8;
int LED_8 = 9;

//break signal OUT
int BS_OUT = A5;

//reverse signal OUT
int RS_OUT = 10;

//toggle switch button between different modes
int toggle_IN = A4;

//switch case statement variable for togglemodes
int toggleState = 0;

//variables to see if the toggle button has been pressed or not
boolean oldSwitchStateToggle = LOW;
boolean newSwitchStateToggle = LOW;

//true or false to save whether button has been pressed for switching case statements
bool enabledToggle;

//debounce time to take care of button bouncing
const int debounce = 100; //ms

//time for holding a current time of millis()
unsigned long t = 0;

void setup()
{
  Serial.begin(9600);
  //toggle button input
  pinMode(toggle_IN, INPUT);

  //led outputs
  pinMode(LED_4, OUTPUT);
  pinMode(LED_3, OUTPUT);
  pinMode(LED_2, OUTPUT);
  pinMode(LED_1, OUTPUT);
  pinMode(LED_5, OUTPUT);
  pinMode(LED_6, OUTPUT);
  pinMode(LED_7, OUTPUT);
  pinMode(LED_8, OUTPUT);

}

void loop()
{
   //checking to see if toggle button has been pushed
   newSwitchStateToggle = digitalRead(toggle_IN);
   if(newSwitchStateToggle != oldSwitchStateToggle)
  {
    if(newSwitchStateToggle == HIGH)
    {
      //enabling toggle for if statements
      enabledToggle = true;
      //case switch for flow through 4 different LED output options
      toggleButtonState();

    }
    else
    enabledToggle = false;
    oldSwitchStateToggle = newSwitchStateToggle;
  }
}

void toggleButtonState()
{
  unsigned long nowToggle = millis();
  switch (toggleState)
  {

    case 0:
    Serial.println("0000");
          if(enabledToggle)
          {
            digitalWrite(LED_1, HIGH);
            t = nowToggle;
            toggleState = 1;
          }

          break;

    case 1:
    Serial.println("1111");
          if(enabledToggle)
          {
            digitalWrite(LED_1, LOW);
            digitalWrite(LED_2, HIGH);
            //alows going to next state after 100ms for button debounce
            if(nowToggle - t > debounce)
            {
              toggleState = 2;
              t = nowToggle;
            }
          }

          break;

     case 2:
     Serial.println("2222");
          if(enabledToggle)
          {
            digitalWrite(LED_2, LOW);
            digitalWrite(LED_3, HIGH);
            if(nowToggle - t > debounce)
            {
              toggleState = 3;
              t = nowToggle;
            }
          }

          break;

     case 3:
     Serial.println("3333");
         if(enabledToggle)
          {
            digitalWrite(LED_3, LOW);
            digitalWrite(LED_4, HIGH);
            if(nowToggle - t > debounce)
            {
              toggleState = 4;
              t = nowToggle;
            }
          }
          break;

     case 4:
     Serial.println("44444");
          if(enabledToggle)
          {
            turnOffLeds();
            if(nowToggle - t > debounce)
            {
              toggleState = 0;
              t = nowToggle;
            }
          }
          break;

  }
}

void turnOffLeds()
{
  digitalWrite(LED_1, LOW);
  digitalWrite(LED_2, LOW);
  digitalWrite(LED_3, LOW);
  digitalWrite(LED_4, LOW);
}

updated code: trying to add in debounce but it will not work

int LED_1 = 2;
int LED_2 = 3;
int LED_3 = 4;
int LED_4 = 5;

int LED_5 = 6;
int LED_6 = 7;
int LED_7 = 8;
int LED_8 = 9;

//toggle switch button between different modes
int toggle_IN = A4;

//switch case statement variable for togglemodes
int toggleState = 0;

//variables to see if the toggle button has been pressed or not
boolean oldSwitchStateToggle = LOW;
boolean newSwitchStateToggle = LOW;

//true or false to save whether button has been pressed for switching case statements
bool enabledToggle;

//debounce time to take care of button bouncing
const int debounce = 100; //ms

//time for holding a current time of millis()
unsigned long t = 0;

int ledBlinkState = LOW;

unsigned long prevBlinkMillis = 0;

const int blinkInterval = 150;

bool state1 = false;
bool state2 = false;
bool state3 = false;
bool state4 = false;
bool state0 = false;

void setup()
{
  Serial.begin(9600);
  //toggle button input
  pinMode(toggle_IN, INPUT);

  //led outputs
  pinMode(LED_4, OUTPUT);
  pinMode(LED_3, OUTPUT);
  pinMode(LED_2, OUTPUT);
  pinMode(LED_1, OUTPUT);
  pinMode(LED_5, OUTPUT);
  pinMode(LED_6, OUTPUT);
  pinMode(LED_7, OUTPUT);
  pinMode(LED_8, OUTPUT);

}

void loop()
{
  unsigned long nowToggle = millis();
  Serial.print("NOWWWWWW");
  Serial.println(nowToggle);
   //checking to see if toggle button has been pushed
   newSwitchStateToggle = digitalRead(toggle_IN);
   if(newSwitchStateToggle != oldSwitchStateToggle)
   {
    t = nowToggle;
    Serial.print("TIMEEEEE");
    Serial.println(t);
    if(newSwitchStateToggle == HIGH)
    {
      if(nowToggle - t > debounce)
      {
        //enabling toggle for if statements
        enabledToggle = true;
        //case switch for flow through 4 different LED output options
        toggleButtonState();
      }

    }
    else
    enabledToggle = false;
    oldSwitchStateToggle = newSwitchStateToggle;
  }

  unsigned long currentBlinkMillis = millis();

  if(state0 == true)
  {
    digitalWrite(LED_5, HIGH);
    digitalWrite(LED_6, HIGH);
    digitalWrite(LED_7, HIGH);
    digitalWrite(LED_8, HIGH);

    if(currentBlinkMillis - prevBlinkMillis >= blinkInterval)
    {
      prevBlinkMillis = currentBlinkMillis;
      if(ledBlinkState == LOW)
      {
        ledBlinkState = HIGH;
      }
      else
      {
        ledBlinkState = LOW;
      }
      digitalWrite(LED_1, ledBlinkState);
      digitalWrite(LED_2, ledBlinkState);
      digitalWrite(LED_3, ledBlinkState);
      digitalWrite(LED_4, ledBlinkState);
    }
  }

  if(state1 == true)
  {
    digitalWrite(LED_1, HIGH);
    digitalWrite(LED_2, HIGH);
    digitalWrite(LED_3, HIGH);
    digitalWrite(LED_4, HIGH);

    if(currentBlinkMillis - prevBlinkMillis >= blinkInterval)
    {
      prevBlinkMillis = currentBlinkMillis;
      if(ledBlinkState == LOW)
      {
        ledBlinkState = HIGH;
      }
      else
      {
        ledBlinkState = LOW;
      }
      digitalWrite(LED_5, ledBlinkState);
      digitalWrite(LED_6, ledBlinkState);
      digitalWrite(LED_7, ledBlinkState);
      digitalWrite(LED_8, ledBlinkState);
    }
  }

  if(state2 == true)
  {
    if(currentBlinkMillis - prevBlinkMillis >= blinkInterval)
    {
      prevBlinkMillis = currentBlinkMillis;
      if(ledBlinkState == LOW)
      {
        ledBlinkState = HIGH;
      }
      else
      {
        ledBlinkState = LOW;
      }
      digitalWrite(LED_1, ledBlinkState);
      digitalWrite(LED_2, ledBlinkState);
      digitalWrite(LED_3, ledBlinkState);
      digitalWrite(LED_4, ledBlinkState);
      digitalWrite(LED_5, ledBlinkState);
      digitalWrite(LED_6, ledBlinkState);
      digitalWrite(LED_7, ledBlinkState);
      digitalWrite(LED_8, ledBlinkState);
    }
  }

  if(state3 == true)
  {
    digitalWrite(LED_1, HIGH);
    digitalWrite(LED_2, HIGH);
    digitalWrite(LED_3, HIGH);
    digitalWrite(LED_4, HIGH);
    digitalWrite(LED_5, HIGH);
    digitalWrite(LED_6, HIGH);
    digitalWrite(LED_7, HIGH);
    digitalWrite(LED_8, HIGH);
  }

  if(state4 == true)
  {
    turnOffLeds();
  }

}

void toggleButtonState()
{
  switch (toggleState)
  {

    case 0:
    Serial.println("0000");
          if(enabledToggle)
          {
            turnOffLeds();
            state4 = false;
            state0 = true;
            toggleState = 1;
          }

          break;

    case 1:
    Serial.println("1111");
          if(enabledToggle)
          {
            turnOffLeds();
            state0 = false;
            state1 = true;
            toggleState = 2;
          }

          break;

     case 2:
     Serial.println("2222");
          if(enabledToggle)
          {
            turnOffLeds();
            state1 = false;
            state2 = true;
            toggleState = 3;
          }

          break;

     case 3:
     Serial.println("3333");
         if(enabledToggle)
          {
            turnOffLeds();
            state2 = false;
            state3 = true;
            toggleState = 4;
          }
          break;

     case 4:
     Serial.println("44444");
          if(enabledToggle)
          {
            turnOffLeds();
            state3 = false;
            state4 = true;
            toggleState = 0;
          }
          break;

  }
}

void turnOffLeds()
{
  digitalWrite(LED_1, LOW);
  digitalWrite(LED_2, LOW);
  digitalWrite(LED_3, LOW);
  digitalWrite(LED_4, LOW);
  digitalWrite(LED_5, LOW);
  digitalWrite(LED_6, LOW);
  digitalWrite(LED_7, LOW);
  digitalWrite(LED_8, LOW);
}

1. the toggleButtonState() should not contain any LED code ... it should only set a flag ... the blink code should be inside loop() and be activated by the flag

2. do button detection at begining of loop() ... the button code should only set a flag, nothing more

3. ... read 2.

So for example, I would be in case 1, and it would set a variable to true. Then in the loop, have an if statement to where if that variable is true, then it will loop through that blinking LED code?

yes ... the loop() repeats many times a second ... use millis() to blink ... see blinkWithoutDelay example sketch

@jsotola I got the flagging figure out and my code works great for blinking LEDs. I am now having trouble with getting the debounce code to work. I have it in my updated code but it does not work. I am trying to incorporate it around my button clicking in the loop(). When looking at it on my serial moniter, "t" is holding nowToggle every instance and not holding it at a single value.

I would recommend you start with an existing library to do the "button debouncing" and "long button press" detection.
The EasyButton library on github and via the Arduino IDE library manager has potential.
Here is a test sketch which shows the "button detection" part of your requirement.
If you were to add a variable to represent "state", this code could be adapted to control a case statement bases on state.
// Sketch uses 3286 bytes (10%) of program storage space.
// Global variables use 357 bytes (17%) of dynamic memory.
#include <EasyButton.h>

// EasyButton(uint8_t pin,
//            uint32_t debounce_time = 35,
//            bool pullup_enable = true,
//            bool active_low = true)
EasyButton button(2);

void onPressed(){
  // Your code here to INCREMENT a "state counter".
  Serial.println("Button pressed");
}

void onPressedForDuration(){
  // Your code here to SET the "state counter" to 0.
  Serial.println("Button pressed for duration");
}

void setup(){

  // Test output to serial monitor.
  Serial.begin(9600);

  // Initialize the button.
  button.begin();

  // Add the callback function to be called when the button is pressed.
  button.onPressed(onPressed);

  // Add the callback function to be called when the button is pressed
  // for at least the given time.
  button.onPressedFor(2000, onPressedForDuration);

}

void loop(){

  // Continuously read the status of the button.
  button.read();

}

I would have done it this way, but I am going to transfer this into the eclipse compiler. I am staying away from arduino made libraries. I am trying to find a way to look at what is going on in the background of the easybutton.h. Do you know where I could find this?

@Myles - You can look at the EasyButton source code to see how it works: https://github.com/evert-arias/EasyButton/tree/main/src

I answered how to do a mode switch with just one button many many years ago.  Make use of it what you will... it's just a sample skeleton. Here is the code I used:
/*
 Using a single switch to select between 3 modes
*/
// Schematic: http://www.pwillard.com/files/mode4.jpg
//===============================================================
// Global Variables & Constants
//===============================================================

const int ledPinOne = 2; // LED1 ANODE
const int ledPinTwo = 4; // LED2 ANODE
const int ledPinThree = 7; // LED3 ANODE
const int modePin = 13; // Active HIGH, held low by 4.7K

int mode = 0; // Selector State (Initial state = ALL OFF)
int val = 0; // Pin 13 HIGH/LOW Status
int butState = 0; // Last Button State
int modeState = 0; // Last Mode State
boolean debug = 1; // 1 = Print Serial Enabled / 0 = disabled

//===============================================================
// SETUP
//===============================================================
void setup () {
 pinMode(ledPinOne, OUTPUT);
 pinMode(ledPinTwo, OUTPUT);
 pinMode(ledPinThree, OUTPUT);
 pinMode(modePin, INPUT);
 if (debug){
 Serial.begin(9600);
 Serial.print("Initial Mode: ");
 Serial.println(mode);
 Serial.print("Setup Complete\n");
 }
}

//===============================================================
// Main Loop
//===============================================================
void loop() {

 val = digitalRead(modePin);

 // If we see a change in button state, increment mode value
 if (val != butState && val == HIGH){
 mode++;
 }

 butState = val; // Keep track of most recent button state

 // No need to keep setting pins *every* loop
 if (modeState != mode){

 // If no keys have been pressed yet don't execute
 // the switch code below
 // if (mode != 0) {

 switch ( mode ) {
 //case 1 is actually handled below as default

case 2:
 digitalWrite(ledPinOne, LOW);
 digitalWrite(ledPinTwo, HIGH);
 showState();
 break;
 case 3:
 digitalWrite(ledPinTwo, LOW);
 digitalWrite(ledPinThree, HIGH);
 showState();
 break;
 default:
 mode = 1;
 // loop back to 1 by default, seems redundant but
 // it also handles the "mode is > 3" problem
 digitalWrite(ledPinThree, LOW);
 digitalWrite(ledPinOne, HIGH);
 showState();
 break;
 } // end switch
// } // end of "if mode = 0" check
 } // end of ModeState check
 modeState = mode; // Keep track of mode recent mode value
 delay(10); // slow the loop just a bit for debounce
}

//===============================================================
// Subroutine
//===============================================================
void showState() {
 if (debug){
 Serial.print("Mode: ");
 Serial.println(mode);
 }
}


text:
Trying to keep my main code running unless an input is LOW for a certain amount of time
I have code that creates a sequential signal with 4 LEDS. It cascades to the right. This works when I hold down the input button. What I need help with is having the code run exactly the same when there is an input signal of .5s HIGH --> .5s LOW (repeat). So what I am thinking in terms of pseudo-code is a code that keeps reading a HIGH signal as long as the signal is not low for more than .5s.
//LED outputs
int LED_5 = 6;
int LED_6 = 7;
int LED_7 = 8;
int LED_8 = 9;

//right turn signal
int RTS_IN  = A0;

//state variable for switch case statements
int stateRightTurn = 0;

//time variable
unsigned long t = 0;
//interval is the time spacing between case statements
unsigned long interval = 100;
//time for shutting off the code
unsigned long off = 600;

void setup()
{
  Serial.begin(9600);

  //inputs
  pinMode(RTS_IN,  INPUT);

  //right turn signal output from left to right
  pinMode(LED_5, OUTPUT);
  pinMode(LED_6, OUTPUT);
  pinMode(LED_7, OUTPUT);
  pinMode(LED_8, OUTPUT);

}

void loop()
{
  StateRight();

}

//sequential turn signals
void StateRight()
{

   switch (stateRightTurn)
    {

    case 0: //idle
          if (digitalRead(RTS_IN) == HIGH)
          {
              Serial.println("0000");
              t = millis();
              SwitchRightLedsOff();
              stateRightTurn = 1;
          }
          break;

      case 1: //One LED On
          if (digitalRead(RTS_IN) == LOW)
          {
              Serial.println("1111-LOWLOWLOW");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          else if (millis() > t + interval)
          {
              Serial.println("1111-HHHHHHHH");
              t = millis();
              digitalWrite(LED_5, HIGH);
              stateRightTurn = 2;
          }
          break;

      case 2: // Two LEDs On
          if (digitalRead(RTS_IN) == LOW)
              {
                  Serial.println("2222-LOWLOWLOW");
                  SwitchRightLedsOff();
                  stateRightTurn = 0;
              }
              else if (millis() > t + interval)
              {
                  Serial.println("2222-HHHHHHHH");
                  t = millis();
                  digitalWrite(LED_6, HIGH);
                  stateRightTurn = 3;
              }
          break;

      case 3: //Three LEDs On
          if (digitalRead(RTS_IN) == LOW)
          {
              Serial.println("3333-LOWLOWLOW");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          else if (millis() > t + interval)
          {
              Serial.println("3333-HHHHHHHH");
              t = millis();
              digitalWrite(LED_7, HIGH);
              stateRightTurn = 4;
          }
          break;

      case 4: //Four LEDs On
          if (digitalRead(RTS_IN) == LOW)
          {
              Serial.println("4444-LOWLOWLOW");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          else if (millis() > t + interval)
          {
              Serial.println("4444-HHHHHHHH");
              t = millis();
              digitalWrite(LED_8, HIGH);
              stateRightTurn = 5;
          }
          break;

      case 5: //No LEDs on
          if (digitalRead(RTS_IN) == LOW)
          {
              Serial.println("5555-LOWLOWLOW");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          else if (millis() > t + interval)
          {
              Serial.println("55555-HHHHHHHH");
              SwitchRightLedsOff();
              stateRightTurn = 0;
          }
          break;
    }
}

//method to switch LEDs off
void SwitchRightLedsOff()
{
  digitalWrite(LED_5, LOW);
  digitalWrite(LED_6, LOW);
  digitalWrite(LED_7, LOW);
  digitalWrite(LED_8, LOW);
}

And what is your actual question? You didn't ask one. And your description doesn't seem clear to me. Please isolate a single issue with your code, describe only this issue, what happened when you tried it and what you expected to happen.

@chrisl I have updated main description. Let me know if that makes more sense.

If you really are going to use this in an actual vehicle, please consider what should happen with your "sequential turn signals" when the vehicle's hazard lights are flashing at the same time. What should the turn signals be doing if the brake light is on at the same time?

@VE7JRO I have all of that code working simultaneously with the code above. I deleted it all out and segmented just this code for simplicity.

It isn't your issue, but you should move t to the other side of the > sign in expressions like this: (millis() > t + interval) so that you are always comparing intervals rather than timestamps.  // Your proposed solution is a debouncing, or lock-out of a low inputs for 0.5s after the last observed high.

millis()-t is the proper way to handle clock rollover as long as millis() and t are of the same type and interval is smaller than rollover value

Assuming that digitalRead(RTS_IN) is the input, I'd read it once at the top of the loop and save the timestamp if it is HIGH, and then use the condition millis() - timestamp <= 500 as a latched input variable.
I'd also do the rest of the Input (i.e.: millis()) at the top of the function, convert the time comparisons from absolutes into intervals, and consider factoring the not-enabled case out of the switch's cases.
Untested code:
//LED outputs
int LED_5 = 6;
int LED_6 = 7;
int LED_7 = 8;
int LED_8 = 9;

//right turn signal
int RTS_IN  = A0;

//state variable for switch case statements
int stateRightTurn = 0;

//time variable
unsigned long t = 0;
//interval is the time spacing between case statements
unsigned long interval = 100;
//time for shutting off the code
unsigned long off = 600;

void setup()
{
  Serial.begin(9600);

  //inputs
  pinMode(RTS_IN,  INPUT);

  //right turn signal output from left to right
  pinMode(LED_5, OUTPUT);
  pinMode(LED_6, OUTPUT);
  pinMode(LED_7, OUTPUT);
  pinMode(LED_8, OUTPUT);

}

void loop()
{
  StateRight();

}

//sequential turn signals
void StateRight()
{
  const int latchInterval = 500; // ms
  static unsigned long lastHigh = -latchInterval; // initialize into the rolled-over past
  unsigned long now = millis();
  int inState = digitalRead(RTS_IN);
  if (inState == HIGH) { //update timer
    lastHigh = now;
  }
  bool enabled = (now - lastHigh <= latchInterval) ; // latched on for 500 ms after off

  switch (stateRightTurn)
  {
    case 0: //idle
      if (enabled)
      {
        Serial.println("0000");
        t = now;
        SwitchRightLedsOff();
        stateRightTurn = 1;
      }
      break;

    case 1: //One LED On
      if (!enabled)
      {
        Serial.println("1111-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t > interval)
      {
        Serial.println("1111-HHHHHHHH");
        t = now;
        digitalWrite(LED_5, HIGH);
        stateRightTurn = 2;
      }
      break;

    case 2: // Two LEDs On
      if (!enabled)
      {
        Serial.println("2222-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t >  interval)
      {
        Serial.println("2222-HHHHHHHH");
        t = now;
        digitalWrite(LED_6, HIGH);
        stateRightTurn = 3;
      }
      break;

    case 3: //Three LEDs On
      if (!enabled)
      {
        Serial.println("3333-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t > interval)
      {
        Serial.println("3333-HHHHHHHH");
        t = now;
        digitalWrite(LED_7, HIGH);
        stateRightTurn = 4;
      }
      break;

    case 4: //Four LEDs On
      if (!enabled)
      {
        Serial.println("4444-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t > interval)
      {
        Serial.println("4444-HHHHHHHH");
        t = now;
        digitalWrite(LED_8, HIGH);
        stateRightTurn = 5;
      }
      break;

    case 5: //No LEDs on
      if (!enabled)
      {
        Serial.println("5555-LOWLOWLOW");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      else if (now - t > interval)
      {
        Serial.println("55555-HHHHHHHH");
        SwitchRightLedsOff();
        stateRightTurn = 0;
      }
      break;
  }
}

//method to switch LEDs off
void SwitchRightLedsOff()
{
  digitalWrite(LED_5, LOW);
  digitalWrite(LED_6, LOW);
  digitalWrite(LED_7, LOW);
  digitalWrite(LED_8, LOW);
}

This worked perfectly! I understand it as well. I was trying to do something with the same thought process

The trick is turning your input(s) into the helpful "an input is LOW for a certain amount of time"  timer-based state variable that your code can use.

If I understand your requirements correctly, you could use a variable to determine if your sequential lights should be flashing or not. If the input signal is LOW for more than 1/2 second, the variable should change to LOW, telling the Arduino to stop flashing your sequential lights.
Let's pretend that your input signal is at the correct voltage and is very accurate with it's time keeping. At the 501ms mark, with no HIGH input signal, your lights should stop flashing.
A simple timer and state variable may work. Here is a test sketch.
// Sketch uses 1144 bytes (3%) of program storage space.
// Global variables use 19 bytes (0%) of dynamic memory.
class MillisTimer{

  private:

    unsigned long m_timeInMilliSeconds;
    unsigned long m_previousMillis;
    byte m_timerActive;

  public:

    MillisTimer(unsigned long timeInMilliSeconds):
      m_timeInMilliSeconds(timeInMilliSeconds),
      m_timerActive(0),
      m_previousMillis(0){
    }

    bool Update(){
      if(m_timerActive && (millis() - m_previousMillis >= m_timeInMilliSeconds)){
        m_previousMillis += m_timeInMilliSeconds;
        return 1;
      }
      else{
        return 0;
      }
    }

    void Start(){
      m_timerActive = 1;
    }

    void Stop(){
      m_timerActive = 0;
    }

    void ReStart(){
      m_timerActive = 1;
      m_previousMillis = millis();
    }

    byte IsActive(){
      return m_timerActive;
    }

};

// Make a copy of the object to work with.
MillisTimer MyTimer(501);

byte inputPin = 2;
byte signalActive = 0;

void setup(){

  // NOTE: Pull-down resistor required if input floating.
  pinMode(inputPin, INPUT);
  MyTimer.Start();

  // Timer status indicator for testing purposes.
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  if(digitalRead(inputPin) == HIGH){
    signalActive = 1;
    MyTimer.ReStart();
  }

  if(MyTimer.Update()){
    signalActive = 0;
  }

  // Test ouput of "signalActive" variable using built in LED on an Uno.
  if(signalActive == 1){
    digitalWrite(LED_BUILTIN, HIGH);
  }
  else{
    digitalWrite(LED_BUILTIN, LOW);
  }

}

I am trying to get this work. I will let you know.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
How do I run 4 LEDs sequentially based off of a push button input?
I am trying to create a program that runs 4 LEDs sequentially while also being able to do other things with different inputs and outputs. Because of this, I am using the millis function and not the delay. I have the code working but not exactly how I want it. It runs through the LEDs and turns them off then runs through again like it is supposed too but there are two problems:

It will pass through the first if statement, then the first again then to the second, then it will go through the first, the second, then the third, etc. I want it to cascade through the if statements, keeping the LED from the previous steps on without repeating. It is causing the LEDs to flash super quick.
The code still runs even if the input is read as LOW as it is dependent on millis. I somehow need it to start from the beginning every time the button is pushed and reset when the button is not pressed.

below the code is a picture of the serial monitor showing the program running through every if statement and not staying in one and moving to the next. If needed, I can add a video showing what the LEDs do.
below is the code
//Code to build 4 sequentially run LEDs that reset everytime there is not input
int RTS_IN  = A0; //input button

//Output LEDs, assigning them to pins
int LED_5 = 5;
int LED_6 = 6;
int LED_7 = 7;
int LED_8 = 8;

//1 second for each time interval
unsigned long Time1 = 1000;
unsigned long Time2 = 2000;
unsigned long Time3 = 3000;
unsigned long Time4 = 4000;
unsigned long Time5 = 5000;

//variables for holding millis values
unsigned long currentMillis;
unsigned long newMillis = 0;

void setup()
{
  Serial.begin(9600);

  pinMode(RTS_IN, INPUT);
  pinMode(LED_5, OUTPUT);
  pinMode(LED_6, OUTPUT);
  pinMode(LED_7, OUTPUT);
  pinMode(LED_8, OUTPUT);

}

void loop()
{
  currentMillis = millis();

  //using sequential method if the input button pressed and held
  if(digitalRead(RTS_IN) == HIGH)
  {
    sequential();
  }
  //keeping LEDs OFF if button has been released
  else
  digitalWrite(LED_5, LOW);
  digitalWrite(LED_6, LOW);
  digitalWrite(LED_7, LOW);
  digitalWrite(LED_8, LOW);
}

//method to run LEDs sequentially
void sequential()
{

  //if statement checking to see if a second has passed to allow the first led to turn on
  if(currentMillis - newMillis >= Time1)
  {
    Serial.println("5 is on");

    digitalWrite(LED_5, HIGH);
    delay(1);

    //if statement checking to see if 2 seconds has passed to allow the second led to turn on
    if(currentMillis - newMillis >= Time2)
    {
      Serial.println("6 is on");

      digitalWrite(LED_6, HIGH);
      delay(1);

      //if statement checking to see if 3 seconds has passed to allow the third led to turn on
      if(currentMillis - newMillis >= Time3)
      {
        Serial.println("7 is on");

        digitalWrite(LED_7, HIGH);
        delay(1);

        //if statement checking to see if 4 seconds has passed to allow the fourth led to turn on
        if(currentMillis - newMillis >= Time4)
        {
          Serial.println("8 is on");

          digitalWrite(LED_8, HIGH);
          delay(1);

          //if statement to turn off LEDs and wait a second before turning the first back on
          if(currentMillis - newMillis >= Time5)
          {
            Serial.println("All off");

            digitalWrite(LED_5, LOW);
            digitalWrite(LED_6, LOW);
            digitalWrite(LED_7, LOW);
            digitalWrite(LED_8, LOW);

            //this is in order to add a period of this process to each of the
            //interval times to keep up with millis without this, they would all stay on
            Time1 = Time1 + 5000;
            Time2 = Time2 + 5000;
            Time3 = Time3 + 5000;
            Time4 = Time4 + 5000;
            Time5 = Time5 + 5000;
            delay(1);

          }
        }
      }
    }
  }
}

updated code below with if else statements and the other programming combined

const int RTS_IN  = A0;
const int LTS_IN = A1;

//break signal
const int BS_IN  = A2;
const int BS_OUT = 11;

//reverse signal
const int RS_IN  = A3;
const int RS_OUT = 10;

const int NR_OF_LEDS = 4;
const int RIGHTLEDS[NR_OF_LEDS] = { 6, 7, 8, 9 };
const int LEFTLEDS[NR_OF_LEDS] = { 5, 4, 3, 2 };
const int interval = 100;

int nrOfRightLedsOn = 0;
int nrOfLeftLedsOn = 0;

unsigned long t = 0;

void StateRight();
void StateRightProcess();

void StateLeft();
void StateLeftProcess();

boolean oldSwitchStateRS = LOW;
boolean newSwitchStateRS = LOW;
boolean oldSwitchStateBS = LOW;
boolean newSwitchStateBS = LOW;

void setup()
{
  Serial.begin(9600);
  pinMode(RTS_IN, INPUT);
  pinMode(LTS_IN, INPUT);

  for (int led = 0; led < NR_OF_LEDS; led++)
  {
    pinMode(RIGHTLEDS[led], OUTPUT);
  }

  for (int led = 0; led < NR_OF_LEDS; led++)
  {
    pinMode(LEFTLEDS[led], OUTPUT);
  }

}

void loop()
{
  StateRight();
  StateLeft();

  newSwitchStateBS = digitalRead(BS_IN);
   if(newSwitchStateBS != oldSwitchStateBS)
  {
    if(newSwitchStateBS == HIGH)
    {
      digitalWrite(BS_OUT, HIGH);
    }
    else
    digitalWrite(BS_OUT, LOW);
    oldSwitchStateBS = newSwitchStateBS;
  }

 newSwitchStateRS = digitalRead(RS_IN);
  if(newSwitchStateRS != oldSwitchStateRS)
  {
    if(newSwitchStateRS == HIGH)
    {
      digitalWrite(RS_OUT, HIGH);
    }
    else
    digitalWrite(RS_OUT, LOW);
    oldSwitchStateRS = newSwitchStateRS;
  }

}

void StateRight()

{
  if(digitalRead(RTS_IN) == LOW)
  {
    SwitchRightLedsOff();
    nrOfRightLedsOn = 0;
    t = millis() + interval;
  }
  else if (nrOfRightLedsOn < NR_OF_LEDS)
  {
    StateRightProcess();
  }
  else
  {
    if(millis() >= t + interval)
    {
      t = millis();
      SwitchRightLedsOff();
      nrOfRightLedsOn = 0;
    }
  }
}

void StateRightProcess()
{
  if(millis() >= t + interval)
  {
    t = millis();
    digitalWrite(RIGHTLEDS[nrOfRightLedsOn], HIGH);
    nrOfRightLedsOn++;
  }
}

void SwitchRightLedsOff()
{
  for (int led = 0; led < NR_OF_LEDS; led++)
  {
    digitalWrite(RIGHTLEDS[led], LOW);
  }
}

void StateLeft()
{
  if(digitalRead(LTS_IN) == LOW)
  {
    SwitchLeftLedsOff();
    nrOfLeftLedsOn = 0;
    t = millis() + interval;
  }
  else if (nrOfLeftLedsOn < NR_OF_LEDS)
  {
    StateLeftProcess();
  }
  else
  {
    if (millis() >= t + interval)
    {
      t = millis();
      SwitchLeftLedsOff;
      nrOfLeftLedsOn = 0;
    }
  }
}

void StateLeftProcess()
{
  if (millis() >= t + interval)
  {
    t = millis();
    digitalWrite(LEFTLEDS[nrOfLeftLedsOn], HIGH);
    nrOfLeftLedsOn++;
  }
}

void SwitchLeftLedsOff()
{
  for (int led = 0; led < NR_OF_LEDS; led++)
  {
    digitalWrite(LEFTLEDS[led], LOW);
  }
}

Thanks for the wonderful question. here is the Arduino project link which you can use for further discussion. I am sure, you will find it very easy to share your project in this way https://wokwi.com/arduino/projects/321913849735283283

To be honest, I don't understand exactly the problems, but I try to give some guideline and hope you can use the idea to fix your problems.
What you need is a so called 'state machine'.
I think (according to your problem) that you have 6 states:
0 Idle (no sequence)
1 One LED on
2 Two LEDs on
3 Three LEDs on
4 Four LEDs on
5 No LEDs on

For this you can best use an enum type and global variable with similar values:
enum EState
{
    Idle,
    OneLedOn,
    TwoLedsOn,
    ThreeLedsOn,
    FourLedsOn,
    NoLedsOn
}

EState _state;

You need a function to check the new state, depending on the current state. In words something like:
current     When                          Action           New
state                                                      state
--------    ----------------------------  ---------------- -----
Idle        digitalRead(RTS_IN) == HIGH   Start counter    OneLedOn
                                          Switch on LED 0
OneLedOn    digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            5 seconds have passed         Switch on LED 1
                                          Start counter    TwoLedsOn
TwoLedsOn   digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            5 seconds have passed         Switch on LED 2
                                          Start counter    ThreeLedsOn
ThreeLedsOn digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            5 seconds have passed         Switch on LED 3
                                          Start counter    ThreeLedsOn
FourLedsOn  digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            5 seconds have passed         Switch LEDs off
                                          Start counter    NoLedsOn
NoLedsOn    digitalRead(RTS_IN) == LOW    Switch LEDs off  Idle
            5 seconds have passed         Switch on LED 0
                                          Start counter    OneLedn

(if you would draw one circle for each state and arrows between them, a so called UML State Diagram, you will see a much clearer way to depict the states and flows).
I don't have a compiler so I do it out of my head.
void Process()
{
    switch (_state)
    {
    case EState::Idle:
        if ((digitalRead(RTS_IN) == HIGH)
        {
            _time = millis();
            digitalWrite(LED_5, HIGH);
            _state = EState::OneLedOn;
        }
        break;
    case EState::OneLedOn:
        if ((digitalRead(RTS_IN) == LOW)
        {
            SwitchLedsOff();
            _state = Idle;
        }
        else if (millis() > time + 5000)
        {
            _time = millis();
            digitalWrite(LED_6, HIGH);
            _state = EState::TwoLedsOn;
        }
        break;
    case EState::TwoLedsOn:
       ...
}

The function SwitchLEDsoff sets all LEDs to low, and you only need one unsigned long _time global variable which you update when a new state starts and check in most states.
Note that high likely you can optimize this (like making each state its own function and removing almost duplicated code), but the main goal is to let you understand how to use a state machine and to use it in this sketch and future sketches.
Update
The following sketch is the same as yours but:

Optimized for reducing code duplication (ProcessState)
Introduced constants
Introduced array for LEDs to iterate over
Removed the state, instead used _nrOfLedsOn
Removed idle state, handled separately now
Prefixed global variables with an underscore (personal preference)
Better names for variables/functions
Used prototypes to put functions in logical order (high level to low level)

Code:
const int RTS_IN  = A0;
const int NR_OF_LEDS = 4;
const int LEDS[NR_OF_LEDS] = { 5, 6, 7, 8 };
const int DURATION = 300;

int _nrOfLedsOn = 0;
unsigned long _time = 0;

void ProcessState();
void ProcessLedsState();
void SwitchLedsOff();

void setup()
{
    Serial.begin(9600);
    pinMode(RTS_IN, INPUT);
    for (int led = 0; led < NR_OF_LEDS; led++)
    {
        pinMode(LEDS[led], OUTPUT);
    }
}

void loop()
{
    ProcessState();
}

void ProcessState()
{
    if (digitalRead(RTS_IN) == LOW)
    {
        SwitchLedsOff();
        _nrOfLedsOn = 0;
        _time = millis() + DURATION + 1;
    }
    else if (_nrOfLedsOn < NR_OF_LEDS)
    {
        ProcessLedsState();
    }
    else
    {
        if (millis() > _time + DURATION)
        {
            _time = millis();
            SwitchLedsOff();
            _nrOfLedsOn = 0;
        }
    }
}

void ProcessLedsState()
{
    if (millis() > _time + DURATION)
    {
        _time = millis();
        digitalWrite(LEDS[_nrOfLedsOn], HIGH);
        _nrOfLedsOn++;
    }
}

void SwitchLedsOff()
{
    for (int led = 0; led < NR_OF_LEDS; led++)
    {
        digitalWrite(LEDS[led], LOW);
    }
}

I think you nailed it! This is a lot clearer way of coding it I believe. I will try to implement this into my code and get back to you. I appreciate the quick response.

You're welcome.

I have implemented the new code with your help and It works great except for one thing, it doesnt enter state 5 and turn the LEDs LOW with RTS_IN HIGH. I have updated my original post

Change SwitchLedsOff; to SwitchLedsOff(); in case 5.

Check the update, I optimized the sketch.

Awesome, I will check that code out and try to implement the parts that I can understand. You have been a great help thank you.

what is the point of have those case statements if the code just falls through. I also do not understand why you add 1 to t in the first if statement in void ProcessState(). Can you explain please?

You are right about the switch statement, I converted it/combined it with the previous if statement. I also fixed a 'bug' where I had two methods named equal. And the reason why to add +1: If you see the function ProcessLedsState, you see if (millis() > _time + DURATION) ... when it's equal it wouldn't trigger immediately, so I added 1. Maybe instead using >= would be better, as you probably want to change LEDs every 300 ms, not when it's (necessarily) more than 300 ms.

so do i only need 2 case statements then?

Let us continue this discussion in chat.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Integration of MAX30100 and DS18B20 Thermal Probe Integration
This is for my final year project that I have been tasked with designing a patient monitoring system. However, during the last stretch of model prototyping, I am experiencing issues with my MAX30100 and DS18B20 thermal probe.
My thermal probe is giving me a proper reading of the temperature. However, the oximeter values are always stuck to zero and the call back function is not executed. I did read that it was an issue where the thermal probe continues to do conversion and doesn't allow the max30100 sensor to perform any other functions. So for that, i just had to pass sensors.setWaitForConversion(false);
I did try to write the code for the DS18B20 thermal probe and the oximeter sensor seperately and it executed perfectly. However, when I try to integrate everything together into a final project, the max30100 sensor doesn't carry out the reading and is stuck to zero while the thermal probe is perfectly working finding out its temperature. I did the same coding process as the previous when i tried to seperately work with the thermal and oximeter sensor. However, it is the final integration that is causing a lot of issues.
The data will be sent to firebase real-time database via the ESP8266 Wi-Fi module. I have got it to work fine. But i am stuck on the final integration of the BP machine, the MAX30100 Oximeter sensor and the DS18B20 Waterproof Thermal Probe. I am also using the Arduino Mega2560 board.
Could anyone guide me as to how do I perform integration of the MAX30100 Sensor with the DS18B20 Probe?
Attaching code for my project below:
#include <LiquidCrystal_I2C.h>
#include <SoftwareSerial.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"

#define REPORTING_PERIOD_MS 1000
PulseOximeter pox;
uint32_t tsLastReport = 0;
float oxy_lvl = 0.00;

unsigned char alert = 0;
unsigned char system_alert = 0;
unsigned char alert_flag=0;

LiquidCrystal_I2C lcd(0x27,16,2);
SoftwareSerial myserial(13, 12);    // RX, TX for blood pressure sensor
SoftwareSerial esp8266(3, 2);     // rx,tx for esp8266

#define ONE_WIRE_BUS 3
#define HELP_TONE buzz, 2000, 200

const int buzz=9;

OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float cel=0.00;

String data_pressure;
char  buff[15];

String send_data_string;

const int no_of_data = 5;
String main_data[10];
int sensorValue = 0;
unsigned int tempVal = 0;

int  sys_u = 130, dia_u = 90, temp_l = 24, temp_u = 37, pulse_l = 30, pulse_u = 120;
int sys, dia, p, stay = 1;

void onBeatDetected()
{
  Serial.println("Heart beat detected!! Oximeter pulse detected!!");
}

void setup()
{
  pinMode(buzz, OUTPUT);
  Serial.begin(9600);
  esp8266.begin(9600);
  myserial.begin(9600);
  sensors.begin();
  sensors.setWaitForConversion(false);
  lcd.begin();
  lcd.clear();
  Serial.print("Initializing Oximeter and other sensors");
  if(!pox.begin())
  {
    Serial.println("Oximeter Failed");
    lcd.print("Oximeter Failed");
    for(;;);
  }
  else
  {
    Serial.println("Oximeter Succeeded");
  }
  //pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);
  pox.setOnBeatDetectedCallback(onBeatDetected);
  lcd.print(F("        Patient "));
  lcd.setCursor(0, 1);
  lcd.print(F(" Health  Monitor "));
  delay(2000);
  send_data_string = String(sys) + ',' + String(dia) + ',' + String(p) + ',' + String(cel) + ',' + String(oxy_lvl);
  Serial.println("send_data_string = " + String(send_data_string));
  send_parameters();
  delay(4000);
  lcd.clear();
}

void loop()
{
  digitalWrite(buzz,LOW);
  read_temperature_and_oxi();
  main_display();
   myserial.listen();
   if (myserial.available())
   {
     while (myserial.available())
     {
       data_pressure = myserial.readString();
     }
     data_pressure.trim();
     data_pressure.toCharArray(buff, data_pressure.length() + 1);
     if (sscanf(buff, "%d,%d,%d", &sys, &dia, &p) == 3)
     {
       lcd.clear();
       lcd.print(F("sys | dia | puls"));
       lcd.setCursor(0, 1);
       lcd.print(sys);
       lcd.setCursor(7, 1);
       lcd.print(dia);
       lcd.setCursor(12, 1);
       lcd.print(p);
       delay(7500);
       read_temperature_and_oxi();
       process();
       alerting();
       delay(500);
       send_data_string = String(sys) + ',' + String(dia) + ',' + String(p) + ',' + String(cel) + ',' + String(oxy_lvl);
       Serial.println("send_data_string = " + String(send_data_string));
       send_parameters();
       delay(3000);
     }
     myserial.end();
   }
   myserial.listen();
   delay(1);
}

void read_temperature_and_oxi()
{
  float HeartRate = 3.0, SpO2 = 3.0;
  pox.update();
  HeartRate = pox.getHeartRate();
  SpO2 = pox.getSpO2();
  //oxy_lvl=SpO2;
  if(millis() - tsLastReport > REPORTING_PERIOD_MS)
  {
    Serial.print("Heart Rate: ");
    Serial.print(HeartRate);
    Serial.print("bpm / SpO2: ");
    Serial.print(SpO2);
    Serial.println(" % ");

    sensors.requestTemperatures();
    cel=sensors.getTempCByIndex(0);
    Serial.print("Temperatures: ");
    Serial.print(cel);
    Serial.println("");

    tsLastReport=millis();
  }
}

void main_display()
{
    lcd.clear();
    lcd.print(F("Temp: "));
    lcd.setCursor(6, 0);
    lcd.print(cel);
    lcd.print((char)223);
    lcd.print('C');
    lcd.setCursor(0, 1);
    lcd.print("SpO2: ");
    lcd.setCursor(6 ,1);
    lcd.print(oxy_lvl);
    delay(200);
}

void send_parameters()
{
  esp8266.listen();
  esp8266.flush();
  esp8266.print(send_data_string);
  delay(5000);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print(F("  Uploaded To "));
  lcd.setCursor(0,1);
  lcd.print(F("  Firebase  "));
  delay(200);
  esp8266.end();
}

void help_display()
{
    lcd.clear();
    lcd.print(F(" PATIENT NEEDS  "));
    lcd.setCursor(6, 1);
    lcd.print(F("HELP      "));
}

void process()
{
   if((sys > sys_u) || (dia > dia_u))
   {
       system_alert = 1;
   }
   else if((p < pulse_l ) || (p > pulse_u))
   {
       system_alert = 2;
   }
   else if((cel < temp_l ) || (cel > temp_u))
   {
       system_alert = 3;
   }
   else
   {
       system_alert = 0;
   }
   delay(200);
}

void alerting()
{
  if(system_alert==1)
   {
    lcd.clear();
    digitalWrite(buzz,HIGH);
    lcd.setCursor(0,0);
    lcd.print("Patient BP");
    lcd.setCursor(0,1);
    lcd.print("Fluctuating");
    delay(3500);
   }
   else if(system_alert==2)
   {
    lcd.clear();
    digitalWrite(buzz,HIGH);
    lcd.setCursor(0,0);
    lcd.print("Patient Pulse");
    lcd.setCursor(0,1);
    lcd.print("Fluctuating");
    delay(3500);
   }
   else if(system_alert==3)
   {
    lcd.clear();
    digitalWrite(buzz,HIGH);
    lcd.setCursor(0,0);
    lcd.print("Temperature");
    lcd.setCursor(0,1);
    lcd.print("Fluctuating");
    delay(3500);
   }
   else
   {
    Serial.print("Continue Monitoring");
    delay(3500);
   }
}

Also attaching the code I wrote for integration of the MAX30100 Oximeter and the DS18B20 Thermal Probe standalone below.
#include <Wire.h>
#include "MAX30100_PulseOximeter.h"
#include <LiquidCrystal_I2C.h>
#include <OneWire.h>
#include <DallasTemperature.h>

#define REPORTING_PERIOD_MS     1000
PulseOximeter pox;
uint32_t tsLastReport = 0;
LiquidCrystal_I2C lcd(0x27, 16, 2);

#define ONE_WIRE_BUS 5
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
float cel=0.00;

// Callback (registered below) fired when a pulse is detected
void onBeatDetected()
{
  Serial.println("Beat!");
}
void setup()
{
  Serial.begin(9600);
  Serial.print("Initializing...");
  sensors.begin();
  sensors.setWaitForConversion(false);
  // Initialize the PulseOximeter instance
  if (!pox.begin()) {
    Serial.println("MAX30100 was not found. Please check the wiring/power.");
    lcd.print("FAILED");
    for (;;);
  } else {
    Serial.println("SUCCESS");
  }
  // pox.setIRLedCurrent(MAX30100_LED_CURR_7_6MA);
  // Register a callback for the beat detection
  pox.setOnBeatDetectedCallback(onBeatDetected);
}
void loop()
{
  float HeartRate = 3.0, SpO2 = 3.0;
  pox.update();
  HeartRate = pox.getHeartRate();
  SpO2 = pox.getSpO2();
  if (millis() - tsLastReport > REPORTING_PERIOD_MS) {
    Serial.print("Heart rate:");
    Serial.print(HeartRate);
    Serial.print("bpm / SpO2:");
    Serial.print(SpO2);
    Serial.println("%");
    sensors.requestTemperatures();
    cel=sensors.getTempCByIndex(0);
    Serial.print("Temperature: ");
    Serial.print(cel);
    Serial.println("");
    tsLastReport = millis();

    lcd.clear();
    lcd.setCursor(0,0);

    lcd.print("HR:");
    lcd.print(HeartRate);
    lcd.print(" bpm");

    lcd.setCursor(0,1);

    lcd.print("SpO2:");
    lcd.print(SpO2);
    lcd.print("%");

    lcd.setCursor(11,1);
    lcd.print("T:");
    lcd.print(cel);
  }
}

The required output when I run the second code:
Heart Rate: 55.38 BPM / SpO2: 96.00%
Temperature: 25.50
Beat!
Heart Rate: 54.07 BPM / SpO2: 95.00%
Temperature: 26.51
Beat!
Heart Rate: 60.38 BPM / SpO2: 97.00%
Temperature: 27.55
Beat!

The output I get when I try to integrate all the sensors together:
Heart Rate: 0.00 BPM / SpO2: 0.00%
Temperature: 27.50
Heart Rate: 0.00 BPM / SpO2: 0.00%
Temperature: 27.30
Heart Rate: 0.00 BPM / SpO2: 0.00%
Temperature: 27.36
Heart Rate: 0.00 BPM / SpO2: 0.00%
Temperature: 28.05

The link for the BP machine: https://www.sunrom.com/566

please delete the screenshots and add the actual text instead ... format it as code ... some people here cannot view images


text:
Code uploading error on NodeMCU v3 "the selected serial port _ does not exist on your connected board"
when trying to upload code to NodeMCU v3, sometimes I get the error "the selected serial port _ does not exist on your connected board" and sometimes "timed out waiting for packet header". My attempts for this problem:

No cable is connected to any pin,
I changed the USB port,
Then I checked the components of the card, everything
seemed fine.
I checked the pin headers, there was no bridge.
Then I cleaned the whole board 4-5 times with 1-minute intervals for the
possibility of solder paste.

Still, the result did not change, what can I do in this case?
EDIT
I opened serial monitor with "74880 baud" and pushed to rst output is,
02:49:04.182 ->
02:49:04.182 ->  ets Jan  8 2013,rst cause:2, boot mode:(3,7)
02:49:04.228 ->
02:49:04.228 -> load 0x4010f000, len 3460, room 16
02:49:04.228 -> tail 4
02:49:04.228 -> chksum 0xcc
02:49:04.228 -> load 0x3fff20b8, len 40, room 4
02:49:04.228 -> tail 4
02:49:04.228 -> chksum 0xc9
02:49:04.228 -> csum 0xc9
02:49:04.228 -> v00062500
02:49:04.228 -> ~ld

On what OS are you? You might need to install the drivers for the CH340 chip, which does the USB communication.

I installed and uptaded driver for CH340

Are you pressing the "boot" button on your NodeMCU during reset, to put it into Flash mode manually before attempting to program it?

I tried that but result doesnt change


text:
Communicate with Sparkfun CAN Bus Shied
i have a Arduino Mega 2560 R3 and a Sparkfun CAN Bus Shied. Im using the SparkFun_CAN-Bus_Arduino_Library-master. I want to communicate over SPI (they have diffrent SPI pins), so i had to change it in defaults.h
Changes:
#define P_MOSI  B,2 //  new pin: 51,    orginal: #define    P_MOSI  B,3
#define P_MISO  B,3 //  new pin :50,    orginal: #define    P_MISO  B,4
#define P_SCK   B,1 //  new pin :52,    orginal: #define    P_SCK   B,5
#define MCP2515_CS B,0 // new pin:53,   orginal:  #define   MCP2515_CS B,2
i connected the pins:
Arduino Mega Pin - Sparkfun pin
51 - 11
50 - 12
52 - 13
53 - 10
also connected: 5v, gnd, rst, (pin 2)
Before i realized that spi pins are diffrent, the can init from demos dont worked.
After changes, init worked but e.g. CAN_Write_Demo i can not see the data in PCAN-View. There is nothing.
I read that PCAN-View is not compatible with my lib so i try the MCP_CAN_lib-master, same problem.
I also tried it with Vector CAN, with both libraries same problem.
Why can't I see the messages?
I also tried other demos e.g. CAN_Read_Demo and sent a can message with PCAN-View but get nothing.
When i run write demos, it dousnt even send anything and when i run read demos e.g. sending from PCAN-View, status from PCAN-View changes instant to BUSHEAVY.
Thank you for helping.

CAN will not send messages into the ether. It must have another node to acknowledge the message. That node needs to be configured for the same bit rate. I use the MCP-CAN_lib-master by Cory Fowler and it works great. You can try the following and if it does not work I would suggest you start with two UNOs and two MPC2515 and get them to work first, the send and receive code is in the examples included with the library. Be careful there are at least three different crystals on the MPC2515 boards, select the correct one. Also be sure the bus is terminated on both ends, that should simply adding a jumper to the CAN module. Hopefully the bus is several feet long, I have heard of problems with short buses although I have never experienced it. Another hint be sure the grounds for all modules are connected. I know that is not necessary but makes getting it started much easier. Also start with something in the 125/250 Kbit rate.

As i know PCAN-View should acknowledge the messages? And i also tried it with a working system where the can bus shield should just listen, but getting nothing (With the working system i see the messages with PCAN-View).

To many unknowns. Post a schematic as you have them wired and your code per forum instructions. Frizz pictures do not count and links to technical information on the hardware you are using are also needed. There are many parts with the same name but different.


text:
"Broken Pipe" when uploading to Arduino UNO
I just got my Arduino UNO and I'm trying to upload the blink example but the upload fails with
ioctl("TIOCMSET"): Broken pipe
ioctl("TIOCMSET"): Broken pipe
avrdude: stk500_recv(): programmer is not responding
ioctl("TIOCMSET"): Broken pipe

I have tried both Arduino IDE 1.0.1 (which I installed via my package manager) as well as version 1.0.5 which I downloaded from the arduino.cc website. I'm running Ubuntu Linux 12.10 if that makes a difference.
I'd appreciate any and all help in getting my arduino up and running!

Are your drivers installed correctly? Did you double check the COM port? A quick Google search didn't return any results...

I got it working by switching USB port. I didn't even realize there is a green led that's on when the arduino is connected. So yes, I'm new to this!

As with any communication error, try these:

Disconnect and reconnect the USB cable.
Use a different USB cable.
Press the reset button on the board.
Restart the Arduino IDE.
Make sure you select the right board in Tools ► Board ►, e.g. If you are using the Duemilanove 328, select that instead of Duemilanove 128. The board should say what version it is on the microchip.
Make sure you selected the right port in Tools ► Serial Port ►. One way to figure out which port it is on is by following these steps:

Disconnect the USB cable.
Go to Tools ► Serial Port ► and see which ports are listed (e.g. COM4 COM5 COM14).
Reconnect the USB cable.
Go back to Tools ► Serial Port ►, and see which port appeared that wasn't there before.

In extreme cases, you may need to burn the bootloader.

Answer adapted from here.

The first point fixed this problem for me: Disconnect & reconnect (in a different port) the USB cable.

It sounds like you have incorrect drivers or the wrong COM port (USB) selected in the IDE
Both are easy to fix. I'd imagine that it would be the COM port.

To do this:

Tools → Serial Port → [COM port... try a few different ones. Also you can use device manager to see which one disappears when you unplug your Arduino]

Few notes on photo:
#1. The selector for the COM port. Choose which one your board is on.
#2. That shows the COM port selected and board. I don't have my UNO connected: ignore that the COM port isn't showing up on the menu.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Storing integer into character buffer
I have my Arduino code as below.I am trying to send Serial request and get response for it. I can able to send request mentioned in Setup function and also able to switch cases. Problem i am facing Print character buffer after storing the  values. can someone suggest me how to store integer value into charcter buffer and print result later.
#include "glob.h"
const int BUFFER_SZ = 32;
char sendBuffer[60]={'0'};

void Take_Reading() {

  for (int row = 0; row < 8; row++)
  {
    //   // get rid of me:
    digitalWrite(SO_enable, array[row][0]);
    digitalWrite(S1_enable, array[row][1]);
    digitalWrite(S2_enable, array[row][2]);
    delay(50);
    analog_1_pv[row] = ANALOG_SCALING * analogRead(A0);
    analog_2_pv[row] = ANALOG_SCALING * analogRead(A1);
    analog_3_pv[row] = ANALOG_SCALING * analogRead(A2);
    if ( (analog_1_pv[row] <= MINV_RANGE || (analog_1_pv[row] >= MAXV_RANGE) ))
    {
      Current_Value1[row] =  0.0;
    }
    else
    {
      Current_Value1[row] =  (analog_1_pv[row] * 12.5) - 31.25;

    }

    if (  (analog_2_pv[row] <= MINV_RANGE || (analog_2_pv[row] >= MAXV_RANGE) ))
    {
      Current_Value2[row] =  0.0;
    }
    else
    {
      Current_Value2[row] =  (analog_2_pv[row] * 12.5) - 31.25;

    }

    if (  (analog_3_pv[row] <= MINV_RANGE || (analog_3_pv[row] >= MAXV_RANGE) ))
    {
      Current_Value3[row] =  0.0;
    }
    else
    {
      Current_Value3[row] =  (analog_3_pv[row] * 12.5) - 31.25;

    }

    Mod_current[row] = (uint16_t)(Mul_Factor * Current_Value1[row]);
    Mod_current[row + 8] = (uint16_t)(Mul_Factor * Current_Value2[row]);
    Mod_current[row + 16] = (uint16_t)(Mul_Factor * Current_Value3[row]);

  }

}

int ID_Check() {

  int ID_value;
  for (int row = 0; row < 8; row++)
  {
    digitalWrite(SO_enable, array[row][0]);
    digitalWrite(S1_enable, array[row][1]);
    digitalWrite(S2_enable, array[row][2]);
    Status_Out[row] = digitalRead(Output_Read);

  }

  ID_value = 1 * Status_Out[7] + 2 * Status_Out[6] + 4 * Status_Out[5] + 8 * Status_Out[4] + 16 * Status_Out[3] + 32 * Status_Out[2] + 64 * Status_Out[1] + 128 * Status_Out[0];
  return (ID_value);

}

int  Take_Temp_Reading()
{

  Temp_Total = Temp_Total - Temp_readings[Temp_index];
  Temp_readings[Temp_index] = analogRead(A5);
  Temp_Total = Temp_Total + Temp_readings[Temp_index];
  Temp_index = Temp_index + 1;

  if (Temp_index >= numReadings)
  {
    Temp_index = 0;
    Temp_Average = Temp_Total / numReadings;
  }
  temp = (Temp_Average * 5.0) / 1023.0;

  //  temp = float(analogRead(A5)) * 5.0 / 1024.0;
  temp_int = (int)(temp * 100.0);
  return (temp_int);
  // Serial.print("Temp"); Serial.println(temp);
}

int SPD_Check()
{

  SPD_STATUS = digitalRead(SPD_STATUS_PIN);
  return (SPD_STATUS);
}

int  DC_Status()
{

  DC_STATUS = digitalRead(DC_STATUS_PIN);
  return (DC_STATUS);

}

int   Take_HV_Reading()
{

  //int analog_int= analogRead(A4);

  total = total - readings[index];
  // read from the sensor:
  readings[index] = analogRead(A4);
  // add the reading to the total:
  total = total + readings[index];
  // advance to the next position in the array:
  index = index + 1;

  // if we're at the end of the array...
  if (index >= numReadings1)
  {
    index = 0;
    average = total / numReadings1;

  }
  else
  {

    HV_voltage = (average * 5.0) / 1023.0;
  }
  if (HV_voltage <= 0.25)
  {

    Conv_HV_voltage = 0.0;
  }
  else
  {
    Conv_HV_voltage = 197.837837838 * HV_voltage + 10.8108108108;
  }

  HV_Reading = (uint16_t)(Conv_HV_voltage * 10);

  //  HV_Reading = (uint16_t)(Conv_HV_voltage * 10);

  return(HV_Reading);
}

void  Serial_Command1()

{
   Take_Reading();
  int Temp_read=Take_Temp_Reading();
  int HV_Read=Take_HV_Reading();
  SPD=SPD_Check();
  DISCONNECTOR=DC_Status();
  Serial.println("Command1 executed ");

  sendBuffer[1]=char(Mod_current[1]) ;
  sendBuffer[2]= ',';
  sendBuffer[2]= Mod_current[1];
  sendBuffer[3]= ',';

  sendBuffer[4]= Mod_current[2];
  sendBuffer[5]= ',';
  sendBuffer[6]= Mod_current[3];
  sendBuffer[7]= ',';

  sendBuffer[8]= Mod_current[4];
  sendBuffer[9]= ',';
  sendBuffer[10]= Mod_current[5];
  sendBuffer[11]= ',';

  sendBuffer[12]= Mod_current[6];
  sendBuffer[13]= ',';
  sendBuffer[14]= Mod_current[7];
  sendBuffer[15]= ',';

  sendBuffer[16]= Mod_current[8];
  sendBuffer[17]= ',';
  sendBuffer[18]= Mod_current[9];
  sendBuffer[19]= ',';

  sendBuffer[20]= Mod_current[10];
  sendBuffer[21]= ',';
  sendBuffer[22]= Mod_current[11];
  sendBuffer[23]= ',';

  sendBuffer[24]= Mod_current[12];
  sendBuffer[25]= ',';
  sendBuffer[26]= Mod_current[13];
  sendBuffer[27]= ',';

  sendBuffer[28]= Mod_current[23];
  sendBuffer[29]= ',';
  sendBuffer[30]= Mod_current[22];
  sendBuffer[31]= ',';

  sendBuffer[32]= Mod_current[21];
  sendBuffer[33]= ',';
  sendBuffer[34]= Mod_current[20];
  sendBuffer[35]= ',';

  sendBuffer[36]= Mod_current[19];
  sendBuffer[37]= ',';
  sendBuffer[38]= Mod_current[18];
  sendBuffer[39]= ',';

  sendBuffer[40]= Mod_current[17];
  sendBuffer[41]= ',';
  sendBuffer[42]= Mod_current[16];
  sendBuffer[43]= ',';

  sendBuffer[44]= Mod_current[15];
  sendBuffer[45]= ',';
  sendBuffer[46]= Mod_current[14];
  sendBuffer[47]= ',';
  sendBuffer[48]= Temp_read;
  sendBuffer[49]= ',';
  sendBuffer[50]= HV_Read;
  sendBuffer[51]= ',';
  sendBuffer[52]= SPD;
  sendBuffer[53]= ',';
  sendBuffer[54]= DISCONNECTOR;

  Serial.println(sendBuffer[1]);

}

void Serial_Command2(int a)
{

  Serial.print("Command2 executed: ");
  Serial.println(a);
}

void setup()
{
  Serial.begin(57600);
  Serial.println("Format 1: <SMCB1,1>");
  Serial.println("Format 2: <SMCB1,1,Length>");

}

// Parse the request, WITHOUT the '<' and '>' delimiters.
void parseRequest(char *request)
{
  // Check the request starts with the prefix "SMCB1,1".
  if (strncmp(request, "SMCB1,1", 7) != 0) {
    Serial.println(F("Error: bad request prefix"));
    return;
  }

  // Remove that known prefix.
  // Now we have either "", ",Length" or ",Timer,On_OFF"
  request += 7;

  // Format 1: ""
  if (request[0] == '\0') {
    //Serial.println(F("Received format 1"));
    Serial_Command1();
    return;
  }

  // Remove the leading comma.
  // Now we have either "Length" or "Timer,On_OFF"
  if (request[0] != ',') {
    Serial.println(F("Error: ',' expected"));
    return;
  }
  request++;

  // Format 2: "Length", no comma.
  char * comma = strchr(request, ',');
  if (!comma) {

    int length = atoi(request);
    Serial_Command2(length);
    //Serial.print(F("Received format 2, length = "));
    // Serial.println(length);
    return;
  }

}

void loop()
{
  static char buffer[BUFFER_SZ];  // received chars
  static size_t pos;              // current position in buffer
  static bool insideRequest;      // are we between '<' and '>'?

  if (Serial.available()) {
    char c = Serial.read();
    if (insideRequest) {
      if (c == '>') {  // end of request received
        buffer[pos] = '\0';  // terminate the string
        parseRequest(buffer);
        pos = 0;             // get ready for the next request
        insideRequest = false;
      }
      else if (pos < BUFFER_SZ-1) {  // add char to buffer
        buffer[pos++] = c;
      }
    }
    else if (c == '<') {  // start of request
      insideRequest = true;
    }
  }
}

Golb.h header file contains
#ifndef GLOB_H
#define GLOB_H
int counter=0;
int Mod_current[24];
const int numReadings = 10;
const int numReadings1 = 10;
int Temp_Total = 0;
int Temp_readings[numReadings];
int Temp_index = 0;
int Temp_Average = 0;
float  reading[10];
float Total = 0.0;
static int i;

int readings[numReadings];
int index = 0;
int total = 0;
int average = 0;

// These PinS are use to enable and disable analog MUX
int SO_enable = 5;
int S1_enable = 4;
int S2_enable = 3;

// temprature sensor permeter
int TempPin = 5;
float temp;
static int temp_int;

// digital mux setting
int Output_Read = 2;

float Vref = 2.5;
// Used for sensor conversion
float ANALOG_SCALING = 0.004887585532746823;
//tempfloat ANALOG_SCALING=0.0049560117;

int Sensor_Value0 = 0;
int Sensor_Value1 = 0;
int Sensor_Value2 = 0;
float analog_1_pv[8];
float analog_2_pv[8];
float analog_3_pv[8];
int Status_Out[8];

//SPD & DC STATUS PIN
static int SPD_STATUS_PIN = 6;
static int DC_STATUS_PIN = 7;

int row;

int Mul_Factor = 10;

float Current_Value1[8] = {
  0.0
};
float Current_Value2[8] = {
  0.0
};
float Current_Value3[8] = {
  0.0
};

//HV perameter setting are defined here
int HV_SensorValue;
int HV_Reading;
float HV_voltage;
float Conv_HV_voltage;
unsigned  int DC_STATUS = 0;
unsigned int SPD_STATUS = 0;
float MINV_RANGE = 2.52;
//float MIDV_RANGE1=1.875;
float MAXV_RANGE = 4.5;

int SPD;
int DISCONNECTOR;

int Serial_Status=0;

int array[8][3] = {
  {
    0, 0, 0
  }
  , {
    0, 0, 1
  }
  , {
    0, 1, 0
  }
  , {
    0, 1, 1
  }
  , {
    1, 0, 0
  }
  , {
    1, 0, 1
  }
  , {
    1, 1, 0
  }
  , {
    1, 1, 1
  }
};

#endif

The simple answer is: don't.
At the moment you are trying to assign integers to chars, and that just won't fit. It's like a round peg in a square hole. Or more like trying to force a bowling pin through a hose pipe. It just isn't going to fit.
So you either need to "print" the values into your final string (say with sprintf()) or just don't build up a string at all and print the values directly. And while you're at it, use some loops to make your code simpler:
for (int i = 0; i < 14; i++) {
    Serial.print(Mod_current[i]);
    Serial.print(",");
}

for (int i = 23; i > 13; i--) {
    Serial.print(Mod_current[i]);
    Serial.print(",");
}

Serial.print(Temp_read);
Serial.print(",");
Serial.print(HV_Read);
Serial.print(",");
Serial.print(SPD);
Serial.print(",");
Serial.println(DISCONNECTOR);

If you really need to create a string the easiest way is probably with sprintf (or snprintf to prevent buffer overflows):
char sendBuffer[200]; // Enough room for 28 integers of 1-5 characters, plus commas.

snprintf(sendBuffer, 200, "%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
    Mod_current[0], Mod_current[1], Mod_current[2], Mod_current[3],
    Mod_current[4], Mod_current[5], Mod_current[6], Mod_current[7],
    Mod_current[8], Mod_current[9], Mod_current[10], Mod_current[11],
    Mod_current[12], Mod_current[13], Mod_current[14], Mod_current[23],
    Mod_current[22], Mod_current[21], Mod_current[20], Mod_current[19],
    Mod_current[18], Mod_current[17], Mod_current[16], Mod_current[15],
    Mod_current[14], Temp_read, HV_Read, SPD, DISCONNECTOR);

int len = strlen(sendBuffer);
Serial.println(sendBuffer);
Serial.print(len);
Serial.println(" bytes");

(note: I think I got the right number of parameters there)

Yes i know that. For my second case , I would like to print Serial statement based on length. It wont work above case. How can i print of specified length.thats reason i tried with String intially but memory is exceeding and controller gets restarts frequently

In that case you will need to use something like sprintf to print your values into the string. I will add an example.

@ in second command i am mentioning length of buffer . I am passing length int as argument So i can print Specified length of character

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Modbus RTU over TCPip
I have developed my arduino code using below library. I tested code working fine over modbus RTU slave. Now i am planning to use RS485 to wifi instead of wire connection. In order to get data over web apllication i need to add another layer of modbus TCP-IP. can some one suggest me is it possible to without changing any hardware add library function which can acts like MODBUS RtU over TCP-IP protocol.
if any library avilable please share it
I am using WIFI device like below.
rs485 to wifi
MODBUS RTU

Modbus TCP simply put is a Modbus packet wrapped in a TCP packet.
There is no 'additional layer of Modbus' added on top. If we look at the osi model pictured below you can see there is only one Modbus application layer (i.e modbus slave/server)

Essentially if the wifi->RS485 gateway strips the payload from the TCP packets and simply spits it out the serial side then no modifications are necessary (apart from the obvious RS485 transceiver you will need to interface the arduino with the gateway).
What you will need to make sure is that the gateway will only send packets directed to port 502 to the arduino (502 is the Modbus TCP port) as it is possible other IP traffic could cause some drama for the modbus slave.
Additionally, you will have to ensure that you set the slave ID of the arduino to be what is specified by the master. Are you also building the Modbus TCP client? If not it is very possible that the required slave ID is 255 which is not supported by the modbus library you have linked.
Modbus (serial) slave IDs can only be between 1 and 247 for traditional reasons when Modbus was first standardised as it was only envisioned to be on serial, however when Modbus TCP was introduced an additional addressing layer (TCP / IP) meant that the unit ID (slave ID when using Modbus TCP) could be anything from 0 - 255. It is common for some vendors (at least in industrial automation) to use a unit ID of 255 for standard Modbus transactions scanning IO and diagnostic or configuration transactions to be send to other unit IDs (essentially making the TCP server a modbus router, forwarding packets to one of the multiple Modbus servers running on that single slave device)

I am not having plan to develop any modbus TCP ip protocol or make any hardware changes. I would like to know with existing library how can i convert the modbus packets into tcp-ip packets to make work as modbus RTU over TCP IP. There is library for modbus TCPIP can use to implement my code

A mentioned in my post whether or not the mobus library you linked will work depends on the master/client and what unit id it will be polling. Do you what this will be? What is the master/client? Do you have any control over it?

the device going to be client.Scada system acts like Master. Intially we used wired connections and now we wanted to go with wireless without changing hardware. By USR model , USR-630 we can config either server or client.we just passing data like modbus packets. I found its working fine with modbus packets. We expected to wifi device convert modbus packets into TCP-IP packets. Since it not doing it , how we can convert into TCP-ip packets

I suspect you mean the arduino device is going to be server/slave? If you want to change from wired to wireless you must change hardware , seeing how that is what you want to do. As I have said before you need to make sure the client I.e your scada can use a unit id in the Renee of 1-247. What is a USR630? What do you mean exactly by "we expected wifi device to convert modbus packets into tcp ip packets" this does not describe your problem at all.

I am using connection from A and B connection from Existing arduino Slave device and connected to rs485 to wifi.  we can config device ID up to 248 device. with device i could able to communicate like wired connection but i could not able to connection in scada over web app. our scada engineer asking  to give protocol that convert MODBUS packets into TCP-IP packets. Thats reason i am looking for expert suggestions here


text:
IOt application example Error
I have downloaded code from below linkLink of code. I am trying test code from below. I am getting warning for below code.I couldnot able to find how to sort out
#include <SPI.h>
#include <Ethernet.h>
#include <PubSubClient.h>

/* ------------------ */
/* SKETCH CREDENTIALS */
/* ------------------ */

const char *deviceId     = "<D56debb6351d9d4e74e000015>";             // * set your device id (will be the MQTT client username)
const char *deviceSecret = "<Y4h+R1NRAxrhFciRhtHLj66ERSv8RExu>";         // * set your device secret (will be the MQTT client password)
const char *outTopic     = "devices/<D56debb6351d9d4e74e000015>/set"; // * MQTT channel where physical updates are published
const char *inTopic      = "devices/<D56debb6351d9d4e74e000015>/get"; // * MQTT channel where lelylan updates are received
const char *clientId     = "<CLIENT-ID>";             // * set a random string (max 23 chars, will be the MQTT client id)

/* ------------ */
/* SKETCH LOGIC */
/* ------------ */

/* Server settings */
byte server[] = { 178, 62, 108, 47 }; // MQTT server address

/* Sample payload published to lelylan */
/* The id is the status property id of the basic light /*
  /* http://lelylan.github.io/types-dashboard-ng/#/types/518be107ef539711af000001/ */
const char *payloadOn  = "{\"properties\":[{\"id\":\"56debb6351d9d4e74e000015\",\"value\":\"on\"}]}";
const char *payloadOff = "{\"properties\":[{\"id\":\"56debb6351d9d4e74e000015\",\"value\":\"off\"}]}";

/* Ethernet configuration */
byte mac[] = { 0xA0, 0xA0, 0xBA, 0xAC, 0xAE, 0x12 };
EthernetClient ethClient;

/* MQTT communication */
void callback(char* topic, byte* payload, unsigned int length); // subscription callback
PubSubClient client(server, 1883, callback, ethClient);         // mqtt client

/* Pins configuration */
int inPin = 2; // button
int outPin = 4; // led

/* Button and led logics */
int state = HIGH;     // current state of the output pin
int reading;          // current reading from the input pin
int previous = LOW;   // previous reading from the input pin
long time = 0;        // the last time the output pin was toggled
long debounce = 200;  // the debounce time, increase if the output flickers

/* arduino setup */
void setup() {
  Serial.begin(9600);
  delay(500);

  Ethernet.begin(mac);
  Serial.print("Connected with IP: ");
  Serial.println(Ethernet.localIP());

  lelylanConnection();      // MQTT server connection
  pinMode(inPin, INPUT);    // button pin setup
  pinMode(outPin, OUTPUT);  // led pin setup
}

/* arduino loop */
void loop() {
  lelylanConnection();

  const char *value;
  reading = digitalRead(inPin);  // read the button state

  // if the input just went from LOW and HIGH and we've waited long enough to ignore
  // any noise on the circuit, toggle the output pin and remember the time
  if (reading == HIGH && previous == LOW && millis() - time > debounce) {
    if (state == LOW) {
      Serial.println("[PHYSICAL] Led turned on");
      lelylanPublish("on");
      state = HIGH;
    } else {
      Serial.println("[PHYSICAL] Led turned off");
      lelylanPublish("off");
      state = LOW;
    }

    time = millis();
  }

  // effectively update the light status
  digitalWrite(outPin, state);
  previous = reading;
}

/* MQTT server connection */
void lelylanConnection() {
  // add reconnection logics
  if (!client.connected()) {
    // connection to MQTT server
    if (client.connect(clientId, deviceId, deviceSecret)) {
      Serial.println("[PHYSICAL] Successfully connected with MQTT");
      lelylanSubscribe(); // topic subscription
    }
  }
  client.loop();
}

/* MQTT publish */
void lelylanPublish(char *value) {
  if (value == "on")
    client.publish(outTopic, payloadOn); // light on
  else
    client.publish(outTopic, payloadOff); // light off
}

/* MQTT subscribe */
void lelylanSubscribe() {
  client.subscribe(inTopic);
}

/* Receive Lelylan message and confirm the physical change */
void callback(char* topic, byte* payload, unsigned int length) {
  // copu the payload content into a char*
  const char *json;
  json = (char *) malloc(length + 1);
  memcpy(json, payload, length);
  json[length] = "\0";

  // update the physical status and confirm the executed update
  if (String(payloadOn) == String(json)) {
    Serial.println("[LELYLAN] Led turned on");
    lelylanPublish("on");
    state = HIGH;
  } else {
    Serial.println("[LELYLAN] Led turned off");
    lelylanPublish("off");
    state = LOW;
  }

  digitalWrite(outPin, state);
  free(json);
}

Arduino: 1.6.6 (Windows 8.1), Board: "Arduino/Genuino Uno"
C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino: In function 'void
  loop()':
C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:77:26: warning:
  deprecated conversion from string constant to 'char*'
  [-Wwrite-strings]
   lelylanPublish("on");

                      ^

C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:81:27: warning:
  deprecated conversion from string constant to 'char*'
  [-Wwrite-strings]
   lelylanPublish("off");

                       ^

C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino: In function 'void
  callback(char*, byte*, unsigned int)':
IOT_Testcode:124: error: invalid conversion from 'const void*' to
  'void*' [-fpermissive]
memcpy(json, payload, length);
                           ^

In file included from C:\Program Files
  (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:25:0,
             from sketch\IOT_Testcode.ino.cpp:1:

c:\program files
  (x86)\arduino\hardware\tools\avr\avr\include\string.h:117:14: error:
  initializing argument 1 of 'void* memcpy(void*, const void*, size_t)'
  [-fpermissive]
extern void *memcpy(void *, const void *, size_t);
          ^

IOT_Testcode:125: error: assignment of read-only location '*(json +
  ((sizetype)length))'
json[length] = "\0";
            ^

IOT_Testcode:125: error: invalid conversion from 'const char*' to
  'char' [-fpermissive]
C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:130:24: warning:
  deprecated conversion from string constant to 'char*'
  [-Wwrite-strings]
 lelylanPublish("on");

                    ^

C:\Users\Ajit\Desktop\IOT_Testcode\IOT_Testcode.ino:134:25: warning:
  deprecated conversion from string constant to 'char*'
  [-Wwrite-strings]
 lelylanPublish("off");

                     ^

IOT_Testcode:139: error: invalid conversion from 'const void*' to
  'void*' [-fpermissive]
free(json);
        ^

In file included from C:\Program Files
  (x86)\Arduino\hardware\arduino\avr\cores\arduino/Arduino.h:23:0,
             from sketch\IOT_Testcode.ino.cpp:1:

c:\program files
  (x86)\arduino\hardware\tools\avr\avr\include\stdlib.h:305:13: error:
  initializing argument 1 of 'void free(void*)' [-fpermissive]
extern void free(void *__ptr);
         ^

exit status 1 invalid conversion from 'const void*' to 'void*'
  [-fpermissive]
This report would have more information with   "Show verbose output
  during compilation"   enabled in File > Preferences.

Kindly let me know how to resolve these warning

Most of those warnings are caused by the author not having a clue what they are doing. That code is so badly written and broken that you should just throw it away and start from scratch. I can't even begin to list the problems with it here.

This code was written and tested using an earlier Arduino IDE version, the author's upload of the source files happened over a year ago.
Within the Arduino 1.6.x branch the preprocessor and compiler behaviour have changed (among other things).
Older libraries will require an earlier Arduino IDE version (i.e. the 1.5.x branch) from https://www.arduino.cc/en/Main/OldSoftwareReleases#previous.
Additionally, we have to keep in mind that there are differences between Arduino.cc and Arduino.org. Those two projects split apart, their IDEs aren't equivalent any more.


text:
Garbage value Serial Monitor
I am building my own arduino.Here is my code Below. I found code working for Digital Ios like blink example ; analog reading, Problem i am facing in Serial Monitor.Whenever i open Serial monitor i get trash values.I have choose proper crystal & proper values.  Please let me know possibility for getting trash values
int led = 2;

// the setup routine runs once when you press reset:
void setup() {
  // initialize the digital pin as an output.
  pinMode(led, OUTPUT);
Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  Serial.println("Welcome:");
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(100);               // wait for a second
}

One of my projects does this too. I leave it connected to a USB port for power so it can control a room fan. Every 4 seconds it writes a line of data to the serial output. When I open a serial terminal on the computer, I immediately see a short stream of garbage, followed by the next, and all subsequent log outputs, properly displayed. It looks as if the serial-to-USB chip has some data buffered in it which it delivers, but out of sync, as soon as the terminal connection is made, but this is just a guess.
Have you tried resetting your chip while the terminal is connected? When I do this, there are no sync issues and the displayed data is all valid.
Update:
If you only ever get garbage from your terminal, then it's likely the terminal and the Arduino aren't matched for one or both of baud-rate or frame-size.
Arduino serial hardware uses an 8N1 frame: 8 data bits, No parity bit, 1 stop bit. Your serial monitor must be set to match this (and it probably is, since this is the most common convention, but worth checking.
Second, the baud rates must match. You've set the Arduino for 9600 baud and your serial monitor program must be also (from your screenshot, it looks like it is).
You said you are using a crystal so it quite unlikely that Arduino's 9600 baud is inaccurate, but this could happen if you were using its internal clock source.
Finally, in the lower left corner of your serial monitor screen shot, it looks like you have selected "No line endings". Serial.println() ends every line with CR/LF. See if that is an available line-ending setting. It is sometimes named "OD OA" (the hex values for Carriage-Return and Line-Feed). Try that setting if it is available.
The serial protocol is one of the oldest communication protocols but it has many variations. (Did someone say "standard"? :-)  Everyone gets bitten by it, eventually.

I have done these many time. Previous board working fine. I have changed The IC also; Even i tried reset while Upload. But still Gives above issue. COde seems working fine only problem i am facing Serial Monitor.

Opening a Serial connection will reset your arduino and restart the whole program.
I learned this the hard way when coding a windows serial com-monitor for triggering systemcalls from arduino


text:
Is there any standard for colors of Serial Peripheral Interface wires?
Having DuPont cables like on the picture...

... and the RFID RC522 reader with colored wires as found in one of the tutorials.

I know that copper is the same inside of the wires. Anyway, is there any standard or de-facto standard of assigning colors to the meaning of the pins? Black for ground and red for +voltage are known from elsewhere. But what about all the other pins? Here is the detail view for better readability:

Nope, there isn't., except for black for GND and red for Vcc, but even these are just conventions.

btw: do you wire this for SPI or for I2C? for SPI don't wire SDA and for I2C don't wire MISO and MOSI.

@Juraj I2C. The SPI was just example. The question was meant to be more general.

No, there is no standard. However:

Red is often +5V
Black is often GND
I often assign colours numerically according to the resistor colour code:

0 - Black
1 - Brown
2 - Red
3 - Orange
4 - Yellow
5 - Green
6 - Blue
7 - Purple
8 - Grey
9 - White

You may have noticed that that's the same order they appear in the cable too, which is helpful. It's handy when working with things like 8 bit data buses, since you can then easily identify which wire is which.
In some disciplines there are standards, like for audio red is right and left is white (that's the little rhyme I use to remember), and of course there's regulations defining colours for mains cables, but for this kind of thing just use whatever makes sense to you.

Thanks for sharing your experience.


text:
My Atlas Scientific sensors measurement give zero values at first reading
I am still continuing my hydroponic nutrient monitoring project. In short, I made a hydroponic nutrient monitoring system with I2C connection, and decided to do serial communication with Raspberry Pi 3B+ to save sensor reading data in CSV file. I am curious about why after uploading the sketch, the sensors always gives zero values at first reading on Serial Monitor.
This is the screenshot of my Serial Monitor.

From left to right: timestamp, EC, pH, Temperature.
Everytime I reset the Arduino, the Serial Monitor first will show no values. On the second line, it shows only EC value. The third line only EC and pH value, then the fourth line and so on will show all values.
How to make the Arduino show all sensor values from the start in the Serial Monitor?
Here is my code that I modified from Atlas Scientific page for my project:
#include <Ezo_i2c.h>
#include <Wire.h>

Ezo_board ec = Ezo_board(100, "EC");
Ezo_board ph = Ezo_board(99, "PH");
Ezo_board temp = Ezo_board(102, "RTD");

bool reading_request_phase = true;

uint32_t next_poll_time = 0;
const unsigned int response_delay = 1000;

void setup()
{
  Serial.begin(9600);
  Wire.begin();
  delay(1000);

}

void loop() {
  if (reading_request_phase)
  {
    ec.send_read_cmd();
    ph.send_read_cmd();
    temp.send_read_cmd();

    next_poll_time = millis() + response_delay;
    reading_request_phase = false;
  }
  else
  {
    if (millis() >= next_poll_time)
    {
      receive_reading(ec);
      receive_reading(ph);
      receive_reading(temp);

      reading_request_phase = true;
    }
  }
}

void receive_reading(Ezo_board &Sensor) {
  Sensor.receive_read_cmd();
  Serial.println();
  Serial.print(ec.get_last_received_reading()/1000);
  Serial.print(",");
  Serial.print(ph.get_last_received_reading());
  Serial.print(",");
  Serial.print(temp.get_last_received_reading());
  Serial.print("");
  delay(1000);
}

Each time you call receive_reading() you pass it one sensor to read the value from. But each time you call receive_reading() you print out all three sensors.
So you:

Read EC and print EC PC TEMP
Read PC and print EC PC TEMP
Read TEMP and print EC PC TEMP

In step one you only have EC, you haven't read PC or TEMP yet.
In step two you have the old reading of EC and a new PC reading but still no TEMP reading.
By step three you finally have a TEMP reading but still the old EC and PC readings from earlier.
You should instead put the receiving command (Sensor.receive_read_cmd()) once for each sensor as a separate thing to displaying the received values. More like:
#include <Ezo_i2c.h>
#include <Wire.h>

Ezo_board ec = Ezo_board(100, "EC");
Ezo_board ph = Ezo_board(99, "PH");
Ezo_board temp = Ezo_board(102, "RTD");

bool reading_request_phase = true;

uint32_t next_poll_time = 0;
const unsigned int response_delay = 1000;

void setup()
{
  Serial.begin(9600);
  Wire.begin();
  delay(1000);

}

void loop() {
  if (reading_request_phase)
  {
    ec.send_read_cmd();
    ph.send_read_cmd();
    temp.send_read_cmd();

    next_poll_time = millis() + response_delay;
    reading_request_phase = false;
  }
  else
  {
    if (millis() >= next_poll_time)
    {
      ec.receive_read_cmd();
      ph.receive_read_cmd();
      temp.receive_read_cmd();
      display_reading();

      reading_request_phase = true;
    }
  }
}

void display_reading() {
  Serial.print(ec.get_last_received_reading()/1000);
  Serial.print(",");
  Serial.print(ph.get_last_received_reading());
  Serial.print(",");
  Serial.println(temp.get_last_received_reading());
}

Also remove the delay() after each printed line, it's just confusing everything and slowing down your reading.

I think there are too much colons on the receive_read_cmd() like. Otherwise good answer

@chrisl copy-pasta ;)


text:
Make two LEDs fade in and out with with different PWM values
I have two UV leds, one Vf 3.3V @ 150 mA and the second one Vf 5V @ 150 mA. I need a circuit to make them fade in and out alternatively, i.e., as one goes dimmer the other goes brighter and vice versa. I tried an Arduino PWM transistor approach with the Attiny85 board and the code below and it works, but I need the ledPin2 led to work with at a lower maxbrightness. How can I modify the code so that I can set the maxbrightness for ledPin2 to be around 25, while the maxbrightness for ledPin1 remains 255 and yet both take the same time to fade in and out?
int ledPin1 = 0;
int ledPin2 = 4;
int minbrightness = 0;
int maxbrightness = 255;
int fadeAmount = 1;
int tim=4;

void setup()  {
   pinMode(ledPin1, OUTPUT);
   pinMode(ledPin2, OUTPUT);
}

void loop()  {
  analogWrite(ledPin1, minbrightness);
  analogWrite(ledPin2, maxbrightness);
  minbrightness = minbrightness + fadeAmount;
  maxbrightness = maxbrightness - fadeAmount;
  if (minbrightness == 0 || minbrightness == 255 ){
    fadeAmount = -fadeAmount ;
  }
  delay(tim);
}

Why not make the change in hardware? Much simpler and no need to change any code. If you really don't want to, why not simply try putting maxbrightness/10 into the analog write for the second LED? You might have to change the variable to a float to do it in the approximately similar time (otherwise you'll only really change a value for the brightness of the second one approximately every 5 counts).

I'd like a code solution so it's easier to use it in another configurations. Also, if I just divide maxbrightness by 10, I am afraid the leds might get out of synch after some cycles.

I don't think you have much choice than to come up with a sort of a counter and instead of having a single variable for the brightness of all the LEDs, you'll have to maintain a separate brightness variable for each channel which will have its own unique dimming profile. You'll then have to empirically determine how many counts it'll take for you to decrease/increase the PWM duty cycle on each separate channel (since perceived brightness isn't linear).
Something like this? The brightness of 32 and a modulo 8 was chosen to be a factor of 256, so it's more or less synced.
int ledPin1 = 0;
int ledPin2 = 4;
int brightnessLP1 = 0;  //begin with the LED off
int brightnessLP2 = 32; //begin with the LED on
int fadeAmount = 1;
int tim=4;

void setup()  {
   pinMode(ledPin1, OUTPUT);
   pinMode(ledPin2, OUTPUT);
}

void loop()  {
  //counter value accommodates the modulo below
  for(int brightnessCounter = 1; brightnessCounter < 257; brightnessCounter++) {

     analogWrite(ledPin1, brightnessLP1);
     analogWrite(ledPin2, brightnessLP2);
     brightnessLP1 = brightnessLP1 + fadeAmount;
     if(brightnessCounter  % 8) {
       brightnessLP2 = brightnessLP2 - fadeAmount;
     }
     delay(tim);
  }
  fadeAmount = -fadeAmount;
}

I'm sure you could make it cleaner or link the brightness values to the counter, but I'll leave that to you.

Thank you. I can work from there.

Of course, you're welcome!


text:
What is the best way to measure PWM signals ( pulseIn ) with the Arduino via a Raspberry Pi?
I connected my Arduino Uno to my raspberry via USB serial. I'm able to read out both digital and analog pins of my Arduino using the Python nanpy library (v.0.8).
However, I can't find support for the pulseIn() function. It seems nanpy doesn't support pulseIn() at all.
What is the best way to measure PWM signals with the Arduino and forward the results to the Raspberry Pi?
I am able to measure PWM using the Arduino GUI, however I would to take PWM samples at fixed time intervals over a long period of time and combine this data with other measurements that my Raspberry is making.I also tried pyFirmata, but it doesn't support pulseIn() measurements either.

It seems like this could be a fairly trivial addition, if you can find the source code for both the Arduino and host portions, and successfully build and use new versions.  Often it's useful to try to create and test a from scratch build before you try to modify it.  But it may also be possible you run into more complicated interactions, for example if the usual pulse timing mechanism delays expected traffic.

You can just have a sketch in the arduino that takes the measurements at whatever interval you want using the analogRead(pin) function and then forward those results to the raspberry pi via serial using Serial.print(whatever you want here). If you don't know how to use serial with arduino just go to their site, they have very good documentation.
Hope that helps :)

Nanpy seems to have a CounterClass that does frequency measurements.
Or do you want to measure the PWM duty-cycle?

I would like to measure the downratio. Preferably I would use pulseIn to measure one uptime pulse and one downtime pulse. From this I can calculate the desired downratio.


text:
How do I transfer more than 1 byte at once via SPI bus?
I have an AD5685R DAC that I am trying to communicate with over SPI. Per the datasheet,

...These [24] bits are transferred to the input register on the 24 falling edges of SCLK and are updated on the rising edge of /SYNC

where /SYNC is used as chip-select.
I believe Arduino's SPI.transfer waits to receive 8 bits after sending 8 bits. But for this particular DAC, I need to send 24 straight bits on 24 clock edges before releasing the chip-select. Is this possible?

I believe Arduino's SPI.transfer waits to receive 8 bits after sending 8 bits.

Incorrect. With SPI, a byte is clocked in at the same time as a byte is clocked out. It may be that this byte is simply a dummy byte though, if the slave has nothing to say.
So for 24 bits, simply clock out 3 bytes without deasserting the select. Since SPI is a synchronous protocol there should be no issue with having a delay in between bytes provided the select is maintained.

In the SPI protocol, you get one byte back for every one you send.  If you are not interested in the response from a device, you can just ignore the return bytes.
SPI has no handshaking.  You just must send no faster than the slave device can handle.  In the case of the AD5685R, that is 50 MHz.
For multibyte transfer, you keep the chip select asserted (low) between every byte by setting the transferMode to SPI_CONTINUE in the SPI.transfer call.  For the last byte, you will deassert the chip select (set it high) by setting the transferMode parameter to SPI_LAST in the SPI.transfer call..

Unless you have one of those weird SPI devices with a positive select.

Note that there is also a version of SPI.transfer for multi-byte (buffer) transfers:
SPI.transfer(buffer, size)

I used the buffer transfer in my library for the TLC59711 (see code) and found the buffer transfer faster than transferring bytes individually using SPI.transfer(val); the switch to buffer transfers is one of the reasons my library is about 3.5 times faster than a previous library for the TLC59711.

This is relatively new, works in Arduino 1.8, not sure about 1.0.


text:
Why is the output on the MOSI line shifted 1 bit over from what I commanded?
I've been trying to work with an AD5685R DAC. Per that datasheet, to get DAC1 to output max voltage (5V), I would perform:
SPI.begin();
SPI.setBitOrder(MSBFIRST);
SPI.setDataMode(SPI_MODE3); // DAC uses CPHA=1, CPOL=1

digitalWrite(CS, LOW);
SPI.transfer(0x31); // upper nibble sends a "write and update" command, lower nibble says "DAC1"
SPI.transfer(0xFF);
SPI.transfer(0xFC); // 14-bit DAC, last 2 bits are dontcares, make them 0
digitalWrite(CS, HIGH);

Replace 0xFFFC with 0x0000 to get 0 volts out.
Sending this command as written somehow writes to DAC4 instead of DAC1! and while 5V will come out when I write 0xFFFC, I get to 2.5V when writing 0x0000 instead of 0V.
If I command this with a Bus Pirate and directly write the bytes out, it works exactly as desired.
I used the Bus Pirate to sniff the SPI traffic and it turns out I'm not getting what I've commanded. Rather than 0x31 0x00 0x00 for instance, I get 0x18 0x80 0x00.
If we break this out into bits:
0x310000: 0011 0001 0000 0000 0000 0000 // commanded
0x188000: 0001 1000 1000 0000 0000 0000 // actually sent

So the command actually sent out is shifted by 1 bit!
Here's the bit pattern for 16383 counts (i.e., 2^14-1):
0x31FFFC: 0011 0001 1111 1111 1111 1100 // commanded
0x18FFFE: 0001 1000 1111 1111 1111 1110 // actually sent

The opcode corresponding to 0x18 is "write to input register 4" (the output occurs because I've pulled the /LDAC pin permanently low, see the datasheet), which explains why I'm getting an output on DAC4 instead of DAC1.
This occurs with both a Sparkfun Pro Micro and an Arduino Mega 2560.
What is going on here? Why is the Arduino not sending out what I've actually commanded? Again, writing the hex codes directly to the DAC using a Bus Pirate works perfectly.

Because something is using the wrong SPI mode.

@IgnacioVazquez-Abrams this is correct, SPI mode should have been SPI_MODE2. Arduino's SPI page doesn't make clear what CPHA=0 vs CPHA=1 is (rising vs falling edge active). But maybe I'm just having a hard time comprehending words... Or, the comments on the AD5685R's sample code is incorrect.

CPOL is clock polarity, and CPHA is clock phase.
The SPI modes are:

Mode 0 (the default) - clock is normally low (CPOL = 0), and the data is sampled on the transition from low to high (leading edge) (CPHA = 0)

Mode 1 - clock is normally low (CPOL = 0), and the data is sampled on the transition from high to low (trailing edge) (CPHA = 1)

Mode 2 - clock is normally high (CPOL = 1), and the data is sampled on the transition from high to low (leading edge) (CPHA = 0)

Mode 3 - clock is normally high (CPOL = 1), and the data is sampled on the transition from low to high (trailing edge) (CPHA = 1)

According to your datasheet:

Data from the SDIN line is clocked into the 24-bit input shift register on the falling edge of SCLK.

Judging by the diagrams on the datasheet, Mode 1 is what you want. You want the trailing edge of high to low.
More information at SPI - Serial Peripheral Interface - for Arduino