# Question
Title: SPI.transfer(buffer, size) does not send data from buffer
I am having trouble getting `SPI.transfer(buffer, size)` to work as expected.

Here is the code:

```
// inslude the SPI library:
#include <SPI.h>

// set pin 10 as the slave select for the digital pot:
const int slaveSelectPin = 10;

uint16_t SPI_message = 0xABCD;

void setup() {
  // set the slaveSelectPin as an output:
  pinMode(slaveSelectPin, OUTPUT);
  // initialize SPI:
  SPI.begin();

}

void loop() {

  SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE0));
  SPI.transfer(0xEF);
  SPI.transfer(&SPI_message, 2);
  SPI.endTransaction();

  delayMicroseconds(300);

}

```

Here is the output of logic analyzer:

As can be seen the call for `SPI.Transfer(0xEF)` works as expected. However `SPI.transfer(&SPI_message,2)` sends 0x0000 instead of 0xABCD on the bus.

**What am I doing wrong?**

# Answer
`SPI.transfer(&SPI_message,2)` is unfortunately destructive. The buffer is updated with the received values. There is a SPI member function\[1\] that can be used for 16-bit data; `SPI.transfer16(SPI_message)`.

To correct your sketch either initialize the buffer before each call (as recommended by @domen) or use the 16-bit transfer function.

There are other SPI APIs that included non-destructive transfer function e.g. read/write. Please see \[2\].

Cheers!

Ref.

1. https://www.arduino.cc/en/Reference/SPITransfer
2. https://github.com/mikaelpatel/Arduino-SPI/blob/master/src/SPI.h#L137
> 4 votes

---
Tags: arduino-uno, spi
---


# Question
Title: Reprogram Atmega 16u2 on Arduino Mega with Arduino IDE?
I had an Arduino mega 2560, suddenly Arduino didn't recognize my computer and I thought the problem is about Atmega 16u2 and I decided to copy hex file from another Arduino Atmega 16u2 and paste to damaged Arduino but it didn't work. in fact, in our laboratory, we don't have any Linux and other software to reset or reprogram Atmega 16u2 on the other hand I know several methods to solve the problem but I need to know can I use the Arduino IDE to reset Atmega 16u2 without other software. thanks a lot.

# Answer
> 3 votes
Yes, you can recover the firmware in 16u2 only with Arduino IDE installed. In subfolder `hardware/arduino/avr/firmwares/atmegaxxu2/` of the IDE installation folder is the hex file of the firmware `Arduino-COMBINED-dfu-usbserial-atmega16u2-Mega2560-Rev3.hex`. The README.txt file in that folder has sample command line to upload the firmware with avrdude.

---
Tags: arduino-mega, arduino-ide, atmega16u2
---


title: How to deal with this array correctly?

text:
# Question
Title: How to deal with this array correctly?
I am using a led strip **WS2812b**, an **ESP8266 (NodeMCU 1.0)** and a gesture sensor **APDS9960**. I want that when I move my hand from *left to right* and from *right to left* I change the colors of the strip of leds, previously saved in an array of strings:

```
const char * colors [11] = {"CRGB :: White",
"CRGB :: WhiteSmoke",
"CRGB :: CadetBlue",
"CRGB :: SteelBlue",
"CRGB :: Teal",
"CRGB :: SlateGray" ,
"CRGB :: MediumPurple",
"CRGB :: Purple",
"CRGB :: PapayaWhip",
"CRGB :: LightPink",
"CRGB :: Crimson"};

```

But when I'm going to turn on the colors using the functions of the **FastLed** library in this way:

```
for (int i = 0; i <NUM_LEDS; i = i + 1) {
       leds [i] = colors [2];
       FastLED.show ();
       delay (10);}

```

All I get is this error:

> invalid conversion from 'const char \*' to 'uint32\_t {aka unsigned int}' \[-fpermissive\]

I guess the problem is **me** when declaring the *array*, could someone help me?

# Answer
You don't want an array of strings containing the (badly formatted) names of variables. Instead you want an array of 32-bit integers containing the values held within those variables.

```
const uint32_t colors[] = {
    CRGB::White,
    CRGB::WhiteSmoke,
    CRGB::CadetBlue,
    CRGB::SteelBlue,
    CRGB::Teal,
    CRGB::SlateGray,
    CRGB::MediumPurple,
    CRGB::Purple,
    CRGB::PapayaWhip,
    CRGB::LightPink,
    CRGB::Crimson
};

```

Since colours are just numbers, in the (hexadecimal) form of `0xRRGGBB` you just store them as 32-bit unsigned integers. The names you have there are just such (constant) variables used for easy reference (`CRGB::White` is `0xFFFFFF`).
> 3 votes

---
Tags: variables, compilation-errors
---


# Question
Title: Trying to instantiate a DS3231 real-time clock within a library
I'm trying to write a library encapsulating things that I do with a DS3231 real time clock. I have managed to compile a sketch using the library, but it apparently blows up when attempting to call clock methods such as `getTime()`.

Header:

```
// JBP_DS3231.h
#ifndef __JBP_DS3231_h__
#define __JBP_DS3231_h__

#include <SD.h>
#include "DS3231.h"
#include "Arduino.h"

class JBP_DS3231
{
  public:
    JBP_DS3231();
    String TimeStamp();
  private:
    DS3231* _realTimeClock;
};

#endif

```

cpp:

```
#include <JBP_DS3231.h>
#include <SD.h>
#include "DS3231.h"
#include "Arduino.h"

JBP_DS3231::JBP_DS3231() {
  String thisTime = "";

  _realTimeClock = &DS3231(SDA, SCL);

  Serial.println("About to try to get time from RTC."); // Last line we hear from.

  thisTime = _realTimeClock->getTimeStr();
  Serial.print("Time in constructor is: ");
  Serial.println(thisTime);
}

String JBP_DS3231::TimeStamp() {
  String timeStamp = "";

  Serial.println("In TimeStamp().");
  timeStamp = _realTimeClock->getDateStr(FORMAT_LONG, FORMAT_MIDDLEENDIAN, '/');
  Serial.print("Value of timestamp is: ");
  Serial.println(timeStamp);
  timeStamp.concat(" ");
  timeStamp.concat(_realTimeClock->getTimeStr());
  Serial.println(timeStamp);

  return timeStamp;
}

```

Script:

```
const String WHO_AM_I = "JBP_DS3231_library_test.ino";
const    int VERSION = 0;

#include <JBP_DS3231.h>

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

  JBP_DS3231 johnsRTC;
  Serial.println(johnsRTC.TimeStamp());
}

void loop() {
  return;
}

void AnnounceAwakening() {
  Serial.print("Sketch ");
  Serial.print(WHO_AM_I);
  Serial.print(" version ");
  Serial.print(VERSION);
  Serial.println(".");
  Serial.println("");
}

```

# Answer
> 0 votes
You appear to be providing a pointer to a constructor, not to an object. Either create a *new* object with `new`, or instantiate the object separately and provide the pointer to the object:

```
_realTimeClock = new DS3231(SDA, SCL);

```

Better still, extend the existing class and implement your own methods:

```
clsss JBP_DS3231 : public DS3231 {
    public:
        JBP_DS3231(uint8_t d, uint8_t c) : DS3231(d, c) {
            String thisTime = "";
            Serial.println("About to try to get time from RTC."); // Last line we hear from.

            thisTime = getTimeStr();
            Serial.print("Time in constructor is: ");
            Serial.println(thisTime);
        }

        String TimeStamp() {
            String timeStamp = "";

            Serial.println("In TimeStamp().");
            timeStamp = getDateStr(FORMAT_LONG, FORMAT_MIDDLEENDIAN, '/');
            Serial.print("Value of timestamp is: ");
            Serial.println(timeStamp);
            timeStamp.concat(" ");
            timeStamp.concat(getTimeStr());
            Serial.println(timeStamp);

            return timeStamp;
        }
};

void setup() {
    Serial.begin(115200);
    JBP_DS3231 myRTC(SDA, SCL);
    Serial.println(johnsRTC.TimeStamp());
}

void loop() {
}

```

(Note: untested)

---
Tags: library
---


title: 16 bit SPI on Arduino Due

text:
# Question
Title: 16 bit SPI on Arduino Due
I'm trying to control AD7091-8 using Arduino Due.

This IC calls for 16 bit SPI R/W. I'd read that I can change the transmit and receive bits of Arduino DUE by changing a register (bits 4-7 of SPI\_CSR).

I was able to change the SPI of Due from 8 to 16 bits. Confirmed this by looking at SCLK and MOSI in the scope. However, the data I want to transfer is becoming intermittent.

I want to send 0x1000. On 8 bits, using the line

```
SPI.transfer(10,0x10,SPI_LAST);

```

I really can see this being sent on MOSI.

However, when I'm on 16 bits, the line

```
SPI.transfer(10,0x1000,SPI_LAST);

```

It's either becoming 0x0000 or 0x0008. I'm losing the bit or it's becoming LSB\_FIRST. Not MSB\_FIRST.

Below is the actual code.

```
#include <SPI.h>
#include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\component\component_spi.h"
#include "C:\Users\Smart Surface 2\AppData\Local\Arduino15\packages\arduino\hardware\sam\1.6.11\system\CMSIS\Device\ATMEL\sam3xa\include\instance\instance_spi0.h"

#define CS 10

void setup() {

  pinMode(CONV,OUTPUT);

  Serial.begin(9600);
  SPI.begin(CS);
  SPI.setDataMode(CS, SPI_MODE0);
  SPI.setClockDivider(CS,21);

  REG_SPI0_WPMR=0x53504900;
  REG_SPI0_CR=0x1;
  SPI0->SPI_CSR[0]=0x00001580;

  SPI.setBitOrder(MSBFIRST);
  delay(1);
}

void loop() {

  SPI.transfer(CS,0x1000,SPI_LAST);

  int a = SPI.transfer(CS,0x0000, SPI_LAST);
  delay(1000);

  Serial.println(a);
}

```

How can I make my data reliable and the order still with MSB first?

# Answer
Found the problem on the SPI library.

When I do the command SPI.transfer, the data is stored on a byte type variable. And I'm passing a 16 bit data on it.

I've changed line 84 of SPI.h to

```
uint16_t transfer(byte _pin, uint16_t _data, SPITransferMode _mode = SPI_LAST);

```

so it will return and receive 16 bit data.

Also have to change the corresponding function on SPI.cpp (line 174)

```
uint16_t SPIClass::transfer(byte _pin, uint16_t _data, SPITransferMode _mode)

```

so they will match.

I've copied and renamed the SPI library that I've changed so it won't affect other codes.
> 2 votes

---
Tags: arduino-due, spi
---


# Question
Title: HTTP post via GPRS (SIM808) to Azure http endpoint logic app is failing
I am using a SIM808 with a atmega2560.

I have setup the endpoint in Azure and that works when I try a http post via postman and/or an online http post tool (I get a 202 as result and see data comming into Azure)

I want to send a json package to an Azure http endpoint (smart app) using the function httpPOST in the SIMCom library from itead.

I am connecting to the network:

logging (I printed all that is written to GSM):

```
AT+CIFSR
DB:STARTING NEW CONNECTION
AT+CIPSHUT
DB:SHUTTED OK
AT+CSTT="provider.net","","" DB:APN OK
AT+CIICR
DB:CONNECTION OK
AT+CIFSR
DB:ASSIGNED AN IP
GPRS status=ATTACHED
AT+CIPSTART="TCP","prod-13.westeurope.logic.azure.com",443
DB:RECVD CMD
DB:OK TCP

```

Then call the httpPost function from the library with the following variables:

```
const char server[35] = "prod-13.westeurope.logic.azure.com";
const int port = 443;
const char path[200] = "/workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=someazuretoken";
const char parameters[100] = "{\"device\":\"alive\",\"timestamp\":\"09270845\"}";

```

Part of the httpPost function from the library for sending the data

```
    int InetGSM::httpPOST(const char* server, int port, const char* path, const char* parameters, char* result, int resultlength)
         ....
    gsm.SimpleWrite("POST ");
    gsm.SimpleWrite(path);
    gsm.SimpleWrite(" HTTP/1.1\r\nHost: ");
    gsm.SimpleWrite(server);
    gsm.SimpleWrite("\r\n");
    gsm.SimpleWrite("User-Agent: Arduino\r\n");
    gsm.SimpleWrite("Content-Type: application/json\r\n");
    gsm.SimpleWrite("Content-Length: ");
    itoa(strlen(parameters),itoaBuffer,10);
    gsm.SimpleWrite(itoaBuffer);
    gsm.SimpleWrite("\r\n\r\n");
    gsm.SimpleWrite(parameters);
    gsm.SimpleWrite("\r\n\r\n");
    gsm.SimpleWrite(end_c);
....

```

Which gives this output on the serial monitor (I printed all that is written to GSM):

```
AT+CIPSEND
DB:>
POST /workflows/someazureID/triggers/manual/paths/invoke?api-version=2016-10-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=someazuretoken HTTP/1.1
Host: prod-13.westeurope.logic.azure.com
User-Agent: Arduino
Content-Type: application/json
Content-Length: 55

{"device":"alive","timestamp":"09270845"}

DB:SENT

```

And then it is waiting for a response:

```
Starting read..
Waiting for Data............................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................
CLOSED

Done..
response:
10

CLOSED

```

which times out I guess.

And I see nothing coming into Azure.

(I am getting data when I try a httpGet on a random site. So hardware, sim and network is working ok I guess)

Any ideas? thx!

# Answer
Juraj's comments put me on the right track, for SSL you need to do more then just select the port.

I did some searching and got it to work using a different GSM library that also supports SSL: tinyGSM

in combination with ArduinoHttpClient

Jeroen

EDIT: It works, but there is a big downside. It looks like there is major overhead, each message seems to uses 13Kb of data...? I suspect this comes from the data that is returned by the endpoint. This is way too much over GPRS so now looking into MQTT.
> 1 votes

---
Tags: http
---


# Question
Title: Differing Serial Values Between Arduino Uno and TTGO ESP32 SX1276
I'm wanting to analogRead the value off a MQ-135 gas sensor. I have tired this with both an Arduino Uno and an TTGO ESP32 SX1276.

When reading the value of the sensor off the Uno, I get values approximately equal to 400 which is expected, as shown in this video. When doing the same on the TTGO, I get values close to 2000. For some reason, this person gets a similar value range as shown in this video.

What I don't understand is how these values are different when only the board is being changed. Do different boards analogRead differently?

More or less, how do I get the TTGO to read the same values as the Uno?

Below is my code for both boards. Nothing is changed between the boards:

```
#define sensor 2 //sensor pin

int gasLevel = 0; //int variable for gas level

void setup() {
  Serial.begin(9600); //start serial comms
  pinMode(sensor,INPUT); //set sensor for input
}

void loop() {
  gasLevel = analogRead(sensor);
  Serial.println(gasLevel);
  delay(1000);
}

```

The following things I have tested:

* Multiple boards of both the Arduino Uno and TTGO
* Different pins, both analog and digital

I also am powering the sensor using 3.3V pin, so there is no variation in the voltage the sensor is receiving.

# Answer
> 3 votes
> Do different boards analogRead differently?

Yes.

Your typical Arduino has a 10-bit ADC. That can give values between 0 and 1023 (210-1), with 400 falling just short of half way.

The ESP32 has a 12-bit ADC. That gives values between 0 and 4095 (212-1), which means that your 2000 falls, yes, just short of half way.

It is not the value from the ADC that is important - it is *what the value represents*. It is meaningless until you convert it into something meaningful, like a voltage.

Like asking "How heavy is it?" -- "It's 23." Completely meaningless, until you qualify it with units, and the units are different because of the different resolutions, so you need to "convert" it into units that have a meaning.

Typically the value represents a proportion of the supply voltage (but not necessarily: it's actually a proportion of the ADC reference voltage, which is often the same thing as the supply voltage). On the Arduino the value is 1/1024th of the supply voltage. On the ESP32 it's 1/4096th.

---
Tags: arduino-uno, analogread, esp32
---


title: Preventing EMI on PCB

text:
# Question
Title: Preventing EMI on PCB
i've made a project consisting of 3 DC motor pumps, Atmega328p on custom PCB, and a relay. I found a problem which causes my PCB custom arduino trips over and over again caused by 12V DC MOTOR. I fix it already by putting a flyback diode on motor. it runs much better but still have a small number of trips on my arduino.

probably i've a bad PCB design and lack of components.

is there a way to prevent these electromagnetic interference caused by motor? or some improvements on my PCB board?

# Answer
Had a problem like this. I ended up using a separate power supply for my DC motor. Don't forget to connect the GND's.
> 0 votes

# Answer
There are few things you can try. First thing that comes to mind is hooking up the power source to an oscilloscope and see if there is not a big voltage dip when motor starts running/runs. This could happen if the motor attempts to draw more current than the power source can deliver, hence the voltage of source would drastically drop and Arduino would restart.

Second thing, assuming this is EMI, which I doubt - You need a proper ground plane, not just a thin trace. That would definitely help. Third thing would be reducing loop areas, by which I mean putting power and GND lines close to each other, look at http://www.ti.com/lit/an/szza009/szza009.pdf. This is a very resourceful document.

Third thing is - put a decoupling capacitor as close to the Arduino as possible. This will even out any spikes you may get, or any unexpected instability.

Hope this helps
> 0 votes

# Answer
The most critical failing of your PCB is the fact that you have no decoupling capacitors near your MCU power pins. These are absolutely required, and are not optional.

To modify your existing PCB, so you don't have to roll a new one, just solder a 0.1µF 0805 SMD capacitor between each VCC and GND pair of pins on the underside of the board.

You should also reduce both the ground impedance and the power supply impedance by replacing your ground traces with a ground pour, and fatten your power traces up a little.
> 0 votes

---
Tags: motor, pcb-design
---


# Question
Title: Servo going up to the limit as soon as attached
I have a Futaba S148 servo (https://servodatabase.com/servo/futaba/s148) connected to an Arduino Uno.

As soon as the script attaches the servo, it rotates to its limit and gets stuck.

I've tried several scripts, and narrowed to the simplest:

```
#include <Servo.h>  // servo library
Servo servo1;  // servo control object
void setup()
{
  //  Attach the servo1 object to digital pin 4.
  servo1.attach(10);
}
void loop()
{
}

```

Also connected the servo to the board with this:

```
#include <Servo.h>  // servo library
Servo servo1;  // servo control object
void setup()
{
  //  Attach the servo1 object to digital pin 4.
  //servo1.attach(10); <--- notice this commented out
}
void loop()
{
}

```

and then the servo remains still.

I'm using a battery pack of 4.8 V which works fine with the servo and the RC radio, so the battery and the servo, works fine together with remote control.

I have another different SG90 servo running with its own power source and connected to the pin 9, and with a different sketch, it works perfectly.

# Answer
> 1 votes
https://www.arduino.cc/en/Reference/ServoAttach \- This should answer it. The library you are using supports only 2 specific pins

---
Tags: servo
---


# Question
Title: Brushless motor + ESC with Arduino question
Sorry in advance as I'm still a rookie with Arduino projects. My goal is to use an Arduino Uno 3 to create an inexpensive drone/plane project.

Here are my materials and my set up:

Upon compiling the code I found here and connecting the 9 V battery to the ESC, all I hear is constant beep sounds from the motor (about once every 1.5 seconds). Can anyone help me figure out what's going on? Is it the 9 V battery that's not giving the motor enough juice? Or am I just too silly hoping to create something that works under $10?

```
#include <Servo.h>
Servo ESC1;

int pos = 0; //Sets position variable

void arm() {
  setSpeed(0); //Sets speed variable delay(1000);
}

void setSpeed(int speed){
  int angle = map(speed, 0, 100, 0, 180);
  //Sets servo positions to different speeds ESC1.write(angle);
}

void setup() {
  ESC1.attach(9); //Adds ESC to certain pin. arm();
}

void loop() {
  int speed; //Implements speed variable
  for(speed = 0; speed <= 70; speed += 5) {
    //Cycles speed up to 70% power for 1 second
    setSpeed(speed);
    //Creates variable for speed to be used in in for loop
    delay(1000);
  }
  delay(4000); //Stays on for 4 seconds
  for(speed = 70; speed > 0; speed -= 5) {
    // Cycles speed down to 0% power for 1 second
    setSpeed(speed); delay(1000);
  }
  setSpeed(0);
  //Sets speed variable to zero no matter what
  delay(1000);
  //Turns off for 1 second
}

```

# Answer
> 2 votes
Like the previous answer stated, you should be using a 20-25c battery (can discharge up to 25A). I don't know exactly how much a 9V draws, but it definitely can't supply more than an AMP. Your motor pulls much more than 1 amp. Get yourself a nice LiPo from hobbyking.com, maybe an 8.4v or 11.1v

The ESC beeping could be telling you it can't draw enough Amps from the battery?

# Answer
> 2 votes
Probably a bit late but your code has some important parts commented out such as (in order):

* delay(1000);
* ESC1.write(angle);
* arm();

Once you add those to the next lines the program should work and the esc shouldn't just beep and actually get the motor to spin

# Answer
> 1 votes
The beeping is actually from the ESC. I believe that this model needs to be properly configured (which you can do using the Arduino - refer to the user manual or here) before it can be used. Some kits come with it preconfigured but since you seem to have possibly purchased it individually you need to configure it yourself. Also it doesn't appear to be that your code wouldn't actually send any PWM signals to the ESC. I've only ever used Servo.write() functions in my quads, so I can't be 100% sure on that.

# Answer
> 0 votes
You need high current for working with this motor, 8.4 LiPo battery for example.

---
Tags: arduino-uno, motor, drone
---


title: Formula creation

text:
# Question
Title: Formula creation
I was creating a scoring formula for a game.

The formula in question is

```
millis() * 1.1 ^ (millis()/10000);

```

However, I'm having trouble understanding the different error messages that the Arduino IDE is projecting to me

> invalid operands of type to binary operator

I have declared the score as an `unsigned long`.

# Answer
I would avoid calling `millis()` twice within the same expression. Not really a big deal in your case, but the two calls can very well return different values, which would make your formula slightly inconsistent. Then, using the proper syntax for the power function, as explained by Kwasmich:

```
uint32_t t = millis();
float score = t * pow(1.1, t/1e4);

```

Note that `1e4` is the scientific notation for `10000.0`. I personally find the former more readable, as you don't have to count the zeros.

Now, it is worth noting that the `pow()` function is very expensive to compute on this kind of 8-bit FPU-less processor. It involves both a logarithm and an exponential. The second line is essentially equivalent to

```
float score = t * exp(t/1e4 * log(1.1));

```

The floating point division is also quite expensive. You could save something like half the processing cycles by pre-computing `log(1.1)/1e4` and using the result in your expression:

```
float score = t * exp(t * 9.53e-6);

```
> 4 votes

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


# Question
Title: Apply patch to library for custom changes in Arduino IDE
I wish to obtain unix epoch timestamps in millisecond precision. I am using an ESP32 along with **DS3231** RTC breakout board from adafruit.

Apparently the Repository is not maintained often but I see a PR which overcomes the rollover for software timer and the developer provided a patch in the comment to use the unix timestamps in ms.

I went to the `libraries` folder where all the downloaded adafruit repos exist. But when I did `git status` it mentions that the library download (from the library manager) is not a git repository.

I wan't to inculcate the changes to the `RTClib` library by using the patch provided. Should I just change the code directly via the Arduino IDE editor?

# Answer
> 1 votes
Save the patch to a file, put it in the directory holding the library, open a terminal on that directory and type:

```
patch -p1 < patchfile

```

You may have to install the "patch" utility if you don't have it yet. On a Debian-like OS (I don't know for other OSes):

```
sudo apt install patch

```

---
Tags: arduino-ide, library, rtc, esp32
---


# Question
Title: Is it possible to make an Arduino send signals to an RC receiver?
I have found bunch of information about how to hack an RC car with a PCB; and how to control an Arduino from a receiver. Also how to run a servo from an Arduino, but I'm looking for a way to make an Arduino send signals to a 27 MHz 3 channel receiver, Using three potentiometers to decide servo location.

Is there any information about this somewhere? - I have an old transmitter lying around if needed.

Links, pointers - anything is welcome.

\[It does not have to be 27 MHz AM, it is just what I have on the shelve, without investing in new gear\]

# Answer
> 2 votes
The easiest way would be to open up the transmitter, desolder the potentiometer used for the stick and solder the cables to Arduino's PWM instead. Then use `analogWrite()` to simulate stick position. If your TX would use that potentiometer with more than 5 V, you'll not able to use full ppm values. A RC or a RCL filter may be needed between PWM output and RC input to "smooth" the PWM into an analog signal. There are a lot of online calculator to find good *R, C and L* to polish your signal.

This assuming your TX is using potentiometer like stick; if it is a really cheap one, it may be using *buttons*. If this is the case, then you connect a transistor in parallel with the button, that way you can keep manual button.

Another way is to program your Arduino to look for ppm signal (normally 50 Hz with high starting value with a period from 500 to 2000 µs) and then look for this signal into the Tx PCB; if found cut the trace of the generator and solder your cable from Arduino. I've seen around a lot of libraries outputting ppm (they are used on drones to mix single ppm channel back to PPM to use only one pin from logic board without having to hack standard RX

# Answer
> 1 votes
Many RC TX have a remote connector where you can input the signal and not having to open them.

In any case, 27 MHz RC are a train of pulses, of variable width, from 2 to 20 ms each, one for each channel, flowed by a 20 ms pause.

This can be recreated in a single output pin.

# Answer
> 1 votes
Consider the methods of US patent 9,996,079 (linked URL):

"Radio frequency device detection and intervention": US 20180081354 A1

After reverse engineering the badly written descriptive, you should be able to come up with an Arduino board set.

P.S. Try not to copy the whole patent.

---
Tags: arduino-uno
---


# Question
Title: Problem with Software Serial: no response
I am using an Arduino Uno board with IDE 1.6.7.

I have tried to implement a tweaked version of the basic example (`SoftwareSerial` example) from the Software Serial library. The code is attached.

It should blink the light and print the message on the serial monitor. But I am not getting anything.

In fact, I also tried the example as it is. It did not work either.

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(8, 9); // RX, TX

void setup() {
    pinMode(13,OUTPUT);
    // Open serial communications and wait for port to open:
    Serial.begin(9600);
    while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
    }
    Serial.println("Goodnight moon!");
    // set the data rate for the SoftwareSerial port
    mySerial.begin(9600);
    delay(1000);
}

void loop() { // run over and over
    mySerial.println("hell");
    if (mySerial.available() > 0) {
        digitalWrite(13,HIGH);
        Serial.write("working..");
        delay(3000);
        digitalWrite(13,LOW);
        delay(2000);
    }
}

```

# Answer
`SoftwareSerial` cannot transmit and receive at the same time. So even if you connected pin 8 to 9 with a wire, your sketch will not receive what was transmitted. That's a guess without your wiring diagram.

NeoSWSerial can simultaneously transmit and receive. It is a drop-in replacement for `SoftwareSerial`.

However, AltSoftSerial is even better, and it only works on pins 8 & 9. Use that instead!

This answer compares all 4 serial types, including `HardwareSerial`.
> 2 votes

# Answer
I built two scetch for testing. One for Arduino Nano no1 and another for Arduino Nano no2. They are tested and working, not only written to this page.

No2 is sending "hello" and No1 is listening and sending it to PC via Serial. The speed (1200bps) is slow, but so it is easier to see what is happening.

Connect Pin10 of no1 to Pin11 of no2 and gnd to gnd. Connect the Nanos to the USB-ports of the PC and set a monitor program (1200, 8N1) to listen no1.

This seems to be a good way to test Serial.print, Serial.println and Serial.write commands. You will be surprised.

/\******No1:*****/

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11); // RX, TX
void setup() {
  Serial.begin(1200);
  Serial.println("Testing");
  mySerial.begin(1200);
}
void loop() { // run over and over
 if (mySerial.available()) //If this is missing, you get fast repeating carpage
{
    Serial.write(mySerial.read());
    Serial.print(".");
 }
}

```

/\******No2:*****/

```
#include <SoftwareSerial.h>
 SoftwareSerial mySerial(10, 11); // RX, TX
 void setup(){
  mySerial.begin(1200);
}
void loop(){
    mySerial.print("Hello");
}

```
> 1 votes

# Answer
> ```
> if(mySerial.available()>0)
>
> ```

`mySerial.available()` returns the number of bytes available in your serial receive buffer. Unless you are sending commands via serial in pins 8 and 9, this will remain 0 and you will never enter the if statement.

Also, you have two declarations for serial here:

1. `Serial.begin()` initialized the built-in UART USB module. Here you will be able to send/receive commands with a program such as Putty.
2. `SoftwareSerial mySerial(8, 9); // RX,` `mySerial.begin()` initializes serial communications with pins 8 and 9 on the Arduino board. This would be if you wanted to send/receive commands with digital I/O instead of, or in addition to, the UART USB module.
> 0 votes

---
Tags: arduino-uno, softwareserial, software
---


# Question
Title: Arduino - My problem is when the condition is greater than 900.00 it will continue the loop and do the code below once
I want is to stop the loop and when it read Greater than 900.00 again it will do task again.

I need condition. When it back to greater than 900.00 the code below will do task and then it will stop. And when it will reach the condition again it will do the code again and it will stop .. Please help me

```
void loop(){
  float reading = analogRead(LIGHTSENSORPIN); //Read light level
  float square_ratio = reading / 1023.0;      //Get percent of maximum value (1023)
  square_ratio = pow(square_ratio, 2.0);      //Square to make response more obvious

  analogWrite(LEDPIN, 255.0 * square_ratio);  //Adjust LED brightness relatively
  analogWrite(LED_BUILTIN, 255.0 * square_ratio);  //Adjust LED brightness relatively
  Serial.println(reading);                    //Display reading in serial monitor

if(reading >= 900.00){

  digitalWrite(smDirectionPin, LOW); //Writes the direction to the EasyDriver DIR pin. (LOW is counter clockwise).
    /*Turns the motor fast 1600 steps*/
      for (int i = 0; i < 400; i++){
    digitalWrite(smStepPin, HIGH);
    delayMicroseconds(700);
    digitalWrite(smStepPin, LOW);
    delayMicroseconds(700);
}
}

  delay(1000);

}

```

# Answer
```
setup(){ ....
......
}
float old_reading=0;
loop() {
float reading = analogRead(LIGHTSENSORPIN); //Read light level
// ... do this always (maybe empty)
// in your code it is LED shining and printing
if ((old_reading<=900) && (reading>900)) {
   // ... do this just just once when reading goes over 900 up
   // in your code it is manipulating motor
   }
old_reading=reading;
// ... do this always , but after special part (maybe empty)
// in your code it is just delay
}

```
* So on begining `old_reading` is just zero, but being declared outside `loop`, it keeps its value between different runs of `loop`.
* the `if (condition)` does not hit, as `reading` is less than 900 (if it starts with more then 900, see next part)
* the end with `old_reading=reading;` makes `old_reading` to be the last known value of `reading`
* when `reading` goes Greater than 900 for first time, the `old_reading` is Less or Equal 900 (as it was the last value of `reading` before it crossed 900 up.
* + so the `if (condiotion)` is true and you start moving motor
* + then (on the end) you set `old_reading=reading;` and `old_reading` is also larger then 900
* + while `reading` stays over 900 in next loops, the `old_reading` does so, and therefore the `if (condition)` does not hit - `(old_reading<=900)` is not true
* + when `reading` falls down 900 or lower, the `if(condition)` also does not hit, but after that the `old_reading=reading;` makes `old_reading` less or equal 900
* and so we are at the start again, skipping the part after `if(condition)` until `reading` gets Greater than 900 (then we run motor, set `old_reading` to something greater than 900 and we already was here and know, how it works :)
> 1 votes

---
Tags: arduino-uno
---


title: ESP8266 not accessing PHP file

text:
# Question
Title: ESP8266 not accessing PHP file
I'm trying to control NodeMCU via Android application and I can control NodeMCU easily but when I added the URL to hit the PHP code to enter data in MYSQL, neither NodeMCU is controllable nor NodeMCU is hitting the PHP code. I'm confused with `content type: text/html` \- I'm not sure where to set this piece. Is there any mistake I'm doing or anything I'm missing?

Following is the ESP8266 code on Arduino IDE:

```
#include <ESP8266WiFi.h>

const char* ssid = "ssid";
const char* password = "password";
const char* host = "aoatech.ml";

WiFiServer server(3000);
int light1 = 13;
int light2 = 15;
int fan = 12;
int socket = 14;
String what;
int which;
String mac;

void setup() {
  Serial.begin(115200);
  delay(10);
  pinMode(light1, OUTPUT);
  pinMode(light2, OUTPUT);
  pinMode(fan, OUTPUT);
  pinMode(socket, OUTPUT);
  digitalWrite(light1, 0);
  digitalWrite(light2, 0);
  digitalWrite(fan, 0);
  digitalWrite(socket, 0);
  Serial.print("Connecting to: ");
  Serial.print(ssid);
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  server.begin();
  Serial.println("Server started");
  Serial.println(WiFi.localIP());
}

void loop() {
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
  Serial.print("Connecting to ");
  Serial.println(host);
  //  const int httpPort = 3000;
  //  if (!client.connect(host, httpPort)) {
  //    Serial.println("Connection failed!");
  //    return;
  //  }
  mac = WiFi.macAddress();
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
  int val;
  if (req.indexOf("/light1/1") != -1){
    val = 1;
    what = "Light_1";
    which = light1;
  }
  else if (req.indexOf("/light1/0") != -1){
    val = 0;
    what = "Light_1";
    which = light1;
  }
  else if (req.indexOf("/light2/1") != -1){
    val = 1;
    what = "Light_2";
    which = light2;
  }
  else if (req.indexOf("/light2/0") != -1){
    val = 0;
    what = "Light_2";
    which = light2;
  }
  else if (req.indexOf("/fan/1") != -1){
    val = 1;
    what = "Fan";
    which = fan;
  }
  else if (req.indexOf("/fan/0") != -1){
    val = 0;
    what = "Fan";
    which = fan;
  }
  else if (req.indexOf("/socket/1") != -1){
    val = 1;
    what = "Socket";
    which = socket;
  }
  else if (req.indexOf("/socket/0") != -1){
    val = 0;
    what = "Socket";
    which = socket;
  }
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }

  digitalWrite(which, val);

  String url = "http://aoatech.ml/hitthis.php?room=Bed%20Room%201";
  url += "&state=";
  url += val;
  url += "&button=";
  url += what;
  url += "&mac=";
  url += mac;

  Serial.print("Requesting URL: ");
  Serial.println(url);

  client.flush();
  //  client.println("HTTP/1.1 200 OK");
  //  client.println("Content-Type: text/html");
      client.print(String("GET ") + url + " HTTP/1.1\r\n" +
           "Host: " + host + "\r\n" +
           "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }
  client.println("");
  client.print(what + " is now: ");

  if(val == 0) {
    client.print("Off");
  } else {
    client.print("On");
  }
  Serial.println("Client disonnected");
}

```

# Answer
Your PHP server has a certain content type it can receive to process your requests from the ESP8266. The two most generic content-types used for php are either application/x-www-form-urlencoded or multipart/form-data. Try to play with those two and see if that solves it for you.
> 0 votes

# Answer
You mixed WiFiServer and client request examples by replacing servers HTTP response text with a HTTP request text. A client object returned by WiFiServer's `available` function is a counterpart of requesting client (for example web browser).

See WebClient example for a client connecting to some server.
> 0 votes

---
Tags: esp8266
---


title: Custom Debounce Code Not Working

text:
# Question
Title: Custom Debounce Code Not Working
It's my custom debounce code

It keeps the led on by flipping the required threshold value when triggered after the led has turned on to keep the led in a high state and vice verse triggered again, the comments on the code explain it in more detail.

```
/*
 * This code is my custom debounce code, I made this but this isn't working as planned,
 * see the thing is that it turns on when I hold the button and if I release it,
 * it starts to flickers and then gradually turn off, what is wrong with my code ?
 * I can't see it.
 */

const int ledPin = 13; // led connected to pin 13
const int PushButton = 2; // a pushbutton connected to pin 2
int switcher = HIGH; // the switcher changes it's value, we require this later
int dilay = 1; // controls the delay
unsigned long lastTrigger = 0; // records the last time the led was turned on

void setup() {
  pinMode(ledPin, OUTPUT); // sets ledpin as output
  pinMode(PushButton, INPUT); // sets pushbutton pin as input
}

void loop() {
  int pushButtonState = digitalRead(PushButton); // stores the value of the pin each time the loop begins agian

  if((millis() - lastTrigger) >= dilay){ // my custom debounce code
    if(pushButtonState == switcher){ //  this is the trick, when the pushbutton pin is high it's equal to the switcher value
      digitalWrite(ledPin, HIGH); // it turns on the led
      int switcher = LOW; // now the switcher value will be low now the pushbutton pin value will also be low keeping the led on
    }else{
      digitalWrite(ledPin, LOW); // now if the led is on and pushbutton is high, then it will not be equal to the switcher because we had changed it in the previous statement
      int switcher = HIGH; // now the switcher is high and the pushbutton value low, switcher isn't equal to pushbutton so there by keeping the ledpin as low

    }

    if(pushButtonState == 1){ // if pushbutton is high
      int lastTrigger = millis(); // then  lastTrigger equals to the current time
    }
  }

}

```

# Answer
> 1 votes
Change `int switcher = LOW/HIGH` to just `switcher = LOW/HIGH`.

Otherwise you are redefining the variable, and will make it a local variable, and not change the global variable with the same name (as you are expecting).

---
Tags: arduino-uno, debounce
---


title: listing sd card files on a tft screen

text:
# Question
Title: listing sd card files on a tft screen
I'm currently working on a **Arduino** project that plays **audio** files from **SD card** through a **speaker**.

First Arduino sends the list of all music files, and when I send it a file name, the music is played.

The project is working well but there's no **GUI**. Everything has to be done via **serial**, and now I want to add a **TFT** screen that will list the music files on the screen, so that whenever I **touch** a file name it should be played.

I haven't bought the TFT yet, and that's because I have a little question for which I need an answer.

**If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.**

Any help would be appreciated.

# Answer
> If I start listing the files, can I scroll up and down ? Because at some point the TFT screen will become full of text, and I don't want the text to be overwritten.

If you program that kind of facility, yes.

A TFT screen is like a blank piece of paper, and you have a set of crayons. You draw on the screen (sometimes with pre-defined shapes, called "letters"). If you want to change what is on the screen you can either throw away your piece or paper and start with a new blank page, or you can get some Tip-Ex® and cover up parts that were there already so you can draw over them.

If you want scrolling you will have to work out for yourself how best to do that given the limited resources you have available.

The simplest method is just to retain a list of the filenames in memory and print just a subset of them on the screen. "Scrolling" then just means displaying a different subset of names.
> 3 votes

---
Tags: sd-card, tft
---


title: nrf24l01+ contradicting itself?

text:
# Question
Title: nrf24l01+ contradicting itself?
I have recently bought a few of these chips on boards along with some "adapter boards" which supposedly regulates the 5v to propper 3.3v with the required capacitors. So power supply shouldn't be a problem although I haven't tried with a separate power supply. Ok, so I like to build my stuff from scratch to really know everything that's going on so I'm not using a library for this chip but I've read the datasheet in it's entirety and have understood all the features. At first after going through every option one of the modules was successfully sending out packets as indicated by the TX\_DS interrupt but nothing was showing up on the one in receiver mode, and after lots of checking I chose to disable every feature and managed to finally get some action as the receiver interrupted each time the transmitter sent out a packet with no CRC and no ACK.

But now there's an issue, the datasheet clearly states:

> The RX\_DR IRQ is asserted by a new packet arrival event. The procedure for handling this interrupt should be:
>
> 1) read payload through SPI,
>
> 2) clear RX\_DR IRQ,
>
> 3) read FIFO\_STATUS to check if there are more payloads available in RX FIFO,
>
> 4) if there are more data in RX FIFO, repeat from step 1).

However upon getting the interrupt and reading out 33 bytes with the command, the status register reads 4E (0100 1110) saying that the interrupt was indeed RX\_DR but also the pipe number bits are all on meaning an empty RX FIFO. The following 32 bytes read 0.

How can this be? Has anyone experienced something similar?

UPDATE: Tested with separate power supply on RX side, issue still stands.

Pictures: https://1drv.ms/f/s!Ag6xBMoahJ8xkOkWMG89RIAa1m71Kw

Arduino code: (feel free to correct me I'm no expert in this language :p)

Main

```
void setup() {
  attachInterrupt(digitalPinToInterrupt(radio.irq), interrupt, FALLING);
  Serial.begin(9600) ;
  Serial.write("\n    ----Boot----\n\nInitializing radio...\n");

  //Starts radio as PRX
  //Sets channel
  //Sets bitrate to 1Mbps
  if (radio.init()) {
    Serial.println("Radio ready.\n\n ----Boot complete----\n\n");
  } else {
    Serial.write("Couldn't initialize radio!\n\n  ----Boot failed----\n");
    return;
  }
  delay(10);
  digitalWrite(9, HIGH);
}

void loop() {
}

void interrupt() {
  Serial.write("\nINTERRUPT\n");
  digitalWrite(9, LOW);

  radio.readRegister(0x17, 2, true, BIN);
  radio.readRXpayload(true);
  radio.clearIRQ();

  digitalWrite(9, HIGH);
}

```

Radio class

```
#include "BitUtils.h"

BitUtils utils;

uint8_t* tmp = (uint8_t*)malloc(sizeof(uint8_t) * 33);
uint8_t initialPipe0[5] = {0x28, 0x18, 0xdb, 0xc2, 0x86};
uint8_t beaconAddress[5] = {0x29, 0x26, 0x13, 0x12, 0x00};

class Radio {
  public:
    uint8_t nullmsg[1] = {0x00};

    uint8_t rx_config[1] = {0b00100011}; //0x00
    uint8_t tx_config[1] = {0b00100010}; //0x00
    uint8_t aa_config[1] = {0b00000000}; //0x01
    uint8_t ch_config[1] = {0b00110100}; //0x05
    uint8_t rf_config[1] = {0b00000110}; //0x06
    uint8_t features_config[1] = {0b00000000}; //0x1D

    uint8_t clear_irq[1] = {0b01110000}; //0x07

    uint8_t clk = 13;
    uint8_t miso = 12;
    uint8_t mosi = 11;
    uint8_t slaveselect = 10;
    uint8_t chipenable = 9;
    uint8_t irq = 2;

    SPISettings spiConfig = SPISettings(2000000, MSBFIRST, SPI_MODE0);

    boolean init() {
      noInterrupts();

      pinMode(clk, OUTPUT);
      pinMode(miso, INPUT);
      pinMode(mosi, OUTPUT);
      pinMode(slaveselect, OUTPUT);
      pinMode(chipenable, OUTPUT);
      pinMode(irq, INPUT);
      digitalWrite(clk, LOW);
      digitalWrite(slaveselect, HIGH);
      digitalWrite(chipenable, LOW);
      delay(11);

      transfer(nullmsg, 1, tmp);
      if (tmp[0] != 0b00001110) {
        return false;
      }

      writeRegister(0x00, rx_config, 2); Serial.print("0x00: ");
      readRegister(0x00, 2, true, BIN);
      writeRegister(0x01, aa_config, 2); Serial.print("0x01: ");
      readRegister(0x01, 2, true, BIN);
      writeRegister(0x05, ch_config, 2); Serial.print("0x05: ");
      readRegister(0x05, 2, true, BIN);
      writeRegister(0x06, rf_config, 2); Serial.print("0x06: ");
      readRegister(0x06, 2, true, BIN);
      writeRegister(0x1D, features_config, 2); Serial.print("0x1D: ");
      readRegister(0x1D, 2, true, BIN);

      pipeAddress(initialPipe0, 0);
      pipeAddress(beaconAddress, 1);

      Serial.print("Pipe 0 address: ");
      readRegister(0x0A, 6, true, HEX);
      Serial.print("Pipe 1 address: ");
      readRegister(0x0B, 6, true, HEX);

      delay(2);
      interrupts();
      return true;
}

    //    -- Operations --

    void clearIRQ() {
      writeRegister(0x07, clear_irq, 2);
      Serial.println("Cleared IRQ");
    }

    void sendTXpayload(uint8_t data[], boolean ack) {
      uint8_t message[33] = {0b10100000};
      if (!ack) {
        message[0] = 0b10110000;
      }
      for (int i = 31; i > -1; i--) {
        message[32 - i] = data[i];
      }

      transfer(message, 33, tmp);
      pulseCE(12);
      delay(2);
    }
    void readRXpayload(boolean report) {
      uint8_t message[33] = {0b01100001};

      transfer(message, 33, tmp);
      if (report) {
        utils.prtArr(tmp, 33, HEX);
      }
    }

    void mode(char m) {
      digitalWrite(chipenable, LOW);

      if (m == 't') {
        writeRegister(0x00, tx_config, 2);
        Serial.println("Set tx mode.");
      }
      if (m == 'r') {
        writeRegister(0x00, rx_config, 2);
        Serial.println("Set rx mode.");
      }
    }

    void pipeAddress(uint8_t* address, uint8_t number) {
      uint8_t pipeNumber = 0x0A + number;
      for (int i = 4; i > -1; i--) {tmp[4 - i] = address[i];}

      if (number < 2) {
        writeRegister(pipeNumber, tmp, 6);
      }else{
        writeRegister(pipeNumber, address, 2);
      }
    }

    void sendTo(uint8_t* address) {
      for (int i = 4; i > -1; i--) {
        tmp[4 - i] = address[i];
      }
      writeRegister(0x10, tmp, 6);
      Serial.print("TX Address: ");
      readRegister(0x10, 6, true, HEX);
    }

    void setChannel(uint8_t ch) {
      writeRegister(0b00000101, new uint8_t[1] {ch}, 2);
      Serial.write("Frequency set to: ");
      Serial.print(2400 + tmp[1], DEC);
      Serial.println("MHz");
    }

    //    -- Low operations --

    void readStatus(boolean prt) {
      transfer(nullmsg, 1, tmp);
      if (prt) {
        utils.prtArr(tmp, 2, BIN);
      }
    }
    void readRegister(uint8_t address, uint8_t amount, boolean prt, uint8_t format) {
      uint8_t message[amount] = {address};
      transfer(message, amount, tmp);

      if (prt) {
        utils.prtArr(tmp, amount, format);
      }
    }
    void writeRegister(uint8_t address, uint8_t* data, uint8_t amount) {
      uint8_t message[amount] = {(uint8_t)(0b00100000 | address)};
      for (uint8_t i = 1; i < amount; i++) {
        message[i] = data[i - 1];
      }

      transfer(message, amount, tmp);
    }
    void pulseCE(int duration) {
      digitalWrite(chipenable, HIGH);
      delayMicroseconds(duration);
      digitalWrite(chipenable, LOW);
    }

    //    -- Bidirectional SPI bus --

    void transfer(uint8_t* data, uint8_t amount, uint8_t* output) {
      SPI.beginTransaction(spiConfig);
      digitalWrite(slaveselect, LOW);
      delayMicroseconds(1);

      for (uint8_t i = 0; i < amount; i++) {
        output[i] = SPI.transfer(data[i]);
      }

      delayMicroseconds(1);
      digitalWrite(slaveselect, HIGH);
      SPI.endTransaction();
    }
};

```

# Answer
> 1 votes
My advice would be to strip out all of the unnecessary code to make a minimal complete example (MCVE). The nRF24L01 is not so complicated when you get to know the data registers, and unfortunately that's where a lot of people get stuck, by trying to use the libraries without reading the datasheet. However, the posted code suggests that you have done your homework. This is how I set up nRF24L01 to use IRQ (chronological order from top to bottom):

```
// Begin SPI
// Register 0x0A: set receiver addresses
// Register 0x11: set payload number of bytes

// flush RX (spi transfer B11100010) and TX (spi transfer B11100001)

// attach ISR on IRQ digital input pin.

// start the main program loop

```

This is the ISR called:

```
void isr(){
// Read payload data
digitalWrite(CSN_pin, LOW);
 data_in[0] = SPI.transfer(B01100001); //read payload register
 data_in[1] = SPI.transfer(B00000000);
 data_in[2] = SPI.transfer(B00000000);
 data_in[3] = SPI.transfer(B00000000);
 // etc
digitalWrite(CSN_pin, HIGH);

// flush RX
digitalWrite(CSN_pin, LOW);
 SPI.transfer(B11100010);//flush RX
digitalWrite(CSN_pin, HIGH);

// Read status register 0x07
digitalWrite(CSN_pin, LOW);
 SPI.transfer(0x07);
 reg7 = SPI.transfer(0x00);
digitalWrite(CSN_pin, HIGH);

reg7 |= B01000000; // RX_DR set bit 6
// write back to status register
digitalWrite(CSN_pin, LOW);
 SPI.transfer(0x20+0x07);
 SPI.transfer(reg7);
digitalWrite(CSN_pin, HIGH);
}

```

*Edit*: bit 6 of the status register is the `RX_DR` flag. If this is 1 (which is the case in the OP's example), then the data have not been received. Set bit 6 to clear the interrupt.

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


title: ModbusMaster.h - changing node

text:
# Question
Title: ModbusMaster.h - changing node
I'm using the ModbusMaster.h library on a project, with arduino-uno and a TTL/RS-485 converter, and the function has to identify the slave that it is communicating. The slaves goes from 1 to 16. After I've begun the connection,

```
ModbusMaster node(1);
node.begin(9600);

```

I have to send a message, and if this massage returns an error, I have to change the slave number, until I got an valid answer. But I didn't find any functions to close this connection, or to delete it, I even have tried,

```
delete &node;

```

but it didn't work. I'm trying to close this connection so I could begin another one with another node, because I didn't find a function to change the slave number.

# Answer
Maybe this question is too old and the API has changed, so my answer is reference.

The ModbusMaster constructor does not accept parameters.

From reading the source code, the method `begin(uint8_t slave, Stream &serial)` just initializes variables and can be called again with a new `slave` value without the need to destroy the ModbusMaster object.

Reference:

\[1\] https://github.com/4-20ma/ModbusMaster/blob/master/src/ModbusMaster.cpp, line 61.
> 2 votes

---
Tags: arduino-uno, modbus
---


# Question
Title: How to establish a connection between an Arduino and a web server via ESP8266
I'm working on a IOT project where three or more IOT device communicates with a web server. The IoT device will have **Arduino UNO** which is connected to a **ESP8266** so internet access is available. Arduino UNO reads **current sensor** data and post it to a website that I built and I also want to control a **single relay switch** from the same website. I am a beginner and most project I find is only single directional communication or making ESP8266 as web server. Please point me to right Direction.

I was able to post sensor data to thingspeak.com. I was also able to control The relay switch from a website but only separately. I was not able to make it work when I combined the two.

Directions:

1. How to build **web APIS** to send and receive data to **Arduino UNO via esp8266**?
2. How to send data and check the received data in **Arduino UNO VIA esp8266**?
3. Can I send and receive data in JSON format **Arduino UNO**?
4. How can the **Arduino UNO** filter required data from the received json?
5. Is this project possible without Arduino and just by programming the ESP8266 module?

I know basic HTML, Basic CSS, Basic JavaScript, Basic Nodejs, json and a tiny bit of JQuery.

# Answer
> Is this project possible without Arduino and just by programming the ESP8266 module?

Yes if you use ESP-12 or an esp8266 dev board like Wemos or NodeMCU. The problem could be the current sensor. I would recommend to read it with I2C ADC module, because the esp8266 A0 can read only to 1 V and is shared with WiFi functions. Wemos boards use a circuit to read analog until 3.3 V, but it doesn't help much.

> How to build web APIS to send and receive data to Arduino UNO via esp8266?

Run your Web server in Internet and let the esp8266 and clients communicate over it. But think about security.

For accessing a Web server from Arduino or esp8266 see the WebClient example of networking libraries.

> How to send data and check the received data in Arduino UNO VIA esp8266?

For Arduino with esp8266 as network adapter connected to Serial you can use AT firmware in esp8266 and WiFiEsp library in Arduino. Or you can have a sketch for the esp8266 with Arduino esp8266 core package and your own protocol over Serial to communicate between esp8266 and Uno. And there are firmwares for esp8266 written as esp8266 sketch, which you can use with corresponding Arduino library (WiFiLink, WiFiSpi).

> Can I send and receive data in JSON format Arduino UNO? How can the Arduino UNO filter required data from the received json?

ArduinoJson library helps with processing the JSON format. Amount of RAM could be a problem on Uno.
> 2 votes

---
Tags: arduino-uno, esp8266, wifi, web-server, http
---


title: ESP8266 01 wifi module

text:
# Question
Title: ESP8266 01 wifi module
I have a weird problem , as I.m trying to connect to esp8266 01 with Arduino Uno when i try sending commands from the serial it doesn't work but if i send it in a function in the setup phase it works

```
#include <SoftwareSerial.h>

SoftwareSerial esp8266(2, 3);

void setup()
{
Serial.begin(9600);
esp8266.begin(9600);
delay(1000);
//sendData("AT", 1000);
//sendData("AT+CWMODE=1", 1000);
}

void loop() {
// put your main code here, to run repeatedly:
if(esp8266.available()) // check if the esp is sending a message
  {
      while(esp8266.available())
      {
          // The esp has data so display its output to the serial window
          char c = esp8266.read(); // read the next character.
          Serial.write(c);
      }
  }
  if(Serial.available())
  {
    delay(1000);
    String command="";
    while(Serial.available()) // read the command character by character
    {
        command+=(char)Serial.read();
    }
    esp8266.println(command); // send the read character to the esp8266
  }
}

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

```

# Answer
> 0 votes
I take your code as a test sketch and will not comment on the terrible way you read Serial input.

The AT firmware requires \r\n as command ending characters. You can set them in Serial Monitor as option LN & CR, but then use `print` to send the command to esp8266.

Or set in Serial Monitor "No line ending" and let in sketch the `println` to send the command. `println` adds \r\n to printed string.

If you had only "New line" set in Serial Monitor and used `println` the resulting command was for AT firmware disturbing "AT\n\r\n".

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


title: ESP8266 disconnects after few hours

text:
# Question
Title: ESP8266 disconnects after few hours
My system looks like this:

ESP8266 is connected to Arduino Uno (2, 3 pins) and a relay's data input to Arduino's pin 12 and power for relay is provided from another source.

Arduino gets data from server and switches on/off relay according to that signal. This system works perfectly for few hours and then suddenly crashes. In my WiFi console I have:

> wlan0: STA 2c:3a:e8:4e:bf:70 WPA: pairwise key handshake completed (RSN) wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0: AP-STA-DISCONNECTED 2c:3a:e8:4e:bf:70 wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: associated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: disassociated wlan0: STA 2c:3a:e8:4e:bf:70 IEEE 802.11: associated wlan0: AP-STA-CONNECTED 2c:3a:e8:4e:bf:70

I have read this Arduino question, but circuit diagram similar to that one. I get power from my PC to run Arduino.

This is my Arduino code :

```
#include "WiFiEsp.h"

// Emulate Serial1 on pins 6/7 if not present
#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(2, 3); // RX, TX
#endif

char ssid[] = "RPi";            // your network SSID (name)
char pass[] = "raspberry";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "192.168.50.1";

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 10000L; // delay between updates, in milliseconds
int testLED = 12;
// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  pinMode(testLED, OUTPUT);
  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");

  //printWifiStatus();
}

void loop()
{
  // if there's incoming data from the net connection send it out the serial port
  // this is for debugging purposes only
  while (client.available()) {
    char c = client.read();
    //code to run relay
    if (c == '#')
    {
      while (client.available() == 0) { } // Do nothing while we wait for the next value

      // reading the second charactor
      c = client.read();
      if (c == '1') {
        Serial.println("On");
        digitalWrite(testLED, HIGH);
        delay(600000);
      }
      else if (c == '0') {
        Serial.println("Off");
        digitalWrite(testLED, LOW);
        delay(600000);
      } //end of C cheking if-else
    }  //end of first charactor # if
    //end of replay code
  }
  // if 10 seconds have passed since your last connection,
  // then connect again and send data
  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server
void httpRequest()
{
  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    // send the HTTP PUT request
    client.println(F("GET /simple.txt HTTP/1.1"));
    client.println(F("Host: localhost"));
    client.println("Connection: close");
    client.println();
    // note the time that the connection was made
    lastConnectionTime = millis();
  }
  else {
    WiFi.begin(ssid, pass);
    Serial.println("Reconnecting again");
  }
}

```

# Answer
> 2 votes
After quite long research I found the solution for my problem.

I did some changed power connection to ESP-8266.

ESP 8266 --------- Arduino Uno

`Vcc` ---------\> 3.3v

`CH_PD` ---------\> 5v divided into 3.3v using resistors

`RX` ---------\> PIN-2 via 3.3v regulator.

After this configuration, my system was working perfectly for days. Thanks for the all suggestions given.

# Answer
> 3 votes
As long as I know you need at least 170mA to power the esp8266 also you need 100-200mA for the arduino and 100mA for the relay so I recommend to use a 1A power supply and solder some capacitors on the 5V and 3.3V rails. Also if your Wi-Fi is giving a ip address that is limited for certain time for example 1-2 hours you need to expand that time for your needs.If it disconnects the esp will lose its IP address and try to recover for example on my NODE MCU it works well for weeks. It also depends on your library (I am using ESP8266WiFi.h). Anyway I recommend to try the WebServer example for testing if the issue is in your code.

# Answer
> 0 votes
After four months of searching - Just use 3.3 V with 1.5 or 2 A and everything will work correctly.

---
Tags: arduino-uno, esp8266, power, relay, iot
---


# Question
Title: Using ATiny102 as HID device(emulating mouse)
I am trying to make my own mouse/keyboard from an attiny (it doesn't have to be attiny102 as the title suggests). I have read many articles on this subject: some are using v-usb library.But I understand this is for arduino uno/leonardo.I want to use an attiny with the least amount of electronic parts attached to it(no external oscillator-only the internal one..etc.). All the articles I read said that arduino can't be used as a host usb device but this applies only for it's built-in micro-usb. Can't I just emulate the HID device using digital pins on my attiny? If this is possible where can you provide some well-documented source for the protocol used when communicating with the pc?

# Answer
I have build a HID midi keyboard with the hiduino lib which is base on LUFA. http://code.google.com/p/hiduino/w/list

I know LUFA is also capable to build a HID mouse device. But you need to switch to a bigger controller (i think). I used a 8u2 from atmel.

I used AVR Studio 6 to compile hiduino. Currently i have no link to the LUFA because the git page is gone. Maybe you find a mirror or a other webpage.
> 1 votes

# Answer
the only USB option for AVR microcontrollers without embedded USB, is VUSB which is somehow rare in Arduino; despite some aged libraries around :

https://blog.petrockblock.com/2012/05/19/usb-keyboard-with-arduino-and-v-usb-library-an-example/ https://github.com/gloob/vusb-for-arduino

but if you can rely on atmel studio, the very rich examples of VUSB itself are enough. I made a HID presenter (just two keys to go back and forth on powerpoint slides) using only an attiny24 which is super cheap. the codeandlife blog is a good start for VUSB. it also has a HID mouse example explained :

http://codeandlife.com/2012/02/11/v-usb-tutorial-continued-hid-mouse/
> 0 votes

---
Tags: arduino-uno, attiny, keyboard, mouse
---


title: SoftwareSerial with ESP8266

text:
# Question
Title: SoftwareSerial with ESP8266
I am communicating with ESP8266 using SoftwareSerial of Arduino UNO. I can successfully send AT commands and get response when communicating through the terminal. But if i **programmatically** send particular AT commands there is no response. For eg: I type AT in serial monitor I get OK But if i send the following through SoftwareSerial pins

```
mySerial.println("AT");

```

there is no response.

Can anyone tell what will be the solution as to how to send AT commands explicitly.

The sketch is

```
#include<SoftWareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

void setup() {
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  mySerial.begin(9600);
  mySerial.println("AT");
  delay(100);
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
}//setup

void loop()  {
  while (mySerial.available()>0 ) {
    char ch=mySerial.read();
    data.concat(ch);
    if(ch=='\n')
      Serial.println(data);
    data="";
  }
  while (Serial.available()>0 ) {
    mySerial.write(Serial.read());
    delay(100);
  }
}//loop

```

I am using Sparkfun Level Shifter to get 3.3V from 5V. The wiring is straightforward. ESP8266 Vcc and CH\_PD to 3.3V; GND to GND; Tx to Arduino 2(Rx) directly; Rx to Sparkfun 3.3V RXO LV side and Arduino 3(Tx) to RXI HV side) so that when Arduino transmits it gets stepped down to 3.3V and ESP8266 receives it. The wiring should be correct as it is working perfectly when AT commands are sent manually.

I tried everything of sending mySerial.write("AT/r/n"), mySerial.print("AT") mySerial.print("\r\n"), etc but nothing seems to work.

Is it that there is some problem with SoftwareSerial. But then how is it working if i send AT commands manually through terminal ?

# Answer
> 3 votes
I have been playing with an ESP8266 over the last couple of days with similar results. My conclusion was that it is very timing dependent.

If you build in (fairly large) delays into your code then you will find it works better. The delays are effectively what you are doing as you type in each new command.

I found, for example, that the `AT+CWJAP` (join access point) command takes quite a while, like 10 seconds or so.

Preferably don't use "actual" delays because they are blocking (unless you don't care about that). You could have a list of commands you want to send, and a system that pulls the next one out of the list when a certain time has elapsed.

If you use something like 5 to 10 second delays between commands you should get better results. At the very least, after sending one command, look for a confirmation string from the device (eg. `OK`, `ERROR` etc.).

# Answer
> 2 votes
Same problem here with this code.

Three step for me to make it work :

* Use method write() and not println()
* Send newline \n when talking to esp8266
* don't wait newline to print the response

```
esp8266Serial.write("AT\n");
delay(100);
while (esp8266Serial.available() > 0 ) {
  char ch = esp8266Serial.read();
  Serial.println(ch);
}

```

I hope it helps

# Answer
> 1 votes
It appears to me that when the ESP8266 sends a few characters to the Arduino, the initial version of the code always erases those characters (`data="";`) without ever printing anything to your serial monitor. So there is no way to tell whether the ESP8266 is sending anything or not.

To make it easier to debug, try printing *every* character from the ESP8266 to the serial monitor, whether or not it makes a complete message.

What do you see on the serial monitor with the following code?

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(2, 3); // RX, TX

String data = "";

void setup(){
// Open serial communications and wait for port to open:
  Serial.begin(9600);
  mySerial.begin(9600);
  mySerial.println("AT");
}//setup

void loop(){
  if( mySerial.available()>0 ){
    char ch=mySerial.read();
    data.concat(ch);
    Serial.print((int)ch, HEX); // debug: print *every* character, in hex.
    if( ch=='\n' ){
      Serial.println();
      // Use "F()" macro as recommended by
      // https://learn.adafruit.com/memories-of-an-arduino/optimizing-sram .
      Serial.print(F("complete message:"));
      Serial.println(data);
      data="";
      Serial.print(F("waiting for next message ..."));
      }
  }
  if( Serial.available()>0 ){
    mySerial.write(Serial.read());
  }
}//loop

```

# Answer
> 0 votes
Did you make sure that your lines end with \n\r?

Remember you need both newline characters to send over the line from the terminal.

# Answer
> -1 votes
The ESP8266 needs 115200 baud.

The example didn't run clean in my case until I increased the baud rate for the Arduino\<-\>Computer (USB) communication to 115200 baud as well. With 115200 on mySerial and 9600 on USB, an AT request of mine did not return an OK in most cases.

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


title: Keep on getting scandone

text:
# Question
Title: Keep on getting scandone
I have a node server with express and socket io behind nginx reverse proxy at AWS. I am try to connect remotely from my NodeMCU esp8266 through websocket io client to my server using WebSocketClientSocketIO (unsuccessfully). I am new and don't know what I am doing wrong. Following are my debug messages. I keep on getting scandone.

```
SDK:2.2.1(cfd48f3)/Core:2.4.2/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1-13-g163bb82)/BearSSL:6d1cefc
del if0
usl
mode : null
mode : sta(84:f3:eb:b7:4e:8c)
add if0

Connecting.....scandone
state: 0 -> 2 (b0)
.state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 1
cnt

connected with Zlink, channel 13
dhcp client start...
....ip:192.168.10.8,mask:255.255.255.0,gw:192.168.10.1
.
Connected to Zlink
IP address: 192.168.10.8

[SETUP] BOOT WAIT 4...
[SETUP] BOOT WAIT 3...
[SETUP] BOOT WAIT 2...
[SETUP] BOOT WAIT 1...
state: 5 -> 0 (0)
rm 0
scandone
scandone
scandone
scandone
scandone
.
.
.
.

```

\`

My sketch:

<pre><code>/*
 * WebSocketClientSocketIO.ino
 *
 *  Created on: 06.06.2016
 *
 */
#include <Arduino.h>

#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WebSocketsClient.h>
#include <Hash.h>
ESP8266WiFiMulti WiFiMulti;
WebSocketsClient webSocket;
const char *ssid = "MyWiFiName";
const char *password = "mypassword";
#define USE_SERIAL Serial
#define MESSAGE_INTERVAL 30000
#define HEARTBEAT_INTERVAL 25000
uint64_t messageTimestamp = 0;
uint64_t heartbeatTimestamp = 0;
bool isConnected = false;
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case WStype_DISCONNECTED:
            USE_SERIAL.printf("[WSc] Disconnected!\n");
            isConnected = false;
            break;
        case WStype_CONNECTED:
            {
                USE_SERIAL.printf("[WSc] Connected to url: %s\n",  payload);
                isConnected = true;
        // send message to server when Connected
                // socket.io upgrade confirmation message (required)
                webSocket.sendTXT("5");
            }
            break;
        case WStype_TEXT:
           USE_SERIAL.printf("[WSc] get text: %s\n", payload);
                        // send message to server
            // webSocket.sendTXT("message here");
            break;
        case WStype_BIN:
            USE_SERIAL.printf("[WSc] get binary length: %u\n", length);
                        hexdump(payload, length);
            // send data to server
            // webSocket.sendBIN(payload, length);
            break;
    }
};
void setup() {
  delay(1000);
    // USE_SERIAL.begin(921600);
    USE_SERIAL.begin(115200);
  WiFi.mode(WIFI_OFF);        //Prevents reconnection issue (taking too long to connect)
  delay(1000);
  WiFi.mode(WIFI_STA);        //This line hides the viewing of ESP as wifi hotspot
 startWiFi();
    USE_SERIAL.setDebugOutput(true);
    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();
      for(uint8_t t = 4; t > 0; t--) {
          USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
          USE_SERIAL.flush();
          delay(1000);
      }

   // WiFiMulti.addAP("SSID", "passpasspass");

    WiFi.disconnect();
    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
    }

```   // webSocket.beginSocketIO("192.168.0.123", 81);
      webSocket.beginSocketIO("http://www.myDomainName.com", 80, "/addr");
 //addr is address where I want to send messages
    //webSocket.setAuthorization("user", "Password"); // HTTP Basic Authorization
    webSocket.onEvent(webSocketEvent);
}
void loop() {
webSocket.loop();
testSend();
    if(isConnected) {
        uint64_t now = millis();
        if(now - messageTimestamp > MESSAGE_INTERVAL) {
            messageTimestamp = now;
            // example socket.io message with type "messageType" and JSON payload
            webSocket.sendTXT("42[\"messageType\",{\"greeting\":\"hello\"}]");
        }
        if((now - heartbeatTimestamp) > HEARTBEAT_INTERVAL) {
            heartbeatTimestamp = now;
            // socket.io heartbeat message
            webSocket.sendTXT("2");
        }
    };
};
void startWiFi() {
   WiFi.begin(ssid, password);
  USE_SERIAL.println("");
  USE_SERIAL.print("Connecting");
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    USE_SERIAL.print(".");
  };
  //If connection successful show IP address in serial monitor
  USE_SERIAL.println("");
  USE_SERIAL.print("Connected to ");
  USE_SERIAL.println(ssid);
  USE_SERIAL.print("IP address: ");
  USE_SERIAL.println(WiFi.localIP());  //IP address assigned to your ESP
  };
void testSend(){
   webSocket.sendTXT("Hello from esp");
   delay(1000);
  };
`
My code on node server where I am trying to collect messages from esp8266 is very simple as bellow:

socket.on('addr1', function (req,res) {
   console.log(req);
   });
</code></pre>

# Answer
> 1 votes
Try to use your Local IP as your client WebSocket.

```
...
...
const char* host = "192.168.x.x";
WifiClient wificlient;
...
...

void setup(){
  ...
  ...
  startWiFi();
  //WiFi.mode(WIFI_OFF);
  //WiFi.disconnect();
  if(!wificlient.connect(host, 80)){
    Serial.println(F("connection failed! "));
    return;
  }
  client.setClient(wificlient);
  ...
  ...
}

```

also add your host on the express NodeJS. I found a issue like your this

```
...
...
var http = require('http').Server(app);
var io = require('socket.io')(http);
var host = "192.168.x.x";
var port = "80";
...
...
socket.emit("<your-text>");
server.listen(host, port, function(){
  console.log("listening on http://"+host+":"+host+" ");
});
...
...

```

Hope this helps.

# Answer
> 0 votes
in the sketch 'simple WiFi begin() is mixed with WiFiMulti system. first the sketch connects to AP and then disconnects and starts WiFiMulti. but:

no AP is configured for WiFiMulti to connect

---
Tags: esp8266, nodemcu, node.js
---


title: Elegoo Nano timer prescaler problem

text:
# Question
Title: Elegoo Nano timer prescaler problem
I am trying to use Timer2 on an Elegoo Nano to produce a "tick" interrupt every 10uS. My plan was to set Timer2 to CTC mode with a /8 prescaler (to get a timer clock of 2MHz from the 16MHz chip clock) and a compare value of 19 (to reset the timer every 20 counts) which should trigger the compareA ISR at 100KHz (every 10us). The problem is that only prescale values of 64 or greater work as expected. Setting the prescaler to any value lower than 64 actually results in the "tick" interval getting much longer (10 times the interval or more). I have carefully studied the ATmega628 datasheet to see if I am configuring every register correctly, but I don't see anything wrong with what I am doing. Here is my code...

```
void initTimer() {

    // ---Disable interrupts during timer initialization
    cli();

    // ---Counter compare value (make CTC interrupt fire every 10uS)
    OCR2A = 19;

    // ---Clear TCCR A register (not used)
    TCCR2A = 0;

    // ---Enable CTC mode with divide-by-8 prescaler
    TCCR2B = _BV( WGM22 ) | _BV( CS21 );

    // ---Enable Timer2 CTC interrupts for compare A match
    TIMSK2 |= _BV( OCIE2A );

    // ---Initialize timer 2 to zero (not really needed in my situation)
    TCNT2 = 0;

    // ---Turn interrupts back on
   sei();
}

SIGNAL( TIMER2_COMPA_vect ) {

    /*
    ** This should execute every 10uS, but for prescaler values
    ** below 64 the interval is many times longer than expected.
    */
}

```

Can anyone point out my mistake?

# Answer
> 0 votes
Ok, I figured it out. It wasn't my timer initialization that was wrong, it was when I was doing it. Although I didn't show it in my original code sample, my initialization function actually returns a dummy boolean value so I could call it automatically if the .cpp file containing the function and the ISR is included in the project, like this...

```
bool initTimer() {

    // ---Set up the timer for CTC interrupts with a 10uS period
    ---
    ---
    ---

    // ---This return value is necessary, but ignored
    return true;
}

bool dummy = initTimer();

```

That final line calls initTimer() during Arduino boot just by including this source file in the project. It's a nice way to "auto-configure" utility objects without needing to explicitly call an initialization function. The boolean dummy return value from initTimer() is needed since C/C++ compilers choke on calling functions this way without storing a return value.

```
void initTimer() {

    // ---Do stuff...
}

// ---The compiler can't digest this...
initTimer();

```

Anyway, I have used this technique many times over several decades in desktop and mobile applications, so I did it in this Arduino project without giving it too much thought, but I failed to consider that it would execute the timer2 initialization BEFORE the Arduino setup routines. Anything I did to timer2 was being overwritten by the Arduino boot code which ran after my initTimer() function. My initialization was having some effect on the operation of timer2 because the Arduino boot setup assumes the timer2 config registers are starting off empty (zeroed) so it just sets config bits without clearing everything first. Any bits I turn on stay on, but Arduino boot up sets additional bits so the resulting timer configuration is unpredictable. The solution was simple... call the initTimer() function from the standard Arduino setup() function instead to ensure it executes LAST.

# Answer
> 2 votes
> Can anyone point out my mistake?

Your mistake is in thinking that it's possible to do more than you can within a 10uS period.

At 16MHz each instruction takes 63ns (for single-clock instructions). 10nS gives you a maximum of (10,000 / 63) 156 assembly instructions. Into that you have to fit the preamble and postamble to store the registers to the stack and retrieve them again.

The remaining clock cycles (maybe no more than 100) won't give you much time to do complex things. And given that many of the Arduino API calls are quite heavyweight, even just something as "simple" as a `digitalWrite()` can overflow that many times over.

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


title: ESP8266 SPIFFS not saving correctly?

text:
# Question
Title: ESP8266 SPIFFS not saving correctly?
Hey all I am having some issues with the SPIFFS for this Wemos D1 mini ESP8266 controller.

This is my Arduino sketch:

```
#include <FS.h>
#include <ArduinoJson.h>

struct RGBLA {
  uint8_t R;
  uint8_t G;
  uint8_t B;
  uint8_t L;
  uint8_t A;
};

void setup() {
  if (!SPIFFS.begin()) {
    Serial.println("error while mounting filesystem!");
  } else {
    // put your setup code here, to run once:
    RGBLA returnedVars = readSPIFFS();

    Serial.begin(115200);
    Serial.println();
    Serial.println("Starting...");

    Serial.println("readSPIFFS 1");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    Serial.println("==================================");

    returnedVars = saveToSPIFFS(25,77, 107, 250, 155, false);
    Serial.println("saveToSPIFFS #1");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    Serial.println("==================================");

    returnedVars = saveToSPIFFS(205,17, 68, 50, 15, true);
    Serial.println("saveToSPIFFS #2");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    returnedVars = readSPIFFS();
    Serial.println("readSPIFFS 2");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    Serial.println();
    Serial.println("END!");
  }
}

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

RGBLA saveToSPIFFS(uint8_t R, uint8_t G, uint8_t B, uint8_t L, uint8_t A, bool saveA) {
  File configFile = SPIFFS.open("/config.json", "w+");

  if (configFile.size() > 3072) {
    Serial.println("Config file size is too large.");
  } else {
    Serial.print("Writing json to Config file...");

    StaticJsonBuffer<200> jsonBuffer;
    JsonObject& json = jsonBuffer.createObject();

    //Get the old value and save it
    RGBLA returnedVars = readSPIFFS();

    Serial.println("Old Values?");
    Serial.print("R: ");
    Serial.println(returnedVars.R);
    Serial.print("G: ");
    Serial.println(returnedVars.G);
    Serial.print("B: ");
    Serial.println(returnedVars.B);
    Serial.print("L: ");
    Serial.println(returnedVars.L);
    Serial.print("AmbientLight: ");
    Serial.println(returnedVars.A);

    if (saveA) {
      //Save Ambient Light data
      json["R"] = returnedVars.R;
      json["G"] = returnedVars.G;
      json["B"] = returnedVars.B;
      json["L"] = returnedVars.L;
      json["A"] = A;

      //Now save the new data
      returnedVars.A = A;
    } else {
      //Save RGBL data
      json["R"] = R;
      json["G"] = G;
      json["B"] = B;
      json["L"] = L;
      json["A"] = returnedVars.A;

      //Now save the new data
      returnedVars.R = R;
      returnedVars.G = G;
      returnedVars.B = B;
      returnedVars.L = L;
    }

    json.printTo(configFile);
    configFile.close();

    //Read new saved values into struct
    //returnedVars = readSPIFFS();
    return returnedVars;
  }
}

RGBLA readSPIFFS() {
  bool exist = SPIFFS.exists("/config.json");

  if (exist) {
    Serial.println("YAY!");
  } else {
    Serial.println("Boo!");
  }

  File configFile = SPIFFS.open("/config.json", "r");
  std::unique_ptr<char[]> buf(new char[configFile.size()]);
  configFile.readBytes(buf.get(), configFile.size());
  DynamicJsonBuffer jsonBuffer;
  JsonObject& json = jsonBuffer.parseObject(buf.get());
  RGBLA returnedVars;

  String debugLogData;
  json.printTo(debugLogData);

  Serial.println("===============");
  Serial.println(debugLogData);
  Serial.println("===============");
  returnedVars.R = json["R"];
  returnedVars.G = json["G"];
  returnedVars.B = json["B"];
  returnedVars.L = json["L"];
  returnedVars.A = json["A"];

  configFile.close();

  return returnedVars;
}

```

And this is the console output:

```
Starting...
readSPIFFS 1
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25
==================================
Writing json to Config file...YAY!
===============
{}
===============
Old Values?
R: 0
G: 0
B: 0
L: 0
AmbientLight: 0
saveToSPIFFS #1
R: 25
G: 77
B: 107
L: 250
AmbientLight: 0
==================================
Writing json to Config file...YAY!
===============
{}
===============
Old Values?
R: 0
G: 0
B: 0
L: 0
AmbientLight: 0
saveToSPIFFS #2
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25
YAY!
===============
{"R":0,"G":0,"B":0,"L":0,"A":25}
===============
readSPIFFS 2
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

END!

```

As you can see, the first **old values** has all **0's** which is incorrect. **AmbientLight** should be **25** at that point since **readSPIFFS 1** has **25**. So this should read:

```
Old Values?
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

```

**saveToSPIFFS #1** is sending values **25, 77, 107, 250, 155 and false** which then outputs correctly as:

```
R: 25
G: 77
B: 107
L: 250
AmbientLight: 0

```

But this time **AmbientLight** should still be **25** since it was sent **false**. It should have taken the **old value (25)** and placed it into the newer save.

```
R: 25
G: 77
B: 107
L: 250
AmbientLight: 25

```

Moving on to **saveToSPIFFS #2** the values again are incorrect. The **AmbientLight** however is correct here. Instead of this output:

```
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

```

it should be gathering the **4** previous **old values**:

```
R: 25
G: 77
B: 107
L: 250
AmbientLight: 25

```

The json after this should not be this:

```
{"R":0,"G":0,"B":0,"L":0,"A":25}

```

It should be this:

```
{"R":250,"G":77,"B":107,"L":250,"A":25}

```

And lastly, the output of **readSPIFFS 2**:

```
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

```

Is incorrect. It should output:

```
R: 25
G: 77
B: 107
L: 250
AmbientLight: 25

```

Then after a **reset** it should have that and not the below for **readSPIFFS 1**:

```
R: 0
G: 0
B: 0
L: 0
AmbientLight: 25

```

So, where am I messing up here?

**UPDATE**

```
struct RGBLA {
  uint8_t R;
  uint8_t G;
  uint8_t B;
  uint8_t L;
  uint8_t A;
};

void setup() {
   RGBLA returnedValues = readSPIFFS();

   Serial.println("readSPIFFS 1");
   Serial.print("R: ");
   Serial.println(returnedVars.R);
   Serial.print("G: ");
   Serial.println(returnedVars.G);
   Serial.print("B: ");
   Serial.println(returnedVars.B);
   Serial.print("L: ");
   Serial.println(returnedVars.L);
   Serial.print("AmbientLight: ");
   Serial.println(returnedVars.A);

   returnedValues = saveToSPIFFS(205, 17, 68, 50, 15, false);

   Serial.println("saveToSPIFFS 1");
   Serial.print("R: ");
   Serial.println(returnedVars.R);
   Serial.print("G: ");
   Serial.println(returnedVars.G);
   Serial.print("B: ");
   Serial.println(returnedVars.B);
   Serial.print("L: ");
   Serial.println(returnedVars.L);
   Serial.print("AmbientLight: ");
   Serial.println(returnedVars.A);
}

RGBLA readSPIFFS() {
   RGBLA returnedVars;
   File configFile = SPIFFS.open("/config.json", "r");

   if (configFile ) {
     Serial.println("YAY!");
     configFile.readBytes((byte*) &returnedValues, sizeof(RGBLA));
     configFile.close();
   } else {
     Serial.println("Boo!");
   }

   return returnedValues;
}

RGBLA saveToSPIFFS() {
   File configFile = SPIFFS.open("/config.json", "w+");

   if (configFile.size() > 3072) {
     Serial.println("Config file size is too large.");
   } else {
     Serial.print("Writing to Config file...");

     //Get the old value and save it
     RGBLA returnedVars = readSPIFFS();

     Serial.println("Old Values:");
     Serial.print("R: ");
     Serial.println(returnedVars.R);
     Serial.print("G: ");
     Serial.println(returnedVars.G);
     Serial.print("B: ");
     Serial.println(returnedVars.B);
     Serial.print("L: ");
     Serial.println(returnedVars.L);
     Serial.print("AmbientLight: ");
     Serial.println(returnedVars.A);

     if (saveA) {
       //Save Ambient Light data
       returnedVars.A = A;
     } else {
       //Save RGBL data
       returnedVars.R = R;
       returnedVars.G = G;
       returnedVars.B = B;
       returnedVars.L = L;
     }

     configFile.write((byte*) &returnedVars, sizeof(RGBLA));
     configFile.close();

     return returnedVars;
}

```

# Answer
You can write a struct to file as binary data. This example is from my project.

global data:

```
struct Stats {
  int heatingTime; // minutes
  int consumedPower; // watts
};

Stats statsData;

```

snippet from setup():

```
  File file = SPIFFS.open(STATS_FILENAME, "r");
  if (file) {
    file.readBytes((byte*) &statsData, sizeof(statsData));
    file.close();
  }

```

snippet from statsSave() function:

```
  File file = SPIFFS.open(STATS_FILENAME, "w");
  if (file) {
    file.write((byte*) &statsData, sizeof(statsData));
    file.close();
  }

```

your updated readSPIFFS should be:

```
RGBLA readSPIFFS() {

  RGBLA returnedVars;
  File configFile = SPIFFS.open("/config.json", "r");
  if (configFile ) {
    Serial.println("YAY!");
    configFile.readBytes((byte*) &returnedValues, sizeof(RGBLA));
    configFile.close();
  } else {
    Serial.println("Boo!");
  }
  return returnedValues;
}

```
> 2 votes

---
Tags: esp8266, arduino-ide, c++, json
---