# Question
Title: ESP8266 Peer to Peer with AP and STA - Cache AP Clients, Flush Their Requests?
I'm fairly inexperienced with Arduino and entirely new to networking, so bear with me.

I've programmed a couple of NodeMCU devices to communicate the use of an instrument via activation of an LED. I have one set up as an access point and another as a client. I roughly followed the second answer from this question to set mine up. I'll eventually shift this particular project to `mqtt` but I'd like to understand how to get the direct peer-to-peer working for other projects as well.

While it *is* partially working, I am having a couple issues that I assume are related to networking.
1. After plugging in the client ESP8266, the server only recognizes it for two loops (taking ~5 seconds each), then I have to restart the client, which is discovered instantaneously by the server.
2. After the client connects, if I press the pushbutton on the client - while recognized - only once, the "toggle" command is repeatedly sent, resulting in the LED blinking for a handful of loops until it stops and the client has to be restarted again.
2.1. If I comment out the button debounce on the client, this happens more reliably. With debounce on, if I click the button immediately upon the first "client found!" message, the LED will *typically* toggle on the second (final) loop. Subsequent presses changing nothing.

Server sketch:

```
// Particle counter use server
// Place outside with LED

// load libraries
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>

// Set up variables
#define use_LED   D2

const char* ssid = "esp_server";
const char* password = "password";

WiFiServer server(80); // set port to 80

int toggle = 0;
String request = "";

void setup() {
  Serial.begin(9600);
  pinMode(use_LED, OUTPUT);

  WiFi.mode(WIFI_AP);
  WiFi.softAP(ssid, password);
  digitalWrite(use_LED, HIGH);
  delay(1000);
  Serial.println(WiFi.softAPIP());

  digitalWrite(use_LED, LOW);

  server.begin();
}

void loop() {
  // Check for a client
  WiFiClient client = server.available();
  if (client) {
  // Wait until client is connected
//  while(!client.available()) { delay(1); }/
  Serial.println("client found!");

  // Parse commands
  String request = client.readString();
  Serial.println(request);

  // After pressing client switch once, this dances between on and off with every loop
  if (request == "toggle") {
    toggle = 1 - toggle; // switches to opposite on request reception
    digitalWrite(use_LED, toggle);
    delay(2000);
  }

  client.flush();
  }

}

```

Client sketch

```
// Particle counter use client
// Place in analysis room with button

#include <ESP8266WiFi.h>
#include <WiFiClient.h>

#define toggle_button D1 // make sure to use a pulldown resistor

int toggled = 0;

// Set up connection to server ESP
const char* ssid = "esp_server";    // ssid of server
const char* password = "password";  // password of server
const int port = 80;                // port of server

byte ip[] = {192,168,4,1};

WiFiClient client;

void setup() {
  Serial.begin(9600);
  pinMode(toggle_button, INPUT);
  Serial.println("active");

  WiFi.mode(WIFI_STA); // Setup as client
  WiFi.begin(ssid, password); // Connect to server ESP
}

void loop() {
  toggled = digitalRead(toggle_button);

  if (client.connect(ip, port)) { Serial.println("CONNECTED"); }

  if (toggled == HIGH) {
    // send command to toggle LED when button is pressed
    Serial.println("triggered");
    client.print("toggle");
  }

  client.flush();
}

```

Strangely, the slow recognition is only on the server side, the client spams its serial output with "CONNECTED", until stopping (I assume when the second loop completes on the server side, I can only monitor the serial of one at a time). But once found the following lines suggesting a WiFi or memory error in the output nestled among all the lines of "CONNECTED":

```
Exception (29):
epc1=0x40202a8f epc2=0x00000000 epc3=0x00000000 excvaddr=0x00000000 depc=0x00000000

ctx: cont
sp: 3ffefa30 end: 3ffefc40 offset: 01a0

>>>stack>>>
3ffefbd0:  3ffe8b70 3ffee9b0 3ffeebe4 40202a8d
3ffefbe0:  0104a8c0 00000000 3ffeebe4 4020328c
3ffefbf0:  00000000 3ffee9b4 3ffeebe4 3ffeec10
3ffefc00:  3fffdad0 3ffee9b0 3ffee998 40202107
3ffefc10:  401070a0 0104a8c0 00000001 40203519
3ffefc20:  3fffdad0 00000000 3ffeec08 40203544
3ffefc30:  feefeffe feefeffe 3ffeec20 40100710
<<<stack<<<

```

I have pulldown resistors on both the client switch and the server LED, I'm guessing that `client.flush()` does not clear the command? I'm baffled as to why the loop on the server only runs twice before I have to reset the client, and why upon resetting the client is instantly recognized, but takes so long to see it again. Does anyone have any advice?

# Answer
You `connect()` and do not `stop()` the client. You get out of the 5 connections limit.

Use client in `if (client.connect(...))`, print and then do `client.stop()`.

And also `stop()` the server's client object.

`readString` has one second timeout. you should send a delimiter and use readStringUntil

Edit: For permanent connection of multiple clients on server side see the WiFiTelnetToSerial example. At client side you can use one global client object. But check if it is connected and if not, call stop and then connect again.

```
void loop() {

    if (!client.connected()) {
      client.stop();
      if (!client.connect(ip, port)) {
        delay(1000);
        return;
      }
    }

    int toggled = digitalRead(toggle_button);

    if (toggled == HIGH) {
      // send command to toggle LED when button is pressed
      Serial.println("triggered");
      client.print("toggle.");
    }
}

```
> 0 votes

---
Tags: esp8266, wifi, nodemcu, networking
---


title: Error running FirebaseDemo on nodeMCU

text:
# Question
Title: Error running FirebaseDemo on nodeMCU
So I followed the guide on GitHub to run this demo which compiles and runs. It does warn of some deprecations and such in the firebase libraries :

> In member function '**const String& FirebaseArduino::error()**' warning: returning reference to temporary \[-Wreturn-local-addr\] **return error\_.message().c\_str();**

It is failing to update my firebase database and the firebase error message is not being displayed, seems to be because of the above error. But this does make it complicated to debug...

Can someone please help me get around this?

Appreciate any feedback or pro tips :)

**UPDATE**

So found an issue on GitHub that solved connecting to the database. Fingerprint update apparently... https://github.com/FirebaseExtended/firebase-arduino/issues/369 but still would like to solve the firebase library error so that everyone can get legible error messages back when using it.

# Answer
> 1 votes
> It does warn of some deprecations and such in the firebase libraries :
>
> In member function 'const String& FirebaseArduino::error()' warning: returning reference to temporary \[-Wreturn-local-addr\] return error\_.message().c\_str();

i also get some depreciation like

```
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'bool FirebaseObject::isNullString(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:67:57: warning: 'const char* ArduinoJson::Internals::JsonVariantCasts<TImpl>::asString() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:28): use as<char*>() instead [-Wdeprecated-declarations]
   return variant.is<const char *>() && variant.asString() == NULL;
                                                         ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp: In member function 'ArduinoJson::JsonVariant FirebaseObject::getJsonVariant(const String&) const':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseObject.cpp:87:26: warning: 'ArduinoJson::JsonObject& ArduinoJson::Internals::JsonVariantCasts<TImpl>::asObject() const [with TImpl = ArduinoJson::JsonVariant]' is deprecated (declared at /home/praz/Arduino/libraries/ArduinoJson-5.13.1/src/ArduinoJson/Deserialization/../JsonVariantCasts.hpp:23): use as<JsonObject>() instead [-Wdeprecated-declarations]
     json = json.asObject().get<JsonVariant>(start);
                          ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/throw_out_of_range.cpp:6:28: warning: unused parameter 'str' [-Wunused-parameter]
 void __attribute__((weak)) __throw_out_of_range(const char* str) {
                            ^
In file included from /home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:1:0:
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.h:82:79: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
   const void AddToJson(const FirebaseCloudMessage& message, JsonObject& json) const;
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseCloudMessaging.cpp:80:60: warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
     const FirebaseCloudMessage& message, JsonObject& json) const {
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'int FirebaseRequest::sendRequest(const string&, const string&, char*, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:76:1: warning: no return statement in function returning non-void [-Wreturn-type]
 }
 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp: In member function 'void FirebaseStream::startStreaming(const string&, const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/Firebase.cpp:89:48: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   analyzeError("STREAM", status, path_with_auth);
                                                ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'String FirebaseArduino::push(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:79: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
                                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:65:7: warning: unused variable 'status' [-Wunused-variable]
   int status = req_.get()->sendRequest(host_, auth_, "POST", path.c_str(), buf);
       ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::set(const String&, const ArduinoJson::JsonVariant&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:94:65: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "PUT", path.c_str(), buf);
                                                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'void FirebaseArduino::getRequest(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:101:60: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "GET", path.c_str());
                                                            ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual void FirebaseArduino::remove(const String&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:147:63: warning: deprecated conversion from string constant to 'char*' [-Wwrite-strings]
   req_.get()->sendRequest(host_, auth_, "DELETE", path.c_str());
                                                               ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp: In member function 'virtual const String& FirebaseArduino::error()':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseArduino.cpp:201:33: warning: returning reference to temporary [-Wreturn-local-addr]
   return error_.message().c_str();
                                 ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:47:50: warning: 'bool HTTPClient::begin(String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:156) [-Wdeprecated-declarations]
     http_.begin(url.c_str(), kFirebaseFingerprint);
                                                  ^
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp: In member function 'virtual void FirebaseHttpClientEsp8266::begin(const string&, const string&)':
/home/praz/Arduino/libraries/firebase-arduino-master/src/FirebaseHttpClient_Esp8266.cpp:51:80: warning: 'bool HTTPClient::begin(String, uint16_t, String, String)' is deprecated (declared at /home/praz/.arduino15/packages/esp8266/hardware/esp8266/2.4.2/libraries/ESP8266HTTPClient/src/ESP8266HTTPClient.h:157) [-Wdeprecated-declarations]
     http_.begin(host.c_str(), kFirebasePort, path.c_str(), kFirebaseFingerprint);
                                                                                ^
Compiling library "ESP8266HTTPClient"

```

to fixed that, go to `Preferences` in Compiler Warnings choose as `Default`. it ignored all warning in depreciation, don't forget to update your library to get Firebase Fingerprint has changed on 2 Aug 2018.

Uploaded your sketch again, your should be get data like

# Answer
> 0 votes
It is quite right to tell you that. The offending code is here:

```
const String& FirebaseArduino::error() {
  return error_.message().c_str();
}

```

In that, it calls the `message()` function on the `error_` object to get a `std::string` object, which it then gets the C string data from with `c_str()`. It then creates (due to the return type) a temporary `String` object and copies the C string data into it.

A reference to that temporary `String` object is then returned and the `String` is then destroyed immediately. That's bad. The returned reference now points to nothing in particular.

It wouldn't surprise me if there were other places where that kind of thing happens. Which would explain why things aren't necessarily working right.

You should raise an issue on the Github issues page for that project with the author.

---
Tags: esp8266, wifi, nodemcu
---


# Question
Title: Can I change Arduino program on-the-fly?
I have Arduino which is programmed to do something. Is it possible that I could allow it to change behaviour by changing program on-the-fly without the need to reprogram Arduino via the computer.

What I need is to send the message via MQTT which will Arduino receive and change its behaviour by it. I managed to change the frequency of messages published or to add some new data, but what if I want to change how decisions are made. What if I want to change some Arduino code, to add some if or another state, can that be done on the fly?

Update: Changing device behaviour on the fly or after restart is acceptable. I am not strict with using arduino, nodemcu is and option. I just need a way to add new functionality to device if I need.

# Answer
Replacing or modifying the existing code during run-time will require some form of uploading and over-writing the old code. This is deliberately not made straightforward or easy for these kinds of micro-controllers.

But you can change the program's strategy on the fly, *if* you anticipate the potential changes and include the code for each of the possibilities.

For example, write a set of functions that each embody one of the various ways of operating, and, at run-time, select which function the program should use. You can change the selection by setting a value from the keyboard or the program could sense some external trigger such as a button-press, or a temperature reading and respond by changing the selection - the value of an int, perhaps. A `switch` statement can use that value to call the appropriate function at the appropriate time:

```
uint8_t strategy = 0;           // init to the default strategy

switch( selector ){
case(1):                // has event 1 happened?
   func1();
   break;

case(2):                // has event 2 happened?
   func2();
   break;

case(3):                // has event 3 happened?
   func3();
   break;

default:                // none of the above or undefined selector value
   funcDefault();
   break;
}

```

This does mean that all of the code for the possible operating strategies must be included at upload-time and share the program-memory space, but unless your job is very complex, even an Uno should be capable enough.

Update:

> I need to be able to update the device with some new functionality.

There is another approach which may or may not fit in an Uno but would be doable with a Mega 2560 or other larger-RAMmed machine: interpreted code.

* Define a set of operations that includes whatever you'll need to operate your external device(s): the necessary I/O operations to read your sensors and control your hardware; to make logical and/or arithmetic tests and conditionally branch or call a function based on the test result; to listen for a user-signal from the terminal (for example) and return to the arduino program. This will be the "language" in which you write your control program.
* Define a concise coding scheme to specify each operation and whatever data it needs, such as reading a temperature sensor and storing the result in a named place. If your control programs won't be too complex, you can get away with pre-defining A, B, ..., Z to be data registers of some appropriate type.
* In C++, write an interpreter for this new language. It's program will consist of the codes you just defined. But this code will be seen as data by the interpreter. This is the key - this pseudo-code will live in RAM, where your interpreter - a collection of C++ functions - can read and execute it, and the Arduino program can download a new one, over-write the old one, and run the interpreter again.

Caveat: Like the Greek mythological Hydra, this is a job that can grow new challenges as you address the current ones, but it is doable if you keep it simple as possible and include only what you must have to make it work.

Run-time-interpreted code can take 10 - 50 times as long to execute as a natively coded application, so anything that can be pre-coded in C++ should be. The finer and more flexible your interpreted instructions, the more expressive you can be when writing the control program, but the interpreter will be more complex to write, slower to execute, and harder to debug. Design your language to be only as flexible as it must be to allow you to write new control algorithms.

If you try to invent an entire pseudo-computer, completely flexible and capable of being programmed for any and all purposes, you'll drive yourself crazy. Whole businesses have folded after sinking money and time into inventing a new and better computer and got so bogged down they couldn't recover. Don't go that route.

Start with the grossest, least flexible operations you can live with and get that much working. Discover its limitations and address those, and only those, one at a time, until you have a sufficiently flexible system in which to control your device.
> 3 votes

# Answer
* Code that writes to flash has to reside in the bootloader section. The only way I know how to execute code in the bootloader section is after a reset. However, even if you could transfer execution to the bootloader section and get something to work, it would have to contend with the fact that flash has limited write cycles and will reduce the life of the device. Possibly to the point of being useless for a practical application.
* Executing code from RAM. Self explanatory, modify code all you want. There is an application note for AVR that discusses this.
* Write an interpreter for your needs. yuk!

EDIT: There is some GCC code example here.
> 1 votes

# Answer
You can change the behaviour of Arduino on-the-fly but it's not necessary to reprogram, just design your code to change behaviour with some variables you get form outsite e.g. a server, but this new changes must be defined previously in your code.

If you have a list of states and want to add more, use a dynamic array or use an array with enough space and when send a MQTT message that Arduino parses adding tha new state or even deleting a state.
> 1 votes

# Answer
> Is it possible that I could allow it to change behaviour by changing program on-the-fly without the need to reprogram Arduino *via the computer*.

(emphasis added by me).

As some answers pointed out, you can change the behaviour if you allow for it in advance. For example, store in EEPROM some setting (like how often something happens) and have a method of changing that setting.

---

## Different bootloader

However if you want to change the behaviour *completely* then you need to upload new code (whether the code is in RAM or program memory doesn't really change this part).

The bootloader installed as a standard on the Arduinos allows for code to be uploaded via a protocol which arrives at the serial port shortly after reset. There is nothing to stop you writing your own protocol (eg. using MQTT) and make your own bootloader which uses that - assuming it is small enough to fit into bootloader space (the largest bootloader the Atmega328P can hold is 4096 bytes).

---

## Stand-alone programmer

Since you asked about uploading new code without needing to have the computer, an alternative is to program it in the field using a stand-alone programmer. There are various ones around, including one developed by user Crossroads from the Arduino Forum:

I wrote the code for that one. The basic approach is to write your new code using the IDE (something you would have to do anyway) and then copy the .hex file to a SD or micro-SD card which is then inserted into the programmer as you can see in the photo. The programmer then connects to the target board via a ICSP interface using a 6-core cable as shown. This reprograms the target in about a second. This makes it practical to reprogram a device "in the field" without having to return it to your base, or carry a laptop around with you.
> 0 votes

# Answer
What you need is not a “one trick pony” (arduino) but an actual “horse” - Raspberry Pi. You have no reason not to such as:

1. Price - RPi Zero - $10
2. Size - ditto -about the size of a Nano
3. Functionality::

Pi . . . . . . . . . . . . . . . . Arduino

wifi . . . . . . . . . . . . . . . . no (wifly /Zigbee now you violate #2)

bluetooth . . . . . . . . . . . . . . . . no

web server . . . . . . . . . . . . . . . . no

mysql database . . . . . . . . . . . .. no

any linux multithreaded apps. . . . . . . .. . . . . . . . . . . . . no

etc etc etc

Did i miss anything? being a technology architect begins with knowing what hardware and software to apply in any given situation. I. E. avoid square pegs in round holes.
> -1 votes

---
Tags: arduino-uno, programming
---


title: Having some issues with an array

text:
# Question
Title: Having some issues with an array
I am having an issue that I can't seem to get my head wrapped around. What I am trying to accomplish is to have a minutes worth of sensor data in an array (reading every 5 seconds) so I'll have 12 values in this after one minute.

I want to keep the array to 12 values so I need to keep moving all the values in it down one index per new value hitting index \[0\] to make sure that each reading has a lifetime of 60 seconds on the array. Here is my code so far:

```
void add_readings_to_averages() {
  // At this point, I am moving values down the array to make room at the beginning.
  for (int a = 11; a >= 0; a--) {
    Serial.print("The value at temperature_c_minute_avg[");
    Serial.print(a);
    Serial.print("] is ");
    Serial.print(temperature_c_minute_avg[a]);
    Serial.println();
    if (a == 11) {
      Serial.println("At 12 so need to overwrite this value");
    }

    if (a <= 10) {
      Serial.print("a is ");
      Serial.println(a);
      temperature_c_minute_avg[a] = temperature_c_minute_avg[a + 1];  // This moves each entry down one index in the array creating an empty space at index[0]
    }

    if (a == 0) {
      temperature_c_minute_avg[a] = temperature_c;
    }
  }

```

I've loaded my array at the time of initialization with some dummy data so I could see what was going on. First run displays as you would expect.

```
The value at temperature_c_minute_avg[11] is 120.00
At 12 so need to overwrite this value
The value at temperature_c_minute_avg[10] is 110.00
a is 10
The value at temperature_c_minute_avg[9] is 100.00
a is 9
The value at temperature_c_minute_avg[8] is 90.00
a is 8
The value at temperature_c_minute_avg[7] is 80.00
a is 7
The value at temperature_c_minute_avg[6] is 70.00
a is 6
The value at temperature_c_minute_avg[5] is 60.00
a is 5
The value at temperature_c_minute_avg[4] is 50.00
a is 4
The value at temperature_c_minute_avg[3] is 40.00
a is 3
The value at temperature_c_minute_avg[2] is 30.00
a is 2
The value at temperature_c_minute_avg[1] is 20.00
a is 1
The value at temperature_c_minute_avg[0] is 10.00
a is 0
2018/11/2 11:4:39  -  Running for a total of 0 hours 0 minutes and 7         seconds

```

But the second time through the `loop()` my array is trashed.

```
The value at temperature_c_minute_avg[11] is 120.00
At 12 so need to overwrite this value
The value at temperature_c_minute_avg[10] is 120.00
a is 10
The value at temperature_c_minute_avg[9] is 120.00
a is 9
The value at temperature_c_minute_avg[8] is 120.00
a is 8
The value at temperature_c_minute_avg[7] is 120.00
a is 7
The value at temperature_c_minute_avg[6] is 120.00
a is 6
The value at temperature_c_minute_avg[5] is 120.00
a is 5
The value at temperature_c_minute_avg[4] is 120.00
a is 4
The value at temperature_c_minute_avg[3] is 120.00
a is 3
The value at temperature_c_minute_avg[2] is 120.00
a is 2
The value at temperature_c_minute_avg[1] is 120.00
a is 1
The value at temperature_c_minute_avg[0] is 0.00
a is 0
2018/11/2 11:4:44  -  Running for a total of 0 hours 0 minutes and 12     seconds

```

The entire array was overwritten with the last value and the new value was not added. The array itself is setup as a global variable. The initialization at the top.

```
float temperature_c_minute_avg[12] = {10.0,20.0,30.0,40.0,50.0,60.0,70.0,80.0,90.0,100.0,110.0,120.0};

```

What am I missing here? Been staring at this for some time, but this is the first time I've tried to use an Arduino array so I can totally believe the issue is PBKAC! :)

# Answer
> 2 votes
Your issue is a C programming issue and has nothing to do with the Arduino specifically. You should research how to implement a circular buffer. You don't want to move around the values within the array, but rather just increment array index values. Keep two index values, one of the current index position (the place where the next recorded value will be placed) and another of the number of values recorded. Eventually the number of values recorded will be equal to your maximum array size and only the index position will increment. When the array index exceeds the maximum array size it wraps back to 0.

# Answer
> 0 votes
In your if (a \<= 10) block, you are inside a for loop that is decreasing and replacing each value with the value inside index+1. This means that as you are going down the indices, you are carrying the 11th index value with you. Here is how it is without variables (allow me to shorten the variable name to t):

```
t[10] = t[11];
t[9] = t[10];
t[8] = t[9];

```

And so forth. Whatever was in a\[11\] is being dragged through each of the variables of lower indices.

I strongly suggest going the other way around with either your loop or which way you are pushing the data. For instance (continuing with array name t):

```
for (int i = 11; i >=0; i--) {
    if (i > 0)
        t[i] = t[i-1]; // shift data from index 10->11, 9->10, etc.
}
t[0] = arbitrary_data; // fill in new 'empty' space

```

Or, alternatively if you still want to put new data in index 11:

```
for (int i = 0; i <= 11; i++) {
    if (i < 11)
        t[i] = t[i+1]; // shift data from index 1->0, 2->1, etc.
}
t[i] = arbitrary_data; // fill in new 'empty' space

```

This is my solution for your current data management method. Another answer suggested a circular buffer where you simply keep track of which datum is being changed at a time and is far more efficient.

---
Tags: arduino-uno, arduino-mega, arduino-ide
---


# Question
Title: ADC noise when sharing ground from external supplies
i have resistor based sensor, when i test it using arduino connect to PC using serial monitor without sharing ground to other circuit it has a nice value between 300-650 in adc range and the error/ accuracy reading just have about 5 value (ex: 607-612) if there is no condition change in the sensor.

But the problem comes when i sharing the ground to the other circuit. The accuracy is messed up bigger than 60 adc value (570-660) with the same condition without sharing ground.

My circuit is powered by PSU 24V and 24V driver to produce input signal for electric pressure regulator. The arduino ground is sharing because to control the input of the 24V driver. Here my circuit in the attachment.

So there is two ground from PC (i need it to use serial monitor) and the PSU 24V

How to eliminate the noise? Is there any way to control the 24v driver and read the sensor at the same time without sharing ground? Maybe using two controller with master/slave? Or there is any advice?

# Answer
You've created what's known as a "Ground Loop". You have 2 grounds in your circuit, your 24v PS has a ground and the PC supplying 5V to your Arduino has a ground. They are not likely to be equivalent and will cause many unwanted side effects.

You can reduce some noise using RC or RLC circuits on your power supply pins. It's probably best to use only a single power supply (and ground).
> 0 votes

---
Tags: sensors, adc
---


title: Calculation error with Optical Encoder

text:
# Question
Title: Calculation error with Optical Encoder
I have corrected my code for reading the optical encoder index but I am now getting a different calculation error. At the index the encoder reset's to zero but now my readouts are as follows: Index point - resets to zero. \- At the 90 degree rotation mark I have a readout of 180 degrees. \- At the 180 degree rotation mark I have a readout of 0 because the code has it reset to zero after 359 degrees. \- At the 270 degree rotation mark I have a readout of 180 degrees. \- At the 0 degree mark it is zero again and that's what I would expect from the index. If I restart the Arduino Mega at the 270 degree mark, the index resets itself to zero like it should. Being new to this, before I had the index working it was working correctly minus the index function, now it seems to be double counting. Any ideas?

```
// Wiring connections for my encoder:
// Brown : VCC = 5V
// Blue + Shield : 0V = GND
// Black : ENCODER0PINA, Pin 20
// White : ENCODER0PINB, Pin 17
// Orange : ENCODER0PINI, Pin 19

#define ENCODER0PINA         20      // this pin needs to support interrupts
#define ENCODER0PINB         17      // no interrupt required
#define ENCODER0PINI         19      // this pin needs to support interrupts

// variables modified by interrupt handler must be declared as volatile
volatile long encoder0Position = 0;
volatile long interruptsReceived = 0;
volatile byte INTFLAG1 = 0;

// track last position so we know whether it's worth printing new output
long previousPosition = 0;

void setup()
{

  // inputs
  pinMode(ENCODER0PINA, INPUT);
  digitalWrite(ENCODER0PINA, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINB, INPUT);
  digitalWrite(ENCODER0PINB, HIGH);  // turn on pullup resistor
  pinMode(ENCODER0PINI, INPUT);
  digitalWrite(ENCODER0PINI, HIGH);  // turn on pullup resistor

  // interrupts
  attachInterrupt(3, onInterrupt, CHANGE);  // encoder track A on interrupt 3 - pin 20
  attachInterrupt(4, onReset, CHANGE);  // encoder Index track on interrupt 4 - pin 19

  // enable diagnostic output
  Serial.begin (115200);
  Serial.println("Ready.");
}

void loop()
{
  // only display position info if has changed
  if (encoder0Position != previousPosition )
  {
    Serial.println(encoder0Position, DEC);

    previousPosition = encoder0Position;
  }
}

// interrupt function needs to do as little as possible

void onReset()
{
  // read Index input
  int i = digitalRead(ENCODER0PINI);
  if (i == 1)
  {
  encoder0Position = INTFLAG1;
  }
}

void onInterrupt()
{
  // read both directional inputs
  int a = digitalRead(ENCODER0PINA);
  int b = digitalRead(ENCODER0PINB);

  if (a == b)
  {
    // b is leading a (counter-clockwise)
    encoder0Position--;
    if (encoder0Position < 0)
    {
      encoder0Position = (encoder0Position + 360);
    }
  }
  else
  {
    // a is leading b (clockwise)
    encoder0Position++;
    if (encoder0Position >= 360)
    {
      encoder0Position = (encoder0Position - 360);
    }
  }
}

```

# Answer
I have figured out my issue, at least I am getting good results. With this code I had to change interrupts from CHANGE to RISING. I want to thank everyone that has made comments on this question. –
> 1 votes

---
Tags: arduino-mega, rotary-encoder
---


# Question
Title: Loops fail after ~5 minutes when making two API calls every 10 seconds using WiFi client
I am running into an issue with a loop call on an Arduino MKR1000. I have tried the solutions suggested in this question and it usually works for 5 minutes and then collapses. I am trying to make two calls to different APIs every 10 seconds and update something on the Arduino accordingly, but the loops seem to be getting out of sync after a few minutes. Here is the code - I tried to shorten it...

```
#include <Time.h>
#include <SPI.h>
#include <WiFi101.h>
#include "arduino_secrets.h"

// put your local wifi info here
const char* ssid     = SECRET_SSID;
const char* password = SECRET_PASS;

const char* host = "bustime.mta.info";

void setup() {
  Serial.begin(9600);
  delay(10);
 // connecting to a WiFi network
  WiFi.begin(ssid, password);

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

void loop() {
  Serial.println("START THE LOOP");
  // Use WiFiclient class to create TCP connections
  WiFiClient client;
  WiFiClient client2;
  char * serviceDeliveryString = new char[40]();
  strcpy(serviceDeliveryString, "/ServiceDelivery");
  char * responseTimestampString = new char[40]();
  strcpy(responseTimestampString, "<ResponseTimestamp>");
  char * TString = new char[40]();
  strcpy(TString, "T");

  if (!client.connect(host, 80)) {
    lcd.clear();
    lcd.gotoXY(0, 0);
    lcd.string(connectionFailed);
    delay(2000);
    return;
  }

  //connect to schedule data
  if (!client2.connect(host, 80)) {
    lcd.clear();
    lcd.gotoXY(0, 0);
    lcd.string(connectionFailed);
    delay(2000);
    return;
  }

  char * req1full = new char [100]();
  strcat(req1full, "GET /api/siri/stop-monitoring.xml?key=KEY&OperatorRef=MTA");
  strcat(req1full, " HTTP/1.1");
  client.println(req1full);
  client.println("Host: bustime.mta.info");
  client.println("Connection: close\r\n");

  char * req2full = new char [100]();
  strcat(req2full, "GET /api/where/schedule-for-stop/MTA_");
  strcat(req2full, stopNum);
  strcat(req2full, ".xml?");
  strcat(req2full, "key=KEY HTTP/1.1");
  Serial.println(req2full);
  client2.println(req2full);
  client2.println("Host: bustime.mta.info");
  client2.println("Connection: close\r\n");

  //Pause long enough for the connection to happen. Make this longer if you have issues.
  delay(1000);

  while(client.available()){
    if (client.findUntil(responseTimestampString, serviceDeliveryString)){
      Serial.println("inside client...");
      client.findUntil(TString, serviceDeliveryString);
      String mtaTime = client.readStringUntil('.');
      Serial.println(mtaTime);
    }
    delay(10);
  }

  while(client2.available()){
    if (client2.findUntil("<currentTime>", "/data")){
      Serial.println("inside client2...");
      String mtaTime2 = client2.readStringUntil('<');
      Serial.println(mtaTime2);
    }
    delay(10);
  }

  client.stop();
  client2.stop();
  delay(9000);

}

```

The output starts out looking good:

```
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:13:38
inside client...
22:13:38
inside client2...
1541211218146
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:13:51
inside client...
22:13:51
inside client2...
1541211231815
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
inside client...
22:14:04
inside client...
22:14:04
inside client2...
1541211244465

```

But eventually something seems to happen with the loops and this is the final output, when it should keep running:

```
inside client...
22:19:02
inside client...
22:19:02
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
START THE LOOP
GET /api/where/schedule-for-stop/MTA_306762.xml?key=KEY HTTP/1.1
START THE LOOP

```

Any suggestions for how to fix this?

# Answer
> 1 votes
You keep calling new to allocate memory but you never free it. This is a memory leak and eventually you run out. Instead of constantly creating new arrays, why don't you make those global or static. Or even just local arrays if you don't need them to be persistent. On a microcontroller you really don't want to be using new unless absolutely necessary.

---
Tags: wifi, spi, time, mkr1000
---


title: ESP32 reset loop when using wifi.h

text:
# Question
Title: ESP32 reset loop when using wifi.h
I have a strange behavior, using ESP32 devkit v.1 boards. Everything works, I can upload blink sketch, serial works, led blinks. However, once I upload any sketch which is using the wifi.h (and utilizing it for example calling WiFi.mode(WIFI\_STA);), upon upload, the board keeps resetting the serial connection, stays up for not more then 1 second, resets again, and so on. I could not debug the issue, since serial is unusable. Any ideas what is wrong? I did a fresh ArduinoIDE, ESP32 board manager install, etc. and normal sketches work flawlessly.

# Answer
> 1 votes
The USB cable was too long, and hence power loss.

Sorry, I figured it out a day after I asked this question.

---
Tags: esp32
---


title: Splitting a message

text:
# Question
Title: Splitting a message
I have a string to be splitted into define chunks.

For example `new_str="abcdefghjklmnopqrstuvwxyz`, and my goal is to split it to chunks of `split_size=5`, so the result should be :`abcde`,`fghij` and so o.

`new_str` gets every time a different string.

`split_size` can be any size.

I have 2 questions:

1) Attached code does the job, but looks a BIT not elegant for a newbie like me. is there another way doing it ?

2)In code attached, output is `Serial.println(tmp)` and should be replaced with an output function to post each chunk to as a MQTT message. Ive rather that each chunk would be stored into a global array, to be sent later on in code out side `msgSplitter`.

So I wrote the following code:

```
int split_size=5;
char new_str[]="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
void setup() {

        Serial.begin(9600);
        Serial.print("String length: ");
        Serial.println(strlen(new_str));
        Serial.print("Split Size: ");
        Serial.println(strlen(split_size));

        msgSplitter(new_str, split_size, "Split #");

}
void msgSplitter( const char* msg_in, int chop_size, char *prefix){
        num=ceil((float)strlen(msg_in)/chop_size);
        char tmp[50];
        int pre_len;

        if (num > 1) {
                for (int k=0; k<num; k++) {
                  pre_len=0;
                        sprintf(tmp,"%s %d: ",prefix,k);
                        pre_len = strlen(tmp);
                        for (int i=0; i<chop_size; i++) {
                                tmp[i+pre_len]=(char)msg_in[i+k*chop_size];
                                tmp[i+1+pre_len]='\0';
                        }
                        Serial.println(tmp);
                }
        }
        else {
                Serial.println(msg_in);
        }
}

```

# Answer
```
// concat version
void msgSplitter(const char* msg_in, int chop_size, char *prefix) {
  char tmp[50];
  int size = strlen(msg_in);
  for (int pos = 0, k = 0; pos < size; pos += chop_size) {
    int l = sprintf(tmp, "%s %d: ", prefix, k++);
    strncat(tmp + l, msg_in + pos, chop_size);
    Serial.println(tmp);
  }
}

// only value version
void msgSplitter(const char* msg_in, int chop_size, char *prefix) {
  char tmp[chop_size + 1];
  tmp[chop_size] = 0;
  int size = strlen(msg_in);
  for (int pos = 0; pos < size; pos += chop_size) {
    strncpy(tmp, msg_in + pos, chop_size);
    Serial.println(tmp);
  }
}

```
> 1 votes

---
Tags: array
---


title: ESP8266 blink sketch not blinking LED

text:
# Question
Title: ESP8266 blink sketch not blinking LED
After flashing the blink sketch to the ESP8266, I removed all the unnecessary wires from flashing - and my setup to try and run the sketch looks like this:

Something to note about flashing - it would take anywhere from 10-50 tries before it would flash successfully, the other times it just failed to upload and spit out the `espcomm` failure to connect message, or it got halfway through the upload and quit. This is the only clue to me that maybe my board is just bad, and it won't be able to run any sketch - I ordered another ESP8266, but I'm still wondering if I could be doing something wrong, it seems fairly straight forward, and I have done a lot of research about this up until this point. This is my first arduino project, other than the starter projects.

Also not represented in the diagram are the female to male jumper cables I am using to connect to the ESP8266. Those connect to the breadboard, and then I plug another wire into the breadboard on the same row to attach it to what it needs to be attached to. I figure none of this stuff matters - as long as it is powered (red LED) it should be working.

Any ideas why the onboard LED isn't blinking? Or is the sketch not running at all? Does the upload problem matter...could it be producing a false positive result? The only other idea I have where something could be different is an output capacitor for the voltage regulator, I have been told that a 10mF capacitor is what I would use (but I have also been told it doesn't matter...and neither does the filter capacitor, I just put it in anyway).

CODE (straight from Arduino IDE / ESP8266 examples):

```
/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

```

Mike pointed out my regulator matters (because of dropout voltage) - I am using this one:

http://www.nteinc.com/specs/1900to1999/pdf/nte1904.pdf

# Answer
The ESP8266 is power hungry, the Arduino may not have enough output current to power it. Also, which voltage regulator you're using matters, as some have higher dropout than others.
> 1 votes

# Answer
Here's how you test your voltage regulator setup:

1. Disconnect the ESP8266.
2. Connect a 10 ohm 1 W (or higher) resistor across the output of the v-reg. One end goes to the output, the other goes to ground.
3. Measure the voltage across the resistor. If it stays regulated close to the expected 3.3V, then you're fine. If not, then this setup can't supply enough current for the ESP8266.
> 1 votes

# Answer
Some ESP8266 - V01 boards won't blink integrated led (only works with GPIO2), so connect it to a resistor (~150 ohms), in series with an external led to ground. I don't know why... is just the way that it is...
> 0 votes

---
Tags: arduino-uno, programming, esp8266, led, sketch
---


title: Connect to ch340 on MacOS Mojave

text:
# Question
Title: Connect to ch340 on MacOS Mojave
I recently upgraded my MacBook Pro to Mojave. Now I'm not able to connect to my Arduino board with ch340g usb-to-serial chip. It is a Arduino board with AtMega 328 and ESP8266 integrated. I downloaded the drivers from the Chinese website for the ch340 and also removed old installations, like some tutorials tell me. I just can't get a `/dev/cu.*` port (besides the `/dev/cu.Bluetooth-Incoming-Port`.

I do have an external FTDI usb to serial board. I didn't get to it to try to connect it.

Does someone know how to get the ch340 to work on MacOS Mojave, or as a last resort: use the FTDI to program/monitor the Arduino board?

# Answer
Ok, this is the solution for me:

remove all old drivers:

```
sudo rm -rf /Library/Extensions/usbserial.kext
sudo rm -rf /System/Library/Extensions/usb.kext

```

Now reboot the computer.

And then (very important, because it took me 10 cables to find the right one) use a **fully connected** cable ;-)

Now I have these ports:

```
/dev/cu.wchusbserial1410
/dev/cu.usbserial-1410

```
> 7 votes

# Answer
this my problem too. i found these solutions

1. mac-usb-serial app
2. a topic in arduino forum

make sure delete old usb driver in these path
/Library/Extensions/usbserial.kext
and
/System/Library/Extensions/usb.kext

---

then install it again download link
> 1 votes

---
Tags: mac-os, ch340
---


# Question
Title: Is there a way to traverse a filesystem and read files with an arduino?
I recently got into arduino and I want to set up something big. My project will need the arduino to be able to get into a specific directory of a windows (later may change to linux but for now windows) computer which will have some files with values required for the arduino to run.

Is it possible to set it to go to a fixed path and open a file with a specific name and get it's contents?

Ideally I would want those values to be stored to my micro sd so I do not load too many things on memory as my board is a Leonardo and the code is quite extensive already. (The board can be changed if needed)

Any help/ideas are appreciated!

# Answer
The Arduino has no access to the file system on a PC. All it has is a serial connection with which it can communicate with some program running on the PC. The code that is handling the PC's file system would have to run on the PC itself.
> 1 votes

# Answer
This could get complicated.

You'll need to develop a USB interface on your Arduino to "talk" to the PC. Then you'll need to write an application (*use whatever language you feel comfortable with - that's an entire religious discussion for another place and time*) that "listens" for the Arduino's USB connection and does most of the legwork. Think of the PC application as sort of a "script server", allowing the Arduino to make cryptic requests ("**FCNT**" requests a 'File Count' on your target PC folder, that sort of thing) which the PC application will then return data from, as needed. (In the previous example "**FCNT**" gets a file count of a predetermined folder - which would return a four-byte \[*integer*\] value revealing the results of the file count.) From this point you could add additional scripts and functionality, allowing your Arduino to make abbreviated (sometimes wonky-seeming) calls to the PC, and have the PC do what is necessary to fulfill those requests.

In the example I hastily described above, your Arduino sends "**FCNT**" and then "listens" to the USB interface, eagerly awaiting the return value that it knows will be a four-byte response. If the PC application were properly programmed, you could get slick with your command calls, sending "**XFR #**" which asks the PC application to "**transfer file \[#\] to me**" at which time the Arduino goes into "paddle board" mode, where it receives data from USB and immediately transfers it to the MicroSD until is "seen" in the data stream, at which point the Arduino returns to normal code operations mode.

Of course, your PC application will need to be extremely fault-tolerant in order to prevent sending your Arduino bad data or worse, sending it into a state that can't be easily recovered, such as if the Arduino "thinks" it's expecting a file and goes into "wait for transfer" state, but the file it requested doesn't exist because it got deleted sometime between the file count request and the transfer request. The Arduino would appear to be "hung up" because it would be in "File Transfer" or "paddle board" mode, and not looking for other messages or awaiting other operator stimulus.

Due to the different architectures, there really is no *simple* way to interface an Arduino to a PC. Sorry about that.
> 0 votes

---
Tags: arduino-leonardo
---


title: ESP Wemos D1 upload fails

text:
# Question
Title: ESP Wemos D1 upload fails
I try to upload simple code (e.g. blink.ino) to my ESP8266-12 (I have the WeMos D1 breakout board). Until now, that worked without a problem: I had to pull GPIO0 down and then I could upload the compiled sketch.

Since today that does not work any more - but I did not change anything.

I get:

> error: espcomm\_upload\_mem failed

(I know that here are some questions / github issues out there that have the same error, but that was often because GPIO0 wasn't pulled down and the ESP was therefore not in FLASH mode.)

My config is: ESP8266, 80MHz, DIO, 115200, 512K (64K SPIFFS), ck, Serial

When I reset my board, having GPIO0 pulled down, the ESP sends this serial info:

> ets Jan 8 2013,rst cause:2, boot mode:(1,7)

The whole debug output is:

```
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM6
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 228624 bytes from D:\Users\myusr\AppData\Local\Temp\build9c9ef3bdfe2fccb480bc6e4bac749e41.tmp/Blink.ino.bin to flash at 0x00000000
    erasing flash
    size: 037d10 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    read 0, requested 1
    setting serial port timeouts to 1000 ms
warning: espcomm_send_command: didn't receive command response
warning: espcomm_send_command(FLASH_DOWNLOAD_BEGIN) failed
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
error: espcomm_upload_mem failed

```

# Answer
> 1 votes
As I found out, GPIO0 has to be LOW **AND** GPIO2 has to be HIGH. It is very important to use pin D3 as GPIO0 and pin D4 as GPIO2 at the WeMos D1 board, because this "routing" is different for other boards and therefore other digital pins are often described.

# Answer
> 0 votes
I was facing the same problem, I simply updated CH34x driver for esp8266 to v1.4 from v1.3 after that I was able to see a new port option named usbserial 1420 & wchusbserial 1420. after selecting wchusbserial 1420 I was able to upload program successfully. As my MacOs running on Mojave

---
Tags: esp8266, uploading
---


# Question
Title: Arduino Nano- Programer not responding after upload WDT
I followed an example link for WDT. Code was copied as is, and uploaded to Nano successfully.

Now- when I wish to upload another code, I get an error message saying `avrdude: stk500_recv(): programmer is not responding`.

Is it possible to undo it ?

code:

```
#include <avr/wdt.h>

#define led 13 // pin 13 is connected to a led on Arduino Uno

void setup()
{
  pinMode(led, OUTPUT);      // set pin mode
  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(100);                // wait for a tenth of a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(100);                // wait for a tenth of a second
}

void loop(){
  wdt_enable(WDTO_15MS);     // enable the watchdog
                             // will fire after 15 ms without reset

  while(1)
  {
//     wdt_reset();          // uncomment to avoid reboot
  }
}

```

# Answer
One of the things with the watchdog is that after a watchdog reset it remains active. It has to specifically be turned off - and the bootloader doesn't (IIRC) normally turn it off.

If the timeout is too short (shorter than the time taken to upload new code) the watchdog will reset the chip while you're uploading.

The only way to turn it off is to physically remove power from the chip, and make sure that the loaded sketch never runs.

1. Select the board / port etc ready to upload
2. Unplug the board
3. Hold the reset button in
4. Plug in the board
5. Press upload on the IDE 6 Just as `avrdude` is about to run (that's the program that does the actual uploading) - just as the compiling has finished, release the reset button

If you did it right you should be able to upload properly. If not, you will have to try again from step 1.
> 1 votes

# Answer
If the WDT program is running when you try to upload a new one, it may be blocking the bootloader. Try holding the reset button while you click the the IDE's upload button, releasing the reset once you see avrdude launch. It may take a few tries to get the button-dance just right.

Update:

> what is avrdude ?

It is the program on your PC that uploads the compiled image to the Arduino. You'll see it running in the lower pane of the Arduino IDE.
> 2 votes

---
Tags: arduino-nano, uploading
---


title: NodeMCU does not connect to wifi

text:
# Question
Title: NodeMCU does not connect to wifi
I'm trying to connect my nodeMCU to my WiFi network but it keeps printing **`........`** which means is not connecting to the network. Here is my code used to connect to WiFi. Any reason why it isn't connecting to WiFi network?.

```
#include <ESP8266WiFi.h>

        // Replace these with your WiFi network settings
        const char* ssid = "******"; //replace this with your WiFi network name
        const char* password = "******"; //replace this with your WiFi network password

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

          WiFi.begin(ssid, password);

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

          Serial.println("success!");
          Serial.print("IP Address is: ");
          Serial.println(WiFi.localIP());
        }

        void loop() {
        }

```

# Answer
> 2 votes
If your WiFi network doesn't have DHCP, then you must set the IP addresses

example:

```
  IPAddress ip(192, 168, 1, 8);
  IPAddress gw(192, 168, 1, 1);
  IPAddress sn(255, 255, 255, 0);
  WiFi.config(ip, gw, sn, gw);

```

gw is gateway. the last parmeter is dns server's IP. sn is subnet mask.

# Answer
> -1 votes
If your powering the device via a computer USB port there is a good chance it’s not providing enough power for the wifi. Try powering fron an external source.

---
Tags: esp8266, nodemcu
---


# Question
Title: using esp8266 feather to burn bootloader on redboard
Is it possible to burn the bootloader of an arduino redboard using an esp8266 feather? whenever i connect my redboard to my pc the ports list on the ide would just be greyed out. I've looked around online and tried everything I found except burning the bootloader since I didnt have a spare arduino, atmega or a programmer. I have an EPS8266 feather though.

If anyone know whether or not this is possible to do and could walk me through on how to do it if it was.

# Answer
The RedBoard has an FT232 chip for the USB interface. Flashing the bootloader on the main MCU will have no effect at all on your problem.

While, yes, it is technically possible to use the ESP8266, it's not easy and, since it won't cure your problem of a greyed out port option, isn't worth the effort to try and do it.

Instead, you should be looking at things like your USB ports, USB cables, FT232 drivers, etc on your computer.
> 1 votes

---
Tags: esp8266, bootloader
---


title: Arduino log file directly to file

text:
# Question
Title: Arduino log file directly to file
I have problem because I need to read values and then save them in a .txt file, but Arduino doesn't have a physical connection with my computer. It only has a connection with a computer using Ubuntu without Arduino IDE or other programs. Also, I don't have an ethernet connection and SD card. I need only to have this data stored. The best way is to send them at the end of cycle to a special text file. Has anybody faced that before?

---

I'm thinking about writing a bash script for reading all values sent by serial and then save them, but how do I get that information from serial?

# Answer
> 2 votes
Any serial terminal emulator application can connect to the Arduino. Select one that has log-to-file capability and open its log file after you've connected it to your Arduino's /dev/tty... device.

Start the Arduino and let it collect & send the data to your terminal program. Close the terminal app's log file (easy step to forget - ask me how I know :) and there's your data.

# Answer
> 0 votes
The Arduino IDE provides a built-in serial monitor functionality, which emulates a serial port over USB. There are many tutorials available for its use.

However, as best I recall the Arduino serial monitor does not allow you to save a log file. If you don't want to write your own code to do this you can use a different terminal emulator, such as putty.

# Answer
> 0 votes
Like what Chris mentioned in the comment, you can use pyserial to do it. You can even add timestamp to your data and append them to the same log file.

---
Tags: datalogging
---


# Question
Title: How to convert byte array into a single variable
In this code i am taking the TID data(20bytes of 160bits) in the form of array according documentation and and its working correctly and getting the output of RFID tags.

Now I just need your guidance that how can i convert the array of 20 Bytes into a single variable or into a double long datatype? or another. Because I have to push it on to my MySQL database server for further processing.

I had tried the following code which works fine

```
byte x[10] = "450210921";
long result = atol(x);
Serial.print("long value of the byte is: ");
Serial.println(result);

```

but when i put the above code into my main code, getting not any error and I am not getting the required output.!

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

void loop()
{
  byte response;
  byte myTID[20]; //TIDs are 20 bytes
  byte tidLength = sizeof(myTID);

  //Read unique ID of tag
  response = nano.readTID(myTID, tidLength);
  if (response == RESPONSE_SUCCESS)
  {
    for(byte x = 0 ; x < tidLength ; x++)
    {
      if(myTID[x] < 0x10) Serial.print("0");
      /*temp[x]=(myTID[x], HEX);*/
      //Swapping values into temp variable
      temp[x]=myTID[x];
      Serial.print(temp[x]);
    }
    /*byte x[10] = "450210921";*/
    //Convert a whole array into a single long variable
    long result = atol(temp);
    Serial.print("long value of the byte is: ");
    Serial.println(result);
  }
  else
    Serial.println("Failed read");
}

```

# Answer
You can't convert 20 bytes to long. Send it as string of hex values. A byte takes two characters in hex, so you will send a 40 characters string, which can be simply decoded back to bytes.

```
char str[sizeof(myTID) * 2 + 1];
const char* hex = "0123456789ABCDEF";
for (int i = 0; i < sizeof(myTID); i++) {
  str[i * 2] = hex[(myTID[i] >> 4)];
  str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
}
str[sizeof(str)] = 0;
Serial.println(str);

```
> 0 votes

---
Tags: arduino-uno, nodemcu, rfid
---


title: Arduino Uno with ESP8266-01 with AT

text:
# Question
Title: Arduino Uno with ESP8266-01 with AT
Here is the schematic I followed:

Here also the link: https://www.circuito.io/app?components=10167,11021,12083,13678,13959

```
#include "DHT.h"
#include "NewPing.h"
#include <SoftwareSerial.h>
#define DEBUG true

SoftwareSerial esp8266(11,10);

#define DHTPIN 2       // DHT-11 Output Pin connection
#define DHTTYPE DHT11   // DHT Type is DHT 11 (AM2302)
#define TRIGGER_PIN 4
#define ECHO_PIN 3
#define MAX_DISTANCE 400

NewPing sonar(TRIGGER_PIN,ECHO_PIN,MAX_DISTANCE);

float hum;
float temp;

DHT dht(DHTPIN, DHTTYPE);

void setup()
{
  Serial.begin (9600);
  dht.begin();

  pinMode(TRIGGER_PIN, OUTPUT);
  pinMode(ECHO_PIN, INPUT);

  sendData("AT+RST\r\n",2000,DEBUG);
  sendData("AT+CWMODE=2\r\n",1000,DEBUG);
  sendData("AT+CIFSR\r\n",1000,DEBUG);
  sendData("AT+CIPMUX=1\r\n",1000,DEBUG);
  sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG);
}

void loop()
{
  delay(2000);  // Delay so DHT-11 sensor can stabalize

  hum = dht.readHumidity();  // Get Humidity value
  temp= dht.readTemperature();  // Get Temperature value

  digitalWrite(TRIGGER_PIN, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN, LOW);

  long duration,distance;
  duration = pulseIn(ECHO_PIN,HIGH);

  distance = duration/58.2;

  Serial.print("Humid: ");
  Serial.print(hum);
  Serial.print(" %, Temp: ");
  Serial.print(temp);
  Serial.print(" C, ");
  Serial.print("Distance: ");
  Serial.print(distance);
  Serial.println(" cm");
  delay(50);

  if(esp8266.available())
  is sending a message
  {
    if(esp8266.find("+IPD,"))
    {
      delay(1000);
      int connectionId = esp8266.read()-48;
      /* We are subtracting 48 from the
         output because the read() function returns
         the ASCII decimal value and the
         first decimal number which is 0 starts at 48 */
      String webpage = "<h1>IOT Garbage Monitoring System</h1>";
      webpage += "<p><h2>";
      if (distance<5)
      {
        webpage+= " Trash can is Full";
      }
      else{
        webpage+= " Trash can is Empty";
      }
      webpage += "</h2></p></body>";
      String cipSend = "AT+CIPSEND=";
      cipSend += connectionId;
      cipSend += ",";
      cipSend +=webpage.length();
      cipSend +="\r\n";

      sendData(cipSend,1000,DEBUG);
      sendData(webpage,1000,DEBUG);
      String closeCommand = "AT+CIPCLOSE=";
      closeCommand+=connectionId;
      closeCommand+="\r\n";
      sendData(closeCommand,3000,DEBUG);
    }
  }
}

String sendData(String command, const int timeout, boolean debug)
{
  String response = "";
  esp8266.print(command);
  long int time = millis();
  while( (time+timeout) > millis())
  {
    while(esp8266.available())
    {
      char c = esp8266.read();
      response+=c;
    }
  }
  if(debug)
  {
    Serial.print(response);
  }
  return response;
}

```

I've been trying to solve this problem for almost a week.

# Answer
If you want to use esp-01 over SoftwareSerial, you must set the AT firmware's default baud rate to 9600 baud. The default baud rate of AT firmware is 115200 baud. SoftwareSerial can't work at this speed.

To change the baud rate you must have a way to communicate with AT firmware at the default baud rate of 115200 baud. You can use the USB adapter of the Uno. Upload BareMinimal sketch from Examples to Uno to make it silent and connect the esp-01 to RX and TX pins of the Uno.

Connect RX to RX and TX to TX to have the cross connection to USB of the Uno. Then connect from Serial Monitor to esp-01 at 115200 with "Both line end characters" set. Try some basic AT commands and then still at 115200 baud send the command to change the default baud rate AT+UART\_DEF=9600,8,1,0,0

---

In setup() in sketch `begin` for SoftwareSerial is missing. Add `esp8266.begin(9600);`

---

Uno pin 11 is RX of software serial, pin 10 is TX. The RX pin 11 must connect to TX pin of esp-01. Same applies for TX pin 10. It must connect to RX pin of the esp-01.

On the Fritzing schema on Uno pin 11 is green wire and on esp-01 TX is green wire. But the green wire is on sides of the level converter not on the same position. The conclusion is that you have RX connected to RX not to TX. Switch wires on best at level converter.

---

The 3.3 V pin of some Uno clones can't supply enough current for WiFi operations of the esp8266. You need to convert to 3.3 V from Uno 5 V pin or use a separate 3.3 V power source for the esp-01.
> 0 votes

---
Tags: esp8266, wifi
---


# Question
Title: Global Variable does not Change when Value is set within Boolean Function
I have a boolean function which contains a string. In my main project this string is extracted from a website using an ESP8266 which is compatible with the Arduino IDE. I need to convert this string to a char\* type of which is to be used in the loop() section of the code. The issue which I have faced is related to the setting of the mPass global variable, which does not change when it is done in the restoreConfig() Boolean function, meaning it remains blank when called for in the loop.

I do understand that this problem is related to the fact that I am defining the mPass within the Boolean function, however I am unsure as to the process in which I can change the global variable without errors.

I have tried resolving this problem through moving the mqttpass, mqttpasslen and mPass variables out of the restoreConfig() function, however it creates significantly more problems than that which I have at the moment. As a result I have only presented the code without any adjustment below:

```
char* mPass = "";

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

void loop() {
  if (restoreConfig()) {
    Serial.println(mPass);
    Serial.println("ABOVE IS mPass IN LOOP");
  }
  delay(1000);
}

boolean restoreConfig() {
  String mqttpass = "DOGS";
  int mqttpasslen = mqttpass.length() + 1;
  char mPass[mqttpasslen];
  mqttpass.toCharArray(mPass, mqttpasslen);
  Serial.println(mPass);
  Serial.println("ABOVE IS mPass IN BOOLEAN");
  return true;
}

```

My current output from this is:

```
DOGS
ABOVE IS mPass IN BOOLEAN

ABOVE IS mPass IN LOOP

```

# Answer
> 1 votes
You have local variable mPass in the function restoreConfig. It 'shadows' the global variable.

---
Tags: programming, esp8266, variables, loop
---


title: How cold or hot can my Arduino Uno get?

text:
# Question
Title: How cold or hot can my Arduino Uno get?
The Arduino Uno Page doesn't say the temperatures that it can operate in. I'm thinking about placing it outdoors. How can I make sure my Arduino Uno is safe in weather that can reach -20 to 105 degrees Fahrenheit? (-26 to 40 degrees Celsius).

# Answer
> 15 votes
**It's not that big of deal.** The ATmega 328p datasheet states this:

> Temperature range: -40 to 85 degrees celsius.

The same goes for the USB chip on the Uno (ATmega 16u2 for UNO R3).

That's inside your limits. It probably could go a bit colder than mentioned, but it'll shorten the length of the board a little bit.

However, there are some things that may go wrong:

* EEPROM might not be stored as long in extreme temperatures. Keep this in mind if you're storing critical data.
* The voltage regulator may not perform as well in hot conditions
* The crystal oscillator may not produce exact values. However, I would imagine that a few hertz more or less wouldn't affect a 16 MHz processor. The tolerance is actually a little less than 1%. You may have some issues with serial (baud rate not correct). I would look into any communications like I2C also. (I don't know exactly how the clock line works... it might be fine for I2C.)
* Resistors/capacitors may not produce the *exact* values. I'd imagine that the tolerance won't be more than 8% on resistors: most resistors are rated at 5% for normal temperatures. It does depend on the manufacturer. Capacitors do have a bigger tolerance, but their main purpose is to "smooth" a signal.
* Extreme cooling/warming may cause minor expansion problems. (Note: it's fine once in a while, but not on an hourly basis of dropping 30 degrees.)
* Other components (LCDs, etc.) should be kept in mind also when looking at the viability of keeping it outdoors.

So as long as all the other components not on the board will happily run in the temperatures that you need, you should be fine. Also, as with all engineering, values often have added "padding" built in. (i.e. 5% tolerance is often 3-4%, maximum 12V it can run on 12.5V, etc.)\*

*What I mean by that is your Arduino won't explode when it's -41 degrees C. It's not great for it, but most likely you should be fine as long is it isn't a regular occurrence.

# Answer
> 4 votes
Like everyone mentions, as long as you're in the shade, hot temperature probably doesn't matter too much as it's within the limits of the components.

I'm more worried about condensation in the mornings. Water vapors will condense on electronics just like it does on grass. You could try electrical epoxy to cover the circuit. The Arduino doesn't run very hot, so the epoxy doesn't do much in terms of preventing it from cooling down. But epoxy does keep water vapor condensation from being a problem.

# Answer
> 1 votes
For hot temperature, just follow the datasheet.

For low temperature, I remember someone last year trying to overclock a UNO with liquid nitrogen so I guess you won't ever meet any problems with low temps :-)

In his blog, that person shows that he could run his UNO at 65 MHz by reducing temperature to -196°C.

Of course, the process was more complex than just reducing the temperature and checking what happens: a lot of improvements were performed on the board.

The blog explains very well how various components can react to cryogenic temperatures; the major issues seemed to be capacitors which capacitance **dramatically** reduces under low temperatures.

# Answer
> 1 votes
I agree with the advice to read the data sheets, but here is a personal answer to the question.

I installed a Raspberry Pi in an enclosure in which the existing Arduino survived last summer.

Even though they have the same overall temperature limits (except the communications section) it was the Pi that stopped working first.

The good news is that bringing it inside it booted right back up.

The temp/humidity went up to 140 F (like a hot car in Phoenix).

So in the end, the data sheet was right in terms of survival. But I would suggest a more conservative approach, such as placing them into a white-painted enclosure to minimize the effects of the sun.

After removing the pi, the Arduino woke up like nothing happened, still outside.

These things are very resilient.

# Answer
> 1 votes
If you must place your device outside, I would suggest a diecast box. The main heat generating component is probably the regulator (Think about it - at 12V, the reg drops 7V, where the micro runs on 5V or maybe 3V3). So running the lowest voltage into the arduino is recommended, I think its good to 7V (for a 5V unit). If you can connect a heat pathway from the chip surface to the case, good (Use heavy guage - at least 2mm thick). Take care you do not connect to the reg tab - use mica or thin mylar and heatsink paste (Avoid galvanic interations). Normal finned heatsinks on the outside of the box actually do the job of shedding heat to the atmosphere. This whole thing should be in a slatted wooden white painted container (A stevenson screen) so direct sun (and rain/dew) dont hit the containing box. This would be a solution for extreme environments. Remember that any heat build from the board must get to the box internal environment - using trapped air you get a very poor thermal contact. Then it has to get through the box and into the air again. Dont forget that current sinks you use on the chip generate some (small) heat in the process.

---
Tags: safety, arduino-uno-smd
---


title: Save Data before Shutdown

text:
# Question
Title: Save Data before Shutdown
I am building a positioner and I store the current position to EEPROM *when the move is complete*. On start up, I want the positioner to return to the HOME position. I am running an UNO powered from the USB. My problem is that if the Arduino is turned off, I would like to stop the move and store the current position before the Arduino dies.

Note that this would also be relevant to devices like thermostats which remember the set point through a power outage.

**POSSIBLE SOLUTIONS**

1. Store position in EEPROM at each step. No, that will wear out the EEPROM.
2. Connect a large capacitor from +5V to Gnd. When this falls below a set level, trigger an interrupt (ISR) that stops motion and stores current position in EEPROM.

**QUESTIONS**

1. Will #2 work, and how could I program it?
2. Any other ideas I am missing?

# Answer
> 4 votes
Thermostats would save the set point to eeprom once when the set point it set by the user. On startup it would just read the set point.

The analogue pins measure relative to VCC. So if you short the analogue pint to VCC the result will remain at max even as the voltage drops.

Instead use a diode to separate the measurement point from the power supply.

simulate this circuit – Schematic created using CircuitLab

As long as power is supplied the gpio input will be high. As soon as the power is removed the gpio pin will be low and the capacitor will need hold enough charge to save the position.

However what would happen if the positioner is manipulated when the arduino is off? Most devices have a callibration routine using end-of-travel detection or something similar they run on startup to find the home position.

# Answer
> 0 votes
Thanks for all the suggestions. At first I wanted a circuit like @ratchet freaks. I wanted to keep the mechanics and circuits very simple since the positioner is 3D printed and uses a standard M3 screw to move, so that rules out limit switches and encoders. I also realized the typical move only takes a max of 10 seconds, so I could just store the commanded position like @CrossRoads suggested. When the `HOME` command is given it steps back to 0.

Here is my Answer:

1. Store the EEPROM address of the persistent information at `EEPROM[0]`.
2. At that Address store the persistent information:
3. Item 1: `EEPROM[EEPROM[0]]` The number of writes to this address block as a two byte unsigned int.
4. Item 2: `EEPROM[EEPROM[0]+2]` The commanded position as a two byte signed int.
5. When the number of writes gets to about 5000, increment the address of the data in `EEPROM[0]`.

Working this way I'll gradually burn out the Arduino EEPROM, but it will take many years!

---
Tags: arduino-uno, eeprom
---


# Question
Title: Trying to connect FT sensor to Arduino Mega using RX TX
I am trying to interface this sensor, https://www.robotous.com/forcetorquesensor (RTF60-HA01-C), with the Arduino Mega. The sensor has an input voltage of 5Vs and communicates using CAN/RS232/RS422. I am using the RS232 and have connected wires properly and have tried to establish Serial Communication using the below code.

```
#include<String.h>
# define BuffSize 32

byte buff[BuffSize];
unsigned char data_field[16];
byte comm[11]  = {0x55, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xAA};
// SOP == 0x55, EOP == 0xAA, Checksum == summation of each data in data_field
void setup() {

  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial2.begin(115200);
  for (int i = 0; i < BuffSize; i++) {
    buff[i] = 13; //Number to initialise buffer
  }

}

  void loop() {
    // put your main code here, to run repeatedly:

     Serial2.write(comm, 11);
    //Serial.println(Serial2.available());
    if (Serial2.available() > 0) {
      //int read = Serial2.readBytes(buff, BuffSize);
        String output = "";
        for(int i=0;i<BuffSize;i++){
        buff[i]=Serial2.read();
        output = output + buff[i] + "|";
     }
  //Serial.println(read);
    Serial.flush();

    Serial.println(output);
    Serial.println();

    }
  }

```

The output I receive is just 0s and the occasional 10. Like below

```
0|0|0|0|0|0|0|0|10|0|0|0|0|0|0|0|0|10|0|0|0|0|0|0|0|0|10|255|255|255|255|255|

```

I am new to this and hope this is not a stupid question. Let

# Answer
The Serial RX and TX pins of an Arduino are not RS-232 compatible without using some type of circuit to give you the proper voltage levels.

```
**RS-232 logic and voltage levels**
0 (space)   Asserted    +3 to +15 V
1 (mark)    Deasserted  −15 to −3 V

```

Connecting the RX/TX pins of an Arduino directly to an RS-232 device may fry your Arduino in addition to just not working for communication. This circuit given below is an example what you'll need. There are pre-made adapter boards available for a few dollars.
> 1 votes

# Answer
You obviously haven't understood the way this device communicates over serial. You don't just throw an "11" at it to get it going - you have to craft a proper command packet and send that, and the device then starts responding with response packets that you must parse properly.

A command packet starts with 0x55, then has the command and data (8 bytes in total), then a checksum and EOP byte (0xAA).

For example:

```
0x55, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0B, 0xAA

```

When reading you do *not* look for "at least one byte" then try and read 32 bytes. That's just never going to work. You need to wait for 0x55 to arrive, then wait for each of the 16 following command+data bytes to arrive, one at a time (they do NOT arrive all at once!), and store them - then calculate the checksum for those command and data bytes, and read the next byte and make sure it matches the checksum. Finally, confirm you have a proper packet by reading the EOP byte of 0xAA.

Ideally, you want to implement a sliding window algorithm whereby you have an array of 19 bytes and incoming bytes filter down from one end of the array to the other. When the first byte is 0x55 and the last byte is 0xAA, and the penultimate byte equals the (truncated) total of bytes 2 to 17 inclusive, do you have an actual packet and can act on the data.
> 0 votes

---
Tags: serial, arduino-mega, sensors, robotics
---


# Question
Title: How to send an integer through pyserial with Python to an Arduino and get back the same result?
There has been similar questions all over the internet but none of them seem to answer my question, so can anybody tell me what is wrong with this code and how I can fix it?

Python code:

```
import serial

arduino_linux=serial.Serial("/dev/ttyACM0",9600)
while True:
    print('write:',str.encode('90')) #print the sent value through the serial to check it with the readed value
    arduino_linux.write(str.encode('90'))#send the following value
    print('readed:',arduino_linux.read())#read the same value back from the arduino

```

my arduino code is as follows

```
void setup() {
  Serial.begin(9600);

}

void loop() {
  Serial.write(Serial.read());

}

```

this is a simple sample of a project, my aim from this code is to send the integer number 90 from the pyserial and make sure the value the Arduino is reading is the same integer.

In case if necessary my project is an object follower with object detector and after calculating all the angles and everything it sends them to the Arduino so the Arduino can act up on the servo's.

This is the result I am getting:

But I would like something like:

```
write:b '90'

```

`readed:b '90'`, not `b'9'` or `b'0'`

I would also like to know how I can change these bytes to integers before I write them to a servo.

# Answer
> 0 votes
Use `Serial.write()` on Arduino to send raw bytes. `print` converts them to text.

`read` is not blocking, it doesn't wait for a byte and returns -1 if the receive buffer is empty. Check if read returned -1 or use `Serial.available()` to get the number of bytes in the RX buffer.

Serial 'echo':

```
void loop() {
  if (Serial.available()) {
    Serial.write(Serial.read());
  }
}

```

---
Tags: serial, programming, python
---


# Question
Title: Running ESP8266 at 3.78V to work with ATMEGA328P at 16 MHz
I have a project that is powered by 2x 18650 battery and feeds it to a step down switching voltage regulator that is configured to give a steady output of 3.78V to both esp8266 and atmega328p.

The esp8266 only sends an HTTP post request to an API every 30 mins and on standby mode whenever it does not do anything. I have tested it for 1 hour and the esp8266 seems to work fine and does not warm. I intend to use the esp8266 in an airconditioned office 24/7 or until the battery runs out. I know it is not safe to give 3.78V because its supposed to have only a maximum of 3.6V but I am asking if anyone has ever had the same application and did not experience any problems?

# Answer
> 0 votes
Other possibilities include:

* Running the Atmega328p at 8MHz and powering at 3.3v. Both devices would be operating within spec.
* Running the whole system at 3.3v but without changing the clock on the '328. The advantage here is you'll get the full throughput from the '328, assuming you need it. The disadvantage (assuming a 16MHz Atmega328p) is that it will be running out of spec (overclocked) but they seem to be conservatively enough speced that most chips do fine. I have built two boards this way for the same reason: to put both a 328p and an ESP8226-01 on one board. I ran some rather rudimentary tests on the Atmega chips I put on those boards to find out if they would work at that voltage. I didn't see any issues and I haven't discovered any since.

Update:

> Would it be possible to run the ATmega at 8 MHz using a 16 MHz external oscillator by simply uploading a new sketch?

It may be possible to use its internal resonator and ignore the connected crystal; I haven't tried this. Could you clip off the external crystal if you needed to?

This article talks about setting the fuses that control the clock frequency. One thing to keep in mind is you'll need to replace the bootloader with one appropriate for the new clock frequency. You may find an 8Mz bootloader ready to upload, or recompile it yourself from source. Optiboot is a good choice: open source, has a small footprint, and you can set its upload baud-rate. You can upload a new bootloader using another Arduino as an ISP programmer - there are lots of articles about doing this and the code for the Arduino-as-programmer is one of the Arduino IDE example-programs.

---
Tags: esp8266
---


title: ESP8266 GET method error

text:
# Question
Title: ESP8266 GET method error
I am working on ESP8266 and I want to send a GET request with AT command to my localhost but I failed every time. Can you help me solve this problem please? Thank you for interest! I attached my terminal code and my code:

```
#define ag_ismi "SUPERONLINE_WiFi_8022"
#define ag_sifresi "rC5YGNYebuCf"
#define IP "192.168.1.9"

void setup() {
  // put your setup code here, to run once:

  Serial.begin(115200);
  Serial.println("AT");
  delay(3000);
  if(Serial.find("OK")){
    Serial.println("AT+CWMODE=1");
    delay(2000);
    String baglantiKomutu=String("AT+CWJAP=\"")+ag_ismi+"\",\""+ag_sifresi+"\"";
    Serial.println(baglantiKomutu);
    delay(5000);
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(60000);
  Serial.println("AT+CIPMUX=1");
  Serial.println("AT+CIPSTART=\"TCP\",\"192.168.1.9\",8000");
  delay(1000);
  String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1";
  //model+="Host: 192.168.1.9:8000\r\n\r\n";
  model+="r\n\r\n";
  Serial.println("AT+CIPSEND=" + String(model.length()));
  Serial.println("\r\n\r\n");
  delay(1000);
  Serial.println(model);
  Serial.println("\r\n\r\n");
  delay(1000);
  Serial.println("");
}

```

# Answer
> 1 votes
It should be

```
String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1\r\n";
model+="Host: 192.168.1.9\r\n\r\n";

```

remove `Serial.println("\r\n\r\n");` before `Serial.println(model);` it is send before GET line

```
Serial.println("AT+CIPSTART=\"TCP\",\"192.168.1.9\",8000");
String model = "GET /kanbanDB/arduino?model=1 HTTP/1.1\r\n";
model+= "Host: 192.168.1.9\r\n\r\n";
Serial.print("AT+CIPSEND=");
Serial.println(model.length());
delay(1000);
Serial.print(model);
delay(1000);

```

EDIT: Remove debug prints to Serial or use SoftwareSerial to connect the esp8266 to Uno. Now the debug prints are sent to esp8266 mixed with AT commands and data. For SoftwareSerial change the default baud rate of the AT firmware.

---
Tags: esp8266
---


title: ESP8266-12F accelstepper wont boot

text:
# Question
Title: ESP8266-12F accelstepper wont boot
If I use 9, 10, 7, 6 , 8, 11 pins for accelstepper, ESP8266 wont boot If I use other pins, all good.

What is the problem?

I use accelstepper and Arduino latest versions.

sketch which won't boot -

```
    #include <AccelStepper.h>
#include <MultiStepper.h>

#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>

const char* ssid = "wiflya";
const char* password = ".........";

#define HALFSTEP 8

// Определение пинов для управления двигателем
#define motorPin1  13 // IN1 на 1-м драйвере ULN2003
#define motorPin2  12 // IN2 на 1-м драйвере ULN2003
#define motorPin3  14 // IN3 на 1-м драйвере ULN2003
#define motorPin4  16 // IN4 на 1-м драйвере ULN2003

// Определение пинов для управления двигателем
#define motor2Pin1  6 // IN1 на 2-м драйвере ULN2003
#define motor2Pin2  3 // IN2 на 2-м драйвере ULN2003
#define motor2Pin3  5 // IN3 на 2-м драйвере ULN2003
#define motor2Pin4  4 // IN4 на 2-м драйвере ULN2003

// Инициализируемся с последовательностью выводов IN1-IN3-IN2-IN4
// для использования AccelStepper с 28BYJ-48
AccelStepper stepper1(HALFSTEP, motorPin1, motorPin3, motorPin2, motorPin4);
AccelStepper stepper2(HALFSTEP, motor2Pin1, motor2Pin3, motor2Pin2, motor2Pin4);

void setup() {
  //Serial.begin(115200);
  //Serial.println("Booting");
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    //Serial.println("Connection Failed! Rebooting...");
    delay(5000);
    ESP.restart();
  }

  stepper1.setMaxSpeed(1300.0);
  stepper1.setAcceleration(400.0);
  stepper1.setSpeed(1300.0);

  stepper2.setMaxSpeed(1300.0);
  stepper2.setAcceleration(400.0);
  stepper2.setSpeed(1300.0);

  //stepper1.moveTo(20000);

  // Port defaults to 8266
  // ArduinoOTA.setPort(8266);

  // Hostname defaults to esp8266-[ChipID]
  // ArduinoOTA.setHostname("myesp8266");

  // No authentication by default
  // ArduinoOTA.setPassword("admin");

  // Password can be set with it's md5 value as well
  // MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
  // ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");

  ArduinoOTA.begin();
}

void loop() {
    // Изменяем направление, если шаговик достигает заданного положения
  //if(stepper1.distanceToGo()==0)
  //  stepper1.moveTo(-stepper1.currentPosition());
  stepper2.runSpeed();
  stepper1.runSpeed();
  //stepper2.runSpeed();

  ArduinoOTA.handle();
}

```

# Answer
Pins 6 to 11 of the esp8266 are QIO SPI pins connected to flash memory of the esp8266. You can't use them.
> 1 votes

---
Tags: esp8266
---


title: Arduino pow() making 9's

text:
# Question
Title: Arduino pow() making 9's
I am having a temporary lapse of judgement, or not understanding how the power method works, but when I put 10 to the power of a number, it is that value -1. So:

```
10*10 = 100

```

Then I would assume, `10^2 = 100`

So if I had a variable `i`, that was equal to `2`, and I asked arduino for `10` to the power of `i`, I would expect it to do `10^2`, and then give me `100`, but instead I get `99`. What am I missing?

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

void loop() {
for (int i =0; i<5; i++){
   int power = i;
   Serial.print(power);
   Serial.print(":");

   int multiplier = pow(10,power);
   Serial.println(multiplier);

  }

}

```

# Answer
> 3 votes
`pow()` works with floating point numbers.

Floating point numbers are just an approximation. You will very rarely get precise results using floating point numbers.

Instead you could write your own little integer-based `ipow()` function.

# Answer
> 3 votes
I put this code into the IDE, and for n\>=2, I got 99, 999, 9999 etc. The catch is that Arduino uses floating point arithmetic to implement the pow() function, and some of your values are being truncated as ints. If you change:

```
   int multiplier = pow(10,power);

```

to

```
   float multiplier = pow(10,power);

```

The results should be as expected.

(The brief reason why floats are used is related to the fact that it is very easy to calculate the pow() function using logs, and this makes it easy to pow() non-integers too. This also means that it may not be as exact as you would hope).

---
Tags: power, code-review, mathematics
---


# Question
Title: ESP8266 is not responding to AT commands and showing mem_failed on every code
I was using Arduino Uno with ESP8266-12E. Today I was reading an article to blink LED using Webpage. The code wasn't uploading so I connected all the pins connected to 3.3V to 5V. Then the code was uploaded successfully. After that I switched off my laptop and Arduino. After 2-3 hours when I got back to work, the module wasn't responding to AT commands even after reconnecting it to 3.3V. The wifi is working fine since it automatically connects to the WiFi I have configured earlier. I used same settings and connections prior to that messing up. Also on every code upload it shows mem\_failed. So, how can I get my WiFi to work?

# Answer
Buy a little development board and learn how to use the ESP8266. Either a NodeMCU or a WEMOS board. They have a USB to serial adapter on the board and a proper regulator.

The initial problem you encountered was most likely caused by insufficient power for the ESP8266. The power supply must be capable of supplying a minimum of 400mA. It needs to have close short wires to the Vcc and ground on the ESP module. It helps to also have a capacitor across Vcc and ground of the ESP module with short leads.

There are some horrible examples on the internet that show the ESP being powered from and Uno's 3.3v power connection. This will never be reliable if it does even work. There is not enough power.

The ESP8266 typically uses about 80mA. This is an average value. When transmitting the peak current is a lot hight. The worst case happens to be when the ESP starts after a reset. I then does an analog power calibration. (for the RF section) Expressif states this, plus the digital power requirements, will equal above 500mA.

The GPIO pins are not 5 volt compatible. A lot of internet examples show the ESP rx and tx lines connected to the rx and tx of a 5 volt Arduino board, without level converters. This is not acceptable. The RX line of the ESP8266 can be damaged.

Powering the ESP module with 5 volts can damage all or parts of the two chips on the module. (the CPU and the external Flash memory chip) Other sections may still work. That is likely what you are seeing.
> 0 votes

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


# Question
Title: Programming stepper motor move a fixed step till it reach the target
I have a stepper motor and try to program it like this but I kinda stuck since I'm new to Arduino. 1. The target is set to 2048, means motor have to move 2048 steps. 2. I program the motor to run 200 steps each time, every 200 steps will stop for a sec until it reach 2048.

I've been using AccelStepper library to program my motor, I found out it is very hard for me to program like this. I'm not asking to do my homework but I dunno where to start. Just wanted to ask what method can I use to program the motor to work like this. Thank you.

# Answer
I would start with the Blocking example provided with the library. Add the delays you need, the steps/distance you want. The following is simple but crude. It is call blocking code. It can only do the following sequence, but sometimes that is good enough.

A bit better would be to have a conditional loop to get to the final target. The loop would move 200, then delay 1 second, subtract the amount moved. Loop until you use up all the required distance. But initially I suggest to keep it simple and just make it work with inline sequences.

```
#include <AccelStepper.h>
// Define a stepper and the pins it will use
AccelStepper stepper; // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5
void setup()
{
    stepper.setMaxSpeed(200.0);
    stepper.setAcceleration(100.0);
}
void loop()
{
    stepper.runToNewPosition(0);
    delay(1000);
    stepper.runToNewPosition(200);
    delay(1000);
    stepper.runToNewPosition(200);
    delay(1000);
    stepper.runToNewPosition(200);
}

```
> 1 votes

---
Tags: motor
---


# Question
Title: Synchronous communication between two Arduino boards using two ESP8266 modules
I am trying to establish communication between two Arduino boards to send data from sensors through a WIFI module. The problem is that I need them to connect to each other whenever they are in range of each other and send the sensor data.

# Answer
The esp8266 WiFiMulti system allows to configure more access points and with the rigth code in loop it always searches the best AP.

Configure one of the esp8266 as AP and setup the other with WiFi Multi only for this one access point.

You can then use events like `onStationModeConnected` to handle data exchange if the connection is established.
> 1 votes

---
Tags: esp8266
---


# Question
Title: Unable to get output on Arduino serial communication with ESP8266 and M6E RFID reader
I am unable to get the output on NODEMCU serial. NODEMCU is connected with Arduino Uno, and Uno is connected with M6E Nano RFID reader. Currently I am unable to understand that am i doing any mistake. Please let me know if any other thing you require.

NodeMCU and M6E Nano RFID reader pin configuration with Arduino Uno

```
NodeMCU         UNO
Vin             Vin
GND             GND
D2              2
D3              3

```

Code for Arduino Uno+M6E Nano RFID Reader

```
#include <SoftwareSerial.h>
SoftwareSerial softSerial(2, 3);

#include "SparkFun_UHF_RFID_Reader.h"
RFID nano;

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

  while (!Serial);
  Serial.println();
  Serial.println("Initializing...");
}

void loop()
{
  byte response;
  byte myTID[20]; //TIDs are 20 bytes
  char str[sizeof(myTID) * 2 + 1];
  const char* hex = "0123456789ABCDEF";

  //Read unique ID of tag
  response = nano.readTID(myTID, sizeof(myTID));
  if (response == RESPONSE_SUCCESS)
  {
    for (int i = 0; i < sizeof(myTID); i++)
    {
      str[i * 2] = hex[(myTID[i] >> 4)];
      str[i * 2 + 1] = hex[(myTID[i] & 0x0F)];
      }
    str[sizeof(str)] = 0;
    Serial.println(str);
   }
  else
    Serial.println("Failed read");
}

```

Code for NODEMCU

```
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
SoftwareSerial NodeMCU(D3,D2);

void setup()
{
  Serial.begin(9600);
  NodeMCU.begin(4800);
  pinMode(D2,OUTPUT);
  pinMode(D3,INPUT);
}

void loop(){
  String str = 0;        // stores received byte

  if(NodeMCU.available())
  {
    // get byte from USB serial port
    str = Serial.read();
    NodeMCU.write(str);
  }
delay(30);
}

```

Unable to find where i am doing the mistake! Thanks in advance

# Answer
> 0 votes
1. You have not the same baud rate on both ends.
2. SoftwareSerial is not reliable at 115200. use 9600 baud
3. SoftwareSerial on esp8266 is not reliable.

remove Uno from the project and connect the reader to NodeMcu

---
Tags: arduino-uno, esp8266, nodemcu
---