# Question
Title: Fade effect analog RGB strip and NodeMCU
I have an analog or dumb RGB strip that I control with HTTP commands. I want to be able to make the strip fade between different colours when I call `http://XX.X.X.XXX/fade`. I want it to do this infinitely until another colour is set or it turns on or off. I have tried doing this with a while loop but I can no longer change the state of the light from fading. Does anyone know how to do this? I'll link my code below.

```
//NodeMCU RGB-Controller for Homebridge & HomeKit (Siri)

#include <ESP8266WiFi.h>

#include <DNSServer.h>
#include <ESP8266WebServer.h>

#define redPin 13 //D7 - Red channel
#define grnPin 12 //D6 - Green channel
#define bluPin 14 //D5 - Blue channel

#define max(a,b) ((a)>(b)?(a):(b))

WiFiServer server(80); //Set server port

String readString;           //String to hold incoming request
String hexString = "FFFFFF"; //Define inititial color here (hex value), 080100 would be a calm warmtone i.e.

int state;

bool fading;

int r;
int g;
int b;

float R;
float G;
float B;

int x;
int V;

///// WiFi SETTINGS - Replace with your values /////////////////
const char* ssid = "SSID";
const char* password = "PASSWORD";
IPAddress ip(XX,X,X,XXX);      // set a fixed IP for the NodeMCU
IPAddress gateway(XX.X.X.X);  // Your router IP
IPAddress subnet(XXX.XXX.XXX.X); // Subnet mask
////////////////////////////////////////////////////////////////////

void WiFiStart() {
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  WiFi.config(ip, gateway, subnet); //Set a fixed IP. You can comment this out and set it in your router instead.
  while (WiFi.status() != WL_CONNECTED) {
    delay(100);
    Serial.print("_");
  }
  Serial.println();
  Serial.println("Done");
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println("");

  server.begin();
}

void allOff() {
  state = 0;
  for (float fade = 1.0; fade >= 0.0; fade -= 0.01) {
    analogWrite(redPin, map((r * fade), 0, 255, 0, 1023));
    analogWrite(grnPin, map((g * fade), 0, 255, 0, 1023));
    analogWrite(bluPin, map((b * fade), 0, 255, 0, 1023));
    delay(2);
  }
  // Set r/g/b to 0 so fade in is possible
  r = 0;
  b = 0;
  g = 0;
}

//Write requested hex-color to the pins
void setHex() {
  const float STEPS = 100; // Change number of steps while fading (lower is faster)
  // Save old values of r/g/b
  byte oldR = r;
  byte oldG = g;
  byte oldB = b;
  long number = (long) strtol( &hexString[0], NULL, 16);
  r = number >> 16;
  g = number >> 8 & 0xFF;
  b = number & 0xFF;
  float deltaR = (r - oldR) / STEPS;
  float deltaG = (g - oldG) / STEPS;
  float deltaB = (b - oldB) / STEPS;
  // Fade to new colour
  for (float f = 0; f < STEPS; f++) {
    analogWrite(redPin, map((oldR + (deltaR * f)), 0, 255, 0, 1023));
    analogWrite(grnPin, map((oldG + (deltaG * f)), 0, 255, 0, 1023));
    analogWrite(bluPin, map((oldB + (deltaB * f)), 0, 255, 0, 1023));
    delay(2);
  }
  state = 1;
}

//Compute current brightness value
void getV() {
  R = roundf(r/2.55);  //was (r/10.23);
  G = roundf(g/2.55);  //was (g/10.23);
  B = roundf(b/2.55);  //was (b/10.23);
  x = max(R,G);
  V = max(x, B);
}

//For serial debugging only
void showValues() {
  Serial.print("Status on/off: ");
  Serial.println(state);
  Serial.print("RGB color: ");
  Serial.print(r);
  Serial.print(".");
  Serial.print(g);
  Serial.print(".");
  Serial.println(b);
  Serial.print("Hex color: ");
  Serial.println(hexString);
  getV();
  Serial.print("Brightness: ");
  Serial.println(V);
  Serial.println("");
}

void setup() {
  Serial.begin(9600);
  delay(1);
  pinMode(redPin, OUTPUT);
  pinMode(grnPin, OUTPUT);
  pinMode(bluPin, OUTPUT);
  WiFi.mode(WIFI_STA);
  WiFiStart();
  setHex();
}

void loop() {
  WiFiClient client = server.available();

  if (!client) {
    return;
  }

  while(client.connected() && !client.available()) {
    delay(1);
  }

  //Respond on certain Homebridge HTTP requests
  if (client) {
    while (client.connected()) {
      if (client.available()) {
        char c = client.read();
        if (readString.length() < 100) {
          readString += c;
        }
        if (c == '\n') {
          Serial.print("Request: ");
          Serial.println(readString);

          //Send reponse
          client.println("HTTP/1.1 200 OK");
          client.println("Content-Type: text/html");
          client.println();

          //On
          if(readString.indexOf("on") >0) {
            setHex();
            showValues();
            fading = false;
          }

          //Off
          if(readString.indexOf("off") >0) {
            allOff();
            showValues();
            fading = false;
          }

          //Fade
          if(readString.indexOf("fade") >0) {
            fade();
            fading = true;
          }

          //Set color
          if(readString.indexOf("set") >0) {
            hexString = "";
            hexString = (readString.substring(9,15));
            setHex();
            showValues();
            fading = false;
          }

          //Status on/off
          if(readString.indexOf("status") >0) {
          client.println(state);
          }

          //Status color (hex)
          if(readString.indexOf("color") >0) {
          client.println(hexString);
          }

          //Status brightness (%)
          if(readString.indexOf("bright") >0) {
          getV();
          client.println(V);
          }

          delay(1);
          client.stop();
          readString="";
        }
      }
    }
  }
}

void fade() {
  while(fading == true){
    hexString = "000000";
    setHex();
    hexString = "FFFFFF";
    setHex();
    hexString = "FF0000";
    setHex();
    hexString = "008000";
    setHex();
    hexString = "0000FF";
    setHex();
    hexString = "FFFF00";
    setHex();
    hexString = "1E1E1E";
    setHex();
   }
 }

```

# Answer
> 0 votes
The variable `fading` cannot ever change, once you are in that `while` loop, since your code doesn't do it and you don't use interrupts either (And I don't know, if the library is supporting this). So the Arduino is stuck forever in this loop and will not respond to any interactions but resetting.

There are basically there are 2 different options for you (not counting the usage of a hypothetical interrupt capability of the Wifi library, as I don't know enough about the library):

1. **Adding Wifi code to the `while` loop:** You can just add code, that watches the Wifi interface into the `while` loop and set the `fading` variable correspondingly. This is the easiest to program option.
2. Rewrite your code (especially the `fade()` function) to be non-blocking, which means it will not block the execution of other code, but will only do something, when it is time to do so, and otherwise return from the function. You can achieve this by using the `millis()` function, which returns the milliseconds since the last startup/reset to use as a time source. Refer to the `BlinkWithoutDelay` example of the Arduino IDE. Also you can google for `millis()`; there are a ton of tutorials out there. When writing non-blocking code you might also want to implement a Finite State Machine (FSM). It's simpler as it sounds. You basically define a simple variable, which sets your current state (for example the states `fading`, `off`, `specific_color`, ...). In your `loop()` function you make a `switch(state_variable){ case` statement, where you insert code for every state in it's own `case`. Outside of the `switch` statement you can then check the Wifi interface and set the state variable correspondingly. If everything is written non-blocking it should work like a charm.

---
Tags: programming, esp8266, wifi, nodemcu, rgb-led
---


# Question
Title: How to prevent breaking my Arduino by mistake?
What is the best practice to make my Arduino circuit more robust against prototyping mistakes (like shorting pins)? I don't want the controller to release its blue magic smoke while experimenting with it, what precautions can I make while designing a circuit?

# Answer
> 14 votes
Not best practices, but an alternative approach:

Consider the Ruggeduino instead of a standard Arduino. At a price ($39.95) comparable with the equivalent Arduino, the Ruggeduino offers:

* Resettable fuse on each GPIO pin, i.e. all GPIO pins are protected from short-circuit to ground or other pins
* All GPIO pins withstand 24 Volts
* Reverse voltage protection (-30 V) on Vin
* Microcontroller overcurrent protection
* 3.3V and 5V outputs on the board are over-current and short-circuit protected

Besides the above points specific to the question, the boards are designed to survive harsh environments and various mistakes. Also, the clock is more precise than on the Arduino.

# Answer
> 11 votes
I don't know if there's *one* best practice, but the following might be helpful:

* Limit the voltage on input pins to 5.5 V maximum.
* Do not short IO pins.
* Use pullup or pulldown resistors when conecting switches or pushbuttons.
* Respect the current limits (for each pin and in total). Use resistors.
* The Arduino is just the brain, not the power station. If you have to drive higher loads, use simple transistors, Darlington arrays, etc.

# Answer
> 1 votes
Don't move any wires with the power on. Way too many boards are damaged that way.

---
Tags: safety
---


# Question
Title: Setting pinMode(pin,input/output) as per user requirement
I am working on arduino IDE and esp8266 nodemcu. As i am going through the IDE I saw that there is a structure of void loop() and void setup() and all examples in the internet included defining the pinModes within the void setup() block. I want to make a program where through mqtt or http the user will give input as to what type of device he/she wants to attach to the esp8266, so based on that i will have to set, INPUT/OUTPUT state on the following pins.

Now my initial idea was :

```
void setup()
{
    connectwifi();
}

void loop()
{
   call_some_function();
}

```

where `call_some_function()` will recieve the requirements from user over http. For example he wants a light on pin3, so `pinMode(pin3,OUTPUT);`

now what I wanted is that, call the method - `call_some_function()` whenever the user needs to add an extra device to it, which means initally when we wanted to add 4 lights to esp8266, we will write

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

```

But now when I have a user defined input, my code will become something like this,

```
call_some_function()
{
     pin=(user gave me the pin no);
     state=(based on the device the server will send the state i.e IN/OUT);
     pinMode(pin,state);
}

```

Now my question is , calling this function 4 times and writing `pinMode()` function 4 times will result in same thing or separate? Also is this doable, like can i write like this? I will be calling this function from `void loop()` instead if `void setup()`, since I continuously listen for user input, Cause I cannot find any other way of making user specific input

# Answer
> Now my question is , calling this function 4 times and writing pinMode() function 4 times will result in same thing or separate? Also is this doable, like can i write like this?

you can call pinMode anytime

And to add something more to pinMode. It is not just some preparation of the pin. It changes things for the connected circuit. Setting to INPUT lets the attached circuit rule. If there is a pull-up circuit the state will be HIGH, if pull-down LOW. INPUT\_PULLUP holds the state HIGH but lets the attached circuit to pull it down. pinMode OUTPUT sets the pin LOW.

In two cases for now I use setting a pin to OUTPUT only for the time I want to control the attached circuit and the I set it back to INPUT. In first case I reset an esp8266 with EN pin connected by setting the pin LOW, then I let the external pull-up hold the EN pin HIGH. Second case is amplifier module for the tone() function. I set the pin to INPUT after tone() otherwise it catches noise.
> 2 votes

# Answer
`pinMode()` is usually called from `setup()` because in most cases, the pin mode remains the same throughout the run. Sometimes there is a reason to change it during the run, such as in your example, and you can call `pinMode()` at whenever is the appropriate time to do that.
> 2 votes

---
Tags: esp8266, arduino-ide, nodemcu
---


# Question
Title: Generate single pulse from timer 1 in arduino nano
i have a code that shot a single pulse from pin D5 timer 0 (based on josh levine code), it works fine. the code is below

```
#define OSP_SET_WIDTH(cycles) (OCR0B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR0B =  0;
    TCNT0 = 0x00;
    OCR0A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR0A = _BV(COM0B0) | _BV(COM0B1) | _BV(WGM00) | _BV(WGM01);
    TCCR0B = _BV(WGM02) | _BV(CS00);
    DDRD |= _BV(5);
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT0 = OCR0B - 1)
#define OSP_INPROGRESS() (TCNT0>0)
#define OSP_SET_AND_FIRE(cycles) {uint8_t m=0xff-(cycles-1); OCR0B=m;TCNT0 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}

```

however, i want to generate the same pulse in pin 10 or 9 which is timer 1, so a change the code a bit just like this

```
#define OSP_SET_WIDTH(cycles) (OCR1B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR1B =  0;
    TCNT1 = 0x00;
    OCR1A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR1A = _BV(COM1B0) | _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(CS10);
    DDRD |= _BV(10);
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT1 = OCR1B - 1)
#define OSP_INPROGRESS() (TCNT1>0)
#define OSP_SET_AND_FIRE(cycles) {uint8_t m=0xff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}

```

but it doesn't work, and i am stuck, any help? i use arduino nano

Thank you

# Answer
Timer1 has a few extra features, so you need to set the registers slightly differently from timer0 (or timer2). You need to also set the WGM13 bit in the TCCR1B register.

Since timer1 is a 16 bit timer, you need to change OSP\_SET\_AND\_FIRE to also use 16 bits.

Lastly; Arduino pin 10 is port B, not port D.

```
#define OSP_SET_WIDTH(cycles) (OCR1B = 0xff-(cycles-1))
void osp_setup(uint8_t cycles) {
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1 = 0x00;
    OCR1A = 0;
    OSP_SET_WIDTH(cycles);
    TCCR1A = _BV(COM1B0) | _BV(COM1B1) | _BV(WGM10) | _BV(WGM11);
    TCCR1B = _BV(WGM12) | _BV(WGM13) | _BV(CS10);
    DDRB |= _BV(DDB2);//pin 10; PB2
}

void osp_setup() {
    osp_setup(1);
}

#define OSP_FIRE() (TCNT1 = OCR1B - 1)
#define OSP_INPROGRESS() (TCNT1>0)
#define OSP_SET_AND_FIRE(cycles) {uint16_t m=0xffff-(cycles-1); OCR1B=m;TCNT1 =m-1;}

void setup()
{
    osp_setup();
}

void loop()
{
    OSP_SET_AND_FIRE(4);
    delayMicroseconds(20);
}

```
> 1 votes

---
Tags: arduino-nano, timers
---


title: String input to character array

text:
# Question
Title: String input to character array
I am in between of project where i am getting string like "hello world" via Bluetooth to arduino I want to list this string into individual character so that I can call any of the character when required, this is not working i am getting only zeros in serial monitor please suggest what i am doing wrong

```
char s;
int k[10];

void setup () {
  Serial.begin(9600);
}
void loop () {
  if (Serial.available() > 0) {
    s = Serial.read();
  }
  k[10] = s;
  for (int x = 0; x < 10; x++) {
    Serial.println(k[x]);
    delay(200);
  }
}

```

# Answer
There are a few problems with your code sample:

---

You check for `Serial.available()>0`, but then assume/grab only one character:

```
if (Serial.available() > 0) {
  s = Serial.read();
}

```

It is possible that the serial receive buffer has more than one byte waiting, but you only capture one.

---

```
k[10] = s;

```

You assign the captured character to the last element of the byte array, regardless of all else. This presents two main problems

1. A C-style string must be terminated with a null character (`'\0'`), and you have immediately put real data in the position that should contain the terminating byte.
2. There is no possible way that bytes 0-9 can ever have any data written to them by this code.

---

Your code assumes that the entire string exists in `k[]` every time through `loop()`. Instead, you should assume that it might take hundreds or thousands of times through `loop()` just to finish receiving your string. The input string should have some kind of end-of-string marker like a newline (`'\n'`) or carriage-return (`'\r'`) (or both) so that your program can look for that and know when the input is fully received.

Below is a simple program that receives a string. Note that it has a portion labeled for when to process the recieved data. That block of code is only entered once a newline and/or carriage return are received.

```
#DEFINE MAX_INPUT 90

char inputBuffer[MAX_INPUT+1]; // Handles up to 90 bytes in a c-style string, with a null character termination.

void setup()
{
  Serial.begin(115200); // initialization
  inputBuffer[0] = '\0'; //Initialize string to emtpy.
  Serial.println("Begin:");
}

void loop() {

  if (Serial.available()>0)
  {
    char input = Serial.read();
    static int s_len; // static variables default to 0
    if (s_len>=MAX_INPUT) {
      // Have received already the maximum number of characters
      // Ignore all new input until line termination occurs
    } else if (input != '\n' && input != '\r') {
      inputBuffer[s_len++] = input;
    } else {
      // Have received a LF or CR character

      // INSERT YOUR CODE HERE TO PROCESS THE RECEIVED DATA //
      // YOU COULD COPY TO A NEW VARIABLE WITH strncpy() OR //
      // SET A FLAG TO SAY TO START SOME OTHER TASK         //
      Serial.print("RECEIVED MSG: ");
      Serial.println(inputBuffer);

      memset(inputBuffer, 0, sizeof(inputBuffer));
      s_len = 0;             // Reset input buffer here if you
                             // have already copied the data.
                             // If you don't reset here, then
                             // you can't start receiving more
                             // serial port data. This is your
                             // 'software' serial buffer, contrast
                             // with the hardware serial buffer.
    }
  }
}

```
> 1 votes

---
Tags: arduino-uno, serial, string, array
---


# Question
Title: State machine waiting for input state isn't getting input states for unknown reason
I have a state machine program used to monitor sensors and activate relays that has been used and adapted on multiple machines and it typically performs exactly as needed. I am attempting to adapt the program to include an additional relay and two sensors and I can't figure out why the program won't update the states for two of the sensors added. All other sensors update and the program runs as intended until the program enters the state to check that the sensors have been interrupted. The final machine will use photo interrupters but I have bread boarded the circuit with both the sensors as well as using switches to attempt to debug the system.

Everything else works flawlessly on the breadboard and the program runs great save for the part where the program is waiting for the state of the sensors to read "BOTH\_RSENSORS\_LOW" on line 304 of the program. I have the serial monitor running to check the status of "RsensorState" that is updated every time line 302 runs. Within the main loop, "RsensorState" should be getting updated on line 174 which is supposed to be updated on line 437 where it should be returning the state based on the sensor inputs. The serial monitor shows no change to the state while changing the input on the pins attached to it. I have tested other pins as well in case they are shorted somehow to HIGH. I have the exact same sensors working fine to return the state of sensors 1 and 2. I have gone over the code and don't know what is missing. Every other block works great and as wanted. Perhaps I have a small syntax error that I am simply not seeing. I have attempted to lay out the program in as easy a format as I can and build the steps of the logic in blocks that are easy for me to navigate.

Board: Arduino DUE

Software: Arduino IDE 1.8.5

Includes the libraries Bounce2.h and LiquidCrystal.h

The device is designed to use a system of two buttons that need to be pressed within a specified time of each other. If at any point they are released they should turn off the relays and wait til both of them are released completely before being able to proceed again. The program is set up in 10 states to perform the functions of the machine.

CLEAR\_SENSORS Turns off relay2 attached to a physical stop designed to align the part so the finished part can be slid through the machine and then checks to see if sensors 1 and 2 are not blocked meaning the part has been removed so the stop can then be be put back in place. Sensors 1 and two are on either side of the stop so that the stop will not be activated and hit the part as it is getting pushed through.

CHECK\_SENSORS Turns back on relays and waits until a part is put back in and the first sensor can see that a part is in place. When it sees a part it moves to the next state.

WAIT\_FOR\_BOTH\_LOW Checks the two safety buttons to be sure they are both released and the operator has not tried to short one out or has stuck something in the switch to hold it on. This is returned to any time the switches fail the timeout parameters.

WAIT\_FOR\_BUTTON Waits for a button to be pressed and goes into the next step.

ONE\_PUSHED\_WAIT\_FOR\_OTHER\_BUTTON looks for the other button to be pressed within the specified time frame. If it is not then the program goes back to waiting for both to be released.

FINAL\_CHECK checks to make sure the part has not been removed. If it has it goes back to waiting for the part to be put back in place and for all buttons to be released.

LOWER\_RAILS checks to make sure the buttons are still being held and if so lowers an aligning and holding railing attached to Relay3

CHECK\_RAIL\_SENSORS checks 2 sensors to be sure they are both blocked and the railing is fully down. They are to act as limit sensors. This is the step the program gets stuck on.

SAFETY\_WINDOW is a small time frame the machine waits until it turns on the relays and then after that time frame turns on relay1

RELAY\_ON turns off the main relay1 and the holding relay3 if the buttons are released and turns them off after the time frame for the relays to run has expired. It then goes to the beginning where it waits for the part to be removed.

When I bypass the CHECK\_RAIL\_SENSORS step the whole things works flawlessly. I am stumped why that particular part isn't working. From what I can tell it has to do with the RsensorState not getting updated as expected like the other sensors are. sensorState updates and functions exactly as expected so I am not sure why RsensorState does not. Am I making a syntax error I am not aware of? I have gone through it a hundred times and maybe I am just not seeing it. All the components have been tested and function as expected. Here is the code:

```
// This sketch reads inputs from two buttons and a sensor to turns on 2 relays
// RelayPin2 is engaged until the end of the first relay's cycle
// It requires that both buttons be pressed within a certain time of each other and held
// A relay pin is then turned on for a specified period of time
// RelayPin3 turns on and is verified by Sensors 3 and 4
// RelayPin2 is turned off after the first relay pin has completed it's cycle
// When the sensor is clear, RelayPin2 is turned on again
// Both buttons must then be released again for another cycle to begin
// A state machine is used, only to make it more clear what is going on.
// Used with an Arduino DUE on Arduino 1.8.5 IDE
// Original sketch found on https://arduino.stackexchange.com/questions/45584/state-machine-logic-problem-with-added-states-monitoring-safety-switches/
// Uses the Bounce2 library: https://github.com/thomasfredericks/Bounce2
//
// When a button is pressed, the input turns HIGH.
//
// Normally only one 'enum' is used for the state, that controls the code.
// This sketch has also a 'enum' for the buttons, which is called the input state.
// define the different states for this sketch.
// An 'enum' is like a number of #define with increasing numbers.

// include the library code:
#include <Bounce2.h>
#include <LiquidCrystal.h>

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

// Logical states of the main state machine
enum
{
  CLEAR_SENSORS,
  CHECK_SENSORS,
  WAIT_FOR_BOTH_LOW,
  WAIT_FOR_BUTTON,
  ONE_PUSHED_WAIT_FOR_OTHER_BUTTON,
  FINAL_CHECK,
  LOWER_RAILS,
  CHECK_RAIL_SENSORS,
  SAFETY_WINDOW,
  RELAY_ON,
} state;       // an 'enum' is its own type.

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

// Define the different sensor states

enum
{
  BOTH_SENSORS_HIGH, // Both Sensors are not blocked
  BOTH_SENSORS_LOW, // Both Sensors are blocked
  SENSOR1_HIGH_SENSOR2_LOW,  // Sensor 1 is not blocked but Sensor 2 is
  SENSOR2_HIGH_SENSOR1_LOW,   // Sensor 2 is not blocked but Sensor 1 is
};

// Define the different rail sensor states

enum
{
  BOTH_RSENSORS_HIGH, // Both sensors are not blocked
  BOTH_RSENSORS_LOW,  // Both rail sensors are blocked
  SENSOR3_HIGH_SENSOR4_LOW,  // Sensor 3 is not blocked Sensor 4 is
  SENSOR4_HIGH_SENSOR3_LOW,  // Sensor 4 is not blocked Sensor 3 is
};

const int ButtonPin1 = 2;
const int ButtonPin2 = 3;
const int Sensor1Pin = 6;
const int Sensor2Pin = 24;
const int Sensor3Pin = 30;
const int Sensor4Pin = 31;
const int RelayPin = 5;
const int RelayPin2 = 13;
const int RelayPin3 = 34;
const int IndicatorPin = 4;
const int IndicatorPin2 = 25;
const int IndicatorPin3 = 26;
const int IndicatorPin4 = 27;
const int IndicatorPin5 = 35;

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

const unsigned long RelayOnTime = 1750;    // Length of time for relay
const unsigned long TimeFrameForSecondButton = 300; // Length of time to allow two pushes
const unsigned long PushSafetyWindow = 300; // Safety Delay after push to be sure part is in place

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

// Instantiate Bounce objects
Bounce debouncer1 = Bounce();
Bounce debouncer2 = Bounce();
Bounce debouncer3 = Bounce();
Bounce debouncer4 = Bounce();
Bounce debouncer5 = Bounce();
Bounce debouncer6 = Bounce();

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

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

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

// Set up Sensor1
  pinMode (Sensor1Pin, INPUT);
  debouncer3.attach(Sensor1Pin);
  debouncer3.interval(5); //Debounce time

// Set up Sensor2
  pinMode (Sensor2Pin, INPUT);
  debouncer4.attach(Sensor2Pin);
  debouncer4.interval(5); //Debounce time

  // Set up Sensor3
  pinMode (Sensor3Pin, INPUT);
  debouncer5.attach(Sensor3Pin);
  debouncer5.interval(5); //Debounce time

// Set up Sensor4
  pinMode (Sensor4Pin, INPUT);
  debouncer6.attach(Sensor4Pin);
  debouncer6.interval(5); //Debounce time

  pinMode(RelayPin, OUTPUT);      // OUTPUT to Relay
  pinMode(RelayPin2, OUTPUT);     // OUTPUT to Second Relay
  pinMode(RelayPin3, OUTPUT);     // OUTPUT to Third Relay
  pinMode(IndicatorPin, OUTPUT);  // OUTPUT to Indicator LED
  pinMode(IndicatorPin2, OUTPUT); // OUTPUT to Second Indicator LED
  pinMode(IndicatorPin3, OUTPUT); // OUTPUT to Third Indicator LED
  pinMode(IndicatorPin4, OUTPUT); // OUTPUT to Fourth Indicator LED
  pinMode(IndicatorPin5, OUTPUT); // OUTPUT to Fifth Indicator LED

  Serial.println("Going to CLEAR_SENSORS state");

// Set initial state of the machine
  state = CLEAR_SENSORS;
}

void loop()
{

  unsigned long currentMillis = millis();

// Update the Bounce instances
  debouncer1.update();
  debouncer2.update();
  debouncer3.update();
  debouncer4.update();

  int inputState = getInputState();
  int sensorState = getSensorState();
  int RsensorState = getRSensorState();

// Process the data in a state machine.
// The output part is also in the state machine.
  switch(state)
  {
    case CLEAR_SENSORS:
       // Turn off relay2 and wait til everything is clear
        lcd.setCursor(0,0);
        lcd.print("Clear Machine");
        digitalWrite(RelayPin2, LOW);     // Turn OFF Relay 2
        digitalWrite(IndicatorPin2, LOW); // Turn OFF IndicatorPin 2
        digitalWrite(IndicatorPin4, HIGH); // Turn ON IndicatorPin 4
      if(sensorState == BOTH_SENSORS_HIGH)
      {
        // Prepare to go to the next state
        Serial.println("Machine Clear Going to CHECK_SENSORS state");
        state = CHECK_SENSORS;
      }
      break;
    case CHECK_SENSORS:
      // Turn on Relay 2 and then verify the sensor is engaged before proceeding
        lcd.setCursor(0,0);
        lcd.print("Load Barricade");
        digitalWrite(RelayPin2, HIGH);  // Turn on Relay 2
        digitalWrite(IndicatorPin2, HIGH); // Turn ON IndicatorPin 2
        digitalWrite(IndicatorPin3, HIGH); // Turn ON IndicatorPin 3
        digitalWrite(IndicatorPin4, LOW); // Turn OFF IndicatorPin 4
      if(sensorState == SENSOR2_HIGH_SENSOR1_LOW)
      {
        // Prepare to go to the next state
        Serial.println("Machine Clear Going to WAIT_FOR_BOTH_LOW state");
        state = WAIT_FOR_BOTH_LOW;
      }
      break;
    case WAIT_FOR_BOTH_LOW:
      // Both buttons must be released to be able to continue.
        lcd.setCursor(0,0);
        lcd.print("Wait For Release");
        digitalWrite(IndicatorPin3, LOW); // Turn OFF IndicatorPin 3
      if(inputState == BOTH_BUTTONS_LOW)
      {
        // Prepare to go to the next state.
        Serial.println("Going to WAIT_FOR_BUTTON state");
        state = WAIT_FOR_BUTTON;
      }
      break;
    case WAIT_FOR_BUTTON:
// This is the state when everything is idle and no buttons are pressed.
// Normally both buttons are released.
// Waiting for the first button to be pressed.
// Both buttons could be pressed at the same time !
        lcd.setCursor(0,0);
        lcd.print("Engage Buttons   ");
      if(inputState == ONE_BUTTON_HIGH || inputState == BOTH_BUTTONS_HIGH)
      {
// At least one button is pressed.
// Prepare to go to the next state.
// Start a timer, because there is a timeout.
        Serial.println("Going to ONE_PUSHED_WAIT_FOR_OTHER_BUTTON state");
        previousMillis = currentMillis;
        state = ONE_PUSHED_WAIT_FOR_OTHER_BUTTON;
       }
      break;
    case ONE_PUSHED_WAIT_FOR_OTHER_BUTTON:
        lcd.setCursor(0,0);
        lcd.print("Wait for Other");
      if(inputState == BOTH_BUTTONS_LOW)
      {
// The button was released. That's not what we want.
// Return to the state to wait for both off.
        Serial.println("Going to WAIT_FOR_BOTH_LOW state");
        state = WAIT_FOR_BOTH_LOW;
      }
      else if(currentMillis - previousMillis >= TimeFrameForSecondButton)
      {
// The timeout has ended.
// The second button was not pushed after the first button
// within the timeout. That's too bad.
        Serial.println("Too Long Going to WAIT_FOR_BOTH_LOW state");
        state = WAIT_FOR_BOTH_LOW;
      }
      else if(inputState == BOTH_BUTTONS_HIGH)
      {
// The timeout has not ended and is still running.
// And now both buttons are pressed.
// We can continue.
// Start the timer for the SAFETY_WINDOW state.
        Serial.println("Going to FINAL_CHECK state");
        previousMillis = currentMillis;
        state = FINAL_CHECK;
      }
      break;
    case FINAL_CHECK:
      if(sensorState != SENSOR2_HIGH_SENSOR1_LOW)
      // Check to make sure the barricade hasn't been removed
      {
        // Prepare to go to the next state
        Serial.println("Machine Clear Going to CHECK_SENSORS state");
        state = CHECK_SENSORS;
      }
      else if(sensorState == SENSOR2_HIGH_SENSOR1_LOW)
      {
        Serial.println("Going to LOWER_RAILS state");
        state = LOWER_RAILS;
      }
      break;
    case LOWER_RAILS:
        lcd.setCursor(0,0);
        lcd.print("Lowering Rails  ");
      if(inputState != BOTH_BUTTONS_HIGH)
      // Check to be sure safety buttons are held and if not wait for another try
      {
        Serial.println("Going to WAIT_FOR_BOTH_LOW state from LOWER_RAILS");
        state = WAIT_FOR_BOTH_LOW;
      }
      else
      // If buttons 1 and 2 are still held proceed to turn on Relay 3 and onto the sensor check
      {
        digitalWrite(RelayPin3, HIGH);  // Turn ON RelayPin3
        digitalWrite(IndicatorPin5, HIGH); // Turn ON IndicatorPin5
        Serial.println("Going to CHECK_RAIL_SENSORS state");
        state = CHECK_RAIL_SENSORS;
      }
      break;
    case CHECK_RAIL_SENSORS:
       lcd.setCursor(0,0);
       lcd.print("Checking Rails  ");
       Serial.println(RsensorState);
       // Wait until the sensors are blocked to move into the next state
      if(RsensorState == BOTH_RSENSORS_LOW)
      {
        Serial.println("Going to SAFETY_WINDOW state");
        state = SAFETY_WINDOW;
      }
      break;
    case SAFETY_WINDOW:
        lcd.setCursor(0,0);
        lcd.print("Wait a second");
      if(inputState != BOTH_BUTTONS_HIGH)
      {
// During the safety time window, a button was released.
// Return to idle.
        Serial.println("Going to WAIT_FOR_BOTH_LOW state");
        digitalWrite(RelayPin, LOW);  // Turn OFF RelayPin
        digitalWrite(IndicatorPin, LOW); // Turn OFF IndicatorPin
        digitalWrite(RelayPin3, LOW);  // Turn OFF RelayPin3
        digitalWrite(IndicatorPin5, LOW); // Turn OFF IndicatorPin5
        state = WAIT_FOR_BOTH_LOW;
      }
      else if(currentMillis - previousMillis >= PushSafetyWindow)
      {
// The buttons are still pressed.
// The time window has reached the end.
// Prepare to go to the next state.
        Serial.println("Going to RELAY_ON state");
        previousMillis = currentMillis;
        digitalWrite(RelayPin, HIGH);  // Turn ON RelayPin
        digitalWrite(IndicatorPin, HIGH); // Turn ON IndicatorPin
        state = RELAY_ON;
      }
      break;
    case RELAY_ON:
        lcd.setCursor(0,0);
        lcd.print("Relay Engaged   ");
      if(inputState != BOTH_BUTTONS_HIGH)
      {
// One of the buttons was released.
// Stop the relay and return to idle.
// Although the relay was triggered, it was not succesful.
        failed++;
        Serial.print("Failed=");
        Serial.println(failed);
        Serial.println("Going to WAIT_FOR_BOTH_LOW state");
        digitalWrite( RelayPin, LOW);  // Turn Off RelayPin
        digitalWrite(IndicatorPin, LOW); // Turn Off IndicatorPin
        digitalWrite(RelayPin3, LOW);  // Turn OFF RelayPin3
        digitalWrite(IndicatorPin5, LOW); // Turn OFF IndicatorPin5
        state = WAIT_FOR_BOTH_LOW;
      }
      else if(currentMillis - previousMillis >= RelayOnTime)
      {
        // Everyting was okay.
        // The buttons are still pressed.
        // It was complete and succesful.
        // It is time to turn off the relay and return to idle.
        success++;
        Serial.print("Success=");
        Serial.println(success);
        Serial.println("Going to CLEAR_SENSORS state");
        lcd.setCursor(0,1);
        lcd.print("Cycles ");
        lcd.print(success);
        digitalWrite(RelayPin, LOW);  // Turn Off RelayPin
        digitalWrite(IndicatorPin, LOW); // Turn Off IndicatorPin
        digitalWrite(RelayPin3, LOW);  // Turn OFF RelayPin3
        digitalWrite(IndicatorPin5, LOW); // Turn OFF IndicatorPin5
        state = CLEAR_SENSORS;
      }
      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 an input state according to the 'enum' values.
  int value1 = debouncer1.read();
  int value2 = debouncer2.read();

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

  return(returnInputState);
}

 // This function is to return the state of sensors 1 and 2
  int getSensorState()
{
  int returnSensorState;

// Read the sensor states and create an input state
  int value3 = debouncer3.read();
  int value4 = debouncer4.read();

    if(value3 == HIGH && value4 == HIGH)
    {
      returnSensorState = BOTH_SENSORS_HIGH;
    }
    else if(value3 == HIGH && value4 == LOW)
    {
      returnSensorState = SENSOR1_HIGH_SENSOR2_LOW;
    }
    else if(value4 == HIGH && value3 == LOW)
    {
      returnSensorState = SENSOR2_HIGH_SENSOR1_LOW;
    }
    else
    {
      returnSensorState = BOTH_SENSORS_LOW;
    }
  return(returnSensorState);
}

 // This function is to return the state of Sensors 3 and 4
  int getRSensorState()
{
  int returnRSensorState;

// Read the sensor states and create an input state
  int value5 = debouncer5.read();
  int value6 = debouncer6.read();

  if(value5 == LOW && value6 == LOW)
    {
      returnRSensorState = BOTH_RSENSORS_LOW;
    }
    else if(value5 == HIGH && value6 == LOW)
    {
      returnRSensorState = SENSOR3_HIGH_SENSOR4_LOW;
    }
    else if(value6 == HIGH && value5 == LOW)
    {
      returnRSensorState = SENSOR4_HIGH_SENSOR3_LOW;
    }
    else
    {
      returnRSensorState = BOTH_RSENSORS_HIGH;
    }
  return(returnRSensorState);
}

```

The part giving me trouble is this state:

```
case CHECK_RAIL_SENSORS:
   lcd.setCursor(0,0);
   lcd.print("Checking Rails  ");
   Serial.println(RsensorState);
   // Wait until the sensors are blocked to move into the next state
  if(RsensorState == BOTH_RSENSORS_LOW)
  {
    Serial.println("Going to SAFETY_WINDOW state");
    state = SAFETY_WINDOW;
  }
  break;

```

It may be something to do with how the sensor state is acquired. I am using Bounce2 to debounce the inputs.

```
 // This function is to return the state of Sensors 3 and 4
  int getRSensorState()
{

  int returnRSensorState;

// Read the sensor states and create an input state
  int value5 = debouncer5.read();
  int value6 = debouncer6.read();

  if(value5 == LOW && value6 == LOW)
    {
      returnRSensorState = BOTH_RSENSORS_LOW;
    }
    else if(value5 == HIGH && value6 == LOW)
    {
      returnRSensorState = SENSOR3_HIGH_SENSOR4_LOW;
    }
    else if(value6 == HIGH && value5 == LOW)
    {
      returnRSensorState = SENSOR4_HIGH_SENSOR3_LOW;
    }
    else
    {
      returnRSensorState = BOTH_RSENSORS_HIGH;
    }
  return(returnRSensorState);
}

```

Any input is greatly appreciated! Please let me know if more clarification is necessary.

*Edit 07/12/18*

IF you use this code don't forget to update this section for it to work! The complete, corrected code is too large to post:

```
// Update the Bounce instances
  debouncer1.update();
  debouncer2.update();
  debouncer3.update();
  debouncer4.update();
  debouncer5.update();
  debouncer6.update();

```

# Answer
Your debouncer update section:

```
// Update the Bounce instances
  debouncer1.update();
  debouncer2.update();
  debouncer3.update();
  debouncer4.update();

```

is missing `debouncer5.update();` and `debouncer6.update();`. It is required to call `update()` once per `loop()` to ensure the object is up to date.
> 2 votes

---
Tags: sensors
---


title: Headers linking - PlatformIO

text:
# Question
Title: Headers linking - PlatformIO
For those who use the IDE Platform IO, I have an issue for you. I use to program a home application of sensor reading and use the library "JC\_Button.h" to manage buttons. There are other third-party libraries, but this in especial is cumbersome. The project tree is shown below.

.

The compile log of the build is here. I have few notion of what is happening. In my opinion, the project does not find the necessary lib.

Thank you in advance.

# Answer
It looks like you are not telling PlatformIO that you need the JC\_Button library. Try adding this to your `platformio.ini` file:

```
lib_deps = https://github.com/JChristensen/JC_Button

```
> 1 votes

---
Tags: compile
---


# Question
Title: hx711 and load cell read out 0 for calibration
I'm using this tutorial from Sparkfun https://learn.sparkfun.com/tutorials/load-cell-amplifier-hx711-breakout-hookup-guide

And using THEIR code. The only difference is I added a delay so it wouldn't write a reading 10x a second.

**QUESTION:** **How do I get nonzeros?**

```
#include "HX711.h"
#define DOUT  3
#define CLK  2
HX711 scale(DOUT, CLK);
float calibration_factor = -7050; //-7050 worked for my 440lb max scale setup
void setup() {
  Serial.begin(9600);
  Serial.println("HX711 calibration sketch");
  Serial.println("Remove all weight from scale");
  Serial.println("After readings begin, place known weight on scale");
  Serial.println("Press + or a to increase calibration factor");
  Serial.println("Press - or z to decrease calibration factor");
  scale.set_scale();
  scale.tare(); //Reset the scale to 0
  long zero_factor = scale.read_average(); //Get a baseline reading
  Serial.print("Zero factor: "); //This can be used to remove the need to tare the scale. Useful in permanent scale projects.
  Serial.println(zero_factor);
}
void loop() {
  scale.set_scale(calibration_factor); //Adjust to this calibration factor
  Serial.print("Reading: ");
  Serial.print(scale.get_units(), 20);
  Serial.print(" lbs"); //Change this to kg and re-adjust the calibration factor if you follow SI units like a sane person
  Serial.print(" calibration_factor: ");
  Serial.print(calibration_factor);
  Serial.println();
  if(Serial.available())
  {
    char temp = Serial.read();
    if(temp == '+' || temp == 'a')
      calibration_factor += 10;
    else if(temp == '-' || temp == 'z')
      calibration_factor -= 10;
  }
  delay(2000);
}

```

NOTE: I did not yet solder anything because I don't want to mess up the soldering and have to buy new cells and wait a week for shipping. So I placed pinheads in the amplifier and connected with m/f jumpers, and used alligator clips to connect to the loose wires.

# Answer
> 0 votes
Only VCC was connected to 5v. Had to add a breadboard to connect VDD as well.

(The kind folks at Sparkfun were able to help me out)

---
Tags: arduino-uno, programming, sensors, pins, code-review
---


# Question
Title: How to filter or eliminate earths magnetic field readings around 3D Magnetic sensor?
Im using the SparkFun MAG3110 3D sensor: https://www.sparkfun.com/products/12670

My application is essentially to make a contactless "magnetic joystick" using a local magnet for accurate and constant 3D position sensing in x, y, x planes of a local magnet, exactly like in this video (skip to 1:06): https://www.youtube.com/watch?v=CO6y6bjFfmY

The magnet I'm using is constant, so i'm trying to figure out a way to remove the earths magnetic field noise around the sensor so it cannot interfere with the sensors readings as if the earths magnetic field was virtually not present.

I've already written code that takes about 50 samples in each plane (x,y,z) and takes the average of each of the planes and outputs those readings minus the average offset values (Ex: Serial.print(x-xavg), Serial.print(y-yavg), Serial.print(z-zavg)). I did this to basically "zero out" the earths magnetic field, like zeroing a weight scale.

That wasn't really effective and results were not anywhere near constant after introducing and removing the local magnet, over and over again.

I've considered:

* a low pass filter
* sensor fusion using my gyroscope/accelerometer module (I know that sensor fusion is usually used to calibrate the Magnometer to be a more accurate compass, but is there anyway to use this technique to eliminate the earths magnetic field?)
* using data from http://www.magnetic-declination.com/ to tie into my calculations to offset the readings
* Using an electromagnet module to output the earths magnetic field inverted continuously in an attempt to cancel out the earths magnetic field
* trying to find a whole new sensor completely that does not have a low enough sensitivity to even detect earths magnetic field

So my questions are:

1. Is there any way to do this?
2. Are any of my considerations practical or possible?
3. Are there even any 3d magnetic sensors on the market that do NOT pick up the earths magnetic field? - I've contacted SparkFun, Arrow, ST, and other companies about this exact question and never really get a sure answer on this question specifically?
4. if not, how was this man in the video able to reduce noise around his sensor? - He shows visually that his sensor is starting to filter out noise, saying that he's using an "adaptive averages" algorithm and links to some code, but I was unable to see/find that and don't understand how he is doing that?

# Answer
> 1 votes
One option is a magnetic gradiometer. This consists of two magnetometers, which are placed at different distances from the local magnet (one close, one far). You subtract the readings to eliminate dependence on the earth's magnetic field, on the (fairly good) assumption that the earth's field does not change over the distance between the sensors.

# Answer
> 1 votes
Earth magnetic field is pretty constant. In your measurements it will show up as an offset that you could subtract, but of course it will change if the sensor rotates.

Whatever measurement noise you see certainly doesnt' come from Earth. Either your setup is close to a local source of magnetic radiation (inductors, wires with high alternating current), or your sensor picks up noise from its power supply. Put your sensor away from high currents, power it with batteries and see how much noise you'll get in that case.

# Answer
> 0 votes
If you're already subtracting the mean of several samples of the ambient field, what's left should be noise, and much lower than your signal (the field due to your handheld magnet).

If you're trying to get a level of precision at the same order of magnitude as the noise, you'll need a larger 'N' (sample size), perhaps of both the ambient and of the desired signal, or apply even more stringent statistical techniques.

But I doubt that's what the experimenter in the video was doing. It's more likely he was close enough the sensor and with a strong enough magnet, that the noise was insignificant by comparison. He was using a rare-earth magnet - are you? Those typically have a stronger field that a more common ceramic or steel one. If not, you may need to use yours at a smaller distance from the sensor to get a similar signal to noise ratio.

---
Tags: arduino-uno, sensors, magnetometer, calculation, calibration
---


# Question
Title: L298N, HC-05 Simple Bluetooth remote car not running in Arduino
Arduino board type used in this session is Arduino Uno R3 DIP/SMD CH340

Below is the description of wiring and code in Arduino to assemble a Bluetooth RC car using android smartphone:

1. Tested the motor dc result both of wheel works (can spin forward and or backward). power direct from the battery.
2. Tested HC-05 bluetooth moduled. The phone can paired the bluetooth module.
3. Tested out1 out2 out3 and out4 on L298N using direct power from the battery the wheel spinning (forward and or backward).
4. The code for the Bluetooth rc simple car used below as described.

The car failed to move (forward, backward, turn left/right). how to make the motor dc and or the motor stepper works remotely. thank you

#include SoftwareSerial mySerial(12, 13); // RX, TX #define m1 3 #define m2 5 #define m3 9 #define m4 10

```
int data=0,kec=0;
boolean forward=true;

int fast[11]={0,80,100,120,140,160,180,200,220,240,255};

void setup()
{
  pinMode(m1,OUTPUT);
  pinMode(m2,OUTPUT);
  pinMode(m3,OUTPUT);
  pinMode(m4,OUTPUT);

  mySerial.begin(9600);
 }

void motorOut(unsigned char lpwm, unsigned char rpwm, boolean arrow){
   if(arrow==false){
      digitalWrite(m3,HIGH);
      digitalWrite(m1,LOW);
      analogWrite(m4,255-lpwm);
      analogWrite(m2,rpwm);
   }
   else{
     digitalWrite(m3,LOW);
     digitalWrite(m1,HIGH);
     analogWrite(m4,lpwm);
     analogWrite(m2,255-rpwm);
  }
}

void loop(){
  if(mySerial.available()>0){
    data=mySerial.read();
    if (data =='0') { kec=0;}
      else if (data =='1') { kec=1;}
        else if (data =='2') { kec=2;}
          else if (data =='3') { kec=3;}
            else if (data =='4') { kec=4;}
             else if (data =='5') { kec=5;}
              else if (data =='6') { kec=6;}
                else if (data =='7') { kec=7;}
                  else if (data =='8') { kec=8;}
                    else if (data =='9') { kec=9;}
                      else if (data =='q') {kec=10;}

  //S= Stop
 if (data == 'S')
 { motorOut(0,0,false); }

//F=Forward
if (data=='F')
{ motorOut(fast[kec],fast[kec],true); }

//I=turn right forward
if (data=='I')
{ motorOut(fast[kec],((fast[kec])/2),true);}

//G=turn left forward
if (data=='G')
{ motorOut(((fast[kec])/2),fast[kec],true); }

//R=turn right
if(data=='R')
{ motorOut(fast[kec],0,true); }

//L=turn left
if(data=='L')
{ motorOut(0,fast[kec],true); }

//B=back
if(data=='B')
{ motorOut(fast[kec],fast[kec],false); }

//H=turn left back
 if (data=='H')
   { motorOut(((fast[kec])/2),fast[kec],false); }

//turn right back
   if (data=='J')
    { motorOut(fast[kec],((fast[kec])/2),false); }
  }
}

```

# Answer
> -1 votes
sorry for my careless. finaly its works....wrong pin assign the main problem....should be IN1, IN2, IN4 and IN3 not IN1, IN2, IN3 and IN4. thank you for all hands for help before

---
Tags: arduino-uno, motor, hc-05, l298n
---


title: ESP8266 cannot read POST parameters

text:
# Question
Title: ESP8266 cannot read POST parameters
I'm working on a simple REST server. I made method to handle `http://<esp8266_IP>/test`. The GET method works like a charm and I got the response. Then I tried to send a POST with a JSON data (I used PostMan) but I cannot read anything.

Searching online I read ESP8266 library cannot parse JSON and in that case I can found plain text into `server.arg("plain")`. I tried that but no success

How can I read the data into the POST method?

```
ESP8266WebServer server(80);
...

void handleTest()
{
    if (server.method() == HTTP_GET)
    {
        ...
    }
    else if (server.method() == HTTP_POST)
    {
        String message = "POST\nHeaders:\n";
        for (uint8_t i = 0; i < server.headers(); i++)
        {
            message += server.headerName(i) + ": " + server.header(i) + "\n";
        }
        message += "\nRequest params:\n";
        for (uint8_t i = 0; i < server.args(); i++){
            message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
        }
        server.send(202, "text/plain", message);
    }
}
...
void setup()
{
    WiFi.begin(ssid, password);
    Serial.println("");

    // Wait for connection
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    if (MDNS.begin("esp8266")) {
        Serial.println(F("[Server] MDNS responder started"));
    }

    server.on("/test", handleTest);
}

```

# Answer
Instead of using below in `handleTest()`

```
else if (server.method() == HTTP_POST)

```

try using below in `setup()`

```
server.on("/test", POST, handleTest);

```
> 1 votes

---
Tags: esp8266, web-server
---


# Question
Title: Which platform is better to debug Arduino memory problems? Linux or Windows?
I am developing a product. I developed every module in the firmware individually. Now I am integrating them but getting memory issues. I am not able to see how the memory is allocated inside the MCU during the runtime.

Can Linux help me debug issues better, using its command than Windows platform?

Thanks in advance.

# Answer
The operating system is irrelevant. If you want to debug the target you need a debugger and a debugging environment. That means a proper hardware debugger interface, not an Arduino's USB serial port, and a proper IDE like Atmel Studio not the Arduino IDE. All are available for both Linux and Windows.
> 2 votes

---
Tags: arduino-ide, c++, atmega328, linux, memory
---


# Question
Title: Variable that holds the users input doesn't empty itself, so the program only works once
This code seems to function, but only works once before I need to press the reset button. Otherwise, it repeats the same error message. It might have something to do with emptying the String variable.

```
// A program that will allow a user to turn ON one of several LED's
// using if...else statements.

String pinAsk="Please select which pin you would like to supply power to:";

// A different coloured LED will be attached to each pin number.
int Red=14; // This one would be the A0 Header on the Arduino
int Yellow=15; // A1
int Green=16; // A2
int Blue=17; // A3
int Purple=18; // A4
int Violet=19; // A5

int invalidColorRed;
int invalidColorYellow;
int invalidColorGreen;
int invalidColorBlue;
int invalidColorPurple;
int invalidColorViolet;
// If the user didn't select any of these colours, then all these variables will
// be given a 1. This triggers an if...else condition that prints out a message,
// to say that they didn't enter a valid input.

String inputColor;
 // The String variable can store integers as well as other characters

String activePin1="The ";
// The users input is printed out between these.
String activePin2=" LED is now active";

int Volts=102; // The 102 tells the Arduino to output 2+ (Two volts)

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

 pinMode(Red,OUTPUT);
 pinMode(Yellow,OUTPUT);
 pinMode(Green,OUTPUT);
 pinMode(Blue,OUTPUT);
 pinMode(Purple,OUTPUT);
 pinMode(Violet,OUTPUT);
}

void loop() {
 Serial.println(pinAsk);
 Serial.println("Red = A0 (14)");
// These describe the available pins and their colors.
 Serial.println("Yellow = A1 (15)");
 Serial.println("Green = A2 (16)");
 Serial.println("Blue = A3 (17)");
 Serial.println("Purple = A4 (18)");
 Serial.println("Violet = A5 (19)");

  while (Serial.available()==0) { } // Wait for user to respond

 inputColor=Serial.readString(); // Store their input into an empty variable

// The following segment checks whether the user has selected to turn ON
// the Red LED.

 if (inputColor=="14") analogWrite(Red,Volts);
 // The String variable can also store integers as well as other characters
 else if (inputColor=="A0") { analogWrite(Red,Volts); }
 else if (inputColor=="Red") { analogWrite(Red,Volts); }
 else if (inputColor=="red") { analogWrite(Red,Volts); }
// User may only use lower-case letters.
  // The "equal equal" sign == doesn't assign a new value.
  // It will test whether a number or string is the same
// as described at the end of the equal's sign.

 else { analogWrite(Red,LOW); }
// If the users input, stored within inputColor, isn’t "14", "A0", "Red",
// or "red" then this Red LED will be turned off.

 if (inputColor!="14" && inputColor!="A0" && inputColor!="Red" && inputColor!="red") { invalidColorRed=1; }

// The exclamation mark or bang ! is a NOT operator.
// A "bang equal" sign != is placed after a variable, such as inputPin!=
// to say that the value must NOT be equal to "14". If the expression is true
// (The condition is fulfilled), then a 1 is given to invalidColorRed.

// The AND operator, shown as a double ampersand && combines
// all the conditions into the same expression. By putting this operator `
// between them, it tells the Arduino that all the variables must NOT be
// any of the values described.

// Each colour has its own invalidColor variable.
// If the user does not enter any of the valid inputs
// (Which means the LED is off), a 1 will be assigned to this colors
// invalidColor variable.

// If all these invalidColor variables have a value of 1, it means all
// the LED’s are off. This can be made into another condition that causes
// the Arduino to read an expression that tells the user that they haven’t
// entered a proper input and to try again.

// Checking to see if the user has opted to turn on the Yellow LED.
 if (inputColor=="15") analogWrite(Yellow,Volts);
 else if (inputColor=="A1" || "Yellow" || "yellow") { analogWrite(Yellow,Volts); }
// The OR || operator combines the Lower-case and Upper-case letters in
// the same expression. A space between the operator and variables is not
// necessary, but improves readability. Also, a single pair of quotation
// marks "" can encase the conditions if || is being used.
 else { analogWrite(Yellow,LOW); }

 if (inputColor!="15" && inputColor!="A1" && inputColor!="Yellow" && inputColor!="yellow") { invalidColorYellow=1; }

// Checking to see if the user has opted to turn on the Green LED.
 if (inputColor=="16") analogWrite(Green,Volts);
 else if (inputColor=="A2") { analogWrite(Green,Volts); }
 else if (inputColor=="Green") { analogWrite(Green,Volts); }
 else if (inputColor=="green") { analogWrite(Green,Volts); }
 else { analogWrite(Green,LOW); }

 if (inputColor!="16" && inputColor!="A2" && inputColor!="Green" && inputColor!="green") { invalidColorGreen=1; }

// Checking to see if the user has opted to turn on the Blue LED.
 if (inputColor=="17") analogWrite(Blue,Volts);
 else if (inputColor=="A3") { analogWrite(Blue,Volts); }
 else if (inputColor=="Blue") { analogWrite(Blue,Volts); }
 else if (inputColor=="blue") { analogWrite(Blue,Volts); }
 else { analogWrite(Blue,LOW); }

 if (inputColor!="17" && inputColor!="A2" && inputColor!="Blue" && inputColor!="blue") { invalidColorBlue=1; }

// Checking to see if the user has opted to turn on the Purple LED.
 if (inputColor=="18") analogWrite(Purple,Volts);
 else if (inputColor=="A4") { analogWrite(Purple,Volts); }
 else if (inputColor=="Purple") { analogWrite(Purple,Volts); }
 else if (inputColor=="purple") { analogWrite(Purple,Volts); }
 else { analogWrite(Purple,LOW); }

 if (inputColor!="18" && inputColor!="A4" && inputColor!="Purple" && inputColor!="purple") { invalidColorPurple=1; }

// Checking to see if the user has opted to turn on the Violet LED.
 if (inputColor=="19") analogWrite(Violet,Volts);
 else if (inputColor=="A5") { analogWrite(Violet,Volts); }
 else if (inputColor=="Violet") { analogWrite(Violet,Volts); }
 else if (inputColor=="violet") { analogWrite(Violet,Volts); }
 else { analogWrite(Violet,LOW); }

 if (inputColor!="19" && inputColor!="A5" && inputColor!="Violet" && inputColor!="violet") { invalidColorViolet=1; }

 if (invalidColorRed==1 && invalidColorYellow==1 && invalidColorGreen==1 && invalidColorBlue==1 && invalidColorViolet==1)
 {
  // This if statement is asking "Are all invalidPin variables equal to 1?"
  // In other words, "Are all the LED's off?"
  Serial.println("");
  Serial.println("That is not a valid option, please try again");
  Serial.println(""); }
  else if (invalidColorRed==0 || invalidColorYellow==0 || invalidColorGreen==0 || invalidColorBlue==0 || invalidColorViolet==0)
  {
  // If the user entered a valid input for at least one LED,
  // this message will play instead.
  Serial.println("");
  Serial.print(activePin1);
  Serial.print(inputColor); // The users input is printed out here.
  Serial.println(activePin2);
  Serial.println(""); }

  inputColor=""; // Shouldn't this empty the variable?
}

```

Can someone tell me whats wrong?

# Answer
Without looking deeply into your code, this is wrong:

```
if (inputColor=="A1" || "Yellow" || "yellow")

```

You need to repeat what you are testing against, ie.

```
if (inputColor=="A1" || inputColor=="Yellow" || inputColor=="yellow")

```

You might want to use the auto-format tool (Ctrl+T). Putting a lot of stuff in one line is just confusing.
> 0 votes

---
Tags: arduino-uno, serial, led, variables, loop
---


# Question
Title: Arduino based IR remote control - Transmission issue
I created a circuit of a 25 key IR remote controller for my RuneAudio device. The device is a standalone ATmega328P-PU running at 3V (2 AAA batteries) with 8 MHz internal clock. The circuit has 5 rows and 5 columns and uses Arduino keypad library. The code is mostly a copy of Nick Gammon's code (http://www.gammon.com.au/forum/?id=11497&reply=4#reply4), with slight modification for my purpose.

Following is the circuit (R1=1K, R2=10K, R3=62 Ohm):

Following is the code I am using:

```
#include <Keypad.h>
#include <avr/sleep.h>
#include <avr/power.h>
#include <IRremote.h>

const byte ROWS = 5;
const byte COLS = 5;
byte keynum;

char keys[ROWS][COLS] =
{
  {'E', 'D', 'C', 'B', 'A'},
  {'J', 'I', 'H', 'G', 'F'},
  {'O', 'N', 'M', 'L', 'K'},
  {'T', 'S', 'R', 'Q', 'P'},
  {'Y', 'X', 'W', 'V', 'U'}
};

byte rowPins[ROWS] = {9, 10, 11, 12, 13}; // Keypad row pins
byte colPins[COLS] = {4, 5, 6, 7, 8};     // Keypad column pins

unsigned long IRCode[25] =  {0xB54A38C7, 0xB54A30CF, 0xB54AE191, 0xB54ADCDD, 0xB54AD6C3, 0xB54AE5ED, 0xB54A50AF, 0xB54A9867, 0xB54AB04F, 0xB54A48B7, 0xB54AD02F, 0xB54AFCF7, 0xB54AF56C, 0xB54AEFEE, 0xB54AEAA0, 0xB54A02FD, 0xB54B176F, 0xB54B100D, 0xB54B08F6, 0xB54B031D, 0xB54A42BD, 0xB54AC23D, 0xB54A1AE5, 0xB54A7887, 0xB54A827D};

// Number of items in an array
#define NUMITEMS(arg) ((unsigned int) (sizeof (arg) / sizeof (arg [0])))

// IR setup (NEC remote)
const byte IRledPin = 3;
const int NumBits = 32;

// Define
Keypad kpd = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
IRsend irsend;

// turn off interrupts until we are ready
ISR (PCINT0_vect)
  {
  PCICR = 0;  // cancel pin change interrupts
  } // end of ISR (PCINT0_vect)

ISR (PCINT1_vect)
  {
  PCICR = 0;  // cancel pin change interrupts
  } // end of ISR (PCINT1_vect)

ISR (PCINT2_vect)
  {
  PCICR = 0;  // cancel pin change interrupts
  } // end of ISR (PCINT2_vect)

void setup ()
{
  pinMode (IRledPin, OUTPUT);

  // Pin change interrupt masks (See list on Nick Gammons original code)
  PCMSK0 |= bit (PCINT1);   // Pin 9
  PCMSK0 |= bit (PCINT2);   // Pin 10
  PCMSK0 |= bit (PCINT3);   // Pin 11
  PCMSK0 |= bit (PCINT4);   // Pin 12
  PCMSK0 |= bit (PCINT5);   // Pin 13
  Serial.begin(9600);
}

void reconfigurePins ()
{
Serial.print("1 Reconfig pins");
Serial.println("");
  byte i;
  for (i = 0; i < NUMITEMS (colPins); i++)
  {
    pinMode (colPins [i], OUTPUT);
    digitalWrite (colPins [i], HIGH);
  }

  for (i = 0; i < NUMITEMS (rowPins); i++)
    {
    pinMode (rowPins [i], INPUT_PULLUP);
    }   // end of for each row
Serial.print("2 DONE Reconfig pins");
Serial.println("");
  }  // end of reconfigurePins

void goToSleep ()
{
Serial.print("3 inside SLEEP");
Serial.println("");

  // Set up keypress detection
  byte i;
  for (i = 0; i < NUMITEMS (colPins); i++)
  {
    pinMode (colPins [i], OUTPUT);
    digitalWrite (colPins [i], LOW);
  }

  for (i = 0; i < NUMITEMS (rowPins); i++)
  {
    pinMode (rowPins [i], INPUT_PULLUP);
  }  // end of for each row

  // Check no pins pressed (otherwise wake on a key release)
  for (i = 0; i < NUMITEMS (rowPins); i++)
  {
    if (digitalRead (rowPins [i]) == LOW)
    {
  Serial.print("ROW LOW: ");
  Serial.print(rowPins [i]);
Serial.println("");
      reconfigurePins ();
      return;
    }
  }

  // Overcome any debounce delays built into the keypad library
  delay (10);

  // At this point, pressing a key should connect the high in the row to the
  // to the low in the column and trigger a pin change
Serial.print("4 Going to SLEEP");
Serial.println("");

  set_sleep_mode (SLEEP_MODE_PWR_DOWN);
  sleep_enable();

Serial.print("5 AWAKE");
Serial.println("");

  byte old_ADCSRA = ADCSRA;
  // Disable ADC to save power
  ADCSRA = 0;

  power_all_disable ();  // turn off various modules

  PCIFR  |= bit (PCIF0) | bit (PCIF1) | bit (PCIF2);   // clear any outstanding interrupts
  PCICR  |= bit (PCIE0) | bit (PCIE1) | bit (PCIE2);   // enable pin change interrupts

  // Turn off brown-out enable in software
  MCUCR = bit (BODS) | bit (BODSE);
  MCUCR = bit (BODS);
  sleep_cpu ();

  // Cancel sleep as a precaution
  sleep_disable();
  power_all_enable ();   // enable modules again
  ADCSRA = old_ADCSRA;   // re-enable ADC conversion

  // Put keypad pins back how they are expected to be
  reconfigurePins ();
Serial.print("6 Leaving SLEEP");
Serial.println("");

}

void loop ()
{

  byte key =  kpd.getKey();
  if (!key)
  {
Serial.print("CALLING SLEEP");
Serial.println("");

    // Sleep if no key is pressed
    goToSleep ();
    return;
 Serial.print("After RETURN");
Serial.println("");

  }

  // Subtract ASCII value of first key value to obtain HEX array argument
  keynum = key - 'A';
Serial.print("SENDING IR.....................................................................................");
Serial.println("");

  // sendNEC(unsigned long data, int nbits);
  irsend.sendNEC(IRCode[keynum], NumBits);
Serial.print(IRCode[keynum]);
Serial.println("");

}

```

The sketch compiles and uploads just fine. It detects key presses and sends out IR signals. But it misses around half of the key presses. I am testing on a breadboard using a single key - R1C5 (S5 in the schematic).

I must admit that despite spending a lot of time on ATmega328 datasheet and Nick's blogs on power saving, I am not able to fully understand the power saving features due to my not-so-mature skills and the complexity of overall project (Raspberry Pi based rune audio + TDA7439 based tone controller + ATmega based power switch for Pi + 2channel Audio amplifier + this IR remote).

I added a few serial prints to check what is happening. The serial outs seem to be out of sync and last message before sleep is "CALLING SLEEP" whereas I expected it to be "4 Going to SLEEP". And adding serial print mysteriously reduces the number of misses.

Following is the serial output, just after power on and a single key press:

```
EP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving SLEEP
SENDING IR.....................................................................................
3041540295
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig

```

The following happens after multiple key presses:

```
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig pins
SENDING IR.....................................................................................
3041540295
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig pins
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving SLEEP
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving
CALLING SLEEP
3 inside SLEEP
4 Going to SLEEP
5 AWAKE
1 Reconfig pins
2 DONE Reconfig pins
6 Leaving SLEEP
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig pins
SENDING IR.....................................................................................
3041540295
CALLING SLEEP
3 inside SLEEP
ROW LOW: 9
1 Reconfig pins
2 DONE Reconfig

```

It would be of great help if someone could show me the light here.

---

Ok. Replaced long serial print strings with single digits where these stand for: 1= 1 Reconfig pins 2= 2 DONE Reconfig pins 3= 3 inside SLEEP 4= ROW LOW= 5= 4 Going to SLEEP 6= 5 AWAKE 7= 6 Leaving SLEEP 8= CALLING SLEEP .....= SENDING IR

I see where it is failing. Now getting the following serial out:

```
6
1
2
7
8
3
49
1
2
8
3
49
1
2
8
3
49
1
2
8
3
49

```

So the program wakes on keypress (6), then reconfigures the pins (1,2), leaves the sleep function (7) enaters the main (8). Here `byte key = kpd.getKey()` DOES NOT detect a keypress and calls sleep again (3). Sleep DOES detect a low row 9 (4-9). After this it gets stuck in a loop of main and sleep functions till key press is over. For now the problem seems to be with kpd.getKey().

# Answer
> 1 votes
> I added a few serial prints to check what is happening. The serial outs seem to be out of sync and last message before sleep is "CALLING SLEEP" whereas I expected it to be "4 Going to SLEEP".

Printing to Serial doesn't send data to your computer. It just adds that data to a TX buffer, and then an interrupt sends each character one byte at a time.

Your prints are happening, but aren't being sent from the queue before the MCU goes to sleep.

You should add

```
Serial.flush();

```

before actually going to sleep to ensure that all data from the TX buffer has been sent. That way your messages will actually be meaningful.

Also if you send more than 64 bytes of data through Serial in a short space of time it will block and wait for some data to be sent out of the TX buffer. The buffer is only 64 bytes in size, so if there is no room left it has to wait for the interrupt. That waiting slows your entire sketch down and can affect the way the sketch operates. A bit like quantum physics - the act of observing the operation of the sketch changes the operation of the sketch.

---
Tags: atmega328, sleep
---


title: How to change byte to int? - Arduino

text:
# Question
Title: How to change byte to int? - Arduino
I have searched everywhere, but can you please help me to get this Byte into int, there are alot of examples on the internet, but not for a beginer like me

CODE:

```
int Button[] = {2, 4, 7 };

byte E = sizeof(Button);

int I = (int) E;

void setup() {

  Serial.begin(9600);

  Serial.print (I); // has to be 3, currently 61

  }

void loop() {

 }

```

I don't know why the byte E doen't convert to a int in int I by using the (int)E command, what would also be convinient would be to read the amount of elements directly as an int . (you might wonder, why I want to do this, it is beacause, I am writing a program with multiple buttons, so I just want to add another pin to the array and not have to change the "I" int( the I int is used for loops))

# Answer
> 2 votes
The code works correctly. The function `sizeof()` returns the number of bytes in a variable, not the number of elements. Your array is of type `int`, which consists of 2 bytes each. So in sum you get 6 bytes for the whole array.

What you want to do (calculating the number of elements in the array) is to divide the number of bytes in the array by the number of bytes for one element:

```
int I = sizeof(Button)/sizeof(Button[0]);

```

The conversion from `byte` to `int` worked correctly, but you really don't need it. You can calculate things with both types the same way. The only difference is the value range. Since a negative element number doesn't make sense and you surely don't want to define more than 255 buttons, you can choose yourself, what you want to use. Using `byte` would save you one byte of memory.

# Answer
> 2 votes
`sizeof` returns the size in bytes. int is two bytes in 8-bit AVR mcu. an array of 3 ints has 6 bytes.

return type of `sizeof` is `size_t` which in 8-bit AVR is same as unsigned int

---
Tags: arduino-uno, array
---


title: Controlling motors and servo with L298N

text:
# Question
Title: Controlling motors and servo with L298N
I'm using an L298N to control the two motors of a robot car, and I also have a servo controlling the HC-SR04. The motors and sensor work fine together, and the servo and sensor work fine together. But when I put them in the code together, only the servo works. Code is

```
#include <Servo.h>

// motor one
int enA = 9;    //enable PWM for right motor
int rightFwd = 7;    //right forward
int rightBack = 6;    //right backward
// motor two
int enB = 10;   //enable PWM for left motor
int leftFwd = 5;    //left forward
int leftBack = 4;    //left backward

//ultrasonic sensor
int trig = 2;
int echo = 3;

//servo for looking left and right
//int servoPin = 8;

int runSpeed = 255;
int distance;
int leftDistance;
int rightDistance;
//int servoCenter = 100;
//int lookAngle = 60;

//Servo servoMotor;

void setup()
{
  Serial.begin(9600);
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(rightFwd, OUTPUT);
  pinMode(rightBack, OUTPUT);
  pinMode(leftFwd, OUTPUT);
  pinMode(leftBack, OUTPUT);
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
//  pinMode(servoPin, OUTPUT);

//  servoMotor.attach(servoPin);
//  servoMotor.write(servoCenter);
}

void loop()
{
  test();
}

void goForward()
{
  Serial.println("Going forward");
  analogWrite(enA, runSpeed*3/4);
  analogWrite(enB, runSpeed*3/4);
  digitalWrite(leftBack,LOW);
  digitalWrite(leftFwd,HIGH);
  digitalWrite(rightBack,LOW);
  digitalWrite(rightFwd,HIGH);
}

void goBackward()
{
  Serial.println("Going backward");
  analogWrite(enA, runSpeed*3/4);
  analogWrite(enB, runSpeed*3/4);
  digitalWrite(leftBack,HIGH);
  digitalWrite(leftFwd,LOW);
  digitalWrite(rightBack,HIGH);
  digitalWrite(rightFwd,LOW);
}

void turnLeft()
{
  Serial.println("Turning left");
  analogWrite(enA, runSpeed*3/4);
  analogWrite(enB, runSpeed*3/4);
  digitalWrite(leftBack,HIGH);
  digitalWrite(leftFwd,LOW);
  digitalWrite(rightBack,LOW);
  digitalWrite(rightFwd,HIGH);
}

void turnRight()
{
  Serial.println("Turning right");
  analogWrite(enA, runSpeed*3/4);
  analogWrite(enB, runSpeed*3/4);
  digitalWrite(leftBack,LOW);
  digitalWrite(leftFwd,HIGH);
  digitalWrite(rightBack,HIGH);
  digitalWrite(rightFwd,LOW);
}

void allStop()
{
  Serial.println("Stopping");
  digitalWrite(leftBack,LOW);
  digitalWrite(leftFwd,LOW);
  digitalWrite(rightBack,LOW);
  digitalWrite(rightFwd,LOW);
}

int getDistance()
{
  //  Getting the distance from the sensor
  long duration, distance;
  digitalWrite(trig,HIGH);
  delayMicroseconds(1000);
  digitalWrite(trig, LOW);
  duration=pulseIn(echo, HIGH);
  distance =(duration/2)/29.1;
  Serial.print(distance);
  Serial.println("CM");
  delay(10);
  return distance;
}

//int lookRight()
//{
//  Serial.println("Looking right\n");
//  servoMotor.write(50);
//  delay(500);
//  int distance = getDistance();
//  delay(100);
//  servoMotor.write(servoCenter - lookAngle);
//  delay(100);
//  servoMotor.write(servoCenter);
//  return distance;
//}
//
//int lookLeft()
//{
//  Serial.println("Looking left\n");
//  servoMotor.write(servoCenter + lookAngle);
//  delay(500);
//  int distance = getDistance();
//  delay(100);
//  servoMotor.write(servoCenter);
//  return distance;
//  delay(100);
//}

void test()
{
  getDistance();
  goForward();
  delay(1000);
  allStop();
  delay(1000);
  goBackward();
  delay(1000);
  allStop();
  delay(1000);
  turnLeft();
  delay(1000);
  allStop();
  delay(1000);
  turnRight();
  delay(1000);
  allStop();
  delay(1000);
//  lookLeft();
//  lookRight();
}

```

I've commented out the servo parts; as it is, the motors and the sensor perform the test perfectly. Uncommenting the servo parts makes the servo and sensor work, but the motors stop.

I see from here that

> On boards other than the Mega, use of the library disables analogWrite() (PWM) functionality on pins 9 and 10, whether or not there is a Servo on those pins.

I'm using 9 and 10 as the enA and enB pins respectively for the PWM of the motors, and the servo is on pin 8.

I built up the code from scratch, testing each function as I went, and it's all good apart from this problem. How can I fix this?

# Answer
> 2 votes
The comment you have found which is also on the Servo library page https://www.arduino.cc/en/Reference/servo and is the core of your problem.

On an Uno, you will have to change the PWM pins to 3,5,6 or 11 as the timer which provides the PWM for pins 9 and 10 is now being used for the Servo library.

This is probably the easiest option, especially if you are using an L298 module, as you should be able to just swap the leads.

Alternatively, there may be an alternative Servo library available which does not use that timer (a quick Google showed some candidates, but I have not tested).

---
Tags: arduino-uno, motor, servo, l298n
---


title: Weird issue with software serial?

text:
# Question
Title: Weird issue with software serial?
Hi i am trying to write a library to communicate between the arduino and the esp 8266. I wrote a command that that sends an AT command to the esp chip. So far I have tested these commands : AT, AT+GMR, AT+CIFSR, AT+CIPMUX=1 etc. with no issue the communication seem robust.

When I tried to send the AT+CIPSERVER=1 command the function did not work. After some attempts to debug the program I manage to get it working but I do not understand why. And this is my issue, I though it was working because of the extra delay that was occurring in my code but after some testing that was not the reason.

Could anyone please explain to me what is happening ? I will continue to work on the code until I figure it out.

**The code :**

**Header file**

```
#ifndef _ESPLIB_h
#define _ESPLIB_h

#if defined(ARDUINO) && ARDUINO >= 100
    #include "Arduino.h"
#else
    #include "WProgram.h"
#endif

#include <SoftwareSerial.h>

// Definitions
#define DEBUG       1
#define BUFFSIZE    64
#define TCPORT      23050
#define ESPTIMEOUT  10000
enum espResponse {
    ok,
    error,
    other
};

// AT Commands
#define CRLF    "\r\n"
#define Q       "=?"
#define AT      "AT"
#define GMR     "+GMR"
#define RST     "+RST"
#define CMUX    "+CIPMUX=1"
#define CWMOD   "+CWMODE"
#define CSERV   "+CIPSERVER=1"
#define CFSR    "+CIFSR"
#define CSEND   "+CIPSEND"

class espdevice
{
    public:
        // Functions
        espdevice(int rx, int tx, int baud);
        void serialEnable(void);
        //boolean tcpServerInit(void);

        #if DEBUG
            void serialDebug(void);
        #endif

    private:

        // Variables
        // Serial Setup parameters
        int _rx;
        int _tx;
        int _baud;

        // Software Serial
        int _espSerialIndex = 0;
        char _espSerialBuffer[BUFFSIZE];
        SoftwareSerial *_espSerial;

        // private functions
        //espResponse _sendEspCommand(const char* cmd);
        boolean _sendEspCommand(const char* cmd);
        espResponse _espCommandOK(void);
        boolean _espSerialAvailable(void);

        // Debug mode
        #if DEBUG

        // variables
        int _serialIndex = 0;
        char _serialBuffer[BUFFSIZE];

        // functions
        void _serialDebug(int select);
        int _arduinofreeRam(void);
        boolean _serialAvailable(void);

        #endif

};

#endif

```

**What I am executing**

```
        _sendEspCommand("AT+CIPMUX=1\r\n");
        _sendEspCommand("AT+CIPSERVER=1,23050\r\n");
        _sendEspCommand("AT+CIFSR\r\n");

```

**Now the function definition**

```
boolean espdevice::_sendEspCommand(const char* cmd)
{
    // variables
    int count = 0;
    boolean flag = false;
    espResponse status = other;

    // sending the command to the ESP
    _espSerial->write(cmd);
    #if DEBUG
        Serial.print("command echo : ");
        Serial.write(cmd);
        Serial.println();
    #endif

    //while (!(status==ok||status==error) || count < 1000) **<- why this thing works  ??????????????**
    //while (status == other && count < ESPTIMEOUT) <- does not work
    while ((status == other) || (count < ESPTIMEOUT)) <- THIS works too
    //while(count < ESPTIMEOUT) <- does not work
    {
        //while (!_espSerial->available()) {};
        if (_espSerialAvailable())
        {
            Serial.println ("Data Are available");
            status = _espCommandOK();
            #if DEBUG
                Serial.print("Data Received from ESP : ");
                Serial.print(_espSerialBuffer);
                Serial.println("");
                Serial.println(status);
            #endif
            /* //code used with the not working part
            if (status == ok)
            {
                flag = true;
                break;
            }
            else if (status == error)
            {
                flag = false;
                break;
            }
            else
            {
            }
            */
        }
        count++;
    }
    Serial.println(count);
    return flag;
}

```

**And the two other functions that are called**

**\_espSerialAvailable()**

```
boolean espdevice::_espSerialAvailable(void)
{
    boolean stringFound = false;
    // Read the serial buffer if data are available
    while (_espSerial->available() > 0)
    {
        char charBuffer = _espSerial->read();

        if (charBuffer == '\n')
        {
            _espSerialBuffer[_espSerialIndex] = 0; // terminate the string
            stringFound = (_espSerialIndex > 0); // only good if we sent more than an empty line
            _espSerialIndex = 0; // reset for next line of data
        }
        else if (charBuffer == '\r')
        {
            // ignoring carriage retun
        }
        else if (_espSerialIndex < BUFFSIZE && stringFound == false)
        {
            _espSerialBuffer[_espSerialIndex++] = charBuffer; // auto increment index
        }
    }

    return stringFound;

}

```

**\_espCommandOK()**

```
espResponse espdevice::_espCommandOK(void)
{
    if (strcmp(_espSerialBuffer, "OK") == 0)
    {
        return ok;
    }
    else if (strcmp(_espSerialBuffer, "ERROR") == 0)
    {
        return error;
    }
    else
    {
        return other;
    }
}

```

**The output from the serial ports for each case**

**working**

```
creating an new tcp server
command echo : AT+CIPMUX=1

Data Are available
Data Received from ESP : AT+CIPMUX=1
2
Data Are available
Data Received from ESP : OK
0
10000
command echo : AT+CIPSERVER=1,23050

Data Are available
Data Received from ESP : AT+CIPSERVER=1,23050
2
Data Are available
Data Received from ESP : no change
2
Data Are available
Data Received from ESP : OK
0
10000
command echo : AT+CIFSR

Data Are available
Data Received from ESP : AT+CIFSR
2
Data Are available
Data Received from ESP : +CIFSR:STAIP,"192.168.1.16"
2
Data Are available
Data Received from ESP : +CIFSR:STAMAC,"5c:cf:7f:fd:ce:14"
2
Data Are available
Data Received from ESP : OK
0
10000

```

**not working**

```
creating an new tcp server
command echo : AT+CIPMUX=1

Data Are available
Data Received from ESP : AT+CIPMUX=1
2
Data Are available
Data Received from ESP : OK
0
98
command echo : AT+CIPSERVER=1,23050

10000
command echo : AT+CIFSR

Data Are available
Data Received from ESP : AT+CIFSR
2
Data Are available
Data Received from ESP : +CIFSR:STAIP,"192.168.1.16"
2
Data Are available
Data Received from ESP : +CIFSR:STAMAC,"5c:cf:7f:fd:ce:14"
2
Data Are available
Data Received from ESP : OK
0
224

```

# Answer
I will leave this here in case anyone is interested. So i am communicating with the esp module at 9600 baud rate. After I send a command to the ESP I was waiting for its response before sending the next command without any delay.

What I found out is that for some reason although I was sending the command to the ESP the esp was not executing the command. So i added a delay(100) to see if the RX of the ESP was disabled during that time and i think i was correct since the commands were executed correctly.

I manage to get the delay down to delay(5). it Breaks after that.

I am using an Arduino micro and an ESP-01.
> 0 votes

# Answer
This may not be the answer you need if you are using it for something else, but if you are using a Micro, I would use the hardware serial Serial1 instead of SoftwareSerial. I've done many projects using a Leonardo (same processor) with ESP8266 as it gives me an extra hardware serial port which isn't connected to the Serial Monitor serial port.

I haven't tried the SoftwareSerial library for a few years, but I remember at the time that it doesn't handle duplex or high baud rates well.

What baud rate are you using? I couldn't see any begin in the code.

EDIT: You might also want to add the 'ATE0' command to turn off command echo. The serial receiver is probably getting swamped with data.
> 0 votes

---
Tags: esp8266, library, softwareserial, arduino-micro
---


title: cant find what is error on my code

text:
# Question
Title: cant find what is error on my code
im working on project which include using of motors and a float switch im getting an error message which expected '}' at end of input . i cant find where should i correct it, btw im putting a float switch at the first of the coding (which on top) and im getting and error, but when i remove the float switch function coding, its running well without any error. so how can i put this switch to it become functional? here is the coding;

```
int motorPin = 4; // pin that turns on the motor
int blinkPin = 9; // pin that turns on the LED
int lamp1 = 5;// lampu pape
int motorklorin = 3;// isi klorin
int switch1 = 2;// switch float
void setup()
{
  pinMode(motorPin, OUTPUT);
  pinMode(blinkPin, OUTPUT); // set pin 13 to an output so we can use it to turn on the LED
  pinMode(lamp1, OUTPUT);
  pinMode(motorklorin, OUTPUT); // MOTOR UNTUK ISI KLORIN
  pinMode(switch1, INPUT_PULLUP);// PELAMPONG
}

void loop()
{
if(digitalRead(switch1) == HIGH)
{
  digitalWrite(motorklorin, LOW);
}
else
{
  digitalWrite(motorklorin, HIGH);
  delay(2000);
  }
{
  digitalWrite(motorPin, HIGH); // turn on the motor
  digitalWrite(blinkPin, HIGH); // turn on the LED
  digitalWrite(lamp1, HIGH);// on lampu
  delay(2000);        // multiply by 1000 to translate seconds to milliseconds

  digitalWrite(motorPin, LOW);  // turn off the motor
  digitalWrite(blinkPin, LOW);  // turn off the LED
  digitalWrite(lamp1, HIGH);// motor 1 jalan (air start turun)
  delay(2000);        // multiply by 60000 to translate minutes to milliseconds

  digitalWrite(motorPin, HIGH); // turn on the motor (motorisi balik air jalan)
  digitalWrite(blinkPin, HIGH); // turn on the LED
  digitalWrite(lamp1, LOW);// on lampu
  delay(5000);        // multiply by 1000 to translate seconds to milliseconds

  digitalWrite(motorPin, HIGH);  // turn off the motor
  digitalWrite(blinkPin,HIGH);  // turn off the LED
  digitalWrite(lamp1, HIGH);// OFF LAMPU semua motor stop
  delay(1000);        // multiply by 60000 to translate minutes to milliseconds
  }

```

# Answer
There is an extra `{` right after your `else{}` statement. Delete this and the code should compile.
> 3 votes

# Answer
I cover this error and how to diagnose it in a blog post. Here it is quoted for posterity:

---

A common problem, and one that can cause a new programmer to pull their hair out.

However, it's a problem that always has a simple solution, and with the right tricks it's also easy to find where the problem lies.

Let's take the following little code snippet, which throws up this exact error:

```
byte i = 0;

void doSomething() {
  digitalWrite(3, LOW);
}

void doSomethingElse() {
  digitalWrite(13, HIGH);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (i == 1) {
    doSomething();
  i++;
}

```

At first glance that all looks perfectly good. But you compile, and you get:

```
/home/matt/Arduino/ErrorTest/ErrorTest.ino: In function 'void loop()':
ErrorTest:21: error: expected '}' at end of input
 }
 ^
exit status 1
expected '}' at end of input

```

Line 21, of course, is the last line of the file. And the error is pretty explicit - it expects a } at the end of the file. However, there is plainly one there already. So what is it on about?

Simply put, there aren't *enough* } to balance out the number of { in the file. For every { there *must* be a } to go with it. On this little file it's easy to just go through and count them all. Add one for a { and subtract one for a }. If the answer is not 0 then there's something wrong. But it can take careful looking to see where the missing one should be, and even I have spent hours going cross-eyed trying to find the location in a big project.

There is one little trick, though, that can help you: Auto Format. The Auto Format facility in both the Arduino IDE and UECIDE (and many other IDEs as well) will sort out your indenting for you according to the presence of (amongst other things) { and }. If the brackets don't match up the formatting would end up wrong.

So let's pass this little program through the auto formatting and see what happens:

```
byte i = 0;

void doSomething() {
  digitalWrite(3, LOW);
}

void doSomethingElse() {
  digitalWrite(13, HIGH);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(13, OUTPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  if (i == 1) {
    doSomething();
    i++;
  }

```

As you can see the loop() function's indenting has changed. And if your eyes are sharp enough you'll already see what was wrong. The "if", which had an opening bracket, didn't have a closing one. The "i++" was supposed to be outside the "if" (as can be seen by the original indenting), but actually it wasn't, and the end of the function was really the end of the "if", leaving the function unfinished.

So fixing it is now really easy. By auto formatting we can see where the imbalance occurs, and fix it:

```
void loop() {
  // put your main code here, to run repeatedly:
  if (i == 1) {
    doSomething();
  }
  i++;
}

```

And now it compiles. But of course that little snippet doesn't actually do anything useful...
> 2 votes

---
Tags: atmega328
---


# Question
Title: How to connect both MicroSD module and MPU9235 power in an arduino
I'm really new at electronics and wiring, so please be kind. Coding is my stuff, but I'm trying to learn something here.

I'm working with a project to store the movements of a skateboard through a MPU 9235 and the idea is to save the output of the sensor to a MicroSD.

I have both components and acquired a LiPO 3.7v 400mAh to take everything off the protoboard and attach at the bottom of the skateboard.

The code is working, everything code wise is working ok, but I'm strugging to understand how to power both MicroSD module and MPU9235, since both have the VCC pin (VDD in some versions).

The current connections are replicated in Fritzing. Only replacing Arduino Uno for an Arduino Nano, and the MPU 6050 from the picture for a MPU9235.

My first thought was to connect the LiPo battery into VIN and GND pins of Nano. From there I believe that I can wire up the 3V3 output directly to VCC from MPU9235.

But what about the MicroSD module?

How would I power its VCC pin since I have no 3V3 pin left? I read that it's not right to use a digital pin as power output.

How can I connect two components that needs power from external source?

# Answer
VIN takes 6-12v and it sends it through the on board regulator - so that is the best way to power the nano.

If you take a wire from the 3v3 pin and split it (solder two wires to one) then you will have two 3v3 feeds to wire to your two devices. This will be the same as you have to do for the Gnd connections, back to the Nano.

Does that make sense? (if not I'll try and draw you something).
> 1 votes

---
Tags: power, arduino-nano, wires, system-design
---


title: ESP32 AP max connections: 4 or 10?

text:
# Question
Title: ESP32 AP max connections: 4 or 10?
I am using the SoftAP feature of the ESP to create a central node, and connecting five or six clients in the final application. However, I don't know if i can connect that many clients.

One of the core files on GitHub, `esp_wifi_types.h` shows two conflicting lines:

```
#line 215, as a member of the 'wifi_ap_config_t' struct
uint8_t max_connection; /**< Max number of stations allowed to connect in, default 4, max 4 */

#line 254
#define ESP_WIFI_MAX_CONN_NUM (10) /**< max number of stations which can connect to ESP32 soft-AP */

```

So is it four or ten? Or something else? Any advice by somebody who's tried this would be appreciated.

esp\_wifi\_types.h on GitHub

# Answer
The answer is as clear as any other EspressIf configuration data, it is 4 or maybe 5, or 8, or 12, 16 or even 20 (the same as a ESP8266!)

To clarify, it seems that around 2015 the maximum was 4 connections, but it is possible to recompile the SDK to support up to 16 connections. There doesn't seem to be a #define of flag that will let a programmer control this.

These links may guide you to a proper solution: https://github.com/esp8266/Arduino/issues/570 or https://myesp8266.blogspot.com/2016/11/esp32-increase-maximum-number-of-sockets.html
> 2 votes

---
Tags: wifi, esp32, softap
---


# Question
Title: SIM808 module GSM working fine, GPS not working (No GPS ready message on power on)
I powered on my SIM808 module. It showed me following output:

```
RDY
+CFUN: 1
+CPIN: READY
Call Ready
SMS Ready

```

It supposed to show `GPS ready` also.

I sent AT command and return ok.
However `AT+CGPSPWR=?` returns error. All GPS command showed error.

I think GPS is not initialized at all as i didn't see GPS message when module powered on.

Why is the GPS not working?

# Answer
You have a version2 module. Use AT+CGNSxxx instead of AT+CGPSxxx
> 5 votes

# Answer
Use `AT+CGNSxxx` instead of `AT+CGPSxxx` commands

`ATGNSPWR=1` and `ATCGNSINF` to get location.

if you get following output

`1,0,19800106001337.000,,,,0.00,0.0,0,,,,,,0,0,,,,,`

It means your GPS is not set.

Try to put GPS antenna outside your room, on open space for 10-15 minutes. GPS bulb will start blinking to confirm it is now ready for use.

Then use `AT+CGNSINF`.

Good luck.
> 2 votes

# Answer
Had the same problem with a Simcom868: AT+CGNSPWR=1 (for the GLONASS) and the most common AT+CGPSPWR=1 didn't work giving me back an ERROR. The Simcom808 needs 2A peak current so check if your power supply unit can reach that power and in case replace it; then try the AT+CGNSPWR=1 or AT+CGPSPWR=1 again.
> 0 votes

---
Tags: gsm, atmega328, softwareserial, gps
---


title: Button Switch arduino

text:
# Question
Title: Button Switch arduino
I'm trying to use my button as a switch (the led goes on after I push the button and the led goes off when I push the button again). I know I have the right circuit, because I also used a code from the internet, which looks really like mine. But my code doesn't work. The led doesn't go on. Does anyone know what is wrong with my code?

I have found the mistake now. The last 2 lines of the code were in the if statement block. But why doesn't it work then?

Here is the code i have written:

```
int ledPin = 8;
int buttonPin = 4;

int ledState = HIGH;      // the current state of the LED
int previousState = LOW;  // the previous state of the button
int readingState ;        // the current state of the button

void setup() {
   // put your setup code here, to run once:
pinMode(ledPin, OUTPUT);
pinMode(buttonPin, INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
readingState = digitalRead(buttonPin);

if(readingState == HIGH && previousState == LOW){
  if (ledState == HIGH){
    ledState = LOW;
  }

  else{
    ledState = HIGH;
    }

digitalWrite(ledPin, ledState);
previousState = readingState;

}
}

```

# Answer
> 0 votes
> I have found the mistake now. The last 2 lines of the code were in the if statement block. But why doesn't it work then?

previousState is set to high, and is never set again, so your if statement will never execute again because previousState is always set to high.

Moving the last line out of the if block sets previousState at every loop, and can then have a value other than HIGH, and then your if condition can be satisfied.

The penultimate line could stay in the if, or be lifted out, logically it shouldn't matter.

---
Tags: button, switch
---