body:
I am having trouble with this code:

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

    #include <Wire.h>
    #include <MPU6050.h>

    MPU6050 mpu;

    // Timers
    unsigned long timer = 0;
    float timeStep = 0.01;

    // Pitch, Roll and Yaw values
    float pitch = 0;
    float roll = 0;
    float yaw = 0;

    int button_pin=5;
    int button_state;
    void setup()
    {
      Serial.begin(115200);

      // Initialize MPU605
      while(mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
      {
        Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
        delay(500);
      }

      // Calibrate gyroscope. The calibration must be at rest.
      // If you don't want calibrate, comment this line.
      mpu.calibrateGyro();

      // Set threshold sensivty. Default 3.
      // If you don't want use threshold, comment this line or set 0.
      mpu.setThreshold(3);

      pinmode(button_pin,INPUT)
    }

    void loop()
    {
      int button_state=digitalRead(button_pin)

      timer = millis();

      // Read normalized values
      Vector norm = mpu.readNormalizeGyro();

      // Calculate Pitch, Roll and Yaw
      pitch = pitch + norm.YAxis * timeStep;
      roll = roll + norm.XAxis * timeStep;
      yaw = yaw + norm.ZAxis * timeStep;

      // Output raw
      Serial.print(" Pitch = ");
      Serial.print(pitch);
      Serial.print(" Roll = ");
      Serial.print(roll);
      Serial.print(" Yaw = ");
      Serial.println(yaw);

      // Wait to full timeStep period
      delay((timeStep*1000) - (millis() - timer));
    }

But when I add this code at the end:

    If (pitch <=90 && pitch => 15 && button_state =(HIGH))
    {
    }

I keep getting this error:

> error: lvalue required as left operand of assignment

I know the issue is about the pitch part of the if. I just need to know how to fix it.

title: Help with arduino float

Answers: 3

body:
You have two declarations of button_state.  This won't cause a problem because the scoping rules will mean inside loop you are using the local one and everywhere else you are using the global one.  Personally I would remove the global one since you aren't using it.

As mentioned in the comments you have mistyped the `If` keyword (but I think this is just on here not in you code) and you have used an assignment statement rather than a equivalence (= instead of ==).

Since you have tagged it as code review here are some minor points you might want to consider.

If a value doesn't change then you could mark it as `const`, this doesn't make much difference to the compiler, it already knows, but it will help you when you come back to the code next week.
  So: `const int button_pin = 5;`

If you only use a `const int` value **once** you might be better `#defining` it (more than once a const value *should* produce smaller code).  The pre-processor (part of the compile process) will replace the defined name with the value, but you have easier to read and maintain code.
  So: `#define button_pin 5`

If you `#define` an int then **always** enclose the value in brackets to protect it from "arithmetic issues" (I can't think of a better way of describing it).
  So: `#define button_pin (5)`

body:
In the if statement:

    if (pitch <=90 && pitch => 15 && button_state =(HIGH))

you assign a new value to button_state, which is illegal.

This should read:

    if (pitch <=90 && pitch => 15 && button_state == HIGH)

body:
The first thing I noticed was that you had a capital `I` in your if-statement.

Secondly, `button_state =(HIGH)` should be `button_state == HIGH`. A single `=` sign means that you are assigning a value to the variable on the left - in this case `button_state`. It is a common mistake that I have made many times.

Also, because it is a boolean comparison, you can simplify the statement by removing the `== HIGH` leaving just `button_state`.

This would then change the if-statement to the following:

    if ((pitch <= 90) && (pitch => 15) && button_state)

I have added extra parentheses for clarity/readability but they're technically not needed.

----------

In addition to what Code Gorilla has already stated in [his answer][1] and a few additional semi-colons, your code should look something like this:

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

    #include <Wire.h>
    #include <MPU6050.h>

    MPU6050 mpu;

    // Timers
    unsigned long timer = 0;
    float timeStep = 0.01;

    // Pitch, Roll and Yaw values
    float pitch = 0;
    float roll = 0;
    float yaw = 0;

    const int button_pin = 5;

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

      // Initialize MPU605
      while(mpu.begin(MPU6050_SCALE_2000DPS, MPU6050_RANGE_2G))
      {
        Serial.println("Could not find a valid MPU6050 sensor, check wiring!");
        delay(500);
      }

      // Calibrate gyroscope. The calibration must be at rest.
      // If you don't want calibrate, comment this line.
      mpu.calibrateGyro();

      // Set threshold sensivty. Default 3.
      // If you don't want use threshold, comment this line or set 0.
      mpu.setThreshold(3);

      pinmode(button_pin,INPUT);
    }

    void loop()
    {
      int button_state = digitalRead(button_pin);

      timer = millis();

      // Read normalized values
      Vector norm = mpu.readNormalizeGyro();

      // Calculate Pitch, Roll and Yaw
      pitch = pitch + norm.YAxis * timeStep;
      roll = roll + norm.XAxis * timeStep;
      yaw = yaw + norm.ZAxis * timeStep;

      // Output raw
      Serial.print(" Pitch = ");
      Serial.print(pitch);
      Serial.print(" Roll = ");
      Serial.print(roll);
      Serial.print(" Yaw = ");
      Serial.println(yaw);

      if ((pitch <= 90) && (pitch => 15) && button_state)
      {
          // Code goes here
      }

      // Wait to full timeStep period
      delay((timeStep*1000) - (millis() - timer));
    }

  [1]: https://arduino.stackexchange.com/a/45541/19409


body:
I am developing a system that reads data from an LM35 temperature sensor and forwards it to a web page using an Arduino Uno and a ESP8266 WiFi Module. The data flow is as follows:

`LM35 --> Arduino Uno --> ESP8266 (Having a web server) --> Webpage`

The Uno sends data to the ESP8266 every `SAMPLE_RATE` seconds (4 seconds in my example) but the ESP8266 keeps updating the web page as it is a dynamic web page running AJAX. The problem is that I can see the data updating only once in a while (I assume when the 4 second delay aligns with the instant when the ESP8266 updates the value on the web page).

How can I make it so that even if The Uno doesn't send new values (during the 4 second gap), the ESP8266 keeps updating the web page with the old values? I have tried numerous times but have failed. Here is my code so far:

ARDUINO SIDE:

    #include <SoftwareSerial.h>
    #include <String.h>

    //a Header for the Filtering Algorithm

    //*******************************************************************/
    //#include "Filter.h"
    //*******************************************************************/

    //Set RESET PIN for ESP8266

    //*******************************************************************/
    #define RST_PIN_ESP8266 13
    //*******************************************************************/

    //Define Baud rate for Serial Communication and ESP8266 Software Serial
    //*******************************************************************/
    #define SERIAL_BAUD_RATE 9600
    #define ESP8266_SOFT_SERIAL_BAUD_RATE 9600
    //*******************************************************************/

    //LM35 Temperature sensor used for this code
    //*******************************************************************/
    #define LM35 A0
    //*******************************************************************/

    //Define Sensor sampling rate
    //*******************************************************************/
    #define SAMPLE_RATE 4000
    //*******************************************************************/

    //Code Features . . Uncomment to enable
    //*******************************************************************/
    //#define LM35_RAW_DEBUG
    //#define TEMP_READ
    //#define PRINT_DEBUG
    #define MEASURE_SALINE
    //*******************************************************************/
    //ESP8266 Software Serial Object
    //*******************************************************************/
    SoftwareSerial ESP8266_Serial(6,7);
    //*******************************************************************/

    //Global Variables
    //*******************************************************************/
    float tempC;
    long rawValue = 0, initCount = 0;
    int initRawValue = 0, i, START_VALUE = 0;
    int SALINE_STARTED = 0, SALINE_IN_PROGRESS = 1, SALINE_EXHAUSTED = 2;
    int saline_status_flag = 0;
    String finalMSG;
    //*******************************************************************/

    //Needed objects for time counting and filtering
    //*******************************************************************/
    unsigned long StartTime = millis();
    //ExponentialFilter<int> ADCFilter(5, 0);
    //*******************************************************************/

    void setup() {
      long rawValue = 0, initCount = 0;
      int initRawValue = 0, i;
      //Set up Serial Communication
      Serial.begin(SERIAL_BAUD_RATE);
      ESP8266_Serial.begin(ESP8266_SOFT_SERIAL_BAUD_RATE);
      pinMode(RST_PIN_ESP8266, OUTPUT);
      Reset_ESP8266();
      while(ESP8266_Serial.available()) {
        getIP();  // Obtain IP for ESP8266
      }
      delay(1000);
      //Increase accuracy
      analogReference(INTERNAL);
      //Start Sensor Calibration
      #ifdef MEASURE_SALINE
        Serial.print(". . . CALIBRATING SYSTEM . . .\n");
        #ifdef PRINT_DEBUG
          Serial.println("\n\nTime Elapsed  :\n\n");
        #endif

        here:
        unsigned long currentTime = millis();
        unsigned long elapsedTime = currentTime - StartTime;

        #ifdef PRINT_DEBUG
          Serial.println(elapsedTime);
        #endif

        if(elapsedTime < 20000) {
          initCount++;
          rawValue += analogRead(LM35);
          #ifdef PRINT_DEBUG
            Serial.println(rawValue);
          #endif
          goto here;
        }
        currentTime = 0;
        elapsedTime = 0;
        rawValue = rawValue / initCount;
        //Averaging from 5000 sensor samples
        initRawValue = rawValue;
        START_VALUE = initRawValue;
        Serial.println("\n. . . CALIBRATION COMPLETE . . .");
        Serial.print("\nInitial Raw LM35 Value  : ");
        Serial.print(START_VALUE);
        Serial.print("\n\n");
        Reinitialize_Variables();
        delay(2000);

        #ifdef PRINT_DEBUG
          Serial.println("\nLM35 Sample Count:\n");
          Serial.println(initCount);
        #endif

      #endif
      initCount = 0;

      #ifdef LM35_RAW_DEBUG
        Serial.println("\n. . . STARTING LM35 DEBUG READING . . .\n\n");
      #endif

      #ifdef MEASURE_SALINE
        Serial.println("\n. . . STARTING SALINE MONITORING. . .\n\n");
      #endif
    }

    void loop() {
      #ifdef MEASURE_SALINE
        Measure_Saline();
      #endif

      #ifdef LM35_RAW_DEBUG
        rawValue = analogRead(LM35);
        Serial.println(rawValue);
      #endif

      #ifdef TEMP_READ
        Read_Temp();
      #endif

      Reinitialize_Variables();
    }

    void Measure_Saline() {
      int dont_print_flag = 0;
      unsigned long StartTime = millis();
      //Take readings (SAMPLE_RATE times) and average them
      here:
      unsigned long currentTime = millis();
      unsigned long elapsedTime = currentTime - StartTime;

      #ifdef PRINT_DEBUG
        Serial.println(elapsedTime);
      #endif

      if(elapsedTime < SAMPLE_RATE) {
        initCount++;
        rawValue += analogRead(LM35);
        #ifdef PRINT_DEBUG
          Serial.println(rawValue);
        #endif
        goto here;
      }
      currentTime = 0;
      elapsedTime = 0;
      rawValue = rawValue / initCount;

      #ifdef PRINT_DEBUG
        Serial.print("initCount  : ");
        Serial.print(initCount);
      #endif
      if(saline_status_flag != SALINE_EXHAUSTED) {
        if(rawValue < START_VALUE) {
          saline_status_flag = SALINE_STARTED;
        } else if(rawValue == START_VALUE) {
          saline_status_flag = SALINE_IN_PROGRESS;
        } else if(rawValue > START_VALUE) {
          START_VALUE = rawValue;
          delay(1000);
          rawValue = analogRead(LM35);
          delay(10);
          if(rawValue > START_VALUE) {
            saline_status_flag = SALINE_EXHAUSTED;
            dont_print_flag = 1;
            Serial.print(rawValue);
            Serial.print("  Saline bottle EXHAUSTED\n");
            finalMSG = (String(rawValue) + " EXHAUSTED\n");
            ESP8266_Serial.println(finalMSG);
          }
        }
        //Saline Therapy Ongoing
        if((saline_status_flag == SALINE_STARTED || saline_status_flag == SALINE_IN_PROGRESS) && dont_print_flag == 0) {
          Serial.print(rawValue);
          Serial.print("  Saline Therapy IN PROGRESS\n");
          finalMSG = (String(rawValue) + " IN PROGRESS\n");
          ESP8266_Serial.println(finalMSG);
        } else if(saline_status_flag == SALINE_EXHAUSTED && dont_print_flag == 0) {
          //Saline Exhausted
          Serial.print(rawValue);
          Serial.print("  Saline bottle EXHAUSTED\n");
          finalMSG = (String(rawValue) + " EXHAUSTED\n");
          ESP8266_Serial.println(finalMSG);
        }
        START_VALUE = rawValue;
      } else {
        Serial.print("  Saline bottle EXHAUSTED\n");
        finalMSG = (String(rawValue) + " EXHAUSTED\n");
        ESP8266_Serial.println(finalMSG);
      }
      delay(200);
    }

    void Read_Temp() {
      rawValue = analogRead(LM35);
      tempC = rawValue * 0.48828125;
      tempC = rawValue / 9.31;
      Serial.println(tempC);
      delay(2000);
    }

    void Reinitialize_Variables() {
      initCount = 0;
      rawValue = 0;
      initRawValue = 0;
      i = 0;
    }

    void getIP() {
      Serial.println(ESP8266_Serial.readStringUntil('\n'));
    }

    void Reset_ESP8266() {
      pinMode(RST_PIN_ESP8266, OUTPUT);
      digitalWrite(RST_PIN_ESP8266, HIGH);
      // (RST_PIN_ESP8266 = 1 -> RESET = 0 so ESP8266 RESET FALSE)
      delay(1000);
      digitalWrite(RST_PIN_ESP8266, LOW);
      // (RST_PIN_ESP8266 = 0 -> RESET = 1 so ESP8266 RESET TRUE)
      delay(1000);
      digitalWrite(RST_PIN_ESP8266, HIGH);
      // (RST_PIN_ESP8266 = 1 -> RESET = 0 so ESP8266 RESET FALSE)
      delay(50);
    }

ESP8266 side:

    /*
     * This Code is for the ESP8266 WiFi Module. It builds a website running AJAX (Asynchronous JavaScript and XML)
     * which allows this webpage to update itself without having to refresh itself which may not be resource friendly
     */

    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>

    #define DEVICE_ID 1

    ESP8266WebServer server(80);
    const char* ssid="COLDSPOT";  // WiFi Access Point to connect to
    const char* password="1234567890"; // Password for the Access Point
    String webSite,javaScript,XML;

    void buildWebsite() {
      buildJavascript();
      webSite = "<!DOCTYPE HTML>\n";
      webSite += javaScript;
      webSite += "\n";
      webSite += "

SALINE MONITORING:

\n";
      webSite += "STATUS = \n";
      webSite += "\n";
      webSite += "\n";
    }

    void buildJavascript() {
      javaScript = "\n";
    }

    void buildXML() {
      XML = "<?xml version='1.0'?>";
      XML += "<response>";
      XML += DataFromArduino(); //incoming data from Arduino. It means it is the value of mapping function.
      XML += "</response>";
    }

    String DataFromArduino() {
      String coming;
      if(Serial.available()) {
        while(Serial.available()) {
          coming = Serial.readStringUntil('\n');
          delay(1);
        } // it is getting via serial port.
        return coming;
      } else {
        return coming;
      }
    }

    void handleWebsite() {
      buildWebsite();
      server.send(200,"text/html",webSite);
    }

    void handleXML() {
      buildXML();
      server.send(200,"text/xml",XML);
    }

    void setup() {
      Serial.begin(9600);
      WiFi.begin(ssid,password);  //trying to connect the modem
      while(WiFi.status() != WL_CONNECTED) {
        delay(500);
      }
      WiFi.mode(WIFI_STA);
      Serial.println("\n\n. . . BOOTING ESP8266 . . .\n");
      Serial.print("DEVICE ID : ");
      Serial.print(DEVICE_ID);
      Serial.print("\n");
      Serial.print("CONNECTED TO ACCESS POINT :  ");
      Serial.println(ssid);
      Serial.flush();
      Serial.println(WiFi.localIP());
      //it is sending the IP to Arduino's port. So I can see the IP on Serial Monitor
      Serial.flush();
      server.on("/", handleWebsite);
      //it is all about setting of server.
      server.on("/xml",handleXML);
      server.begin();
    }

    void loop() {
      server.handleClient();
    }

Please note that I have already changed the baud rate of the ESP8266 to 9600. I am using [THIS ESP8266][1] Module.

  [1]: http://www.sparkfun.com/products/13678

title: Need help with sending Arduino data to web page with ESP8266

Answers: 1

body: If you take the variable `String coming` out of the function `DataFromArduino()` and make it a global variable (by adding it to the line after String website1).  That way it will store its value between calls to  `DataFromArduino()` and return the same result if it has had nothing new.


body:
can i run Atmega1284P at 3.3V and 8Mhz speed.? can i burn Nick Gammon Arduino bootloaders into the chip.?

Thank You

title: Running Atmega1284P at 3.3 and 8Mhz

Answers: 1

body:
Atmega1284P 8MHz @ 3.3V?

Yes, you can. Documentation states this is permitted voltage for that frequency:  0 - 10MHz @ 2.7V - 5.5V http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-42719-ATmega1284P_Datasheet.pdf

Nick Gammon Arduino bootloaders?

On this page http://www.gammon.com.au/bootloader it states Atmega1284.
In code https://github.com/nickgammon/arduino_sketches/blob/master/Atmega_Self_Read_Signature/Atmega_Self_Read_Signature.ino
there is signature for Atmega1284P so it should work without issues.


body:
I am using an Arduino M0 Pro and have a device connected via Pin 0 and 1 of it. So I am using the predefined Serial5 interface to receive data from it. I have the following code snippet/method that tries to read an answer from Serial5 if it is available. Otherwise it returns an empty string.

    String read_answer() {
      String str = "";
      // Check if bytes are available
      if (Serial5.available()) {
        char c;
        // Read an character unless the read() method returns -1
        // The -1 is identical to 255
        while ((c = Serial5.read()) != 255) {
          // Append the read character to the string array
          str.concat(c);
        }

        // Output the string on the serial debug interface
        Serial.print("Read: \"");
        Serial.print(str);
        Serial.print("\"\n");
      }
      // Return the read string
      return str;
    }

If I send an the following string "ABCDEF HIJKL MNOPQR" via an FTDI towards it the first times it correctly printed :

    Read: "ABCDEF HIJKL MNOPQR"

But suddenly it just stops reading the complete string. The output is something like that:

    Read: "ABCDEF HIJKL MN

It is just cut off and everything stops working, over and over again. It might be a very stupid mistake but I don't know where to check next. If I missed something to explain or more context is needed pls tell me.

title: Incomplete serial string input

Answers: 1

body:
Your code has no idea when the string is finished. At the moment it is just waiting until the receive buffer is empty (`Serial.read()` returns -1), but since serial is a *slow* protocol that could happen at any time, not just at the end of the string.

You need something to terminate your string so it knows when the end is. The most common way is to use a line feed character (`\n`, character 10) or a carriage return (`\r`, character 13) or a combination of the two.

    char c;
    while ((c = Serial5.read()) != '\n') {
        if (c != 255) {
            str.concat(c);
        }
    }

    // Output the string on the serial debug interface
    Serial.print("Read: \"");
    Serial.print(str);
    Serial.print("\"\n");


body:
I have a strange issue. I have 3 LEDs, each is supposed to beep with a correlated tone... Imagine the beginning of a racing game (beeping with traffic lights). Here's my code:

    #include "pitches.h"

    //Beginning Melody
    int melody[] = {
      NOTE_C3, NOTE_C3, NOTE_C4
    };

    //Beginning Note Durations
    int noteDurations[] = {
      2, 2, 1
    };

    int redLight = 3;
    int yellowLight = 5;
    int greenLight = 6;

    void setup() {
      Serial.begin(9600); //initialize serial communication

      pinMode(redLight, OUTPUT);
      pinMode(yellowLight, OUTPUT);
      pinMode(greenLight, OUTPUT);
    }

    void loop() {
      playBegin();
      delay(5000);
    }

    void playBegin(){
      int lightColor = 1;

      for (int thisNote = 0; thisNote < 3; thisNote++) {

        if(lightColor == 1){
          analogWrite(redLight, HIGH);
        }else if (lightColor == 2){
          analogWrite(yellowLight, HIGH);
        }else{
          analogWrite(greenLight, HIGH);
        }
        lightColor++;

        int noteDuration = 1000 / noteDurations[thisNote];
        tone(11, melody[thisNote], noteDuration);
        delay(1000);
        noTone(11);

        analogWrite(redLight, LOW);
        analogWrite(yellowLight, LOW);
        analogWrite(greenLight, LOW);
      }
    }

Originally, the 3 LEDs would light up correctly. The red light is plugged into Pin 3, the yellow light into Pin 5, and the green light into Pin 6. HOWEVER, when I added in the tones, the red light (in Pin 3) doesn't light up. The 3 tones still sound off correctly, and the yellow and green LEDs work perfectly fine. This is ONLY not working for the red LED, it just doesn't light up while the 1st tone happens.

When I take out the line of code where tone() is, it works fine and the red light will turn on at the correct time again. This is ONLY happening when the tone() function is included.

To be clear, this is the exact line of code that is affecting the red LED:

    tone(11, melody[thisNote], noteDuration);

Furthermore, I swapped the pins of the yellow and red LEDs to see if it was an issue with the red LED, and it was not. It's whatever LED is plugged into Pin 3, and again, ONLY when the tone() function is in the code as well. I'm not sure how they're conflicting. This does not appear to be an issue with my hardware.

I'm working with Arduino Uno. If you need anymore info, let me know.

Thanks!

title: LEDs not working with tone() function

Answers: 3

body:
You have a timer conflict.

`tone()` uses a timer, and `analogWrite()` on certain pins uses the same timer.

Quite why you're using `analogWrite()` though, with `HIGH` (which equates to `1`) as the duty cycle I don't quite understand. I would have though `digitalWrite()` would be a better choice. A duty cycle of 1 would be pretty much invisible anyway...

body:
If you read the documentation for the tone function ( https://www.arduino.cc/en/Reference/Tone ), you might notice this line:

    Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

body:
Following on from the information provided by [Majenko][1] and [Delta_G][2] and a minor modification/simplification, here is the resulting code:

    #include "pitches.h"

    //Beginning Melody
    int melody[] = {
      NOTE_C3, NOTE_C3, NOTE_C4
    };

    //Beginning Note Durations
    int noteDurations[] = {
      2, 2, 1
    };

    int redLight = 3;
    int yellowLight = 5;
    int greenLight = 6;

    void setup() {
      Serial.begin(9600); //initialize serial communication

      pinMode(redLight, OUTPUT);
      pinMode(yellowLight, OUTPUT);
      pinMode(greenLight, OUTPUT);
    }

    void loop() {
      playBegin();
      delay(5000);
    }

    void playBegin(){
      for (int thisNote = 0; thisNote < 3; thisNote++) {

        if(thisNote == 0){
          digitalWrite(redLight, HIGH);
        }else if (thisNote == 1){
          digitalWrite(yellowLight, HIGH);
        }else{
          digitalWrite(greenLight, HIGH);
        }

        int noteDuration = 1000 / noteDurations[thisNote];
        tone(11, melody[thisNote], noteDuration);
        delay(1000);
        noTone(11);

        digitalWrite(redLight, LOW);
        digitalWrite(yellowLight, LOW);
        digitalWrite(greenLight, LOW);
        delay(200);
      }
    }

  [1]: https://arduino.stackexchange.com/a/45556/19409
  [2]: https://arduino.stackexchange.com/a/45557/19409


body:
This is the MCU: http://www.microchip.com/wwwproducts/en/ATtiny88 - it advertises a hardware I2C interface, but I am struggling with it. It is mounted on my own board (which worked fine if I dropped an ATMega instead).

**edited - prev screencapture were from an ungrounded logic analyzer**

First tried the [Femtocow ATTiny][1] - it has complained about no Wire library at the `#include Wire.h` line. So i went into `C:\Program Files\Arduino\hardware\arduino\avr\libraries`, grabbed the Wire folder and copied it into `C:\Program Files\Arduino\libraries`. Compiled fine, loaded the binary with avrdude, got a few first TWI communication fine, then it started trashing.

Second attempt was with the cores from [Drazzy ATTinycore][2] which came with its own Wire library. Compiled fine, loaded the binary and got the same behaviour.

This is how the messed up I2C line looks in both cases. Starts fine, then appears to go wonky, after a few of these wonky bursts the lines go silent. Also, in spite of having changed the frequency to both 100 and 400 kHz i have this weird 1.953 kHz clock...

    #define F_TWI             400000L
    //#define F_TWI             100000L

    ....

      Wire.begin(); // Initiate the Wire library
      Wire.setClock(F_TWI);

[![enter image description here][3]][3]

I am using Arduino 1.8.2. Anything gives ?

  [1]: https://github.com/FemtoCow
  [2]: https://github.com/SpenceKonde/ATTinyCore
  [3]: https://i.stack.imgur.com/MrFAV.png

title: The Wire library and an ATTiny88 MCU

Answers: 1

body:
My issue has ultimately come from some memory differences between the ATTiny88 and the ATMega88 - the latter has twice as much SRAM - 1 kB. There normally have not been any warnings on this running out of RAM issue except for once - can't recall how but Arduino IDE did warn.

However, until I got to the bottom of it there have been some digging that had to be done. Like getting used to the programmer either working as expected, or erroring and failing, or erroring and not failing. Then there are the, sometimes changing, folders into which Arduino IDE outputs its files. Also there are non-working board configurations causing the used Wire libraries to issue read and write requests followed by just a NAK. Oh, and not to forget about the messed up signals - turns out they weren't messed up, just the logic analyzer was.


body:
i need to measure the air resistance and roll resistance of a vehicle. I plan on using a toothed disc with a proximity sensor which will output a square wave signal in to an arduino. Then I will drive until I reach a certain speed, after which I will disconnect the drive from the wheels and let the vehicle roll until it has reached another certain speed (2 or 3 kph lower than the speed at which I started). By measuring the time it takes to decelerate I can calculate the air and rolling resistance.

I want to use an arduino as the brain box. Once the frequency of the sensor signal drops below a given value the arduino should start measuring time. Once the frequency drops below a second given value the arduino should stop measuring. For example between 25Hz and 20Hz. I would like to change the Frequency (that corresponds to a speed) so i can test at different speeds. I would then want to log the time it took to my pc on the serial monitor. I plan on using an Arduino Mega 2560.

My knowledge of coding in C is very limited so I'm a bit stuck on how I would write such a program. Anybody got any ideas on how to program something by using interrupts? The vehicle on which I want to do this is an Urban Concept car for the Shell Eco-marathon efficiency race.

title: Deceleration time logger between frequencies

Answers: 0


body:
I want to use `Seeeduino`, but I can't activate port connection for it.

To use `Seeduino` I installed Seeeduino from `Board Manager` in Arduino Studio.

And then installed `USB Serial Driver` from this binary.

http://www.ftdichip.com/Drivers/VCP/MacOSX/FTDIUSBSerialDriver_v2_4_2.dmg

But somehow there is no corresponding port in `Tools` -> `Port`.
How can I activate the port?

title: Can't activate Seeeduino port

Answers: 0


body:
I want to know how to connect my Arduino to my website on 000webhost.com (free webhosting account). I'm using ESP-11 WiFi module and it is connected to the internet.

This is my Arduino code:

<!-- language: c++ -->

    #include <SoftwareSerial.h>
    SoftwareSerial ESP11 = SoftwareSerial(10,11); // RX, TX
    #define DEBUG true

    // WIFI SHIELD DECLARATION
    String ssid = "\"SampleSSID\"";
    String pass = "\"SamplePass\"";
    String tcp = "\"TCP\"";
    String remoteip = "\"jvystocksystem.000webhostapp.com\"";
    String portnum = "80";

    void setup(){
      ESP11.begin(9600);
      Serial.begin(9600);
      sendData("AT+CWMODE=1\r\n",2000,DEBUG); // configure as access point and Client
      sendData("AT+RST\r\n",2000,DEBUG); // reset module
      sendData("AT+GMR\r\n",2000,DEBUG); // View version Info
      sendData("AT+CWLAP\r\n",5000,DEBUG); // List all available AP's*/
      sendData("AT+CWJAP=" + ssid + "," + pass + "\r\n",10000,DEBUG); // Connect to AP
      sendData("AT+CIFSR\r\n",2000,DEBUG); // get ip address
      sendData("AT+CIPMUX=0\r\n",2000,DEBUG); //Single TCP Connections
      sendData("AT+CIPSTART="+ tcp +"," + remoteip + "," + portnum + "\r\n",3000,DEBUG); // Start connecting to localhost <link id>,<type>,<remote IP>,<Port Number>

      String getStr = "GET /getCpno.php?user_type=admin HTTP/1.0"; // Getting info from my online database through my online website
      getStr += "\r\n\r\n";
      String cmd;
      // send data length
      cmd = "AT+CIPSEND=";
      cmd += String(getStr.length());
      sendData(cmd + "\r\n",1000,DEBUG);
      sendData(getStr,3000,DEBUG);
    }

    void loop() {
      // put your main code here, to run repeatedly:
    // For ESP8266
      if(ESP11.available()) // check if the esp is sending a message
      {

        if(ESP11.find("+IPD,"))
        {
         delay(1000); // wait for the serial buffer to fill up (read all the serial data)
         // get the connection id so that we can then disconnect
         int connectionId = ESP11.read()-48; // subtract 48 because the read() function returns
                                               // the ASCII decimal value and 0 (the first decimal number) starts at 48

         ESP11.find("pin="); // advance cursor to "pin="

         int pinNumber = (ESP11.read()-48)*10; // get first number i.e. if the pin 13 then the 1st number is 1, then multiply to get 10
         pinNumber += (ESP11.read()-48); // get second number, i.e. if the pin number is 13 then the 2nd number is 3, then add to the first number

         digitalWrite(pinNumber, !digitalRead(pinNumber)); // toggle pin

         // make close command
         String closeCommand = "AT+CIPCLOSE=";
         closeCommand+=connectionId; // append connection id
         closeCommand+="\r\n";

         sendData(closeCommand,1000,DEBUG); // close connection
        }
      }
    }

    /*
    * Name: sendData
    * Description: Function used to send data to ESP8266.
    * Params: command - the data/command to send; timeout - the time to wait for a response; debug - print to Serial window?(true = yes, false = no)
    * Returns: The response from the esp8266 (if there is a reponse)
    */

    String sendData(String command, const int timeout, boolean debug)
    {

        String response = ""; // ESP8266 sendData String
        ESP11.print(command); // send the read character to the esp8266

        long int time = millis();

        while( (time+timeout) > millis())
        {
          while(ESP11.available())
          {

            // The esp has data so display its output to the serial window
            char c = ESP11.read(); // read the next character.
            response+=c;
          }
        }

        if(debug)
        {
          Serial.print(response);

        }
        return response;
    }

But my code is not returning the value I want from the database, instead I'm getting this in my serial monitor:

[![Serial monitor][1]][1]

I hope you guys can help me with my code.

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

title: How to connect Arduino with ESP8266-11 WiFi module to 000webhost (free webhosting)

Answers: 1

body:
The web server is using virtual hosts. Unless you tell it to which virtual host are you making a request, the server won't know where to send the request and generate an error.

You need to add the required header `Host`, which tell it just that.

Make the proper request like this:

<!-- language: c++ -->

    String getStr = "GET /getCpno.php?user_type=admin HTTP/1.1\r\n";
    getStr += "Host: jvystocksystem.000webhostapp.com\r\n"; // add the required header
    getStr += "\r\n";


body:
I am a newbie with arduino. I am trying to have a counter with 3 buttons. Each Button when pressed will increase the number of counts. The counter should still count if button 2 is pressed while button 1 has not been released, and button 3 should also be able to increase the counter even if button 2 and button 1 are still pressed.

My code below counts if only one button is pressed at a time.

    #include <LiquidCrystal.h>
    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
    int pbutton1 = 2;
    int pbutton2 = 3;
    int pbutton3 = 4;
    int count = 0;

    void setup() {
      lcd.begin(16, 2);
      pinMode (pbutton1, INPUT);
      pinMode (pbutton2, INPUT);
      pinMode (pbutton3, INPUT);

      lcd.print("My Counter");
    }

    void loop() {

      lcd.setCursor(0, 1);
      lcd.print("Total ");
      if (digitalRead(pbutton1) == HIGH) {
        lcd.print(count++);
        while (digitalRead(pbutton1) == HIGH); //monitor button to avoid continous count
      }

      if (digitalRead(pbutton2) == HIGH) {
        lcd.print(count++);
        while (digitalRead(pbutton2) == HIGH); //monitor button to avoid continous count
      }

      if (digitalRead(pbutton3) == HIGH) {
        lcd.print(count++);
        while (digitalRead(pbutton3) == HIGH); //monitor button to avoid continous count
      }
    }

title: Arduino simultaneous push button for a counter

Answers: 2

body:
`while (digitalRead(pbutton1) == HIGH);` This blocks execution so nothing else can happen while the button is pressed. To avoid continous updating of the var while the button is pressed, create 3 booleans that keep track of the button state.

<!-- language: c++ -->

    bool button1_is_pressed = false;
    ....
    // If the button is pressed AND it was not previously pressed
    if (digitalRead(pbutton1) == HIGH && !button1_is_pressed) {
        button1_is_pressed = true;
        lcd.print(count++);
    }
    // Not pressed - reset state variable
    else if (digitalRead(pbutton1) == LOW) {
        button1_is_pressed = false;
    }

Do this for the other buttons as well.

body:
I have managed to solve this using the PushButton library. If buttons are pressed simultaneously, the count still sums up when the button is released.

    #include <LiquidCrystal.h>
    #include <Pushbutton.h>

    LiquidCrystal lcd(7, 8, 9, 10, 11, 12);
    int count = 0;

    #define button1 14
    #define button2 15
    #define button3 16

    Pushbutton pbutton1(button1);
    Pushbutton pbutton2(button2);
    Pushbutton pbutton3(button3);

    void setup() {
      lcd.begin(16, 2);
      lcd.print("My Counter");
    }

    void loop() {

      lcd.setCursor(0, 1);
      lcd.print("Total ");
        if (pbutton1.getSingleDebouncedPress()){
          count = count + 1; //increase the counter once the button is released
        }
        if (pbutton2.getSingleDebouncedPress()){
          count = count + 1; //increase the counter once the button is released
        }
        if (pbutton3.getSingleDebouncedPress()){
          count = count + 1; //increase the counter once the button is released
        }

      lcd.print(count);
    }


body:
I have tried using the [thingspeak-arduino library](https://github.com/mathworks/thingspeak-arduino) and tested some of the examples:

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

    #include <WiFi.h>
    #include <WiFiClient.h>
    #include <SPI.h>
    #include <ThingSpeak.h>
    char ssid[] = "Benok4G";    //  your network SSID (name)
    char pass[] = "password";   // your network password
    WiFiClient  client;

    unsigned long myChannelNumber = 344468;
    const char * myReadAPIKey = "xxxxxxxxx";

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      WiFi.begin(ssid, pass);
      ThingSpeak.begin(client);
    }

    void loop() {
      // put your main code here, to run repeatedly:
      float voltage = ThingSpeak.readFloatField(myChannelNumber, 1, myReadAPIKey);

      Serial.print("Latest voltage is: ");
      Serial.print(voltage);
      Serial.println("V");

      delay(30000);
    }

When i run this code, I get this on the Serial Monitor.
[![enter image description here][1]][1]

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

Why is it 0.00? It's supposed to be 24.0

http://184.106.153.149/channels/344468/fields/1/last

Did I do something wrong? I am very frustrated because I've tried a lot of methods already just to fetch the data from ThingSpeak to my Arduino using ESP8266. I can send but when receiving I am really lost and confused.

title: Thingspeak Library returns 0 using ESP8266 on Arduino

Answers: 1

body:
    #include <WiFi.h>

From the [WiFi library reference page](https://www.arduino.cc/en/Reference/WiFi):
>With the Arduino WiFi Shield, this library allows an Arduino board to connect to the internet.

From the [Arduino WiFi Shield product page](https://store.arduino.cc/arduino-wifi-shield):
> It is based on the HDG204 Wireless LAN 802.11b/g System in-Package. An AT32UC3 provides a network (IP) stack capable of both TCP and UDP.

But you're not using an Arduino WiFi Shield or anything compatible. You're using an ESP8266 which is completely different. Thus you can't use the WiFi library for your project.

Instead you will need to use the appropriate ESP8266 library. If you are programming the ESP8266 directly that will be the [ESP8266WiFi library](https://github.com/esp8266/Arduino/blob/master/doc/esp8266wifi/readme.rst), which is bundled with the [ESP8266 core for Arduino](https://github.com/esp8266/Arduino). If you are using the ESP8266 as a WiFi module controlled via AT commands that will be the [WiFiEsp](https://github.com/bportaluri/WiFiEsp) library


body:
I just got a simple scheme where i have a button connected to the **5V** connector and to the **4th** digital PIN and then i got a led connected to the **2nd** PIN and to the **GND**. When i press the button the LED should switch on and when i don't press it, it shouldn't bright. The problem here is that i got a True value when i'm not pressing the button. What could it be? Here goes the code:

    int Button=0;

    void setup() {
    Serial.begin(9600);
    pinMode(2, OUTPUT);
    pinMode(4, INPUT);
    }

    void loop() {

    Button = digitalRead(4);

    Serial.println(Button);

    if (Button == HIGH) {

      digitalWrite(2, HIGH);

    } else {

      digitalWrite(2, LOW);

    }

      delay(200);

    }

title: Arduino receives HIGH when the button is LOW

Answers: 1

body:
You will need a pushbutton connected as follows:

The signal labeled Vout will connect to digital pin 4.

[![Pushbutton schematic][1]][1]

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

Explanation:

When the pushbutton is NOT pressed, no current flows through the resistor, and Vout = 0V. When the pushbutton IS pressed, current flows through the resistor, and Vout = 5V.

This resistor is called a pull-down resistor, because it pulls the signal down to ground. A pull-up resistor would reverse the operation of the pushbutton (i.e. Vout = 5V when not pressed, and 0V when pressed.)


body:
This question is not for a project, I am just trying to understand what happens and why.

The sketch below works as expected as long as the ISR trigger is FALLING. The red led in the main loop is blinking, apparently without any disturbance from the interrupts.
The question is what goes wrong, and why, when the ISR trigger is set to LOW.

    int sensorPin3=3;
    int ledPinGreen=12;
    int ledPinRed=11;
    int sensorStatus;
    byte ledGreenStatus;

    void setup() {
    pinMode(ledPinGreen,OUTPUT);
    pinMode(ledPinRed,OUTPUT);
    pinMode(sensorPin3,INPUT_PULLUP);
    ledGreenStatus=HIGH ;
    Serial.begin(9600);
    }

    void loop() {

    attachInterrupt(digitalPinToInterrupt(sensorPin3), sensorOn, LOW);
    digitalWrite(ledPinRed,HIGH);
    delay (5000);
    digitalWrite(ledPinRed,LOW);
    delay (5000);
    }

    void sensorOn()
    {
    static unsigned long lastInterruptTime=0;
    unsigned long interruptTime=millis();
    if(interruptTime-lastInterruptTime>100)
    {
    digitalWrite(ledPinGreen,ledGreenStatus);
    ledGreenStatus =! ledGreenStatus;
    lastInterruptTime=interruptTime;
    }
    }

If the sensor is activated and the signal on interrupt pin 3 is LOW, sensorOn will be executed. What happens if the ISR has been executed once? Does the program return to the main loop to the place where the interrupt was initiated and then right back to the ISR, or does it stay in the ISR without getting back to the mainloop for as long as the signal stays LOW?

If the sensor is activated for a couple of seconds:
1) if the program keeps running the ISR, I would not expect activity from the red led (main loop), but that led is blinking, with delay of about 2 seconds (without the interrupt that should be 5 seconds).
This way it looks to me that the program returns to the main loop, but the delay time is wrong, so it doesn’t return to the right place, or the timing is not correct anymore. Why doesn’t this happen with the ISR trigger set to FALLING? Is the amount of interrupts disturbing the timing of the main loop delay?

2) if the program keeps executing the ISR but returns to the main loop every time in between, I would expect the millis() to be updated every time. In that case I would also expect the green led to blink because of the debouncing time. However the green led is not bliking. This makes me think that the program stays in the ISR so the millis() are not updated and the green led won’t blink.
But that doesn’t match with the red led behaviour.

3) if the sensor is only activated for a short amount of time, the red led turns on or off the moment the signal on the interrupt pin is no longer LOW. No visible delay. I don’t understand why a longer LOW time on the interrupt pin makes a blink with about 2 seconds delay and a short LOW time makes no delay at all.

Thank you in advance for your help!

title: Main loop delay behaviour with interupt

Answers: 3

body:
You need to understand the concept of an *interrupt*.

When a given condition is meet (a timer, a button, a signal), an ISR is called. Whatever the MCU was doing at that time is "suspended". In practical terms, it doesn't matter what it was doing when the interrupt comes.

ISR must be as short as posible (and don't call Serial, anything comms related),

Once the ISR is finished, the MCU continues the execution of the main program as if the interrupt never happened. (Almost; ISR changes things in the program).

If the same condition occurs again, the same ISR will be called again.

The usual pattern is just signal a condition inside the ISR and testing it inside the loop, like

    bool buttonPressed = false;

    void loop() {
       if (buttonPressed) {
         // Execute some action.
        buttonPressed = false;
        }
      ...
     }

    void ISRButtonPressed() {
      buttonPressed = true;
    }

There is no state, no memory. Each time is the same thing.

body:
> The question is what goes wrong, and why, when the ISR trigger is set to LOW.

edge vs. level triggered interrupts.

Read the datasheet.

body:
As Look Alterno said in another post, the key is that the ISR is called every time the condition is fulfilled. Your condition is LOW, so, every time the MCU find the pin in LOW, it call ISR ... **thousands** of times each second. That takes lot of time and that is what makes your code slow.

Solution: You have to set your interrupt to RISING, FALLING or CHANGING, but not LOW or HIGH. RISING and FALLING only look for an edge in the input signal, so they will call ISR only one.

BUT ... you have to debounce your input pin if you have it connected to anything mechanical, or else you will get several RISING and FALLING in a quick serie.

Also, you only need execute `attachInterrupt` once, in the `setup`


body:
I have been working on getting a state machine to work correctly but am having trouble with adding in the last bit of logic. What it needs to do is several things:

* Read two button inputs.
* Make sure they are pressed and held within a certain amount of time of each other as defined by "PushTimeWindow" and if not wait til both are released.
* Wait for a certain period as defined by "PushSafetyWindow".
* Turn on a relay for an amount of time as specified by "RelayOnTime".
* After the relay is off wait for both buttons to be released before they can be read again.
* If at any time one or both released turn off the relay and wait for both to be released to be pushed again.
* Count the number of successful relay periods and display them

Almost everything is doing what I had hoped it would do with the exception that I can't get the program to only allow the two switches to be pushed within a certain time frame as defined by the PushTimeWindow. Either button one needs to be pushed and held and then the second button pressed within the specified time. This window of time is intended to only allow the relay to be turned on if both buttons have been pushed within the set time. I have two states that I am trying to use to handle it but it seems to ignore them. Cases ONE_PUSHED and PUSHED_WINDOW are intended to handle this and seem to be ignored by the program. These two were added to handle that additional logic but otherwise the rest of the program works great and handles the other functions fine. I can't figure out what I am doing wrong with that logic. This is an added function to a previous question answered by user Jot
[here][1].
I suspect that the two new cases might be redundant and true no matter what and that is why they seem to be ignored, or is it that they are never called on to be tested as true or not?

The sketch uses the Bounce2 library to debounce the noisy switches and each button has pull down resistors and otherwise works well.

Here is the sketch *(Updated 10/17/17)*:

    // 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,
      ONE_PUSHED,
      PUSHED_WINDOW,
      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
    const unsigned long PushSafetyWindow = 50; // Safety Delay after push

    // 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 ONE_PUSHED:
          //One button is pushed
          if(inputState == SOMETHING_ELSE)
          {
            //One button was pushed
            Serial.println("One button Pushed");
            previousMillis = currentMillis;
            state = PUSHED_WINDOW;
          }
          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;

        //Check to see if the other button is pushed, if not wait for both off
        case PUSHED_WINDOW:
          if(currentMillis - previousMillis >= PushTimeWindow)
          {
            Serial.println("Going to WAIT_FOR_BOTH_ON state 2");
            state = WAIT_FOR_BOTH_OFF;
            previousMillis = currentMillis;
          }
          //If window to push has expired go to WAIT_FOR_BOTH_OFF state
          else if(inputState == BOTH_ON)
          {
            Serial.println("Going to SAFETY_WINDOW 2");
            state = SAFETY_WINDOW;
          }
        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 >= PushSafetyWindow)
          {
            // 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);
    }

The part of the sketch that doesn't seem to run are these two cases that should be called when one button is pressed:

    case ONE_PUSHED:
          //One button is pushed
          if(inputState == SOMETHING_ELSE)
          {
            //One button was pushed
            Serial.println("One button Pushed");
            previousMillis = currentMillis;
            state = PUSHED_WINDOW;
          }
          break;
The sketch should then run the case PUSHED_WINDOW to check if the inputState goes to BOTH_ON within the window defined in PushTimeWindow. If that time has been exceeded the sketch should then wait until both buttons are released again and then wait for another try.

    case PUSHED_WINDOW:
          if(currentMillis - previousMillis >= PushTimeWindow)
          {
            Serial.println("Going to WAIT_FOR_BOTH_ON state 2");
            state = WAIT_FOR_BOTH_OFF;
            previousMillis = currentMillis;
          }
          //If window to push has expired go to WAIT_FOR_BOTH_OFF state
          else if(inputState == BOTH_ON)
          {
            Serial.println("Going to SAFETY_WINDOW 2");
            state = SAFETY_WINDOW;
          }

Unfortunately the sketch never seems to run either of the cases which is where I am having trouble debugging.

The sketch will run on an Arduino Nano with an ATmega328P programmed with Arduino 1.8.5. The two input buttons are Rees mushroom head momentary industrial switches that are software debounced and have smoothing capacitors to hardware debounce as well. Inputs have 1K pull down resistors and the system is powered by a 9V power supply. The output to the relay pin drives the base of a NPN TIP31C transistor that powers the input of a relay with 9V. The relay has a capacitor with a resistor across it on its input to smooth out back spikes that occur when the relay triggers. The hardware all seems to be working fine and as intended.

*Edit 10/20/2017*
The solution to the question is included in the below code. The problem was with the state machine seeming to skip the window required to press the button. Some of the enum names were also changed as per suggested but if possible will be renamed again if better names come to me to be more clear what they are to do.

*Edit 10/23/2017*
Tried to name everything as clearly as possible and include documentation as to source and function of sketch.

Here is the final sketch:

    // This sketch reads inputs from two buttons to turn on a relay
    // It requires that both buttons be pressed within a certain time of each other and held
    // A relay pin is then turned on for a specified period of time
    // Both buttons must then be released again for another cycle to begin
    // A state machine is used, only to make it more clear what is going on.
    // Used with an Arduino Nano board on Arduino 1.8.5
    // Found on https://arduino.stackexchange.com/questions/45584/state-machine-logic-problem-with-added-states-monitoring-safety-switches/
    // Uses the Bounce2 library: https://github.com/thomasfredericks/Bounce2
    //
    // 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_LOW,
      WAIT_FOR_BUTTON,
      ONE_PUSHED_WAIT_FOR_OTHER_BUTTON,
      SAFETY_WINDOW,
      RELAY_ON,
    } state;       // an 'enum' is automatically an integer.

    // define the different input states.
    enum
    {
      BOTH_BUTTONS_LOW,      // no buttons are pressed.
      BOTH_BUTTONS_HIGH,     // both buttons are pressed.
      ONE_BUTTON_HIGH,       // probably one of the buttons is pressed.
    };

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

    // The 'previousMillis' is exclusively for the state machine portion only.
    // It is used for different software timers in different states.
    // That is okay, because within the state machine the states are seperated from each other.
    // Funtions outside the state machine would require a separate timer.
    unsigned long previousMillis;

    const unsigned long RelayOnTime = 1750;    // Length of time for relay
    const unsigned long TimeFrameForSecondButton = 300; // Length of time to allow two pushes
    const unsigned long PushSafetyWindow = 50; // Safety Delay after push

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

    // Instantiate Bounce objects
    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(15); //Debounce time

      pinMode(RelayPin, OUTPUT);  // OUTPUT to Relay
      pinMode(IndicatorPin, OUTPUT); // OUTPUT to Indicator LED
      Serial.println("Going to WAIT_FOR_BOTH_LOW state");
      state = WAIT_FOR_BOTH_LOW;
    }

    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_LOW:
          // Both buttons must be released to be able to continue.
          if(inputState == BOTH_BUTTONS_LOW)
          {
            // Prepare to go to the next state.
            Serial.println("Going to WAIT_FOR_BUTTON state");
            state = WAIT_FOR_BUTTON;
          }
          break;
        case WAIT_FOR_BUTTON:
    // This is the state when everything is idle and no buttons are pressed.
    // Normally both buttons are released.
    // Waiting for the first button to be pressed.
    // Both buttons could be pressed at the same time !
          if(inputState == ONE_BUTTON_HIGH || inputState == BOTH_BUTTONS_HIGH)
          {
    // At least one button is pressed.
    // Prepare to go to the next state.
    // Start a timer, because there is a timeout.
            Serial.println("Going to ONE_PUSHED_WAIT_FOR_OTHER_BUTTON state");
            previousMillis = currentMillis;
            state = ONE_PUSHED_WAIT_FOR_OTHER_BUTTON;
           }
          break;
        case ONE_PUSHED_WAIT_FOR_OTHER_BUTTON:
          if(inputState == BOTH_BUTTONS_LOW)
          {
    // The button was released. That's not what we want.
    // Return to the state to wait for both off.
            Serial.println("Going to WAIT_FOR_BOTH_LOW state");
            state = WAIT_FOR_BOTH_LOW;
          }
          else if(currentMillis - previousMillis >= TimeFrameForSecondButton)
          {
    // The timeout has ended.
    // The second button was not pushed after the first button
    // within the timeout. That's too bad.
            Serial.println("Too Long Going to WAIT_FOR_BOTH_LOW state");
            state = WAIT_FOR_BOTH_LOW;
          }
          else if(inputState == BOTH_BUTTONS_HIGH)
          {
    // The timeout has not ended and is still running.
    // And now both buttons are pressed.
    // We can continue.
    // Start the timer for the SAFETY_WINDOW state.
            Serial.println("Going to SAFETY_WINDOW state");
            previousMillis = currentMillis;
            state = SAFETY_WINDOW;
          }
          break;
        case SAFETY_WINDOW:
          if(inputState != BOTH_BUTTONS_HIGH)
          {
    // During the safety time window, a button was released.
    // Return to idle.
            Serial.println("Going to WAIT_FOR_BOTH_LOW state");
            state = WAIT_FOR_BOTH_LOW;
          }
          else if(currentMillis - previousMillis >= PushSafetyWindow)
          {
    // 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
            digitalWrite(IndicatorPin, HIGH); // Turn ON IndicatorPin
            state = RELAY_ON;
          }
          break;
        case RELAY_ON:
          if(inputState != BOTH_BUTTONS_HIGH)
          {
    // 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_LOW state");
            digitalWrite( RelayPin, LOW);  // Turn Off RelayPin
            digitalWrite(IndicatorPin, LOW); // Turn Off IndicatorPin
            state = WAIT_FOR_BOTH_LOW;
          }
          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_LOW state");
            lcd.setCursor(0,1);
            lcd.print(success);
            digitalWrite(RelayPin, LOW);  // Turn Off RelayPin
            digitalWrite(IndicatorPin, LOW); // Turn Off IndicatorPin
            state = WAIT_FOR_BOTH_LOW;
          }
          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_BUTTONS_LOW;
        }
        else if(value1 == HIGH && value2 == HIGH)
        {
          returnInputState = BOTH_BUTTONS_HIGH;
        }
        else
        {
        // Not both on, not both off, so it must be something else.
        returnInputState = ONE_BUTTON_HIGH;
        }

      return(returnInputState);
    }

  [1]: https://arduino.stackexchange.com/questions/45172/problem-with-dual-safety-switches-initiating-timed-relay

title: State Machine Logic problem with added states monitoring safety switches

Answers: 2

body:
**Intro**

You did not get any answers, because someone has to read the whole sketch and you have not explained which problem you want to solve with the two extra states and you did not fully explain what the extra states do.

I don't see a problem with my original example for the 'SAFETY_WINDOW' state. As soon as one button is released, it bails out.
I can image that the state rushes through 'WAIT_FOR_BOTH_OFF' and 'WAIT_FOR_BOTH_ON' when there is a lot of noise. Slowing it down in the sketch or with Bounce2 is a good improvement.
I could have made a mistake that I don't see, but now it is up to you to investigate where the problem comes from.

**Software**

You already found [Majenko about FSM][1]. Good, I hope you have studied it.
Perhaps you should make a sketch, just for fun, with a simple state machine.

As you can see, the integer 'state' rules it all.
The large switch-case statement contains the seperate pieces of code for each state. The order of those pieces of code does not matter. The integer 'state' defines what will be executed.

You never set the variable 'state' to 'ONE_PUSHED', therefor that piece of code will never be executed. However, please don't add that somewhere in the sketch. Explain why you want to detect if just one button is pushed.

Every piece of code of every state should make sense. I think that you have gone a little too far and the sketch is going haywire and is not going in a direction.

Is the problem that during the time that both buttons needs to be pressed (just before the relay turns on), the sketch thinks that both are pressed, even when one button is released ? Is that the problem ?

When that would be caused by a bug in the sketch, then the bug should be fixed. Trying to make a workaround around a bug is bad. If the workaround contains a bug itself, then fixing a bug with another bug is something you will never get out.

Please add a welcoming message to the display and the serial port. That way you can see if the Arduino was reset.

**The software thing to do**

There is a problem. Please describe it clearly. Then make the smallest possible test sketch to investigate that problem.
Perhaps a small sketch using the function "getInputState" and display it a number of times per second.

**Hardware**

The input impedance of an Arduino pin is very high. It could be a few hundred MegaOhms. That means if one pin is connected to something, and the pin next to it is open (not connected), then the open pin might read the same signal as its neighbour pin, just by sensing the nearby voltage through the air.

Can you make a photo of that button ?
Is there a spring inside the button ?
How long are the wires or cables to the Arduino ?
Are there other cables alongside that cable ?
Are there electrical devices nearby that could cause spikes ?
How is the button and the pullup/pulldown resistor connected ? Can you show it in a diagram ? You can even make a drawing and make a photo of that.
Are you sure it is like that, can you verify that ?
Verify it once more with a multimeter. Measure the Arduino pin with the button(s) pressed and released. Is the really going HIGH when the corresponding button is pressed ?
Can you try to connect the buttons to other pins of the Arduino board ? Perhaps an input is blown.
Is the GND of the Arduino connected to a computer, and the computer to earth ground ?
Are the wires to the buttons somehow connected to some kind of ground ?
Or to a metal enclosure or something like that ?
Is there another ground problem ?
Do you use a good and certified power supply for the Arduino ? I hope not a very cheap power supply that is leaking the mains voltage to the output.
I forgot which Arduino board you use. Which Arduino board and which Arduino IDE version do you use ?

**Common mistakes**

There are a number of common mistakes. I think you made a few of them. If you can recognize them, perhaps you can avoid them.

 - The famous XY-problem: [xyproblem.info][2].
   This happens a lot.
   Someone is too focussed to fix a problem, and wandering away from the
   original problem.
 - Trying to get a result right now.
   No experienced software designer
   does that. Investigate the problem by excluding the rest.
   Make small tests.
 - Make a good description/explanation.
   If it is an art or a skill,
   describing something in a logical way is very important.
   It can be half the work.
 - Ground problems.
   Ground problems is a major problem. When everything is connected okay,
   the ground could be connected in the wrong place.
   This is a tough subject.
 - Never trust your tools.
   Once someone knows how to make something work, but there is a bug
   somewhere that is impossible to find, then perhaps there is no bug.
   It can be a broken Arduino board, or other bad hardware or a bug
   in the Arduino software. It happens.

**ADDED**

I understand now that both buttons should be pushed within a certain time. That is the third millis timer that will be needed. I have a problem with the names that you choose for this new situation. I hope you don't mind that I made my own names. You had most of the conditions and the timeout, but bailing out as soon as the one button was released was missing.
The possibility that both buttons are pressed at the same time should also be accepted.

I did test my previous sketch, but I did not test this code. I had to draw a time diagram on a piece of paper to see the sequence of the states. I suggest you do the same.
The states are still in sequential order, there is no need for a parallel path in the state machine, or wildly jumping to all kind of states. Everything flows in a logic way from one state to the next in a sequential way.

My diagram on my piece of paper tells me that the "WAIT_FOR_BOTH_ON" has to be replaced by two other states. It needs other conditions and it should get a timeout. Let's call the new states "WAIT_FOR_BUTTON" and "ONE_PUSHED_WAIT_FOR_OTHER_BUTTON".

You might give this next constant a better name (it is the time frame in which the second button has to be pushed after the first one is pushed):

    const unsigned long TimeFrameForSecondButton = 200;

Waiting for both off is still the same. The next state is changed into "WAIT_FOR_BUTTON".

    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_BUTTON state");
        state = WAIT_FOR_BUTTON;
      }
      break;

Then wait for a button (just one or perhaps two at the same time).

    case WAIT_FOR_BUTTON:
      // This is the state when everything is idle and no buttons are pressed.
      // Normally both buttons are released.
      // Waiting for the first button to be pressed.
      // Both buttons could be pressed at the same time !
      if(inputState == SOMETHING_ELSE || inputState == BOTH_ON)
      {
        // At least one button is pressed.
        // Prepare to go to the next state.
        // Start a timer, because there is a timeout.
        Serial.println("Going to ONE_PUSHED_WAIT_FOR_OTHER_BUTTON state");
        previousMillis = currentMillis;
        state = ONE_PUSHED_WAIT_FOR_OTHER_BUTTON;
      }
      break;

While waiting for the second button, if anything is wrong then return to the state to wait for both off.

    case ONE_PUSHED_WAIT_FOR_OTHER_BUTTON:
      if(inputState == BOTH_OFF)
      {
        // The button was released. That's not what we want.
        // Return to the state to wait for both off.
        Serial.println("Going to WAIT_FOR_BOTH_OFF state");
        state = WAIT_FOR_BOTH_OFF;
      }
      else if(currentMillis - previousMillis >= TimeFrameForSecondButton)
      {
        // The timeout has ended.
        // The second button was not pushed after the first button
        // within the timeout. That's too bad.
        Serial.println("Going to WAIT_FOR_BOTH_OFF state");
        state = WAIT_FOR_BOTH_OFF;
      }
      else if(inputState == BOTH_ON)
      {
        // The timeout has not ended and is still running.
        // And now both buttons are pressed.
        // Hurray, we can continue.
        // Start the timer for the SAFETY_WINDOW state.
        Serial.println("Going to SAFETY_WINDOW state");
        previousMillis = currentMillis;
        state = SAFETY_WINDOW;
      }
      break;

Can you merge this in the code ? And remove the things that are not used ?

I'm still unhappy with the names of the variables and states and so. When you look at it a year later, you must know what is going on. Can you give that a thought, it does not matter if the names are very long.

**Reaction to 10/20/2017**

Awesome!
A medium-complex problem solved in a straightforward logical way without using delay.

A few tips:

The header should explain what it is; the date; which Arduino board; which Arduino IDE version; a link to this stackexange.com page and so on.

Your indents are not always the same. Can you get all the "case" blocks like the others ?

Normally, using three timers with millis() requires three 'previousMillis' variables. The 'previousMillis' is used three times. That needs some extra explanation:

    // The 'previousMillis' is exclusively for the state machine only.
    // It is used for different software timers in different states.
    // That is okay, because the states are seperated from each other.
    unsigned long previousMillis;

Now that I think of it, the state machine does not rule the sketch, it processes the buttons.
If you would add a buzzer, and it would need a timeout to turn off, then that timeout must be done outside the state machine. That timeout should also get it's own variable, for example: previousBuzzerMillis.

What about the names for the input states. Is "BOTH_BUTTONS_ON", "BOTH_BUTTONS_OFF, "JUST_ONE_BUTTON" better ? Or "BOTH_BUTTONS_PUSHED", "BOTH_BUTTONS_RELEASED", "ONLY_ONE_BUTTON" ?

I can't think of better names for other variables at the moment. Even the name "SAFETY_WINDOW" seems obvious.

**Correction nov 3, 2017**
I just learned that 'enum' is **not** automatically an integer. An 'enum' is its own type.

  [1]: https://hackingmajenkoblog.wordpress.com/2016/02/01/the-finite-state-machine/
  [2]: http://xyproblem.info/

body:
It looks like you are correct that the ONE_PUSHED and PUSHED_WINDOW branches are being ignored, because you never set the state to ONE_PUSHED.

I believe your just need to update the WAIT_FOR_BOTH_OFF 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 ONE_PUSHED state");
            state = ONE_PUSHED;
          }
          break;


body:
At this point, I have yet to actually touch an Arduino.  I'm toying with the RPi3 along with Home Assistant, but I'm always thinking of ways to do useless things that are fun.

Let's say I had a kitchen with 32 cabinet doors and drawers and I wanted to make sure that each one had a switch that would detect a simple on/off state.  That would translate to a map whereby a visual indicator would show that something's "ajar."

- Is this the best approach to achieve this goal?
- How many Arduino boards would this require, and/or are there other methods or concepts to achieve the same ultimate goal?

Thanks!

title: Door sensors on every cabinet in the kitchen

Answers: 2

body:
Touch less sensors (IR, magnetic hall), detecting drawer state.

1pc Arduino with I/O expanders to increase I/O ports.

body:
Since you are just starting out, start simple and build from there. Build a system that can handle one cabinet door. By doing that, you will learn a lot of the basics, without the risk of having to troubleshoot a large complex system.

The most common sensor to detect open or closed door is called a [reed switch][1]. They are low cost and simple to use.

The number of Arduinos required is mainly dependent on how much wiring you want to do. I would probably choose one battery-powered Arduino with wireless communication for each door, to avoid having wires between cabinets at all.

  [1]: https://www.sparkfun.com/products/10601


body: I am thinking about buying an ATtiny84A, which fits perfectly into my project. I want to embed it into a watch that I am designing right now. But I want to buy an SMT version so I have less space to consume. What do I need for programming it through USB? Special Atmel chip? Or just 2 digital pins from USB directly into it? Thank you very much. :)

title: ATtiny84A programming without shield

Answers: 2

body:
You need an [Surface Mount Adapter Kits][1]

[![enter image description here][2]][2]

This is a soldered version for breadboard prototyping.

There is a model that doesn't requires soldering:

[![enter image description here][3]][3]

This cost US$70 ([http://www.logicalsys.com/painfo-vpasp-vb.asp?adapter=pa8tss-ot][4])

After that, you mount your SMD on a breadboard and program the ATtiny as normal.

Of course, it doesn't work if your ATtiny is already soldered in the watch.

  [1]: https://www.digikey.com/en/product-highlight/l/logical-systems/surface-mount-adapter-kits
  [2]: https://i.stack.imgur.com/REFrY.jpg
  [3]: https://i.stack.imgur.com/5J5Nk.jpg
  [4]: http://www.logicalsys.com/painfo-vpasp-vb.asp?adapter=pa8tss-ot

body:
You need to design your device to permit In Circuit Serial Programming - ISP.  This will let you continue to refine the program once the chip is in the circuit, and it will also be your primary method of programming *and testing* small production quantities.

Basically this means that the ISP and reset pins of your processor need to be able to be externally contacted - either by a header, pads for "pogo pin" spring contacts, an SOIC test clip, or perhaps micrograbbers hooked onto individual pins.

It also means that anything connected to those pins needs to not interfere with or be harmed by the programming process.  That particularly means that anything which could drive any of these pin needs to *not* do so while the MCU is being programmed, nor load them, nor get lastingly confused by operations the programmer does on them.

You'll also need an ISP programmer.  Proper ones are sold, but beware of cheap clones and marginal designs as these often give users plenty of trouble.  Fortunately, you can use an everyday Arduino running the ISP sketch to program ATtiny chips.  Do beware though, that if your target is powered at 3.3v it is *not safe* to use a programmer with 5v signals on it - you might get away with it a few times, but eventually it will cause issues.  So if you want to use an Arduino to ISP a lower voltage target, you either need an Arduino that runs at 3.3v, or to implement level shifting.

Do spend some effort to verify that you have the software support resources you may need for the ATtiny84A - it's one of the less common chips so it won't have the same degree of community support.

A further possibility is to use ISP to put a serial (or other) bootloader into the chip and then rely on that, however this won't cover all eventualities - if you discover you need to change the fuses, you'll need ISP for that, as it's something a bootloader can't do.


body:
I just got my first arduino starters kit so I'm a total noob in it. My simple LED blinker did work, afterwards I used a switch button with a debouncer script. It worked like I wanted but I wanted to try a buzzer instead of the LED, which did not work. Afterwards when I put the LED back in it didn't work anymore either.

The onboard LED does still work. Does this mean my breadboard had a short circuit? Is there any way I can know this for sure? And what exactly went wrong? Did I have to use a higher resistor?

title: How do I know if I have a short circuit

Answers: 1

body: I would highly recommend using a digital multimeter in this case. They are not too expensive and a must for electrical projects. Most have functions such as checking for shorts. In addition, you can check to see if the pin in question changes voltage when activated. The thing to remember is that heat kills electrical components, and high current causes heat (high power, really, but watch your current and you will be fine) get familiar with the formula v=I/R and don't put too much current through your buzzer or LED. LEDs have very little resistance.


body:
i have a question on how to program a certain sequence for my robot.

lets say if i would to program to make it run from position a to b, i have a sensor attach to it that should it detect x, it would perform an action called y at the position where it detect x, where action y doesnt change its position.

i would like the robot to continue from where it left after performing action y to go towards b. however i do not know how to pause sequence from a to b and continue from where it left off after performing action y. i am controlling only the motor of the wheels so i can only set the speed of the wheels.

is there a pause function in general( not sleep) in c++ and to continue running its lines of code from where it paused?

title: stop running a certain function when sensor picks up something and return to where it stops?

Answers: 2

body:
You can use different ways:

- Pause/sleep, don't use this, since it will block other activities

- Poll, poll for time, and check every so-many ms what to do.

- Timers/Interrupts, every microcontroller has one or more timers which you can use to generate an interrupt to perform an action. The interrupt can change the mode, and in your main program you can check for the mode what to do (go to another position, pick up something etc.

The last one takes a bit more programming, but is the preferred way to easily make changes later on.

There is no 'pause' function in C, but you can of course pause until an interrupt is triggered. In the datasheet of your microcontroller you can read how this can be used.

So in general your loops look like:

    loop()
    {
       switch (mode)
       {
       case modeMoveAToB:
           ... move from A to B (just a small portion, like 1 cm)
           break;

       case modeActionY:
           ... Perform action Y
           mode = modeMoveAToB;
           break;
       }

       if (SensorTriggered)
       {
          mode = modeActionY;
          SensorTriggered = false;
       }
    }

In the trigger interrupt you set SensorTriggered to true.

Make sure that the modeActionY does not take long, so let it move e.g. 1 cm, so the sensor (SensorTriggered) is checked every 1 cm. If you need other actions, just add them in the case statement. And make the inside of each case statement a function, so you can easily reuse it later and/or keep the functionality clearly divided.

body:
> stop running a certain function when sensor picks up something and return to where it stops?

simple:

1) write that certain function as an ISR - that's not used by the mcu;

2) when the sensor picks up something, set the flag of the respective ISR - execution will jump to the corresponding ISR.

3) sit back and enjoy.


body:
Hello I have been using the WifiEsp to send and receive data from Thingspeak.
All is well until I put my http request on the Void Loop() section.

My Goal: I want to receive data every loop not on only on setup.
Here is my code

    #include <WiFiEsp.h>
    #include <WiFiEspClient.h>
    #include <SoftwareSerial.h>
    SoftwareSerial Serial1(6, 7); // RX, TX
    WiFiEspClient  client;
    int status = WL_IDLE_STATUS;

    #define SSID "Benok4G"
    #define PASS "password"
    char reply;
    char server[] = "184.106.153.149";

    void setup() {
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial1.begin(9600);
    WiFi.init(&Serial1);
    while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(SSID);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(SSID, PASS);
    }
    Serial.println("You're connected to the network");

    }

    void loop() {
    Serial.println();
    Serial.println("Receiving Data...");
    if (client.connect(server, 80)) {
    Serial.println("Connected to server");
    client.println("GET /channels/344468/fields/3/last?key=ABCDEFGH
    HTTP/1.1");
    client.println("Host: api.thingspeak.com");
    client.println("Connection: close");
    client.println();

    while (client.available()) {
    char c = client.read();
    Serial.write(c);
    }

    if (!client.connected()) {
    Serial.println();
    Serial.println("Disconnecting from server...");
    client.stop();
    while(true);
     }
    }

I can receive the letter "a" properly. However, I want it too loop and give me updated value every loop.

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

BUT! when I put the code from the void setup() to the the void loop().
I get this error..
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/8D2S3.jpg
  [2]: https://i.stack.imgur.com/JZS46.jpg

Any ideas on how can I loop it without getting the error? I tried adding delays and putting it on another function, still the same. It will only work when I put in inside the void setup()

Thanks!

title: WifiEsp client TIMEOUT when put on a loop

Answers: 0


body:
I have been searching for some sort of library that can create, query, and insert data into a SQLite style database from an Arduino to an SD card.

I have looked at the Arduino Extended Database library. But I don’t think it will quite fill this role.

I don’t need all the features of sql. But a simple query system would go a long way.

Does anyone know of a library like this?

title: Relational Database for Arduino on SD card?

Answers: 0


body:
Do I understand the code in `EEPROM.cpp / write()` correctly, that `val` is only written to the EEPROM, if `val` differs from the current EEPROM contents at the given `address`?

And if the answer is *yes*, what is `commit()` doing?

title: does EEPROM.write() only writes changed data?

Answers: 2

body:
From library [Library][1], see fragment:

> EEPROM.write does not write to flash immediately, instead you must
> call EEPROM.commit() whenever you wish to save changes to flash.
> EEPROM.end() will also commit, and will release the RAM copy of EEPROM
> contents.

Probably to prevent too many writes into the same page (mostly EEPROM is divided in pages), the write stores it into some temporary buffer and the commit actually writes it to EEPROM. This decreases the number of writes, and since the number of writes has a maximum, the lifetime of the EEPROM is increased.

Update: Majenko's comment mentions no EEPROM is used, but flash, see below.

  [1]: http://esp8266.github.io/Arduino/versions/2.0.0/doc/libraries.html

body:
I read that after the EEPROM.commit() you need to add a delay(500).
I had several issues with the EEPROM data gone after several restarts
of the esp8266.


body:
I have a HDMI Switch module which switches Input signals. It has a 4 pin push button to switch inputs. ([![front photo][1]][1] - [![back photo][2]][2])

I want to modify the button in order to control it with an Arduino. (push via Arduino command) What should i do in order to achieve this ?

I am newbie in Arduino so please excuse my mistakes.

Thanks

  [1]: https://i.stack.imgur.com/guz7M.jpg
  [2]: https://i.stack.imgur.com/T2EZD.jpg

title: Modify On board 4 pin switch to work with Arduino

Answers: 1

body:
Although it looks like 4 pins it's actually 2. You can see that they are connected together in pairs. This is identical to any other tactile switch of the kind used in many Arduino demos and examples.

All you need is some way of connecting the left pair of pins to the right pair of pins (in the underside image). The right pair are ground (you can tell because they are connected to the ground plane - the large copper area), so the input the left pair of pins are connected to must be active-low with a pullup resistor. That makes things simple enough.

If you can share the grounds between the switch circuit and the Arduino then it's possible to do it with just wires. However care must be taken:

Chances are this is a 3.3V based system (there's very few 5V systems around these days - the Arduino is pretty old technology from that perspective), so just setting an output HIGH or LOW and connecting it directly could damage the switch. Instead you need to emulate an *open drain* output. That means instead of setting a pin to OUTPUT and toggling it between HIGH and LOW to press the button you actually have to toggle the mode of the pin - that is, toggling between INPUT and OUTPUT + LOW.

For instance:

    void press() {
        digitalWrite(BUTTON_PIN, LOW);
        pinMode(BUTTON_PIN, OUTPUT);
    }

    void release() {
        pinMode(BUTTON_PIN, INPUT);
    }

You can, if you so choose, turn any GPIO pin into a real *open drain* output by using it to switch a transistor which in turn switches the button:

<!-- 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/bA8q8.png)

<!-- End schematic -->

Now it's just output a HIGH to turn the transistor ON and short the button, or LOW to turn the transistor OFF.

If you can't / don't want to share the grounds, then you can replace the transistor with an opto-isolator:

<!-- 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/Ht91a.png)

<!-- End schematic -->

That is by far the safest option since it completely isolates (*galvanic isolation*) the Arduino and the switch box.


body:
I am trying to connect my A7 to my Arduino Uno but I can't find a way to communicate with it. I searched a lot on the internet to find some schemes but not one of them worked. Here is my actual setup:

    ARDUINO              A7

    PIN 6      <=>       URXD
    PIN 7      <=>       UTXD
    GND        <=>       GND
    5V         <=>       5V

Here is my code:

    #include<SoftwareSerial.h>
    SoftwareSerial myserial(6,7);//RX,TX

    void setup() {
      Serial.begin(9600);
      myserial.begin(115200);
      Serial.println("Starting...");
    }

    void loop() {
       delay(1000);
       myserial.println("AT");
       Serial.println(myserial.read());
    }

I tried by connecting USB instead of 5V, both of them, connecting the POWER pin, or interchange 6 and 7, pressing the power button, with different delays, different baud rates, but I always get the same output on my computer:

    Starting...
    -1
    -1
    -1
    -1
    ...

Sometimes it goes 0 when I plug the USB and press the power button. The LED on the A7 is responding when I press the button and sometimes it powers up the circuit.

I also tried [this solution][1] with really simple code:

    void setup() {
       Serial.begin(115200);
    }

    void loop() {
    }

Again with different bauds rates but the compiler outputs an error:

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    ...

So I don't know what is wrong. Maybe the board is not working but it's most certainly my mistake, so I am asking for your help to solve this puzzle.

Thank you!

  [1]: https://arduino.stackexchange.com/questions/41850/arduino-connect-uno-to-a7-ai-thinker

title: AI A7 Thinker connection with Arduino

Answers: 2

body: I'm dealing with the exact same thing right now trying to get mine to work. The only help I can give so far is that that avrdude error was solved for me when i stopped trying to upload code to the uno with the a7 powered. think it has to do with the programmer using the same RX/TX ports.

body:
You said...

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
    avrdude: stk500_recv(): programmer is not responding

Those errors are occurring because you are attempting to upload to your Arduino using the same Tx/Rx wires that the software is using and trying to upload on.

**A Possible Fix**

You need to power down the A7.  Possibly pull the ground wire from it when you go to upload your program.  There are alternatives to doing this that are better, but the point is that the A7 is using those wires and keeping them busy.  If the A7 if off then the upload should work.  After uploading, then re-connect the A7 ground wire so it gets power.


body:
I am trying to do a simple GET request. But I always get status code -1. Here is my complete code.

    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>

    WiFiClient client;
    #define AP_SSID "CCR"
    #define AP_PASSWORD  "ccrxxxxx"

    void wifiConnect() {
      Serial.print("Connecting to AP");
      WiFi.begin(AP_SSID, AP_PASSWORD);
      while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
      }
    }

    void setup() {
      Serial.begin(9600);
      pinMode(0,1);
      Serial.begin(9600);
      delay(300);
      Serial.println("starting");
      WiFi.disconnect();
      Serial.println("disconnected");
      wifiConnect();
      Serial.println("Connected");
    }

    void loop() {
      HTTPClient http;
      http.begin("https://calm-falls-41696.herokuapp.com/api/v1/cards");
      http.addHeader("Content-Type", "application/json");
      int httpCode = http.GET();
      Serial.println(httpCode);
      if(httpCode == HTTP_CODE_OK) {
      Serial.print("HTTP response code ");
        Serial.println(httpCode);
        String response = http.getString();
        Serial.println(response);
      }
      http.end();
    }

Wifi connection was successful. But in my serial terminal I always see -1. I am using PlatfromIO in Visual Studio code.

**Update 1:** The URL was corrected.

     http.begin("https://calm-falls-41696.herokuapp.com/api/v1/cards.json");

I tested it with `google.com` too. But it is still returning -1.

title: Simple GET request with ESP8266HTTPClient

Answers: 2

body:
I tested your code only changing the URL and header, like this:

    //  http.begin("http://calm-falls-41696.herokuapp.com/api/v1/cards");
      http.begin("http://bing.com");
      http.addHeader("Content-Type", "text/html");

And it return httpCode == 400.

As @tttapa said, it looks like the library doesn't support https.

body:
As Musa said, I needed to suply the website certificate footprint to http.begin.

    void loop() {
      HTTPClient http;
      String thumbprint="08:3B:71:72:02:43:6E:CA:ED:42:86:93:BA:7E:DF:81:C4:BC:62:30";
      String path = "https://calm-falls-41696.herokuapp.com/api/v1/cards.json";
      http.begin(path, thumbprint);
      int httpCode = http.GET();
      Serial.println(httpCode);
      if(httpCode == HTTP_CODE_OK) {
        Serial.print("HTTP response code ");
        Serial.println(httpCode);
        String response = http.getString();
        Serial.println(response);
     }
      http.end();
      delay(1000);
    }