# Question
Title: How to determine the source of constants in libraries?
Preamble:

I am trying to figure out how to program and use the timers in the Feather M0 using the Arduino IDE. I have seen a number of examples published, but I'm not one to just blindly copy some code and expect it to work. The issue that I'm having (and it seems to be ubiquitous in Arduino) is that there does not seem to be a concept of dependencies. In order to reference constants, they have to be defined somewhere.

Question:

How can I find the source of the definition of the constants that people keep referring to in their code? For example, in this code a Arduino Zero, M0 timer example, reference is made to `TC_CTRLA_PRESCALER_DIV1` among other constants. Where is this constant defined?

Efforts:

I've searched generally and specifically for these constants. But, as you would imagine in C, it's difficult to find the actual source versus a simple reference to the constant.

I've also tried a search in the installed Arduino IDE with SAMD and Adafruit SAMD libraries installed. For example

```
~/Arduino$ grep -r --include=*.h --include=*.cpp "TC.*_PRESCALER_DIV"

```

Did not yield anything. I apologize if this is a naive question, but I haven't been able to find a simple, obvious answer. Actually, I haven't been able to find any answer.

# Answer
The name `TC_CTRLA_PRESCALER_DIV1` indicates this is a macro. A trick for quickly finding the exact location of a macro definition is:

1. File \> Preferences \> Compiler Warnings \> All \> OK
2. In your sketch, add a `#define` directive for the macro name that definitely changes the definition:

```
#define TC_CTRLA_PRESCALER_DIV1 foobar

```
3. Sketch \> Verify/Compile
4. After the compilation finishes, examine the compiler output in the black console window at the bottom of the Arduino IDE window (you will need to scroll up to see it all) for a "redefined" warning. The warning will state the path of the original definition:

```
    C:\Users\per\AppData\Local\Temp\arduino_modified_sketch_804921\sketch_aug05a.ino:1:0: warning: "TC_CTRLA_PRESCALER_DIV1" redefined [enabled by default]

   #define TC_CTRLA_PRESCALER_DIV1 foobar

   ^

  In file included from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21g18a.h:268:0,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/samd21.h:69,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd.h:105,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/sam.h:470,

                   from C:\Users\per\AppData\Local\Arduino15\packages\arduino\hardware\samd\1.6.19\cores\arduino/Arduino.h:48,

                   from C:\Users\per\AppData\Local\Temp\arduino_build_309126\sketch\sketch_aug05a.ino.cpp:1:

  C:\Users\per\AppData\Local\Arduino15\packages\arduino\tools\CMSIS-Atmel\1.1.0/CMSIS/Device/ATMEL/samd21/include/component/tc.h:113:0: note: this is the location of the previous definition

   #define TC_CTRLA_PRESCALER_DIV1     (TC_CTRLA_PRESCALER_DIV1_Val   << TC_CTRLA_PRESCALER_Pos)

   ^

```
> 1 votes

# Answer
First of all, the definitions of these constants won't tell you very much. They just represent the registers and bits used in the datasheet of the microcontroller.

If you do want to find their definitions, try looking in `~/.arduino15/`.
> 1 votes

---
Tags: library, constants, samd21g
---


# Question
Title: Is it possible to connect many arduino uno in one pc?
We have many Arduinos and we will be putting each of them in a cubicle. All of them are connected to only one PC. The PC will stand as a server were you can control your Arduino there.

# Answer
> 8 votes
Yes, you can connect multiple Arduino UNO (USB) boards to a single PC. There's a simple way and a more advanced way to manage it.

The simple way is, having multiple boards plugged in, but using only one `Arduino Software` IDE to control one board at a time. (*IDE = Integrated Development Environment. Some elements of the Arduino system use non-standard technical terms.*) **Use the `Tools > Port` menu to select which one of the attached boards to control.** The selected board type and port appear in the lower right status bar.

A more advanced way to manage multiple boards, is to open multiple Arduino Software IDE instances -- each instance has its own independent `Tools > Port` setting. You could then edit, verify, and upload two different "sketches" (*programs*) to two different boards, without losing your place and without having to constantly change the Tools \> Port setting. This would be convenient if you were developing a communications protocol between two or more boards.

**This multiple-ports technique won't work unless you launch another instance of the Arduino Software IDE, without closing the first one.** It isn't enough to use the `File` menu to open another window, because then you just get another window that shares the same `Tools > Ports` setting. Changing the ports setting on one window, changes the setting on all of the windows that belong to that instance. To support multiple boards at the same time, you have to actually launch the Arduino Software IDE again, without closing the first one, to create a second instance.

Usually you'd expect each window would represent a unique document, and they'd all be related to the application. But Arduino Software IDE has a hidden dependency between its windows. Whenever you restart the IDE, that opens a new and invisible *instance* of the IDE, where it remembers the board and port settings. If you use the File menu to open a new window, that new window is still part of the same IDE. So changing the `Tools > Port` setting on one window, changes that setting for all of the windows that belong to that instance of the IDE.

But if you restart the Arduino Software IDE (e.g. Windows Start Menu \> Arduino-1.6.0), without closing the previously opened IDE, then you get a second instance. If you pay attention to the port setting visible on the lower right status bar of each window, you can distinguish which windows belong to which IDE instance.

Each time you launch the Arduino Software IDE, you start a new *instance* of the software, that can talk to one board. Each instance of the IDE can have an unlimited number of windows, but they all share the same Tools \> Port setting. If you re-launch the Arduino Software IDE again without closing it first, then you get a second instance that can have a different Tools \> Port setting, and thus control another board at the same time.

Verified on Windows 7, Arduino Software IDE 1.6.0, with two Arduino UNO revision R2 boards (firmware rev 0001), Arduino device driver 1.0.0.0.

# Answer
> 3 votes
I've run into the same question my self just on a Mac so in case anyone with Mac run into it: It is possible to connect and use many Arduinos to Mac at the same time. To do so run `$ open -n /Applications/Arduino.app/` which will open a second instance of the Arduino IDE and you'll be able to select the Board and Port of each one and open multiple Serial windows. Notice that each Serial window has the path to the serial device which will help you know which window connected to which Arduino.

# Answer
> 2 votes
yes, you are only limited by the number of USB ports you have, however you have to consider is this is the best way to achieve what you are trying to do. You can get an ESP8266 device like the nodemcu, or something that gives you a wireless connection. With this, you can connect infinite number of devices to the central PC wirelessly. A Bluetooth module is also a good idea, it all depends on your budget and what you are trying to achieve.

# Answer
> 1 votes
I connect multiple arduinos to my ubuntu system. I use text editor to write code and upload code and read output from terminal.

List arduino devices

```
$ ls /dev/ttyACM*
/dev/ttyACM0    /dev/ttyACM1

```

To upload code to arduino

```
# to arduino 1
$ arduino --port /dev/ttyACM0 --board arduino:avr:uno --upload bt/bt.ino

 # to arduino 2
$ arduino --port /dev/ttyACM1 --board arduino:avr:mega --upload bt/bt.ino

```

To check output

```
$ screen /dev/ttyACM1 115200

$ screen /dev/ttyACM0 9600

```

---
Tags: serial
---


# Question
Title: POST request on Arduino MKR1400 GSM not working
Im trying to send a POST request from the Arduino MKR1400 GSM board to a server with a database.

I've tested the server using Postman (https://www.getpostman.com/) and it handles the POST request correctly, the json data gets uploaded to database fine.

The problem is that the same POST request from the Arduino MKR GSM 1400 does nothing. I've tried using `client.print` and I get the same result.

I'm not sure what I'm doing wrong or how to debug this issue, any ideas?

**Arduino code:**

```
#include <MKRGSM.h>
#include "Credentials.h"

// Definiciones para el GPRS
const char PINNUMBER[]     = SECRET_PINNUMBER;
const char GPRS_APN[]      = SECRET_GPRS_APN;
const char GPRS_LOGIN[]    = SECRET_GPRS_LOGIN;
const char GPRS_PASSWORD[] = SECRET_GPRS_PASSWORD;

GSMClient client;
GPRS gprs;
GSM gsmAccess;
GSMScanner scanner;

char ip[4] = {xxx,xxx,xxx,xxx};
char ipstring[14];
char path[] = "/atcapp.php";
int port = 80; // port 80 is the default for HTTP

char respName[30] = "Arduino MKR GSM 1400";
char toolName[30] = "Herramienta martillo";
char location[30] = "Mave Aeronautica S.L.";
char tlState[4] = "OUT";
unsigned long int user_id = 4294967295;
unsigned long int tool_id = 1234567899;
unsigned long int tmeStmp = 1532684104;
char notes[100] = "";

char postData[200];
char packetData[500];

void setup() {

  Serial.begin(9600);
  while(!Serial);
  sprintf(ipstring,"%d.%d.%d.%d",ip[0],ip[1],ip[2],ip[3]);
  post(respName,user_id,location,toolName,tool_id,tlState,tmeStmp,notes);

}

char post(char* resp,unsigned long int userid,char* location, char* toolName,unsigned long int toolid,char* toolState,unsigned long int timeStamp,char* notes)
{
  Serial.println("Connecting to GPRS Network...");
  boolean connected = false;

  while (!connected) {
    if ((gsmAccess.begin(PINNUMBER) == GSM_READY) &&
        (gprs.attachGPRS(GPRS_APN, GPRS_LOGIN, GPRS_PASSWORD) == GPRS_READY)) {
      connected = true;
    } else {
      Serial.println("GPRS connection failed");
      delay(1000);
      return -1;
    }
  }

  if (client.connect(ip, port)) {
    sprintf(packetData,"POST %s HTTP/1.1\nHost: %s\nUser-Agent: Arduino/1.0\nConnection: close\nContent-Length: %d\nContent-Type: application/json\nCache-Control: no-cache\n\n{\n\"responsable\":\"%s\",\n\"user_id\":%lu,\n\"loc\":\"%s\",\n\"tool\":\"%s\",\n\"tool_id\":%lu,\n\"tool_state\":\"%s\",\n\"timestamp\":%lu,\n\"note\":\"%s\"\n}\n",path,ipstring,sizeof(postData),resp,userid,location,toolName,toolid,toolState,timeStamp,notes);
    client.beginWrite();
    for(int i=0;i<sizeof(packetData);i++){
        Serial.write(packetData[i]);
        client.write(packetData[i]);
    }
    client.endWrite();

    while(client.connected()){
      Serial.println("Client still connected.");
      while(client.available()){
        Serial.println("Client still available.");
        char c = client.read();
        Serial.print(c);
      }
    }

    Serial.println("disconnecting.");
    client.stop();

    Serial.println();
    Serial.println("Done.");
    return 1;
  }else{
    Serial.println("Cannot connect to server.");
    return 0;
  }

}

void loop() {}

```

**Serial port output:**

It's my first time ever asking a question here, any contructive criticism is more than valuable to me. Thank you in advance,

# Answer
> 0 votes
The problem most likely stems from your `Content-Length` header. You are using `sizeof(postData)` as the length of your content - however `postData` is a 200 byte array which is not used for anything. `sizeof()` will always return `200` for that regardless of what the rest of your program is doing.

`Content-Length` *must* be equal to the number of bytes after the second of the two `\n` separating the header from the body. The best way to calculate that is up add up the length of all the strings that get inserted into the body formatting (using `strlen()` *not* `sizeof()`), and then add to that a constant value which is equal to the number of static characters (including `\n`) in the body (I make that 108 possibly?).

```
int dataLen = 108;
dataLen += strlen(resp);
dataLen += strlen(userid);
dataLen += strlen(location);
dataLen += strlen(toolName);
dataLen += strlen(toolid);
dataLen += strlen(toolState);
dataLen += strlen(timeStamp);
dataLen += strlen(notes);

```

Alternatively you pre-format the body into a separate string and use `strlen()` on that to get the length *before* starting to send data. Of course, you don't need to store all the header in the string, since you can just send that line-by-line...

```
sprintf(packetData,"{\n\"responsable\":\"%s\",\n\"user_id\":%lu,\n\"loc\":\"%s\",\n\"tool\":\"%s\",\n\"tool_id\":%lu,\n\"tool_state\":\"%s\",\n\"timestamp\":%lu,\n\"note\":\"%s\"\n}\n",resp,userid,location,toolName,toolid,toolState,timeStamp,notes);
client.beginWrite();
client.print(F("POST "));
client.print(path);
client.println(F(" HTTP/1.1"));

client.print(F("Host: "));
client.println(ipstring);

client.println(F("User-Agent: Arduino/1.0"));
client.println(F("Connection: close"));
client.print(F("Content-Length: "));
client.println(strlen(packetData));
client.println(F("Content-Type: application/json"));
client.println(F("Cache-Control: no-cache"));
client.println();

client.print(packetData);

client.endWrite();

```

Note the use of `F()` around your static text to save copious amounts of RAM on AVR-based boards. Not really necessary on an ARM-based board, but a good thing to get into the habit of to keep things portable.

If you want to debug what is being sent I would suggest making a "debug" wrapper class that comprises both `client` and `Serial`:

```
class TwinPrint : public Print {
    private:
        Print *_ch1;
        Print *_ch2;

    public:
        TwinPrint(Print &ch1, Print &ch2) : _ch1(&ch1), _ch2(&ch2) {}
        size_t write(uint8_t c) {
            _ch1->write(c);
            _ch2->write(c);
            return 1;
        }
};

```

You can then construct a new object:

```
TwinPrint debug(client, Serial);

```

and do your writing to that and it will come out on both `client` and `Serial` at once:

```
debug.print(F("POST "));
debug.print(path);
debug.println(F(" HTTP/1.1"));

debug.print(F("Host: "));
debug.println(ipstring);

debug.println(F("User-Agent: Arduino/1.0"));
debug.println(F("Connection: close"));
debug.print(F("Content-Length: "));
debug.println(strlen(packetData));
debug.println(F("Content-Type: application/json"));
debug.println(F("Cache-Control: no-cache"));
debug.println();

debug.print(packetData);

```

---
Tags: gsm, http, mkr1000, strlen
---


# Question
Title: Which type of sensor should i use to get RPM of an engine?
Using Arduino *(i got **leonardo** and **uno**)*, I'm looking for a way to get the **RPM of my car's engine**. I know this can be done using an OBD2 connection however i'm looking for a different way.

# Sensing?

I need a reference for a **sensor** / a **creative way** to get this data.

Having said that, these approaches came up:

* guessing the RPM by reading the amps in the car's 12V connection
* recording the sound of the engine using a microphone and setting thresholds for certain RPM values

# Answer
> 2 votes
I would think something like this would benefit you greatly. If your vehicle was produced after 1996 it will have an OBD port near the steering wheel that allows you to read diagnostic information from the car. This diagnostic information always includes error codes (think: Check engine light), and often includes operating information like speed and engine rpm.

# Answer
> 0 votes
What about measuring the speedometer? I suspect that would be easiest - you may get away with hooking up the speedo directly to the Arduino analog (but measure with multimeter first!).

# Answer
> 0 votes
I'm doing this with a TCRT5000 and a LED+phototransistor, you can find them all over Amazon and eBay. I painted one quarter of a camshaft pulley white, and the other three-quarters flat black, and mounted the optical sensor over the edge of the pulley. This is on a Subaru, where the cam pulley and timing belt are all underneath a shroud, which keeps out ambient light. It works quite well.

Plus a .1uf capacitor next to the Arduino, because the transitions between high and low were pretty noisy without it.

---
Tags: sensors
---


# Question
Title: How arduino boards eliminate the need to press buttons to flash?
I've come across many Arduino shields for various boards like the Uno, ESP8266, and ESP32 which sometimes have a button for flashing and other times they do not because the flashing is automatic.

When I upload a binary sketch to ESP32 directly through a separate Serial to USB converter, I have to make the button connections and press the buttons manually for the uploading process to work.

The manual button pressing flashing process for the ESP32 goes like this:

* Hold the Reset button (IO0 to ground)
* Hold the Flash button (EN to ground)
* Release the Reset button (IO0 to float)
* Release the Flash button (EN to 3.3v)
* The board is now in flashing mode
* Press "Upload" in Arduino IDE
* Wait until the IDE log shows "Connecting..."
* Wait until the sketch is fully uploaded
* Press the Reset button (IO0 to ground then float)

Arduino boards like the WeMos Lolin32 board eliminate the button pressing process completely during the flashing process.

**QUESTION**: Which part of the hardware on the Lolin32 board makes the flashing process autonomous?

Here's the manual uploading schematic:

And here's the WeMos Lolin32 board, that eliminates the button pressing process completely when I upload a sketch:

I believe the answer will also apply to any other auto-flashing board out there.

# Answer
I'm not familiar with this board, but according to this schematic: https://wiki.wemos.cc/\_media/products:lolin32:sch\_lolin32\_v1.0.0.pdf

U4 (one of the small 6-leg components) connects to IO0 (pin 25) on the ESP-32. The transistor inside U4 combines the RTS and DTR signals (from U6 USB-Serial converter IC, which will be the large IC marked SIL2104) to put IO0 in the correct state for flashing. The RTS and DTR signals can be set by the host (the computer doing the flashing).

Apologies for the lack of depth, but the short answer is components U4 and U6 on the board work together on the command from the host computer to put IO0 in the correct state for flashing.
> 3 votes

---
Tags: serial, usb, sketch, esp32
---


# Question
Title: The voltage level fluctuates whenever ESP8266 receives signal
Good afternoon dear community,

I am trying to built a WiFi communication with Arduino using ESP8266 module. There is one servo, one step motor connected to Arduino and whenever the ESP8266 Wi-Fi module receives a signal, the voltage level on the motor and servo fluctuate dramatically, which causes inaccurate results on how motor and servo behaves. I have connected the ESP8266 module using SoftwareSerial, and even when the signal is not transferred into motor or sevo, the voltage levels change whenever a data is received by the WiFi module.

Below is my code,

```
#include <Servo.h>
#include "SoftwareSerial.h"
SoftwareSerial softSerial(10, 11); // RX, TX

// Components:
Servo servo1;
Servo firstESC;

// Motor:
const int MAX_SPEED = 1850;
const int MIN_SPEED = 1200;
int armValue = 1500;
int speedIncrease = 20;
int speedDecrease = speedIncrease * 3;

// Direction:
int currentPos;
const int MAX_ANGLE = 120;
const int MIN_ANGLE = 60;
const int MID_ANGLE = 90;

void setup() {
   Serial.begin(9600);
   Serial.setTimeout(10);

   softSerial.begin(9600);
   // softSerial.setTimeout(10);

   // Setup servo:
   servo1.attach(9);
   servo1.write(90);

   // Setup direction:
   Serial.println("The motor is arming in 2 seconds, please wait.");
   firstESC.attach(8);

   // Arm the motor after 2 seconds:
   delay(2000);
   firstESC.writeMicroseconds(armValue);

   Serial.println("Serial is setting up, wait time: 3000 ms.");
   delay(3000);

   // Check board communication:
   softSerial.println("AT");
   delay(1000);
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   // Connect to WIFI:
   Serial.println("Connecting to wifi, wait time 4000 ms.");
   softSerial.println(--- COMMAND TO CONNECT WIFI ---);
   delay(4000);
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   // Wait for connection to be stable:
   delay(2000);

   // Get IP address:
   Serial.println("Requesting IP Address.");
   softSerial.println("AT+CIFSR");
   delay(2000);
   softSerial.println("AT+CIPMUX=1"); // Set multiple connection available.
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   delay(2000);

   // Set up server:
   Serial.println("Connecting to server..");
   softSerial.println("AT+CIPSTART=3,\"TCP\",\"192.168.1.67\",1235");
   delay(2000);
   while (softSerial.available()) {
     String message = softSerial.readString();
     Serial.println(message);
     delay(1000);
   }

   Serial.println("Set up is complete, loop started.");

}

String inString = "";
bool reading = false;

void loop() {

   while (softSerial.available() > 0)
   {
    char inChar = softSerial.read();

    if(inChar == 'O') {
      reading = false;
    }

    if(reading) {
      if (inChar == ','){
        Serial.println(inString);
        int val = inString.toInt();

        //Motor input
        if (val >= MIN_SPEED && val <= MAX_SPEED){
          setSpeed(val);
        }

        //Direction input
        else if (val >= MIN_ANGLE && val <= MAX_ANGLE ){
          setRotation(val);
        }
        inString = "";
      }
      else{
        if(inChar !='\0' && inChar != '\n' ){
          inString += inChar;
        }
      }
    }

    if(inChar == ':') {
      reading = true;
    }

   }

   if (Serial.available())
   {
      String message = Serial.readString();
      // Serial.print(message);
      setSpeed(message.toInt());
   }
}

void setSpeed(int customSpeed){
  firstESC.writeMicroseconds(customSpeed);
}

void setRotation(int angles){
  servo1.write(angles);
}

```

# Answer
> 3 votes
The ESP8266 is notoriously noisy, chiefly because the cheap boards the ESP8266 is commonly sold on don't implement any form of power filtering.

So you really have to add your own. As I had to recently when adding an ESP8266 board to an audio system.

For that I came up with this schematic:

VCCA is your main incoming power. VCCD feeds the power into the ESP8266. The motors are connected to the same point as VCCA.

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


# Question
Title: Turning LED On/Off by using SIM808 with Arduino Mega
I am trying to turn an LED on/off by using GSM 808 module. Here `#a0 = LED off` and `#a1 = LED on`. I have used `lcdShow` function to display characters in LCD display. But nothing appears on display. What is wrong in this code?

```
#include <SoftwareSerial.h>
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
//I2C pins declaration
LiquidCrystal_I2C lcd (0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
SoftwareSerial SIM808 (10, 11);
char inchar;
const int LED = 2;

void setup ()
{

    Serial.begin (9600);
    SIM808.begin (9600);
    delay (10000);
    SIM808.print ("AT+CMGF=1\r");
    delay (100);
    SIM808.print ("AT+CNMI = 2,2,0,0,0\r");
    delay (100);

    lcd.begin (16, 2);
    lcd.backlight ();

    delay (1000);

    pinMode (LED, OUTPUT);
    digitalWrite (LED, HIGH);
}

void loop ()
{
    if (SIM808.available () > 0)
    {
        inchar = SIM808.read ();
        if (inchar == '#')
        {
            lcdShow (inchar);
            delay (10);
            inchar = SIM808.read ();
            if (inchar == 'a')
            {
                lcdShow (inchar);
                delay (10);
                inchar = SIM808.read ();
                if (inchar == '0')
                {
                    lcdShow (inchar);
                    digitalWrite (LED, LOW);
                }
                else if (inchar == '1')
                {
                    lcdShow (inchar);
                    digitalWrite (LED, HIGH);
                }
            }
        }
        SIM808.println ("AT+CMGD = 1,4");
    }

}

void lcdShow (char i)
{
    lcd.setCursor (0, 0);
    lcd.print (i);
    delay (5000);

}

```

# Answer
> -1 votes
Firstly your code was really poorly formatted, making it difficult to see what it did.

After reformatting my best guess as to why you LCD is blank is that the SIM808 is does not have any data available. print something in the `else` statement.

Next it could be that the LCD is not working, print something out in `setup()`.

You might also want to add a delay to `loop()` to prevent the Arduino spamming your SIM808.

---
Tags: arduino-mega, gsm
---


# Question
Title: How to stop extra LEDs from lighting in LED cube
So I build LED cubes and the way I have it programmed is I use an analog pin for the ground layers and set them to high when i want an led on that layer lit up. So lets say I wanted the following LEDs lit

But in reality the LEDs light up in all the layers that are set to high obviously so this is what actually ends up lighting

What should I incorporate in order to avoid this happening. I am using an Arduino Nano, do I need to edit my code or is it hardware?

# Answer
> 2 votes
Your circuit design has to be used with multiplexing. Multiplexing introduces flicker. Since you seem to be wanting to move the grid of LEDs rapidly that flicker will translate into a very undesirable effect.

So you have a number of choices:

1. Re-design your system so that you don't use multiplexing. With each LED directly driven you get zero flicker, but you end up with as many wires and GPIO pins needed as you have LEDs (although shift registers could be used to move the bulk of the wiring closer to the LEDs). That's impractical.
2. Use multiplexing but have the frequency so high that flickering is no longer noticeable. We're talking thousands or millions of loops per second to keep it looking smooth (depending on how fast you are spinning the grid). You would need a high speed multiplex driver chip for this.
3. Time your multiplexing to the spinning of the grid.

The third option relies on quite a high rate of spin, since your multiplexing increments one column or row for each revolution. With 5 columns to work through it would take 5 revolutions to work through the entire grid.

You need some way of identifying the start of each revolution (e.g., a hall-effect sensor), and each time you start a new revolution you illuminate just one column of LEDs. The faster you spin the smoother the effect will be.

If you want to have LEDs on or off for just part of the revolution it's then down to you to work out when to turn them on or off for that one specific column. That's when the fun *really* begins.

---
Tags: arduino-nano, led
---


title: Arduino network with minimum wiring

text:
# Question
Title: Arduino network with minimum wiring
For a parking management system I am going to create an Arduino network.

An Arduino with an ultrasonic sensor will be placed above each parking space. If car is parked at specific location Arduino will inform master (PC) and also turn RED light ON.

I am not sure how I can make network with minimum wiring. I think RS485 will be suitable for this purpose.

There will be almost 200 Arduinos in a network. I have following questions in mind:

1. Should I go for RS485 protocol or something else?
2. Can RS485 support 200 devices as there will be only short communication (i.e device ID and parking status)?
3. I am planning to lay CAT6 cable. Two pairs will be used for power transmission and two pairs will be available for communication.

# Answer
> 3 votes
This sounds, to me, like a job for CAN. It's the current de-facto standard for industrial inter-MCU cabled connections. It's used, not only in automobiles, but also to control elevators and almost all other modern industrial distributed applications.

Note that CAN is designed to only support up to 30 nodes, so you would need to split your network into sections and have groups of nodes amalgamated together into a single sub-network. For 200 nodes you may want 10 subnetworks - that is, 20 nodes connected together to one super-node, which is then connected to the "backbone" CAN bus.

However, CAN can be run at lower baud rates than normal, and that increases the number of nodes you can have on any one network segment. It potentially (bus capacitance permitting) support thousands of nodes.

Another option is to use CAN to connect multiple "master" nodes together into a backbone, and then those "master" nodes connect to a number of sub-nodes using LIN (which is cheaper to implement than CAN).

LIN can support a maximum of 15 nodes (plus one master node) per network, so you can get a theoretical maximum of 29\*15 (assuming 1 CAN node is the connection to the PC), or 435 nodes.

You could also use RS-485, but that is also limited to around 30 "unit loads", and the number of nodes you could put on one segment is dependent on the "load" each node imposes. In practical terms it's rare to go over 30-40 nodes on a single segment, and grouping nodes together into sub-networks (as above with CAN/LIN) would be needed. So you may as well use the current standard for this kind of communication, and use CAN/LIN.

# Answer
> 0 votes
Regarding your third point, a CAT6 cable may not work as well as you expect for power delivery depending on the topology you choose. The most common variety of CAT6 uses AWG24 wires with a resistance about 0,085 Ohm/m, so a 100 m chunk of such cable will have a resistance of about 17 Ohms. Assuming a current of 100mA, you will lose 1.7V in the cable, so if you supply it with 5V, the load will only see 3.3V.

This is one more reason to split your network into segments. If I were to implement this project, I would power the "backbone" cable with higher voltage (12 - 24V) and install DC-DC converters producing 5V locally in each upper-level node.

It seems from the comments that you're looking into solutions which would allow you to use standard UARTs for communication. You can of course use RS485 (you will still need several segments). Otherwise, I advice you to look at how LIN is implemented: essentially, a 19200 bps UART signal is made open-drain (to combine all TX/RX pairs into a single wire) and amplified to 12V for noise immunity. Software-wise, a master sends a frame including slave's address and waits for a reply, then talks to the next slave and so on. Slaves only respond when they receive a frame with their address in it.

If you don't want to spend extra effort and implement something standard, at least looking into an existing spec while implementing your own solution will save you a lot of trouble.

---
Tags: rs485, network
---


title: Arduino sensing its 'Motion'

text:
# Question
Title: Arduino sensing its 'Motion'
I am working on a project where I need the Arduino to 'sense' at what direction its moving. For example, I want the Arduino to 'sense' that it is moving towards 'forward' direction, 'backwards' direction etc.

Is that possible using an Arduino? Can I use a motion sensor to do this (probably not)?

Can any one please help me to find the right 'direction'?

# Answer
For this you need a acceleration/gyro sensor, like the MPU6050.

By tracking x/y/z movements, you can define what is forward/backards etc. Also you can track angles/tilts (in 3 directions).

See an example how to use it here: MPU-6050
> 1 votes

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


title: How to print 'µ' in the serial monitor?

text:
# Question
Title: How to print 'µ' in the serial monitor?
I have been trying to print the letter `µ` on the Serial Monitor of Arduino IDE but I failed to do so. Is there any way to print `µ` or any other `Non ASCII` characters such as `Ó`,`ß`,`Ô`,`Ò`,`õ`,`Õ`,`þ`, etc using `Serial.print()`?

# Answer
> 6 votes
Most of what follows has already been covered in previous answers. I am posting this nevertheless because I feel no answer so far makes the whole story clear enough. Let me break down the question into two sub-questions.

# 1. How can I get non-ASCII characters correctly print on the serial monitor?

The answer is simply **send them as UTF-8**.

That's really all there is to it. The serial monitor expects you to send UTF-8, and it will print the characters correctly only if you use this encoding. But that brings the second question:

# 2. How can I get the characters as UTF-8 in my Arduino program?

Here you have several options:

## Option 1: encode them yourself

For example, the Greek letter “μ” (U+03BC) in UTF-8 is (0xce 0xbc). You can send those bytes explicitly, like

```
Serial.write(0xce);
Serial.write(0xbc);

```

or, more comfortably, like

```
Serial.print("\xce\xbc");

```

The second syntax is more convenient because it allows the character to be embedded within a longer string.

## Option 2: let the Arduino IDE encode them

If you can get the characters in the IDE's editor window, either with an appropriate keyboard layout or by copying and pasting from another application, then you can use them as is in the string:

```
Serial.print("μ");

```

The editor will save the source code as UTF-8, and those UTF-8 bytes will go undisturbed from the source file to the compiled program, to the Arduino memory, to the serial port, and finally to the serial monitor.

This option is the best for readability. However, it is somewhat fragile: if the source code ever gets re-encoded (e-mail clients and servers sometimes do that), then the resulting program will not work as expected.

## Options 3: let the compiler encode them

You can ask the compiler to do the UTF-8 encoding for you with the syntax

```
Serial.print(u8"\u03bc");

```

Here, the escape sequence `\u03bc` is a way to represent the Unicode character U+03BC (i.e. “μ”), and the `u8` prefix means that you want the string as a byte array encoded in UTF-8.

Note that, in practice, the `u8` prefix is not needed, as the gcc compiler assumes UTF-8 by default. I would keep the prefix anyway because it doesn't hurt to make the encoding explicit, and it may avoid angering some language lawyer...

Note also that the syntax above only works for characters U+0000 through U+FFFF, i.e. the basic multilingual plane. For other Unicode characters, you have to use the syntax `\U` \+ 8 hex digits. For example, the character “” (U+1F60E: smiling face with sunglasses) can be printed with:

```
Serial.print(u8"\U0001f60e");

```

**Clarification about UTF-16**: A common misconception has it that with `\u` you write the characters as UTF-16 code units, and with `\U` you write UTF-32 code units. But it is incorrect: both syntaxes are used to describe a single character (technically, a code point), irrespective of the encoding. Since the UTF-16 encoding for “” is (0xd83d 0xde0e), one could be tempted to write

```
// Write as UTF-16 code units in the source code.
Serial.print("\ud83d\ude0e");  // WRONG

```

but then the compiler rightfully complains

```
error: \ud83d is not a valid universal character
error: \ude0e is not a valid universal character

```

So forget about UTF-16. There is no UTF-16 involved anywhere, except in the internal representation used by a Java widget used to implement the serial monitor, which is a completely irrelevant implementation detail.

# Answer
> 1 votes
The Serial Monitor uses Unicode, so sending characters in that format is possible. The UTF-16 code for µ is 03BC, and you can send it by prepending `\u`:

```
Serial.print("\u03BC");

```

The actual stream of transformations is you provide Unicode (essentially UTF-16) in your string. C++ then converts that into a stream of 8-bit characters in UTF-8 format, which is then sent down the serial connection. Java then receives those and interprets them as UTF-8, recombining them back into the original UTF-16 characters for display in the JTextArea that comprises the Serial Monitor in the Arduino IDE.

This complex transformation is done because:

* UTF-8 is easier to stream over an 8-bit data link, but is very hard to work with in a program (because of variable-length byte sequences), and
* UTF-16 is hard to stream (and breaks ASCII compatibility) but is far easier to work with programmatically (since it is just fixed size 16-bit characters).

So your `0x03BC` gets transformed into `0xCE,0xBC` which is the UTF-8 representation of the Unicode character `0x03BC`.

# Answer
> 0 votes
It depends on your operating system, the arduino version and perhaps even on the selected board.

You have selected a weird character, because there are two versions: the *micro* µ and the *mu* μ.
See: https://en.wikipedia.org/wiki/Mu\_(letter) and https://en.wikipedia.org/wiki/Micro-. They are not the same.

In linux with the Arduino 1.8.5 and Arduino Uno board, everything supports UTF-8 (the Arduino ide, the serial monitor and the ino file).

To test it, I have written the micro character with AltGr+m in the sketch. It is stored in the ino file as C2 B5, which is UTF-8. It shows in the serial monitor as µ.

With gtkterm, it shows as a µ, and in hexadecimal and it shows C2 B5. That confirms that everything is UTF-8 in linux with Arduino version 1.8.5.

The Unicode "\u03BC" shows a µ in the serial monitor. It is stored in the ino file as 5C 75 30 33 42 43. That is not UTF-8 and not UTF-16, but ASCII for the characters "\u03BC". That is okay, since that is what is typed in the sketch. With gtkterm it shows a µ and CE BC in hexadecimal mode. The CE BC is UTF-8 for mu.

That means the Unicode is translated to UTF-8. Perhaps the compiler translates it to UTF-8?

These are the only tests that I did. It is just a very small part of all possibilities.

**Conclusion:**
Try to type µ (*mu* or *micro*) in the Arduino ide editor.
Using AltGr+m will only work if you have selected a certain keyboard settings. Perhaps you can copy the character from the Wikipedia page.
Using Unicode "\u03BC" seems to be possible.

\[ADDED\]
The **internal** format of text in Java was UTF-16, but only a fixed two byte format, not the four bytes. It was therefor only a subset of the Unicode characters. The newest Java version supports the real UTF-16 format for user strings, and thus supports all the Unicode characters.
The data that is stored to a ino file and the data that is transmitted to the serial monitor can be ASCII for normal characters with the addition of UTF-8. Most special characters that I use require two bytes in the UTF-8 format.
For Majenko: look at the binary data of a ino file and the binairy serial data. It is not a fixed two byte per character, but just one byte for normal characters.
I still don't know who translates the Unicode description of a character to UTF-8. It would be indeed weird if the compiler did that, so somewhere Java might automatically translate that.

---
Tags: arduino-uno, serial
---


# Question
Title: Can adjustable constant current/voltage source be made with Arduino?
I would like to create a 18650 battery automatic management system that can handle and restore used up cells using solar panels for power. To do that I need to create adjustable constant current source that will limit the current/voltage going into the cell/cells to a small enough value.

Since there are more features I would like to implement (like checking cell capacity) I would love to use Arduino with least amount of components as possible to keep the cost down.

My first question is: Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?

The pseudocode for logic I'm proposing is simpe:

1. Use ADC to check voltage on the capacitor (or a very small value power resistor when working as current source)
2. Calculate required voltage adjustment
3. Use AnalogWrite to set new PWM value into internal PWM controller.

Second question: PWM causes a lot of "switching" in the MOSFET. When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss? Since the batteries have some internal resistance voltage variation of +-20% should be acceptable.

# Answer
You are basically describing (if you add an inductor and a diode into the mix) a simple switching regulator. That is, at its simplist, a PWM signal, some smoothing (inductor, diode, capacitor), and feedback.

Use the Arduino's PWM to switch a P-channel MOSFET in the voltage supply. That switched supply is then fed through an inductor, and then smoothed with a capacitor:

simulate this circuit – Schematic created using CircuitLab

M1 does the switching of the power to charge the rest of the circuit. L1 + C1 smooths the PWM out giving a constant smooth (ish) voltage. D1 completes the circuit between L1 and C1 in one direction only keeping the charge in the right part of the circuit.

R1 keeps the MOSFET turned off when not being driven.

R2 is a very small "shunt" resistor (maybe 0.1Ω for example).

The size of C1 and L1 are determined by the switching frequency of your PWM and the current demands of the circuit. The higher your switching frequency the smaller your inductor can be, The higher your current demands the larger C1 needs to be.

Reading A1 gives the output voltage of the circuit, so you can adjust the PWM (using PID would be good) to get a specific voltage.

Reading A0 and A1 and subtracting one from another gives you the voltage drop across R2. From that, you can calculate the current through R2 using Ohm's Law. You can then use that to adjust the PWM to give you a specific current.

Of course, you can't do both at once. You either have a constant current (during the first charging phase to bring the cell voltage up to 4.2V), and then switch to constant voltage until the current drops to around 0.3C. For dead cells, an initial constant current phase of (IIRC) 0.1C can recover the cell.

Some important notes about lithium cells:

* They explode (just ask Samsung), so take care. It can be good to do your experimenting with the cell contained within a fireproof container.
* Lithium Ion and Lithium Polymer cells don't like being over-discharged, but as long as they haven't been reverse charged they can generally be recovered.
* Cells that are used in a series pack and haven't been charged with a proper balancing charger may well have been reverse charged if the pack has "died".

The reverse charge thing is what actually kills a Lithium cell. Basically, no two cells will have exactly the same capacity. If you have, say, three cells in series and you discharge the whole pack to below the recommended minimum, once cell will have less charge than the others. If that cell hits zero the current from the other cells will start flowing backwards through it, and that backward current causes copper crystals to deposit on the electrolyte layer between the electrodes. Those pierce the electrolyte layer and short the two electrodes together, and at that point the cell is dead. No amount of recovery charging will get it back, it's physically damaged.

So in summary:

* A single cell that has been over-discharged by itself will generally be recoverable.
* A series pack of cells that has been over-discharged may well have physically damaged one of the cells in the pack through reverse charge flow.

---

> Will Arduino be fast enough to control a MOSFET that will pump magic pixies into a capacitor to achieve steady value of voltage on said capacitor?

Sure. You should pre-condition your power so it is always within a tolerable limit (i.e., feed your solar panel power through a suitable 5V buck regulator to give a clean 5V supply). There will always be some latency in the circuit due to how long the inductor "resists" changes in the voltage. A typical Arduino takes ~100µs to sample an ADC. In this kind of environment, that time is negligible since it's generally much faster than a single period of PWM. You can't respond faster than one period of PWM anyway.

> When MOSFET is not saturated state it's resistance is high and a lot of power is wasted as heat. Would it be possible NOT to use PWM to control it, but instead to turn it OFF or ON each cycle to minimize power loss?

That's what PWM does. It's ON or OFF. On at the start of a cycle, then off part way through. Yes, there is a brief period twice per cycle while it *does* the switching, but that will be minimal compared to the on and off periods. The losses from that switching will be negligible compared to, say, running a MOSFET as an adjustable resistance controlled from an op-amp with feedback from a current shunt (i.e., a *linear* regulator).
> 1 votes

---
Tags: power, pwm, battery, solar
---


# Question
Title: Controlling servo via serial port without any delay
I have such code:

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

}
void serialEvent() {
  while (Serial.available()) {
   Serial.println(Serial.readString());
  }
  }

```

When I send there something - it's sent with a delay (1-2 seconds). How can I make it so that Serial.readString() is carried out without delay?

Please, help me)

# Answer
> 0 votes
`readString()` uses a 1 second timeout to determine when the end of a string occurs. It's not suitable for anything - I have no clue why they included it in the API.

Instead you need to read the data a character at a time (as and when characters become available) and use a suitable string termination indicator to trigger processing of the string.

A common termination indicator is `\n` (line feed) or `\r\n` (carriage-return followed by line feed).

Read each character when it arrives on the serial port and add it to a string (not a String, a string - a NULL-terminated array of `char`). Only when you see `\n` arrive should you then start examining the string to see what you have received, and act on it accordingly.

I have a blog post here that details reading from serial, and another one here that shows you some techniques for splitting up strings (`strtok()` is a useful function). There's also plenty of other questions here about splitting strings with answers detailing similar methods.

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


# Question
Title: Can multiple Arduinos be connected to a single relay?
I have a 16 channel relay that will basically manage 16 different contacts. However, each channel in the relay needs to be controlled by an individual Arduino. So in total I would have 16 different Arduino boards that will each control a single channel in the relay. Is this possible? If so, how do I make the conenctions? I tried it earlier using several arduinos and connecting their ground wires together but did not seem to work, the relays remained energized. I am using the SAINSMART 16-Channel 12V Relay Module

# Answer
Looking at the schematic, here are some points to be kept in mind when using this relay board:

* The relay board should be powered through the 12V connector
* The relay board has its own 5V regulator
* The optocouplers are attached in "reverse"

So, the external connections should be

* Connect all the arduino grounds together, and connect them to the board ground
* Do not connect any +5V wire together
* Connect arduino 1 to IN1, arduino 2 to IN2 and so on
* Writing a HIGH value on the INx pin will result in the relay to be de-energized (so contact goes in NC position), writing a LOW value on INx pin energizes the relay (so contact goes in NO position)

If making this connection the board does not work as expected, try to detach all the arduino boards and manually shorting IN1 and +5V, IN1 and GND, IN2 and +5V, ...
> 2 votes

# Answer
You could think of using 16 Arduino's sending messages (or a control signal) to a Master Arduino which controls the 16 relays.

You can use a protocol (like ModBus, I2C). Or you can connect each Arduino to a dedicated input pin of a 16:1 Multiplexer and let the Master check all 16 lines one by one to check which relay need to be enabled.

This way you can even add more intelligent logic in the Master if needed.
> 0 votes

# Answer
You wrote that joining Arduino ground together didn't work.

This leads me to believe that you didn't do the most important connection. You need to have each Arduino ground connected to the Relay Module ground. Usually this requirement is fulfilled, because people power all devices from the same power supply.

Without that Relay Module inputs are "floating", and their states are random.
> 0 votes

---
Tags: arduino-uno, relay
---


# Question
Title: EDB. Is it possible to create multiple tables with db.create()?
Good day! I seem to be having trouble creating multiple tables with EDB. I am using Arduino UNO and SD Card module to save my db.

Here is my Serial.

Here is my table declaration.

```
struct LogEvent {
  int id;
  String fname;
  float temperature;
}
logEvent;

struct SecondEvent {
  int id;
  String lastname;
}
secondEvent;

```

Here is my db.create() code.

```
db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
db.create(0, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

```

Now, when I try to retrieve, it is a whack. Here is my save and retrieve code.

```
void createRecords(int num_recs, float correctTemperature)
{
    Serial.print("Creating Records... ");
    for (int recno = 1; recno <= num_recs; recno++)
    {
      correctId++;
      logEvent.id = correctId;
      logEvent.fname = "Brix Nicholson";
      logEvent.temperature = correctTemperature;
      secondEvent.id = correctId;
      EDB_Status result = db.appendRec(EDB_REC logEvent);
      if (result != EDB_OK) printError(result);
    }
  Serial.println("DONE");
}

void createRecordSecondEvent()
 {
   correctId++;
   secondEvent.id = correctId;
   secondEvent.lastname = "Secretaria";
   EDB_Status result = db.appendRec(EDB_REC secondEvent);
   if (result != EDB_OK) printError(result);
 }

void selectLastRecord()
{
  int lastRecNum = db.count();
  EDB_Status result = db.readRec(lastRecNum, EDB_REC logEvent);
  if(result == EDB_OK)
   {
     Serial.print(" ID: ");
     Serial.print(logEvent.id);
     Serial.print(" Name: ");
     Serial.print(logEvent.fname);
     Serial.print(" Temp: ");
     Serial.println(logEvent.temperature);
   }
   else printError(result);
}

void selectLastSecondRecord()
{
 int lastRecNum = db.count();
 EDB_Status result = db.readRec(lastRecNum, EDB_REC secondEvent);
 if(result == EDB_OK)
  {
   Serial.print("Second Event ID: ");
   Serial.print(secondEvent.id);
   Serial.print("Last Name: ");
   Serial.print(secondEvent.lastname);
  }
  else printError(result);
}

```

# Answer
I think I have found the answer to my problem. I forgot to increase the address of the EDB\_header.

I wrote:

```
db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
db.create(0, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

```

Instead of:

```
db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
db.create(1, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

```
> 1 votes

# Answer
> I think I have found the answer to my problem. I forgot to increase the address of the EDB\_header.

you're right about increasing the address of EDB\_header. But the address is the position from where the library starting reading/writing.

if you have a look at https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L66 and https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L34

the library writes a fixed size of the header in the binary format which includes

1. a magic byte to recognize the EDB header
2. the number of records currently present in the table which is 0 at of this time
3. size of your single record
4. the size of the table (max amount of memory that the table is allowed to consume)

and to write a new record https://github.com/jwhiddon/EDB/blob/master/EDB.cpp#L93

so in

```
db.create(0, TABLE_SIZE, (unsigned int)sizeof(logEvent));
db.create(1, TABLE_SIZE, (unsigned int)sizeof(secondEvent));

```

the second statement will override the old header excluding the first byte (0'th position)

the solution to your problem will be

```
unsigned int FIRST_TABLE_HEADER_POSITION = 0;
db.create(FIRST_TABLE_HEADER_POSITION, FIRST_TABLE_SIZE, (unsigned int)sizeof(logEvent));

unsigned int SECOND_TABLE_HEADER_POSITION = FIRST_TABLE_HEADER_POSITION + (unsigned int)sizeof(EDB_Header) + FIRST_TABLE_SIZE;

db.create(SECOND_TABLE_HEADER_POSITION, SECOND_TABLE_SIZE, (unsigned int)sizeof(secondEvent));

```

now you can use

```
EDB_Status result = db.open(FIRST_TABLE_HEADER_POSITION );

```

and

```
db.close();
EDB_Status result = db.open(SECOND_TABLE_HEADER_POSITION );

```
> 1 votes

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


# Question
Title: Serial receiver (Arduino Micro ATmega32U4) in bad state
I have configured two Arduino Micros as a pair of multiplexer/demultiplexers communicating via Tx and Rx.

Everything works great except for one little thing. If I reset the **sender** (multiplexer) the **receiver** (demultiplexer) goes into a bad state resulting in random low and high outputs.

Resetting the receiver brings it back to a normal state but I am hoping someone might have a better solution. Using the serial monitor I noticed that during the reset process on the sender there are some seemingly random bits being transmitted toward the end. Not sure if this has anything to do with it.

The code for the sender is:

```
byte PINBold;
byte PINDold;
byte PINFold;

byte PBmask = B11111110;
byte PDmask = B11010011;
byte PFmask = B11110011;

void setup() {
  Serial1.begin(3704400); // Speed
  DDRB = DDRB & B00000001; // Sets pins to digital input: 11,10,9,8,MI,MO,SCK
  DDRD = DDRD & B00101100; // Sets pins to digital input: 2,3,4,6,12
  DDRF = DDRF & B00001100; // Sets pins to digital input: A0,A1,A2,A3,A4,A5
}

void loop() {
  if (((PINB & PBmask) != PINBold) |((PIND & PDmask) != PINDold) | ((PINF & PFmask) != PINFold)) {
    Serial1.write(PINB);
    Serial1.write(PIND);
    Serial1.write(PINF);

    PINBold = PINB & PBmask;
    PINDold = PIND & PDmask;
    PINFold = PINF & PFmask;
  }
}

```

The code fore the receiver is:

```
void setup() {
Serial1.begin(3704400); // Speed
DDRB = DDRB | B11111110; // Sets pins to digital output: 8,9,10,11,MI,MO,SCK
DDRD = DDRD | B11010011; // Sets pins to digital output: 2,3,4,6,12
DDRF = DDRF | B11110011; // Sets pins to digital output: A0,A1,A2,A3,A4,A5

PORTB = PORTB | B11111110;
PORTD = PORTD | B11010011;
PORTF = PORTF | B11110011;
}

void loop() {
if (Serial1.available() > 2) {
PORTB = Serial1.read();
PORTD = Serial1.read();
PORTF = Serial1.read();
}
}

```

# Answer
Ok, there are some issues in your code. First of all, are you sure that a baudrate of 3.7Mbps is what you need? Can't you go a bit slower?

If you are dealing with mechanical parts (e.g. buttons), then a refresh rate of 100Hz cannot be noticed; to send 3 bytes you need 30 bits, and at 9600 bit/s this means 320 Hz of frequency. Reducing the speed increases the rejection to noise too, so I'd go with a lower speed (even a 38.4kbps is fine).

Then you are reading the PINx registers too many times, which can lead to inconsistency. What happens if the value changes after the if but before the updating of the value? It's better to store it in a variable.

These, however, are not the root cause of your problem. The main issue, as anticipated by Jot, is that you are not using a protocol to synchronize the two elements. This means that at the bootup the receiver does not know if it is at the beginning of the "frame" or in the middle. Moreover start conditions when the sender is not online are not ignored.

So a "protocol" must be agreed between the two. The simplest one I can think of revolves around the fact that you can reserve a bit for the flow control.

Looking at your port masks, I can see that if we split the PINB values in the two nibbles and then move the lowest one one bit to the left, we get that bit 3 is never used for transmitting a pin data:

```
PINB 76543210 -> 7654x321 (pin 0 was not used)

```

consequently we use this as a control bit. It has value 1 for the first bit in the frame, and 0 otherwise. On the receiver side, you look for a byte with this bit set, then record also the other two, then check if the other two have a 0 in this position and, if confirmed, you have your frame.

This solution has the highest throughput, but may be a bit fragile when some noise is present (false start of frames, possibly).

For this reason I suggest you to add another byte to the packet, thus having to transmit four bytes. Again, the first one has the bit set in position 3, and the other have zero. But in this case the first byte has a predefined value, and consequently the receiver has just to look for this specific value (and the robustness is increased.

Ok people, I can hear your question. Where is the code? Well, here it is. For the sender, you have to perform a bit of manipulation on the bytes to be sent. I chose the hex value 0x5A because it has a lot of transitions (difficult to replicate from a noise) and it has a 1 bit in position 3. I also changed the things said at the beginning (baud rate and reading PINx only once); feel free to revert the changes if you have different needs. Moreover I initialized the old variables, and I set the direction of the pins based on the mask rather than having it done manually (easier to maintain).

EDIT: I added the possibility to get the current status by sending a char on the serial interface (useful when the receiver boots up)

```
byte PINBold;
byte PINDold;
byte PINFold;

const byte PBmask = B11111110;
const byte PDmask = B11010011;
const byte PFmask = B11110011;

const byte StartOfFrame = 0x5A; // bit 3 is always '1'

void setup()
{
    Serial1.begin(38400); // Speed
    DDRB = DDRB & (~PBmask); // Sets pins to digital input: 11,10,9,8,MI,MO,SCK
    DDRD = DDRD & (~PDmask); // Sets pins to digital input: 2,3,4,6,12
    DDRF = DDRF & (~PFmask); // Sets pins to digital input: A0,A1,A2,A3,A4,A5

    PINBold = ~PBmask; // Force a 1 in a forbidden position -> force a sending at first round
    PINDold = ~PDmask;
    PINFold = ~PFmask;
}

void loop() {
    byte currPINB = PINB & PBmask;
    byte currPIND = PIND & PDmask;
    byte currPINF = PINF & PFmask;

    bool shouldSendData = false;

    if ((currPINB != PINBold) || (currPIND != PINDold) || (currPINF != PINFold))
    {
        PINBold = currPINB;
        PINDold = currPIND;
        PINFold = currPINF;
        shouldSendData = true;
    }

    while (Serial1.available())
    {
        Serial1.read();
        shouldSendData = true;
    }

    if (shouldSendData)
    {
        Serial1.write(StartOfFrame);
        Serial1.write((currPINB & 0xF0) | ((currPINB >> 1) & 0x07)); // send currPINB 7654_321, where _ is a '0'
        Serial1.write(currPIND); // bit 3 is always '0'
        Serial1.write(currPINF); // bit 3 is always '0'
    }
}

```

On the receiver side, what you need is to wait for the start of frame, then you have your data. I prefer to implement it as a very small state machine. I also added a bonus timeout feature to exit from the payload state after 10ms of inactivity.

EDIT: Added the sending of a char at the beginning, to trigger a resending of the status from the master (if available). Included also the functional code from the question, since the OP added the receiver

```
const byte StartOfFrame = 0x5A; // bit 3 is always '1'

const byte PBmask = B11111110;
const byte PDmask = B11010011;
const byte PFmask = B11110011;

// State machine states
const byte SM_WaitingForSOF = 1;
const byte SM_WaitingForPayload = 2;

byte SM_CurrentState;

bool receivedData;
byte receivedPortB;
byte receivedPortD;
byte receivedPortF;

uint8_t startOfTransmissionMillis;
const byte transmissionTimeout_ms = 10;

void setup()
{
    Serial1.begin(38400); // Speed

    DDRB = DDRB | PBmask; // Sets pins to digital output: 8,9,10,11,MI,MO,SCK
    DDRD = DDRD | PDmask; // Sets pins to digital output: 2,3,4,6,12
    DDRF = DDRF | PFmask; // Sets pins to digital output: A0,A1,A2,A3,A4,A5

    SM_CurrentState = SM_WaitingForSOF;
    receivedData = false;
    receivedPortB = 0;
    receivedPortD = 0;
    receivedPortF = 0;

    Serial1.write('H'); // Any byte is ok; it is used to trigger a sending of the status
}

void loop() {
    receivedData = false;

    switch (SM_CurrentState)
    {
        case SM_WaitingForSOF:
            while (Serial1.available() > 0) // can also be a "if"
            {
                if (Serial1.read() == StartOfFrame)
                {
                    SM_CurrentState = SM_WaitingForPayload;
                    startOfTransmissionMillis = (uint8_t)millis();
                    break;
                }
            }
            break;
        case SM_WaitingForPayload:
            if (Serial1.available() >= 3)
            {
                receivedPortB = Serial1.read();
                receivedPortD = Serial1.read();
                receivedPortF = Serial1.read();

                if (((receivedPortB & 0x08) | (receivedPortD & 0x08) | (receivedPortF & 0x08)) == 0)
                { // All the payload bits have '0' as bit 3, so communication was ok
                    receivedData = true;
                }

                SM_CurrentState = SM_WaitingForSOF;
            }
            else if ((((uint8_t)millis()) - startOfTransmissionMillis) > transmissionTimeout_ms)
            {
                SM_CurrentState = SM_WaitingForSOF;
            }
            break;
        default:
            SM_CurrentState = SM_WaitingForSOF;
            break;
    }

    if (receivedData)
    {
        PORTB = (PORTB & (~PBmask)) | (receivedPortB & 0xF0) | ((receivedPortB & 0x07) << 1);
        PORTD = (PORTD & (~PDmask)) | receivedPortD;
        PORTF = (PORTF & (~PFmask)) | receivedPortF;
    }
  }
}

```

**Beware**: untested code. I'm confident that no major bugs are present, but some tweaking may be necessary
> 0 votes

---
Tags: arduino-leonardo
---


# Question
Title: How do I pull chip select pin up and down, when I have CAN shield and Newhaven Display 4.3CTP-SHIELD-N share the same chip select pin(10)?
I am currently working on an Arduino project, which must be able to listen to the data going through CAN bus and display it on the Touchscreen LCD Newhaven Display 4.3CTP-SHIELD-N.

Problem is that Sparkfun CAN shield and the LCD shield share the same chip select (CS/SS) pin 10. I've tried changing the chip select of the CAN shield by changing values in library headers, but it did not work and now I think that I should pull pin 10 low, when executing CAN code, then pull it up for the CAN shield. Afterwards, do the same for the LCD shield, but I do not know how to write the code for that. Is this the right way to think about the problem or am I missing something?

At this point, I am very confused because some people say that, if two shields have same chip select pin, it's impossible to stack them. Others claim that they succeeded in stacking two shields like that.

What other methods are there for stacking two shields with the same chip select pin?

I am using this CAN library: https://github.com/sandeepmistry/arduino-CAN/blob/master/API.md

This LCD library: https://github.com/NewhavenDisplay/FTDI\_FT801

# Answer
You will have to use a different chip select pin for one of the shields. You should do it to the display shield since that goes on top.

* Change the code to use a different chip select pin for the display shield
* Break or cut off pin 10 from the display shield, and solder a wire from where pin 10 was to your newly chosen chip select pin.
> 0 votes

---
Tags: arduino-uno, can-bus
---


# Question
Title: Arduino MKR WIFI 1010: WiFi101 shield: NOT PRESENT
A few days ago I received my MKR WIFI 1010 including MKR2UNO Board. Vin Connected via power plug, and USB to PC connected as well. The Blink example works fine. Or any example excluding WIFI. I tried to use examples in "Examples\>WIFI101" like Firmware Version or Scan Networks. It always comes back with "WiFi101 shield: NOT PRESENT" I even attempted to tun "Tools\>FirmwareUpdater" By testing the connection, it comes back with "Programmer not responding". I read somewhere that a double-tap on the reset button might help. After doing this and a click on "refresh-list", I see two ports displayed. A click on the new port and "Test connection" Same result "Programmer not responding". On the MKR 1010 I see three LED's on: They are labeled "ON", "L" and "CHRG" which is slow flashing as well. I seem not to be able find tutorials or any help really pertaining to MKR wifi 1010. Since this board is different from MKR WIFI 1000, the examples there are not helping. I also cant find any layout and explanation pf the on-board LED's. Very frustrating! I hope, any of you can give me some help. Thanks a lot!

# Answer
The right WiFi library for the MKR1010 is WiFiNINA. You can install it in Library Manager.

the schema of the board is here

from variant.h

```
// LEDs
// ----
#define PIN_LED     (6u)
#define LED_BUILTIN PIN_LED

```

you can get support from developers on Arduino forum
> 1 votes

# Answer
The WiFi101 is a shield for the Uno using the ATWINC1500 module.

The MKR1010 is a complete board with an ESP32-based module.

The two are completely different. You can't use the library for one on the other.

You need the WiFiNINA.h library which is available in the library manager, or from Github here.
> 1 votes

---
Tags: wifi
---


# Question
Title: Send AT commands to ESP8266 from Arduino Nano serial monitor
I have an Arduino nano and an ESP8266-01.

The first thing to do seems to be to send AT commands via the serial monitor and see the replies.

ESP connect as follows:

```
  GND   GND
  GPIO2 not connected
  GPIO0 not connected
  RX    to Arduino RX via level shifter
  TX    to Arduino TX via level shifter
  CHPD  3.3V
  RST   3.3V
  VCC   3.3V

```

Image of breadboard (imgur rejects) https://www.dropbox.com/s/aif8afi29amy02h/20180807\_135218.jpg?dl=0

When connecting the red light comes on and the blue light flashes quickly (and the Arduino RX light flashes with it) then goes out.

Here is the sketch I'm using. (The ESP8266 must be disconnected from RX+TX for uploading of the sketch to work.)

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

  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  delay(1000);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH);
  delay(250);
  digitalWrite(LED_BUILTIN, LOW);
  delay(3000);
 }

```

(I like to blink the LED to demonstrate that uploading worked.)

With the serial monitor set to 115200 (NL&CR) I sent `AT` and nothing happens.

What have I got wrong? I really don't understand! Thanks in advance for any suggestions.

(This is actually my third ESP8266. The first worked fine on 5V but stopped working after I set the baud rate to 9600. I presume 5V killed it but it's strange that it worked for so long. The second, connected as above, when powered up made that power supply red hot and melted the jumpers.)

# Answer
> 1 votes
First problem is that io 0 of the esp8266 must be pulled HIGH for normal boot. With io 0 not HIGH, the esp8266 starts in flashing mode.

Your other problem is the reset pin connection. It must be connected with pull-up resistor or not connected.

See ESP8266 Hardware Design Guidelines

> Pin32 serves as an RST pin which can be left floating when it is not used. The reset pin is held low when the chip is enabled. In order to avoid resets caused by external interference, the lead is generally required to be short, and no external pull-up resistor is necessary

I suspect that "The reset pin is held low when the chip is enabled." is a bad translation. They say in pin description "32 EXT\_RSTB I External reset signal (Low voltage level: Active)". What they mean is that the chip resets when reset pin is set LOW.

# Answer
> 1 votes
So:

* Connect the ESP8266 RX/TX directly to the Arduino, not via the level shifter.
* No need to connect GPIO0.
* RST can be either left floating or connected to 3.3V; it makes no difference.
* No need to `Serial.begin`; an empty sketch will work.

This is what you want to see in the terminal:

```
AT

OK
AT+CWMODE?

+CWMODE:2

OK
AT+CWMODE=1

OK
AT+CWLAP

+CWLAP:(3,"SKY61611",-83,"90:21:06:79:fb:0a",1,110,0)
+CWLAP:(3,"SKY3CA89",-90,"60:38:e0:d4:7d:7d",6,96,0)
+CWLAP:(3,"PLUSNET-TS2H",-75,"a4:08:f5:ae:ab:c2",6,103,0)
+CWLAP:(3,"SKY3CA89",-79,"90:21:06:c6:1f:6d",6,120,0)
+CWLAP:(3,"MY WIFI 6739",-38,"18:e3:bc:2c:67:39",6,127,0)
+CWLAP:(3,"BTHub6-CF7H",-88,"88:a6:c6:27:53:a4",6,108,0)
+CWLAP:(3,"SKY7A62E",-79,"7c:4c:a5:1c:7f:59",11,130,0)
+CWLAP:(4,"EE-mce6kx",-86,"e4:3e:d7:71:35:f3",11,128,0)

OK

```

The next thing to do is to set the ESP8266's baud rate to 9600 so that it can be used with `SoftwareSerial`. The command to do this is

```
AT+UART_DEF=9600,8,1,0,0

```

Then we can move the ESP8266 off the Arduino's RX/TX pins onto some other pins and forward commands from the terminal to the ESP8266 and print the responses.

```
#include <SoftwareSerial.h>

#define RX 10
#define TX 11
SoftwareSerial esp8266(RX, TX);

void setup() {
  Serial.begin(9600);
  esp8266.begin(9600);
  Serial.println("setup() done");
}

    // Check for messages form the ESP8266 and process them.
void processEsp() {
  while (esp8266.available() > 0) {
    String line = esp8266.readStringUntil('\n');
    processLine(line);
  }
}

void loop() {
  if (Serial.available() > 0)
  {
    String command = Serial.readStringUntil('\n'); // AT+CWLAP
    Serial.println("Command Sent: " + command);
    esp8266.println(command);
  }

  processEsp();
  //Serial.println("...");
  //delay(1000);
  // We wait once.
  // During that wait the buffer fills, and we only see what's in the buffer.
}

void processLine(String line) {
  Serial.println(line);
}

```

The serial reader must run in a tight loop; a `delay` causes it's buffer to fill and characters beyond the buffer length are lost. Enabling the `delay` causes the `AT+CWLAP` response to be truncated.

There is no way to detect the end of a response to an AT command. The ESP8266 can send anything at any time. What it sends should be processed line by line; the line/record delimiter is `\r\n`.

---
Tags: esp8266, arduino-nano
---


title: Serial Communication - strtok() issue

text:
# Question
Title: Serial Communication - strtok() issue
I'm working on UART communication between an ESP32 (sender) and ESP8266 NodeMCU board(receiver).

The host is sending out the following character string:

```
Serial.println("2753192144$1&");

```

The `2753192144` is the payload. The `$1&` is the trailer of the packet - `$1` signifies a particular option for the receiver and `&` is the termination character to signify that the packet is complete.

On the receiver end - this is what I have:

```
#define MAX_REC_STR_SIZE 10
#define REC_TRAILER_SIZE 4 // $1& and string terminator
#define TRUE_TRAILER_SIZE 2 // option size really

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

void loop() {
    if(Serial.available()){
    char data [MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1];
    Serial.readBytesUntil('&', data, MAX_REC_STR_SIZE + REC_TRAILER_SIZE); // data does not contain termination &
    data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator

    // Tokenizing
    char *payload = strtok(data, "$"); // getting payload
    char opt = strtok(NULL, "$")[0]; // getting option - 1 in our sample

    // Print
    Serial.println(payload);
    Serial.println(opt);
  }
}

```

**This code results in a stack exception error in the serial monitor**. If I remove the last line which prints `opt`, the payload print works fine and I get `2753192144`in the serial output.

I tested this exact code out in a standard C compiler, except instead of the serial read part - I defined a character array with `2753192144$1&` and used `printf` instead of `Serial.println`. See the code below

```
#include <stdio.h>
#include <string.h>

int main()
{
    char data[] = "2753192144$1";

    char *payload = strtok(data, "$");
    char opt = strtok(NULL, "$")[0];
    printf("Payload is %s and opt is %c", payload, opt);

    return 0;
}

```

This code outputs

```
Payload is 2753192144 and opt is 1

```

This works fine. Any ideas why the Arduino sketch isn't working?

# Answer
> 2 votes
```
data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE + 1] = 0; // adding null terminator

```

That line places a 0 in the byte *following* the array.

If you define an array of size \[x\] you have slices \[0\] to \[x-1\] available. If you try accessing \[x\] you will be altering other items on the stack after the array.

That's called a *buffer overrun* and is one of the most common causes of programs crashing.

If you want to put a 0 at the end of the array, you should use

```
data[MAX_REC_STR_SIZE + TRUE_TRAILER_SIZE] = 0; // adding null terminator

```

You should also check that the `strtok()` calls actually return a valid pointer. If the incoming string is not in the right format and `strtok()` can't split the string up, it will return NULL. If you then try and access that NULL pointer as if it were a valid array you will have a nasty crash.

---
Tags: serial, uart
---


# Question
Title: Problem in reading data from encoder with arduino
Hello guys I am trying to count the number of the steps of a stepper motor with an encoder (Avago heds).

I found an Arduino sketch to count that steps and display them on the console and I found online the scheme to connect that encoder to Arduino.

The problem is that the encoder returns as output only 0, even if I rotate manually the motor. I also tried to measure the voltage of the encoder with a voltmeter but the voltage does not change even if I rotate the motor.

That is the Arduino Sketch

Here some picture's of Arduino-encoder connections

P.S. The motor works because I tried it before

Thank you for help

# Answer
In my experience (industrial encoders and PLCs) when the output don't change when the motor shaft is rotated its usually one of the following:

* The set screw connecting the motor shaft to the encoder that isn't tight,
* broken wire (bad connection to the encoder) or
* a bad encoder.

Your picture shows what looks like a cover over the encoder coupling to the motor. Look and make sure that the encoder is actually rotating with the motor.

Then double check your connections. If a DMM still shows no voltage changes (use AC range if turning the motor to show that the encoder output is pulsing).

If there is still no joy, its likely that the encoder is bad.
> 2 votes

---
Tags: motor, stepper, rotary-encoder
---


# Question
Title: BMP280 seems to give odd pressure readings
I have connected an UNO with BMP280 and it sends reading through ESP-01 to thingspeak, and all seems working fine, but my pressure readings seem a bit odd.

To be clear any unchanged pressure reading is around 35.000 value.

As i understood that is in pascal, which is a bit strange, because the expected pascal value should be around 100.000

Code used is below, what am i missing ? Or are the readings ok?

Connection diagram and code used below:

```
    //ThingSpeak channel Key
String statusChWriteKey = "asd";

//Basic icludes
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BMP280.h>
#include <SoftwareSerial.h>
SoftwareSerial EspSerial(6, 7); // Rx,  Tx
#define HARDWARE_RESET 8

#define BMP_SCK 13
#define BMP_MISO 12
#define BMP_MOSI 11
#define BMP_CS 10

Adafruit_BMP280 bme; // I2C

int temperature = 0;
int pressure = 0;
int altitude = 0;

// Variables to be used with timers
long writeTimingSeconds = 17; // ==> Define Sample time in seconds to send data
long startWriteTiming = 0;
long elapsedWriteTime = 0;

int spare = 0;
boolean error;

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

  pinMode(HARDWARE_RESET,OUTPUT);

  digitalWrite(HARDWARE_RESET, HIGH);

  Serial.println(F("BMP280 test"));

  if (!bme.begin()) {
    Serial.println("Could not find a valid BMP280 sensor, check wiring!");
    while (1);
  }

  EspSerial.begin(9600); // Comunicacao com Modulo WiFi
  EspHardwareReset(); //Reset do Modulo WiFi
  startWriteTiming = millis(); // starting the "program clock"

}

void loop()
{

  start: //label
  error=0;

  elapsedWriteTime = millis()-startWriteTiming;

  if (elapsedWriteTime > (writeTimingSeconds*1000))
  {
    readSensors();
    writeThingSpeak();
    startWriteTiming = millis();
  }

  if (error==1) //Resend if transmission is not completed
  {
    Serial.println(" <<<< ERROR >>>>");
    delay (2000);
    goto start; //go to label "start"
  }
}

/********* Read Sensors value *************/
void readSensors(void)
{
  temperature = bme.readTemperature();
  pressure = bme.readPressure();
  altitude = bme.readAltitude(1013.25);

}

/********* Conexao com TCP com Thingspeak *******/
void writeThingSpeak(void)
{

  startThingSpeakCmd();

  String getStr = "GET /update?api_key=";
  getStr += statusChWriteKey;
  getStr +="&field1=";
  getStr += String(temperature);
  getStr +="&field2=";
  getStr += String(pressure);
  getStr +="&field3=";
  getStr += String(altitude);
  getStr +="&field4=";
  getStr += String(spare);
  getStr += "\r\n\r\n";

  sendThingSpeakGetCmd(getStr);
}

/********* Reset ESP *************/
void EspHardwareReset(void)
{
  Serial.println("Reseting.......");
  digitalWrite(HARDWARE_RESET, LOW);
  delay(500);
  digitalWrite(HARDWARE_RESET, HIGH);
  delay(8000);//Tempo necessário para começar a ler
  Serial.println("RESET");
}

/********* Start communication with ThingSpeak*************/
void startThingSpeakCmd(void)
{
  EspSerial.flush();//limpa o buffer antes de começar a gravar

  String cmd = "AT+CIPSTART=\"TCP\",\"";
  cmd += "184.106.153.149"; // Endereco IP de api.thingspeak.com
  cmd += "\",80";
  EspSerial.println(cmd);
  Serial.print("sent ==> Start cmd: ");
  Serial.println(cmd);

  if(EspSerial.find("Error"))
  {
    Serial.println("AT+CIPSTART error");
    return;
  }
}

/********* send a GET cmd to ThingSpeak *************/
String sendThingSpeakGetCmd(String getStr)
{
  String cmd = "AT+CIPSEND=";
  cmd += String(getStr.length());
  EspSerial.println(cmd);
  Serial.print("sent ==> lenght cmd: ");
  Serial.println(cmd);

  if(EspSerial.find((char *)">"))
  {
    EspSerial.print(getStr);
    Serial.print("sent ==> getStr: ");
    Serial.println(getStr);
    delay(500);//tempo para processar o GET, sem este delay apresenta busy no próximo comando

    String messageBody = "";
    while (EspSerial.available())
    {
      String line = EspSerial.readStringUntil('\n');
      if (line.length() == 1)
      { //actual content starts after empty line (that has length 1)
        messageBody = EspSerial.readStringUntil('\n');
      }
    }
    Serial.print("MessageBody received: ");
    Serial.println(messageBody);
    return messageBody;
  }
  else
  {
    EspSerial.println("AT+CIPCLOSE");     // alert user
    Serial.println("ESP8266 CIPSEND ERROR: RESENDING"); //Resend...
    spare = spare + 1;
    error=1;
    return "error";
  }
}

```

# Answer
It appears that you might be looking at a field 3 in Thingspeak instead of field 2...Here is why:

Do you live at a low elevation? Here is why I ask that question.

This statement:

pressure = bmp.readPressure();

returns the pressure in **pascals** (sea level is 101325 pascals) from the BMP280 and assigns it to the variable pressure.

To get pressure in mb you would divide by 100 (a mb is = to 1 hPa or 100 Pascals). If you were expecting a value of 100 (kPa?) perhaps that means you would be living near sea level.. perhaps about 100 feet (35m) or so.

If that is the case then the statement:

altitude = bmp.readAltitude(1013.25);

which ultimately feeds the Thingspeak field 3 the calculated altitude in meters (in this case about 35 meters). Check and make sure you are looking at Thingspeak field 2 and not field 3 for pressure readings.

If you want to see pressure in mb change the line that reads pressure from the BME280 to the following:

pressure = bmp.readPressure()/100;
> 1 votes

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


# Question
Title: Do I need a full Arduino board hardwired to a sensor to send data via Wi-Fi?
Basically I want to wire a Wheatstone bridge style load-cell into a moving trolley and transmit the data to a remote workstation so I can get real-time feedback about the loading conditions.

Do I need to have a full board riding on the trolley that is wired in between the Wi-Fi transmitter and the bridge amplifier or is there a way that the current variations from the bridge can be read directly by the Wi-Fi transmitter and relayed to the remote in some translatable format?

The trolley design is extremely streamlined and it would be a bummer to have to add more than minimal electronics to make this happen...

# Answer
> 1 votes
There are small packages out there with built in WiFi. Node MCU is one of them, however its analog to digital conversion isn't up to the task of measuring bridges. If you go that route you'll need to add a ADC to the Node MCU which will increase the total package size.

---
Tags: wifi, communication
---


# Question
Title: ESP8266HTTPClient conflict with other libraries?
I can successfully send a GET request with the ESP8266HTTPClient library in the first sketch. However the exactly same code won't work when used in the second sketch, which is more complex and uses other libraries too. I'm not sure why, maybe a conflict between libraries?

Sketch 1 (working)

```
#define DEBUG

#ifdef DEBUG
  #define SB(...) Serial.begin(__VA_ARGS__)
  #define SP(...) Serial.print(__VA_ARGS__)
  #define SPL(...) Serial.println(__VA_ARGS__)
#else
  #define SB(...)
  #define SP(...)
  #define SPL(...)
#endif

#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "TALKTALK-17409C";
const char* password = "HPHRKJYX";

void setup() {

   SB(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    SPL("Waiting to connect…");
  }

  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("http://francescosoave.com/blind/getTime.php?pw=ciao");
    int httpCode = http.GET();
    SP("HTTP: ");
    SPL(httpCode);
    if(httpCode > 0){
      String payload = http.getString();
      SP("PAYLOAD: ");
      SPL(payload);
    }

    http.end();
  }
}

void loop() {}

```

Sketch 1 response in the serial monitor (Tools -\> Debug port -\> Serial // Tools -\> Debug Level -\> HTTP\_CLIENT)

```
SDK:2.2.1(cfd48f3)/Core:2.4.1/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1)
scandone
scandone
state: 0 -> 2 (b0)
state: 2 -> 3 (0)
state: 3 -> 5 (10)
add 0
aid 3
cnt
Waiting to connect…

connected with TALKTALK-17409C, channel 10
dhcp client start...
Waiting to connect…
ip:192.168.1.4,mask:255.255.255.0,gw:192.168.1.1
Waiting to connect…
[HTTP-Client][begin] url: http://francescosoave.com/blind/getTime.php?pw=ciao
[HTTP-Client][begin] host: francescosoave.com port: 80 url: /blind/getTime.php?pw=ciao
[HTTP-Client] connected to francescosoave.com:80
[HTTP-Client] sending request header
-----
GET /blind/getTime.php?pw=ciao HTTP/1.1
Host: francescosoave.com
User-Agent: ESP8266HTTPClient
Connection: close
Accept-Encoding: identity;q=1,chunked;q=0.1,*;q=0

-----
[HTTP-Client][handleHeaderResponse] RX: 'HTTP/1.1 200 OK'
[HTTP-Client][handleHeaderResponse] RX: 'Server: nginx'
[HTTP-Client][handleHeaderResponse] RX: 'Date: Wed, 08 Aug 2018 21:24:46 GMT'
[HTTP-Client][handleHeaderResponse] RX: 'Content-Type: text/html; charset=UTF-8'
[HTTP-Client][handleHeaderResponse] RX: 'Transfer-Encoding: chunked'
[HTTP-Client][handleHeaderResponse] RX: 'Connection: close'
[HTTP-Client][handleHeaderResponse] RX: 'Vary: Accept-Encoding'
[HTTP-Client][handleHeaderResponse] RX: 'X-Powered-By: PHP/5.6.32'
[HTTP-Client][handleHeaderResponse] RX: 'Vary: Accept-Encoding'
[HTTP-Client][handleHeaderResponse] RX: 'Access-Control-Allow-Origin: *'
[HTTP-Client][handleHeaderResponse] RX: ''
[HTTP-Client][handleHeaderResponse] code: 200
[HTTP-Client][handleHeaderResponse] Transfer-Encoding: chunked
HTTP: 200
[HTTP-Client] read chunk len: 11
[HTTP-Client][writeToStreamDataBlock] connection closed or file end (written: 11).
[HTTP-Client] read chunk len: 0
[HTTP-Client][end] still data in buffer (2), clean up.
[HTTP-Client][end] tcp stop
PAYLOAD: TIME: 22:24
[HTTP-Client][end] tcp is closed
pm open,type:2 0

```

Sketch 2 (not working)

```
#define DEBUG

#ifdef DEBUG
  #define SB(...) Serial.begin(__VA_ARGS__)
  #define SP(...) Serial.print(__VA_ARGS__)
  #define SPL(...) Serial.println(__VA_ARGS__)
#else
  #define SB(...)
  #define SP(...)
  #define SPL(...)
#endif

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

const char* ssid = "TALKTALK-17409C";
const char* password = "HPHRKJYX";

ESP8266WebServer server(80);   //instantiate server at port 80 (http port)
IPAddress ip(192, 168, 1, 7);
IPAddress gateway(192, 168, 1, 1);
IPAddress subnet(255, 255, 255, 0);

String pageFinal = "";
byte curPos;
boolean timerState = true; //true = on, false = off
//int[] curTime = {0, 0}; // {hour, minutes

// HTML PAGES
String page1="<!DOCTYPE html>"
"<html>"
"<head>"
"<meta charset='utf-8'/>"
"<meta name='viewport' content='width=device-width, initial-scale=1'>"
"<meta http-equiv='Content-Type' content='text/html;charset=UTF-8' />"
"<link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css' integrity='sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B' crossorigin='anonymous'>"
"<link rel='stylesheet' type='text/css' href='http://www.francescosoave.com/blind/style.css'>"
"<script src='https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js' type='text/javascript'></script>"
"<script src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js'></script>"
"</head>"
"<body>"
"<div class='container'>"
"<div class='row'>"
"<table class='table' id='radioForm'>"
"<thead>"
"<tr><th>Fran's Blind</th></tr>"
"</thead>"
"<tbody>"
"<tr><td align='center'>"
"<form action='/' method='get' id='manualForm'>"
"<input id='1' type='submit' class='btn btn-primary' name='manualBtn' value='1' />"
"</td></tr>"
"<tr><td align='center'>"
"<input id='2' type='submit' class='btn btn-primary' name='manualBtn' value='2' />"
"</td></tr>"
"<tr><td align='center'>"
"<input id='3' type='submit' class='btn btn-primary' name='manualBtn' value='3' />"
"</td></tr>"
"<tr><td align='center'>"
"<input id='4' type='submit' class='btn btn-primary' name='manualBtn' value='4' />"
"</td></tr>"
"<tr><td align='center'>"
"<input id='5' type='submit' class='btn btn-primary' name='manualBtn' value='5' />"
"</td></tr>"
"<tr><td align='center'>"
"<input id='6' type='submit' class='btn btn-primary' name='manualBtn' value='6' />"
"</td></tr>"
"<tr><td align='center'>"
"<input id='7' type='submit' class='btn btn-primary' name='manualBtn' value='7' />"
"</form>"
"</td></tr>"
"<tr><td align='center'><form action='/' method='get'>"
"<input id='timer' name='timerBtn' value='' class='' type='submit'></form><p>Timer is <span id='timerMsg'></span></p>"
"</td></tr>"
"</tbody>"
"</table>"
"</div>"
"</div>"
"</body>"
"<script>"
"$( document ).ready(function() {"
"setInterval(function(){"
"$('#timerMsg').fadeOut(function () {"
"$(this).fadeIn();"
"});"
"} ,1000);";

// page2 / page2_5 change timer button
// page 3/ page3_5 change current position button
String page2 = "$('#timer').attr({'class': 'btn btn-danger', value: 'TURN OFF'});$('#timerMsg').html('on');});";
String page2_5 = "$('#timer').attr({'class': 'btn btn-success', value: 'TURN ON'});$('#timerMsg').html('off');});";
String page3 = "$('#";
String page3_5 = "').attr({'class': 'btn btn-warning'});";
String page4 = "</script></html>";

void setup(void){

  WiFi.config(ip, gateway, subnet);
  delay(1000);
  SB(115200);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    SPL("Waiting to connect…");
  }

  SP("IP address: ");
  SPL(WiFi.localIP());

  //here's the same GET request as in Sketch 1 but here it doesn't work
if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    http.begin("http://francescosoave.com/blind/getTime.php?pw=ciao");
    int httpCode = http.GET();
   SP("HTTP: ");
   SPL(httpCode);
    if(httpCode > 0){
      String payload = http.getString();
      SP("PAYLOAD: ");
      SPL(payload);
    }

    http.end();
  }

  server.on("/", control);
  server.begin();
  SPL("Server listening");
}

int  i = 0;

void loop(void){
  server.handleClient();
}

void control(){

  if(server.args() > 0){ //there is something to change
    if(server.argName(0) == "timerBtn"){
      timerState = !timerState; //change timer
    }else if(server.argName(0) == "manualBtn"){
      curPos = server.arg(0).toInt(); //change current (manual)
    }
  }

  //build the page
  if(timerState)
    pageFinal = page1 + page2;
  else
    pageFinal = page1 + page2_5;

  pageFinal += page3 + curPos + page3_5 + page4;
  server.send(200, "text/html", pageFinal);
}

```

Sketch 2 response in the serial monitor (Tools -\> Debug port -\> Serial // Tools -\> Debug Level -\> HTTP\_CLIENT)

```
SDK:2.2.1(cfd48f3)/Core:2.4.1/lwIP:2.0.3(STABLE-2_0_3_RELEASE/glue:arduino-2.4.1)
scandone
Waiting to connectâ€¦
IP address: 192.168.1.7
[HTTP-Client][begin] url: http://francescosoave.com/blind/getTime.php?pw=ciao
[HTTP-Client][begin] host: francescosoave.com port: 80 url: /blind/getTime.php?pw=ciao
[HTTP-Client] failed connect to francescosoave.com:80
[HTTP-Client][returnError] error(-1): connection refused
HTTP: -1
[HTTP-Client][end] tcp is closed
Server listening
pm open,type:2 0

```

edit: the issue was in the Wifi.config() line. It should be `WiFi.config(ip, gateway, subnet, gateway);`

# Answer
If you want to configure a static IP address, make sure it is unique in you LAN and outside the range managed by the DHCP server.

EDIT: the WiFi.config() function doesn't assign the gateway address as DNS address. add 4th parameter with DNS server address.

```
WiFi.config(ip, gateway, subnet, gateway);

```
> 1 votes

# Answer
Comment out the WiFi.config() line in the second example. You’re probably not configuring your ESP correctly. Let it get it’s configuration from its DHCP server.
> 0 votes

---
Tags: esp8266, http
---


title: Time-bound LED program

text:
# Question
Title: Time-bound LED program
I am trying to program a sketch such that an LED will light up for as long as a push button is pressed down. I have tested the components and electronics configuration before with a simpler program, and it all works, but there seems to be a problem in the code. I wanted to know how my sketch may be altered so the code will work:

```
const int ledPin = 12;
const int switchPin = 2;
const int Time = 100;
int buttonState = 0;
int count = 0;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(switchPin, INPUT);
}

void loop() {
buttonState = digitalRead(switchPin);
while (buttonState == HIGH) {
    count++;
    delay(100);
  }
  count=count*10;

  if (count>1) {
    digitalWrite(ledPin, HIGH);
    delay((count*10));
    digitalWrite(ledPin, LOW);
  }

}

```

# Answer
> 3 votes
```
while (buttonState == HIGH) {
    count++;
    delay(100);
}

```

this will never exit when the button is ever high. You should also reset count after the if.

Instead you want to either do `buttonState = digitalRead(switchPin);` inside the loop or rejig the function to be a state machine using timestamps like blink without delay.

# Answer
> -1 votes
Try installing a 1-10k resistor to ground connected to the input pin switchPin, assuming that the pushbutton is connecting 5V to switchPin. This will force a true logic 0 when the button is not pressed.

---
Tags: arduino-mega
---


# Question
Title: I want to make my stepper motor work for 1 hour
I already tried code that makes the stepper motor work for a few minutes only. I'm using a clock module, a DS1302 and the stepper library already present. Also the driver I'm using is an L298n. If someone could help out it would be nice. Thanks.

```
#include <Stepper.h>
#include <virtuabotixRTC.h>

virtuabotixRTC myRTC(5, 6, 7);
const int stepsPerRevolution = 200;
Stepper myStepper(stepsPerRevolution, 8, 9, 10, 11);

const int OnHour = 12;
const int OnMin = 52;
const int OffHour = 12;
const int OffMin = 55;

void setup() {
  Serial.begin(9600);
  myStepper.setSpeed(100);
}

void loop() {
  myRTC.updateTime();
  Serial.print(myRTC.dayofmonth); //You can switch between day and month if you're using American system
  Serial.print("/");
  Serial.print(myRTC.month);
  Serial.print("/");
  Serial.print(myRTC.year);
  Serial.print(" ");
  Serial.print(myRTC.hours);
  Serial.print(":");
  Serial.print(myRTC.minutes);
  Serial.print(":");
  Serial.println(myRTC.seconds);
  if (myRTC.hours >= OnHour && myRTC.minutes >= OnMin && myRTC.hours <= OffHour && myRTC.minutes < OffMin) {
    Serial.print(myRTC.hours);
    Serial.print(":");
    Serial.print(myRTC.minutes);
    Serial.print(":");
    Serial.println(myRTC.seconds);
    myStepper.step(stepsPerRevolution);
  }
}

```

# Answer
> 2 votes
The problem you have is you are treating minutes and hours separately. That won't work - they need to be combined. As it stands your "on" time is:

* Minutes greater than W, and
* Hours greater than X, and
* Minutes less than Y, and
* Hours less than Z.

Or, to rearrange that:

* Hours between X and Z, and
* Minutes between W and Y.

You can see that won't work. You will only get "on" for the block of minutes between W and Y for each hour in your "ON" period.

For example, if you want ON from 9:30 to 12:45, you get:

* If hours greater than or equal to 9 and less than or equal to 12, and
* Minutes greater than or equal to 30 and less than or equal to 45

So, that's 9:30 to 9:45, 10:30 to 10:45, 11:30 to 11:45 and 12:30 to 12:45

Even worse if you want 9:30 to 12:00... the second part of the IF above becomes:

* Minutes greater than or equal to 30 and less than or equal to than 0.

That can never happen. There is no number that is both greater than 30 and less than 0.

So you have to combine the two values together, to create a "minutes since midnight" value. Then your ON time is decided by the number of minutes, not the hours and the minutes separately. It's simple enough:

```
int minutesSinceMidnight = myRTC.hours * 60 + myRTC.minutes;

```

Your ON time then becomes, for 9:30, 9 * 60 + 30 = 570, to 12:00 = 12 * 60 + 0 = 720.

So:

```
if (minutesSinceMidnight >= 570 && minutesSinceMidnight <= 720) {
    // Do your stepping
}

```

---
Tags: arduino-uno, stepper, l298n
---