message:
Operating system on Atmel 328 Arduino?

Is it possible to use some sort of multitasking OS like ScmRTOS on Arduino based on Atmel 328 chip?

body:
You can use FreeRTOS on the AVR family:

* http://www.freertos.org/a00098.html


sender: user

message:
Will I be able send a HTTP request using the Arduino Yún?

After spending countless hours trying to get my wifi module to work only to fail, I've decided I might as well get an [Arduino with built-in wifi][1].

Would I be able to send HTTP requests (GET, POST etc) straight out of the box or would I have to configure and connect some additional components/modules to the board?

Also, I plan on connecting a thermistor and a GPS module to the Arduino. When the thermistor reaches a certain level, it sends the GPS coordinates of my server. Is this possible in terms of practicality and voltage? And would I be able to write a sketch using the Arduino board or would I have to switch the board to something like 'Generic ESP8266 Module' (something we have to do if we want to program the ESP8266 using the Arduino IDE).

  [1]: https://www.amazon.co.uk/Arduino-A000008-Yun-Microcontroller/dp/B00MBCGWQQ/ref=sr_1_21?s=computers&ie=UTF8&qid=1506630245&sr=1-21&keywords=arduino wifi

sender: assistant

body:
Looking at your other two questions as well I see you have had limited success with a ESP8266.  I have never used a Yun, but I haven't seen much good stuff about them on here.  If you want a Linux based none real time system then you may as well get a PI.

Most people seem to think the way to use an ESP8266 is to hook it up to an Arduino and use it as a 'serial over wifi' link.  You can do that, but its like owning a Porsche and Kia and always using the Kia on Motorway journeys.  The ESP8266 is an 80MHz chip with 0.5 MByte of RAM, and you could program it in just the same way as an Arduino if you download the board support package.  It does have only 10 Digital pins and 1 Analog (which I think has lower resolution that the Arduino), but that's where the Arduino comes in.  If you need to hook up lots of pins, then stick the Arduino on the I2C bus as a slave to the ESP.

Now I suspect you have an ESP-01 board and are wondering what the [heck] I am talking about, 10 pins.  The number '01' is the number of GPIO pins that are taken to the edge of the board, so really you want to look at ESP-12E or ESP-13E boards (they still cost about the same $1).  You might want to look at a Wemos D1 or a Node MCU.  Both are fully fledge dev boards, jus plug in the USB and away you go.

So to answer your question:

Get a Wemos D1, hook the hardware up like you wood the Arduino (thermistor and GPS - via SoftwareSerial) and then either code a web server to run on the Wemos or Get it to Post message to you favourite server (see examples for details of either approach)


message:
What sensor is used to judge transparency?

I want to create a system to separate between an aluminum can and a plastic bottle.

Both are lightweight, so I'm thinking of using the transparency property, meaning that the can is not transparent, but the plastic bottle is.

Will the light sensor work out?

Or would you suggest me another type of sensor I should use?

body:
A light sensor should work. If the aluminium can reflect much light, you can consider putting the light and light sensor on the same side, close together.

If not, put the light and light sensor of opposite sides so the light beam goes through the bottle.


body:
A light sensor should work. Another option would be an inductive Sensor to detect the Aluminium Can. And if you need to know if there is a Can in your sensor area you can combine it with an IR (or capacitive) Sensor, which should detect both Can types.

So it would be something like this:

    if(IRdetect == true){
      if(inductive == true){
        type = alu;
      }else{
        type = plastic;
      }
    }else{
      // no Can
    }

Some cheap sensors as Example:

 - Inductive: [Banggood][1]

 - Infrared: [Banggood][2]

  [1]: https://www.banggood.com/Wholesale-NPN-DC-6-36V-Inductive-Proximity-Sensor-Detection-Switch-p-41603.html?rmmds=search
  [2]: https://www.banggood.com/Adjustable-Infrared-Proximity-Switch-Photoelectric-Detect-Sensor-NPN-p-1046453.html?rmmds=search


message:
Power source for arduino project

The project is to make a 4WD car using arduino uno(clone) and four toy dc motors. I am using a adafruit motor shield v1.2(clone). The car is required to run autonomously, please suggest batteries for the arduino and the shield.
Also when I am using external power connector for arduino, all the motors start at different timing.

body:
I've been using usb power packs.

 - Easy to source (can be found in all electronics stores and many general stores).
 - Come in many sizes (500mAh to 20,000 mAh are common).
 - Rechargable, usually by using a generic phone changer with a usb micro connector.
 - Not costly.
 - Quite roubust.
 - Most Arduino boards and many motor driver boards are designed to be powered from usb.

Make sure you get one that is rated for enough current for your project.


body:
Car batteries are wonderful, and almost never explode. A badly mistreated Li-{Fe,Po,Ion}, however... ouch. Otherwise use banks of NiMh/NiCd.

If you don’t fear death, use Li-Ion batteries with a TP4056 + DW01A IC, it can handle charging from USB, and provides over-discharge protection, so your batteries don’t die.
https://www.addicore.com/TP4056-Charger-and-Protection-Module-p/ad310.htm
It also has current limiting built-in.


message:
i2c wire length

I have some problems with i2c. I can not use long wires on SDA and SCK bus.

This seems to be the consequence of the capacity between the SDA and SCK wires and not between SDA/SCK and GND.

I figured this out by placing capacitors in a breadboard with a Arduino UNO and some MCP23017's (with 2k2 pull-up resistors).

100pF capacitor between SDA and SCK: No problem.

150pF: The communication stops.

1nF from SDA to GND and/or 1nF from SCK to GND: No problem.

A two wire cable is approx 50pF per meter, so 2 meters seems the limit.

With an ATtiny85 (8MHz clock, 100k i2c speed) as master it is even worse:
With 2k2 pull-up a capacity of 68pF is killing.

By reducing the pull-up resisters to 470E I was able to go up to 200pF  (hurray: 4 meters of wire).

Someone any idea how to increase the distance by tuning the SDA/SCK timing?

body:
As @majenko wrote, the I2C bus was not designed to go over wires or into a cable. It is ment for components on the same pcb board.
As @mikaelpatel wrote there are bus drives which convert the I2C signal into some kind of RS-485 signal for twisted pair cables.

The crosstalk between SDA and SCL should be avoided at all times. Don't put SDA and SCL into wires that are next to each other. When using twisted pair cable (for example Cat5), then use SDA in a different pair than SCL.
The worst situation is when SDA and SCL are next to each other in a flat ribbon cable.

The capacitance caused by the cable from SDA to GND and from SCL to GND can be compensated some by a lower value of the pullup resistors and by lowering the clock speed.

The maximum current is specified as 3 mA. That means with 5V, the lowest value for the pullup resistor is 1k6.
A little more can be achieved with a current driver of 3 mA instead of the pullup resistors. This is not often done, but it creates a better signal.

The Arduino Wire library for the Arduino Uno can be set to 50 kHz with Wire.setClock. I don't know the lowest value, but there is a limit without warning. I don't know the lowest clock speed for an Attiny microcontroller. A software I2C bus implementation can often go much lower.
*Note that some sensors have a minimum clock speed.*

The rule of thumb is that 50 cm is the maximum for the I2C wires. However, some say that they are able to use the normal I2C bus over 6 meters cable. My opinion is that the I2C should always work, since it is not very fault tolerant, and the Arduino Wire library for the Arduino Uno is not fault tolerant at all. Therefor, don't go near the limits.

The [MultiSpeedI2CScanner][1] (probably only working for Atmega chips) helped me a lot to learn about the I2C limits in different situations.

  [1]: https://github.com/RobTillaart/Arduino/tree/master/sketches/MultiSpeedI2CScanner


body:
With 2 shielded cables, separate for SDA, SCL no problem to go several meters.

I just connected 2 I2C devices on common shielded cables 6m long SDA, SCL
3.3V and GND on non-shielded cables

Successfully tried also computer mice shielded cables, it's about 1.5m working no problem

Pull up resistors approx. 4k7


message:
How To Communicate Three NodeMcu In Access Point Mode

I'm working on project which for example 3 nodemcu connected with eachother in a line(1 connected to 2 and 2 connected to 3) and they are all in access-point mode (they are all server) and now my problem is how to communicate between 1 to 2 and 2 to 3 i have tried tcp but its for server-client

any help would be appreciated

body:
Look at the WiFi library. The function WiFi.mode() can set your NodeMCU as access point, station or both access point and station (WIFI_AP, WIFI_STA, WIFI_AP_STA or WIFI_OFF).

In the mode WIFI_AP_STA, your NodeMCU works both as access point and as a station independently; no need for special considerations.

You still need to know the IP address of each NodeMCU to make them to talk to each other. You can configure things to get fixed IP for each NodeMCU as a station.


message:
HC-SR04 calibration conditions

As is known, the speed of sound depends of [temperature and Relative Humidity](http://www.rane.com/pdf/ranenotes/Enviromental_Effects_on_the_Speed_of_Sound.pdf). I'm trying to calibrate HC-SR04 sensor taking account these factors.

In [SparkFun page](https://www.sparkfun.com/products/13959) there is no mention about environmental conditions in calibration (only is informed that speed of sound is 340 m/s). I found [a paper](http://www.sciencedirect.com/science/article/pii/S221302091630163X) with some calibration, but again it is no mention of original conditions.

I'm using the time elapsed per response to calculate distance in Arduino with access to a temperature & humidity chamber, so I want to recreate the calibration conditions to probe if the sensor is accurate.

Anyone know the environmental conditions of HC-SR04 calibration?

body:
The HC-SR04 is not calibrated, nor does it take any measurements.

All it does is allow *software* on a connected microcontroller or system like an Arduino to measure the sum of the round trip time delay and some small internal offset delay, and from this calculate distance.

As the timing and calculation are entirely in *your* program, calibration is entirely up to you.

Under known conditions you could measure both a short and a long distance.  This would give you a slope and intercept - the slope from the speed of sound (which should not depend on the device at all, only on the conditions and your timing reference), and the intercept or offset, having to do with latencies in the system.

You could then cross-check at other distances, but under fixed conditions behavior should be linear.

As there is some initial ringing of the sender which can couple to the receiver and be mistaken for an echo, there will be a minimum distance below which you cannot reliably take a reading - as a guess, this is more than 5 cm, but you'll have to see, and it may even vary a little from unit to unit.

*To a degree, it's a little bit amazing that these even work.  They use an RS232 level shifter to generate transmit pulses, and it's been alleged that the receive circuit is horribly mistuned, not really matching the emitted frequency at all... but despite that they do seem to work fairly well*.


message:
Arduino with ATmega32U4 low power but keep Serial1 working

I am looking for a low power solution for my ATmega32U4. It uses Serial1 to communicate with Bluetooth, so I need to have it active. When I receive data from Serial1, I want to power up the Arduino, do some magic, and then power it off...

body:
For Power Down/Standby Mode you would have to use an Interrupt Pin to reactive the MCU. If you do not mind possible loss of the first character you could connect an Interrupt Pin to Serial1 RX and wake up on the first start bit.

The startup delay (i.e. time until UART is up and working) may impact the first character received. You could always start off by sending a number of null character as a "wake up call"; classical break sequence.

Cheers!

Ref. ATmega16/32U4, Chap. 7. Power Management and Sleep Modes.


message:
Problem with Dual Safety Switches Initiating Timed Relay

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);

    }

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.


message:
Need help with my urgent problem

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

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.


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

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.

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.


message:
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

<!-- 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());
    }

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.


message:
ESP8266-01 wrong flow control settings

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

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!


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

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);
      }

    }

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
    }


message:
ERROR on SIM900AT comand HTTPDATA (POST method)

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

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.


message:
A4988 Vref too low

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

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. ;)


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

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?

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!


message:
2 sensors, add delay between each reading

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.

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


message:
Using Interrupt on Arduino

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

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.


message:
Audio.h Library Issues

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!

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


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

[![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

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;
    }


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

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);

    }

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.


message:
Adafruit RTC begin() not returning false

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));
      }
    }
    ....

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;
}
```


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

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

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


message:
Can Arduino Mega ADK charge connected smartphone?

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

Is it capable of providing power to the smartphone?

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.


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

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?

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;

...


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

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?

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