body:
I have been working on an Arduino project that has me kind of stumped. What it needs to achieve is that two momentary safety switches need to be pushed and held within a specified time frame as defined by "PushTimeWindow" then continue to be held as a relay is engaged for the period of time as defined by "RelayOnTime" and at any point if either or both of the momentary switches are released the relay needs to turn off immediately. The number of successful pressed is then displayed on an LCD screen. I have most of that portion of the code working OK so far. It seems to do what I want it to do even if the code could be much more efficient.

I need to figure out a way to ensure the buttons are released first before another successful two hand press can be registered and another cycle initiated and they can't simply be held as the cycles continue. I have been trying to figure out how to place "state change" logic into the code but can't figure out where or how to include it properly. I created a variable called "LastButtonSafeChecked" and one called "ButtonSafeChecked" to act as a comparison but I can't get it to work properly. Where can I include that logic and is a state change the correct way to go about it in this case?
Any suggestions on improving the code and implementing the missing logic are greatly appreciated as I think it is outside the scope of my coding knowledge. I included a lot of serial print lines in order to try and debug what events were happening. Here is the code:

    /*
    Designed to detect two button presses within specific time gap
    Then turn on a relay for a specified time
    Then turn it off and look for another press
      */
    // include the library code:
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

    // this constant won't change:
     const int  ButtonPin1 = 2;   // the pin that pushbutton 1 is attached to
     const int  ButtonPin2 = 3;   // the pin that pushbutton 2 is attached to
     const int  RelayPin = 5;     // the pin that the Relay is attached to

    // Variables will change:
    int ButtonPushCounter = 0;    // counter for the number of button presses
    int ButtonState1 = 0;         // current state of the button1
    int ButtonState2 = 0;         // current state of button2
    int LastRelayState = 0;     // previous state of relay
    int ButtonSafeOn1 = 0;        // button1 time check passed
    int ButtonSafeOn2 = 0;        // button2 time check passed
    int ButtonSafeChecked = 0;     // Button Check passed flag
    int LastButtonSafeChecked = 0;  // Last State of button check
    int RelayOn = 0;            // toggles relay on off state
    unsigned long RelayMillis = 0;  //on time check for relay
    unsigned long Button1Millis = 0;  //on time check for Button1
    unsigned long Button2Millis = 0;  //on time check for Button2
    const long RelayOnTime = 1000; //Length of time for relay
    const long PushTimeWindow = 1000; //Length of time to allow two pushes

    void setup() {
      // set up the LCD's number of columns and rows:
      lcd.begin(16, 2);
      // Print a message to the LCD.
      lcd.print("Press Count");
       // initialize the button pins as a inputs:
       pinMode(ButtonPin1, INPUT);
       pinMode(ButtonPin2, INPUT);
       // initialize the Relay Pin as an output:
       pinMode(RelayPin, OUTPUT);
       // initialize serial communication:
       digitalWrite(RelayPin, LOW);
       Serial.begin(9600);
    }

    void loop() {
    unsigned long currentMillis = millis();
       // read the pushbutton input pins:
       ButtonState1 = digitalRead(ButtonPin1);
       ButtonState2 = digitalRead(ButtonPin2);
    //check if Button1 is HIGH
        if (ButtonState1 == HIGH) {
            Button1Millis = currentMillis;
            Serial.println("Button1");
         }
    //check if Button2 is HIGH
        if (ButtonState2 == HIGH) {
            Button2Millis = currentMillis;
            Serial.println("Button2");
          }
    //let program know Button1 is within window
       if (ButtonState1 == HIGH) {
          if (currentMillis - Button1Millis < PushTimeWindow){
            ButtonSafeOn1 = 1;
        } else {
            ButtonSafeOn1 = 0;
        }
       }
    //let program know Button2 is within window
       if (ButtonState2 == HIGH) {
          if (currentMillis - Button2Millis < PushTimeWindow){
            ButtonSafeOn2 = 1;
        } else {
            ButtonSafeOn1 = 0;
        }
       }
    //Double Check both buttons are still pushed
       if (ButtonState1 == HIGH && ButtonState2 == HIGH) {
    //Check to see if both button safetys add up and Change RelayOn to 1
        if (ButtonSafeOn1 + ButtonSafeOn2 == 2){
          ButtonSafeChecked = 1;
          RelayOn = 1;
          Serial.println("Relay On");
          } else {RelayOn = 0;
          ButtonSafeChecked = 0;
         }
        }
    //Turn off relay if too much time elapsed
        if (currentMillis - RelayMillis < RelayOnTime) {
          RelayOn = 0;
          ButtonSafeChecked = 0;
        }
    //Turn on relay pin if RelayOn is 1
      if (RelayOn == 1) {
           digitalWrite(RelayPin, HIGH);
           Serial.println("Relay Pin should go High");
        } else {digitalWrite(RelayPin, LOW);
        }
    //update the RelayMillis if it is still on
      if (RelayOn == 1){
          RelayMillis = currentMillis;
        }
    //increment counter to diplay press count
        if (LastRelayState != RelayOn){
          ButtonPushCounter++;
          Serial.println("State of Relay");
          Serial.print(RelayOn);
          Serial.println("  ");
          Serial.println("State of Last Relay State");
          Serial.print(LastRelayState);
        }
         // Delay a little bit to avoid bouncing
         delay(75);
         // set the cursor to column 0, line 1
      // (note: line 1 is the second row, since counting begins with 0):
      lcd.setCursor(0, 1);
      // print the number of seconds since reset:
      lcd.print((ButtonPushCounter/2));
      //Save Current Relay State for Next Loop
       LastRelayState = RelayOn;
      //Save Current Button Safety check for comparison for state change
       LastButtonSafeChecked =  ButtonSafeChecked;
    }

*update 10/13/17*
Here is the current code that includes the Bounce2 library as suggested by user Jot as well as the state machine he created to handle the task. Could I have implemented Bounce2 better?

    // A state machine is used, only to make it more clear what is going on.
    //
    // When a button is pressed, the input turns HIGH.
    //
    // Normally only one 'enum' is used for the state, that controls the code.
    // This sketch has also a 'enum' for the buttons, which is called the input state.

    // define the different states for this sketch.
    // An 'enum' is like a number of #define with increasing numbers.
    // include the library code:
    #include <Bounce2.h>
    #include <LiquidCrystal.h>

    // initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

    enum
    {
      WAIT_FOR_BOTH_OFF,
      WAIT_FOR_BOTH_ON,
      SAFETY_WINDOW,
      RELAY_ON,
    } state;       // an 'enum' is automatically an integer.

    // define the different input states.
    enum
    {
      BOTH_OFF,        // no buttons are pressed.
      BOTH_ON,         // both buttons are pressed.
      SOMETHING_ELSE,  // probably one of the buttons is pressed.
    };

    const int ButtonPin1 = 2;
    const int ButtonPin2 = 3;
    const int RelayPin = 5;

    // The previousMillis is used twice for two different things.
    // That is okay in this state machine.
    unsigned long previousMillis;

    const unsigned long RelayOnTime = 1750;    // Length of time for relay
    const unsigned long PushTimeWindow = 300; // Length of time to allow two pushes

    // Counters for the number of failed relay triggers and successful cycles.
    // They can probably be normal integers as well.
    unsigned long failed = 0;
    unsigned long success = 0;

    Bounce debouncer1 = Bounce();
    Bounce debouncer2 = Bounce();

    void setup()
    {
      lcd.begin(16, 2);
      lcd.print("Press Count");
      Serial.begin(9600);
      Serial.println("Unit Online");

    // Set up first button
      pinMode(ButtonPin1, INPUT);
      debouncer1.attach(ButtonPin1);
      debouncer1.interval(5); //Debounce time

    // Set up second button
      pinMode(ButtonPin2, INPUT);
      debouncer2.attach(ButtonPin2);
      debouncer2.interval(5); //Debounce time

      pinMode(RelayPin, OUTPUT);  // OUTPUT to Relay

      Serial.println("Going to WAIT_FOR_BOTH_OFF state");
      state = WAIT_FOR_BOTH_OFF;
    }

    void loop()
    {

      unsigned long currentMillis = millis();

    // Update the bounce instances
      debouncer1.update();
      debouncer2.update();

      int inputState = getInputState();

      // Process the data in a state machine.
      // The output part is also in the state machine.
      switch(state)
      {
        case WAIT_FOR_BOTH_OFF:
          // Both buttons must be released to be able to continue.
          if(inputState == BOTH_OFF)
          {
            // Prepare to go to the next state.
            Serial.println("Going to WAIT_FOR_BOTH_ON state");
            state = WAIT_FOR_BOTH_ON;
          }
          break;
        case WAIT_FOR_BOTH_ON:
          // This is the state when everything is idle and no buttons are pressed.
          // Normally both buttons are released,
          // but when both are pressed, then go to the next state.
          if(inputState == BOTH_ON)
          {
            // Prepare to go to the next state.
            Serial.println("Going to SAFETY_WINDOW state");
            previousMillis = currentMillis;
            state = SAFETY_WINDOW;
          }
          break;
        case SAFETY_WINDOW:
          if(inputState != BOTH_ON)
          {
            // During the safety time window, a button was released.
            // Return to idle.
            Serial.println("Going to WAIT_FOR_BOTH_OFF state");
            state = WAIT_FOR_BOTH_OFF;
          }
          else if(currentMillis - previousMillis <= PushTimeWindow)
          {
            // The buttons are still pressed.
            // The time window has reached the end.
            // Prepare to go to the next state.
            Serial.println("Going to RELAY_ON state");
            previousMillis = currentMillis;
            digitalWrite(RelayPin, HIGH);  // Turn ON RelayPin
            state = RELAY_ON;
          }
          break;
        case RELAY_ON:
          if(inputState != BOTH_ON)
          {
            // One of the buttons was released.
            // Stop the relay and return to idle.
            // Although the relay was triggered, it was not succesful.
            failed++;
            Serial.print("Failed=");
            Serial.println(failed);
            Serial.println("Going to WAIT_FOR_BOTH_OFF state");
            digitalWrite( RelayPin, LOW);  // Turn Off RelayPin
            state = WAIT_FOR_BOTH_OFF;
          }
          else if(currentMillis - previousMillis >= RelayOnTime)
          {
            // Everyting was okay.
            // The buttons are still pressed.
            // It was complete and succesful.
            // It is time to turn off the relay and return to idle.
            success++;
            Serial.print("Success=");
            Serial.println(success);
            Serial.println("Going to WAIT_FOR_BOTH_OFF state");
            lcd.setCursor(0,1);
            lcd.print(success);
            digitalWrite(RelayPin, LOW);  // Turn Off RelayPin
            state = WAIT_FOR_BOTH_OFF;
          }
          break;
        default:
          Serial.println("Error, unknown state");
          break;
      }
    }

    // This function returns the input state.
    // There is no StateChangeDetection, because a state machine is used.
    int getInputState()
    {
      int returnInputState;

      // Read the debounce state and create a input state according to the 'enum' values.
      int value1 = debouncer1.read();
      int value2 = debouncer2.read();

      if(value1 == LOW && value2 == LOW)
      {
        returnInputState = BOTH_OFF;
      }
      else if(value1 == HIGH && value2 == HIGH)
      {
        returnInputState = BOTH_ON;
      }
      else
      {
        // Not both on, not both off, so it must be something else.
        returnInputState = SOMETHING_ELSE;
      }

      return(returnInputState);

    }

title: Problem with Dual Safety Switches Initiating Timed Relay

Answers: 3

body:
From what I understood, this is what you're trying to do:

 - Turn a relay on as long as both buttons are pushed for 'pushWindowTime' milliseconds;
 - Keep the relay on for 'relayOnTime' milliseconds, or until at least one of the buttons are pushed.

I believe the difficulty you're facing is mostly because time is a parameter in your program, and in order to achieve that you're using 'millis()', [which returns the number of milliseconds elapsed since the program starts][1]. But rather than working with that, it may be easier in this case to use a delay associated to a loop, which is what I did.

    int ButtonPin1 = 0;
    int ButtonPin2 = 0;
    int RelayPin = 0;

    int ButtonState1 = 0;
    int ButtonState2 = 0;

    bool highState = false;

    int pushTimeWindow = 10000;
    int relayOnTime = 10000;

    void setup() {
      //IOs definition
      pinMode(ButtonPin1, INPUT);
      pinMode(ButtonPin2, INPUT);
      pinMode(RelayPin, OUTPUT);

      digitalWrite(RelayPin, LOW);
    }

    void loop() {

      //Loop for reading each button's state in a given period of time 'pushTimeWindow'.
      for(int i = 0; i < pushTimeWindow; i++) {

        //Reads each button's state at every iteraction
        ButtonState1 = digitalRead(ButtonPin1);
        ButtonState2 = digitalRead(ButtonPin2);

        //Flags a boolean if both buttons are pushed.
        if((ButtonState1 == HIGH)&&(ButtonState2 == HIGH))
          highState = true;

        //If a button is released, breaks the loop.
        else {
          highState = false;
          break;
        }
        //Delays the loop one second.
        delay(1000);
      }

      if(highState) {

        //Loop to activate the relay as long as both buttons are pushed, during the time limit 'relayOnTime'.
        for(int i = 0; i < relayOnTime; i++) {

          ButtonState1 = digitalRead(ButtonPin1);
          ButtonState2 = digitalRead(ButtonPin2);

          //Activates the relay if both buttons are pushed.
          if((ButtonState1 == HIGH)&&(ButtonState2 == HIGH))
            digitalWrite(RelayPin, HIGH);

          //Shuts down the relay if a button is released and breaks the loop.
          else {
            digitalWrite(RelayPin, LOW);
            break;
          }

      //Delays the loop one second.
      delay(1000);
    }

      }

      //Makes sure that every time loop() starts again, the relay is shut down.
      highState = false;

    }

Hope this answers your question. Let us know what you find.

  [1]: https://www.arduino.cc/en/Reference/Millis

body:
The Arduino has a loop function, that runs over and over again.
The Arduino has a millis function for the time.
Those two combine beautifully with a state machine.

Once I made a function that returns the input value as BOTH_OFF, BOTH_ON, or SOMETHINE_ELSE, then the state machine automatically unfolds itself.

I hope you see how clean the code is. Every state has its own code. You don't have to think for hours how to make a spaghetti of if-statements. Although the sketch is now larger, there is no unnecessary code.
If you want to change something, you only have to find the state that you want to change. Adding a new state is also easy.

I have added some explanation in the sketch.

    // A state machine is used, only to make it more clear what is going on.
    //
    // When a button is pressed, the input turns HIGH.
    // Are there an external pulldown resistors ?
    //
    // Normally only one 'enum' is used for the state, that controls the code.
    // This sketch has also a 'enum' for the buttons, which is called the input state.

    // define the different states for this sketch.
    // An 'enum' is like a number of #define with increasing numbers.
    enum
    {
      WAIT_FOR_BOTH_OFF,
      WAIT_FOR_BOTH_ON,
      SAFETY_WINDOW,
      RELAY_ON,
    } state;       // an 'enum' is automatically an integer <- it is not an integer

    // define the different input states.
    enum
    {
      BOTH_OFF,        // no buttons are pressed.
      BOTH_ON,         // both buttons are pressed.
      SOMETHING_ELSE,  // probably one of the buttons is pressed.
    };

    const int ButtonPin1 = 2;
    const int ButtonPin2 = 3;

    // The previousMillis is used twice for two different things.
    // That is okay in this state machine.
    unsigned long previousMillis;

    const unsigned long RelayOnTime = 1000;    // Length of time for relay
    const unsigned long PushTimeWindow = 1000; // Length of time to allow two pushes

    // Counters for the number of failed relay triggers and successful cycles.
    // They can probably be normal integers as well.
    unsigned long failed = 0;
    unsigned long success = 0;

    void setup()
    {
      Serial.begin(9600);
      Serial.println("Hello");

      pinMode(ButtonPin1, INPUT);
      pinMode(ButtonPin2, INPUT);

      pinMode(LED_BUILTIN, OUTPUT);  // LED_BUILTIN for testing

      Serial.println("Going to WAIT_FOR_BOTH_OFF state");
      state = WAIT_FOR_BOTH_OFF;
    }

    void loop()
    {
      unsigned long currentMillis = millis();

      // Collect all input data.
      int inputState = getInputState();

      // Process the data in a state machine.
      // The output part is also in the state machine.
      switch(state)
      {
        case WAIT_FOR_BOTH_OFF:
          // Both buttons must be released to be able to continue.
          if(inputState == BOTH_OFF)
          {
            // Prepare to go to the next state.
            Serial.println("Going to WAIT_FOR_BOTH_ON state");
            state = WAIT_FOR_BOTH_ON;
          }
          break;
        case WAIT_FOR_BOTH_ON:
          // This is the state when everything is idle and no buttons are pressed.
          // Normally both buttons are released,
          // but when both are pressed, then go to the next state.
          if(inputState == BOTH_ON)
          {
            // Prepare to go to the next state.
            Serial.println("Going to SAFETY_WINDOW state");
            previousMillis = currentMillis;
            state = SAFETY_WINDOW;
          }
          break;
        case SAFETY_WINDOW:
          if(inputState != BOTH_ON)
          {
            // During the safety time window, a button was released.
            // Return to idle.
            Serial.println("Going to WAIT_FOR_BOTH_OFF state");
            state = WAIT_FOR_BOTH_OFF;
          }
          else if(currentMillis - previousMillis >= PushTimeWindow)
          {
            // The buttons are still pressed.
            // The time window has reached the end.
            // Prepare to go to the next state.
            Serial.println("Going to RELAY_ON state");
            previousMillis = currentMillis;
            digitalWrite(LED_BUILTIN, HIGH);  // LED_BUILTIN for testing
            state = RELAY_ON;
          }
          break;
        case RELAY_ON:
          if(inputState != BOTH_ON)
          {
            // One of the buttons was released.
            // Stop the relay and return to idle.
            // Although the relay was triggered, it was not succesful.
            failed++;
            Serial.print("Failed=");
            Serial.println(failed);
            Serial.println("Going to WAIT_FOR_BOTH_OFF state");
            digitalWrite( LED_BUILTIN, LOW);  // LED_BUILTIN for testing
            state = WAIT_FOR_BOTH_OFF;
          }
          else if(currentMillis - previousMillis >= RelayOnTime)
          {
            // Everyting was okay.
            // The buttons are still pressed.
            // It was complete and succesful.
            // It is time to turn off the relay and return to idle.
            success++;
            Serial.print("Success=");
            Serial.println(success);
            Serial.println("Going to WAIT_FOR_BOTH_OFF state");
            digitalWrite(LED_BUILTIN, LOW);  // LED_BUILTIN for testing
            state = WAIT_FOR_BOTH_OFF;
          }
          break;
        default:
          Serial.println("Error, unknown state");
          break;
      }
    }

    // This function returns the input state.
    // There is no StateChangeDetection, because a state machine is used.
    int getInputState()
    {
      int returnInputState;

      // Read the buttons and create a input state according to the 'enum' values.
      int ButtonState1 = digitalRead(ButtonPin1);
      int ButtonState2 = digitalRead(ButtonPin2);

      if(ButtonState1 == LOW && ButtonState2 == LOW)
      {
        returnInputState = BOTH_OFF;
      }
      else if(ButtonState1 == HIGH && ButtonState2 == HIGH)
      {
        returnInputState = BOTH_ON;
      }
      else
      {
        // Not both on, not both off, so it must be something else.
        returnInputState = SOMETHING_ELSE;
      }

      return(returnInputState);
    }

**A few extra notes about a state machine or "finite state machine" or "FSM":**

In the SAFETY_WINDOW state, I use "if .. else if .." instead of two seperate "if" statements. When the state is changed due to the buttons, then I don't want to check the timeout anymore.

In the SAFETY_WINDOW state, the relay is turned on, because there I prepare for the next state. If you think that is confusing, you can add a state in between, for example called INITIATE_RELAY_ON, and turn the relay on in that state and then continue to the next state.
That is also nice about a state machine. You can add or remove states and move code around for you convenience.

In the SAFETY_WINDOW state I check the buttons first and then the timeout. I could also check the timeout first. It does not matter.
This is typical for a state machine. When delay is replaced by millis and the Arduino loop and the state machine are executed many times per second, then it does not matter which condition is checked first.

A sketch can have many state machines. Sometimes a library contains a state machine. Such libraries often have a 'update' function, that is supposed to be called every time the Arduino loop runs.

**Correction nov 4, 2017**
Oops, an 'enum' is **not** automatically an integer. An 'enum' is its own type. Its type is more like the type of a union or struct.

body:
> Here is the code:

your code and the code pieces posted so far suffer from two problems: 1) too specific to the application; and 2) too complicated.

here is a different approach to consider:

1) write a piece of code that reads the state of a button, with or without debouncing;

2) write a piece of code that detects no press, single press, double press, and long press (or even more if you want), using 1) above.

3) write a piece of code that detects the same but for two buttons, using 2) above.

...

you can consider the use of enum to make the code more robust.

with this approach, your code can be reused for future projects, and will be easier to maintain / understand as it is very intuitive and modular.


body:
Today I found a problem in my project, here is the video of problem

[https://streamable.com/wamm9][1]

code MASTER : https://www.dropbox.com/s/l4x3zwzv6szrs50/MASTER.ino?dl=0

    #include <Wire.h>

    const int BUTTON1 = 5;
    const int BUTTON2 = 6;
    int buttonchoose;

    void setup() {
      // put your setup code here, to run once:
      pinMode(BUTTON1, INPUT);
      pinMode(BUTTON2, INPUT);
      Wire.begin();
      Serial.begin(9600);
    }

    void loop() {
      Serial.println("You want turn X motor");
      Serial.println("1-YES  2-NO");
      buttonchoose = fonctioninput();
      delay(500);
      if (buttonchoose == 1) {
        //Turn motor x for onerevolution
        Wire.beginTransmission(8); // transmit to device #8
        Wire.write('X'); // send M (milk)
        Wire.endTransmission();    // stop transmitting
        Serial.println("send X");
      }
      Serial.println("You want turn Y motor");
      Serial.println("1-YES  2-NO");
      buttonchoose = fonctioninput();
      delay(500);
      if (buttonchoose == 1) {
        //Turn motor Y for onerevolution
        Wire.beginTransmission(8); // transmit to device #8
        Wire.write('Y'); // send M (milk)
        Wire.endTransmission();    // stop transmitting
        Serial.println("send Y");
      }

      Serial.println("You want turn Z motor");
      Serial.println("1-YES  2-NO");
      buttonchoose = fonctioninput();
      delay(500);
      if (buttonchoose == 1) {
        //Turn motor Z for onerevolution
        Wire.beginTransmission(8); // transmit to device #8
        Wire.write('Z'); // send M (milk)
        Wire.endTransmission();    // stop transmitting
        Serial.println("send Z");
      }
    }

    int fonctioninput() {
      int val1 = 0;
      int val2 = 0;
      int buttonreturn = 0;
      while ( (val1 - val2) == 0) {
        val1 = digitalRead(BUTTON1);
        val2 = digitalRead(BUTTON2);
      }

      if (val1 == 1) {
        buttonreturn = 1;
      }
      else {
        buttonreturn = 2;
      }
      return buttonreturn;
    }

code SLAVE : https://www.dropbox.com/s/2lg8ogjep80gtsa/SLAVE.ino?dl=0

    #include <Wire.h>
    #include <Stepper.h>

    const int stepsPerRevolution = 64;
    int led = A0;
    Stepper motorX(stepsPerRevolution, 2, 3, 4, 5);
    Stepper motorY(stepsPerRevolution, 6, 7, 8, 9);
    Stepper motorZ(stepsPerRevolution, 10, 11, 12, 13);

    void setup() {
      Wire.begin(8);
      // Wire.onRequest(requestEvent);
      Wire.onReceive(receiveEvent);

      pinMode(led, OUTPUT);
      motorX.setSpeed(60);
      motorY.setSpeed(60);
      motorZ.setSpeed(60);
      Serial.begin(9600);
    }

    void loop() {}

    void receiveEvent(int howMany) {

      char choose;

      while (Wire.available() > 0) {
        //initialization
        choose = 'A';
        choose = Wire.read();

        if (choose == 'X')    {
          Serial.println("TURN MOTOR X");

          turnX();
        }
        else if (choose == 'Y') {
          Serial.println("TURN MOTOR Y");
          turnY();
        }
        else if (choose == 'Z') {
          Serial.println("TURN MOTOR Z");
          turnZ();
        }
      }
      analogWrite(led, 1020);
      delay(300);
      analogWrite(led, 0);
    }

    void turnX() {
      motorX.step(stepsPerRevolution);
    }

    void turnY() {
      motorY.step(stepsPerRevolution);
    }

    void turnZ() {
      motorZ.step(stepsPerRevolution);
    }

When I choose yes to turn a motor it works well but the other motors that is after does not work.
I want the other motors to turn if I choose yes even if the previous motor is running.
Please, I need your URGENT help because my project is blocked
 :(

  [1]: https://streamable.com/wamm9

title: Need help with my urgent problem

Answers: 1

body: The step function from the Stepper library is blocking.  So it can only run one motor at a time.  You need a different stepper library that is non-blocking.  Try AccelStepper.


body:
I am using nodeMCU along with oneWire temperature sensor ds18b20, and 2x16 LCD display (not I2C). I am using Arduino IDE to program nodeMCU. I am getting a compilation error:

    C:\Program Files (x86)\Arduino\libraries\OneWire/OneWire.h:108:2: error: #error "Please define I/O register types here"
    #error "Please define I/O register types here"
    ^
    exit status 1
    Error compiling for board NodeMCU 1.0 (ESP-12E Module).

What is meant by: "Please define I/O register types here"? Thank you for the help.

title: Compilation Error in nodeMCU along with oneWire temperature sensor ds18b20, and 2x16 LCD display (not I2C)

Answers: 1

body:
It appears you're using an outdated version of the OneWire library that does not support ESP8266. Please follow these instructions to upgrade to the latest release of the library:

1. Sketch > Include library > Manage libraries...
1. Wait for the download to finish.
1. In the "Filter your search..." box, type "onewire".
1. Click on the "OneWire" entry.
1. Click the "Update" button.
1. Wait for the installation to finish.
1. Click the "Close button.

The recent releases of the OneWire library [have support for ESP8266](https://github.com/PaulStoffregen/OneWire/commit/4ae7f068be9dab4ef2287512af695c20aa6c54b4) so this should solve your compilation issue.


body:
<!-- language: lang-cpp -->

    * /
    #define CUSTOM_SETTINGS
    #define INCLUDE_KEYPAD_SHIELD

    /* Include 1Sheeld library. */
    #include <OneSheeld.h>

    /* Define an iterator. */
    int iterations = 0;

    /* A name for the LockPin on pin D2. */
    int lockPin = 2;
    int ledRed = A5;
    int ledGreen = A4;

    /* A name for the switch led on pin D5. */
    const int lampuPin = 5;
    const int ledlampu = A0;

    // variables will change:
    int buttonState = 0; // variable for reading the pushbutton status
    int stateBefore = 0;
    int i = 0;
    int j = 0;

    void setup() {
      /* Start communication. */
      OneSheeld.begin();
      /* Set the LED & LOCK as output. */
      pinMode(lockPin, OUTPUT);
      pinMode(ledRed, OUTPUT);
      pinMode(ledGreen, OUTPUT);
      /* Set the LampuPin pin as output. */
      pinMode(lampuPin, INPUT);
      /* Set the LED pin as output. */
      pinMode(ledlampu, OUTPUT);
    }

    void loop() {
      //======Lampu Rumah=======
      // read the state of the pushbutton value:
      buttonState = digitalRead(lampuPin);
      if (buttonState != stateBefore) {
        if (buttonState == HIGH and i == 0) {
          digitalWrite (ledlampu, HIGH);
          j = 1;
        } else if (buttonState == LOW and j == 1) {
          i = 1;
        } else if (buttonState == HIGH and i == 1) {
          digitalWrite (ledlampu, LOW);
          j = 0;
        } else if (buttonState == LOW and j == 0) {
          i = 0;
        }
      }
      stateBefore = buttonState;
    }

    //======Pintu Hadapan Rumah=======
    /* Check if "1" is pressed, iterate one time. */
    if (iterations == 0 && isOnePressed()) {
      iterations++;
    } else if (iterations == 1 && isTwoPressed()) {
      /* Check if "2" is pressed, iterate one time. */
      iterations++;
    } else if (iterations == 2 && isThreePressed()) {
      /* Check if "3" is pressed, iterate one time. */
      iterations++;
    } else if (iterations == 3 && isFourPressed()) {
      /* Check if "4" is pressed, iterate one time. */
      iterations++;
    } else if (isOtherButtonPressed()) {
      /* Check if any other button is pressed, reset iterations. */
      iterations = 0;
    }
    if (iterations == 4) {
      /* Check if the number of iterations is 4, blink the LED. */
      digitalWrite(lockPin, LOW);
      digitalWrite(ledGreen, HIGH);
      digitalWrite(ledRed, LOW);
      OneSheeld.delay(6000);
      digitalWrite(lockPin, HIGH);
      digitalWrite(ledRed, HIGH);
      digitalWrite(ledGreen, LOW);
      OneSheeld.delay(1000);
      /* Reset the iterator. */
      iterations = 0;
    }

    /* Helper functions check if a certain button is pressed by checking its row and column. */

    boolean isOnePressed() {
      return Keypad.isRowPressed(0) && Keypad.isColumnPressed(0);
    }

    boolean isTwoPressed() {
      return Keypad.isRowPressed(0) && Keypad.isColumnPressed(1);
    }

    boolean isThreePressed() {
      return Keypad.isRowPressed(0) && Keypad.isColumnPressed(2);
    }

    boolean isFourPressed() {
      return Keypad.isRowPressed(1) && Keypad.isColumnPressed(0);
    }

    boolean isOtherButtonPressed() {
      return ((Keypad.isAnyColumnPressed() || Keypad.isAnyColumnPressed()) && !isOnePressed() && !isTwoPressed() && !isThreePressed() && !isFourPressed());
    }

title: There is an error stating that "exit status 1 expected unqualified-id before 'if'. This project is used to turn on/off LED and magnetic door

Answers: 1

body:
You got an extra closing brace after this line.

    stateBefore = buttonState;
    }

It ends the loop function so the next if is outside any function and illegal.  Hit Control-T in the IDE to auto-format the code and it will line up the indention and that will help you spot these sorts of errors.


body:
Changed ESP8266-01 to wrong settings by mistake. It was working ok
at 115200 (its default settings). It was connected like this:

PC->(USB)->Arduino->ESP8266.

Using Arduino as bridge

 - Pins 0 and 1 (RX/TX) connected directly to ESP8266 since I didnt have
   USB to TTL adapter.
 - MCU removed so I could make that scenario work

It was just for testing AT commands. I did it like that because I realized that I was getting errors all the time trying to connect
using SerialSoftware (and different pins in Arduino).

Found out later that SerialSoftware does not work correctly at 115200...

So I issued the following AT command:

             AT+UART_DEF=9600,8,1,0,3

Now I cannot connect to the ESP8266 to correct that setting. All I get is garbage characters. I understand it's because of the flow control settings. I set it to both RTS and CTS which I also read later ESP8266 does not support?

Have tried:

 - Using Putty to change settings of COM port at connect. Have tried all speeps and flow control settings combinations I could think of. I get nothing or garbage characters.
 - Changing COM port setting from Device Manager (Windows 7)
 - Flashing ESP8266 using official tool (ESPFlashDownloadTool_v3.6.1.0).It won't sync with the ESP8266. It does not allow me to adjust speed to 9600. Minimun speed that show is 115200
 - Changing settings in ESPFlashDownloadTool_v3.6.1.0 so it will sync at 9600 (file: spi_download.conf)

I cannot think of anymore ideas. Have I completely messed up my ESP8266?

Is there a way that I'm not aware of that could fix this problem? How?

Thanks in advance!

Jorge

title: ESP8266-01 wrong flow control settings

Answers: 2

body:
    AT+UART_DEF=9600,8,1,0,3

Are you aware that this configuration (3) as a rule would require both RTS and CTS extra physical signals to work ? That means, if you do not connect anything there, the level present at some pin configured anywhere would prevent ESP8266 from receiving further data from serial.

In general people use "no flow control" (0)

    AT+UART_DEF=9600,8,1,0,0

body:
andre,

As I stated in my post I did it by mistake. Nonetheless I was able to fix it by using a different flashing tool that used just one .bin file instead of many like the official ESP8266 tool does.

Can anyone please explain me why is that? Why are there different tools to flash the ESP8266? In concrete, why one requires just one file that will update the SDK and AT firmware in one pass, and the other requires many differente files? Or just a link to a site o post so I can better understand the differences?

The tool I ended up usign is "ESP8266 Flash Downloader"

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/xvkGR.jpg

The file I used: `AiThinker_ESP8266_DIO_8M_8M_20160615_V1.5.4.bin`

Thanks!


body:
I've been working on a project for the last few days and spent a LOT of time googling, reading and testing. I'm kinda running out of ideas now and instead of bumping my head to the wall I thought posting my issue here in the hopes someone might be able to point me towards the right direction

I've got an Arduino UNO programmed as I2C Master and an ATtiny85 as an I2C slave. An single Adafruit Neopixel LED is attached to the slave.

When running the two sketches below everything actually works perfect.....for about a minute or so.
While during correct operations the Neopixel LED is actually changing color correctly and the serial monitor on the Uno shows the correctly updated R-G-B values, things change after about 1 minute of running.
The LED keeps blinking, which tells me the ATtiny is not frozen.
The UNO keeps sending I2C and is receiving I2C data...but the data is constant. The updated RGB that the Uno (master) has been sending to the ATtiny slave are somehow not handled (correctly) by the slave.

Any thoughts are more then appreciated. I'm totally lost and do not know which directions to go from here so any pointers would be more then welcome.

The Master - Arduino Uno -

    #include <Wire.h>

    #define I2C_MASTER_ADDR 0x04
    #define I2C_SLAVE_ADDR 0x05

    /*
    * Software config
    */
    int pollInterval = 700;//Milliseconds

    //Demo's
    #define demoLedInterval 150//In milliseconds
    boolean demoRequest = false;

    /*
    * Internal variables
    */
    unsigned long lastPoll = 0;

    int demoLedState = 0;
    unsigned long lastDemoLedUpdate = 0;

    /*
    * Setup function
    */
    void setup()
    {
     Wire.begin(I2C_MASTER_ADDR);  // join i2c bus (address optional for master)
     Serial.begin(115200);         // start serial for output
     Serial.println("Setup complete");
    }

    /*
    * The main loop
    */
    int i =0;
    void loop()
    {

     /*
      * Poll the slave
      */
     if( (millis()-lastPoll) > pollInterval)
     {
       /*
        *
        */
       int red=0; int green=0; int blue=0;

         if(i==0)
         {
           Serial.println("Write data to slave - set led red");
           Wire.beginTransmission(I2C_SLAVE_ADDR);
           Wire.write(0xC2);//Command
           Wire.write(0x00);
           Wire.write(255);//Data
           Wire.endTransmission();
           Wire.beginTransmission(I2C_SLAVE_ADDR);
           Wire.write(0xC3);//Command
           Wire.write(0x00);
           Wire.write(0);//Data
           Wire.endTransmission();
           Wire.beginTransmission(I2C_SLAVE_ADDR);
           Wire.write(0xC4);//Command
           Wire.write(0x00);
           Wire.write(0);//Data
           Wire.endTransmission();
         }
         if(i==1)
         {
           Serial.println("Write data to slave - set led green");
           Wire.beginTransmission(I2C_SLAVE_ADDR);
           Wire.write(0xC2);//Command
           Wire.write(0x00);
           Wire.write(0);//Data
           Wire.endTransmission();
           Wire.beginTransmission(I2C_SLAVE_ADDR);
           Wire.write(0xC3);//Command
           Wire.write(0x00);
           Wire.write(255);//Data
           Wire.endTransmission();
           Wire.beginTransmission(I2C_SLAVE_ADDR);
           Wire.write(0xC4);//Command
           Wire.write(0x00);
           Wire.write(0);//Data
           Wire.endTransmission();
         }
         if(i==2)
         {
           Serial.println("Write data to slave - set led blue");
           Wire.beginTransmission(I2C_SLAVE_ADDR);
           Wire.write(0xC2);//Command
           Wire.write(0x00);
           Wire.write(0);//Data
           Wire.endTransmission();
           Wire.beginTransmission(I2C_SLAVE_ADDR);
           Wire.write(0xC3);//Command
           Wire.write(0x00);
           Wire.write(0);//Data
           Wire.endTransmission();
           Wire.beginTransmission(I2C_SLAVE_ADDR);
           Wire.write(0xC4);//Command
           Wire.write(0x00);
           Wire.write(255);//Data
           Wire.endTransmission();
         }

       i++; if(i>2) i =0;

       /*
        * General request (without data). Should return something though
        */
       Serial.println("General request for slave");
       Wire.requestFrom(I2C_SLAVE_ADDR, 7);//Request N bytes, N=byte_len
       delay(10);//Give the slave time to answer
       while (Wire.available())
       {
         uint8_t next_byte = Wire.read();
         Serial.print(next_byte);Serial.print(" ");
       }
       Serial.println("\n");

       lastPoll = millis();
     }//End if time to poll again

    }//End loop

The Slave code - ATtiny 85 - Main file

    #include <EEPROM.h>
    #include <OneWire.h>
    #include <TinyWireS.h>
    #include <Bounce2.h>
    #include <Adafruit_NeoPixel.h>
    #ifdef __AVR__ //Which will be true for ATtiny85
      #include <avr/power.h>
    #endif

    #define I2C_SLAVE_DEFAULT_ADDR 0x05

    #include "namespaces.h"//Include at last to make sure all libs are present

    //Software config
    #define BUTTON_DEBOUNCE 5//Debounce milliseconds

    //Hardware config
    #define NEOPIXEL_PIN  1
    #define BUTTON_PIN    3
    #define DS2401_PIN    4

    #define NUMPIXELS     1

    /*
     * Initialize instances/classes
     */
    Bounce button = Bounce();
    Adafruit_NeoPixel neopixel = Adafruit_NeoPixel(NUMPIXELS, NEOPIXEL_PIN, NEO_GRB + NEO_KHZ800);
    OneWire ds(DS2401_PIN);

    void setup()
    {
      uint32_t _now = millis();

      //Start I2C
      uint8_t _device_addr = EEPROM_DATA::get_device_addr();
      //TinyWireS.begin(_device_id);
      TinyWireS.begin(I2C_SLAVE_DEFAULT_ADDR);
      TinyWireS.onReceive(I2C::receiveEvent);
      TinyWireS.onRequest(I2C::requestEvent);

      //Start NeoPixel
      neopixel.begin();
      neopixel.setPixelColor(NUMPIXELS-1, neopixel.Color(255, 255, 255) );
      neopixel.show();

      //Start Button
      pinMode(BUTTON_PIN, INPUT_PULLUP);
      button.attach(BUTTON_PIN);
      button.interval(BUTTON_DEBOUNCE);

    }

    unsigned long lastBlink = 0;
    boolean lastBlinkState;

    void loop()
    {

      button.update();

      if(VARS::led_needs_update)
      {
        led_update();
        VARS::led_needs_update = false;
      }

      if(button.fell())
      {
        VARS::button_state = HIGH;
      }
      if(button.rose())
      {
        VARS::button_state = LOW;
      }

      //testblink
      if ( (millis()-lastBlink) > 600)
      {
        if(lastBlinkState)
        {
          neopixel.setPixelColor(NUMPIXELS-1, 0,0,0 );
          neopixel.show();
          lastBlinkState = false;
        }
        else
        {
          led_update();
          lastBlinkState = true;
        }
        lastBlink = millis();
      }

      // This needs to be here for the TinyWireS lib
      TinyWireS_stop_check();
    }

    /*
     * Helper functions
     */
    void led_update()
    {
      neopixel.setPixelColor(NUMPIXELS-1,
        VARS::led_red,
        VARS::led_green,
        VARS::led_blue
      );
      neopixel.show();
    }

The Slave code - ATtiny 85 - namespaces.h

    namespace VARS
    {
      //These are available in a I2C response
      volatile boolean button_state = 0;
      volatile int led_red = 0;
      volatile int led_green = 0;
      volatile int led_blue = 0;
      uint8_t sn_family;
      uint8_t sn_bit1;
      //uint64_t serial_number = 0;
      //int I2C_response_max_length = 4;//Count the above

      //These are internal
      volatile boolean led_needs_update = false;
      int update_interval     = 300;
      unsigned long last_update = 0;
    }

    //===========================================================================

    namespace EEPROM_DATA
    {
      uint8_t default_device_addr   =     I2C_SLAVE_DEFAULT_ADDR;
      uint8_t this_device_address   =     0x05;

      bool device_addr_valid(uint8_t addr)
      {
        return (addr > 0x04 && addr < 0x7E);
      }
      bool store_device_addr(uint8_t new_device_addr)
      {
        if (!device_addr_valid(new_device_addr)) return false;//cancel if out of bounds. Assume corrupt data.
        EEPROM.write(EEPROM_DATA::this_device_address, new_device_addr);//Set new i2c address into EEPROM
        return true;
      }
      uint8_t get_device_addr()
      {
        uint8_t _addr = EEPROM.read(EEPROM_DATA::this_device_address);
        if (!device_addr_valid(_addr))
        {
          _addr = EEPROM_DATA::default_device_addr;
          store_device_addr(_addr); //update EEPROM with a valid/default device id.
        }
        return _addr;
      }
    }

    //===========================================================================

    namespace COMMANDS
    {
      enum {
        assign_new_device_addr  =     0xC1,
        set_led_red             =     0xC2,
        set_led_green           =     0xC3,
        set_led_blue            =     0xC4
      };
      bool do_command(uint8_t cmd, uint16_t cmd_data)
      {
        //interpret command.
        switch (cmd)
        {
          //set new i2c slave adress.
          //ATTENTION: After command is performed, the chip will need a hard reset.
          case COMMANDS::assign_new_device_addr:
            uint8_t new_device_addr;
            new_device_addr = uint8_t(cmd_data & 0x007F);//ensure the address is 7-bit.
            return EEPROM_DATA::store_device_addr(new_device_addr);//return true if saved, false if invalid address.
            break;

          case COMMANDS::set_led_red:
            //if (cmd_data > 0x00FF) break;//ignore out of range data. Assume corrupt packet.
            VARS::led_red = int(cmd_data);
            VARS::led_needs_update = true;
            break;

          case COMMANDS::set_led_green:
            //if (cmd_data > 0x00FF) break;//ignore out of range data. Assume corrupt packet.
            VARS::led_green = int(cmd_data);
            VARS::led_needs_update = true;
            break;

          case COMMANDS::set_led_blue:
            //if (cmd_data > 0x00FF) break;//ignore out of range data. Assume corrupt packet.
            VARS::led_blue = int(cmd_data);
            VARS::led_needs_update = true;
            break;
        }
      }
    }

    //===========================================================================
    int pointer = 0;
    namespace I2C{

      //Gets called when the ATtiny receives a general i2c data request.
      //Tx_stop is sent after end of call, so all bytes need to be sent before leaving.
      void requestEvent()
      {

    //The number of bytes requested should NOT exceed the number of bytes returned
        TinyWireS.send( VARS::button_state );
        TinyWireS.send( VARS::led_red );
        TinyWireS.send( VARS::led_green );
        TinyWireS.send( VARS::led_blue );

      }

      //Gets called when the ATtiny recieves an i2c message THAT CONTAINS DATA from another device.
      void receiveEvent(uint8_t byte_count)
      {
        //first byte is command, next 2 bytes is data for command. Total must equal 3 bytes.
        if (!TinyWireS.available() || byte_count != 3 ) return;

        //retrieve the command and 16-bit data.
        //Incomming data is ordered CMD,Data-MSB,Data-LSB.
        uint8_t cmd = TinyWireS.receive();
        uint16_t cmd_data = (TinyWireS.receive() << 8);
        cmd_data += TinyWireS.receive();

        COMMANDS::do_command(cmd, cmd_data);
      }

    }

title: Arduino <<I2C>> ATtiny85 stops updating variables after a while

Answers: 1

body:
After diving into interrupts, timing etc I did found the solution.
Thanks for all the suggestions, in particular to @Jot!

In the end I took the following steps:

- adding a 1ms delay after each Wire.endTransmission()

- dropped the Neopixel lib (https://github.com/cpldcpu/light_ws2812)

Below is the final code, for anyone interested.
There is still an issue with this code: requesting multiple bytes from the slave always results in receiving just a single byte. But since that's most likely unrelated to the original question I'm opening a new topic for that (if I really can't find a solution myself, that is).

Master

    /*
     *
     */

    #include <Wire.h>

    #define I2C_MASTER_ADDR 0x04
    #define I2C_SLAVE_ADDR 0x05

    /*
     * Software config
     */
    int pollInterval = 700;//Milliseconds

    /*
     * Internal variables
     */
    unsigned long lastPoll = 0;

    /*
     * Setup function
     */
    void setup()
    {
      Wire.begin(I2C_MASTER_ADDR);  // join i2c bus (address optional for master)
      Serial.begin(115200);         // start serial for output
      Serial.println("Setup complete");
    }

    /*
     * The main loop
     */
    int i = 0;
    void loop()
    {

      /*
       *
       */
      if( (millis()-lastPoll) > pollInterval)
      {
        Serial.println("Write data to slave");
        Wire.beginTransmission(I2C_SLAVE_ADDR);
        Wire.write(0x01);//Register to start at
        switch(i)
        {
          case 0:
            Wire.write(255);
            Wire.write(0);
            Wire.write(0);
            i++;
            break;
          case 1:
            Wire.write(0);
            Wire.write(255);
            Wire.write(0);
            i++;
            break;
          case 2:
            Wire.write(0);
            Wire.write(0);
            Wire.write(255);
            i = 0;
            break;
        }
        Wire.endTransmission();
        delay(1);//Dont let the slave panic

        //Set the register pointer back to 0x01
        Wire.beginTransmission(I2C_SLAVE_ADDR);
        Wire.write(0x00);//Register to start at
        Wire.endTransmission();
        delay(1);//Dont let the slave panic

        //Get values from the three registers up form 0x01
        Wire.requestFrom(I2C_SLAVE_ADDR, 6);//Request N bytes
        while (Wire.available())
        {
          uint8_t next_byte = Wire.read();
          Serial.print(next_byte);Serial.print(" ");
        }
        Serial.println("\n");

        lastPoll = millis();
      }//End if time to poll again

    }//End loop

Slave

    #include <EEPROM.h>
    #include <OneWire.h>
    #include <TinyWireS.h>
    #include <Bounce2.h>
    #include <WS2812.h>
    #ifdef __AVR__ //Which will be true for ATtiny85
      #include <avr/power.h>
    #endif

    //Software config
    #define I2C_SLAVE_DEFAULT_ADDR 0x05
    #define BUTTON_DEBOUNCE 5//Debounce milliseconds

    //Hardware config
    #define NEOPIXEL_PIN  1
    #define BUTTON_PIN    3
    #define DS2401_PIN    4

    #define NUMPIXELS     1

    /*
     * I2C Registers
     *
     * Register map:
     * 0x00 - Button state
     * 0x01 - led value red
     * 0x02 - led value green
     * 0x03 - led value blue
     * 0x04 - SerialNumber - Family (byte 0)
     * 0x05 - SerialNumber - Byte 1
     * 0x06 - SerialNumber - Byte 2
     * 0x07 - SerialNumber - Byte 3
     * 0x08 - SerialNumber - Byte 4
     * 0x09 - SerialNumber - Byte 5
     * 0x10 - SerialNumber - Byte 6
     * 0x11 - SerialNumber - CNC (byte 7)
     *
     * Total size: 12
     */
    const byte reg_size = 12;
    volatile uint16_t i2c_regs[reg_size];

    /*
     * Internal variables
     */
    cRGB value;
    volatile boolean led_needs_update = false;
    volatile byte reg_position;

    /*
     * Initialize instances/classes
     */
    Bounce button = Bounce();
    WS2812 led(NUMPIXELS);

    void setup()
    {
      //Start I2C
      //uint8_t _device_addr = EEPROM_DATA::get_device_addr();
      TinyWireS.begin(I2C_SLAVE_DEFAULT_ADDR);
      TinyWireS.onReceive(i2cReceiveEvent);
      TinyWireS.onRequest(i2cRequestEvent);

      //Start Led
      led.setOutput(NEOPIXEL_PIN);
      value.b = 255; value.g = 0; value.r = 0;
      led.set_crgb_at(0, value); //Set value at LED found at index 0
      led.sync(); // Sends the value to the LED

      //Start Button
      pinMode(BUTTON_PIN, INPUT_PULLUP);
      button.attach(BUTTON_PIN);
      button.interval(BUTTON_DEBOUNCE);

    }

    void loop()
    {
      button.update();

      if(led_needs_update)
      {
        led_update();
        led_needs_update = false;
      }

      if(button.fell())
      {
        i2c_regs[0x00] = true;
      }
      if(button.rose())
      {
        i2c_regs[0x00] = false;
      }

      // This needs to be here for the TinyWireS lib
      TinyWireS_stop_check();

    }

    /*
     * I2C Handelers
     */
    void i2cReceiveEvent(uint8_t howMany)
    {
        if (howMany < 1)
        {
            return;// Sanity-check
        }

        reg_position = TinyWireS.receive();
        howMany--;
        if (!howMany)
        {
            return;// This write was only to set the buffer for next read
        }

        while(howMany--)
        {
            //Store the recieved data in the currently selected register
            i2c_regs[reg_position] = TinyWireS.receive();

            //Proceed to the next register
            reg_position++;
            if (reg_position >= reg_size)
            {
                reg_position = 0;
            }
        }
        led_needs_update = true;
    }//End i2cReceiveEvent()

    void i2cRequestEvent()
    {
        //Send the value on the current register position
        //NOT WORKING when requestin multiple bytes
        //TinyWireS.send(i2c_regs[reg_position]);

        //WORKAROUND
        int n = reg_size - reg_position;//Number of registers to return
        for(int i = reg_position; i < n; i++)
        {//Return all bytes from the reg_position to the end
          TinyWireS.send(i2c_regs[i]);
        }

        // Increment the reg position on each read, and loop back to zero
        reg_position++;
        if (reg_position >= reg_size)
        {
            reg_position = 0;
        }
    }//End i2cRequestEvent

    /*
     * Helper functions
     */
    void led_update()
    {
      cRGB val;
      val.r = i2c_regs[0x01];
      val.g = i2c_regs[0x02];
      val.b = i2c_regs[0x03];
      led.set_crgb_at(0, val);
      led.sync(); // Sends the value to the LED
    }


body:
Good day community, I have a project which is VEHICLE GPS Tracker and I'm using Arduino Mega, NEO GPS6MV2 and SIM900. I'm using SIM900 to send the GPS coordinates on a web server. I'm using the POST method and SIM900 is capable of this by using AT commands. I will also save the coordinates on a MySQL database.
My problem here is I can't send the data on the MySQL database. As you can see on the latter part of the commands, it response "ERROR". [![enter image description here][1]][1] That's why the coordinates failed to enter on the database. This is what I have on the database: [![enter image description here][2]][2]What do you think is the problem here?

  [1]: https://i.stack.imgur.com/jZvtl.png
  [2]: https://i.stack.imgur.com/y5ORK.png

title: ERROR on SIM900AT comand HTTPDATA (POST method)

Answers: 1

body:
1. If you say you are going to send 90 characters you **must** send 90 characters. No more, no less. I count 70 there.
2. You have to send them immediately the modem responds `DOWNLOAD` otherwise it times out (10 seconds) and you get `ERROR`. It looks to me like you're not sending anything (except maybe a blank line) for those 10 seconds and only trying to send once it has errored.


body:
I'm driving a stepper rated at 5V/1.7A using an A4988-based driver circuit with a 12V power supply.  An Arduino controls the stepping sequence.

According to the datasheet for my A4988, I should be calculating Vref as:

Imax = Vref / (8 * Rs)  so,

Vref = I * (8 x Rs) (where Rs is 0.1 ohm on this particular board and confirmed with meter).

So, Vref should be (1.7A x .8) or 1.36V to drive 1.7amps.

The problem is, I cannot adjust the A4988 to get Vref up that high.

With the adjustment pot full swing, the best I can get is .9 to 1V.  When I energize and hold the motor and use an amp meter, the coil is drawing about .9 amps -- which is still less than the 70% of 1.7 Amps I would like (using full-step mode).

Is Vref potential limited by the input voltage of 12 volts?  Is there something else I'm missing?

Thanks in advance.

Added:  This is the circuit I am using:
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/riJAo.png

title: A4988 Vref too low

Answers: 1

body: You have a 30K resistor divider in series with the trimmer. Change the 30K resistor for one rated at 27K to obtain those higher values. ;)


body:
Let's say I have one MQ5 gas sensor at home and one MQ135 gas sensor at the park. They are wirelessly hooked to Arduino.

My questions are:

Can Arduino post the data from two or more sensors to one Google Spreadsheet and organize it in two different charts?

Can only one Arduino accomplish this?

If not, what are the alternatives?

title: Can Arduino post multiple sensor data to one Google Spreadsheet?

Answers: 1

body:
Not directly but with addon service like Pushingbox, temboo and so on it can.

If you google on your topic there are a ton of ways to do it!


body:
I have two temperature sensors, an MCP9808 and a DS18B20, connected to an arduino and I've read that it could be advantageous to set a small delay between temperature readings. What I wonder is where I should set the delay, in the setup function:

    tempsensor.begin();                           //initialize communication with mcp9808
    sensors.begin();                              //initialize communication with dc18b20
    readSensors();

or the readSensors function?:

    temp = tempsensor.readTempC();              //read current temperature and save value inside "temp"
    sensors.requestTemperatures();              // Send the command to get temperatures
    temp2 = sensors.getTempCByIndex(0);

As you can probably tell I am very new to all of this, intuition tells me that I should set the delay within the readSensors function.

Any alternative suggestions about how I should be readings temperature data from two different sensors connected to one arduino would be appreciated.

EDIT

after re-reading question and based on first answer I haven't made it unequivocally clear my intention; I want to delay the time between the mcp9808 and the ds18b20 temperature readings, so that it waits X seconds between each. I have read that this may help to reduce noise.

title: 2 sensors, add delay between each reading

Answers: 2

body:
>  I've read that it could be advantageous to set a small delay between
> temperature readings

Although temperature is typically a measure that changes slowly in time, there is nothing in programming/device side preventing you from making readings in short intervals; unless this added time is necessary to prevent issues on other tasks, but so it should be not related to that.

body:
The essence of your question is actually about managing processor to processor communications.  As the temperature sensors you have chosen appear as peripheral processors which communicate to your processor over SMBus (MCP9808) or 1-Wire bus (DS18B20).

Both temperature sensors actually abstract you from the details of (likely) thermistor Analog to Digital Conversion (ADC) sampling and (likely) exponential averaging over multiple samples in order to reduce noise by providing a digital communication interface.  As you can see, there may be many steps taken before the temperature data is available over the digital communication interface.  Each step takes a finite amount of time.

In almost all cases there is a microprocessor busy at work inside the temperature probe.  How well that processor's code is written dictates how much you can (skip reading the [MCP9808][1] and [DS18B20][2] specification sheet(s) and) "abuse" the protocol.

If you ask for the data faster then the temperature probe can obtain a new sample, in the best case, it is likely you will be supplied with duplicate values or values clearly designated as errors.  In the worst case, you may get back incorrect values indistinguishable from normal values.  Read the specification sheets and consider the source of the parts.

All this said, it may be that the 2 libraries you have chosen to use are not compatible.  Yes, one library is using the SMBus / I2C approach and the other is using the 1-Wire bus approach.  However, if both libraries use any single Arduino resource (for example a hardware timer or a hardware interrupt) at the same time, they may interfere with one another.

To test this, comment out the instantiation and code for one of the approaches and see if the other begins working as you expected in the first place.  Then repeat the experiment commenting out the other.

In the end, it is almost always better to use as few libraries as possible when assembling software for an Arduino.  There may be some effort to make some libraries work together.  But it is impractical to test all library combinations.  For this specific case, using several temperature devices of the same type (all using the same serial bus) and assigning different addresses to each would allow you to restrict your self to only including / using one library.

  [1]: http://www.microchip.com/wwwproducts/en/en556182
  [2]: https://datasheets.maximintegrated.com/en/ds/DS18B20.pdf


body:
I'm currently working on a project in which I'm supposed to make an Arduino car dodge any kinds of obstacles. I know how to do without using Interruptions but as I was searching online I found out that this is something that is used and would turn out better. Is it really possible? And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object. I know that it is supposed to be the first thing it will do if I program it that way but, can I program how the Interrupt will act upon the machine? And if so, how exactly?

Thanks

title: Using Interrupt on Arduino

Answers: 3

body:
Interrupts help if an event needs to be dealt with over the time period of a few processor clock cycles. Such as the deployment of air bags.  If the accumulated delay of not responding in a few processor clock cycles adds up to considerable error.  Such as a Real Time Clock (RTC). Or, if an event is so short that it might be missed during periodic polling (checking). Such as counting flashes of lighting during a storm.

If this type of response time is not needed, interrupts may be more trouble than they are worth.

This is because interrupts can stop the processor from executing the normal program and force it to execute the interrupt program.  This can be very confusing to new programmers.  At any moment an interrupt may stop their program and possibly erase or change what that program was working on.  Both the program that is running and the interrupt program need to be written to tolerate this processor behavior.

It is almost always easier to "poll" the state of obstacle sensors (in this case) rather than tying its state to an "interrupt".  Using the Arduino paradigm, the purposes of the loop() entry point is to do just this.  A function which will be called over and over again.  Each time it is called you can "poll" the sensor and cause the model car to vier around an obstacle.

body:
See https://arduino.stackexchange.com/questions/30968/how-do-interrupts-work-on-the-arduino-uno-and-similar-boards/30969#30969

>  I was searching online I found out that this is something that is used and would turn out better. Is it really possible?

That's very vague. *What* did you find online?

> And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object.

Set a flag in the interrupt, which you detect in your main loop. In the main loop make the car stop when the flag becomes true.

body:
> Is it really possible?

anything is possible.

> And if so, I don't exactly grasp the concept of using it to make (for example) the car stop once it senses an object.

all an interrupt does is to take the execution to a different place. in practical terms, an interrupt would execute some quick functions and set some flags for the main loop to execute.

interrupts are critical to embedded engineering and it is very difficult for a real-world code to run without interrupts.


body:
I'm trying to incorporate audio into my Arduino project for the first time, and have been have a lot of issues. I originally couldn't get the Audio library to work, but after installing it through the Arduino application, I figured the Audio.h library would work fine. However, it spit out this error:

> WARNING: library Audio claims to run on (sam) architecture(s) and may be incompatible with your current board which runs on (avr) architecture(s).
In file included from /Documents/Arduino/libraries/Audio/src/Audio.h:16:0,
                 from /Documents/Arduino/boxgame/boxgame.ino:1:

Then it lists plenty of syntax issues, none of which have to do with my code. I think it's giving errors from the library, but I'm not really sure what's happening. Here's an example of one of the slew of errors:

> /Users/tschadius/Documents/Arduino/libraries/Audio/src/DAC.h:37:2: error: 'IRQn_Type' does not name a type
  IRQn_Type isrId;

Any ideas as to how I can fix this? The error message goes on for quite a while, but none of them appear to be from my code that I've written.

Thanks!

title: Audio.h Library Issues

Answers: 1

body:
Occasionally people do not realize how many platforms the Arduino paradigm has been ported to.  In almost all cases the ported to platform far exceeds the features found on an Arduino Uno.  So there exists a considerable amount of software that can not run on an Arduino Uno or on an Arduino Uno with out additional hardware.  But, usually, such software is surrounded by "text", "web-pages" and other "readme"  type files explaining the situation.

For the [Arduino Audio library][1], the web-page says this:

> Audio
>
> Compatible with Arduino Due only
>
> The Audio library enables an Arduino Due board to play back .wav files
> from a storage device like an SD card.
>
> The Due uses the DAC0 and DAC1 pins to play sounds.

  [1]: https://www.arduino.cc/en/Reference/Audio


body:
I've done a Wifi radio with a headless Raspberry Pi in the past (connecting a radio MP3 stream available on internet directly on boot, without any user input), and now I'm wondering: would it be possible to do the same with an Arduino, battery-powered?

Please correct me if I'm wrong but it seems that all these features are available:

1. battery-powered: this is definitely possible with a few AAs

2. audio output (easily possible with a DAC I think?)

3. Wifi (possible with a shield, right?)

4. Internet access to http://198.51.100.0/myradio.mp3 stream

5. real-ime MP3 stream decoding (Is an Atmega enough for this?)

**Does this mean that a Wifi radio based on Arduino is possible?**

title: Wifi radio with an Arduino

Answers: 0


body:
I use an ATSAMD21E16B-AU in my circuit and I want to upload the bootloader with the SAM-BA flash programming tool in this official link:
http://www.atmel.com/Images/Atmel-42366-SAM-BA-Bootloader-for-SAM-D21_ApplicationNote_AT07175.pdf.

I will use that directly with USB cable signals D+, D-, 5V, GND (SAMD microprocessor has internal USB serial hardware and D+ D- pins)

Before I try to upload it, it needs to appear in Device Manager on Windows as a "COM port" with EDBG driver. Because it didn't, SAM-BA doesn't show any COM port as EDBG in the "Select the connection" section.

Can I burn a bootloader to ATSAMD without an JTAG device? For example, I want learn if I can do that with Arduino Zero?

title: COM port problem when uploading bootloader to SAMD21G

Answers: 0


body:
[![enter image description here][1]][1]

I am new to Arduino and I have written code that makes 3 LEDs blink while the push button is off, so the lights are blinking from left to right (1,0,0)(0,1,0)(0,0,1) and then repeat from left to right.

Now I am trying to modify this code so that whenever the system receives a High from the switch it reverses the order, so it should start blinking from right to left and keep blinking that way until I press the push button and then return to left to right.

I hope my issue is clear. I only know how to use the if & else.

Here is my code:

    int switchState;
    int switchst = LOW;
    int d=LOW;

    void setup() {
      pinMode(3,OUTPUT);
      pinMode(4,OUTPUT);
      pinMode(5,OUTPUT);
      pinMode(2,INPUT);
    }

    void loop() {
      switchState = digitalRead(2);
      if (switchState == HIGH) {
        d= ~d;
        if(d==LOW) {
        digitalWrite(3,~switchst);
        digitalWrite(4,switchst);
        digitalWrite(5,switchst);
        delay(200);
        digitalWrite(3,switchst);
        digitalWrite(4,~switchst);
        digitalWrite(5,switchst);
        delay(200);
        digitalWrite(3,switchst);
        digitalWrite(4,switchst);
        digitalWrite(5,~switchst);
        delay(200);
      }  else {
        digitalWrite(3,switchst);
        digitalWrite(4,switchst);
        digitalWrite(5,~switchst);
        delay(200);
        digitalWrite(3,switchst);
        digitalWrite(4,~switchst);
        digitalWrite(5,switchst);
        delay(200);
        digitalWrite(3,~switchst);
        digitalWrite(4,switchst);
        digitalWrite(5,switchst);
        delay(200);
      }
    }

The problem with this code is that it doesn't keep blinking if I release the push button.

This is the old code. It only goes from left to right and keeps repeating.

    int switchState = 0;
    int switchst = LOW;

    void setup() {
      pinMode(3,OUTPUT);
      pinMode(4,OUTPUT);
      pinMode(5,OUTPUT);
      pinMode(2,INPUT);
    }

    void loop() {
      switchState = digitalRead(2);
      if (switchState == switchst) {
        digitalWrite(3,~switchst);
        digitalWrite(4,switchst);
        digitalWrite(5,switchst);
        delay(200);
        digitalWrite(3,switchst);
        digitalWrite(4,~switchst);
        digitalWrite(5,switchst);
        delay(200);
        digitalWrite(3,switchst);
        digitalWrite(4,switchst);
        digitalWrite(5,~switchst);
        delay(200);
      } else {
        digitalWrite(3,switchst);
        digitalWrite(4,switchst);
        digitalWrite(5,switchst);
      }
    }

  [1]: https://i.stack.imgur.com/XiK8l.png

title: Changing the order of blinking LEDs with the push of a button

Answers: 2

body:
The easiest is to use a 'mode', which is a boolean that keeps the state if it is blinking right, let's call it blinkToRight. Initially this is true.

An if statement will be used to change the order.

So the program will be something like (not tested):

global:

    bool blinkToRight = true;

in Setup:

    pinMode(3,OUTPUT);
    pinMode(4,OUTPUT);
    pinMode(5,OUTPUT);
    pinMode(2,INPUT);

In Loop:

    // Check if loop is reversed
    blinkToRight = checkReverse();

    if (blinkToRight)
    {
       show(true, false, false);
       show(false, true, false);
       show(false, false, true);
    }
    else
    {
       show(false, false, true);
       show(false, true, false);
       show(true, false, false);
    }

    void show(bool led1, bool led2, bool led3)
    {
       digitalWrite(2, led1);
       digitalWrite(3, led2);
       digitalWrite(4, led3);
       delay(200);
    }

checkReverse will check the input button and returns true if the mode should be reversed.

However, you cannot simply check for the button state. The problem is bouncing. But check in the Arduino examples to a debounce example for this problem and the program should work as expected.

See example: [Debounce example][1]

  [1]: https://www.arduino.cc/en/Tutorial/Debounce

Since only one led will be on, you can also use the following functions for Loop and show:

In Loop:

    // Check if loop is reversed
    blinkToRight = checkReverse();

    if (blinkToRight)
    {
       show(3);
       show(4);
       show(5);
    }
    else
    {
       show(5);
       show(4);
       show(3);
    }

Show:

    void show(int ledOn)
    {
       digitalWrite(ledOn == 3);
       digitalWrite(ledOn == 4);
       digitalWrite(ledOn == 5);
       delay(200);
    }

And it's even better to use constants:

    const int LED1   = 3
    const int LED2   = 4
    const int LED3   = 5
    const int BUTTON = 2

Setup:

    pinMode(LED1  , OUTPUT);
    pinMode(LED2  , OUTPUT);
    pinMode(LED3  , OUTPUT);
    pinMode(BUTTON, INPUT);

Loop

    // Check if loop is reversed
    blinkToRight = checkReverse();

    if (blinkToRight)
    {
       show(LED1);
       show(LED2);
       show(LED3);
    }
    else
    {
       show(LED3);
       show(LED2);
       show(LED1);
    }

Show:

    void show(int ledOn)
    {
       digitalWrite(ledOn == LED1);
       digitalWrite(ledOn == LED2);
       digitalWrite(ledOn == LED3);
       delay(200);
    }

body:
In my opinion, there are two things I'd change. The first one is that delay functions should be avoided whenever possible, the other is that the switch bounces.

In order to solve the bounces, you will have to wait some time to stabilize the signal:

 if (debouncedValueOfButton != (digitalRead(button_pin) == HIGH))
 { // Is there a change?
  if (((byte)currMillis) - lastMillisForButton) >= millisButtonDebounce)
  { // Yes, without bounces
   debouncedValueOfButton = !debouncedValueOfButton;
   if (debouncedValueOfButton)
   { // Rising edge
    if (increment > 1)
     increment = 1; // Go in one direction
    else
     increment = 2; // Go in the other direction
   }
  }
 }
 else
  lastMillisForButton = (byte)currMillis;

So, if the value is different from the one I think it is I'll wait for some milliseconds; if it is stable then I change the value I think it is.

As for removing the delay, I think it is better to use an approach similar to the "blink without delay" sketch:

 if ((((uint16_t)currMillis) - lastMillisForBlink) >= millisBetweenBlinks)
 {
  lastMillisForBlink += millisBetweenBlinks;
  currentLed = (currentLed + increment) % 3;

  digitalWrite(led0_pin, currentLed == 0);
  digitalWrite(led1_pin, currentLed == 1);
  digitalWrite(led2_pin, currentLed == 2);
 }

In this implementation, you use a variable increment to decide whether you have to go forward or backwards; when increment is 1 the led to be colored are `0 -> 1 -> 2 -> (3)0 -> 1 ...`; when it is 2 the led are `0 -> 2 -> (4)1 -> (3)0 -> 2 ...`.

The complete code is (DISCLAIMER: NOT TESTED)

    const byte led0_pin = 3;
    const byte led1_pin = 4;
    const byte led2_pin = 5;
    const byte button_pin = 2;

    int8_t currentLed, increment;
    unsigned int lastMillisForBlink;
    const unsigned int millisBetweenBlinks = 200;

    bool debouncedValueOfButton;
    byte lastMillisForButton;
    const byte millisButtonDebounce = 50;

    void setup() {
     pinMode(led0_pin,OUTPUT);
     pinMode(led1_pin,OUTPUT);
     pinMode(led2_pin,OUTPUT);
     pinMode(button_pin,INPUT);

     increment = 1;
     currentLed = 2; // At first run, currentLed will be increased by 1, so it starts at 0
     lastMillisForBlink = millis() - millisBetweenBlinks; // trigger a refresh at first loop

     debouncedValueOfButton = (digitalRead(button_pin);
    }

    void loop() {
     unsigned long currMillis = millis();

     if ((((uint16_t)currMillis) - lastMillisForBlink) >= millisBetweenBlinks)
     {
      lastMillisForBlink += millisBetweenBlinks;
      currentLed = (currentLed + increment) % 3;

      digitalWrite(led0_pin, currentLed == 0);
      digitalWrite(led1_pin, currentLed == 1);
      digitalWrite(led2_pin, currentLed == 2);
     }

     if (debouncedValueOfButton != (digitalRead(button_pin) == HIGH))
     { // Is there a change?
      if (((byte)currMillis) - lastMillisForButton) >= millisButtonDebounce)
      { // Yes, without bounces
       debouncedValueOfButton = !debouncedValueOfButton;
       if (debouncedValueOfButton)
       { // Rising edge
        if (increment > 1)
         increment = 1; // Go in one direction
        else
         increment = 2; // Go in the other direction
       }
      }
     }
     else
      lastMillisForButton = (byte)currMillis;
    }


body:
I'm a beginner with Arduino. I managed to grasp the basic understanding and try to use each component/shield that came with my Arduino kit.

I'm unable to use the following component:

 - Step Motor 28BYJ-48
 - Step Motor controller board ULN2003APG

I connected the Arduino to the ULN2003APG and put some coding such that I can see that the ULN2003APG's LED turned on from 1, 2, 3, 4, 1, 2, 3, 4, and so on. So this is as expected as per programming below.

**My issue:**

 1. I noticed the LED in the ULN2003APG is not as bright as a regular
    LED.
 2. Once I plugged in the 28BYJ-48 to the ULN2003APG, the ULN2003APG's LED all off.
 3. The motor (28BYJ-48) doesn't spin - at all.
 4. I tried to spin the motor with my 2 fingers, it seems pretty heavy - is this normal?

**Is this a faulty ULN2003APG or is it a faulty 28BYJ-48 or is it a faulty programming? please help.**

Program:

    #include <Stepper.h>

    int pin1=8;
    int pin2=9;
    int pin3=10;
    int pin4=11;
    int _step=0;
    void setup() {
        Serial.begin(9600);
        pinMode(pin1, INPUT);
        pinMode(pin2, INPUT);
        pinMode(pin3, INPUT);
        pinMode(pin4, INPUT);
    }

    void loop() {
      switch (_step){
        case 0:
          digitalWrite (pin1, HIGH);
          digitalWrite (pin2, LOW);
          digitalWrite (pin3, LOW);
          digitalWrite (pin4, LOW);
          break;
        case 1:
          digitalWrite (pin1, LOW);
          digitalWrite (pin2, HIGH);
          digitalWrite (pin3, LOW);
          digitalWrite (pin4, LOW);
          break;
        case 2:
          digitalWrite (pin1, LOW);
          digitalWrite (pin2, LOW);
          digitalWrite (pin3, HIGH);
          digitalWrite (pin4, LOW);
          break;
        case 3:
          digitalWrite (pin1, LOW);
          digitalWrite (pin2, LOW);
          digitalWrite (pin3, LOW);
          digitalWrite (pin4, HIGH);
          break;
      }
      _step ++;
      if (_step == 4){
        _step = 0;
      }
      Serial.println(_step);
      delay(250);

    }

title: Cannot spin motor 28BYJ-48 with controller board ULN2003APG

Answers: 1

body:
What happens if you change

    pinMode(pin1, INPUT);
    pinMode(pin1, INPUT); // Pin 2 ?
    pinMode(pin3, INPUT);
    pinMode(pin4, INPUT);

to

    pinMode(pin1, OUTPUT);
    pinMode(pin2, OUTPUT);
    pinMode(pin3, OUTPUT);
    pinMode(pin4, OUTPUT);

Answer for Q1 - Q3. You are using pinMode as an input. Using digitalWrite() on an INPUT will enable (HIGH) or disable (LOW) the internal pullup resistor on the input pin. The pin will not be able to "source" enough current to operate the stepper motor.

A4. The stepper motor has a "mechanical" 1/64 gear ratio. This is why it is hard to turn by hand.

Here are 2 pages that will help you to understand the issue: https://www.arduino.cc/en/Reference/PinMode and https://www.arduino.cc/en/Reference/DigitalWrite.


body:
I am programming my arduino with the capability to keep time with the DS3231 from Adafruit. I do not have the module yet, but am trying to figure out the rest of the build without it.

However, it seems like the way to determine RTC is working does not work, as it returns true, even without the module.

Example code from the Adafruit RTC library for using this module:

    // Date and time functions using a DS3231 RTC connected via I2C and Wire lib
    #include <Wire.h>
    #include "RTClib.h"

    RTC_DS3231 rtc;

    char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

    void setup () {

    #ifndef ESP8266
      while (!Serial); // for Leonardo/Micro/Zero
    #endif

      Serial.begin(9600);

      delay(3000); // wait for console opening

      if (! rtc.begin()) { // part that fails. begin() returns true when should return false
        Serial.println("Couldn't find RTC");
        while (1);
      }

      if (rtc.lostPower()) {
        Serial.println("RTC lost power, lets set the time!");
        // following line sets the RTC to the date & time this sketch was compiled
        rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
        // This line sets the RTC with an explicit date & time, for example to set
        // January 21, 2014 at 3am you would call:
        // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
      }
    }
    ....

title: Adafruit RTC begin() not returning false

Answers: 2

body:
If you look at the library source code it will be clear why `begin()` returns true.

From https://github.com/adafruit/RTClib/blob/1.2.0/RTClib.cpp#L434-L437:

<!-- language: lang-cpp -->

    boolean RTC_DS3231::begin(void) {
      Wire.begin();
      return true;
    }

I suppose they plan to eventually make the return value of `begin()` mean something but for now it does not.

body:
This should not happen anymore.

Actually, if you have a look at the last version of the source code on GitHub (1.13.0), you will see that now the developers implemented also a case in which the method returns false.

from https://github.com/adafruit/RTClib/blob/1.13.0/RTClib.cpp#L1537-L1543 :

```
boolean RTC_DS3231::begin(void) {
  Wire.begin();
  Wire.beginTransmission(DS3231_ADDRESS);
  if (Wire.endTransmission() == 0)
    return true;
  return false;
}
```


body:
I want to have two RF transceivers communicate, one as transmitter and one as a receiver, for longer distances. For that I'm using WIR 1186 RF modules with Arduino.

Pin connections are as below:

 - Arduino :5v,gnd,RX,TX,2,3
 - WIR1186 :VCC,gnd,Tx,Rx,prg,cts

But Arduino is not serially communicating with the WIR1186 module.

Below is the code:

    char ch;
    int prog = 2;
    int cts = 3;
    int stat;
    unsigned int output;

    void setup() {
      Serial.begin(9600);
      pinMode(prog, OUTPUT);
      digitalWrite(prog, LOW);
      stat = digitalRead(prog);
      Serial.println(stat);
      Serial.write("B=9600\r\n");
      output = Serial.read();
      Serial.println(output);
      digitalWrite(cts, HIGH);
    }

    void loop() {
      Serial.write('a');
      delay(1000);
    }

[Here is the datasheet of WIR1186][1]

Please help me out with this.

  [1]: http://robokits.download/datasheets/WIR-1186_RobokitsIndia.pdf

title: How to make two WIR 1186 RF transceivers communicate over serial communication?

Answers: 2

body:
If you use pin 2 and 3 for serial communication you have to use [SoftSerial][1], because Serial is hardwired to pin 0 and 1.

  [1]: https://www.arduino.cc/en/Reference/SoftwareSerial

body:
Two things are wrong:

1. You aren't setting PROG to HIGH to enable transmit mode - you are stuck in programming mode.
2. CTS is an *output from the module to an input on the Arduino*. You don't set it high - you look to see what level it is to see if it is safe to send more data.

To quote from the datasheet you link to:

> The WIR-1186 offers data flow control hardware to allow for zero data over-run and loss when sending large
files and data packets. The internal data buffer on the WIR-1186 module is 128bytes. When the data terminal1
sends a large file for wireless transmission the module2 will except 128bytes and then set the CTS pin LOW to
alert the data terminal to wait for the CTS to back HIGH before sending more data over UART.

(footnotes mine)

Also you *cannot* use pins 0 and 1 for serial if you are at the same time using them for USB debugging. You will either have to move to another pair of pins and use `SoftwareSerial`, or invest in a better Arduino with more than one UART.

Another thing of importance: If your WIR-1186 isn't on some kind of carrier board with voltage regulator and logic level translation it's safe to say that you have killed it. Well done.

> # Warnings
> * **The maximum allowable voltage on any of the interface pins with respect to GND is 3.6V**
> * **The maximum input voltage VCC with respect to GND is 3.6V**
> * The baud rate setting in configure mode is fixed 9600bps
> * Do not leave the UART_TX input pin of the module open. The module will send junk data on thewireless channel. It must be pulled up to VCC if not used.

----

1 Arduino
2 WIR-1186


body:
I suppose Arduino Mega ADK acts as the USB host for the connected smartphone.

Is it capable of providing power to the smartphone?

title: Can Arduino Mega ADK charge connected smartphone?

Answers: 1

body:
If you [read the documentation](https://store.arduino.cc/arduino-mega-adk-rev3), you will see this paragraph:

> NB: Because the MEGA ADK is a USB Host, the phone will attempt to draw power from it when it needs to charge. When the ADK is powered over USB, 500mA total is available for the phone and board.The external power regulator can supply up to 1500mA. 750mA is available for the phone and MEGA ADK board. An additional 750mA is allocated for any actuators and sensors attached to the board. A power supply must be capable of providing 1.5A to use this much current.

So yes (though slowly), if you connect it to a suitable power supply.


body:
We have an installation that provides:

- a common line (C), which divides into two wires;
- an input line (I), which carries the signal from a button (between I and C there's normally 0V, and 12V when the button is pressed);
- an output line (O), which carries a signal to a bell (between O and C there's always 12V).

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/mfxgB.png)

<!-- End schematic -->

A controller is to close the OC circuit every time a given temporal pattern shows in I (say, a concrete Morse-like -short/long- sequence of pulses), so the bell will ring if the concrete word is recognized at the input. Such a controller has been implemented in C++ and uploaded to an Arduino Nano, and it works fine on a protoboard, with a button as input and led as output, all in the same electrical range.

Since both the IC and the OC are 12V circuits, and the controller is in the 5V range, what is the *minimal circuit* to embed the controller between the IC and the OC circuits?

title: How to embed a 5V-range Arduino-based controller in a 12V-range DC circuit?

Answers: 3

body:
Just use a **transistor that can handle 12**V with the base connected to the Arduino and that's it...

Maybe I didn't get what you were trying to say, but anyway, I think that's what you are looking for.

body:
I think you can use "mosfet" control 12v with 5v voltage also if you think this is insufficient you can add the relay, control relay with mosfet without how much voltage as you want.
I made disco lights with rgb strip led and when I run the circuit different time and different type of led turn on and turn off I used 3 mosfets and 3 arduino outputs the strip led work with 12v.

body:
easy:

1) use a transistor's b-c junction;

2) use a mosfet;

3) use a relay, solid state or mechanical;

4) find a chip with 12-compliant pins;

...


body: I have bought an Arduino Primo board. I have configured it to connect to my wifi router and changed it to STA mode. Now, how do I program it to send HTTP requests to a server? Which library file I should use? Any tutorial?

title: How to send HTTP requests using wifi of Arduino Primo board?

Answers: 1

body:
With Arduino Primo use the WiFi Link library. Look at WiFi Link Examples in IDE menu.

[Arduino org web archive pages][1]

  [1]: https://web.archive.org/web/20170711112326/http://www.arduino.org/products/boards/arduino-primo


body:
I have an Arduino Due with an Arduino Ethernet Shield V2 that I use to control multiple daisy-chained [WS2811 LED strips][1].

When I turn on most of the LEDs the Arduino and attached wires seem to become an antenna, picking up fluctuations that make the LEDs flicker, by messing with the data on the WS2811 data line. Touching the data cable, touching the ethernet plug on the shield, or simply hovering my hand over the Arduino adds noise that causes flickering in the lights.

When I pull out the ethernet plug, it stops. (The Arduino continues to update the WS2811 chips, even without network connection)

[![My setup][2]][2]

The flickering is especially strong when I set the first couple of LEDs in the chain to White (biggest draw of current), while having red or green colored LEDs at the beginning causes milder flickering (even if there are LEDs set to White further back in the chain).

Some more observations:

- The LED strips are powered from both sides. It doesn't seem to be a power issue.

- I tried with a different Arduino Due, a different Ethernet shield, a different router and Ethernet cable, and a different power supply.

- The router the Arduino is plugged into, is positioned on the same table, and powered from the same power bar as the LED/Arduino power supply.

- I tried running the Arduino and the LEDs from different power supplies but that didn't help. Rather the opposite (which makes sense)

- This happens no matter how long the equipment has already run or how hot it is.

Another mystery:
You might notice the lose ground cable from the LED strip connector. When I plug that into the Arduino Due, the LEDs don't get turned on at all. When I plug that ground cable into the Ethernet shield sitting on the Due, then some lights turn on wrong. No matter if Ethernet is plugged in or not (though there's a difference in the 'wrongness' of the lights when Ethernet is plugged in). Note, that the Arduino and the LED strips already share ground 1 foot away as they are both fed by the same 12V power supply.

Where are all these grounding issues coming from and how do I get rid of them? What else could I try?

  [1]: https://www.aliexpress.com/item/5m-DC12V-Black-PCB-30-48-60-leds-m-10-16-20-ws2811-ic-meter-10/2000165819.html?spm=2114.search0104.3.1.7XDXC9&ws_ab_test=searchweb0_0,searchweb201602_3_10152_10065_10151_10130_10068_5400015_10307_10137_10060_10155_10154_10056_10055_10054_5370015_10059_100031_10099_9912_5380015_10103_10102_5410015_5430015_10052_10053_10142_10107_10050_10051_10084_10083_10080_10082_10081_5390015_10178_10110_10111_10112_10113_10114_10312_10313_10314_10315_10078_10079_10073_5420015-10050_9912,searchweb201603_1,ppcSwitch_7&btsid=48e1d9dd-a72a-491a-86d6-0224a80abeae&algo_expid=efcfa1d7-98cc-4bca-8311-843a896e1ca6-0&algo_pvid=efcfa1d7-98cc-4bca-8311-843a896e1ca6
  [2]: https://i.stack.imgur.com/slzg2.jpg

title: Grounding issues Arduino Ethernet Shield makes WS2811 LEDs flicker

Answers: 1

body:
I suspect that the signal driving the LED strip does not have enough voltage swing. And that ground noise/resistance is what makes the system sometimes appear to work correctly.

With 12 volt LED strips, the data signal into the WS2811 should swing at least 0.3x to 0.7x 12 volts, or below 3.6 volts (low) to above 8.4 volts (high).

The Arduino Due has output signals from 0 volts to 3.3 volts.

Which would explain the observation that if ground is connected directly between Due and LED then the Due output is never high enough to signal the LEDs.

I would try using a logic level converter between the Arduino Due output and the LED strip data input.


body:
When I try to upload a sketch to an Arduino Nano, it stays stuck on uploading, and after a time it shows the following error code:

 - stk500_getsync() attempt 1 of 10: not in sync: resp=0xc2
   stk500_getsync() attempt 2 of 10: not in sync: resp=0xc2
   stk500_getsync() attempt 3 of 10: not in sync: resp=0xc2
   stk500_getsync() attempt 4 of 10: not in sync: resp=0xc2
   stk500_getsync() attempt 5 of 10: not in sync: resp=0xc2
   stk500_getsync() attempt 6 of 10: not in sync: resp=0xc2
   stk500_getsync() attempt 7 of 10: not in sync: resp=0xc2
   stk500_getsync() attempt 8 of 10: not in sync: resp=0xc2
   stk500_getsync() attempt 9 of 10: not in sync: resp=0xc2
   stk500_getsync() attempt 10 of 10: not in sync: resp=0xc2

Sometimes the `resp=0xc2` variable changes to another hex code.

The weird thing here is that before this happened everything worked fine. I could upload and the serial communication was fine. But after trying to upload the same sketch with a different variable, this started to happen.

Windows recognizes the COM port, in Arduino the COM port is selected. Sometimes, without doing anything, the Arduino works fine again, I can see the serial communication fine, but after some time the serial communication stops sending and again I can't upload the sketch.

I have 2 Arduino Nanos. Both of them start presenting the same problem. But the other one has the Power, RX, and TX led always on and this one never worked again, like the other one that sometimes can upload the sketch and see the serial communication that the last sketch was sending. I have an Arduino Mega, this one has the ATmega16U2 to communicate to USB and this one works fine. And I also have a NodeMCU Lua, with CH341. But this one works just fine.

title: Arduino nano ATmega328p with CH341 won't upload

Answers: 2

body:
If you are using a fairly recent version of the Arduino IDE, try using the old bootloader for the 328P.
Go to Tools --> Processor:"ATmega329P" --> ATmega328P(Old Bootloader)

body: Open your device manager in computer if ot would show your arduino nano as USB 2.0 then you need to install CH340G DRIVERS from Google install it and then again connect it to the computer your problem would be solved but remember to remove TX and RX pins before uploading code...


body:
I need to make a car tracker powered from a car battery. The problem is the SIM800L needs to be powered with 3.8v to 4.2v, and at 2A preferably. I want to connect the car battery to my Mega first then the Mega powers the SIM800L.

So:

Car battery > Mega > SIM800L

What do I need to achieve this?

This is the SIM800L model:

[![This is the Sim800l][1]][1]

  [1]: https://i.stack.imgur.com/UozTk.jpg

title: Connecting Arduino Mega + SIM800L to a car battery

Answers: 2

body:
With this setup you are overstressing the onboard regulator, while wasting a lot of power (not suggested on a battery setup, even if the battery is quite big).

First of all, the power. You have a MEGA, which runs at 5V/few mA, and a SIM800L, which runs at 4V/2A. I suggest you to have two power supplies. On ebay you can find cheap XL4015 converters rated at 5A. You connect IN+ to the +12V, IN- to the ground, then set the first one to output 5V, while the other to 4V. If you want to have the most correct powering scheme connect the 5V to the USB port, otherwise connect it to the +5V pins (note that you will exclude the fuse).

Then there is another problem: the UART levels. As a first approximation you can hope that the arduino reads the correct levels, so you'll just have to lower the TX voltage from 5V to 3.3V. You can do this by using a voltage divider with a 4.7k resistor between arduino TX and SIM RX and a 10k resistor between SIM RX and ground (see, for instance, how they did it in [this image][1]).

  [1]: https://www.geeker.co.nz/images/detailed/2/SIM800L_V1_3.jpg

body:
> I want to connect the car battery

The Mega has an NCP1117 linear voltage regulator onboard. This is qualified for automotive use, however the max. output current at 12V input voltage is only 1A, which is too less to supply your SIM800.

Next thing you should consider: The car voltage is not stable. Voltage peaks up to 40V can occur, especially when starting the engine. This will stress your components, and destroy them in worst case.

I would use two DC/DC converters with high enough input voltage and adjust one to 7V output (for the Arduino), the other one to 4V (for the SIM) and connect the ground lines together.

For voltage level matching between Arduino and SIM Uart see page 32 of [SIM800 hardware manual][1].

  [1]: https://cdn-shop.adafruit.com/datasheets/sim800h_hardware_design_v1.00.pdf


body:
I'm trying to upload this code on ESP8266, and when I do, it just resets continuously.  This also happens when you have memory bugs, but obviously, this code has no memory bugs!  Here is the code:

    #include "Arduino.h"

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

    void loop()
    {

    }

    void foo(){
     for(unsigned int i = 1; i <= 10000; i++){
      Serial.println("FOOBAR");
     }
    }
Also, in the serial monitor, I get this (per reset):

    Soft WDT reset

    ctx: cont
    sp: 3ffef130 end: 3ffef390 offset: 01b0

    >>>stack>>>
    3ffef2e0:  feefeffe feefeffe feefeffe 00002580
    3ffef2f0:  0000001c 00000001 3ffe85b1 402023d4
    3ffef300:  feefeffe 00000005 3ffe842d 3ffee364
    3ffef310:  3fffdad0 00000006 3ffee340 40201fd1
    3ffef320:  3ffe85b0 00000000 3ffee340 40201fd1
    3ffef330:  3ffe8428 00000000 3ffee340 40201fec
    3ffef340:  00000001 feefeffe 3ffee340 40202010
    3ffef350:  feefeffe 00000000 00002580 40201c00
    3ffef360:  3fffdad0 00000000 3ffee35c 40201c2e
    3ffef370:  feefeffe feefeffe feefeffe 402021c8
    3ffef380:  feefeffe feefeffe 3ffee370 40100718
    <<<stack<<<
    Õ®(ŽL‰Ì== I5

So, why is this happening?

title: Why is there a limitation in using Serial.println on ESP8266?

Answers: 2

body:
It's happening because you're not giving the ESP8266 a chance to do its housekeeping activities and the watchdog (which is enabled by default) is timing out - as evidenced by the very first line of your output:

> Soft WDT reset

You need to allow the MCU to do other things at the same time as you are printing to serial:

    void foo(){
        for(unsigned int i = 1; i <= 10000; i++){
            Serial.println("FOOBAR");
            yield();
        }
    }

body:
With Arduino/ESP8266 you have to break your tasks in little pieces so `setup` and `loop` takes as little time as possible.

Your elemental tasks is executing one `Serial.println`. We first reformulate `foo` to run a single elemental task in each invocation. Then, we move the call to `loop`, so `setup` ends quickly. In `loop` we use the variable `iterations` to controls calls to `foo`. When it reaches zero it signal the end of the "setup" part.

    #include "Arduino.h"
    int iterations = 10000;
    void setup()
    {
        Serial.begin(9600);
    }
    void loop()
    {
      if (iterations > 0) {
        iterations--;
        foo();
      }
    }
    void foo(){
      Serial.println("FOOBAR");
    }

It can be tricky to break some big code in small parts, but it's something you must learn to do, because there is no other way.