# Question
Title: How to run TCP socket server on Arduino Uno WiFi?
## 2017-03-23 update

I still don't know why it works so well on Yún. Maybe it has a better antenna? Anyway, I've returned Uno WiFi and got a SparkFun ESP32 Thing. Unfortunately, it has the same problem as Uno WiFi. To fix it I've switched from TCP to UDP. It made a world of difference: servos are very responsive now. UDP is OK for my use case: I can send the state of the whole system in each message and lost messages or messages arriving out of order are not a big problem.

## Original question

I want to control servos over WiFi with high precision and low latency. I managed to achieve this using TCP socket communication with Arduino Yún. I want to repeat this with Arduino Uno WiFi, but I can't find example code for socket communication. I connected to the board using telnet but servo output is jerky — as if there was a `delay` after each `servo.write` call.

How can I run a TCP socket server on Arduino Uno WiFi in a way that allows for fast low latency communication?

## Longer description

I experimented with controlling servos over WiFi using an Arduino Yún board that I borrowed from a friend. I connected a MG92B servo to pin 9, 5V, and GND. I start a TCP socket server on the Arduino and send angle values from a Python script dozens of times per second. It works smoothly.

Encouraged by this experiment I bought my own Arduino. I chose Arduino Uno WiFi (developer edition) because, unlike Yún, it's compatible with shields. Unfortunately I can't find example code for socket communication. I found an example that uses telnet, so I adapted it and used it with my Python script. Sadly, the servo movement is jerky — as if there was a `delay` after each `servo.write` call.

Below is a video showing both boards running two sketches: "no network movement" and "network movement".

## Video

## Code

I attach all code I used.

### Arduino oscillation test with no remote control

I use this code to test that the servo is working correctly. It works on both Arduino Yún and Arduino Uno WiFi.

```
#include <Servo.h>

const int servoPin = 9;
Servo servo;

void setup() {
    servo.attach(servoPin);
}

void loop() {
    // configure movement
    int angleMin = 15;
    int angleMax = 165;
    int interval = 30;

    // oscillate between `angle_min` and `angle_max`
    int angle = angleMin;
    for (int i = 0; i < 2; i = (i + 1) % 2) {
        int sign = pow(-1, i);
        for (int j = 0; j < angleMax - angleMin; j += 1) {
            angle += sign;
            servo.write(angle);
            delay(interval);
        }
    }
}

```

### Arduino Uno WiFi reading from telnet

This is jerky.

```
#include <Servo.h>
#include <UnoWiFiDevEd.h>

const int servoPin = 9;
Servo servo;

void setup() {
    Wifi.begin();
    servo.attach(servoPin);
}

void loop() {
    while (Wifi.available()) {
        servo.write(Wifi.read());
    }
}

```

### Arduino Yún reading from socket

This is smooth.

```
#include <Bridge.h>
#include <Servo.h>
#include <YunClient.h>
#include <YunServer.h>

// configure
const int port = 5555;
const int servoPin = 9;

// listen on given port
Servo servo;
YunServer server(port);

void setup() {
    // set up servo
    servo.attach(servoPin);

    // start server
    Bridge.begin();
    server.noListenOnLocalhost();
    server.begin();
}

void loop() {
    YunClient client = server.accept();
    byte angle;

    if (client) {
        while (client.connected()) {
            angle = client.read();
            if (angle != 255) {
                servo.write(angle);
            }
        }

        client.stop();
    }

    Serial.println("waiting for client");
    delay(1000);
}

```

### Python writing to socket

This is the network equivalent of the Arduino oscillation test. Works both with Yún (port 5555) and Uno (port 23).

```
import socket
from time import sleep

# connect
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.240.1', 5555))  # use 5555 for Yun and 23 for Uno

# configure movement
angle_min = 15
angle_max = 165
interval = 30 / 1e3

# oscillate between `angle_min` and `angle_max`
while True:
    angle = angle_min
    for sign in [1, -1]:
        for _ in range(angle_max - angle_min):
            angle += sign
            client.send(bytearray([angle]))
            sleep(interval)

```

# Answer
I *suspect* these delays are caused by TCP buffering.

For some theory on this sort of thing, perhaps read about Nagle's Algorithm which covers some of the issues with small packet buffering. It seems reasonable to me that lower-power and/or lower-speed (or even "just different") boards would use more aggressive buffering.

TCP uses all manner of buffering and checks to ensure guaranteed delivery of data (or reported error), whereas UDP does not.

If UDP is working for you, perhaps you may want to include some of your own error tracking in the comms protocol, unless missing the odd packet is not an issue to your control system.
> 1 votes

---
Tags: arduino-uno, wifi, tcpip
---


title: TCCR1A and TCCR2A on Leonardo

text:
# Question
Title: TCCR1A and TCCR2A on Leonardo
I'm trying to use the TTS library for Arduino on an Arduino Micro board, which is based on the Leonardo. When I try to compile my sketch I get some errors;

```
/libraries/TTS/TTS.cpp: In function 'void soundOff()':
/libraries/TTS/TTS.cpp:355: error: 'TCCR2A' was not declared in this scope
/libraries/TTS/TTS.cpp:355: error: 'COM2B1' was not declared in this scope
/libraries/TTS/TTS.cpp: In function 'void soundOn()':
/libraries/TTS/TTS.cpp:382: error: 'TCCR2A' was not declared in this scope
/libraries/TTS/TTS.cpp:382: error: 'COM2B1' was not declared in this scope
/libraries/TTS/TTS.cpp:382: error: 'WGM20' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'TCCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'CS20' was not declared in this scope
/libraries/TTS/TTS.cpp:383: error: 'WGM22' was not declared in this scope
/libraries/TTS/TTS.cpp:384: error: 'OCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:385: error: 'TCNT2' was not declared in this scope
/libraries/TTS/TTS.cpp: In function 'void sound(byte)':
/libraries/TTS/TTS.cpp:424: error: 'OCR2B' was not declared in this scope
/libraries/TTS/TTS.cpp:425: error: 'TCNT2' was not declared in this scope

```

Googling revealed that the Leonardo uses different timers. And other things I don't understand! But I couldn't piece together an answer beyond that.

What are the correct constants to use for Leonardo boards, and is there a way I can update the library to work across both?

# Answer
> 0 votes
Apparently the library in the OP's link has been updated to support the Leonardo, so this problem should now be solved.

---
Tags: arduino-leonardo, library, timers, arduino-micro
---


# Question
Title: Connecting Saleae Logic 8 to MISO (pin 12) on Uno 3 w/ NRF24L01+ halts program
I have an `NRF24L01+` with the base module (regulates voltage) connected to an Arduino Uno 3. I'm using the `tmrh20` `NRF24` library and am running one of the example programs. I'm trying to sniff the SPI bus so I have a Saleae Logic 8 hooked up. As soon as I connect the clip to the `MISO` pin the Arduino program stops executing. I'm able to reproduce this 100% of the time. It seems it is only the `MISO` pin that is causing the problem. For the library I am using `MISO` uses `pin 12` on the Uno 3.

Anybody know what is going on? It seems as if the Saleae is grounding `pin 12` when I hook it up. Not sure why it is only `pin 12` that is an issue though.

I can reproduce the same problem when I manually connecting pin 12 straight to `GND` as well.

I can collect samples without `MISO` just fine but that of course only tells me half the story.

Any suggestions?

EDIT: Here are some links and resources for more information.

I'm basically following the instructions from this article: http://arduino-info.wikispaces.com/Nrf24L01-2.4GHz-HowTo

The breakout board http://www.addicore.com/1x-nRF24L01-Adapter-p/ad279.htm

And it's schematic:

Link to the datasheet for the radio itself: http://www.nordicsemi.com/eng/Products/2.4GHz-RF/nRF24L01  And some photos of how I have it wired up:

# Answer
It would appear from your description that the leads on your logic analyzer distort of the SPI MISO waveform and the Arduino does not read incoming data correctly.

To avoid this, you could place an digital isolator between the Arduino and the Logic 8.

Any decent oscilloscope should also allow you to read the SPI bus.
> 1 votes

---
Tags: arduino-uno, spi, nrf24l01+
---


# Question
Title: Could I Connect many Arduino Nano boards together?
I want to know if I could connect many Arduino Nano boards together (Example : 10 boards ) , Also i want to know if there is any problem in Communication between them using I2C , could this affects processing speed on every board , and if there's going to be any kind of delay when communicating?

# Answer
> I want to know if I could connect many Arduino Nano boards together...

Yes, you can read about it here at arduino.cc. Where is says: "...it can be helpful to set up two (or more!) Arduino ... boards to share information with each other..."

> ... i want to know if there is any problem in Communication between them using I2C ...

This feature, according to the above link, is expected to work. (Can you explain the type of problems you are avoiding?)

> ...could \[i2c communication\] affect processing speed on every board ...

Most likely it will. Most Arduino platforms do not run operating systems. So your program is all that is running. If your program is busy sampling sensors, it will be difficult (not impossible) to concurrently handle i2c communications.
> 2 votes

# Answer
Yes it certainly is possible. And can work well if done properly. The concern that I have is when longer wiring lengths are used. I2C is not intended for extended distributions. And if that were the plan then I STRONGLY advise using proper I2C buffer chips designed for that purpose.

The more devices, the more wire, all adds to the capacitance on the lines. Because I2C uses pull up resistors to produce a high the added capacitance limits either the length of wire that can be used, or the transmission frequency. I have used I2C buffers in may products and it is very useful when extended length is required. I use both I2C buffers, and also I2C isolated buffers. The company I work for manufactures distributed control electronics. I am one of the hardware designers. I have been using I2C like this for about 15 years.

For now have a look at this web page. http://www.techbitar.com/how-to-network-many-arduinos-with-sensors-using-i2c.html

I'm sure it will spur some questions. It makes things simpler if there is only one master controlling the communications bus. Multimast is possible but can have more conflicts and you then need to deal with that issue. Best not to go there.

I2C is not a very robust protocol but still can be usable between processors if handled carefully. Keep it simple.
> 2 votes

---
Tags: arduino-nano, i2c, communication
---


# Question
Title: How is it possible to access the CPU registers using memory addresses?
The following is taken from ATmega328-328P Data sheet.

According to this, I can access all the 32 registers in CPU using memory addresses. For example:

```
 unsigned char *register = 0x0;

```

will access the first register. Is this true? if so, then is this also possible to do on regular CPUs (like my laptop), since I thought you can only use a pointer to access memory and not CPU registers.

Is the register mapped into the SRAM in this case?

# Answer
> 2 votes
Microcontrollers tend to be simple compared to processors like you would find in your laptop. Most operating system make use of the higher security features that can prevent user programs from straying where they shouldn't be.

As far as registers being memory mapped, it really depends on the particular architecture, each CPU. They are not all the same.

> Is the register mapped into the SRAM in this case?

The data address space maps the 32 general-purpose registers, all the I/O registers (including those also accessible through the I/O address space), and the RAM

---
Tags: c, sram
---


# Question
Title: Hex output although I always define integer
Code below is to read 4 thermometers and use values to turn on or off the heaters (I'm stuck at reading).

I'm reading and displaying temperature very well, but it comes to the problem, where I want to set the limit of heating, a value of 37 degrees. It comes to the problem, when I want to read the value of "tempa", but the Arduino doesn't respond properly: it somehow reads the value as char or I get the output in hex instead of integer (although I never declared a character in whole program).

It can be seen in last 2 lines before "CHANNEL\_2".

Lines are:

```
lcd.setCursor(10, 0);    //termometer
lcd.write(tempa);    //termometer

```

absoluta, absolutb, absolutc and absolutd are variables, which are technically values of temperature in Kelvin.

tempa, temb, tempc and tempd are variables, the temperature in celsius.

```
#include <LiquidCrystal.h>
#define  LM335_pin  0                          // LM335 output pin is connected to Arduino A0 pin
#define  LM335_pio  1                          // LM335 output pin is connected to Arduino A0 pin
#define  LM335_pip  2                          // LM335 output pin is connected to Arduino A0 pin
#define  LM335_pir  3                          // LM335 output pin is connected to Arduino A0 pin

const int rs = 7, en = 8, d4 = 5, d5 = 4, d6 = 3, d7 = 2; // LCD module connections (RS, E, D4, D5, D6, D7)
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

  //-----------------------HEATERS----------------------------------------
//int grelea = 11;  //heater_1
//int greleb = 10;  //heater_2
//int grelec = 9;   //heater_3

void setup() {
  lcd.begin(20, 4);

//  pinMode(grelea, OUTPUT);
//  pinMode(greleb, OUTPUT);
//  pinMode(grelec, OUTPUT);

}
int  absoluta, tempa; //sensor_1
int  absolutb, tempb; //sensor_2
int  absolutc, tempc; //sensor_3
int  absolutd, tempd; //sensor_4

void loop() {

  delay(1000);

  //-----------------------CHANNEL_1----------------------------------------
  absoluta = analogRead(LM335_pin) * 0.489;
  tempa = absoluta - 273;

  lcd.setCursor(0, 0);    //termometer

  lcd.setCursor(0, 0);    //termometer
  lcd.write("Temp1=");    //termometer

  lcd.setCursor(8, 0);    //termometer
  lcd.write((tempa / 10)% 10  + 48);    //termometer

  lcd.setCursor(9, 0);    //termometer
  lcd.write(tempa % 10  + 48);    //termometer

  lcd.setCursor(10, 0);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 0);    //termometer
  lcd.write("C");    //termometer

  lcd.setCursor(15, 0);    //termometer
  lcd.write(tempa);    //termometer

  //---------------------------------------------------------------

  //-----------------------CHANNEL_2----------------------------------------
  absolutb = analogRead(LM335_pio) * 0.489;
  tempb = absolutb - 273;

  lcd.setCursor(0, 1);    //termometer
  lcd.write("Temp2=");    //termometer

  lcd.setCursor(8, 1);    //termometer
  lcd.write((tempb / 10) % 10  + 48);    //termometer

  lcd.setCursor(9, 1);    //termometer
  lcd.write(tempb % 10  + 48);    //termometer

  lcd.setCursor(10, 1);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 1);    //termometer
  lcd.write("C");    //termometer
  //---------------------------------------------------------------

  //-----------------------CHANNEL_3----------------------------------------
  absolutc = analogRead(LM335_pip) * 0.489;
  tempc = absolutc - 273;

  lcd.setCursor(0, 2);    //termometer
  lcd.write("Temp3=");    //termometer

  lcd.setCursor(8, 2);    //termometer
  lcd.write((tempc / 10) % 10  + 48);    //termometer

  lcd.setCursor(9, 2);    //termometer
  lcd.write(tempc % 10  + 48);    //termometer

  lcd.setCursor(10, 2);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 2);    //termometer
  lcd.write("C");    //termometer
  //---------------------------------------------------------------

  //-----------------------CHANNEL_4----------------------------------------
  absolutd = analogRead(LM335_pir) * 0.489;
  tempd = absolutd - 273;

  lcd.setCursor(0, 3);    //termometer
  lcd.write("Temp4=");    //termometer

  lcd.setCursor(8, 3);    //termometer
  lcd.write((tempd / 10) % 10  + 48);    //termometer

  lcd.setCursor(9, 3);    //termometer
  lcd.write(tempd % 10  + 48);    //termometer

  lcd.setCursor(10, 3);    //termometer
  lcd.write(char(223));    //termometer

  lcd.setCursor(11, 3);    //termometer
  lcd.write("C");    //termometer
  //---------------------------------------------------------------
}

```

# Answer
> 1 votes
`lcd.write()` will write one byte to the LCD. It makes no attempt to try to interpret the data type of the input parameter. You can think of it like sending "raw data" to the LCD.

`lcd.print()` can be called with many types as input and will interpret that the user wishes to print a human-readable expression of the data. Also, it can print more than one byte.

As an example, the `char` variable with content `'A'` is represented in RAM by the byte with value 65 (the ASCII code for 'A'). If you call `lcd.print('A')`, it will see that `'A'` is a `char` and will send whatever raw data to the LCD to get an "A" on the screen. It just so happens that sending a raw byte 65 will accomplish this, but that is a coincidence; the LCD driver understands ASCII for getting characters to print on the screen.

If you call `lcd.write(125)`, then the actual byte `125` (in binary, `01111101`) is sent to the LCD. If you wanted to actually print the 3-digit number 125, `lcd.print(125)` would end up sending 3 bytes to the LCD: The ASCII values for `'1'`, `'2'`, and `'5'` (which are 49, 50, and 53). The `print()` function takes care of this interpretation for you.

---
Tags: arduino-uno, string, variables
---


# Question
Title: "undefined reference to SD" with SdFat library
is there any way to rename a file in sd card without using **SdFat**? Thank you im getting error when inclung the

```
    #include <SPI.h>
    //#include <SD.h>
    #include <SdFat.h>
    extern SdFat SD;

```

the error msg was "Error compiling for board Arduino/Genuino Uno. "

```
Local\Temp\ccZn9IeW.ltrans2.ltrans.o: In function FatVolume::init(unsigned char) [clone .constprop.18]': \Arduino\libraries\SdFat\src/FatLib/FatVolume.cpp:439: undefined reference to SD' \Arduino\libraries\SdFat\src/FatLib/FatVolume.cpp:440: undefined reference to `SD'

```

# Answer
> 1 votes
Remove the `extern` keyword from `SdFat SD;` because it tels the compiler that the variable is defined elsewhere and it is not and the linker then can't find it.

---
Tags: arduino-uno, sd-card
---


title: Midi controlled LED by USB

text:
# Question
Title: Midi controlled LED by USB
I am trying to create something that will allow me to control an individually adressable LED strip using an electric piano using its midi output.

Some things to note:

* The piano can output midi either via USB or via standard midi connectors.
* I have an Arduino Uno and an Arduino Mega available
* I'm using a WS2812B strip with +ve, ground and data cables

I don't believe there's a way to read midi from my piano direct to the arduinos without reflashing the USB controller. For this reason I'm connecting via USB to my mac. On my mac I've written a program which reads the midi input and can understand it and send it on to somewhere else.

The arduino for the light strip I think I can program pretty easily but I have some questions:

* If I need to power the LED strip, should I be powering it from the arduino power or giving it its own power source with common ground?
* Is splitting it up into midi -\> computer, computer -\> arduino, arduino -\> LED strip sensible? If not how should I be going about it?
* Am I making life difficult by going the USB route for Midi or should I switch to midi connectors and connect direct to the arduino somehow?

# Answer
I did some time ago something very similar, except not using USB, and on an STM32 (Arduino compatible STM32F103C8T6), but the principle is similar.

Regarding another MIDI test I did on an Arduino, I used the 47 Effects library and for the WS2813 (software-compatible with WS2812B) the FastLed library.

One MIDI port is easy to use (supported by 47 Effects), which uses the single UART of the Arduino UNO.

You have to write a small program to convert the MIDI notes to WS2812 LED data, which is not much more than filling in a structure. Mapping 61 or 88 notes to 30, 60 or 144 LED notes is not so easy, just clip the notes, or use some mapping factor.

You cannot use the Arduino for powering the LED strip, use a separate adapter for that. Only the line signal comes from the Arduino, and connect GNDs together.

The Arduino should be fast enough to both read MIDI, translate it to LED data (unless you make some very time consuming algorithm) and send the data.
> 2 votes

---
Tags: arduino-uno, arduino-mega, led, midi
---


# Question
Title: ESP-01S Relay V1.0 connection with Arduino
I am new to Arduino

Let me ask you about IOT(internet of things).

I want to connect ESP-01S Relay v1.0

Where does the NC port goes on Arduino? Is it TX or RX?

Also, where does the NO goes on Arduino? Is it TX or RX?

# Answer
The 2 connections you refer to (NC and NO) are connections to the relay switch.

* **NO** stands for *normally open*
* **NC** stands for *normally closed*
* **C** or **COM** stands for *common*

When the relay is unenergised, the common is connected to the NC terminal. When power is applied to the relay, the coil energises and switches, so now common is connected to the NO terminal.

From my reading of the usage document located on the GitHub repository, you are supposed to program the ESP module before plugging it into the relay board. There are no terminals broken out for you to connect to the Tx and Rx on the relay board.

However, the following board from AUS-eParts has a header to connect a 3V TTL cable. This can be used to program the ESP module.
> 2 votes

# Answer
Common, Normally Connected and Normally Open are terminals switched by the relay. There you connect what should be switched. Common is input and the two other terminals are connected, one if the coil is powered and the other when the coils is without power. The relay is controlled by the esp-01. No Arduino should be connected to this.

Disconnect the esp-01 from the relay board and use an 3.3 V USB-to-TTL Serial adapter to program the esp-01 with Arduino IDE

Add Over The Air support to your esp8266 sketch with ArduinoOTA library and then you can upload new versions of your sketch over WiFi. To debug the sketch with `print` use Telnet server or my TelnetStream library.
> 0 votes

---
Tags: esp8266, wifi
---


title: Daikin Remote ARC

text:
# Question
Title: Daikin Remote ARC
I started off attempting to use the IRRemote Library and a VS1838B Sensor to capture the Daikin air condition signal. I’ve read about the timing and in all honesty, I don’t think I can do it on my own so I looked to find the code others had created and adapt it to my own, trying their remote controls first thinking Daikin may only have a few sets.

I can’t confirm that will work as yet because I’ve only been able to find the code below but I’m not quite sure what is the best practice for ripping (stripping out the parts I don’t need) it apart.

When I attempted to capture the IR codes, most of the time I get nothing at all. My stereo remote is immediate displayed though.

Now the good news, based on Harizanov’s work, he’s mapped the ARC533 Remote, which is the same model that I have.

NV2S (On the Inverter)

Code Here: Control Daikin air conditioner over the Internet

Code here: Github: mharizanov/Daikin-AC-remote-control-over-the-Internet

Can anyone provide a recommendation on how I could trim up this code to try it?

# Answer
> 1 votes
I had a problem with my daikin A/C. After spending lot of time trying to fix this problem, i found out that is is using long ir codes which is hard to simulate using the IRSenderBitBang (38 kHz). After lot of fustation I used irdevkit.com. It has a ir decoder built in and I can control it using ESP8266. Works well

---
Tags: remote-control
---


# Question
Title: Using MQTT to send time stamp - to Arduino
In previous question in this forum - I asked about updating clock on an ESP8266, using MQTT broker to send a time stamp on demand, in following manner:

1) ESP8266 sends a publish containing the payload :"sync",

2) broker answers in string format ( this part is python )

```
def on_message(self, client, obj, msg):
    self.arrived_msg = msg.payload.decode()
    if self.arrived_msg == "sync":
        a = datetime.datetime.now()
        b = "%d,%d,%d,%d,%d,%d,%d" % (a.year, a.month, a.day, a.hour, a.minute, a.second, a.microsecond) .  <------ here a string time format is created
        self.client.publish(topic=self.topics[0], payload=b, qos=self.topic_qos)

```

3) on a terminal (MAC OS), subscribed to relevant topic- cant see publish results. which are OK:

```
sync                           <----- ESP sends request
2018,9,18,12,44,18,903242      <----- string answer from broker

```

4) **BUT** when Arduino code get this time stamp:

```
void callback(char* topic, byte* payload, unsigned int length) {
        char incoming_msg[50];
        // ledBlink(30, 5);
        Serial.print("Message arrived [");
        Serial.print(topic);
        Serial.print("] ");
        for (int i = 0; i < length; i++) {
                Serial.print((char)payload[i]);  <----- print #1
                incoming_msg[i] = (char)payload[i];  <----- generate incoming msg
        }
        Serial.println("");

        if (strcmp(topic,clockTopic)==0) {       <------- detect relvant topic for clock sync
                Serial.print(incoming_msg);  <------ Print #2
        }

```

5) I get this result on serial monitor :

```
Message arrived [HomePi/Dvir/Clock] 2018,9,18,13,48,5,230009 <---- here time stamp is OK , Print #1
2018,9,18,13,48,5,230009$��?O: @ . <----- Print #2

```

EDIT1:

6) I tried adding a null termination in time stamp, but it just added `\0` to time stamp Appreciate any help

Guy

# Answer
> 1 votes
You forgot to set the terminating zero of the c-ctring `incoming_msg`.

add `incoming_msg[length] = 0;`

# Answer
> 1 votes
In C a string is "null terminated". That means that the very last character of every string *must* be character 0 (or NULL).

You need to ensure that you add that NULL character to the end of your `incoming_msg` string to terminate it, or force the entire string to be cleared to NULLs before you populate it.

The simplest way is to zero the string:

```
bzero(incoming_string, 50);

```

Or you can force a 0 to be appended after each byte is added:

```
incoming_msg[i] = (char)payload[i];
incoming_msg[i+1] = 0;

```

Or just add one at the end:

```
incoming_msg[length] = 0;

```

There's many ways of doing it - as long as you get that NULL in there somehow.

---
Tags: esp8266, mqtt
---


# Question
Title: How can you have two blinking leds and a fading one
I am trying to make a alarm and I have two blinking leds (red and blue). They work fine but I want two more that fade in and out.

I have a buzzer on it too.

I am very new to programming. By the way, the code below runs with no errors; just does not do what its intended to.

```
int led = 9;
int brightness = 0;
int fadeAmount = 5;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  delay(200);
  digitalWrite(11, LOW);
  delay(200);

  digitalWrite(12, HIGH);
  delay(200);
  digitalWrite(12, LOW);
  delay(200);

 digitalWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);
}

```

# Answer
> 2 votes
While there are better ways to do this, as pointed out by other posters, for what you're trying to learn right now, your program (almost!) works just fine. You'll need the more advanced techniques as you progress to more complex programs. But for now, I made a couple of edits to your program to get you going:

* The most important one was to use `analogWrite()` for the PWM LED (LED 9). That makes it fade in and out instead of turn on and off (with a long period).
* I turned one LED on and one off at the same time, getting rid of the dark periods and 400ms of combined delay.
* I doubled the fadeAmount to fade in and out a little faster; it wasn't very visible with an increment of 5.

Here it is with those changes:

```
int led = 9;
int brightness = 0;
int fadeAmount = 10;

void setup() {
  pinMode(11,OUTPUT);
   pinMode(12,OUTPUT);
    pinMode(led, OUTPUT);
}

void loop() {
  digitalWrite(11, HIGH);
  digitalWrite(12, LOW);
  delay(200);
  digitalWrite(11, LOW);
  digitalWrite(12, HIGH);
  delay(200);

 analogWrite(led, brightness);

 brightness = brightness + fadeAmount;

if (brightness <= 0 || brightness >= 255) {
  fadeAmount = -fadeAmount;
}
 delay(30);

```

}

Update:

> what if i wanted to add a a second led

I'm assuming you mean a fading LED, that it's pretty clear where you'd a blinking one?

Blinking in-phase is easy - write the same `brightness` to both. To fade them out of phase, you'll need a second brightness-variable (and possibly a second fade-amount), and an increment/decrement and limit test for each LED.

But note how your code starts getting more complex as you add components and try to manage them in a single loop, with `delay()`s? That's when you'll want to try the Blink Without Delay example, and compare adding new LEDs that way, to adding new LEDs to your current program.

# Answer
> 0 votes
You have 2 problems:

1. You are using `digitalWrite()` with an analog value. `digitalWrite()` will interpret a value of `0` as LOW and any other value as HIGH. So the LED will mostly be on and only off in the time, when the brightness value becomes zero. You will have to use `analogWrite()` to get a fading effect.
2. Currently your fading effect will be very very slow, since the value is only updated once every 830 ms. You should ditch all the `delay()` calls and instead use the principle, that is shown in the `BlinkWithoutDelay` example of the Arduino IDE. Think of the blinking as being like baking a pizza. When you want to bake a pizza in your oven, you wouldn't want to sit in front of the oven, staring at the pizza and waiting for it to be ready. This is basically, what you are doing with LED blinking in your sketch. With the pizza you would look at the clock, when you put the pizza in. Then you would go away doing other things and regularly check the clock for how much time has gone by. And then, when it is finally the time to take the pizza out, you would go back to the oven. There are plenty explanations and tutorials on the web, what exactly is done there.

Here at the Arduino documentation you can find the example with explaining text.

---
Tags: arduino-uno, led, buzzer
---


# Question
Title: Correlated signal from two sensors in one circuit
I have water level/humidity sensor and a LDR diode hooked to arduino like this (the resistor is 10k)

* On `A0` I can read signal from water sensor (blue)
* On `A1` I can read signal from light sensor (yellow)

The problem is that both signals seem to be correlated. When I dip the water sensor to water and keep the light levels the same, the signal from light goes up as well (dramatically).

I suspect that this is due to Ohm's law. The voltage in a circuit depends on the total resistance of the circuit. Both sensors act as a sort of resistors so when one's resistance changes the voltage in the circuit changes as well.

How can I wire the sensors such that the change in resistance of either sensor doesn't affect the second? Or do I need a separate power supply for each sensor?

# Answer
> 1 votes
If I've found the same humidity sensor, it has pretty big output impedance and the maximum input impedance for the `ADC` input is `10kOhms`. According the the datasheet the recommended minimum load for the sensor is about `80kOhms` (?). That means readings of humidity sensor will be highly affected by sampling capacitor initial charge (= the value of previous reading).

Basically reading `GND` between sensor readings helps to separate the results from each other, but the humidity sensor won't be able to charge sampling capacitor to its output voltage without amplifying the current (you'll get values much lower than it should be).

Or you can repeat the readings on humidity sensor channel several times until the value is more "stable".

---
Tags: sensors
---


# Question
Title: not able to resolve "a function-definition is not allowed here before '{' token "
I, being new to Arduino started off by making a simple lcd watch which also shows the temperature.

Everything was working fine untill this error came up **"a function-definition is not allowed here before '{' token "**

And I have done everything to resolve the problem. I wrote the function from scratch. I read somewhere that a function definition can't come within a function, so I made it a Global function(though, personally I somehow don't feel that it's true). But even then the error managed to survive.

Being completely frustrated I don't know what to do. Can anyone please help me out ?

here's my code :-

```
#include < LiquidCrystal.h >

  const int rs = 12,
    en = 11,
    d4 = 5,
    d5 = 4,
    d6 = 3,
    d7 = 2,
    lm = A0;
int input;
float temp;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void tem() //Calculates Temperature
{
  int i = analogRead(lm);
  float temp = 500.0 * i / 1024;

  lcd.print("Temp : ");
  lcd.print(temp);
  lcd.print(" ^C");

}

void Clock(int h = 0, int m = 0, int s = 0, char ch = 'A') {
  int H = h;

  char ampm = ch;

  void mornight(char ampm) //changes am to am to pm and vice versa
  { //THE RED HIGHLIGHTED ERROR LINE
    String AMPM;
    if (ampm == 'A')
      AMPM = "PM";
    else
      AMPM = "AM";

  }
  while (H != 12) //HOUR'S LOOP
  {
    for (int M = m; M <= 59; M++) //MINUTE'S LOOP
    {
      for (int S = s; S <= 59; S++) //SECOND'S LOOP
      {
        delay(1000);
        lcd.clear();

        if (H < 10) {
          lcd.print('0');
          lcd.print(H);
          lcd.print(':');
        } else {
          lcd.print(H);
          lcd.print(":");
        }
        if (M < 10) {
          lcd.print('0');
          lcd.print(M);
          lcd.print(':');
        } else {
          lcd.print(M);
          lcd.print(":");
        }
        if (S < 10) {
          lcd.print('0');
          lcd.print(S);
          lcd.print(AMPM);
        } else {
          lcd.print(S);
          lcd.print(AMPM);
        }
        lcd.setCursor(0, 1);
        tem(); // shows temperature

      }
      s = 0;
    }
    m = 0;
    if (H == 23) {
      H = 1;
      mornight(ampm);
    } else
      H++;
  }
}

void setup() {
  lcd.begin(16, 2);
  lcd.setCursor(0, 1);
  Clock(10, 1, 20);

}
void loop() {

}

```

# Answer
> 1 votes
Your line:

```
void mornight(char ampm)

```

Is trying to define a function called `mornight()` inside of `Clock()`.

Functions are "global" if they are defined outside of any other function. I can't see what you tried in order to make this function global, but besides object-oriented programming, plain functions are always global.

A "non-global" function would mean defining a class and declaring the function inside the class definition; but even then you have to define the function (that is, the actual instructions in the function) outside of any other class or function definition.

# Answer
> 0 votes
Move function `void mornight(char ampm)` outside of function `void Clock(int h = 0, int m = 0, int s = 0, char ch = 'A') {`

as the error message says, function can't be defined inside functions

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


# Question
Title: Interfacing Logitech Joystick to Arduino and interrupt a while loop
I am working on a project of a robot arm. The joints are made of servo motor. The basic function can be describe as:

* The robot arm (the servos) were moved manually by the Logitech joystick.
* The user could press a certain button to remember a position. I made 6 buttons for 6 positions, in detail.
* After the remembering, if an activating button was pressed, the robot arm would move repeatedly around those 6 positions **until a stopping button was pressed**.

The problem was the bold words.

In order to make the robot arm could move repeatedly with one pressing, I used a `while` loop.

However, when the program was in `while` loop, the joystick events stopped updating no matter how I pressed or pulled the joystick. Therefore, I couldn't program a stopping button.

I guessed that was because the joystick events were called outside the loop, but I don't know how to get it inside. My code was based on the example of the USB Host Shield library.

Here is the code. It contained 3 files. My robot also has some more function so I only quote the part that I had problem here.

.ino file:

```
#include <usbhid.h>
#include <hiduniversal.h>
#include <usbhub.h>
#include "le3dp_rptparser.h"
// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#include <SPI.h>
#endif

USB                                             Usb;
USBHub                                          Hub(&Usb);
HIDUniversal                                    Hid(&Usb);
JoystickEvents                                  JoyEvents;
JoystickReportParser                            Joy(&JoyEvents);

//int waist_back, shoulder_back, wrist_back, gripper_back;

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial);
#endif
  Serial.println("Start");

   if (Usb.Init() == -1)
       Serial.println("OSC did not start.");

  delay( 200 );

  if (!Hid.SetReportParser(0, &Joy))
      ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1  );

}

void loop()
{
    Usb.Task();
}

```

.cpp file: This was where I worked. Please look at the `JoystickEvents::OnGamePadChanged`

```
#include "le3dp_rptparser.h"

//Many parameters for robot here

JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
    joyEvents(evt)
{}

void JoystickReportParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
    bool match = true;

    // Checking if there are changes in report since the method was last called
    for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
        if( buf[i] != oldPad[i] ) {
            match = false;
            break;
        }
  }
    // Calling Game Pad event handler
    if (!match && joyEvents) {
        joyEvents->OnGamePadChanged((const GamePadEventData*)buf);

        for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
    }
}

void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
{
  Serial.print("X: ");
  Serial.print(evt->x);
  Serial.print(" Y: ");
  Serial.print(evt->y);
  Serial.print(" Hat Switch: ");
  Serial.print(evt->hat);
  Serial.print(" Twist: ");
  Serial.print(evt->twist);
  Serial.print(" Slider: ");
  Serial.print(evt->slider);
  Serial.print(" Buttons A: ");
  Serial.print(evt->buttons_a);
  Serial.print(" Buttons B: ");
  Serial.print(evt->buttons_b);
  Serial.println("");

  // Manual control program here. I didn't post because it was so long.

  //Activation

  if (evt->buttons_a == 32){
    while (evt->slider == 0){

    //Robot working here, also a long code that was out of limit for a block here.

    Serial.print(evt->slider);
    }
  }
}

```

.h file:

```
#if !defined(__HIDJOYSTICKRPTPARSER_H__)
#define __HIDJOYSTICKRPTPARSER_H__

#include <usbhid.h>

struct GamePadEventData
{
  union { //axes and hut switch
    uint32_t axes;
    struct {
      uint32_t x : 10;
      uint32_t y : 10;
      uint32_t hat : 4;
      uint32_t twist : 8;
    };
  };
  uint8_t buttons_a;
  uint8_t slider;
  uint8_t buttons_b;
};

class JoystickEvents
{
public:
    virtual void OnGamePadChanged(const GamePadEventData *evt);
  static GamePadEventData mostRecentEvent;
};

#define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)

class JoystickReportParser : public HIDReportParser
{
    JoystickEvents      *joyEvents;

  uint8_t oldPad[RPT_GAMEPAD_LEN];

public:
    JoystickReportParser(JoystickEvents *evt);

    virtual void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

#endif // __HIDJOYSTICKRPTPARSER_H__

```

After the `//Activation` under `JoystickEvents::OnGamePadChanged`, no matter how I pulled the slider of the joystick, the event was not updated, the `evt->slider` always returned zero and the robot arm couldn't be stopped.

Is there any method to update the joystick event inside the `while` loop?

Or another method other than `while` loop to make something move repeatedly after pressing one button, and can be stopped with another button?

Thank you so much for reading, and please help me!

# Answer
As full code is not posted I cant suggest you correctly but you should add the two buttons, START & STOP.

When STOP button is pressed all events (your code is performing on) should stop working.

Just make sure when you program for a joystick control, the code for START & STOP buttons should fall under the joystick control loop.

```
if (STOP PRESSED){

}else if(START PRESSED){

    //INVOKE THE FUNCTIONS FOR ACTIONS TO BE PERFORMED
}

```
> 1 votes

# Answer
The trick is to never use a while loop to wait for something physical to happen. Instead write code that doesn't block execution of the rest of the code. Write your code so that instead of sitting in a while loop, the function relies on being called over and over from the loop function. Let the loop function do the looping.
> 0 votes

---
Tags: usb, shields, interrupt, robotics, joystick
---


# Question
Title: Question regarding Servo including Serial monitor display
I tried to make code following your instruction about `mills`, and it looks like this. Unfortunately, it is not working. Is there problem with my code?

Here is my code:

```
#include <LiquidCrystal.h>
#include<Servo.h>

Servo myservo;  // create servo object to control a servo

// These constants won't change. They're used to give names to the pins used:
const int analogInPin1 = A0;  // Analog input pin that the photosensor is attached to
const int analogInPin2 = A1;  // Analog input pin that the photosensor is attached to
const int analogInPin3 = A2;  // Analog input pin that the photosensor is attached to
const int analogInPin4 = A3;  // Analog input pin that the photosensor is attached to
int sensorValue1;
int sensorValue2;
int sensorValue3;
int sensorValue4;
unsigned long m;

//declare counter as an input
int Chactr =0;
int Disctr =0;

byte state;

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

void setup() {
  myservo.attach(9);  // attaches the servo on pin 9 to the servo object
  myservo.write(0);  // back to 0 degrees.
  delay(1000); // wait for a second.
  pinMode(13, OUTPUT); // initialize digital pin 13 as an output.
  Serial.begin(9600);  // initialize serial communications at 9600 bps:
  lcd.begin(16,2);

  delay(5000);
}

void loop() {

  // read the analog in value:
  sensorValue1 = analogRead(analogInPin1);
  sensorValue2 = analogRead(analogInPin2);
  sensorValue3 = analogRead(analogInPin3);
  sensorValue4 = analogRead(analogInPin4);

  delay(3000);

  // print the results to the Serial Monitor:
  Serial.print("sensor1 = ");
  Serial.print(sensorValue1);
  Serial.print("\n");

  Serial.print("sensor2 = ");
  Serial.print(sensorValue2);
  Serial.print("\n");

  Serial.print("sensor3 = ");
  Serial.print(sensorValue3);
  Serial.print("\n");

  Serial.print("sensor4 = ");
  Serial.print(sensorValue4);
  Serial.print("\n");

  Serial.print("Led State:  ");
  Serial.println(state);
  Serial.print("\n");

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250)
  {
    m=(millis()+60000);
  }

  if(sensorValue1 <=568 && sensorValue2 <=519 &&sensorValue3 <=418 && sensorValue4 <=249)
  {
    m=0;
  }

  if (sensorValue1 >=569 && sensorValue2 >=520 && sensorValue3 >=419 && sensorValue4 >=250 && m==millis())
  {
    state=1;
    delay(5000);
    digitalWrite(13, LOW); // turn the LED off by making the voltage LOW
    delay(5000); // wait for a second

    myservo.attach (9);
    myservo.write(30);
    delay(3000);
    myservo.write(0);
    delay(3000);

    myservo.detach ();
    delay (1000);

    Disctr = Disctr + 1;

    delay(900);

    Serial.print("Battery Full: Discharge ON");
    Serial.print("\n");
  }
  else if (sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4 ==0 )
  {
    m=(millis()+60000);
  }

  if(sensorValue1 >=1 && sensorValue2 >=1 && sensorValue3 >=1 && sensorValue4 >=1)
  {
    m=0;
  }

  if(sensorValue1 ==0 && sensorValue2 ==0 && sensorValue3 ==0 && sensorValue4  ==0 && m==millis())
  {
    state=0;
    delay(5000);
    digitalWrite(13, HIGH ); // turn the LED On by making the voltage high
    delay(5000); // wait for a second

    Chactr = Chactr + 1;
    delay(900);

    Serial.print("Battery Empty: Charging ON");
    Serial.print("\n");
  }
  {
    lcd.setCursor(0,0);
    lcd.print("Charge Cycle: ");

    lcd.setCursor(13,0);
    lcd.print(Chactr);

    lcd.setCursor(0,1);
    lcd.print("Discha Cycle: ");

    lcd.setCursor(13,1);
    lcd.print(Disctr);

    delay(1000);
  }
}

```

# Answer
> -1 votes
So what you want to do is be able to activate the servo when 4 green bars appear over the course of one minute correct?

I think you would need to create three if statements and one new variable. The first if statement will be, if it detects four green bar, then `m=(millis() + 60000)`. Then you will need to nest another if statement in here to say if it detects ONLY three bar, then `m = 0`. Your third if the statement is if it detects the four green bars AND `m == millis()` then the servo will activate.

This is how I would do it, but I am not very experienced. I'm pretty sure others will have a cleaner and simpler code but this should work.

---
Tags: lcd, servo
---


# Question
Title: Getting FFT arduino code to run over 9+ hours, utilizing micros()
I am a beginner in Arduino, coding, and electrical engineering (learning on my own time) and am working on creating an EEG. I've got the hardware down and have managed to get numerical data output from the analog (A0) of Arduino. The next step is transforming these numbers to outputting dominant frequency and I have managed to find a code that uses FFT to find the dominant frequency from the input of A0. The following is the code:

```
#include "arduinoFFT.h"

#define SAMPLES 128             //Must be a power of 2
#define SAMPLING_FREQUENCY 1000 //Hz, must be less than 10000 due to ADC

arduinoFFT FFT = arduinoFFT();

unsigned int sampling_period_us;
unsigned long microseconds;

double vReal[SAMPLES];
double vImag[SAMPLES];

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

sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));
}

void loop() {

/*SAMPLING*/
for(int i=0; i<SAMPLES; i++)
{
    microseconds = micros();    //Overflows after around 70 minutes!

    vReal[i] = analogRead(0);
    vImag[i] = 0;

    while(micros() < (microseconds + sampling_period_us)){
    }
}

/*FFT*/
FFT.Windowing(vReal, SAMPLES, FFT_WIN_TYP_HAMMING, FFT_FORWARD);
FFT.Compute(vReal, vImag, SAMPLES, FFT_FORWARD);
FFT.ComplexToMagnitude(vReal, vImag, SAMPLES);
double peak = FFT.MajorPeak(vReal, SAMPLES, SAMPLING_FREQUENCY);

/*PRINT RESULTS*/
Serial.println(peak);     //Print out what frequency is the most dominant.

for(int i=0; i<(SAMPLES/2); i++)
{
    /*View all these three lines in serial terminal to see which frequencies has which amplitudes*/

    //Serial.print((i * 1.0 * SAMPLING_FREQUENCY) / SAMPLES, 1);
    //Serial.print(" ");
    //Serial.println(vReal[i], 1);    //View only this line in serial plotter to visualize the bins
}

delay(1000);  //Repeat the process every second OR:
//while(1);       //Run code once

```

}

The problem I have is with the line microseconds = micros(). The comment state that this will overflow after 70 minutes and after some days of research, I sorta understand what is meant by this. However, I need this program to run over 9 hours, so I can log the dominant frequency of the brainwave throughout the night. Is that possible?

# Answer
Chris Do, there is indeed a rollover problem when `micros` is used that way. When that happens, the samples are taken at full speed without interval. That will create bad data for the FFT.
The solution is in the Blink Without Delay example. The magic to avoid a rollover problem is the substraction with two `unsigned long` values.

The arduinoFFT library is in the Library Manager of the Arduino IDE.
The example "FFT\_03.ino" uses `micros` in the wrong way.

The next sketch shows how to avoid the rollover problem:

```
// Use micros() without rollover problem for a fixed sample rate
// for a certain amount of samples.

#define SAMPLES 128

unsigned long previousMicros;
const unsigned long intervalMicros = 1000UL;   // 1000 Hz is 1000 us

float vReal[SAMPLES];
float vImag[SAMPLES];

void setup() {
}

void loop() {

  previousMicros = micros();  // set the previousMicros just before entering the for-statement
  for(int i=0; i<SAMPLES; i++) {

    // A while-statement to wait.
    // Note that the ';' at the end means 'do nothing'.
    while( micros() - previousMicros < intervalMicros);

    // The 'previousMicros' is increased with a fixed number, for a fixed sample rate.
    previousMicros += intervalMicros;  // for next interval

    vReal[i] = float(analogRead(0));
    vImag[i] = 0.0;
  }

  delay(1000);
}

```

Take the current value of `micros` and substract the previous value of micros. The result of that substraction is a valid number, even during a rollover. It is the only way that always works.

The line to calculate the sample period has too many things in it that can go wrong. These lines:

```
unsigned int sampling_period_us;
sampling_period_us = round(1000000*(1.0/SAMPLING_FREQUENCY));

```

In my example, I set the `intervalMicros` to a certain number. Could you do that as well? When everything works, you can try to calculate it.

Added: The answer by Edgar Bonet is exactly the same. That is no surprise because there is no other way.
> 3 votes

# Answer
As long as you never compare timestamps, the rollover is not an issue. The idiom you used:

```
while (micros() < previous_timestamp + period) ...

```

is comparing two timestamps. This is incorrect, and it fails whenever `micros()` rolls over. However, subtracting timestamps to get a duration does work fine across rollover events. And comparing durations does always work. So the correct idiom is:

```
while (micros() - previous_timestamp < period) ...

```

Note also that the way you update `microseconds` is incorrect. You are incrementing it by the period you want **plus** the time taken by the CPU to execute some of the code in the loop. You should instead increment it by the requested period and no more. Here is my take at what you are trying to accomplish:

```
/* SAMPLING */
microseconds = micros();  // record initial time
for (int i = 0; i < SAMPLES; i++) {
    while (micros() - microseconds < sampling_period_us)
        ;  // wait for the right time to take the sample
    microseconds += sampling_period_us;  // update as per the period
    vReal[i] = analogRead(0);
    vImag[i] = 0;
}

```
> 2 votes

---
Tags: arduino-uno, programming, timers, time
---


title: Powering arduino and node mcu

text:
# Question
Title: Powering arduino and node mcu
I want to power up my Arduino and my Nodemcu via 12 V , 1 A power adapter (it's an AC to DC power Adapter).

Recently I have two voltages regulators: a 5 V for nodemcu and 9 V for Arduino Uno.

The question is does the 1A affect both boards or not?

# Answer
> 2 votes
In principle not. However, the voltage regulators may become quite hot, since you are going down from 12 V to 9 V and 5 V (especially the step from 9 V to 5 V is quite a lot). It depends on the current (in (milli)Amps) how hot they get.

For the adapter it does not matter, if it is 1 A or 10 A, the microcontrollers will only take whatever they need. Only if the adapter can deliver less than needed by both microcontrollers there is a problem.

The voltage regulators are not of switching type I guess, so they will use the same amount of amperes. Assuming the Arduino Uno takes 300 mA (at 5 V) and the NodeMCU 200 mA (at 12 V), you can add them together: 200 mA + 300 mA = 500 mA. Since this is less than 1 A the adapter can deliver, you are ok.

---
Tags: arduino-uno, power, nodemcu, current, voltage
---


# Question
Title: Switch two or more digital outputs of ESP8266 at the same time
I'd like to control some digital ICs with a ESP8266-12.

1. How can I switch 2 pins to HIGH in the same moment?
2. How can I switch one to LOW and the other to HIGH in the same moment?
3. Is it possible with every port or only with grouped ports and how are the groups?

# Answer
See the datasheet: esp8266-technical\_reference\_en

Paragraph 2.2.2 shows how to use the output registers.

With the registers GPIO\_OUT, GPIO\_OUT\_W1TS and GPIO\_OUT\_W1TC you can set or clear multiple GPIOs.
> 1 votes

---
Tags: esp8266, pins, port-mapping
---


# Question
Title: send more than one byte at a time SPI Arduino
I have recently been trying to send integers via SPI between two arduino Uno's. I am using the first example of Nick Gammons tutorial, and trying to modify it to get a basic understanding of how to communicate via SPI.

http://www.gammon.com.au/spi

MASTER

```
// Written by Nick Gammon
// February 2011

#include <SPI.h>

void setup (void)
{

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

}  // end of setup

void loop (void)
{

  char c;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (const char * p = "Hello, world!\n" ; c = *p; p++)
    SPI.transfer (c);

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

```

SLAVE - WITHOUT INTERRUPTS

```
// Written by Nick Gammon
// February 2011

#include <SPI.h>

char buf [100];
volatile byte pos;
volatile boolean process_it;

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

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < (sizeof (buf) - 1))
    buf [pos++] = c;

  // example: newline means time to process buffer
  if (c == '\n')
    process_it = true;

}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf);
    pos = 0;
    process_it = false;
    }  // end of flag set

}  // end of loop

```

SLAVE - WITH INTERRUPTS

```
// Written by Nick Gammon
// April 2011

// what to do with incoming data
byte command = 0;

// start of transaction, no command yet
void ss_falling ()
{
  command = 0;
}  // end of interrupt service routine (ISR) ss_falling

void setup (void)
{

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  // interrupt for SS falling edge
  attachInterrupt (0, ss_falling, FALLING);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;

  switch (command)
  {
  // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  // add to incoming byte, return result
  case 'a':
    SPDR = c + 15;  // add 15
    break;

  // subtract from incoming byte, return result
  case 's':
    SPDR = c - 8;  // subtract 8
    break;

  } // end of switch

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{
// all done with interrupts
}  // end of loop

```

ORIGINAL ISSUE - I am able to get this working, so the wiring is correct, however i am unable to get it to send anything other than a string. I can change the string and that works, but i am getting confused with pointers in C. Any code i have tried doesn't compile correctly, or doesn't send at all if it does compile. Could someone give me a clue as to where to start with this. My best effort is below

MASTER

```
#include <SPI.h>

int x = 10000;
int y = 20000;
int z = 30000;
byte High_x = highByte(x);
byte Low_x = lowByte(x);
byte High_y = highByte(y);
byte Low_y = lowByte(y);
byte High_z = highByte(z);
byte Low_z = lowByte(z);

int X =  word(High_x<<8|Low_x);
int Y =  word(High_y<<8|Low_y);
int Z =  word(High_z<<8|Low_z);

  byte myArray[7];

void setup (void)
{

  Serial.begin(115200);
  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

 myArray[0] = High_x;
 myArray[1] = Low_x;
 myArray[2] = High_y;
 myArray[3] = Low_y;
 myArray[4] = High_z;
 myArray[5] = Low_z;
 myArray[6] = 0;

  Serial.println(X);
  Serial.println(Y);
  Serial.println(Z);
  delay(2000);
}

void loop (void)
{

  byte data;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (byte * p =  myArray[0]; data = *p; p++)
    SPI.transfer (data);
    Serial.println("sending data");

  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

```

SLAVE

```
#include <SPI.h>

byte buf [100];
volatile byte pos;
volatile boolean process_it;

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

  // turn on SPI in slave mode
  SPCR |= bit (SPE);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // get ready for an interrupt
  pos = 0;   // buffer empty
  process_it = false;

  // now turn on interrupts
  SPI.attachInterrupt();
Serial.println("End of Setup");
}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  Serial.println("Beginning of Interrupt Routine");
byte data = SPDR;  // grab byte from SPI Data Register

  // add to buffer if room
  if (pos < (sizeof (buf) - 1))
    buf [pos++] = data;

  // example: newline means time to process buffer
  if (data == '0')
    process_it = true;
      Serial.println("End of Interrupt Routine");
}  // end of interrupt routine SPI_STC_vect

// main loop - wait for flag set in interrupt routine
void loop (void)
{
    Serial.println("Beggining of Loop");

  for(int i = 0; i < 100; i++)
  if (process_it)
    {
    buf [pos] = 0;
    Serial.println (buf[i]);
    pos = 0;
    process_it = false;
    }  // end of flag set
    Serial.println("End of Loop");
}  // end of loop

```

In the future i hope to send 10 16-bit integers over SPI from an arduino to an arduino or maybe arduino to a raspberry Pi.

Thanks

EDIT -I have started using the code that uses interrupts and managed to get the data i need sent across, however, i can only get the correct data by setting both the first and second element of the array to "High\_x", otherwise it skips the first part of data?

NEW MASTER

```
#include <SPI.h>

int x = 10000;
int y = 20000;
int z = 30000;
byte High_x = highByte(x);
byte Low_x = lowByte(x);
byte High_y = highByte(y);
byte Low_y = lowByte(y);
byte High_z = highByte(z);
byte Low_z = lowByte(z);

int X =  word(High_x<<8|Low_x);
int Y =  word(High_y<<8|Low_y);
int Z =  word(High_z<<8|Low_z);

  byte myArray[8];

void setup (void)
{

  digitalWrite(SS, HIGH);  // ensure SS stays high for now

  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();

  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);

 myArray[0] = High_x;
 myArray[1] = High_x;
 myArray[2] = Low_x;
 myArray[3] = High_y;
 myArray[4] = Low_y;
 myArray[5] = High_z;
 myArray[6] = Low_z;
 myArray[7] = 0;

  Serial.print("wait for loop");
  //Serial.println(X);
  //Serial.println(Y);
  //Serial.println(Z);
  delay(2000);
}

void loop (void)
{

  byte data;

  // enable Slave Select
  digitalWrite(SS, LOW);    // SS is pin 10

  // send test string
  for (byte * p =  &myArray[0]; data = *p; p++){
    SPI.transfer (data);
  }
  // disable Slave Select
  digitalWrite(SS, HIGH);

  delay (1000);  // 1 seconds delay
}  // end of loop

```

NEW SLAVE

```
byte buf [100];
volatile byte pos;
// what to do with incoming data
byte command = 0;

// start of transaction, no command yet
void ss_falling ()
{
  command = 0;
}  // end of interrupt service routine (ISR) ss_falling

void setup (void)
{

  Serial.begin(9600);

  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);

  // turn on SPI in slave mode
  SPCR |= _BV(SPE);

  // turn on interrupts
  SPCR |= _BV(SPIE);

  // interrupt for SS falling edge
  attachInterrupt (0, ss_falling, FALLING);

}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte data = SPDR;

  // add to buffer if room
  if (pos < (sizeof (buf) - 1))
    buf [pos++] = data;

}  // end of interrupt service routine (ISR) SPI_STC_vect

void loop (void)
{

  for(int i = 0; i < 100; i++){

    Serial.println (buf[i]);
    pos = 0;
    delay(1000);
  }
}  // end of loop

```

Any suggestions on why this is necessary? Is there some basic SPI idiosyncrasy I'm missing?

Thanks all

Ross

# Answer
> 2 votes
You have a couple of issues going on here.

First of all, Nick Gammon's example is transmitting strings. Strings have the property that a particular value, `'\0'` (null), cannot normally appear in the string itself, and it can therefore be used as an "end flag" to mark the end of the string. This is why the `for` loop on the master side works correctly.

Note that the null itself is NOT transmitted over the SPI link. Instead, Nick shows an example of using another character (`'\n'` \- newline) to trigger processing on the slave side.

If you want to transmit binary data, which could easily contain bytes of 0x00 (null), you need to find a different way to delimit the data on both the sending side and the receiving side. Your example data (16-bit integers of 10000, 20000 and 30000) doesn't contain any null bytes, but you can't rely on that in general. Also, because the null doesn't actually get transmitted, you can't use it on the receiving side to trigger processing.

There are a couple of approaches that are frequently used to send binary data:

* Send the number of bytes explicitly at the beginning of the transaction, and trigger receive-side processing once that number of bytes has been received.
* Use a "special" value (e.g., null) to mark the end of the data, but then you have to "escape" that value in some way if it ever appears in the actual data.

---

In addition to all of that, you have a bug on your master side code. The initialization of your `for` loop, `byte * p = myArray[0]` does not set the pointer `p` to the address of `myArray` as intended; instead, it sets it to the value of the first byte in the array, which is 0x27 (`High_x`). You need to say either `byte * p = &myArray[0]` or simply `byte * p = myArray`.

# Answer
> 3 votes
I can see two big problems at your code (there could be more, but i didnt look that hard).

First is using Serial.println in interrupt routine. This prevent receiving of more than one byte as Serial.println will take much more time to execute than receiving 6 bytes (even on slow SPI clock) on SPI. In most cases Interrupt routines should finish fast.

Next problem is that you are testing for char 0 ('0') which is not equal to byte 0 you are sending as end of data, but has value of 48 in decimal.

Edit for how to test for end of data:

You can test for end of that few different ways, having fixed number of byte transfers, setting interrupt on slave select pin or encode data binary data in base64 and use control char. I would recommend interrupt.

---
Tags: spi, communication
---


# Question
Title: Using WifiUdp.h on Arduino Mega and ESP8266?
I was trying to run this library on Arduino Mega, using ESP8266 as replacement of Wifi Shield, as suggested on my older thread.

The problem is, I got error in compiling, after with this code :

```
#include <WiFiEsp.h>
#include <WiFiEspClient.h>
#include <WiFiEspUdp.h>

#include "AppleMidi.h"
APPLEMIDI_CREATE_INSTANCE(WiFiUDP, appleMIDI1);
....

```

> exit status 1
>
> 'WiFiUDP' was not declared in this scope

if I modified the code into this :

```
#include <WiFiEsp.h>
#include <WiFiUdp.h>

#include "AppleMidi.h"
APPLEMIDI_CREATE_INSTANCE(WiFiUDP, appleMIDI1);
....

```

I got this error instead

> C:\Program Files (x86)\Arduino\libraries\WiFi\src\utility\server\_drv.cpp:313:40: error: 'WARN' was not declared in this scope
>
> ```
> WARN("error waitResponse isDataSent");
>
>                                     ^
>
> ```
>
> exit status 1

Full code here at pastebin. I was pretty much stuck now. Please help! :(

Thanks :D

# Answer
the WiFiEsp class for UDP is `WiFiEspUDP`

```
#include <WiFiEsp.h>
#include <WiFiEspUdp.h>
#include "AppleMidi.h"

APPLEMIDI_CREATE_INSTANCE(WiFiEspUDP, AppleMIDI);

```
> 2 votes

---
Tags: esp8266
---


# Question
Title: Wemos D1R2 - Onewire 2 DS18B20 passing to variable
I'm a beginer, did some tests with Uno and now have a Wemos D1R2 on my hands... I'm building a sort of weather station that will send data to thingspeak.com and log this data there. I managed to merge 2 examples together (1 to send data to thingspeak) and (1 to read 1 DS18B20 with onewire) I now need to connect 2 or more DS18B20 sensors on the same Onewire BUS (I also managed to do this using this tutorial http://arduino-info.wikispaces.com/Brick-Temperature-DS18B20#mult ), the readings come alright on serial monitor but when I try to send the readings to thingspeak a get a error:

> temp\_logger\_multime\_sensors\_2:174: error: statement cannot resolve address of overloaded function

Serial.print printTemperature(Probe01);

My piece of code:

```
/* References
    DHT11 sensor data to Thingspeak using a Wemos D1
    http://www.esp8266learning.com/dht11-sensor-data-to-thingspeak-using-a-wemos-d1.php#codesyntax_3

   Rui Santos - Complete project details at http://randomnerdtutorials.com

   YourDuino Multiple DS18B20 Temperature Sensors on 1 wire
   http://arduino-info.wikispaces.com/Brick-Temperature-DS18B20#mult
   V1.01  01/17/2013 ...based on examples from Rik Kretzinger
*/

#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// replace with your channel’s thingspeak API key and your SSID and password
String apiKey = "THINGSPEAKKEY";
const char* ssid = "WIFINAME";
const char* password = "WIFIPASSWORD";
const char* server = "api.thingspeak.com";

/*-----( Declare Constants and Pin Numbers )-----*/
#define ONE_WIRE_BUS_PIN 5

/*-----( Declare objects )-----*/
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS_PIN);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

DeviceAddress Probe01 = { 0x28, 0xFF, 0x51, 0xA5, 0x61, 0x16, 0x03, 0x92 }; // probe 1
DeviceAddress Probe02 = { 0x28, 0xFF, 0xF8, 0x99, 0x52, 0x16, 0x04, 0xB1 }; // probe 2

WiFiClient client;

void setup()   /****** SETUP: RUNS ONCE ******/
{
  // start serial port to show results
    Serial.begin(115200);
  delay(10);

/*  Serial.begin(9600);
  Serial.print("Initializing Temperature Control Library Version ");
  Serial.println(DALLASTEMPLIBVERSION);
  */
  // Initialize the Temperature measurement library
  sensors.begin();

 WiFi.begin(ssid, password);

  // Connecting to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected on IP ...");
  // Printing the ESP IP address
  Serial.println(WiFi.localIP());
}

/*-----( Declare User-written Functions )-----*/
  void printTemperature(DeviceAddress deviceAddress)
  {
  float tempC = sensors.getTempC(deviceAddress);
     if (tempC == -127.00)
     {
     Serial.print("Error getting temperature  ");
     }
     else
     {
     Serial.print(tempC);
     }
  }// End printTemperature

void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
  delay(1000);
  Serial.println();
  Serial.print("Number of Devices found on bus = ");
  Serial.println(sensors.getDeviceCount());
  Serial.print("Getting temperatures... ");
  Serial.println();

  // Command all devices on bus to read temperature

  sensors.requestTemperatures();

float StrProbe01 = printTemperature(Probe01); //THINK PROBLEM IS HERE
float StrProbe02 = printTemperature(Probe02); //AND HERE

  Serial.print("Probe 01 temperature is:   ");
    printTemperature(Probe01);  //<-- THIS PART WORKS
  Serial.println();

  Serial.print("Probe 02 temperature is:   ");
    printTemperature(Probe02);

  Serial.println();

if (client.connect(server,80)) {
  String postStr = apiKey;
  postStr +="&field1=";
  postStr += float(StrProbe01);
  postStr +="&field2=";
   postStr += float(StrProbe02);
  postStr += "\r\n\r\n";

  client.print("POST /update HTTP/1.1\n");
  client.print("Host: api.thingspeak.com\n");
  client.print("Connection: close\n");
  client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
  client.print("Content-Type: application/x-www-form-urlencoded\n");
  client.print("Content-Length: ");
  client.print(postStr.length());
  client.print("\n\n");
  client.print(postStr);

  Serial.print("Temperature: ");
  Serial.print printTemperature(Probe01);
  Serial.print(" degrees Celsius Humidity: ");
  Serial.print printTemperature(Probe02);
  Serial.println("Sending data to Thingspeak");
  }
  client.stop();

  Serial.println("Waiting 20 secs");
  // thingspeak needs at least a 15 sec delay be een updates
  // 20 seconds to be safe
  delay(20000);

}//--(end main loop )---

```

I suspect I have to transform `printTemperature(Probe01);` into a variable first (as you can see on the code) and use this variable on `postStr += StrProbe01;` as but I tried as you can see on the code and it didnt work either.

*** UPDATE *** The code below works sending data to thingspeak and serial monitor fine with 1 DS18B20

```
#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// replace with your channel’s thingspeak API key and your SSID and password
String apiKey = "THINGSPEAKKEY";
const char* ssid = "WIFINAME";
const char* password = "WIFIPASSWORD";
const char* server = "api.thingspeak.com";

const char* t2 = "5";
const char* h2 = "12.34";

//START DS18B20 Stuff
// Data wire is plugged into pin D1 on the ESP8266 12-E - GPIO 5
#define ONE_WIRE_BUS 5  // DS18B20 pin

// Setup a oneWire instance to communicate with any OneWire devices (not just Maxim/Dallas temperature ICs)
OneWire oneWire(ONE_WIRE_BUS);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature DS18B20(&oneWire);
char temperatureCString[6];
char temperatureFString[6];

//END DS18B20 stuff

WiFiClient client;

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

// dht.begin();
DS18B20.begin(); // IC Default 9 bit. If you have troubles consider upping it 12. Ups the delay giving the IC more time to process the temperature measurement

WiFi.begin(ssid, password);

// Connecting to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected on IP ...");
// Printing the ESP IP address
Serial.println(WiFi.localIP());
}

void getTemperature() {
  float tempC;
  float tempF;
  do {
    DS18B20.requestTemperatures();
    tempC = DS18B20.getTempCByIndex(0);
    dtostrf(tempC, 2, 2, temperatureCString);
    tempF = DS18B20.getTempFByIndex(0);
    dtostrf(tempF, 3, 2, temperatureFString);
    delay(100);
  } while (tempC == 85.0 || tempC == (-127.0));
}

// runs over and over again
void loop()
{

 getTemperature();

if (client.connect(server,80)) {
String postStr = apiKey;
postStr +="&field1=";
postStr += String(temperatureCString);
postStr +="&field2=";
postStr += String(temperatureFString);
postStr += "\r\n\r\n";

client.print("POST /update HTTP/1.1\n");
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n");
client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
client.print("Content-Type: application/x-www-form-urlencoded\n");
client.print("Content-Length: ");
client.print(postStr.length());
client.print("\n\n");
client.print(postStr);

Serial.print("Temp in C: ");
Serial.print(temperatureCString);
Serial.print(" and Temp in F: ");
Serial.print(temperatureFString);
Serial.println("Sending data to Thingspeak");
}
client.stop();

Serial.println("Waiting 20 secs");
// thingspeak needs at least a 15 sec delay be een updates
// 20 seconds to be safe
delay(20000);
}

```

And this code works fine displaying 2 DS18B20 on serial monitor connected to 1 Onewire BUS, but I need to implement (uncomment) the thingspeak part now.

```
#include <ESP8266WiFi.h>
#include <OneWire.h>
#include <DallasTemperature.h>

// replace with your channel’s thingspeak API key and your SSID and password
String apiKey = "THINGSPEAKKEY";
const char* ssid = "WIFINAME";
const char* password = "WIFIPASSWORD";
const char* server = "api.thingspeak.com";

/*-----( Declare Constants and Pin Numbers )-----*/
#define ONE_WIRE_BUS_PIN 5

/*-----( Declare objects )-----*/
// Setup a oneWire instance to communicate with any OneWire devices
OneWire oneWire(ONE_WIRE_BUS_PIN);

// Pass our oneWire reference to Dallas Temperature.
DallasTemperature sensors(&oneWire);

DeviceAddress Probe01 = { 0x28, 0xFF, 0x51, 0xA5, 0x61, 0x16, 0x03, 0x92 }; // probe 1
DeviceAddress Probe02 = { 0x28, 0xFF, 0xF8, 0x99, 0x52, 0x16, 0x04, 0xB1 }; // probe 2

WiFiClient client;

void setup()   /****** SETUP: RUNS ONCE ******/
{
  // start serial port to show results
    Serial.begin(115200);
  delay(10);

  // Initialize the Temperature measurement library
  sensors.begin();

 WiFi.begin(ssid, password);

  // Connecting to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected on IP ...");
  // Printing the ESP IP address
  Serial.println(WiFi.localIP());

}  //--(end setup )---

/*-----( Declare User-written Functions )-----*/
  void printTemp(DeviceAddress deviceAddress)
  {
  float tempC = sensors.getTempC(deviceAddress);
     if (tempC == -127.00)
     {
     Serial.print("Error getting temperature  ");
     }
     else
     {
     Serial.print(tempC);
     }
  }// End printTemp

void loop()   /****** LOOP: RUNS CONSTANTLY ******/
{
  delay(1000);
  Serial.println();
  Serial.print("Number of Devices found on bus = ");
  Serial.println(sensors.getDeviceCount());
  Serial.print("Getting temperatures... ");
  Serial.println();

  // Command all devices on bus to read temperature

  sensors.requestTemperatures();

  Serial.print("Probe 01 temperature is:   ");
    printTemp(Probe01);
  Serial.println();

  Serial.print("Probe 02 temperature is:   ");
    printTemp(Probe02);

  Serial.println();

/*
if (client.connect(server,80)) {
  String postStr = apiKey;
  postStr +="&field1=";
  postStr += float(StrProbe01);
  postStr +="&field2=";
   postStr += float(StrProbe02);
  postStr += "\r\n\r\n";

  client.print("POST /update HTTP/1.1\n");
  client.print("Host: api.thingspeak.com\n");
  client.print("Connection: close\n");
  client.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
  client.print("Content-Type: application/x-www-form-urlencoded\n");
  client.print("Content-Length: ");
  client.print(postStr.length());
  client.print("\n\n");
  client.print(postStr);

  Serial.print("Temperature: ");
  Serial.print printTemp(Probe01);
  Serial.print(" degrees Celsius Humidity: ");
  Serial.print printTemp(Probe02);
  Serial.println("Sending data to Thingspeak");
  }
  client.stop();

  Serial.println("Waiting 20 secs");
  // thingspeak needs at least a 15 sec delay be een updates
  // 20 seconds to be safe
  delay(20000);
 */
}//--(end main loop )---

```

It has all to do on generate a sort of variable (perhaps float , im not sure) and passing it as a http string

Thanks

# Answer
In the code that works, you have:

```
if (client.connect(server,80)) {
String postStr = apiKey;
postStr +="&field1=";
postStr += String(temperatureCString);
postStr +="&field2=";
postStr += String(temperatureFString);
postStr += "\r\n\r\n";

```

In the code that does not work you are doing this:

```
if (client.connect(server,80)) {
  String postStr = apiKey;
  postStr +="&field1=";
  postStr += float(StrProbe01);
  postStr +="&field2=";
   postStr += float(StrProbe02);
  postStr += "\r\n\r\n";

```

Print out the both the Strings that you are sending, postStr, using Serial.print. Compare the result. I'm not at home at the moment to try it out, but I'm sure the float(StrProbe01) and float(StrProbe02) is wrong. Thingspeak explains in their guidelines what the string that you are sending should look like.
> 1 votes

# Answer
Since the DeviceInformation variables are not POD (Plain Old Data) it would be slightly more efficient to use references or pointers, this will avoid copying them around. If you do that you could make you global variables Probe01 and Probe02 const variables.

In loop around line 98 you call printTemperature() and assign the return value to a float. Which is very strange, because around line 72 you define `void printTemperature()`. So I suspect there may be a function in the Dalas library call printTemperature that returns a float and this is the overloaded function it is talking about.

So to fix it change the name of you printTemperature function and change the two lines it is called on. Hopefully that will fix this problem.
> 0 votes

# Answer
Re your edit : I'd create a new project and put just the commented out code in setup (and the minimum you need to get it working) and then post the problems you have with that.

I can't see any compile problems, but the data you are sending to thingspeak doesn't look right. I think you are sending:

```
String postStr = apiKey + "&field1=" + float(StrProbe01) + "&field2=" + float(StrProbe02) + "\r\n\r\n";

```

And I think you should be sending:

```
String postStr = "field1=" + float(StrProbe01) + "&field2=" + float(StrProbe02) + "\r\n\r\n";

```

(Based on this example Arduino.cc)
> 0 votes

# Answer
Try returning float from printTemp:

```
 /*-----( Declare User-written Functions )-----*/
  float printTemp(DeviceAddress deviceAddress)
  {
  float tempC = sensors.getTempC(deviceAddress);
     if (tempC == -127.00)
     {
     Serial.print("Error getting temperature  ");
     }
     /* else
     {
     Serial.print(tempC);
     }
     */ you won't be needing this
     return tempC;
  }// End printTemp

```

And call it as you would in your commented example. I suspect that it is not the most efficient way, but it should work.
> 0 votes

---
Tags: arduino-ide, esp8266, variables, ds18b20
---


# Question
Title: Using delay(1000); without influence on analogWrite?
So, I'm trying to read the voltage on analog pin A0 and make a "regulation", where if the voltage will be lower than 2.5V (analog value 512), then it should be output pin 9 used as PWM with duty cycle of 50% ( analogWrite(ledPin, 128); ) unless the voltage rises again higher than 2.5V.

Where/how am I supposed to use mentioned line ( analogWrite(ledPin, 128); in IF sentence, so it will be used continuous untill it is reached the limit?

PS: I just want to refresh LCD with frequency of 1 Hz while PWM works independently of delay(1000). How is that even possible?

How am I able to do that?

```
#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

const int numRows = 2;
const int numCols = 16;

void setup() {
  lcd.begin(numCols, numRows);
}

void loop() {

    int sensorValue = analogRead(A0);
    float voltage = sensorValue * (5.0 / 1023.0);
        lcd.setCursor(0, 0);
        lcd.write(voltage);

        delay(1000);
}

```

# Answer
> 2 votes
The PWM started by `analogWrite` will not be influenced be the `delay`, because the analogWrite function only sets the registers and starts the PWM. The PWM generator is independent from the CPU on AVR microcontrollers. On esp8266 for example the PWM is generated with use of interrupt and it is too not influenced by the `delay` function. To stop the PWM you must call analogWrite with 0 or change the pin mode.

# Answer
> 0 votes
You don't need an if-statement here. You can simply contineously take the measurements and act accordingly.

About the `delay(1000)`:

It is considered a bad coding practice to use `delay()`, especially for longer periods, because it's just busy waiting. In real life you wouldn't just sit fiddling your thumbs, until a task is done. You would do something else in the intermediate time. Here you can reach this by using non-blocking code like in the `BlinkWithoutDelay` example of the Arduino IDE.

About PWM:

PWM is not handled by the software, but by the hardware. The Atmega on the Arduino has dedicated PWM hardware included in the package, which will handle the control of the PWM pin, so that the CPU can do other things.

# Answer
> 0 votes
I think you need something like this, with a flag so you are not contantly restarting the PWM on pin 8 and making the output erratic:

```
void loop(){
if (analogRead(A0)<512  && halfLevel9 == 0){
analogWrite (9, 128);
halfLevel9 = 1; // flag to let you know it's been set
}
else {
analogWrite (9, withWhat?);
halfLevel9 = 0;
}
// use blink without delay to determine if 1 second has passed
{
// write whatever is going to the LCD
}
// do other stuff while the 1 second passes
}

```

---
Tags: lcd, pwm
---


# Question
Title: Using two sensors with delay concurrently
I want to use an ultra-sonic sensor and the led concurrently. I want the led to blink every 0.2 seconds and the ultra-sonic to measure distance without regard to the blinking.

The problem is I have the following code for blinking:

> ```
> digitalWrite(13, HIGH);
> delay(1000);
> digitalWrite(13, LOW);
> delay(200);
>
> ```

which makes the ultra-sonic sensor to be delayed as well, but I want it to keep measuring distance. Any tips?

# Answer
> 1 votes
There is a non-blocking library that works similar to `delay()` Virtual Delay. This sketch turns your Uno's built-in LED ON for 1 second, then OFF for 200ms, repeatedly.

```
#include <Arduino.h>
#include "avdweb_VirtualDelay.h"

VirtualDelay delay1, delay2;

void setup(){

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

}

void loop(){

  // This sequence has a deadlock.
  if(delay1.elapsed()){
    digitalWrite(LED_BUILTIN, LOW);
    delay2.start(200);
  }

  if(delay2.elapsed()){
    digitalWrite(LED_BUILTIN, HIGH);
    delay1.start(1000);
  }

  // This breaks the deadlock. You can start with any
  // delay object you want e.g. delay2.start(0);
  DO_ONCE(delay1.start(0));

  // Your code here.

}

```

The library's author has an excellent tutorial on their website: avdweb Virtual Delay timer for Arduino.

# Answer
> 0 votes
You could try to use millis(). It is a timer that measures how long your program has been running. With some math, you could use millis to let your LED blink without delaying the ultra sonic sensor.

---
Tags: arduino-uno, sensors, led
---


# Question
Title: Battery voltage monitor right after deep sleep
i have my esp32 module in deep sleep and i use it with a couple of buttons using a wake up that detect the button pressed now i'd like to have a battery level to send to a server right before going back to deep sleep. How can i do it? and what cheap rgb led do you suggest using?

# Answer
> 1 votes
Using "battery level" (voltage) is poor way to monitor its useful life. Battery discharge characteristic varies with its technology. On the other hand many electronics devices are very tolerable as far as "supply level " AKA voltage.

RGB LED light intensity can be made to monitor different voltage, however, I fail to see how you propose to send the LED intensity level /state to other device.

Addendum

As I pointed out - the battery useful life depends on technology. You mentioned AAA , hence I assume alkaline battery. Then I would suggest software solution. Let the server monitor the actual running time of your device.Then measure or calculate the load your device is drawing from the battery. Then determine or calculate the discharge curve of your battery and let the server "output" the battery life / discharged level in relation to time. Perhaps I misunderstood and you actually wanted the RGB LED to be connected to the server. Then you can display green LED up to 80% of battery life and so on ...Keep in mind that the discharge curve is pretty abrupt at the end of battery useful life,

---
Tags: esp8266, arduino-ide, power, sleep, esp32
---


# Question
Title: IoT gabage monitoring system with my own Android application
I'm developing a device system in our campus - my aim is to provide three IoT smart garbage containers that will get the fill level (to determine the space of garbage inside and to inform the garbage collector if the garbage is empty, not yet full and full), temperature and humidity from the garbage bin and will send the information to my application that I'm going to develop.

I don't know how I can connect these three IoT devices which are a fair distance from each other. I know it should be wireless though I can't figure out the exact Arduino device to provide connection to my mobile application.

# Answer
> 2 votes
Does your campus have WiFi? If so, go with EPS8266 if its pins are OK for your sensors. ESP Pinout

You'd want to keep an eye on power consumption; you'd sample your sensors per desired interval and deep-sleep at all other times. Check out available sleep here. It also has en example of how to sample and send a sensor, and sleep afterwards.

On the application end, you could either use a ready service such as Blynk, or go for a custom solution and send the data on your server. Of course, you would then need to write an API and some sort of application to present your data.

Let me also point out that for measuring garbage level, you should calculate the total volume of your bin and subtract the volume of garbage your sensor detects. Having non-uniform trash would give you some trouble, but it's a good technique for an estimation of garbage volume. Also, if using ultrasonic distance sensors, given the fact that you have temperature readings available, you should compensate your measurements; check this out.

---
Tags: sensors, battery
---


# Question
Title: Arduino GSM module + SMS string sending garbage value
I want to check the water level and have an SMS sent via a GSM module. Reed switches are connected to four Arduino analog inputs.

I am unable to add a string and tank level (TKLVL) in program. The program is sending some garbage value via SMS. But TKLVL variable prints the right value.

What is wrong with my code?

```
    #include <SoftwareSerial.h>
    SoftwareSerial SIM900(10, 11);
    String textMessage;
    #define LED1 2
    #define IRLED 3
    //#define rf433DATA 4
    //D4 IS CONNECTED TO RF433MHZ RECEIVER CHANGE ACC TO LIBRARY
    #define PIRpower 5
    int receiver = 6;
    #define VALVE1 7
    #define GSMRESET 8
    #define pumpONdetect 9
    #define VALVE2 12
    //#define TANK_SENSPOWER 13 //
    #define TANK_SENS4 A0  //full tank wigh buzzer
    #define TANK_SENS3 A1
    #define TANK_SENS2 A2
    #define TANK_SENS1 A3  //low tank
    int TKLVL= 0;
    int LEVEL;

    void setup()
    { pinMode(LED1, OUTPUT);
      pinMode(IRLED, OUTPUT);
      pinMode(PIRpower, OUTPUT);
      //CHECK RECEIVER PIN
      pinMode(GSMRESET, OUTPUT);
      pinMode(VALVE2, OUTPUT);
      // pinMode(TANK_SENSPOWER, OUTPUT); //DRIVE THIS PIN LOW TO ON TANK POWER(PNP TRANSISTOR)
      pinMode(TANK_SENS4, INPUT); //FULL TANK WITH BEEP BUZZER
      pinMode(TANK_SENS3, INPUT);
      pinMode(TANK_SENS2, INPUT);
      pinMode(TANK_SENS1, INPUT); //LOW TANK WATER
      // digitalWrite(TANK_SENSPOWER, HIGH); //turns OFF tanksenspower OFFvia PNP transistor..
      Serial.begin(9600);
      SIM900.begin(9600);
      Serial.print("SIM900 ready...");
      SIM900.println("AT+CMGD=1,4\r");
      delay(1000);
      // AT command to set SIM900 to SMS mode
      SIM900.println("AT+CMGF=1\r");
      delay(400);
      // Set module to send SMS data to serial out upon receipt
      SIM900.println("AT+CNMI=2,2,0,0,0\r");
      delay(400);
      digitalWrite(VALVE1, LOW);

    }

    void loop()
    {
      if (SIM900.available() > 0) {
        textMessage = SIM900.readString();
        Serial.print(textMessage);
        delay(10);
      }
      if (textMessage.indexOf("Von") >= 0)
      {
        G_valve1On();
        Serial.println("on loop");
        textMessage = "";
      }
      if (textMessage.indexOf("Voff") >= 0)
      {
        G_valve1Off();
        Serial.println("off loop");
        textMessage = "";
      }

      if (textMessage.indexOf("Tanklvl") >= 0)
      {
        Tanklvl_calc();
         Serial.print("TKLVL is=");
         Serial.println(TKLVL);
        //  TKLVL=LEVEL;
        // Serial.print("level is=");
        //Serial.println(LEVEL);
        String msg ="TANK IS " + TKLVL;
        Serial.println(msg);
        sendSMS(msg);
        textMessage = "";
      }

    }
    //SEND SMS function
    void sendSMS(String lvlmsg)
    {
      SIM900.print("AT+CMGF=1\r");
      delay(1000);
      SIM900.println("AT+CMGS=\"+9182375*****\"\r");
      delay(100);
      SIM900.println(lvlmsg);
      delay(100);
      SIM900.println((char)26);
      delay(1000);
      SIM900.println();
      delay(5000);
    }

    void G_valve1On()
    {
      digitalWrite(VALVE1, HIGH);
      Serial.println("...turning valve1 on...");
    }
    void G_valve1Off()
    {
      digitalWrite(VALVE1, LOW);
      Serial.println("...turningvalve1 off...");
    }

    int Tanklvl_calc()
    {
      if (digitalRead(TANK_SENS4) == HIGH)
      {
        TKLVL = 100;
        Serial.println("TANK LEVEL 100%");
      }
      else if (digitalRead(TANK_SENS3) == HIGH)
      {
        TKLVL = 75;
        Serial.println("TANL LEVEL 75%");
      }
      else if (digitalRead(TANK_SENS2) == HIGH)
      {
        TKLVL = 50;
        Serial.println("TANK LEVEL 50%");
      }
      else if (digitalRead(TANK_SENS1) == HIGH)
      {
        TKLVL = 25;
        Serial.println("TANK LEVEL 25%");
      }
      else
      {
        TKLVL = 0;
        Serial.println("TANK LEVEL IS LESS THAN 25%");
      }
      return(TKLVL);
    }

```

# Answer
> 1 votes
Using Strings in a microcontroller is a no-no. First, try to send a test SMS, to see if everything works OK on SIM800-Arduino etc.

If you receive it correctly, then try to play with char arrays. First, declare a char array big enough for your data to fit in. Let's use a demo array, but keep in mind that it's your responsibility to keep things tidy.

```
byte sizeOfBuffer = 10;
char smsString[sizeOfBuffer] = {'\0'};

```

What we did is create an smsString array of 10 bytes, 9 bytes for data and 1 byte for our special end of sting character. Since we don't want Arduino to handle things with Strings, we have to tell our microcontroller where does that String end. That's what '\0' does.

Then, modify the send function to accept that data type.

```
//SEND SMS function with char array
void send_SMS_charArray(char *lvlmsg, byte sizeOfsms)
{
  SIM900.print("AT+CMGF=1\r");
  delay(1000);
  SIM900.println("AT+CMGS=\"+918237504767\"\r");
  delay(100);
  for (byte i=0; i<sizeof(sizeOfsms); i++){
    SIM900.print(lvlmsg[i]);
  }
  Serial.println();
  delay(100);
  SIM900.println((char)26);
  delay(1000);
  SIM900.println();
  delay(5000);
}

```

Finally, to call the new function you would do something like

```
sprintf_P(smsString, PSTR("TANK IS: %i"), TKLVL);
send_SMS_charArray(smsString, sizeOfBuffer);

```

Notice sprintf\_P when using static messages such as "TANK IS". It will save your life in a few months.

# Answer
> 0 votes
TKLVL is integer type. Convert it to String object and add :-

String msg = "TANK IS " + String(TKLVL)

---
Tags: arduino-uno, gsm, c-string
---


# Question
Title: Writing and reading an ID to/from an Arduino reliably
I need a way to both ID (a sketch/compiled hex) and later on, identify based on this ID the project that got uploaded to my Arduino microcontroller. As of right now, I have explored multiple options for storing the ID and reading the ID from the Arduino. The ID would be a custom string or later on multiple strings. Here are the 3 options I have been thinking about with their pros and cons:

---

**Option 1:**

**Writing:** A custom function that would be added to every sketch before compilation, containing the ID information and a serial connection setup

**Reading:** The function would dump the ID over the serial connection using a fixed baud, after this, the projects original serial and baud would be initialized. The microcontroller would need to be rebooted in order for the user to be able to read the ID from it.

**Pros:** Easy to implement.

**Cons:** Would require manual or software restart of the microcontroller in order to read the ID

---

**Option 2:**

**Writing:** writing the ID to the EEPROM

**Reading:** reading the ID from the EEPROM over the serial connection.

**Pros:** Would probably not interference with the original code

**Cons:** it wears the EEPROM, it might need its own function in the sketch to read the ID from the EEPROM thus making it a complicated Option1.

---

**Option 3:** Editing the HEX file to include a signature

**Writing:** add the ID to the hex file itself (hex editing), after compiling it.

**Reading:** dumping the hex file and decoding the string.

**Pros:** No baud or serial needed to be set?

**Cons:** Probably slow, can end up producing a bad hex file, hard to implement properly with larger ID-s and structures

---

Example data:

`project="marlin2.1",
config="prusa",
version="8.80",
env1="pin2"`

As said, the basic idea is storing an ID but I would late want to expand this and store more information like a struct. This solution should be able to Target as many Arduino models as possible. I am looking for the best way that I might have missed to achieve this task or any recommendations.

# Answer
> -1 votes
I'd go with #2. If you are concerned that you will eventually burn-out your EEPROM (100.000 **write** cycles per ATmega328 ds), try writing a macro, which will dictate at which upload you want new ID to be written in EEPROM. Heck, instead of writing all of these onboard, why don't you maintain an offline lookup database and encode things yourself? It would still require writing to EEPROM but you could encode your information in a couple of ints.

---
Tags: serial, eeprom
---


# Question
Title: Hibernate Arduino for 12hrs with rtc1302 module
ok, Good morning, guys, with a data acquisition project, in this, I get data every 12 hours, even if it's only 12 hours, the arduino gets connected directly, and it's being powered by a 9v battery, for longer life of this battery, to try to hibernate the arduino with real time, using the real time clock 1302, you could help me to make a code for this clock, for I have never used it before! thank you

# Answer
> 1 votes
You need 3 pieces of code and one replacement:

1) Ditch ds1302 and get yourself an RTC with an interrupt pin (like DS3231 which Jot suggests). It will make your life easier.

2) Setup your RTC to fire an interrupt every 12 hours.

3) Since you have successfully implemented a sleep mode, try to wake your Arduino up using a hardware interrupt. See Nick Gammon's guide for interrupts, and read carefully about waking your micro with an external interrupt. You can prototype it using a pushbutton, which will either connect your interrupt pin to GND or Vcc. Use an appropriate resistor as well. This guide has good information for starters.

To sum up: you'll have your Arduino sleep at all times and your RTC set to fire a hardware interrupt. When fired, the interrupt wakes Arduino, and the interrupt code will handle your measurements.

---
Tags: time, rtc, sleep
---