# Question
Title: How to connect Arduino with ESP8266-11 WiFi module to 000webhost (free webhosting)
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:

```
#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:

I hope you guys can help me with my code.

# Answer
> 1 votes
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:

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

```

---
Tags: arduino-mega, esp8266, http
---


# Question
Title: Arduino receives HIGH when the button is LOW
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);

}

```

# Answer
You will need a pushbutton connected as follows:

The signal labeled Vout will connect to digital pin 4.

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.)
> 2 votes

---
Tags: arduino-uno, button
---


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

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

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

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

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

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

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

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

```

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

void loop()
{

  unsigned long currentMillis = millis();

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

  int inputState = getInputState();

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

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

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

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

  return(returnInputState);

}

```

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

Once I made a function that returns the input value as BOTH\_OFF, BOTH\_ON, or SOMETHINE\_ELSE, then the state machine automatically unfolds itself.

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

I have added some explanation in the sketch.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  return(returnInputState);
}

```

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

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

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

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

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

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

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

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

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

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

int ButtonState1 = 0;
int ButtonState2 = 0;

bool highState = false;

int pushTimeWindow = 10000;
int relayOnTime = 10000;

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

  digitalWrite(RelayPin, LOW);
}

void loop() {

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

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

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

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

  if(highState) {

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

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

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

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

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

  }

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

}

```

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

# Answer
> Here is the code:

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

here is a different approach to consider:

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

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

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

...

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

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

---
Tags: button, relay, millis, debounce
---


# Question
Title: Thingspeak Library returns 0 using ESP8266 on Arduino
I have tried using the thingspeak-arduino library and tested some of the examples:

```
#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.

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.

# Answer
> 1 votes
```
#include <WiFi.h>

```

From the WiFi library reference page:

> With the Arduino WiFi Shield, this library allows an Arduino board to connect to the internet.

From the Arduino WiFi Shield product page:

> 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, which is bundled with the ESP8266 core for Arduino. If you are using the ESP8266 as a WiFi module controlled via AT commands that will be the WiFiEsp library

---
Tags: arduino-uno, esp8266, library
---


title: Get 25 kHz PWM on a 16 MHz Arduino

text:
# Question
Title: Get 25 kHz PWM on a 16 MHz Arduino
I am trying to output a 25 kHz software PWM on at least four pins simultaneously with variable duty cycles on each pin individualy.

I've got all the actual PWM outputs via internal timers 2x8 1x16 with variable duty cycles and am looking for a way to output a 25 kHz PWM on the four pins (any pins) via an external timer if necessary. How can I do that?

# Answer
> 5 votes
At 16 MHz, your instruction cycle is 62.5 ns, and your PWM period is 40 \\$\mu\\$s. This is only 640 instruction cycles per PWM period.

To have any hope of doing this, the first thing you need to do is forget using anything Arduino other than the hardware. Download the datasheet for the AVR in question and start getting familiar with it. Your best bet is to use 8 bit timers to reduce the overhead of loading them.

My approach would be to use every 8 bit timer available, and divide the outputs up among the timers. Load the shorest pulse width output in the 8 bit tiemrs. Keep a 16 bit timer available to use for the PWM period. Start all the timers at once. On the first 8-bit timer interrupts, toggle the output, and reload the timers with the time between the next shorest pulse width. Rinse and repeat.

Alternatively you could run one timer, and write a little scheduler that puts the outputs in order from shortest to longest pulse width, constantly poll the timer, and toggle the bits as needed.

Both of these options have a ton of software overhead, and the pulse widths will all be semi-deterministic. Neither would be good for any application where the micro has to do anything else in a timely fashion, such as communication or drive a LCD.

# Answer
> 1 votes
Look into using one of the AVR chips that have more PWM outputs. For example, AT90PWM81 which includes six hardware PWM outputs.

# Answer
> 0 votes
```
void setup()
{
    // Set the main system clock to 8 MHz.
    noInterrupts();
    CLKPR = _BV(CLKPCE);  // enable change of the clock prescaler
    CLKPR = _BV(CLKPS0);  // divide frequency by 2
    interrupts();

    // Configure Timer 0 for phase correct PWM @ 25 kHz.
    TCCR0A = 0;           // undo the configuration done by...
    TCCR0B = 0;           // ...the Arduino core library
    TCNT0  = 0;           // reset timer
    TCCR0A = _BV(COM0B1)  // non-inverted PWM on ch. B
        | _BV(WGM00);  // mode 5: ph. correct PWM, TOP = OCR0A
    TCCR0B = _BV(WGM02)   // ditto
        | _BV(CS00);   // prescaler = 1
    OCR0A  = 160;         // TOP = 160

    // Same for Timer 1.
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1  = 0;
    TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
        | _BV(COM1B1)  // same on ch. B
        | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
    TCCR1B = _BV(WGM13)   // ditto
        | _BV(CS10);   // prescaler = 1
    ICR1   = 160;

    // Same for Timer 2.
    TCCR2A = 0;
    TCCR2B = 0;
    TCNT2  = 0;
    TCCR2A = _BV(COM2B1)  // non-inverted PWM on ch. B
        | _BV(WGM20);  // mode 5: ph. correct PWM, TOP = OCR2A
    TCCR2B = _BV(WGM22)   // ditto
        | _BV(CS20);   // prescaler = 1
    OCR2A  = 160;
}

void loop()
{
    analogWrite( 3,   1);  // duty cycle = 1/160
    analogWrite( 5,  53);  // ~ 1/3
    analogWrite( 9, 107);  // ~ 2/3
    analogWrite(10, 159);  // 159/160
}

```

---
Tags: pwm
---


# Question
Title: Door sensors on every cabinet in the kitchen
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!

# Answer
> 2 votes
Touch less sensors (IR, magnetic hall), detecting drawer state.

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

# Answer
> 1 votes
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. 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.

---
Tags: switch
---


title: Main loop delay behaviour with interupt

text:
# Question
Title: Main loop delay behaviour with interupt
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!

# Answer
> 1 votes
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`

# Answer
> 0 votes
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.

# Answer
> 0 votes
> The question is what goes wrong, and why, when the ISR trigger is set to LOW.

edge vs. level triggered interrupts.

Read the datasheet.

---
Tags: interrupt
---


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

text:
# Question
Title: How do I know if I have a short circuit
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?

# Answer
> 3 votes
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.

---
Tags: arduino-uno, breadboard
---


# Question
Title: stop running a certain function when sensor picks up something and return to where it stops?
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?

# Answer
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.
> 1 votes

# Answer
> 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.
> 0 votes

---
Tags: c++
---


title: ATtiny84A programming without shield

text:
# Question
Title: ATtiny84A programming without shield
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. :)

# Answer
> 1 votes
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.

# Answer
> 0 votes
You need an Surface Mount Adapter Kits

This is a soldered version for breadboard prototyping.

There is a model that doesn't requires soldering:

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

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.

---
Tags: attiny
---


# Question
Title: Arduino simultaneous push button for a counter
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
  }
}

```

# Answer
`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.

```
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.
> 0 votes

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

```
> 0 votes

---
Tags: arduino-uno, button, input
---


title: Multiple IDE instances

text:
# Question
Title: Multiple IDE instances
I recently moved all in for Linux and have no intentions of going back to Windows, but programming for Arduino is a little annoying as I cannot find a way to have multiple instances.

In Windows you create individual shortcuts for several Arduino IDE instances. When you launch these from the desktop they are autonomous, meaning you can set a board/port combination for each one.

I have yet to find a way to do that in Ubuntu. Is there some form of isolation I can use? I tried using workspaces but they all still see just the one setting.

I do not want to have a bunch of VMs and switch from one to the other unless that is the only option left.

Is there some way I can emulate the Windows autonomous shortcut approach in Ubuntu?

# Answer
There is nothing special about it, it just works.

I strongly suggest to remove everything that is Arduino related from the repositories and have a minimal Java environment installed.

It is no problem to have a gcc build environment together with Arduino though. Even a gcc-avr build environment from the repositories is no problem. But don't install any Arduino or Java-rxtx from the repositories.

You can download the linux version and unpack it in a folder. Go to that folder where you unpacked the Arduino files and right-click on the 'arduino' file to create a shortcut. Move that shortcut to your Desktop.
Depending on the flavor of Ubuntu that you have, you can also create a starter and fill in the whole path of the 'arduino' file.

Then you can start the Arduino IDE, and just click/activate that shortcut or starter again for another instance of the Arduino IDE. They will work independent of each other. You have to set the right board for each instance of course. A third one or more is also possible.

If you have trouble with shortcuts or starters, then you can even open a terminal and go to the unpacked files, type "./arduino" to start it. Open an other terminal (or new 'tab' in the terminal) and do the same.

You don't have to makes copies of the Arduino files, you don't have to make multiple shortcuts or starters. Just start a new instance by activating the shortcut or starter once more.

I recommend to use only the newest version (at the moment 1.8.3). But if you need to run an older version then you can download and unpack older versions in seperate folders. Be careful that you can not run different versions of the IDE at the same time. The Arduino IDE before 1.6.x differs too much from 1.8.x. All of them share the same ~/.arduino15 folder with settings and downloaded files, which can cause trouble when running a new version, then an older version and then a newer version again.
> 1 votes

# Answer
Use UECIDE. It does everything Arduino IDE does, can have multiple instances running out of the box, and projects/libraries are 100% compatibles.

You get a nice standard interface, with a project, edit and output panes.

IDE can be extended with plugins:

Download it from the same site. You have versions for Windows, Mac and Linux:

> Linux files
>
> To run on 64-bit Linux you may need extra libraries installed. These are for the compilers, not for UECIDE, some of which only come in a 32-bit flavour. Possible libraries include the i386 version of libc6.
>
> ```
> uecide-0.8.9-pre17_all.deb
> uecide-0.8.9-pre17-linux.zip
>
> ```

As UECIDE follow follow strictly the rules for project/directory organization as standard Arduino IDE, libraries and projects are compatibles. You can use Arduino IDE and UECIDE on the same project without harm.

I used Arduino IDE at first, and later slowly migrate to UECIDE, keping both for a while, but right now I keep Arduino IDE only as a backup.

@Majenko is the mantainer. Shy guy, doesn't promote himself.
> 0 votes

---
Tags: arduino-ide, ubuntu
---


# Question
Title: Modify On board 4 pin switch to work with Arduino
I have a HDMI Switch module which switches Input signals. It has a 4 pin push button to switch inputs. ( \- )

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

# Answer
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:

simulate this circuit – Schematic created using CircuitLab

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:

simulate this circuit

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

---
Tags: arduino-uno, button, switch
---


title: The Wire library and an ATTiny88 MCU

text:
# Question
Title: The Wire library and an ATTiny88 MCU
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 \- 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 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);

```

I am using Arduino 1.8.2. Anything gives ?

# Answer
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.
> 0 votes

---
Tags: arduino-uno, i2c, attiny, avrdude
---


title: MKR FOx 1200 doesn't upload Sketch

text:
# Question
Title: MKR FOx 1200 doesn't upload Sketch
My Arduino MKR Fox 1200 doesn't upload any sketches. First it worked, but now it doesn't. It compiles the bare minimum sketch (empty loop and empty setup) but then uploads forever and after a long while it says port busy or Board not Found on Port

# Answer
I think that your Operating System has not found the board. This could be for any number of reasons, not least a Windows update, if you have Windows :).

1. Close the IDE and unplug the board.
2. Wait 10 seconds.
3. Plug the board in, did the OS detect the board?
4. If NO, Unplug board and restart computer.
5. IF NO, When booted plug in board, did it detect the board -\> No Stop.
6. If yes, start the IDE.
7. Check you have the write COM port selected.
8. Try loading a sketch again, did it work?

Other things to try:

* New USB cable
* Different USB port.
* Remove other USB devices, my Xbox controller sometimes prevents Arduinos attaching, not idea why.
* Different board.
* Different computer.
> 0 votes

---
Tags: sketch, uploading, port-mapping
---


# Question
Title: ESP8266 Analog read interferes with wifi?
Short version: I have a program that connects my ESP8266 to WIFI so I can control a relay connected to it over the internet or a button. I also have a sensor for my door. This software works perfectly, if I add a light dependent resistor to it (which is connected correctly since I do get readings from it) and start reading data I lose my WIFI connection. Has anyone got any idea why this is happening?

Long version:

So I have this program running on my Esp8266

```
#include <ESP8266WiFi.h>

IPAddress ip(192, 168, 0, 150);
IPAddress gateway(192, 168, 0, 1);
IPAddress subnet(255, 255, 255, 0);

const char* ssid = "mySSID";
const char* password = "myPSW";
const char* host = "192.168.0.228";

const int buttonPin = 0;
const int relayPin =  4;
const int doorPin = 5;
const int ldrPin = A0;

//int ldrState;
//int serialCount = 0;
//int ldrMin = 0;
//int ldrMax = 1024;
int buttonState = 0;
int doorState = 0;
byte Main_Light_State_Begin;
bool Main_Light_State;
bool doorNotified = false;
bool button_action_taken = false;
bool Main_Light_DBR = true;
String HTTP_Get_Response;

WiFiServer server(80);

//Functions
String HTTP_Get(char* Adress, String URL, bool Last_Line_Bool) {
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(Adress, httpPort)) {
    Serial.println("connection failed");
    return "Failed";
  }

  Serial.print("Requesting URL: ");
  Serial.println(URL);
  Serial.println("at adress");
  Serial.println(Adress);
  client.print(String("GET ") + URL + " HTTP/1.1\r\n" +
               "Host: " + Adress + "\r\n" +
               "Connection: close\r\n\r\n");
  delay(10);

  String Response;
  String Last_Line;

  while (client.available()) {
    String line = client.readStringUntil('\r');
    Serial.print(line);
    Response = Response + line;
  }
  return Response;

  Serial.println();
  Serial.println("closing connection");

}

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

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");

  server.begin(); -
  Serial.println("Server started");

  Serial.println(WiFi.localIP());
  pinMode(relayPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  pinMode(doorPin, INPUT);
//  pinMode(ldrPin, INPUT);
}

void loop() {
  if (WiFi.status() != WL_CONNECTED) {
    Serial.println("Wifi NOT Connected");
  }
  //Sensors
  buttonState = digitalRead(buttonPin);
  doorState = digitalRead(doorPin);
  //ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
  //Serial.println(analogRead(ldrPin));
//  if (serialCount == 1000) {
//    Serial.println(ldrState);
//    serialCount = 0;
//  } else {
//    serialCount ++;
//  }

  //Doorsensor
  if (doorState == HIGH) {
    if (doorNotified == false) {
      Serial.println("DOOR");
      HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?door_opened=true", false);
      doorNotified = true;
    }
  } else if (doorState == LOW) {
    if (doorNotified == true) {
      doorNotified = false;
      delay(500);
    }
    else {
      doorNotified = false;
    }
  }

  //Button
  if (buttonState == LOW) {
    if (button_action_taken == false) {
      if (Main_Light_State == true) {
        Serial.println("SWITCH");
        Main_Light_State = false;
        digitalWrite(relayPin, HIGH);
        delay(500);
        Main_Light_DBR = false;
      }
      else if (Main_Light_State == false) {
        Serial.println("SWITCH");
        Main_Light_State = true;
        digitalWrite(relayPin, LOW);
        delay(500);
        Main_Light_DBR = false;
      }
      button_action_taken = true;
    }
  } else if (buttonState == HIGH) {
    if (button_action_taken == true) {
      button_action_taken = false;
      delay(500);
    }
    else {
      button_action_taken = false;
    }

  }
  //Main_Light_State
  if (Main_Light_State == true) {
    digitalWrite(relayPin, LOW);
    if (Main_Light_DBR == false) {
      HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_on_dbr=true", false);
      Main_Light_DBR = true;
    }

  } else if (Main_Light_State == false) {
    digitalWrite(relayPin, HIGH);
    if (Main_Light_DBR == false) {
      HTTP_Get_Response = HTTP_Get("192.168.0.228", "/index.php/?main_light_off_dbr=true", false);
      Main_Light_DBR = true;
    }
  }

  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  Serial.println("new client");
  while (!client.available()) {
    delay(1);
  }

  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();

  if (req.indexOf("/main_light/on") != -1) {
    Main_Light_State = true;
    Main_Light_DBR = false;
  } else if (req.indexOf("/main_light/off") != -1) {
    Main_Light_State = false;
    Main_Light_DBR = false;
  } else if (req.indexOf("/main_light/switch") != -1) {
    Serial.println("SWITCH");
    if (Main_Light_State == true) {
      Main_Light_State = false;
    }
    else if (Main_Light_State == false) {
      Main_Light_State = true;
    }
    Main_Light_DBR = false;
  } else if (req.indexOf("/main_light/state") != -1) {

  } else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  client.flush();

  String s = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n";
  s += (Main_Light_State) ? "1" : "0";

  client.print(s);
  delay(1);
  Serial.println("Client disonnected");
}

```

With the lines I commented like above everything works fine. I have a light dependant resistor connected (correctly, I get correct measurements from it) to A0. From the moment on I uncomment the lines involving this LDR and thus start reading data from it I lose my wifi connection. Has anyone got any idea why this is? Thank you!

# Answer
> 8 votes
I have found that this was caused by reading the analog pin to many times in a short period of time. I replaced

```
  ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
  Serial.println(analogRead(ldrPin));
  if (serialCount == 1000) {
    Serial.println(ldrState);
    serialCount = 0;
  } else {
    serialCount ++;
  }

```

with this:

```
if (serialCount == 10000) {
  ldrState = map(analogRead(ldrPin), ldrMin, ldrMax, 0, 100);
  Serial.println(ldrState);
  serialCount = 0;
} else {
  serialCount ++;
}

```

Although I thought of this approach before, my mistake was that I was still reading the sensor every time the code loops, I just wasn't printing it to the serial monitor until each 100th loop.

This still gives me a reading several times per second, which is way more then I need. Anyway, now I know that I can't read my ESP8266 Analog pin to many times per second or the wifi will disconnect (at least when using it with the Arduino IDE)

# Answer
> 6 votes
This is an old question that has been answered, but I would like to offer a slightly more elegant solution (IMO!):

In my method which reads the analog data, I check and only read every 50 milliseconds:

```
void readAnalogSensor() {
   if( millis() % 50 != 0 )
       return;
   .
   .  // Do your sensor read and processing here
   .
}

```

This avoids having to keep a loop count and seems more deterministic - the loop count value will not necessarily increase in a consistent fashion depending on what else is going on in the loop. Having the millis values available is also useful if you need to implement some button debounce code.

# Answer
> 2 votes
Here is what I usually do to give repetition at fixed intervals:

```
void readAnalogSensor(){
  if (millis()<taskTime) return; // time is not expired yet
  taskTime += 50; // set time for the following execution
  // .... more code for the task that is done every 50 ms
}

```

This requires an `unsigned long variable taskTime`. You may also use a constant instead of the 50.
`taskTime` should be set to some value close to `millis()` at the end of `setup()`, otherwise there will be a rapid sequence of executions while `taskTime` catches up with `millis()`.

---
Tags: arduino-ide, wifi, esp8266
---


# Question
Title: What device do I add in order to detect if my project is moved?
I seem to be going round in circles trying to find the answer to this question, so thought I'd ask the good folk here.

I have an Arduino pro mini 3.3v based project, using lowpower libraries. It wakes up every h hours and takes a reading. I would now like it to still wake up every h hours but in the meantime know whether the item (the board, or its container) has actually physically been moved - like binary, did it move or not at all?

I don't need constant monitoring of position. Once triggered I'd turn off the interrupt until the next wake up event.

In my mind I see the solution as being an interrupt attached to low power device which when moved slightly triggers the event to be recorded.

pseudo code would be:

```
if ((hour == h_hour) && movementDetectedSinceLastWakeup){
  doStuff();
} else {
  goBackToSleep(2hrs);
}

```

My question is, what kind of sensor should I consider for this job?

* 3.3v
* lowpower
* can trigger interrupt

EDIT "move" as in it vibrated past some set level.

# Answer
There's two basic ways of detecting vibration - one which is quantifiable and one which isn't (much).

The simplest way is a sprint (possibly weighted) inside a metal tube. Vibration causes the spring to move and touch the tube - the resultant circuit is just the same as using a button. Sensitivity can't be controlled (other than maybe "how many times in a given period does the spring touch the tube"), but it's very very simple to use. They are often used in simple movement alarms (for things like bikes, etc).

The second method is to use an accelerometer. These are harder to work with but they do give you the actual amount of vibration at any given time. They are far more sensitive than a simple spring+tube, but since they are an active component they need to be constantly queried (often through I2C or an analog input). That makes them harder to use in a low-power scenario.

Some accelerometers are more intelligent and can be programmed to trigger an interrupt when vibration above a certain level is detected, though again that increases the complexity of working with them.

So in short: the lowest power option is the simple spring+tube sensor - it uses zero quiescent current. The best option is a programmable accelerometer that can trigger an interrupt to wake the main MCU. Which you choose depends on how sensitive you need the device to be...
> 2 votes

# Answer
I would say, that a gyroscope would be perfect for physical movement. In case there is change in X, Y or Z axis, it should turn on a flag as an indicator.

The model MPU-6050 would be ok for this project.
> 0 votes

---
Tags: sensors, power, interrupt
---


title: Maintain delay with NEO-6M

text:
# Question
Title: Maintain delay with NEO-6M
Ì am building speedometer with NEO-6M and have some problems with my code. The scenario is that I send some data from our Arduino to another device via a TX pin with a delay of 50 ms. This delay of 50 ms needs to be maintained and should not exceed. The issue with GPS data, which arrives from the device, is that it is received every 1 second. This issue will cause the 50ms delay to be longer and exceed to 1050 ms. In my last code change delay is not maintained on 50 ms, it is all 1000 ms. Not sure what I did wrong. My code is

# original

```
#include <AD9850.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>

static const int RXPin = 0, TXPin = 1;
static const uint32_t GPSBaud = 9600;

const int W_CLK_PIN = 8;
const int FQ_UD_PIN = 9;
const int DATA_PIN = 10;
const int RESET_PIN = 11;

double freq = 1;
double trimFreq = 124999500;

int phase = 0;

unsigned int speed = 0;

TinyGPSPlus gps;
SoftwareSerial ss(RXPin, TXPin);

void setup()
{
  Serial.begin(115200);
  ss.begin(GPSBaud);
  DDS.begin(W_CLK_PIN, FQ_UD_PIN, DATA_PIN, RESET_PIN);
  DDS.calibrate(trimFreq);
}

void loop()
{
  // Dispatch incoming characters
  while (ss.available() > 0)
    gps.encode(ss.read());

  {
    digitalWrite(outPin, HIGH);   // sets the pin on
    delayMicroseconds(50);        // pauses for 50 microseconds
    digitalWrite(outPin, LOW);    // sets the pin off
    delayMicroseconds(50);        // pauses for 50 microseconds
  }

  if (gps.speed.isUpdated())
  {
    Serial.print(F("SPEED      Fix Age="));
    Serial.print(gps.speed.age());
    Serial.print(F("ms Raw="));
    Serial.print(gps.speed.value());
    Serial.print(F(" km/h="));
    Serial.println(gps.speed.kmph());
    speed = gps.speed.kmph();
    //calculate the frequency with map()
    freq = map(speed, 0, 100, 0, 160);
    DDS.setfreq(freq, phase);
  }
}

```

# revised

(replying to https://arduino.stackexchange.com/a/45657) Thank you for help. Is it possible to put GPS speed in this code? https://pastebin.com/LdT7UHBQ I used your code and it works but my boss demands that we modify his code and make it maintain delay with it.

```
long prevTxTime = 0;
const int delayTime = 51;

void setup()
{
  Serial1.begin(115200);
  Serial2.begin(115200);
}

void loop()
{

  int b, chunk = 0;

  if (Serial2.available())
  {
    b = Serial2.read();
    chunk = b >> 6;
    if (chunk == syncc)
    {
      bytes[syncc] = b & 63;
      syncc++;
      if (syncc == 4)
      {
        syncc = 0;
        tach = bytes[0] + (bytes[1] << 6);
        velocityfreq = bytes[2] + (bytes[3] < delayTime)
        {
          //speed from gps would most likely need to be set here as "speedfromgps"

          SendData();
          prevTxTime = millis();
        }
      }

      void SendData()
      {
        sprintf(charToSend, "%d|%d|%d|%d|%d\n\r",
                data1, data2, data3, data4, speedfromgps);

        Serial1.print(charToSend);
      }

```

# Answer
* What is `outPin`?
* Don't start a `SoftwareSerial` object on the `Serial` port. Just use `Serial`
* The Serial Monitor window will have to use the GPS baud rate if the GPS is connected to pins 0 & 1. This is a good choice, but you'll have to disconnect pin 0 to upload a new sketch over USB.
* Don't use `delay`. This prevents the sketch from reading GPS characters. Eventually, the input buffer will overflow and characters will be lost. Instead, save a timestamp and compare the current time with the timestamp. When the difference is 50ms, simply toggle the pin and save another timestamp.
* Try NeoGPS. It's smaller, faster, more reliable and more accurate than all other GPS libraries. There are many tips on the Installation and Troubleshooting pages, and the examples are structured properly. If you want to use pins other than 0 & 1, be sure the read the section about choosing a serial port. `SoftwareSerial` is the worst choice.

Here is your sketch, modified to use `Serial` and `NeoGPS`:

```
#include <AD9850.h>
#include <NMEAGPS.h>
NMEAGPS gps;

#define gpsPort Serial  // GPS on pins 0 & 1
static const uint32_t GPSBaud = 9600;

const int OUT_PIN   = 4; ???
const int W_CLK_PIN = 8;
const int FQ_UD_PIN = 9;
const int DATA_PIN  = 10;
const int RESET_PIN = 11;

const double trimFreq = 124999500.0;

int phase = 0;

unsigned long lastToggle;

void setup()
{
  //Serial.begin(115200);  // NOT needed if gpsPort *is* Serial (pins 0 & 1)
  gpsPort.begin( GPSBaud );

  DDS.begin(W_CLK_PIN, FQ_UD_PIN, DATA_PIN, RESET_PIN);
  DDS.calibrate(trimFreq);

  pinMode( OUT_PIN, OUTPUT ); // must be set to output mode
  lastToggle = millis();
}

void loop()
{
  // Toggle the OUT_PIN every 50ms
  if (millis() - lastToggle > 50) {
    digitalWrite( OUT_PIN, !digitalRead(OUT_PIN) );   // toggle the pin
    lastToggle += 50; // step to the next toggle time
  }

  // Dispatch incoming characters
  if (gps.available( gpsPort )) {
    gps_fix fix = gps.read(); // get a fix structure with all GPS fields

    Serial.print(F("SPEED km/h="));

    // for testing, use some random values (comment this out later)
    fix.valid.speed = true;
    fix.spd.whole   = random( 0, 35 );

    if (fix.valid.speed) {
      float speed=fix.speed_kph();
      Serial.print( speed );

      double freq = map(speed, 0, 100, 0, 160);
      DDS.setfreq(freq, phase);

      Serial.print( ' ' ); // for debugging, show the DDS frequency
      Serial.print( freq );
    }
    Serial.println();
  }

}

```

Notice that it checks to see if there is a valid speed. The GPS device may not know the speed, depending on satellite reception.

If you want to try it, NeoGPS is available from the Arduino IDE Library Manager, under the menu **Sketch -\> Include Library -\> Manage Libraries**.

---

### UPDATE

For the code you posted (which is not a complete program) in an Answer (instead of editing your question :-/), you could do something like this:

```
#include <NMEAGPS.h>
NMEAGPS gps;
gps_fix fix;

#define gpsPort Serial  // GPS on pins 0 & 1 or whatever
static const uint32_t GPSBaud = 9600;

void setup()
{
  Serial1.begin(115200);
  Serial2.begin(115200);

  gpsPort.begin( 9600 );

    ...other things?
}

void loop()
{
  // Constantly read GPS characters
  if (gps.available( gpsPort )) {

    // Update the global fix structure with the latest GPS info.
    //   The speed will be used later by SendData.
    fix = gps.read();
  }

  // Constantly read Serial2 characters (a sensor?)
  if (Serial2.available())
  {
    int b     = Serial2.read();
    int chunk = b >> 6;
    if (chunk == syncc)
    {
      bytes[syncc] = b & 63;
      syncc++;

      if (syncc == 4)
      {
        syncc = 0;
        tach = bytes[0] + (bytes[1]<<6);
        velocityfreq = bytes[2] + (bytes[3]< delayTime)  ??? "<" ???

        SendData();
        prevTxTime = millis();
      }
    }
  }
}

void SendData()
{
  // No need to use sprintf, just print the pieces.

  Serial1.print( data1 );
  Serial1.print( '|' );
  Serial1.print( data2 );
  Serial1.print( '|' );
  Serial1.print( data3 );
  Serial1.print( '|' );
  Serial1.print( data4 );
  Serial1.print( '|' );

  // use the current GPS speed, as set in loop
  Serial1.print( fix.speed_kph() );
  Serial1.print( F("\r\n") ); // F macro saves RAM for doubled-quoted string constants
}

```

I had to guess at the nesting of curly braces because IT IS NOT INDENTED, nor do the CURLY BRACES MATCH. sad.
> 1 votes

---
Tags: arduino-uno, gps
---


# Question
Title: Talking to ADS8698 (18-bit ADC) over SPI
I want to talk to an ADS8698 over SPI (see page 36 for details on their SPI implementation) using a Teensy 3.2. Right now I'm only getting zeros back and I feel like (perhaps wrongly) that I've followed the datasheet correctly. I believe my SPI mode is correct and, given the clock rates I'm using, I should be observing the timing constraints properly.

(1) Is there a glaring error here? I haven't coded that many SPI interfaces, so I might have a novice mistake in there.

(2) Is there existing code for a product that uses a nearly identical SPI interface to the ADS8698 (any product that has a similar timing diagram would do)?

```
#include <SPI.h>

#define USB_RATE 19200//usb transfer rate
#define SPI_CLOCK 10000000//spi clock frequency

#define CS0 10

SPISettings ADC_SPI(SPI_CLOCK, MSBFIRST, SPI_MODE1);

void setup()
{
  // disable both multiplexers
  pinMode(CS0, OUTPUT);
  digitalWrite(CS0, HIGH);
  // prepare serial protocols
  Serial.begin(USB_RATE);
  SPI.begin();
}

void read_ADC()
{
  // begin the session by taking CS0 low
  SPI.beginTransaction(ADC_SPI);
  digitalWrite(CS0, LOW);// slave select disable
  // delayMicroseconds((int) (1e6 * 20/SPI_CLOCK));// wait > 16 clock cycles
  // transfer 16 bits while the ADC performs conversion
  SPI.transfer(0); // I'm not trying to set any registers, just waiting (zero is fine)
  SPI.transfer(0); // I'm not trying to set any registers, just waiting (zero is fine)
  // data should be ready, so try to read it
  Serial.println(SPI.transfer(0));
  Serial.println(SPI.transfer(0));
  // end the session by taking CS0 high
  digitalWrite(CS0, HIGH);// slave select enable
  SPI.endTransaction();
}

void loop()
{
  delay(1000);
  read_ADC();
}

```

The system is wired like this:

# Answer
> 1 votes
Per the Datasheet PG47

During power-up or reset, the default content of the command register is all 0's and the device waits for a command to be written before being placed into any mode of operation.

If your still working with this I'm going to be tackling this same thing very soon, hopefully I can get it to work with DMA. https://forum.pjrc.com/threads/34863-Teensy-CC-Dummy-Load-300W/page4

---
Tags: spi, teensy
---


# Question
Title: Burn Bootloader to Chinese Arduino 2560 with AVR ISP programmer
I got my hands on one of these ISP programmer for Atmel AVR microcontroller in USB stick design:

Then I selected Progammer \> AVR ISP and clicked on Burn Bootloader but it says

`stk500_recv(): programmer is not responding`.

Has anybody any experience doing this and if so, could they point me in the right direction?

**Edit:** I've also added the following to programmers.txt

```
mySmartUSB.name=mySmartUSB
mySmartUSB.protocol=stk500v2
mySmartUSB.communication=serial
mySmartUSB.program.tool=avrdude
mySmartUSB.program.extra_params=-P{serial.port}

```

# Answer
That error is common and usually means you either have the wrong board selected or the wrong port. Check the tools menu. Be sure you have the port for the programmer and not the port for the board if the board is also connected.
> 1 votes

# Answer
What if you use another Arduino to burn bootloader on your Arduino 2560? Check this(click here) tutorial on my Github page. Maybe this will help.
> 0 votes

---
Tags: bootloader, isp, clones, atmega2560
---


# Question
Title: Arduinos using I2C reading integers wrong
I have two Arduino unos, and I am using I2C to have them communicate with each other. The A4, A5, and GND of each Arduino is connected to the other. These are my functions:

On the sending Arduino:

```
void playNote(int pitch, int len, int location){
  Serial.println(String(String(location) + ":" + String(pitch) + "," + String(len) + "\n"));
  Wire.beginTransmission(location);
  Wire.write(pitch);
  Wire.write(len);
  Wire.endTransmission();
}

```

On the receiving Arduino:

```
void receiveEvent(int howMany){
  int pitch = Wire.read();
  int len = Wire.read();
  Serial.println("Pitch: " + String(pitch) + ", Length: " + String(len));
  playNote(pitch,len);
}

```

`pitch` always sends fine. When I send `len` as 150, it works and is received as 150. However, when `len` is sent as 300, it is received as 44. I cannot figure out why this is. Any help is appreciated.

# Answer
wire.write(n) sends a single byte of value n

150 decimal = 96 Hex
300 decimal = 012C Hex ...so is 2 bytes, and is truncated to one byte of value 2C Hex.

2C Hex = 44 decimal

Send a single byte! Maximum value of a byte is 255 decimal

If you need to send multiple Len bytes, then you need to ascertain the number of bytes and send them individually. In your code you send multiple bytes concatenated one after the other already ...you send Pitch followed by Len.
All you need to do is split Len into L1, L2 bytes first.

L1 = Len and xFF
Shift Len left or do other logical math to derive high byte, L2
Then send L1 and L2
> 3 votes

---
Tags: i2c, communication
---


# Question
Title: Simple GET request with ESP8266HTTPClient
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.

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

```
> 4 votes

# Answer
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.
> 2 votes

---
Tags: esp8266, nodemcu, iot
---


title: Newcomer at Arduino

text:
# Question
Title: Newcomer at Arduino
I think it will become readily apparent that i have absolutely zilch programming experience as I am currently going out my mind with a problem i am having trying to get my first arduino uno project off the ground. I am simply attempting to acquire the necessary libraries including a TimeLib.h library file, but however i seemingly cant even figure out how exactly to complete that very simple first step. I am giving it a serious go trying to break into this interesting field and would greatly appreciate any advice anyone could generously provide. With regards,

Newcomer

# Answer
> 2 votes
If you are using the Arduino IDE then you first need to include the library then you can put `#include <TimeLib.h>` at the top of your sketches.

There is plenty of documentation online about how to use Arduino. To solve your immediate problem I would go here: https://www.arduino.cc/en/Guide/Libraries

---
Tags: arduino-uno
---


title: Keep RTC time in a loop

text:
# Question
Title: Keep RTC time in a loop
I recently started a project with HC-SR04 sensors and RTC DS1302 clock. The idea is when a sensor detects an object, call and keep a timestamp (hh:mm:ss) all over the loop until Else If{} appears, but I don't know how to.

```
#include <DS1302.h>
#include <Time.h>
#include <TimeLib.h>
#define echoPin 12 // Echo Pin
#define trigPin 13 // Trigger Pin

time_t t = now();
DS1302 rtc(6,20,21);
String inTime;

void setup()
{
  Serial.begin(9600);
  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
}

void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;

   if (distance <= 4) {
    inTime= rtc.getTimeStr();
    Serial.println(inTime);

    }

    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");

    }

  delay(500);
}

```

Appreciate any help, thanks.

# Answer
> 1 votes
Check '{' and '}' pairs in your code.

```
void loop(){
    long duration, distance;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);
    duration = pulseIn(echoPin, HIGH);
    distance = (duration/2) / 29.1;
    if (distance <= 4) {
        inTime= rtc.getTimeStr();
        Serial.println(inTime);

   }
} //<--- what is this little fella doing here?
    else if (distance >= 5 || distance <= 0){
    Serial.println("Out of range");
    }

delay(500);
}

```

---
Tags: arduino-mega, rtc, hc-sr04
---


# Question
Title: Controlling Servo Motors with push button. Problem though
I have this setup where I have and Arduino Uno, a mini servo motor, and a pushbutton. I use a single pushbutton to control the servo motor to go to one position, then push it again to go back. It first goes to 0 degrees, then if you push it it goes to 180 degrees then vice versa. The problem is that in its initial state (which is 0 degrees), the servo motor makes noise. Like it's running or something then it gets hot.

I've seen other servo motors that never do this. Here is my code by the way:

```
#include <Servo.h>

const int buttonPin = 8;
const int servoPin = 9;
int buttonState = 0;
int directionState = 0;
Servo servoOne;
int pos = 0;

void setup() {
  servoOne.attach(9);
  servoOne.write(directionState);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (directionState == 0) {
    if (buttonState == HIGH) {
      directionState = 1;
      for (pos = 0; pos < 180; pos = pos + 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  } else if (directionState == 1) {
    if (buttonState == HIGH) {
      directionState = 0;
      for (pos = 180; pos > 1; pos = pos - 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  }
}

```

I really need all the help I can get.

# Answer
You might need to add more time to the delay. Also, check how your powering the servo. If you're powering from the Arduino, it might be drawing to much current and causing issues. If it's a bigger servo, try to hook it up to an external power source and just connect the PWM line and it's ground.
> 1 votes

# Answer
Looks like your delay is too short. If the delay gets over before the servo can reach the set postion, it will skip that command and execute the next one.

Also I agree with @julio about how are you powering your servo. By "mini" servo I assume that you are using a micro servo. I have a Tower Pro 9G micro servo (which I use as steering servo btw, small but pretty decent), and it works fine if I power it with the Arduino UNO, but torque is a bit less. Anyways, check your servo's datasheet, your servo might need more power. Just hook it up to a power supply and make sure the grounds are common. The jitter might just be the result of inappropriate power.
> 1 votes

# Answer
The most basic issue with servo motors is wrong cabling and then insufficient motor driver in terms of amperage. And then, PWM duty cycle must be set correctly. If you don't treat those things properly, you may hear noises such as humming, vibration instead of turning the motor.
> 0 votes

# Answer
The code was absolutely ok but position 180 was a problem sometimes. Those servos simply can't reach position 180 because the end is on 178 or nearby. But the servo was trying to go on that position. The solution is simple: try a different position (179 or less).
> 0 votes

# Answer
I think you need to do some debouncing on the button.

You can modify the code to suit your project:

```
/*
 Debounce

 Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
 press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
 a minimum delay between toggles to debounce the circuit (i.e. to ignore
 noise).

 The circuit:
 * LED attached from pin 13 to ground
 * pushbutton attached from pin 2 to +5V
 * 10K resistor attached from pin 2 to ground

 * Note: On most Arduino boards, there is already an LED on the board
 connected to pin 13, so you don't need any extra components for this example.

 created 21 November 2006
 by David A. Mellis
 modified 30 Aug 2011
 by Limor Fried
 modified 28 Dec 2012
 by Mike Walters

 This example code is in the public domain.

 http://www.arduino.cc/en/Tutorial/Debounce
 */

// constants won't change. They're used here to
// set pin numbers:
const int buttonPin = 2;    // the number of the pushbutton pin
const int ledPin = 13;      // the number of the LED pin

// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are long's because the time, measured in miliseconds,
// will quickly become a bigger number than can be stored in an int.
long lastDebounceTime = 0;  // the last time the output pin was toggled
long debounceDelay = 50;    // the debounce time; increase if the output flickers

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);

  // set initial LED state
  digitalWrite(ledPin, ledState);
}

void loop() {
  // read the state of the switch into a local variable:
  int reading = digitalRead(buttonPin);

  // check to see if you just pressed the button
  // (i.e. the input went from LOW to HIGH),  and you've waited
  // long enough since the last press to ignore any noise:

  // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer
    // than the debounce delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
  }

  // set the LED:
  digitalWrite(ledPin, ledState);

  // save the reading.  Next time through the loop,
  // it'll be the lastButtonState:
  lastButtonState = reading;
}

```
> -1 votes

---
Tags: arduino-uno, motor, servo, code-review
---


title: Is it possible to HTTP inside an ISR

text:
# Question
Title: Is it possible to HTTP inside an ISR
I am developing a 247 monitoring system with **Arduino**. The values need to be sent to server periodically as well as upon interrupt (**Watchdog**). To access the internet, I am using the **SIM800** module. Now, **Is it possible to HTTP inside an ISR**? As far as I know, **Serial** communication should not be used in ISR. Then how can I communicate with SIM800? Any suggestion will be valuable.

# Answer
> 2 votes
No, you cannot do HTTP in an interrupt, and you certainly can't use SoftwareSerial in an interrupt.

To trigger a heavy task in an interrupt you just set a flag (variable) which means "this task is due to be performed". Your main loop then checks that variable, runs the task, and resets the variable ready for the next time the interrupt triggers.

In multithreading environments these flags are called *semaphores* (yes, from the old signalling system using flags on ships). One thread (the interrupt) signals to the other thread (`loop()`) that it can do something.

---
Tags: serial, interrupt, communication, isr
---


# Question
Title: Unable to access SD Card when using GPS and MS5611 sensors
I'm trying to connect multiple sensors to an arduino and write the retrieved data in to a SD. When I test each module separately it works properly, but when I put everything together the SD card module doesn't work, can anybody help me?

This is the code that I'm using:

```
#include <Arduino.h>
#include <SPI.h>
#include <SD.h>
#include <Wire.h>
#include <TinyGPS++.h>
#include <SoftwareSerial.h>
#include <MS5611.h>

// SD
#define GPS_STORED_DATA_FILE_NAME "gps.txt"
#define SDCARD_PIN 10
bool _sdError = false;

// GPS
#define GPS_RX_PIN 9
#define GPS_TX_PIN 8
#define GPS_BAUD 9600
TinyGPSPlus _gps;
SoftwareSerial _ss (GPS_RX_PIN, GPS_TX_PIN);
unsigned long _timeLastMeasurementGps;

// MS5611
MS5611 _ms5611;

void sdTest(double latitude, double longitude, float elevation, double time) {
  if (_sdError) {
    //Serial.print("SD ERROR. Stopping writing");
    return;
  }
  String fileName = GPS_STORED_DATA_FILE_NAME;
  File myFile = SD.open(fileName, FILE_WRITE);

  if (myFile) {
    Serial.print("Writing to ");
    Serial.print(fileName);
    Serial.print("...");
    //myFile.println("testing 1, 2, 3.");
    myFile.print(latitude);
    myFile.print(" | ");
    myFile.print(longitude);
    myFile.print(" | ");
    myFile.print(elevation);
    myFile.print(" | ");
    myFile.println(time);
    myFile.flush();
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening");
    Serial.print(fileName);
    _sdError = true;
  }

  // re-open the file for reading:
  myFile = SD.open(fileName);
  if (myFile) {
    Serial.print(fileName);
    Serial.println(":");

    // read from the file until there's nothing else in it:
    while (myFile.available()) {
        // Serial.write(myFile.read());
      myFile.read();
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.print("error opening ");
    Serial.println(fileName);
  }
}

void smartDelay(unsigned long ms)
{
  unsigned long start = millis();
  do
  {
    while (_ss.available())
      _gps.encode(_ss.read());
  } while (millis() - start < ms);
}

void setupSd() {
  Serial.print("Initializing SD...");
  pinMode(SS, OUTPUT);

  if (!SD.begin(SDCARD_PIN))
    Serial.println(" ERROR");
  else
    Serial.println(" DONE");
}

void setupGps() {
  Serial.print("Initializing GPS...");
  _ss.begin(GPS_BAUD);
  smartDelay(1000);
  _timeLastMeasurementGps = millis();
  Serial.println(" DONE");
}

void setupMs5611()
{
   Serial.print("Initializing vario...");
   while(!_ms5611.begin(MS5611_ULTRA_HIGH_RES))
  {
    Serial.println("Could not find a valid MS5611 sensor, check wiring!");
    delay(500);
  }
  // Serial.print("ms5611 Oversampling: ");
  // Serial.println(_ms5611.getOversampling());
  Serial.println(" DONE");
}

void setup()
{
  Serial.begin(115200);
  setupMs5611();
  setupSd();
  setupGps();
}

void loop()
{
  delay (100);
   sdTest(1, 2, 3, 4);
}

```

Thanks in advance!

# Answer
I suspect that your problem lies with how your SD card is connecting via the SPI bus.

The problem is that a lot of Serial Peripheral Interface (SPI) devices, particularly the cheaper ones, don't properly put the MISO pin into high-impedance when SS is pulled high.

I had almost exactly this situation with one of my projects. I eventually resolved it by placing a tri-state buffer in the MISO line for each of the SPI devices.

I used a 74HC125 (4-channel tri-state buffer).

This is the page on Better SPI Bus Design in 3 steps that finally got me on the right track. I think the explanations are reasonably clear (at least compared with many other sites I found!).
> 2 votes

# Answer
If you are using an SPI SD breakout board (like 50 cents on AliExpress), than it does work only when not connected to other SPI devices.

However, when connected to other SPI devices it cannot communicate. The only way I could overcome this problem was to use an SD recorder/logger, which is a shield that fits on an Arduino (and contains a small proto space and sometimes a RTC. Or use a device that has multiple SPI ports.

Type (SD reader) that do not work together with other SPI devices:

Type (SD Data recorder/logger) that do work together with other SPI devices:
> 1 votes

# Answer
The SD I have is the following:

https://www.banggood.com/Micro-SD-TF-Card-Memory-Shield-Module-SPI-Mciro-SD-Adapter-For-Arduino-p-919914.html

Using the SdFat library I managed to make it work a "little": if I draw something in the external screen (PCD8544) during the setUp process the SD card will not work, otherwise it will work. I'll end up buying a new SD card reader.
> 0 votes

---
Tags: sensors, spi, sd-card
---