title: Arduino baud rate 8 times too high?

text:
# Question
Title: Arduino baud rate 8 times too high?
I'm having a strange issue where in order to get the expected serial output on my serial monitor, I have to set the baud rate on my serial monitor to be 8 times higher than the rate that i set in my Serial.begin(). For example, Serial.begin(4800) works with a serial monitor baud rate of 38400.

The setup is an atmega328P and an atmega8u2 built up on a breadboard similar to an UNO R1. I followed Nick Gammon's tutorial and his scripts to flash the 328P with the bootloader (http://www.gammon.com.au/forum/?id=11637), and I used the DFU programmer (on OS X) to flash the 8u2. When I plug my computer into the USB connector on the breadboard, the device correctly shows up as an Arduino Uno in my computer's devices list using lsusb. I can also flash sketches to the 328P using the breadboard tutorial (https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard).

The fact that I get the expected results on my serial monitor (even though it's at the wrong baud rate) leads me to believe my hardware is set up correctly. I'm thinking that it could be a bit/byte confusion in the firmware, has anyone encountered something like this or have ideas? I currently can't flash sketches over the USB connector and I believe it is due to the baud rate mismatch.

# Answer
> 1 votes
There are two baud rates you need to diagnose. One is the baud rate the ATMega8U2 runs at, and the other is the baud rate the ATMega328P runs at.

You need to work out which one is being calculated wrong:

* The ATMega8U2's baud rate is set by the USB connection when you open the port
* The ATMega328P's baud rate is set by your sketch

Obviously, the two have to match. However, a baud rate isn't just set as a number, it's calculated as a fraction of the CPU clock.

If the CPU clock on just one of the chips is different to what the firmware or sketch expects then the calculation for the baud rate will be wrong.

An example:

Your ATMega328P is expected to be running at 1MHz - however, the fuse settings have it set to run from the internal 8MHz clock. That means everything on that chip will run 8× faster than expected, so you have to compensate with a lower baud rate.

Another example:

Your ATMega8U2 is expected to be running at 16MHz - however, the fuse settings have it set to run at 2MHz. That means everything on that chip (except the USB which is clocked separately) will run 8× slower than expected, so you have to compensate on the ATMega328P with a lower baud rate.

So check the fuse settings on both chips. Make sure they are set to the right speeds for your firmware and boards.txt file settings.

Also, you should look at getting a cheap oscilloscope or logic analyser. That would allow you to monitor precisely what is going on with the communication between the two chips and work out if the baud rate is actually 8× faster than expected (ATMega8U2 at fault), or the normal speed but you have to specify it as a lower number (ATMega328P at fault).

---
Tags: arduino-uno, usb, baud-rate, breadboard
---


title: Tx Rx Arduino uno

text:
# Question
Title: Tx Rx Arduino uno
first of all let me thank you all , you have been of great help. So, my problem is the next , i have note counter machine i need to read the data from the machine to the arduino , as bytes or ascii , just some readble data . The machine is connected on the arduino via 2 pins , tx and rx and the data i am getting is not readble and kind of wierd , and one more question do i need some kind of serial shiled or no ?Because right now it is connected with just 2 wires . Thank you

```
#include <AltSoftSerial.h>

// AltSoftSerial always uses these pins:
//
// Board          Transmit  Receive   PWM Unusable
// -----          --------  -------   ------------
// Teensy 3.0 & 3.1  21        20         22
// Teensy 2.0         9        10       (none)
// Teensy++ 2.0      25         4       26, 27
// Arduino Uno        9         8         10
// Arduino Leonardo   5        13       (none)
// Arduino Mega      46        48       44, 45
// Wiring-S           5         6          4
// Sanguino          13        14         12

AltSoftSerial altSerial;

void setup() {
  Serial.begin(9600);
  while (!Serial) ; // wait for Arduino Serial Monitor to open
  Serial.println("AltSoftSerial Test Begin");
  altSerial.begin(9600);
}
byte rx_byte =0 ;
char text ;
char hex;
void loop() {
  if (altSerial.available()) {
    // get the byte from the software serial port

   rx_byte = altSerial.read();
    // send a byte to the software serial port
    //altSerial.println(text);
  Serial.print(rx_byte, HEX);

}
     //Serial.println("TUKA SUM");
      //text = altSerial.read();

    //hex=(text);

  //Serial.print(text);
    //Serial.write(text);
  // Serial.println(text);

```

# Answer
> 0 votes
The 9-pin port is designed for connecting to a printer. It uses the RS-232 protocol, not UART.

You cannot connect it directly to an Arduino - you must connect it via a MAX232 adaptor board.

**Disconnect the cable immediately - the voltage levels of RS-232 are likely to do permanent damage to the Arduino.**

---
Tags: arduino-uno
---


# Question
Title: ESP8266WebServer how to parse Json payload in post request that is bigger than the ram
I need to post a big json to the nodemcu server which would be bigger than the ram's size

I am using esp8266werserver and arduinojson libraries. I know how to use arduinojson to parse huge json response from other servers by parsing the response as a stream using response.getstream() . I can reuse a small static buffer in the stack to parse the whole json in a loop which performs really well.

But when I use nodemcu as a server, I can't find any similar method in the ESP8266WebServer to allow me to process json response as a stream. All I can only do is to read the string file in server.arg("plain") which may crash as the string may get bigger than the ram.

Is there a quick and dirty workaround? I look at the source in parsing.cpp there is a readBytesWithTimeout method that seems to be responsible to actually parsing the response stream. I am wondering if I may override this function to do what I need but I don't know how.

https://github.com/esp8266/Arduino/blob/master/libraries/ESP8266WebServer/src/Parsing.cpp

# Answer
The ESP8266WebServer library can process only a HTML-Form POST request of application/x-www-form-urlencoded or mulripart/ content type.

You could sent the JSON as multipart 'upload' to save it to file, but it would require to build the multipart format of the POST body.

If you want to process POST with application/json content type, you could make a simple web server implemented with WiFiServer.
> 1 votes

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


title: expected ')' before executarAcao

text:
# Question
Title: expected ')' before executarAcao
here is the code:

```
#define pinSom 7
#define pinRele1 2
#define pinRele2 3
#define tempoMaximoDeUmaPalma 150 //milisegundos
#define tempoMaximoEntrePalmas 500 //milisegundos

int contaPalmas = 0;
long tempoEspera = 0;
long tempoEsperaEntrePalmas = 0;

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

void loop() {{
  // verifica o estado do sensor de som (ele fica normalmente com
  int sensorSom = digitalRead(pinSom) ;

  //se o sensor detectou palmas
  if (tempoEspera == LOW) {

      //espera um tempo para não detectar a mesma palma mais de uma vez
    tempoEspera = tempoEsperaEntrePalmas = millis();
    contaPalmas++;
  }else if ((millis() - tempoEspera) >= tempoMaximoDeUmaPalma)
     tempoEspera = 0;
  }

    //caso exceda o tempo maximo entre palmas, zera o contador de palmas

    {

    if ( (contaPalmas != 0) && ((millis() - tempoEsperaEntrePalmas)
    (i get the error here) executarAcao();
    contaPalmas = 0;
    TempoEsperaEntrePalmas = millis();

 }
}
void executarAcao()
{
   switch (contaPalmas) {
    case 2:
      digitalWrite(pinRele1, !digitalRead(pinRele1));
      break;
   }

```

# Answer
> 3 votes
You're missing closing brackets in the line above your error.

It compiles now, but I have no idea whether it works as you intend. Try forcing yourself to always open and close brackets when you begin one, and making sure to indent properly.

Also, Arduino code is case-sensitive.

```
#define pinSom 7
#define pinRele1 2
#define pinRele2 3
#define tempoMaximoDeUmaPalma 150 //milisegundos
#define tempoMaximoEntrePalmas 500 //milisegundos

int contaPalmas = 0;
long tempoEspera = 0;
long tempoEsperaEntrePalmas = 0;

void executarAcao()
{
  switch (contaPalmas) {
    case 2:
      digitalWrite(pinRele1, !digitalRead(pinRele1));
      break;
  }
}

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

void loop() {
  // verifica o estado do sensor de som (ele fica normalmente com
  int sensorSom = digitalRead(pinSom);

  //se o sensor detectou palmas
  if (tempoEspera == LOW) {
      //espera um tempo para não detectar a mesma palma mais de uma vez
    tempoEspera = tempoEsperaEntrePalmas = millis();
    contaPalmas++;
  }
  else if ((millis() - tempoEspera) >= tempoMaximoDeUmaPalma) {
     tempoEspera = 0;
  }
    //caso exceda o tempo maximo entre palmas, zera o contador de palmas
  else {
    if ((contaPalmas != 0) && (millis() - tempoEsperaEntrePalmas)) {
      executarAcao();
      contaPalmas = 0;
      tempoEsperaEntrePalmas = millis();
    }
  }
}

```

# Answer
> 1 votes
This error means you did not close a pair of brackets, either `{}` or `()`. The solution is to check through your code to make sure brackets are always in pairs.

---
Tags: arduino-uno
---


# Question
Title: How do I see underlying code and definitions inside Arduino IDE on MacOS X El Capitan
I'm a newbie to Arduino so please excuse the easy question and guide me to the appropriate sources or forums. I just bought an Arduino Uno Starter Kit that comes with the "Arduino Projects Book" by Scott Fitzgerald et al and I'm happily working my way through the projects. I downloaded the Arduino IDE (version 1.7.10) onto my mac and am turning on lights, etc. However, I'd like to see the underlying code. For example, I use the code "digitalWrite" to turn off/on LEDs. I'd like to see the code for this. I can imagine that it's just a write of 1 or 0 to a particular memory address, but I'd still like to see it. I was hoping there was a right-click-\>"Go To Definition", but I don't see it. I downloaded the Arduino IDE to my Downloads folder and run it just from there. It's called Arduino.app. I don't see a folder with .c and .h files as suggested in this post: Arduino IDE, Underlying Code and Libraries Maybe I'm missing them?

Also, is it possible to set a breakpoint?

Again, sorry if these are "obvious" questions. And I did look at the Arduino site without any success.

Thanks,

Dave

# Answer
> 1 votes
The simplest way is to look at the source on Github:

Can you set a breakpoint? No. The Arduino IDE and the bootloader don't support such functionality. To do that you need a real IDE (like Atmel Studio) and a hardware debugger.

# Answer
> -1 votes
Yes, they need a right-click-\>"Go To Definition"

Assuming the first appearance of a variable is the definition (variable declaration), use the following easily learnt "hack"..

Double click variable, then ^F, Esc, ^Home, ^G

..(where ^ = Ctrl).

---
Tags: arduino-uno, arduino-ide, debugging
---


# Question
Title: NodeMCU ESP8266 12E loses code after power is reconnected
I have uploaded a simple code to control a 8 channel relay by turning individual relays on and off When I upload the code it works properly, the code works properly and the relays turn on and off in the desired pattern. However when i disconnect the USB cable from my computer and reconnect it, the code isnt working anymore, there is no visible action happening. Is the code erased from memory after power is cut?

```
int pins[] = {D0, D1, D2, D4, D5, D6, D7, D8};
int i;

void setup()
{
  Serial.begin(115200);
  for(i=0;i<8;i++)
  {
    pinMode(pins[i],OUTPUT);
    digitalWrite(pins[i],HIGH);
  }
}
void loop()
{
  for(i=0;i<8;i++)
  {
    digitalWrite(pins[i],LOW);//Turns this relay on
    Serial.println(pins[i]);
//Turn the previous relay off
    if(i==0)
    {
      digitalWrite(pins[7],HIGH);
    }
    else
    {
      digitalWrite(pins[i-1],HIGH);
    }
    delay(700);
  }
}

```

My circuit:
NodeMCU | Relay
D0 IN1
D1 IN2
D2 IN3
D4 IN4
D5 IN5
D6 IN6
D7 IN7
D8 IN8
Vin VCC
GND GND

# Answer
> 2 votes
D3 (GPIO0) and D4 (GPIO2) both need to be high on startup for the user program to be executed. The relay board connected to those pins are preventing a sufficient high on those pins.

If you need to use those pins then try using a stronger pull-up resistor on those pins. Try 330-470 ohms.

Either that or you will need to add additional circuitry between the port pins and the relay driver. Also please be aware that this will place a high on the relay driver input and will try to turn on the relays. Your powerup conditions may not be what you expect.

# Answer
> 1 votes
Your code will block the loop for more than 5 seconds. For the NodeMcu I found that if the main loop is delayed for long time strange things will happen. So you may also try refactoring to get rid of the for loop and using a simple counter to toggle the relays in each iteration of the main loop. so that your main loop will only be blocked for less than a second.

---
Tags: nodemcu, flash
---


title: Adding POE to Ethernet Board

text:
# Question
Title: Adding POE to Ethernet Board
If I was to use the Arduino A000024, would I be able to add a POE MODULE to the board to get a Ethernet board with POE to run my arduino project?

# Answer
> 0 votes
If the pinout is what the Ethernet shield expects, then yes. The rows of holes at an odd angle are designed for a POE board similar to that. I can't vouch for whether the pinout is correct though. It *looks* ok, but it depends on the dimensions of the board whether it fits the existing pinout.

---
Tags: electronics, ethernet-shield
---


# Question
Title: How can I have code in a project that won't compile for Arduino?
I want to test the algorithms in my code without needing to send it to an actual Arduino board. I figured I could lay out my project like:

```
project/
    core.cpp      # core algorithms
    core.h        # header for core.cpp
    project.ino   # Arduino setup() loop() calling into core
    pc-main.cpp   # main(argv) calling into core

```

**However, when I do this, the Arduino IDE wants to compile `pc-main.cpp`, which won't work since it uses stdio and all that. What can I do instead?**

Is there a way to hide a file from the build, other than changing the extension which would inconvenience other editors and compilers? Is there a different standard approach to this kind of problem?

---

What I've thought of:

* I could put `pc-main.cpp` in another directory and have the build for it refer to the files in the Arduino project directory, but that seems awkward and I'd like a more elegant solution.
* I could symlink the `core.*` files into the Arduino project directory from elsewhere, but that would also be inelegant, and inconvenience Windows users should one want to compile the project.
* I could put an `#ifdef` around the contents of `pc-main.cpp`, but I haven't found a suitable `#define` to check for, other than board-specific ones.

I don't want a solution which requires extra steps for each build; the whole point of trying to do this is fast and easy development.

I would also prefer one which does not bring in a whole additional build system, testing framework, or IDE; for example, I found arduino\_ci and PlatformIO while researching this question. I'll switch to looking at such options if there *isn't* a good solution to the problem as I've stated it here.

---

\[My question is arguably the same as Project structure to build for PC and Arduino at a high level, but the question and answer there are broad and about organizing modules and not how to make the build actually work.\]

# Answer
I would use conditional compilation, like this:

```
#ifndef(ARDUINO)
// Non-Arduino code.
#endif

```
> 8 votes

---
Tags: arduino-ide, compile, build
---


title: Run piece of code based on a feature

text:
# Question
Title: Run piece of code based on a feature
I am an engineering student completely new at using Arduino so my following question might be silly but still. I do not think you'll need to get the entire code so I am only going to expose the idea. So basically, I would like a customer to choose a feature between three of them (let's name them 1, 2, 3). Depending on the feature he chose, the corresponding `setup()` and the corresponding `loop()` have to run. For example, if he chooses the second feature, in the main `setup()`, the `setup2()` has to run and in the main `loop()`, the `loop2()` has to run only. The other `setup()` functions and `loop()` functions have to do nothing. I first thought I could do this using switch cases but I am looking for another way to implement that as a teacher told me this method would take too much time.

```
void setup() {

      setup1(); //only runs if 1st feature chosen
      setup2();
      setup3();
}

void loop() {

      loop1(); //only runs if 1st feature chosen
      loop2();
      loop3();
}

```

And also, I wrote the three `setup()` and the three `loop()` in different files (of course, `setup1()` is in the same file as a `loop1()`, etc., ...). Is it possible to include them in the main file (for instance, like `<#include nameoffile.h`)?

# Answer
You probably want to do something like this:

```
typedef enum { FEATURE1, FEATURE2, FEATURE3 } Feature;

//implement these
Feature getFeatureFromUser(){}
void setup1(){}
void setup2(){}
void setup3(){}
void loop1(){}
void loop2(){}
void loop3(){}

void setup() {
  Feature f = getFeatureFromUser();

  switch (f) {
    case FEATURE1:
      setup1();
      while (true) {
        loop1();
        if (serialEventRun) serialEventRun();
      }
    case FEATURE2:
      setup2();
      while (true) {
        loop2();
        if (serialEventRun) serialEventRun();
      }
    case FEATURE3:
      setup3();
      while (true) {
        loop3();
        if (serialEventRun) serialEventRun();
      }
  }
}

//never reached
void loop() {}

```

It's good to know that there's no hard rules about how the Arduino functions should be used. Examples like this demonstrate how Arduino's standard requirements of `void setup()` and `void loop()` don't quite match every use case.

**EDIT**: The serialEventRun lines are normally called behind the scenes after each execution of Arduino's normal `loop()`, so adding them here will result in the standard behavior of serial events
> 1 votes

# Answer
If the feature selection is not at runtime but is at compile time you could do it like this:

```
#define FEATURE1 true   // Feature 1 is enabled

void setup() {
    #if FEATURE1
    setup1(); //only runs if 1st feature chosen
    #endif
    setup2();
    setup3();
}

void loop() {
    #if FEATURE1
    loop1(); //only runs if 1st feature chosen
    #endif
    loop2();
    loop3();
}

void setup1(void) {}
void setup2(void) {}
void setup3(void) {}

void loop1(void) {}
void loop2(void) {}
void loop3(void) {}

```
> 0 votes

---
Tags: sensors, sketch, variables
---


# Question
Title: avrdude: stk500_getsync(): not in sync: resp=0x00
I have arduino pro mini 5V, 16M ATMega328 and CP2102 USB to TTL. I've wired them like this:

When I try to upload a sketch to the arduino board I'm getting the following error:

```
avrdude: stk500_getsync(): not in sync: resp=0x00

```

The board type and the serial port are correct. The sketch also compiles successfully and I've installed the CP2102 drivers. I've noticed that even if I unplug all wires from the arduino board(and just leave the cp2102 connected to the PC), I'm getting the same error again. I'm using Windows 7.

Anyone else encountered the same issue?

# Answer
> 6 votes
It's hard to tell from your pictures, but are all the header pins soldered to the boards? If not, they need to be: there's no chance that the proper electrical connections will be made reliably if they're just inserted loosely into the holes.

# Answer
> 5 votes
This error means that the program responsible for uploading (avrdude) can not communicate with your arduino.

Did you reset the board just before programming? The reset pin of the arduino seems unconnected in your picture; so the board wouldn't be executing the bootloader when the serial cables expects it to.

Try either to reset the board manually just before programming, or connect the rst pin.

# Answer
> 3 votes
I solved this problem by connecting **DTR** signal from USB-converter to the pin which says **GRN** on the board (the one aside TXD). It was not obvious to find, but seen on ebay some arduino-dedicated-usb-programmer which seemed to be connected this way - so I took the chance. I do not get this error anymore and uploading works every time!!!

Cheers!

# Answer
> 1 votes
As some of the other answers have said, you may not have soldered on the header pins. You can't just push them into place and hope for the best. See my Pro Mini:

My soldering is reasonably neat, however you can see the solder come through to the other side.

Also see:

A lot of the issues in those threads apply to any Arduino.

# Answer
> 1 votes
To solve my sync issue I added a connection from USB serial adapter RST to ProMini DTR pin. I'm using Linux Mint 18 OS with Arduino IDE 1.8.5 - My other Arduino clones (UNO\_r3 and Nano) uses the CH340G chip so I knew I had working drivers. Sorry for the picture quality, my old camera and I don't know how to balance LED light bulbs. The pins from USB to ProMini are: (U)GND-(P)GND; (U)3V3-(P)no connection; (U)5V-(P)VCC; (U)TX-(P)TX; (U)RX-(P)RX; (U)RST-(P)DTR. Hope this helps. 73 AB1OP\_Ralph

# Answer
> 0 votes
This problem is caused by using the wrong USB cable. I have three cables, two of which work find, and one of which has this issue. The cables with the ferrite bead around them will work. The one cable that I have which works has a braided shield surrounding the conductors, and it is about 2 feet long. I have a 3 foot cable with no bead and no shield that exhibits this issue.

# Answer
> 0 votes
I had the exact same problem. I tried installing the IDE on another laptop and uploaded the program from that laptop. Problem solved. Then I came back to my laptop, uninstalled the IDE and re-installed it. It works.

However, I wasn't satisfied because I can't find the source of the problem... so I tried running everything again the same exact way.. I found the problem but am not sure if that can be the actual cause of it.

In my project, I needed to carry out serial communication between Arduino and MATLAB (GUI). In order to see/verify the output(type) of MATLAB (GUI) serial data, I used HYPERTERMINAL and also VIRTUAL SERIAL PORT EMULATOR. I noticed that every time hyperterminal is running or VSPE is running while my serial monitor is on, it screws up the uploading feature of the program. I'm not sure if it's because of the VSPE or HYPERTERMINAL, but reinstalling the IDE worked for me. :-)

# Answer
> 0 votes
This has happpened to me as well. I had a bluetooth/TTL unit wired to RX/TX, which are the same ports used by the usb connection to the computer (where transfer of the program happens), and all I had to do was disconnect RX to the BT unit when transferring the program.

# Answer
> 0 votes
{linux}

The solution for me was to set the correct USB port.

I had been previously working with my Uno on USB0.

I could not upload to my nano as I had it connected on USB1

In menu: Serial Port -\> /dev/ttyUSB1

# Answer
> 0 votes
I spent hours looking for a solution to the same error message. Everything was correct - Board chosen, COM port, everything.

I switched my TX and RX pins, and connected the tx and rx to each other, instead of them being switched (which I saw from a tutorial). Then I pressed the manual reset, held it down, and uploaded, then released while it read Uploading. It worked.

Hope this helps.

---
Tags: uploading, arduino-pro-mini
---


title: ESP8266 stuck in flash mode?

text:
# Question
Title: ESP8266 stuck in flash mode?
I have the setup described here: https://learn.adafruit.com/esp8266-temperature-slash-humidity-webserver/wiring

I currently have the reset pin set to float and the GPIO0 pin grounded, which should make it execute the uploaded program, but instead I get the flash mode output:

```
    writing flash
...................................................................................................................................................................................................................................................

```

How do I put it into execution mode?

# Answer
> 1 votes
I was stuck in a similar scenario. I managed to exit programming mode by floating GIPO0, then grounding RST for ~3 seconds, then floating it. If you power off the esp, and now turn it on, it should have exited programming mode. Powering it off is actually optional.

---
Tags: arduino-ide, esp8266, flash
---


title: Board Updating problems

text:
# Question
Title: Board Updating problems
I have updated Arduino AVR Boards in IDE and before I updated, ESP8266 boards were working, now after I updated, it says "Error downloading "URL for esp"" and no matter which website I listed inside the preference:

```
http://arduino.esp8266.com/stable/package_esp8266com_index.json
https://github.com/esp8266/Arduino/releases/download/2.3.0/package_esp8266com_index.json

```

None of them are being downloaded and I cannot program ESP8266. Can I get some help? Thank you.

# Answer
> 1 votes
If you are using windows 10 try installing from git followimg the instruction here.

https://arduino-esp8266.readthedocs.io/en/latest/installing.html

That was how I get it to work when I found updating it through the ide didn't work

---
Tags: esp8266
---


# Question
Title: ESP32 not seen by a network analyzer application in server mode
I have used the **scan wifi** and **blink** examples provided by Espressif, they are both working on the ESP32 using arduino ide.

However, I can not see my ESP( the SSID and signal strength) in the list of detected wifi when searching for it using a network analyzer app ( Net analyzer on android)

This was solved when I used the ESP as Access point. In Client mode the ESP is using the WIFI capability. But why it can not be seen by others?

why is the ESP32 Lolin getting hot only when it is in AP mode?

Thanks in advance

# Answer
> In Client mode the ESP is using the WIFI capability. But why it can not be seen by others?

The app is looking for access points. (if it is looking for SSID) And if you do not have the ESP set as an access point it will not be seen.

> why is the ESP32 Lolin getting hot only when it is in AP mode?

Because the radio is on all the time. It has to be available for a connection. When it is not an access point, the ESP goes into a sleep mode when it does not have any need to communicate.
> 1 votes

---
Tags: esp32
---


# Question
Title: Turn infrared LED on and off in order to simulate an infrared signal
**Note I am able to send and recieve IR signals. This question is only for purposes of learning.**

When using the existing library `#include <IRremote.h>` it is very simple to read and transmit infrared signals. **However I will like to send the signals myself with `digitalWrite(pin, HIGH);`**

## 1) Receive an infrared signal from a remote control in order to clone it and send it later with Arduino.

For this to work I have purchased an infrared LED.

I connect the left leg of the IR LED to pin 11, the middle leg to the ground and the right leg to 5 volts.

Then I upload the following sketch to arduino:

```
#include <IRremote.h>

int receiverpin = 11; // left leg of IR receiver is connected to this pin

IRrecv irrecv(receiverpin);
decode_results results;

void setup() {
  pinMode(receiverpin, INPUT);
  Serial.begin(9600);
  irrecv.enableIRIn();
}

void loop() {
  if (irrecv.decode(&results))
  {
    Serial.println(results.value, HEX);
    irrecv.resume();
    delay(150);
  }
}

```

When I run that and press the power button of my samsung remote control this is what I capture through serial:

```
Encoding  : SAMSUNG
Code      : E0E040BF (32 bits)
Timing[67]:
 +4500, -4500     + 550, -1650     + 550, -1700     + 550, -1700
 + 550, - 600     + 500, - 550     + 550, - 550     + 550, - 600
 + 550, - 550     + 550, -1700     + 550, -1650     + 550, -1700
 + 550, - 550     + 550, - 550     + 550, - 600     + 550, - 550
 + 550, - 550     + 550, - 600     + 550, -1650     + 550, - 600
 + 550, - 550     + 550, - 550     + 550, - 550     + 550, - 600
 + 550, - 550     + 550, -1700     + 550, - 550     + 550, -1700
 + 500, -1700     + 550, -1700     + 550, -1650     + 550, -1750
 + 500, -1650     + 550
unsigned int  rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};  // SAMSUNG E0E040BF
unsigned int  data = 0xE0E040BF;

```

**What is this supposed to mean. How can I conver this to 0s and 1s?**

## 2) Sending cloned signal from arduino.

Now if I want to power on my TV with arduino I will need a Infrared LED. I will connect pin 3 to the long leg of my LED and ground to the short leg. Once I pefrom that connection I will run this sketch:

```
#include <IRremote.h>

IRsend irsend;

void setup() {}

void loop() {

  irsend.sendSAMSUNG(0xE0E040BF, 32); //Power Code
  delay(1000); // try again in 1 second

}

```

**Note this code works and my TV powers on with my Arduino!**

## 3) Now my question

It was very simple to read and transmit infrared signals using `IRremote.h` header.The only thing I had to do was capture 0xE0E040BF that I got when reading the infrared signal and use that hex code on part 2. From reading on the internet I have researched that sending an IR signal is just turning and IR LED on and off very fast (38khz). How can I tranlate what I read:

```
 rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};

```

To 0s and 1s and then send that hard coded for puposes of learning.

Acording to this link: http://www.remotecentral.com/cgi-bin/codes/samsung/tv\_functions/

The infrared code to power on a samsung tv is:

```
0000 006d 0022 0003 00a9 00a8 0015 003f 0015 003f 0015 003f 0015 0015 0015
0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 003f 0015 003f 0015 0015
0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 003f 0015 0015 0015
0015 0015 0015 0015 0015 0015 0015 0015 0015 0015 0040 0015 0015 0015 003f
0015 003f 0015 003f 0015 003f 0015 003f 0015 003f 0015 0702 00a9 00a8 0015
0015 0015 0e6e

```

I have converted that to binary and it comes to be:

```
000000000000000000000000011011010000000000100010000000000000001100000000101010010000000010101000000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000010000000000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000011100000010000000001010100100000000101010000000000000010101000000000001010100000000000101010000111001101110

```

**Now every time I see a 0 I will power off the LED and every time I see a 1 I will power on the LED waiting about 10 microseconds in order to have a frequency of 38khz** This is how my sketch looks like:

```
int pinSend=3;
char data[1248] = "000000000000000000000000011011010000000000100010000000000000001100000000101010010000000010101000000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000111111000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000000101010000000000010101000000000001010100000000010000000000000000010101000000000001010100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000000000111111000000000001010100000000001111110000000000010101000000000011111100000000000101010000011100000010000000001010100100000000101010000000000000010101000000000001010100000000000101010000111001101110";
int waitTimeInMicroseconds = 5; // counter to try with different wait times in order to see what frequency works best

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

void loop() {

  Serial.print("Starting sending IR signal waiting ");
  Serial.print(waitTimeInMicroseconds);
  Serial.println(" microseconds");

  int len = sizeof(data);

  for(int i=0; i<len; i++)
  {
    if( data[i] == '0') // if 0 turn off LED
    {
      digitalWrite(pinSend,LOW);
    }
    else // else turn ON LED
    {
      digitalWrite(pinSend,HIGH);
    }

    delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds
  }

  Serial.println("Done! Is TV on??????");
  delay(1000); // wait 1 second for next atempt

  waitTimeInMicroseconds++; // next time try with different wait time

}

```

**When I run that code the TV does not turn on why? How can I hard code the 0s and 1s for purposes of learning?**

# Answer
Finally managed to figure it out without using any library. This is how I turn on my TV:

```
int pinSend=3;
int waitTimeInMicroseconds = 33; // counter to try with different wait times in order to see what frequency works best
unsigned int  rawData[67] = {4500,4500, 550,1650, 550,1700, 550,1700, 550,600, 500,550, 550,550, 550,600, 550,550, 550,1700, 550,1650, 550,1700, 550,550, 550,550, 550,600, 550,550, 550,550, 550,600, 550,1650, 550,600, 550,550, 550,550, 550,550, 550,600, 550,550, 550,1700, 550,550, 550,1700, 500,1700, 550,1700, 550,1650, 550,1750, 500,1650, 550};

int isOn =1;

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

void loop() {

    Serial.print("starting with ");
    Serial.println(waitTimeInMicroseconds);

    for(int jj=0; jj<16; jj++)
    {
    for(int i=0; i<67; i++)
    {
        if(isOn==0)    {
          isOn=1;

          int x=0;

          while(true)
          {
            digitalWrite(pinSend,HIGH);
            delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds
            digitalWrite(pinSend,LOW);
            delayMicroseconds(waitTimeInMicroseconds); // wait in microseconds

            x=x+waitTimeInMicroseconds+waitTimeInMicroseconds;

            if(x > rawData[i])
            {
              break;
            }
          }

        }
        else{
          isOn=0;
          delayMicroseconds(rawData[i]);
        }

    }
    }

    delay(2500);
    //waitTimeInMicroseconds++;

}

```
> 0 votes

---
Tags: pwm, frequency, infrared
---


# Question
Title: Capturing interrupt on both edges when it's set on RISING or FALLING
I've been trying to capture rising edge of an IR sensor output. This sensor's Vcc connected to Arduino 5V and it has a digital output pin. I've observed the digital output pin on an Oscilloscope. It's not noisy.

When I attach a rising edge interrupt on digital pin 2. It somehow captures both rising and falling edges. This response is the same for when it's set for FALLING or CHANGE.

I've tried code at below both on Arduino Uno and

```
volatile bool caughtAnInterrupt = false;

void setup() {

  Serial.begin (19200);

  pinMode(2, INPUT);

  attachInterrupt(digitalPinToInterrupt(2), test, RISING);
}

void loop() {

  if (caughtAnInterrupt){

    Serial.println("Rising edge detected");

    caughtAnInterrupt = false;
  }
}

void test() {

  caughtAnInterrupt = true;
}

```

# Answer
> 1 votes
I've solved the issue with the reply by eventHandler to another post. Here it is;

> The problem you are having is because the button glitches are producing many interrupts on each button press. You can find a good description and a way of solving it using hardware here.
>
> Let me explain, when you press the button, the mechanical contact will have a transcient state in which it will fluctuate ON-OFF for a short period of time. The same effect might happen when you release the button.
>
> One way of solving this problem is using a capacitor parallel to the load. Another "easier" way would be done by software. The idea is to set a fixed arbitrary time in which you don't allow new interrupts. You could use the millis() or micros() library to set this time. The code would look something like this.
>
> ```
> unsigned long lastInterrupt;
>
> void ngt()
> {
>
>   if(millis() - lastInterrupt > 10) // we set a 10ms no-interrupts window
>     {
>
>     state = !state;
>
>     lastInterrupt = millis();
>
>     }
> }
>
> ```
>
> This way you don't process new interrupts until 10ms have elapsed.
>
> Note: adjust the time to your requirements.

---
Tags: arduino-uno, arduino-mega, interrupt
---


# Question
Title: Eclipse Arduino Leonardo Pro Micro ATMega32U4 Programming Issue
Help Needed as I am little bit lost. I've procured a Pro Micro Board from sparkfun. Great little board and it work like clock work when using the standard Arduino Programming IDE.

Well Copied the code thru to the Eclipse Project, Hit compile and all seems well. But Trying to write the code to the device the following happens.

---

avrdude: Version 6.3-20171130 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch

```
     System wide configuration file is "C:/Users/vente/.arduinocdt/packages/arduino/tools/avrdude/6.3.0-arduino14/etc/avrdude.conf"

     Using Port                    : COM5
     Using Programmer              : avr109
     Overriding Baud Rate          : 57600
     AVR Part                      : ATmega32U4
     Chip Erase delay              : 9000 us
     PAGEL                         : PD7
     BS2                           : PA0
     RESET disposition             : dedicated
     RETRY pulse                   : SCK
     serial program mode           : yes
     parallel program mode         : yes
     Timeout                       : 200
     StabDelay                     : 100
     CmdexeDelay                   : 25
     SyncLoops                     : 32
     ByteDelay                     : 0
     PollIndex                     : 3
     PollValue                     : 0x53
     Memory Detail                 :

                              Block Poll               Page                       Polled
       Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
       ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
       eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00
       flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00
       lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
       calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
       signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

     Programmer Type : butterfly
     Description     : Atmel AppNote AVR109 Boot Loader

```

Connecting to programmer: .avrdude: butterfly\_recv(): programmer is not responding

avrdude: butterfly\_recv(): programmer is not responding avrdude: butterfly\_recv(): programmer is not responding avrdude: butterfly\_recv(): programmer is not responding avrdude: butterfly\_recv(): programmer is not responding avrdude: butterfly\_recv(): programmer is not responding Found programmer: Id = "F"; type = @ Software Version = �.u; Hardware Version = �. avrdude: butterfly\_recv(): programmer is not responding avrdude: butterfly\_recv(): programmer is not responding avrdude: error: buffered memory access not supported. Maybe it isn't a butterfly/AVR109 but a AVR910 device? avrdude: initialization failed, rc=-1 Double check connections and try again, or use -F to override this check.

avrdude: butterfly\_recv(): programmer is not responding avrdude: error: programmer did not respond to command: leave prog mode avrdude: butterfly\_recv(): programmer is not responding avrdude: error: programmer did not respond to command: exit bootloader

avrdude done. Thank you.

---

I've setup the Programming interface a as a Leonardo Board. AVR ISP.

For some reason It seems as if and it might be me that the usb does not reset? and go into programming mode.

Please Help

# Answer
I assume you use Eclipse Sloeber plugin for Arduino. For serial upload over USB using bootloader choose programmer `Default`. All other programmers are for flashing over ICSP.
> 1 votes

---
Tags: atmega32u4
---


# Question
Title: How to program a BSFrance LoRA32u4 from Arduine IDE 8.5?
I've bought a BSFrance LoRA32u4 from DIYmall on eBay UK.

https://bsfrance.fr/lora-long-range/1311-BSFrance-LoRa32u4-1KM-Long-Range-Board-Based-Atmega32u4-433MHz-LoRA-RA02-Module.html

I've copied the "bsfrance" directory (from the ZIP) into Arduino/hardware (on 64-bit Ubuntu 16.04).

Staring the Arduino IDE, I've selected the correct board (Tools\>\>Board\>\>BSFrance\>\>LoRA32u4).

I've selected the correct port Tools\>\>Port\>\>/dev/ttyACM1 (LoRA32u4).

Verifying a trivial sketch looks fine:

```
void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

```

Result:

```
Sketch uses 4104 bytes (14%) of program storage space. Maximum is 28672 bytes.
Global variables use 149 bytes of dynamic memory.

```

The USB device appears in `lsusb` as: `Bus 002 Device 077: ID 239a:800c`.

Clicking install causes a white LED to flicker for around ten seconds, but results in:

```
avrdude: error: buffered memory access not supported. Maybe it isn't
a butterfly/AVR109 but a AVR910 device?
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

```

or:

```
Couldn't find a Board on the selected port. Check that you have the
correct port selected.  If it is correct, try pressing the board's reset
button after initiating the upload.

```

or:

```
Found programmer: Id = "CATERIN"; type =

```

or:

```
Device code: 0x0d

```

or:

```
.   Software Version = 1.0; Hardware Version =

```

or:

```
An error occurred while uploading the sketch

```

How do I transfer code onto this board?

(I am new to Arduino, so I may be missing something obvious. I do have lots of experience programming vanilla ATMEGAs in C without the Arduino IDE.)

--

I have an AVRISP mkII - would burning a new boot-loader help, or just wreck the USB-serial on the device?

# Answer
I emailed BSFrance and they were very helpful, coming back with a few suggestions which I could not get to work.

I then tried the Sketch\>\>Upload Using Programmer with my AVRISPmkII and it worked. I'm guessing there is a bootloader/Linux issue with the board I bought, and bypassing it let me program the board.

It also works flawlessly with my Mac Mini.
> 0 votes

# Answer
I've had the same problem, but couldn't fix it with the "Upload using programmer". Instead i sound that the problem was that the serial connection kept dropping after a couple of seconds. My colleague, also on Ubuntu, had the same issue.

This fixed it for me: https://learn.adafruit.com/adafruit-arduino-ide-setup/linux-setup#udev-rules

The board registers as an Adafruit board on my system, and apparently the ModemManager is not too keen on that.

After running first command in the link and restarting, i could upload to the board from Arduino IDE with no errors.
> 1 votes

---
Tags: atmega32u4
---


title: How to set time for 15 seconds

text:
# Question
Title: How to set time for 15 seconds
When user used one password after close the servo the password will valid for 15 seconds then it will not work. Other 9 will be same process

Here is code I need just this to set

```
int locker = 13;
int lockerState = 0;
const int buzzer = 49;
String readString;

#include <Servo.h>
Servo myservo;
int pos = 0;

void setup() {
  Serial.begin(9600);
  pinMode(locker, OUTPUT);
  pinMode(buzzer, OUTPUT);
  myservo.attach(9);
}

void loop() {
  lockerState = digitalRead(locker);
  while (Serial.available()) {
    delay(3);
    char c = Serial.read();
    readString += c;
  }

  if (readString.length() >0) {
    Serial.println(readString);
    if ((readString == "2028") || (readString =="1234") || (readString =="1294") || (readString =="4795") || (readString =="5651") || (readString =="7616") || (readString =="5648") || (readString =="1487") || (readString =="7095") || (readString =="2554"))
    {
      digitalWrite(locker, HIGH);
      for (pos = 0; pos <= 180; pos += 1) {
      myservo.write(pos);
      delay(30);
      }
      delay(5000);
      digitalWrite(locker, LOW);
      /* for (pos = 180; pos >= 1; pos -= 1) {
      myservo.write(pos);
      delay(30);
      } */
      readString="";
    }
      /* else if (readString == "proceed") {
        digitalWrite(locker, HIGH);
        for (pos = 0; pos <= 180; pos += 1) {
        myservo.write(pos);
        delay(30);
        }
      digitalWrite(locker, LOW);
      readString="";
      } */
      if (readString == "decline") {
         digitalWrite(locker, HIGH);
         for (pos = 180; pos >= 0; pos -= 1) {
         myservo.write(pos);
         delay(30);
         }
      digitalWrite(locker, LOW);
      readString="";
      }

    else {
      tone(buzzer, 500);
      delay(1000);
      noTone(buzzer);
      delay(1000);
      readString="";
  }
 }
}

```

# Answer
In programming, there are many cases where designing data structures is more important than the code itself. Once you have a data structure that makes sense, the code flows very naturally. I think this is one of those cases, so let's start by looking at what data you have to store for each of your passwords:

* the password itself (let's call it the *code*)
* whether it has ever been used and, if so, whether it has expired
* if it has been used but has not expired yet: when it was used for the first time

This can be saved in an object with the following data fields:

```
const char * const code;
enum { UNUSED, USED, EXPIRED } status;
uint32_t first_use;  // valid if status == USED

```

Now think about what kind of *actions* you want to perform on such a password:

* you want to be able to test whether it matches some user entry
* you want check whether it can be used and, if so, take note that it is being used

Based on these requirements, I propose the following class:

```
const uint32_t PASS_LIFE_TIME = 15000;

class Password {
public:
    Password(const char *c)
        : code(c), status(UNUSED) {}
    bool matches(const char *entry) {
        return strcmp(code, entry) == 0;
    }
    void update() {  // expire if it needs to be
        if (status == USED && millis() - first_use > PASS_LIFE_TIME) {
            status = EXPIRED;
        }
    }
    bool use() {  // returns true on success
        if (status == UNUSED) {
            status = USED;
            first_use = millis();
        }
        update();
        return status != EXPIRED;
    }
private:
    const char * const code;
    enum { UNUSED, USED, EXPIRED } status;
    uint32_t first_use;  // valid if status == USED
};

```

Now you need to store all the passwords in an array, and a couple of functions to operate on the password collection as a whole:

```
const int PASS_COUNT = 10;

Password passwords[PASS_COUNT] = { "2028", "1234", "1294",
    "4795", "5651", "7616", "5648", "1487", "7095", "2554" };

void update_all_passwords()
{
    for (int i = 0; i < PASS_COUNT; i++)
        passwords[i].update();
}

// Returns true on success, and uses the matching password.
bool try_entry(const char * entry)
{
    for (int i = 0; i < PASS_COUNT; i++)
        if (passwords[i].matches(entry))
            return passwords[i].use();
    return false;  // no match found
}

```

The function `update_all_passwords()` is meant to be called on each iteration of `loop()`. It may seem superfluous, as a password is updated whenever you try to use it. However, without regular updating, a used password could be reused 49.7 days later, because of the `millis()` rollover.

Now, in your program, you just need to:

1. Put a call to `update_all_passwords()` at the beginning of `loop()`
2. Replace the big condition that tests for a valid password by `if (try_entry(readString.c_str()))`
> 1 votes

---
Tags: timers
---


# Question
Title: How to read sound sensor readings and light up sensor with water sensor if the readings is above threshold & when water is detected for 2 mins?
I am student that is new to Arduino and working on a project to trigger an alert if the sound level detected exceeds the threshold for a period of 2 mins. But I am stuck, would like to check how do I write a code to analog read sound sensor input and light up sensor if the readings is above datum for 2 mins? I had simple code but it triggers the light up immediately. :/

I have combined the coding together and this is the new code that worked with the help gotten:

```
    #define led 4 // led to D4
const int soundsensor= A0; //sound sensor to A0
const int threshold= 100; // to set the threshold value for sound sensor
int ssanalogread; //name of sound sensor analog read
bool wasOver;//add to globals
unsigned long firstDetect;

void setup() {
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  pinMode(soundsensor,INPUT);// to get input from sound sensor

} // end void setup

void loop() {

     sound1();

} // close void loop

void sound1() {

  ssanalogread=analogRead(soundsensor); // reads analog data from sound sensor
  Serial.println(ssanalogread);

   if ((ssanalogread > threshold)){ //replace if else
      if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 1*10*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
      wasOver = true;
   } // end first if
  else {
     wasOver = false;
     digitalWrite(led,LOW);
  } // end else

} //end loop

//this code works and is ok to run. can adjust the timing

```

# Answer
> 1 votes
You set a timestamp when the sound first exceeds the threshold and only set the output high when `millis() - firstDetect > 2*60*1000`

```
//add to globals
bool wasOver;
unsigned long firstDetect;

//replace if else
if ((ssanalogread > threshold)){
   if(!wasOver){
       firstDetect = millis();
   }
   if(millis() - firstDetect > 2*60*1000){
      digitalWrite(led,HIGH); //turns led on if the sensor reads more than threshold
   } //end if
   wasOver = true;
} else {
   wasOver = false;
   digitalWrite(led,LOW);
}

```

# Answer
> 1 votes
This is actually a lot harder than you might at first think.

Your "sound sensor" is little more than a microphone and amplifier. It gives you an audio waveform - whereas what you are interested in is the peak power.

An audio waveform goes both positive and negative:

The "peak" of the waveform can both be positive (above the line) or negative (below the line).

To get that peak you have to rapidly sample over a short period and find both the maximum and minimum values, and get the difference between them.

However, the Arduino can't see negative values on the ADC - so you only get the upper portion of the waveform, which is less than ideal. Really you should add a DC offset to the output of the sound sensor to bring the signal up to the middle of the ADC range (adding a 10kΩ + 10kΩ voltage divider across the input pin to +5V/GND would do the job).

If you don't add a DC offset then you can rapidly sample for a short period of time and work out the maximum value:

```
uint16_t getMaximum(uint8_t pin, uint32_t t) {
    uint16_t maximum = 0;
    uint32_t ts = millis();
    while (millis() - ts < t) {
        uint16_t sample = analogRead(pin);
        if (sample > maximum) {
            maximum = sample;
        }
    }
    return maximum;
}

```

Now to get the maximum over, say, a 10ms period, you can:

```
uint16_t maximum = getMaximum(A0, 10);

```

However, if you add a DC offset it gets a little more tricky, but the results will be better:

```
uint16_t getMaximum(uint8_t pin, uint32_t t) {
    int16_t maximum = 0;
    int16_t minimum = 0;
    uint32_t ts = millis()
    while (millis() - ts < t) {
        // The -512 here removes the DC offset from the reading. 512 is half
        // the ADC range.
        int16_t sample = analogRead(pin) - 512;
        if (sample > maximum) {
            maximum = sample;
        }
        if (sample < minimum) {
            minimum = sample;
        }
    }

    // We now have a positive value as the maximum and a negative
    // as the minimum - or zero if none went into the max or min
    // region of the waveform.  Subtract a negative from a positive
    // is like adding a positive to a positive.  But we only want
    // a positive result, so we'll get the absolute value.
    return abs(maximum - minimum);
}

```

Now that you actually have your peak-peak value of your waveform over a short period you can use it to work out when the sound goes above a threshold and when it goes below, and how long it's been above that threshold. The basic method is:

* Is the sound above the threshold?
    + Yes: Was it above the threshold before?
    + No: Set a timestamp and a flag to say it's above the threshold.
    + Yes: Has it been above \> 2 minutes?
        - Yes: light the LED
    + No: Was it above the threshold before?
    + Yes: Has it been above \> 2 minutes?
        - Yes: Extinguish the LED

The thing here is to know that you are looking for changes in the "above the threshold" state to start your timing. A simple implementation may look like:

```
static uint32_t wentAbove = 0;
static bool isAbove = false;
const uint16_t threshold = 300;

uint16_t maxval = getMaximum(A0, 10);

if (maxval > threshold) {
    if (!isAbove) {
        isAbove = true;
        wentAbove = millis();
    } else {
        if (millis() - wentAbove > 120000) {
            digitalWrite(13, HIGH);
        }
    }
} else {
    if (isAbove) {
        isAbove = false;
        digitalWrite(13, LOW);
    }
}

```

<sub>*Note: all code untested.*</sub>

---
Tags: arduino-uno, programming, sensors, c++, sound
---


# Question
Title: The ESP8266 connects to open WiFi hotspots, even If I supply a password
This question is more out of curiosity, then out of a need to solve something.

I was trying out some experiments with the ESP8266 Arduino core when I realized that I had programmed an SSID and password for the ESP8266, but the WiFi that I had set up was an open network.

I tried going through the documentation and then the Arduino core source code, but couldn't find if `WiFi.begin(ssid,passphrase)` a function does this on purposes, as in it was designed that way, or did it just happen to work this way.

Also, I would like to know if there is a way to stop the ESP from connecting to an open network when the passphrase is provided.

# Answer
It's probably by chance - however it's impossible to know.

Connecting is done by `wifi_station_connect()`, which is a function provided by the (closed source) ESP8266 SDK. So we can never know what it's actually doing.

However, the sequence is probably something like:

* -\> Connect
* \<- Ok, give me a password
* -\> Here it is
* \<- Right, you're connected

Or, with no PSK:

* -\> Connect
* \<- Right, you're connected

Although you specify the password (which just gets stored in the configuration) if it never asks for it then it just doesn't use it.

Can you force it? Not without knowing what's going on in the mystery `wifi_station_connect()` function. There is nothing much in the documentation for the SDK that even hints at a clue.
> 2 votes

---
Tags: esp8266, wifi
---


# Question
Title: What is the best serial communication method between an Arduino and a spectral sensor?
I have an Adafruit AS7262 visible spectral sensor. I want to receive the data of the sensor with an Arduino.
The sensor has two serial communication options: UART(asynchronous) or I2C(synchronous). I want to know which method is more suitable for the sensor to communicate with the Arduino microcontroller. I was thinking that UART is more suitable, because the sensor has his own master clock, in other words if I choose I2C then the Arduino needs to work as the "slave" and I dont think that is very suitable, because the Arduino has its own master clock also. For this reason I think that asynchronous method is more reliable, but I am not sure about this.

# Answer
The I2C on this device is slave, not a master. Even though it has its own clock, it is designed to operate as a slave being read by a master.

You will have no issues using the I2C interface - in fact Adafruit uses it for their own software library.

Since there is already a I2C-based library available from the manufacturer I would use that, unless there is a good reason to use the UART instead.
> 1 votes

# Answer
Arduino will serve as the Master controller and will send the call to the slaves. AS7262 is a sensor device, Arduino will send the call commmand then receive the data from its sensors. Sometime confusion arrises because developers are accustomed to the desktop computer as the Master, but in this case, Arduino receives data and engage a forward action like sending info to USB or WiFi connected computer or just do a feedback control to another digital or analog device.

You will find further reading on this subject at Arduino community here

Also
> 0 votes

---
Tags: serial, sensors
---


# Question
Title: How to upload a sketch to Arduino if it goes to deep sleep mode quickly
I have created sketch where Arduino goes to powerdown mode in about 1s after boot. Now I can not upload other sketch, because programmer does not get proper response. I tried to hold reset and release it at various stages during compile/upload, but it does not help. I suspect the programmer needs to communicate with Arduino for several seconds. Any advice how to erase the sketch without programmer, or how to ban the sleep mode? It is Pro Mini 168. Thanks

# Answer
> 2 votes
Hold the reset button while you start the upload. Wait until you upload first tries to connect to the Arduino, then release the reset.

If you can't get that to work, the next option is to load another Arduino with the ArduinoISP example sketch, connect the two as described in the comments, and use the 2nd Arduino to program yours.

Update:

> Would another Arduino overcome this problem?

Ok, then it's time for plan B. Using a programmer (real, or simulated by another Arduino) doesn't depend on the 'failing' Arduino's bootloadloader but uses a direct (SPI) interface to program it. This article has more information.

# Answer
> 0 votes
Turn on Verbose output (Under File:preferences). Press & hold the Reset button. After the compilation ends, you will see a message like:

"Compiled xxx of 32xxx bytes". That's when the download starts - release reset. It make take a few tries to get the timing of the release correct.

If you can't get the reset to take hold, then it's time to reburn the bootloader using a Programmer connected to the ICSP pins.

---
Tags: power
---


# Question
Title: How to build a valid HTTP Response. Recv failure: Connection reset by peer
I'm developing an Arduino server that should respond with a message when it receives a POST Request.

If I test my project with a HTTP Client (like insomnia or postman), I get an error:

```
Error: Failure when receiving data from the peer

```

I still get a response that I can read but with a final error.

That's my client request:

```
> POST /SOMETHING/ HTTP/1.1
> Host: [ARDUINO IP]
> User-Agent: insomnia/6.2.0
> Accept: */*
> Content-Length: 0

```

And this is my Arduino response considered as not valid:

```
< HTTP/1.1 200 OK
< Connection: close
< [MY MESSAGE]

* Recv failure: Connection reset by peer
* stopped the pause stream!
* Closing connection 2

```

As you can notice, I just added 2 strings

```
HTTP/1.1 200 OK
Connection: close

```

before the real message.

Am I missing something to create a valid response?

Thanks

# Answer
HTTP requires an empty line after HTTP headers.

First line is status line. Then the header lines. The headers are terminated by an empty line. Then the response body follows. Line terminator for HTTP is \r\n. Arduino println() function uses \r\n.

The response with body should contain Content-type and Content-length header. Alternative to Content-lenght is "chunked" Transfer-Encoding.

ESP8266WebServer library handles HTTP for you.
> 1 votes

---
Tags: http, esp8266
---


# Question
Title: Why my light meter's values are blank on Arduino Serial Monitor?
I tried to represent the values of TSL 2591 Adafruit light sensor on my Arduino Serial Monitor, but for some reason, I could not do that. The Arduino Serial Monitor just enters some blank values and scrolls down. Here is the code:

```
uint16_t x = tsl.getLuminosity(TSL2591_VISIBLE);
y = float(tsl.getLuminosity(TSL2591_VISIBLE));
z = (y, DEC);
Serial.write((byte)z);

```

`x`, `y`, and `z` are floats initially.

# Answer
Use Serial.println(x); to print a number as text. Function write() sends the raw byte and Serial Monitor shows the character with that ASCII code, which is not valid or a not visible control character.

---

For the `z = (y, DEC);` from Wikipedia:

> In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

so `z` is always 10 (value of constant DEC), which is ASCII code for the new line character
> 3 votes

---
Tags: serial, sensors
---


# Question
Title: getting error 'Serial' was not declared in this scope
I am adding Dust Sensor to my particle photon project at home,

I got this GitHub project that I want to test before implementing a final code.

I am not an expert in cpp, I wanted to modularise the dust sensor codebase to separate library so I created new dustSensor.cpp file and kept the code linked above.

but I keep getting error:

'Serial' was not declared in this scope

'Serial1' was not declared in this scope

'DEBUG' was not declared in this scope

'DEC' was not declared in this scope dustSensor.cpp:13:57:

I do have Serial.begin(57600) called in setup() function but still get the above error

# Answer
I learned that I needed to include `Arduino.h` header file

apart from that I learned .ino files and .cpp files is that the .ino files transparently include particle.h for you.

The other difference is that .ino files generate forward declarations for you. This is necessary when you’ve implemented a function later in the file than when you’ve first used it. For example, if you pass the function to something like Particle.subscribe in setup() but you’ve implemented it farther down the file.
> 5 votes

---
Tags: serial, programming, softwareserial, serial-data, cpp
---


# Question
Title: How to write a script if water sensor comes into contact with water for more than 2 mins and LED lights up
I am a newbie to arduino and programming. I would like to come out with a code for water sensor to detect the presence of water for more than 2mins before lighting up the LED lightbulb. Currently using Arduino, Grove baseshield with grove water sensor http://wiki.seeedstudio.com/Grove-Water\_Sensor/.

I have the simple base code but not sure how do i go about adding in the function to detect water for a longer period of time before the light lights up:

```
#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

int isWater;
bool wasWater = false;
//bool isWater, wasWater = false;    // true => currently we are not seeing water
uint32_t waterstart_ms = 0;        // time first saw water

void setup() {
  pinMode(watersensor, INPUT);
  pinMode(led, OUTPUT);
}

void loop()
{
   // Is there water?
 isWater = digitalRead(watersensor);     // read sensor
 Serial.println(isWater);

   if( isWater ){
      if( wasWater ) {
      waterstart_ms = millis();  // First water: note the time
      }
        if( millis() - waterstart_ms >= 1*5*1000 ){// Water continues for 5s (trial first); time to light LED?
            digitalWrite(led, HIGH);
        }//end if
            wasWater = true;
   } // end first if
   else {
      wasWater = false; // No water; LED off
      digitalWrite(led, LOW);
   }
}

```

# Answer
Should the LED be latched (stay on forever, once it's on), or go out if the sensor later detects no water? I'll assume the latter. Here's an (untested) state machine that should give you a good start. It keeps track of whether water was already seen, when it started, and whether it is seen now. There is some redundant switching of the LED; removing that (if desired) "is left as an exercise for the reader".

```
#define watersensor 8               //Grove water sensor to Arduino Digital Pin 8
#define led 4                      //Grove LED to Digital Pin 4

#define TWOMIN (2*60*1000L)

bool isWater, wasWater = false;    // true => currently/were seeing water
uint32_t WaterStart_ms = 0;        // time first saw water

void setup() {
  pinMode(watersensor, INPUT_PULLUP);  // pullup for testing w/a button
  pinMode(led, OUTPUT);
}

void loop()
{
  // Is there water?
  isWater = !digitalRead(watersensor);     // read sensor

  if ( isWater ) {
    if ( !wasWater ){
      // First water: note the time
      WaterStart_ms = millis();
      wasWater = true;
    }
    else {
      // Water continues; time to light LED?
      if ( (millis() - WaterStart_ms) >= TWOMIN )
        digitalWrite(led, HIGH);
    }
  }
  else {
    // No water; LED off
    wasWater = false;
    digitalWrite(led, LOW);
  }
  delay(300);
}

```

Update:

Added `wasWater = true;` at line 27. The `delay(300)` at line 40 isn't necessary. Ran correctly when I tested it with a button (also negative logic) for the sensor.

> the light lights up randomly.

See if your sensor gives solid responses (try printing its output in loop() ). If it dithers around transitions, you may need to wait for some number of readings in a row that are opposite to the previous sensor state before you accept its new state as real.
> 1 votes

---
Tags: arduino-uno, sensors, shields, millis
---


title: Hot Swap Sensor

text:
# Question
Title: Hot Swap Sensor
Is there a way to have a sensor be hot swappable, as in it can be disconnected and reconnected without locking up the Arduino? I have an I2C sensor that I want to be able to disconnect and reconnect without having to restart the board.

# Answer
The I2C bus is not blocking the operation, if the sensor isn't there. Also the `Wire` library will not block in this case. It will just return an error code, which you should handle in your code.

But this doesn't mean, that every library, which wraps the I2C workload for a specific sensor, is doing the same. Depending on the sensor and the used library you will have to check yourself, if it is blocking in any way. (This part is not better answerable without information on what sensor and what library will be used)

So: Yes, this is totally possible, but you will have to deal with the errors from disconnecting the sensor and handle them in your code. By polling the sensor in a regular fashion (like Jot mentioned in the comments) will give you the information, if there is a sensor with this address on the bus. The `Wire.endTransmission()` method will return `2` (received NACK on transmit of address), if no device with the specified address is reachable on the bus.

Depending on the used sensor, you might have to initialize the sensor correctly after every reconnect. Especially, if the disconnect happend during a transmission. Refer to the datasheet of the sensor to find out, what happens in this case with the sensor.

If you plan to use different sensors, you have to check for their specific addresses (since different types of sensor often have different hardwired addresses/address spans) and - if the sensors are controlled differently - determine, what sensor is actually connected. The least may be possible by reading their status registers, which can work for many sensor types.
> 1 votes

---
Tags: programming, sensors, i2c
---


# Question
Title: How to use a precompiled library in a project with Arduino-IDE
I'm discovering the Arduino development and after quite some googling, I can't find an answer to the following question.

I'd like to distribute some code as mylib.h + precompiled mylib.o (this will be code ported from sources which I can't divulgate).
How is it possible to build a sketch using this precompiled mylib.o in the Arduino-IDE environment?
Do I simply have to put this mylib.o in a specific path and include the mylib.h in the sketch? If yes, which path? If no, what specific configuration steps do I have to follow?

Thanks in advance.

# Answer
See https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification

> library.properties file format \[...\] precompiled - (available from Arduino IDE 1.8.6/arduino-builder 1.4.0) (optional) set to true to allow the use of .a (archive) and .so (shared object) files. The .a/.so file must be located at src/{build.mcu} where {build.mcu} is the architecture name of the target the file was compiled for. Ex: cortex-m3 for the Arduino DUE. The static library should be linked as an ldflag.

So with the correct metadata and file layout the precompiled objects should be available. You'll need to set the *architectures* property to indicate you're using esp8266 as your tag suggests.

More info on the library manager here https://github.com/arduino/Arduino/wiki/Library-Manager-FAQ including how to add to the public library list.
> 4 votes

---
Tags: arduino-ide
---


title: programming relays wit millis code

text:
# Question
Title: programming relays wit millis code
Trainset info,

```
Turnout 1 = relay 1 - makes turnout track go left
          = relay 2 - makes turnout track go right
Turnout 2 = relay 3 - makes turnout track go left
          = relay 4 - makes turnout track go right
 Signal 1 = relay 5 - makes signal go green - train 1 starts driving
          = relay 6 - makes signal go red - train 1 stops for signal
 Signal 2 = relay 7 - makes signal go green - train 2 starts driving
          = relay 8 - makes signal go red - train 2 stops for signal

```

I have a arduino - uno and a 8 relay board. I want to run a program (loop) for 1/2 hour / 1800 seconds. Switching time should be 2 seconds (relay ON)

Can somebody help me with a millis code please.

Loop times should be:

```
relay 1 = (2),1250,(2),546 - total 1800 seconds
relay 2 = 620,(2),630,(2),546 - total 1800 seconds
relay 3 = 10,(2)1260,(2),526 - total 1800 seconds
relay 4 = 630,(2),640,(2),512 - total time 1800 seconds
relay 5 = 20,(2),1270,(2),505 - total time 1800 seconds
relay 6 = 600,(2),750,(2),446 - total time 1800 seconds
relay 7 = 640,(2),640,(2),516 - total time 1800 seconds
relay 8 = 1240,(2),450,(2),106 - total time 1800 seconds

```

Regards, Martinus van Walsum xxxxxxxx@xxxxxxxx.com

# Answer
> 1 votes
This is functional. I would do more by making a function to be called with the time and state information. It would reduce the number of if statements. But this is simple to understand. I started with Blink without delay.

I did two relays. For the others, copy and paste, then change the relay numbers and times.

```
/*
  Blink without Delay
  http://www.arduino.cc/en/Tutorial/BlinkWithoutDelay
*/

const int On =  1;
const int Off =  0;

// constants won't change. Used here to set a pin number:
const int ledPin =  LED_BUILTIN;// the number of the LED pin
const int relay1 =  5;
const int relay2 =  6;

// Variables will change:
int ledState = LOW;             // ledState used to set the LED

// Generally, you should use "unsigned long" for variables that hold time
// The value will quickly become too large for an int to store
unsigned long previousMillis = 0;        // will store last time LED was updated

int    secondCount = 0;

// constants won't change:
const long interval = 1000;           // interval at which to blink (milliseconds)

#define onTime  2           //relay on time

#define relay1_on1 0
#define relay1_on2 (relay1_on1+onTime+1250)

#define relay2_on1 62
#define relay2_on2 (relay2_on1+onTime+630)

void setup() {
  // set the digital pin as output:
  digitalWrite(relay1, Off);
  digitalWrite(relay2, Off);
  pinMode(ledPin, OUTPUT);
  pinMode(relay1, OUTPUT);
  pinMode(relay2, OUTPUT);
}

void loop() {
  // here is where you'd put code that needs to be running all the time.

  // check to see if it's time to blink the LED; that is, if the difference
  // between the current time and last time you blinked the LED is bigger than
  // the interval at which you want to blink the LED.
  unsigned long currentMillis = millis();

  if (currentMillis - previousMillis >= interval) {
    // save the last time you blinked the LED
    previousMillis = currentMillis;

    //------------------------------
    // Relay 1
    if (secondCount == relay1_on1) {
      digitalWrite(relay1, On);
    }
    if (secondCount == (relay1_on1 + 2)) {
      digitalWrite(relay1, Off);
    }

    if (secondCount == relay1_on2) {
      digitalWrite(relay1, On);
    }
    if (secondCount == (relay1_on2 + 2)) {
      digitalWrite(relay1, Off);
    }

    //------------------------------
    // Relay 2
    if (secondCount == relay2_on1) {
      digitalWrite(relay2, On);
    }
    if (secondCount == (relay2_on1 + 2)) {
      digitalWrite(relay2, Off);
    }

    if (secondCount == relay2_on2) {
      digitalWrite(relay2, On);
    }
    if (secondCount == (relay2_on2 + 2)) {
      digitalWrite(relay2, Off);
    }

    //------------------------------
    // if the LED is off turn it on and vice-versa:
    if (ledState == LOW) {
      ledState = HIGH;
    } else {
      ledState = LOW;
    }

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

    secondCount++;
    if (secondCount == 180) {
      secondCount = 0;
    }
  }

}

```

---
Tags: programming
---


# Question
Title: Arduino losing connection to Serial port after running function
For some reason when I loop my code through a separate function the serial port hangs up. The serial connection appears fine when I call cases within the loop but not when I call outside.

I tried to figure out where the problem is and for some reason using the `Serial.print(ComControlValue);` and the output is

> -1

But the error still persists.

Previous it was this before I changed the baudrate

> -b⸮⸮⸮⸮ Waiting for Command

It's not printing out the -1 I'm using as the main case. Could this be the problem?

```
#include <Wire.h>
/* RPi Army variables */
int RPi[3] = {3,6,9};                                        // SDA/SCL code names for the different Raspberry pi's

/* Define parameters for computer control */
int ComControlValue = -1;

void setup() {
  Serial.begin(115200);                                     // Establish Serial connection to computer
  Wire.begin();                                             // join i2c bus as master
}

void loop() {
 switch(ComControlValue){
  /* -1 : nothing happened yet */
  case -1:
     Serial.println("Waiting for Command");
     while (Serial.available()==0){}
     ComControlValue=Serial.parseInt();                             // Pull value from serial port
     break;

  case 111:
     Serial.println("Eat more Toast");
     ComControlValue = -1;
     break;

  case 210:
     Sendsignals(RPi[0],333);
     Sendsignals(RPi[1],333);
     Sendsignals(RPi[2],333);
     ComControlValue= -1;
     Serial.print(ComControlValue);
     break;
  }
}

void Sendsignals(int Rpi, int code){
   char str[4];
   sprintf(str, "%3d\n", code);
   Wire.beginTransmission(Rpi);                                 // transmit to device of choice
   Wire.write(str);                                             // sends 16 bytes
   Wire.endTransmission();                                      // stop transmitting
}

```

# Answer
Your str variable in function Sendsignals is short. sprintf writes 5 bytes to it, 3 digits, the \n and terminating zero. The terminating zero is written outside of the allocated array and causes the crash.
> 2 votes

---
Tags: serial
---


# Question
Title: Problem with modbus communication between two arduinos when writing more than 27 registers
I have the following problem: I want send 200 registers from a modbus master to a slave. Both are arduinos. I can't send more than 27 registers. When I send more i get the Errorcode `255` which means `timeout`. I know that the modbus message is limited to 253 bytes (256 bytes - server address (1 byte) - CRC (2 bytes)). Listed here: MODBUS APPLICATION PROTOCOL SPECIFICATION page.5

**My setup:**

* I use two Arduino Mega 2560. One as a master and the other as the slave. If that works I want to use more than one slave. They are connected via Serial1 master TX1 (pin18) to slave RX1 (pin19) and master RX1 (pin19) to slave TX1 (pin18).
* The modbus library I'm using is ModbusRtu.h from smarmengol.
* Because i want to ultimately communicate with more than one slave device I use RS-485. To send the message as a broadcasat but thats not relevant now because first I want to send to one slave to test it out.

I know that the array is much bigger as the registers I want to send. Thats because I wanted to know when the the timeout happens. Sending 27 registers works fine and the slave recieves all of the 27. But when sending more than 27 registers I get the timeout and nothing will be send.

**Master code**

```
#define SERIAL_BUFFER_SIZE 256
#include "ModbusRtu.h"

#define Timeout 150
#define QUERYINTERVALL 50

/* Defined the buffersize as stated in
 * C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h
*/

modbus_t telegram;

// Test sending large array
uint16_t sendLargeArray[200] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
                                18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
                                33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
                                48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62,
                                63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
                                78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92,
                                93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105,
                                106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117,
                                118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129,
                                130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141,
                                142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153,
                                154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165,
                                166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
                                178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189,
                                190, 191, 192, 193, 194, 195, 196, 197, 198, 199};

Modbus master;

void dataSend();

void setup()
{

 /**
 *  Modbus object declaration
 *  u8id : node id = 0 for master, = 1..247 for slave
 *  u8serno : serial port (use 0 for Serial)
 *  u8txenpin : 0 for RS-232 and USB-FTDI
 *               or any pin number > 1 for RS-485
 */
    master = Modbus(0, 1, 8); // this is master with RS-485 config
    master.begin(9600, SERIAL_8N2);
    master.setTimeOut(Timeout);
    Serial.begin(9600); // setup Serial for USB debugging
}

void loop()
{
    uint8_t error = master.getLastError(); //get errorcode
    uint8_t state = master.getState();     // get state from master 0 = idle 1 = waiting

    dataSend(); // function for sending array

    // Error Code
    Serial.print("Error code: ");
    Serial.print(error);
    Serial.println();

    // Print master state
    Serial.print("Master State: ");
    Serial.print(state);
    Serial.println();
}

void dataSend()
{
    uint8_t slaveId;
    uint8_t u8state;
    unsigned long u32wait;
    slaveId = 1;
    u32wait = millis() + QUERYINTERVALL;
    bool staywhile = true;

    // telegram for sending sendLargeArray
    telegram.u8id = 1;
    telegram.u8fct = 16;
    telegram.u16RegAdd = 0;
    telegram.u16CoilsNo = 28; // 27 or less works fine
    telegram.au16reg = sendLargeArray;
    u8state = 0;

    // Master broadcasts data
    while (staywhile)
    {
        switch (u8state)
        {
        case 0:
            if (millis() > u32wait)
                u8state++; // wait state
            break;
        case 1:
            master.query(telegram); // send query (only once)
            u8state++;
        case 2:
            master.poll(); // check incoming messages
            if (master.getState() == COM_IDLE)
            {
                u8state = 0;
                u32wait = millis() + QUERYINTERVALL;
                staywhile = false;
            }
            break;
        }
    }
}

```

**Slave code**

```
#define SERIAL_BUFFER_SIZE 256
#include "ModbusRtu.h"

/* Defined the buffersize as stated in
     * C:\Program Files (x86)\Arduino\hardware\arduino\avr\cores\arduino\USBAPI.h
    */

// data array for modbus network sharing

uint16_t recieveLargeArray[200] = {};

 /**
  *  Modbus object declaration
  *  u8id : node id = 0 for master, = 1..247 for slave
  *  u8serno : serial port (use 0 for Serial)
  *  u8txenpin : 0 for RS-232 and USB-FTDI
  *               or any pin number > 1 for RS-485
 */
Modbus slave(1, 1, 8); // this is slave @1 and RS-485

void setup()
{
  Serial.begin(9600);
  slave.begin(9600, SERIAL_8N2); // baud-rate at 9600
}

void loop()
{
  uint8_t error = slave.getLastError();
  slave.poll(recieveLargeArray, 28); // receiving 27 or less registers works fine

  // print every 5th element of the recieved array
  // no spamming console that way
  Serial.print("Recieve: ");
  for (int i = 0; i < 200; i += 5)
  {
    Serial.print(recieveLargeArray[i]);
    Serial.print(",");
  }
  // Error Code
  Serial.println();
  Serial.print("Error code: ");
  Serial.print(error);
  Serial.println();

  memset(recieveLargeArray, 0, 200 * sizeof(uint16_t)); // recieveLargeArray = {}

}

```

**Questions**

* Does anyone know why I cant send more than 27 registers?
* Did anyone made a simillar project and can share the code?
* Has anyone a fix for that?

Help is very appreciated.

Cheers ueberBrot

Link issuepage on ModbusRTU.h GitHub

**Edit**

* Forgot to mention that I increased the buffer size inside the `ModbusRTU.h` library aswell. I did it like that `#define MAX_BUFFER 256` as mentioned in this comment from Juraj
* Changed the define location of `#define SERIAL_BUFFER_SIZE 256` in both sketches to the top.

# Answer
I did change the `MAX_BUFFER` inside `ModbusRTU.h` from 64 to 256. As you stated before in there its only the size for the used array. What I also did was move the `#define SERIAL_BUFFER_SIZE 256` inside both my sketches to the top. That did nothing, After that I found a way to increase the RX and TX buffer size with the help of this post. I changed it from 64 to 256. maybe I could have changed those with a `#define` in my sketches aswell?.

Now I can send a max of 59 registers at once. Im not sure why I cant send more because the max should be 123 registers at once and the buffer is 256 bytes so 123 registers x 2 bytes = 246 is enough space in the buffer.
> 0 votes

# Answer
In ModbusRtu.h:

`#define MAX_BUFFER 64 //!< maximum size for the communication buffer in bytes`

27\*2=54 bytes for registers and 10 for header and crc.

Change the MAX\_BUFFER define. On Mega you have enough RAM.

btw: RS485 doesn't imply mandatory use of Modbus. You could use your own protocol.
> 1 votes

---
Tags: serial, arduino-mega, rs485, modbus
---


title: STM32 and NRF send & receive

text:
# Question
Title: STM32 and NRF send & receive
This is my send and receive code in STM32 (blue board). But i can't send and receive data . why? I did use Enrf24.h . Enrf24 link: https://github.com/spirilis/Enrf24 send code is:

```
#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#include <string.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t txaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setTXaddress((void*)txaddr);
}

void loop() {
  Serial.print("Sending packet: ");
  radio.print("OONN");
  radio.flush();  // Force transmit (don't wait for any more data)
  delay(1000);
  Serial.print("Sending packet: ");
  radio.print("OOFF");
  radio.flush();
  delay(1000);
}

```

receive code is:

```
#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t rxaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
const char *str_on = "ON";
const char *str_off = "OFF";
void dump_radio_status_to_serialport(uint8_t);
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setRXaddress((void*)rxaddr);
  radio.enableRX();  // Start listening
}

void loop() {
  char inbuf[33];
  while (!radio.available(true));
  if (radio.read(inbuf)) {
    Serial.print("Received packet: ");
    Serial.println(inbuf);
  }
}

```

this image can help :

# Answer
> 0 votes
You did not say which library you are using, but based on the `#include`s, I am assuming http://maniacbug.github.io/RF24

This line in your receiver code:

```
  while (!radio.available(true));

```

does not make sense. You are passing `true` to the `radio.available()` function, but the function does not care about a parameter.

You probably mean something like:

```
while (!radio.available());

```

When you pass in a variable, you are calling a variant of the function that expects a pipe number to be given, and `true` is defined as `1`. Your transmitter, however, is not sending on pipe number 1.

# Answer
> 0 votes
First of all, remove

```
while (!radio.available(true));

```

after that use

```
PA_5 ----> SCK
PA_6 ----> MISO
PA_7 ----> MOSI

```

it will work correctly.

# Answer
> -1 votes
It is better answer for some reseans in Enrf library you can not send data with write untill txbuf\_len==0

> size\_t Enrf24::write(uint8\_t c) {
> if (txbuf\_len == 32) { flush(); // Blocking OTA TX } txbuf\[txbuf\_len\] = c; txbuf\_len++; return 1; }

dont use purge then

> txbuf\_len = 0

this is for read dat

```
#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t rxaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
const char *str_on = "ON";
const char *str_off = "OFF";
void dump_radio_status_to_serialport(uint8_t);
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setRXaddress((void*)rxaddr);
  radio.enableRX();  // Start listening
 // radio.autoAck(false);
}

void loop() {
  char inbuf[35];
  if (radio.read(inbuf))
  {
    Serial.print("Received packet: ");
    Serial.println(inbuf);
  }
}

```

this is write for write data:

```
#include <SPI.h>
#include <Enrf24.h>
#include <nRF24L01.h>
#include <string.h>
#define ce_nrf PB12
#define csn_nrf PB13
#define irq_nrf PA0
Enrf24 radio(ce_nrf, csn_nrf, irq_nrf);  // P2.0=CE, P2.1=CSN, P2.2=IRQ
const uint8_t txaddr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0x01 };
void setup() {
  Serial.begin(9600);
  SPI.begin();
  SPI.setDataMode(SPI_MODE0);
  SPI.setBitOrder(MSBFIRST);
  radio.begin();  // Defaults 1Mbps, channel 0, max TX power
  radio.setTXaddress((void*)txaddr);
}
int i=0;
void loop() {
  i++;
  Serial.print("Sending packet: ");
  Serial.println(i);
  radio.print("1234567890123456789012--------->");
  //radio.purge();
  delay(100);
}

```

---
Tags: spi, nrf24l01+
---


title: How to combine time into a variable

text:
# Question
Title: How to combine time into a variable
I have an Arduino Uno project which is recording student attendance using fingerprint sensor. So when sensor found a match, the serial monitor will be printing out Student ID and current time like this:

```
    DateTime now;
    void setup()
      {
          ...
      }

    void loop()
      {
          .....
          //found a match
          Serial.print("Found ID #");
          Serial.println(finger.fingerID);
          Serial.print("Time->");
          Serial.print(now.hour(), DEC);
          Serial.print(':');
          Serial.print(now.minute(), DEC);
          Serial.print(':');
          Serial.print(now.second(), DEC);
      }

```

Sample result will be:

```
Found ID#1
Time-> 18:11:54

```

I would like to store the time into a variable and print it out instead of printing hour, minute, and second separately. How can I do that???

I have tried to do like this as below but I'm getting an error, I would like to store it as a string. How can I do that?

```
string time = now.hour() + ':' + now.minute() + ':' + now.second();

```

# Answer
> 2 votes
You want to use `snprintf` for this:

```
char timeString[9];

snprintf(timeString, 9, "%02d:%02d:%02d", now.hour(), now.minute(), now.second());
Serial.println(timeString);

```

By using a format string like this you are taking into account time portions \< 10 (like 7 minutes and 23 seconds past 3 am, which would otherwise be 3:7:23) by padding the time with leading zeroes where needed.

---
Tags: arduino-uno, c++
---


# Question
Title: Can the function be written without ";" in the end?
I have seen the following code on the Internet:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);
void setup()
{
  mySerial.begin(9600);
  Serial.begin(9600);
  delay(100);
}
void loop()
{
  if (Serial.available()>0)
  mySerial.write(Serial.read());
  if (mySerial.available()>0)
  Serial.write(mySerial.read());
}

```

The command works perfectly fine. How was it possible in the code to write the command without ";" at the end of the line?

The link to the code is: enter link description here

# Answer
> 1 votes
Do you refer to this block?

```
if (Serial.available()>0)   <- here
mySerial.write(Serial.read());
if (mySerial.available()>0) <- here
Serial.write(mySerial.read());

```

If so, there *is* a `;` at the end of each command. The commands are just split onto two lines each. It could be written like this:

```
if (Serial.available()>0) mySerial.write(Serial.read());
if (mySerial.available()>0) Serial.write(mySerial.read());

```

The second and fourth lines are the body of the `if`. Better indenting with the original arrangement would be:

```
if (Serial.available()>0)
    mySerial.write(Serial.read());
if (mySerial.available()>0)
    Serial.write(mySerial.read());

```

Or even better, include the brackets around the body:

```
if (Serial.available()>0) {
    mySerial.write(Serial.read());
}
if (mySerial.available()>0) {
    Serial.write(mySerial.read());
}

```

---
Tags: compilation-errors, command-line
---


title: MKR1000 and DS18B20 temperature sensor

text:
# Question
Title: MKR1000 and DS18B20 temperature sensor
I am new to Arduino and electronics in general and I can't get my MKR1000 to read correct data from a DS18B20 temperature sensor.

Here is the tutorial I followed.

**The issue is**: I always get the same readings from the sensor: `-127.00`.

I should mention I have tried 2 different sensors and get the same readings.

From the sensor, GND goes directly to GND on the board, and I have the 4.7kΩ resistor in between the data and power wires.

According to the sensor manufacturer, output leads: Yellow (VCC), Red (DATA), Black (GND).

Data line is connected to the pin `~2` on the MKR1000.

```
/********************************************************************/
// First we include the libraries
#include <OneWire.h>
#include <DallasTemperature.h>
/********************************************************************/
// Data wire is plugged into pin 2 on the Arduino
#define ONE_WIRE_BUS 2
/********************************************************************/
// 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 sensors(&oneWire);
/********************************************************************/
void setup(void)
{
 // start serial port
 Serial.begin(9600);
 Serial.println("Dallas Temperature IC Control Library Demo");
 // Start up the library
 sensors.begin();
}
void loop(void)
{
 // call sensors.requestTemperatures() to issue a global temperature
 // request to all devices on the bus
/********************************************************************/
 Serial.print(" Requesting temperatures...");
 sensors.requestTemperatures(); // Send the command to get temperature readings
 Serial.println("DONE");
/********************************************************************/
 Serial.print("Temperature is: ");
 Serial.print(sensors.getTempCByIndex(0)); // Why "byIndex"?
   // You can have more than one DS18B20 on the same bus.
   // 0 refers to the first IC on the wire
   delay(1000);
}

```

Any idea what I am doing wrong?

# Answer
Looks like you have it wired wrong. A schematic would really help but it looks like you've got 5V going directly into the sensors data line (yellow wire) it's connected on your breadboard to the orange wire +5V. The power wire of your temperature sensor (red wire) is running through a 4.7K resistor which is not likely what you wanted here either.
> 3 votes

---
Tags: temperature-sensor, mkr1000, ds18b20
---