# Question
Title: How to configure 8*8 Dot Matrix LED display with this particular code?
I'm making a cryptocurrency ticker using NodeMCU ESP8266 and have this code so far, I don't know how to configure a dot matrix led 4 segments of 8\*8 each with this particular code. The only thing I need is correction is the initialization of the display.

Here's the code:

```
/*******************************************************************
    A project to display crypto currency prices using an ESP8266

    Main Hardware:
    - NodeMCU Development Board (Any ESP8266 dev board will work)
    - dot matrix led 4 segments of 8*8

    Written by Brian Lough
    https://www.youtube.com/channel/UCezJOfu7OtqGzd5xrP3q6WA
 *******************************************************************/

// ----------------------------
// Standard Libraries - Already Installed if you have ESP8266 set up
// ----------------------------

#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include <Wire.h>
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#define MATRIX32
#include  <SPI.h>

// ----------------------------
// Additional Libraries - each one of these will need to be installed.
// ----------------------------

#include <CoinMarketCapApi.h>
// For Integrating with the CoinMarketCap.com API
// Available on the library manager (Search for "CoinMarket")
// https://github.com/witnessmenow/arduino-coinmarketcap-api

//#include "SH1106.h"
// The driver for the OLED display
// Available on the library manager (Search for "oled ssd1306")
// https://github.com/squix78/esp8266-oled-ssd1306

#include <ArduinoJson.h>
// !! NOTE !!: When installing this select an older version than V6 from the drop down
// Required by the CoinMarketCapApi Library for parsing the response
// Available on the library manager (Search for "arduino json")
// https://github.com/squix78/esp8266-oled-ssd1306

// ----------------------------
// Configurations - Update these
// ----------------------------

char ssid[] = "rum1";       // your network SSID (name)
char password[] = "@@mywifi34@@";  // your network key

// Pins based on your wiring
#define MAX_DEVICES 4
#define CLK_PIN 13
#define DATA PIN 11
#define CS_PIN 10

//#define SCL_PIN D5
//#define SDA_PIN D4

// CoinMarketCap's limit is "no more than 10 per minute"
// Make sure to factor in if you are requesting more than one coin.
// We'll request a new value just before we change the screen so it's the most up to date
unsigned long screenChangeDelay = 10000; // Every 10 seconds

// Have tested up to 10, can probably do more
#define MAX_HOLDINGS 10

#define CURRENCY "eur" //See CoinMarketCap.com for currency options (usd, gbp etc)
#define CURRENCY_SYMBOL "E" // Euro doesn't seem to work, $ and £ do

// You also need to add your crypto currecnies in the setup function

// ----------------------------
// End of area you need to change
// ----------------------------

WiFiClientSecure client;
CoinMarketCapApi api(client);

display.begin(CS_PIN, MAX_DEVICES);

MD_Parola P = MD_Parola(CS_PIN, MAX_DEVICES);

//MD_Parola.h display(0x3c, SDA_PIN, SCL_PIN);

unsigned long screenChangeDue;

struct Holding {
  String tickerId;
  float amount;
  bool inUse;
  CMCTickerResponse lastResponse;
};

Holding holdings[MAX_HOLDINGS];

int currentIndex = -1;
String ipAddressString;

void addNewHolding(String tickerId, float amount = 0) {
  int index = getNextFreeHoldingIndex();
  if (index > -1) {
    holdings[index].tickerId = tickerId;
    holdings[index].amount = amount;
    holdings[index].inUse = true;
  }
}

void setup() {

  Serial.begin(115200);

  // ----------------------------
  // Holdings - Add your currencies here
  // ----------------------------
  // Go to the currencies coinmarketcap.com page
  // and take the tickerId from the URL (use bitcoin or ethereum as an example)

  addNewHolding("bitcoin");
  addNewHolding("dogecoin");
  addNewHolding("ethereum");

  // ----------------------------
  // Everything below can be thinkered with if you want but should work as is!
  // ----------------------------

  // Initialising the display
  display.init();
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 0, F("HODL Display"));
  display.setFont(ArialMT_Plain_10);
  display.drawString(64, 18, F("By Brian Lough"));
  display.display();

  // Set WiFi to station mode and disconnect from an AP if it was Previously
  // connected
  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  // Attempt to connect to Wifi network:
  Serial.print("Connecting Wifi: ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  IPAddress ip = WiFi.localIP();
  Serial.println(ip);
  ipAddressString = ip.toString();
}

int getNextFreeHoldingIndex() {
  for (int i = 0; i < MAX_HOLDINGS; i++) {
    if (!holdings[i].inUse) {
      return i;
    }
  }

  return -1;
}

int getNextIndex() {
  for (int i = currentIndex + 1; i < MAX_HOLDINGS; i++) {
    if (holdings[i].inUse) {
      return i;
    }
  }

  for (int j = 0; j <= currentIndex; j++) {
    if (holdings[j].inUse) {
      return j;
    }
  }

  return -1;
}

void displayHolding(int index) {

  CMCTickerResponse response = holdings[index].lastResponse;

  display.clear();

  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.setFont(ArialMT_Plain_16);
  display.drawString(64, 0, response.symbol);
  display.setFont(ArialMT_Plain_24);
  double price = response.price_currency;
  if (price == 0) {
    price = response.price_usd;
  }
  display.drawString(64, 20, formatCurrency(price));
  display.setFont(ArialMT_Plain_16);
//  display.setTextAlignment(TEXT_ALIGN_CENTER);
//  display.drawString(64, 48, " 1h:" + String(response.percent_change_1h) + "%");
  display.setTextAlignment(TEXT_ALIGN_CENTER);
  display.drawString(64, 48, "24h: " + String(response.percent_change_24h) + "%");

  display.display();
}

void displayMessage(String message){
  display.clear();
  display.setFont(ArialMT_Plain_10);
  display.setTextAlignment(TEXT_ALIGN_LEFT);
  display.drawStringMaxWidth(0, 0, 128, message);
  display.display();
}

String formatCurrency(float price) {
  String formattedCurrency = CURRENCY_SYMBOL;
  int pointsAfterDecimal = 6;
  if (price > 100) {
    pointsAfterDecimal = 2;
  } else if (price > 1) {
    pointsAfterDecimal = 4;
  }
  formattedCurrency.concat(String(price, pointsAfterDecimal));
  return formattedCurrency;
}

bool loadDataForHolding(int index) {
  int nextIndex = getNextIndex();
  if (nextIndex > -1 ) {
    holdings[index].lastResponse = api.GetTickerInfo(holdings[index].tickerId, CURRENCY);
    return holdings[index].lastResponse.error == "";
  }

  return false;
}

void loop() {
  unsigned long timeNow = millis();
  if ((timeNow > screenChangeDue))  {
    currentIndex = getNextIndex();
    if (currentIndex > -1) {
      if (loadDataForHolding(currentIndex)) {
        displayHolding(currentIndex);
      } else {
        displayMessage(F("Error loading data."));
      }
    } else {
      displayMessage(F("No funds to display. Edit the setup to add them"));
    }
    screenChangeDue = timeNow + screenChangeDelay;
  }
}

```

And here's the error:

```
crytodisplayDraft1:82:1: error: 'display' does not name a type

 display.begin(CS_PIN, MAX_DEVICES);

 ^

C:\Users\SUDU0005\Documents\Arduino\crytodisplayDraft1\crytodisplayDraft1.ino: In function 'void setup()':

crytodisplayDraft1:130:3: error: 'display' was not declared in this scope

   display.init();

   ^

crytodisplayDraft1:131:28: error: 'TEXT_ALIGN_CENTER' was not declared in this scope

   display.setTextAlignment(TEXT_ALIGN_CENTER);

                            ^

crytodisplayDraft1:132:19: error: 'ArialMT_Plain_16' was not declared in this scope

   display.setFont(ArialMT_Plain_16);

                   ^

crytodisplayDraft1:134:19: error: 'ArialMT_Plain_10' was not declared in this scope

   display.setFont(ArialMT_Plain_10);

                   ^

C:\Users\SUDU0005\Documents\Arduino\crytodisplayDraft1\crytodisplayDraft1.ino: In function 'void displayHolding(int)':

crytodisplayDraft1:191:3: error: 'display' was not declared in this scope

   display.clear();

   ^

crytodisplayDraft1:193:28: error: 'TEXT_ALIGN_CENTER' was not declared in this scope

   display.setTextAlignment(TEXT_ALIGN_CENTER);

                            ^

crytodisplayDraft1:194:19: error: 'ArialMT_Plain_16' was not declared in this scope

   display.setFont(ArialMT_Plain_16);

                   ^

crytodisplayDraft1:196:19: error: 'ArialMT_Plain_24' was not declared in this scope

   display.setFont(ArialMT_Plain_24);

                   ^

C:\Users\SUDU0005\Documents\Arduino\crytodisplayDraft1\crytodisplayDraft1.ino: In function 'void displayMessage(String)':

crytodisplayDraft1:212:3: error: 'display' was not declared in this scope

   display.clear();

   ^

crytodisplayDraft1:213:19: error: 'ArialMT_Plain_10' was not declared in this scope

   display.setFont(ArialMT_Plain_10);

                   ^

crytodisplayDraft1:214:28: error: 'TEXT_ALIGN_LEFT' was not declared in this scope

   display.setTextAlignment(TEXT_ALIGN_LEFT);

                            ^

Multiple libraries were found for "Wire.h"
 Använd: C:\Users\SUDU0005\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.6.3\libraries\Wire
Oanvänd: C:\Users\SUDU0005\Documents\Arduino\libraries\Wire
exit status 1
'display' does not name a type

```

So, how do I configure the display?

# Answer
> 1 votes
First and major point, is that if you want to repeat existing device, then you have wrong hardware. Comments in the code tell us:

```
 Main Hardware:
- NodeMCU Development Board (Any ESP8266 dev board will work)
- **OLED I2C Display (SH1106)**

```

You have dot matrix display with MAX7219 chip (most likely), which uses completely different library to work with. Microcontrollers are not like PCs, if you change a display, you should seriously rework the code. All code like `display.something()` has to be re-written. MD\_Parola seems to be a library for interfacing your dot matrix display. You instantiate an object of that library: `MD_Parola P = MD_Parola(CS_PIN, MAX_DEVICES);` but then never use created object `P` anywhere (also, this a bad name for an object. `display` or `matrix` are much better). Instead, code uses object `display`, which is never created - that's exactly what compiler is trying to tell you:

```
error: 'display' was not declared in this scope

```

So. to summarize: in order to change your code, you have to study MD\_Parola lib, and seriously change all functions related to display. Obviously, that's beyond a scope of a simple question...

---
Tags: esp8266, display
---


# Question
Title: How to use the Osepp proximity module with arduino uno
I have recently purchased an Osepp proximity module at Radio Shack and am attempting to use it with my Arduino Uno. How should I connect it to the Arduino, and what library do I use?

# Answer
> How should I connect it to the Arduino

Refer to the schematic in the page you link to. That shows you which pin is which. It's I2C, so there's just 2 data pins, power, and ground.

> and what library do I use?

The Osepp board is a GP2Y0D805Z0F connected to a PCA9534 IO expander. There is a library here.
> 1 votes

---
Tags: arduino-uno, proximity
---


# Question
Title: Help, I want to turn relay constantly on until a difference is detected, but triggered only one instead
Help, I want to use arduino to control relay for electricity, i get data from a sensor and when a value is detected it should be constantly on until another detection triggered again, i can get the program to work but triggered only once instead when it should be constantly turned on, here'e my code:

```
int Pinout = 13;

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

void loop() {
    int val = analogRead(A0);
    if (val <= 500) {
        digitalWrite(Pinout, LOW);
    }
    else {
        digitalWrite(Pinout, HIGH);
    }
}

```

the relay i am using is a chinese relay module with 3 pin and VCC and GND connected to external power supply, and INput pin to 13 digital pin Arduino and the relay is which i believed is Active LOW, and for analog read i am using moisture sensor

# Answer
> 1 votes
As far as I can see, the relay will stay on when `val` is less or equal than 500, and stay off when `val` is higher than 500.

However, there might be a problem when `val` keeps fastly moving around 500; it will switch on and off quite fast.

To prevent this, you should make two 'triggers', e.g. turn it on when the value \<= 480, and turn it off when the value \>= 520. When it is in between 480 and 520 it will not change. This will cause less fast changes of the relay. Of course if the initial value is already between 480 and 520 you have to make a choice yourself.

---
Tags: pins, relay, sketch
---


# Question
Title: Multiple variant.cpp entries for same physical pin
Some `variant.cpp` files have more than one entry that points to the same physical pin. For example (from Arduino Zero's file):

```
// 14..19 - Analog pins
// --------------------
{ PORTA,  2, PIO_ANALOG, PIN_ATTR_ANALOG, ADC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // ADC/AIN[0]

...

// 43..45 - Alternate use of A0 (DAC output), 44 SWCLK, 45, SWDIO
{ PORTA,  2, PIO_ANALOG, PIN_ATTR_ANALOG, DAC_Channel0, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_2 }, // DAC/VOUT

```

The first entry sets up the pin as a regular analog input pin on A0. The second entry sets it up as a DAC on pin IDE pin 43.

The corresponding `variant.h` file defines the DAC pin and A0 as entry 14, rather than 43. I also have seen plenty of examples online that use the DAC via A0 when working with an Arduino Zero.

```
/*
 * Analog pins
 */
#define PIN_A0               (14ul)
#define PIN_A1               (15ul)
#define PIN_A2               (16ul)
#define PIN_A3               (17ul)
#define PIN_A4               (18ul)
#define PIN_A5               (19ul)
#define PIN_DAC0             (14ul)

```

Finally, I see other variants, like this one that don't even bother to create a DAC-specific entry. So presumably it doesn't actually matter? If not, then why is it in the Arduino Zero `variant.cpp` file at all?

A related question: How does using a pin for multiple purposes work? For instance, if I had a pin I've configured for SPI MOSI (in `variant.cpp`), and I wanted to also use it for PWM (given the datasheet says the pin is on a SERCOM and a timer), do I actually need two entries in `variant.cpp` and thus two different IDE pins to use in my sketches (one that has a pin type of `PIO_SERCOM` and another with `PIO_PWM`)? I can think of plenty of times working with an Arduino UNO, for instance, where I've just used the same IDE pin number for general IO as well as SPI (MOSI).

# Answer
The `analogWrite` function checks the `PIN_ATTR_ANALOG` attribute from pin description in variant.cpp to determine if the pin has DAC capability. Then it checks if the pin is `ADC_Channel0` or `DAC_Channel0`. This is unnecessary and redundant. There is no other use for `DAC_Channel0`.

In Arduino SAMD core and derived cores the pin 'map' in variant.cpp defines pin capabilities used by Arduino core. It is not a complete copy of the mux table from the datasheet. In some variant.cpp files comments contain the additional mux options of the pin.

For PWM the analogWrite function configures the pin and for SPI, the SPI library configures the pin.

If you want to use the pin for other SERCOM function, the function `pinPeripheral` is used to set up the pin. Here is a tutorial.

Arduino core doesn't support a configuration of a different wave output then analogWrite. To configure a different wave output or capture, a third party library or direct registers configuration is necessary.

The Arduino `pinPeripheral(pin, peripheral)` function uses the variant.cpp mapping and the possible parameters are:

```
PIO_EXTINT=0,     /* The pin is controlled by the associated signal of peripheral A. */
PIO_ANALOG,       /* The pin is controlled by the associated signal of peripheral B. */
PIO_SERCOM,       /* The pin is controlled by the associated signal of peripheral C. */
PIO_SERCOM_ALT,   /* The pin is controlled by the associated signal of peripheral D. */
PIO_TIMER,        /* The pin is controlled by the associated signal of peripheral E. */
PIO_TIMER_ALT,    /* The pin is controlled by the associated signal of peripheral F. */
PIO_COM,          /* The pin is controlled by the associated signal of peripheral G. */
PIO_AC_CLK,       /* The pin is controlled by the associated signal of peripheral H. */
PIO_DIGITAL,      /* The pin is controlled by PORT. */

```

If you are good with the Arduino variant.cpp configuration, then for direct registers access configuration the pin 'map' from variant.cpp and the `pinPeripheral` function can be at help if the pin should not be hardcoded. Example from peripherals setup for 'phase cutting' with a Triac in my project:

```
const PinDescription& pinDesc = g_APinDescription[triacPin]; // Arduino pin description
TCC = (Tcc*) GetTC(pinDesc.ulPWMChannel);
uint8_t tcChannel = GetTCChannelNumber(pinDesc.ulPWMChannel);
bool periF = (pinDesc.ulPinAttribute & PIN_ATTR_TIMER_ALT);

// setup the pin as TCC wave out pin
pinPeripheral(triacPin, periF ? PIO_TIMER_ALT : PIO_TIMER);

TCC->CC[tcChannel].reg = PULSE_PERIOD;

```
> 1 votes

---
Tags: pins, spi, arduino-zero, samd21g, dac
---


# Question
Title: PlatformIO :collect2.exe: error: ld returned 1 exit status
I am trying some library files for esp8266. I created hpp and .cpp files. But i try to compile program i got this error on VSCode. collect2.exe: error: ld returned 1 exit status \*** \[.pio\build\huzzah\firmware.elf\] Error 1 I put files in src folder but still got this. What are points that i missed?

```
Building in release mode
Linking .pio\build\huzzah\firmware.elf
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::Neotimer()':
main.cpp:(.text._ZN8NeotimerC2Ev+0x0): multiple definition of `Neotimer::Neotimer()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8NeotimerC2Ev+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::Neotimer()':
main.cpp:(.text._ZN8NeotimerC2Ev+0x0): multiple definition of `Neotimer::Neotimer()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8NeotimerC2Ev+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::Neotimer(unsigned long)':
main.cpp:(.text._ZN8NeotimerC2Em+0x0): multiple definition of `Neotimer::Neotimer(unsigned long)'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8NeotimerC2Em+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::Neotimer(unsigned long)':
main.cpp:(.text._ZN8NeotimerC2Em+0x0): multiple definition of `Neotimer::Neotimer(unsigned long)'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8NeotimerC2Em+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::~Neotimer()':
main.cpp:(.text._ZN8NeotimerD2Ev+0x0): multiple definition of `Neotimer::~Neotimer()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8NeotimerD2Ev+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::~Neotimer()':
main.cpp:(.text._ZN8NeotimerD2Ev+0x0): multiple definition of `Neotimer::~Neotimer()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8NeotimerD2Ev+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::init()':
main.cpp:(.text._ZN8Neotimer4initEv+0x0): multiple definition of `Neotimer::init()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer4initEv+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::repeatReset()':
main.cpp:(.text._ZN8Neotimer11repeatResetEv+0x0): multiple definition of `Neotimer::repeatReset()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer11repeatResetEv+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::done()':
main.cpp:(.text._ZN8Neotimer4doneEv+0x4): multiple definition of `Neotimer::done()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer4doneEv+0x4): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::set(unsigned long)':
main.cpp:(.text._ZN8Neotimer3setEm+0x0): multiple definition of `Neotimer::set(unsigned long)'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer3setEm+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::get()':
main.cpp:(.text._ZN8Neotimer3getEv+0x0): multiple definition of `Neotimer::get()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer3getEv+0x0): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::stop()':
main.cpp:(.text._ZN8Neotimer4stopEv+0x4): multiple definition of `Neotimer::stop()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer4stopEv+0x4): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::reset()':
main.cpp:(.text._ZN8Neotimer5resetEv+0x8): multiple definition of `Neotimer::reset()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer5resetEv+0x8): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::repeat()':
main.cpp:(.text._ZN8Neotimer6repeatEv+0xc): multiple definition of `Neotimer::repeat()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer6repeatEv+0xc): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::repeat(int)':
main.cpp:(.text._ZN8Neotimer6repeatEi+0x8): multiple definition of `Neotimer::repeat(int)'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer6repeatEi+0x8): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::repeat(int, unsigned long)':
main.cpp:(.text._ZN8Neotimer6repeatEim+0x4): multiple definition of `Neotimer::repeat(int, unsigned long)'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer6repeatEim+0x4): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::start()':
main.cpp:(.text._ZN8Neotimer5startEv+0x4): multiple definition of `Neotimer::start()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer5startEv+0x4): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::debounce(bool)':
main.cpp:(.text._ZN8Neotimer8debounceEb+0x8): multiple definition of `Neotimer::debounce(bool)'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer8debounceEb+0x8): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::restart()':
main.cpp:(.text._ZN8Neotimer7restartEv+0x4): multiple definition of `Neotimer::restart()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer7restartEv+0x4): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::waiting()':
main.cpp:(.text._ZN8Neotimer7waitingEv+0x4): multiple definition of `Neotimer::waiting()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer7waitingEv+0x4): first defined here
c:/users/dogan/.platformio/packages/toolchain-xtensa/bin/../lib/gcc/xtensa-lx106-elf/4.8.2/../../../../xtensa-lx106-elf/bin/ld.exe: .pio\build\huzzah\src\main.cpp.o: in function `Neotimer::started()':
main.cpp:(.text._ZN8Neotimer7startedEv+0x0): multiple definition of `Neotimer::started()'; .pio\build\huzzah\src\communication.cpp.o:communication.cpp:(.text._ZN8Neotimer7startedEv+0x0): first defined here

```

Sorry, i am new on stackexchange community so i can do basic mistakes about usage.

Now, i am adding my main.cpp,communication.cpp and communication.h files. As i said before, i didnt included neotimer and deleted. I used to add this library to my project, PIO library interface. I am thinking this problem coming from this. Great thanks for your patient and advises.

communication.cpp:

```
#include "communication.h"
#include "database.h"
#include "management.h"
#include "wifi.h"

String GetCommand(String data, char separator, int index)
{
  int found = 0;
  int strIndex[] = {0, -1};
  int maxIndex = data.length() - 1;

  for (int i = 0; i <= maxIndex && found <= index; i++)
   {
    if (data.charAt(i) == separator || i == maxIndex)
    {
      found++;
      strIndex[0] = strIndex[1] + 1;
      strIndex[1] = (i == maxIndex) ? i + 1 : i;
    }
  }
  return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

void checkStream(WiFiServer tcpServer,WiFiClient tcpClient, Neotimer timer,boolean pulseCheck)
{

 // WiFiClient _tcpClient;
  tcpClient.setTimeout(200);
  tcpClient  = tcpServer.available();

  if(tcpClient && tcpClient.connected())
  {
    Serial.println("Timer Off");
    timer.stop();
    String requestStr = tcpClient.readStringUntil('\r');
      if(requestStr.length()>=8)
      {
        tcpClient.print(ParseStream(requestStr));
        pulseCheck = false;
        delay(3000);
         String requestSplitStr = GetCommand(requestStr, ' ', 0);
         if(requestSplitStr == "ayg_set_modem_info")
         {
          Serial.println("Device is going to sleep now!");
          Sleep();
         }
      }
  }
  else
  {
    return;
  }
}

String ParseStream(String content)
{
  String requestSplitStr = GetCommand(content, ' ', 0);
  if(requestSplitStr == "ayg_set_modem_info")
  {
    String ssid = GetCommand(content, ' ', 1);
    String pass = GetCommand(content, ' ', 2);
    Serial.println("SSID,PASS TAKING");
    delay(200);
    ClearEP();
    boolean resSsid = WriteEPSsid(ssid);
    boolean resPass = WriteEPPass(pass);
    Aprint("SSID: "+ReadEPSsid());
    Aprint("Pass: "+ReadEPPass());
    //_tcpClient.flush();
    if(resPass)
    {
      if(STATest())
      {
        return JsonResult("true");

      }
      else
      {
        return JsonResult("false");
      }

    }
    else
    {
      return JsonResult("false");
    }

  }

  else if(requestSplitStr == "ayg_get_vbatt")
  {
    return JsonResult(GetBattery());
   // _tcpClient.flush();
   // _tcpClient.stop();
  }

```

communication.h

```
#ifndef communication_h
#define communication_h
#if ARDUINO > 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <WiFiServer.h>
#include <WiFiClient.h>
#include <neotimer.h>
#include "ArduinoJson.h"

//VARIABLES

    String GetCommand(String data, char seperator, int index);
    String ParseStream(String content);
    void checkStream(WiFiServer tcpServer,WiFiClient tcpClient, Neotimer timer,boolean pulseCheck);
    String JsonResult(String result);

#endif

```

main.cpp:

```
#include <stdlib.h>
#include <HX711.h>
#include <Arduino.h>
#include <ESP8266WebServer.h>

#include <string.h>
#include "communication.h"
#include <management.h>
#include <wifi.h>
#include <database.h>

#define DOUT 13 // D7
#define SCK 15 // D8
#define led1 5 // D1- Color?
#define led2 4 // D2-Color?
#define led3 0 // D3-Color?
#define led4 2 // D4 Color?
#define led5 14 // D5 Color_?
#define button 12 //Button-D5
#define VERSION "1.0"
#define CALIBRATIONWEIGHT 5.0
#define LPG  12.2

struct rst_info *rtc_info = system_get_rst_info();
ADC_MODE(ADC_VCC);
WiFiServer _tcpServer(41400);
WiFiClient _tcpClient;
//HTTPClient http;
HX711 scale;

/*Scale Values*/
float tareValFromclient;
float calibration_factor = 26845.0;
float grossWeight;
char sGrossWeight[10];
int ledPercentage;
/*Sleep Values*/
bool sleepPulseCheck=false;

/*Timers and Intervals*/
/*const unsigned long sleepInterval = 200000; // Seconds to sleep
const unsigned long scaleInterval = 2000; // Interval for scaling tank
const unsigned long ledInterval = 200;
Neotimer sleepTimer(sleepInterval);
Neotimer scaleTimer(scaleInterval);
Neotimer ledTimer(ledInterval);*/

#pragma region PROTOYPES
/*PROTOTYPES*/
void Initialize();
String checkTankTare();
void powerUpScale();
void powerDownScale();
bool Tare();
void getGrossWeight(float *fGross, char*sGross);
String getDeviceTare();
float calculateFirstNetWeight();
float getNetWeight();
int calculatePercentage();
void ledDrivePercentage(int percentage);
String calibrateScale();
#pragma endregion

/*---------------------------------------*/

void setup() {
  ESP.eraseConfig();
  Initialize();
  Serial.println("started");
}

void loop() {
  //Serial.printf("connected:%d\n", WiFi.softAPgetStationNum()); // bağlı client sayısı
 calibrateScale();
// checkStream(_tcpServer,_tcpClient,/*sleepTimer*/sleepPulseCheck);
 ledDrivePercentage(calculatePercentage());
 WriteEPGross(sGrossWeight);

 if(sleepPulseCheck == false)
 {
   sleepPulseCheck = true;
  // sleepTimer.start();
   Serial.println("Sleep Fired");

 }
}

```

# Answer
The problem stems from the fact that the author of the Neotimer "library" defined the methods *in the header file*, see neotimer.h.

If you include this header in more than 1 source of your project, you will get these "multiple definition" errors.

To solve this issue you have (at least) these options:

1. Make Neotimer a *correct* library with separated header and source files. Compile the source into a library file. Since I'm not experienced with Arduino I don't know how other libraries do this.
    * Disadvantage: You're messing with 3rd-party code. Commonly this is discouraged. You'll have to maintain your copy of the library yourself, which renders some benefits of using libraries void.
2. Don't include `neotimer.h` in a *header* file of yours, include it only in *one of your source* files. If you need some declaration like the `Neotimer` type in other modules, add a forward declaration but don't include its header file.
3. Use another library that is better implemented.

You might say that you include `neotimer.h` in only one module. That's wrong. You included it in your own header file `communication.h`, which you include in *both* source files. This way it sneaks into *both* modules. You can't do anything about this with preprocessor "magic" because both modules are compiled independently from each other.

---

This is the class declaration of `Neotimer` as of 2020-01-12 18:40 UTC. Use as much as you need from it as forward declaration. You could even put this in decent header file.

```
class Neotimer{
    public:
    //Methods
    Neotimer();
    Neotimer(unsigned long _t);      //Constructor
    ~Neotimer();            //Destructor

    void init();            //Initializations
    boolean done();         //Indicates time has elapsed
    boolean repeat(int times);
    boolean repeat(int times, unsigned long _t);
    boolean repeat();
    void repeatReset();
    boolean waiting();          // Indicates timer is started but not finished
    boolean started();          // Indicates timer has started
    void start();           //Starts a timer
    unsigned long stop();           //Stops a timer and returns elapsed time
    void restart();
    void reset();           //Resets timer to zero
    void set(unsigned long t);
    unsigned long get();
    boolean debounce(boolean signal);
    int repetitions = NEOTIMER_UNLIMITED;

    private:

    struct myTimer{
        unsigned long time;
        unsigned long last;
        boolean done;
        boolean started;
    };

    struct myTimer _timer;
    boolean _waiting;
};

```
> 1 votes

---
Tags: esp8266
---


# Question
Title: Serial loopback not working with jumper wires connected
I'm a beginner to Arduino programming. Before attempting anything more complex I'm trying to get some very basic functionality first, so using some of the sketchbook examples I'm trying to get the most basic serial loopback working. I used the `SerialEvent` sketch as a reference point to come up with this:

```
String inputString = "";
bool stringComplete = false;
int inByte = 0;

void setup() {
  // initialize serial:
  Serial.begin(9600);
  // wait for serial port to connect. Needed for native USB port only
  while (!Serial) {
    ;
  }
  // reserve 200 bytes for the inputString:
  inputString.reserve(200);
  Serial.println("Hello world\n");
}

void loop() {
  while (Serial.available()) {
    char inChar = (char)Serial.read();
    inputString += inChar;
    if (inChar == '\n') {
      stringComplete = true;
    }
  }
  if (stringComplete) {
    Serial.println(inputString);
    inputString = "";
    stringComplete = false;
  }
}

```

When I flash that image to the Arduino and then open the Serial monitor, everything appears to work fine. As pictured below, whatever I type gets echoed back to me after pressing Enter:

However, it's a different story when I connect the TX and RX pins on the board, as pictured here:

As soon as I do that, the serial communication becomes totally non-responsive. It still prints out "Hello world" at the beginning, but it no longer echoes back the messages that get sent in, as you can see here:

I should say that even when it is no longer echoing messages back, the yellow "RX" light on the board does still briefly light up when I press Enter. But the "TX" light doesn't. Note that both lights light up if I unplug the jumper wire.

It seems to me that what I'm trying to do here is a very simple thing, that really shouldn't be this hard. Is there something obvious I'm missing? Any advice?

# Answer
You are trying to use the serial port connected to two devices at a time:

* to the on-board serial/USB bridge that allows communication with your computer
* some unspecified external serial device.

Connecting your TX (transmit pin) to two receivers is fine: whatever you write will be received by both.

Connecting your RX to two transmitters doesn't work, you can at most read the data sent by one transmitter.

On the Uno board, there are resistors along the serial connection between the main MCU and the serial/USB bridge. Thanks to the resistor on the RX line, you can connect an external device to the MCU's serial port: The device's TX will override the USB bridge. This means the main MCU can no longer receive what you send it from the serial monitor.
> 0 votes

# Answer
I can not comment, it turns out that this example that you are working is not very suitable, since the RX and TX are directly connected to the USB connection (for Arduino UNO), that is, you can only use these pins as long as it is loaded from Sketch uses An external power supply to connect the Arduino, my recommendation is to work if you have a sensor to verify the transmission of data by serial port. Greetings
> 2 votes

---
Tags: serial, c
---


title: Control LED strip via serial monitor

text:
# Question
Title: Control LED strip via serial monitor
I've been struggling with writing a code for Arduino UNO so that I could use my phone and change the colour of the LED strip via terminal.

```
#include <FastLED.h>
#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 4); // RX, TX

#define NUM_LEDS 22
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup() {

  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
}

char a;

void loop()
{
    if (btSerial.available())
    {
      a= (char)btSerial.read();

      if(a=="b")
      {
        btSerial.println("Turning LED blue");
        leds[0] = CRGB::Blue; // Turns 1 LED to blue
        FastLED.show();
      }
    }
}

```

So basically I'd like to be able to change LED colours with my phone. If you enter "r", the LEDS turn red, if you enter "b", leds turn blue etc. Maybe even add some patterns. Brightness controller would be nice too to save some battery.

EDITED. Serial works.

```
#include <FastLED.h>
#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 4); // RX, TX

#define NUM_LEDS 22
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(9600);
  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);}

char a;

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

```

3.

```
#include <FastLED.h>
#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 4); // RX, TX

#define NUM_LEDS 22
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup() {
  Serial.begin(9600);
  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);}

char a;

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

    if (a=='b'){
      btSerial.println("Turning LED blue");
      leds[0] = CRGB::Blue;
      FastLED.show();}

```

RECENT:

```
#include <FastLED.h>
#include <SoftwareSerial.h>

SoftwareSerial btSerial(2, 4); // RX, TX

#define NUM_LEDS 28
#define DATA_PIN 6
CRGB leds[NUM_LEDS];

void setup()
{
  Serial.begin(9600);
  btSerial.begin(9600);
  btSerial.println("Connected to Arduino");
  FastLED.addLeds<WS2812, DATA_PIN>(leds, NUM_LEDS);
}

char a;

void loop()
{
  if (btSerial.available())
  {
    a= (char)btSerial.read();

    if( a == 'b' )
    {
      btSerial.println("Sinine"); //All LEDs are blue
      fill_solid( leds, NUM_LEDS, CRGB::Blue);
      FastLED.show();
    }

    if( a == 'r' )
    {
      btSerial.println("Punane"); //All LEDs are red
      fill_solid( leds, NUM_LEDS, CRGB::Green);
      FastLED.show();
    }

    if( a == 'g' )
    {
      btSerial.println("Roheline"); //All LEDs are green
      fill_solid( leds, NUM_LEDS, CRGB::Red);
      FastLED.show();
    }

    if( a == 'y' )
    {
      btSerial.println("Sinine"); //All LEDs are yellow
      fill_solid( leds, NUM_LEDS, CRGB::Yellow);
      FastLED.show();
    }

    if( a == 'w' )
    {
      btSerial.println("Sinine"); //All LEDs are white
      fill_solid( leds, NUM_LEDS, CRGB::White);
      FastLED.show();
    }

    if( a == 'o' )
    {
      btSerial.println("Väljas"); //All LEDs are turned off
      fill_solid( leds, NUM_LEDS, CRGB::Black);
      FastLED.show();}

    if ( a == 'z' ) //1 blue LED from start to finish
    {
      int i= 2;
      while (i > 0)
      {
        for (int dot = 0; dot < NUM_LEDS; dot++)
        {
            leds[dot] = CRGB::Blue;
            FastLED.show();
            leds[dot] = CRGB::Black;
            delay(100);
        }
      }
    }

     if ( a == 'x' ) //1 red LED from start to finish
     {
      int i= 2;
      while (i > 0)
      {
        for (int dot = 0; dot < NUM_LEDS; dot++)
        {
            leds[dot] = CRGB::Green;
            FastLED.show();
            leds[dot] = CRGB::Black;
            delay(100);
        }
      }
     }
  }
}

```

# Answer
You seem to lack the basic understanding, how Serial (UART) communication works. So I will explain the basic principles. From there you should be able to implement, what you want.

Serial (aka UART) transmits the data serially, byte after byte (thus it's name). When you type in a text in the Serial Monitor of the Arduino IDE and send it, you have no influence, when exactly each byte will be transmitted. As the UART interface doesn't know messages or "chunks of data", only bytes, it will transmit each byte, when it is ready. There might be a short pause inbetween the bytes. This is an important fact to know, if you want to implement commands longer than 1 byte.

The normal `Serial` interface is mostly implemented in the Uno's hardware, thus it doesn't depend on the running software that much. `SoftwareSerial` does all the hard communication work in software, thus it comes with some caveats (blocking write operations, more limited baudrate, only possible to receive on one `SoftwareSerial` interface at once, ...). But both mostly share the same code interface.

`Serial.available()` returns the number of received bytes, that are still in the internal buffer. You are already using this to only read from the buffer, when there is actually data to read in it (with the if statement). Then you read one byte from the buffer by `Serial.read()`. Currently you are giving the return value (the read data) directly to the other serial interface for sending. Thus the value is not saved anywhere in your sketch. Doing a `Serial.read()` will remove the read byte from the buffer and return it. Thus the read byte will no longer be in the buffer.

The code with the 2 if statements and serial functions is mostly used to forward the data between the two serial interfaces. For your use case you don't need this. Instead you should read the data into a local variable like you did in your first sketch:

```
if (btSerial.available())
{
  a= (char)btSerial.read();

  if(a=="b")
  {
    btSerial.println("Turning LED blue");
    leds[0] = CRGB::Blue; // Turns 1 LED to blue
    FastLED.show();
  }
}

```

Here you are first checking, if there is data to read in the `btSerial` buffer. If yes, you read it into the variable `a`. This variable now holds a single character. If you also want to forward this character to `Serial`, you can now use `Serial.write(a);` to do so. Then you want to check the value of the received character. Here we are doing a little excourse:

---

In C/C++ 2 different kinds of quotes are used: The double quotes `"` and the single quotes `'`. Double quotes mark string literals, which consists of a series of characters. Single quotes mark single character values - only one character. In your if statement you check for equality. If you think about it, you see, that checking if 2 single characters are equals is a lot easier, than checking if two strings are equal (checking 1 character on each side versus checking multiple characters on each side). Thus it is a difference, if you compare string literals or single characters. Comparing a single character variable with a string literal doesn't work - they are two completely different things. Instead you should compare the character variable to a single character:

```
if( a == 'b' )

```

---

As you are adding more commands for your project, you will see, that if statements don't order the code very good. In this case a switch statement is better:

```
switch(a){
    case 'b':
        // Doing what you want to do with the LEDs here
        break;
    case 'c':
        ...
        break;
}

```

This will execute the corresponding code part depending on the value of `a`. You can read more about this construct on the web (google something like "C switch").

---

Now you should be able to implement simple 1 byte/character commands in your code. Also review and understand the examples from the Arduino IDE about Serial.

If you need more complex commands (maybe with some payload data in addition to the command), you have to introduce a communication protocol onto the Serial interface. The simplest way is to define whole messages by using a delimiter character at the end of every message. Mostly the newline `'\n'` character is used for this purpose. You basically read the data from Serial and save it on a `char`-array/string until you received the newline character. Then you know, that you have received a complete message, and you can start to process it as a whole. When finished, you clear your message buffer and again wait for a new message. For this to work, you of course have to ensure, that the delimiter character is never part of your send data (as the code would think, that it marks the end of the message).

You can see this in the `SerialEvent` example in the Arduino IDE. Try to understand, what happens there. There are also many tutorials on the web.

I hope, I could enlighten you a bit. Good luck with your project.
> 0 votes

---
Tags: led-strip
---


# Question
Title: SIM800C, CPIN: NOT READY (ERROR CODE : +CME ERROR: 10)
I'm using a SIM800C module, and usually it works fine, but lately it has started giving the error "+CPIN: NOT READY" with ERROR CODE : +CME ERROR: 10(SIM NOT INSERTED). As soon as I get this message, the voltage on SIM\_VDD drops to 0V. The problem is intermittent (i.e. it happens only sometimes).

I have read all related posts on here. Here is some info on my setup: -Schematics is designed according to SIM800C documentation. -I use 6-pin SIM connector. -Adding decoupling caps on SIM\_VDD, on input power, and on VBAT (for SIM900) does not help. -Signal strength is fine (about CSQ=20). -I tried reinserting different SIM cards, nothing helped

The "+CPIN: NOT READY" is sent at different times, however, often quite soon after power on.After removing battery & attaching it again, starts working again. why this issue is occuring..?

# Answer
The antenna is too close to the module. You probably used the spiral antenna. Try using the PCB antenna with long (10cm) cable. Had the same problem, solved with the antenna.
> 1 votes

# Answer
Definitely related to poor antenna matching. This is complex stuff and should preferably be fixed by changing antenna matching (e.g. by a matching circuit or simply trying out a different antenna). I have also seen that it helps to wait until you get the unsolicited modem response "Call Ready". Until you get this message, it can disturb the modem to receive any AT command.
> 0 votes

---
Tags: arduino-ide, gsm, atmega328, gps, rf
---


# Question
Title: Can I use a mobile charger (output 5V) to power an Arduino Uno?
I have made a home automation Arduino project using an HC-05 Bluetooth module. I want to power my Arduino from the main AC supply. Can I use a mobile charger/adapter to power it? Or should I buy a 12v adapter, and solder it to a barrel connector that fits the Arduino input?

# Answer
Yes, you can. Both options are valid.
> 4 votes

# Answer
Yes you can use any options that you have mentioned in your question. One can say your question is your answer.
> 2 votes

# Answer
> Can I use a mobile charger/adapter to power it?

The answer is almost yes: I use a phone charger myself.

Two reasons that it may not work out:

1. There are lots of unsafe, non-isolated, cheap phone chargers out there. Stay away from them. Use a brand name one that came with your phone.
2. Try to stay away from the QC2.0 or QC3.0. they are intelligent and negotiate the output voltage on the phone, up to 9 or 12v. They are compatible with non smart load but you don't want to run the risk.
> 2 votes

# Answer
Yes you can, simply connect the 5V VCC wire directly to VCC and connect GND to GND.

If using a 12V charger, then connect VCC to Vin.

**DON'T FORGET GND TO GND**
> 0 votes

# Answer
Yes you can, I tried with a sony 5V 850mA batery, it works.

I recommend you a multimeter if you haven\`t had one before.
> 0 votes

# Answer
I am in the middle of this problem now and it seems the two out of three chargers I tried attempt to negotiate the voltage with my Arduino system. Those are Huawei and Meizu ones designed to be used with multiple devices of their respective brands. The multimeter reads solid 5.2V output before I flip the switch to Arduinos. Once I flip the switch the multimeter starts jumping hectically from 1.8 to 2.6v and all the LEDs on Arduinos and other components start flashing like a Christmas tree. Browning out, I assume. The adapter that works is a really cheap nameless one that I got for free in some package.

Plugging Arduinos into the battery bank and the charger into that battery bank seems to be a very stable and versatile solution that hasn't created any problems for me yet. Except that most battery banks have trouble producing over 2 amperes of current if your system needs that much.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Problem uploading to board error, but I've selected the port and the board type?
I am having an issue when I try to upload a program to the board. I am working on a Simon Says game, and when I first started uploading, my computer handled it fine. Everything worked properly.

However, now I have added 3 LEDs for the colors and 3 buttons. I wrote a program for them to start the game, and then went to test it. That's when my Arduino would beep 3 times and then 75% of the time my computer would give me this error:

> Problem uploading to board. See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

25% of the other time I get this:

> An error occurred while uploading the sketch

It seems as though my project is getting too complicated for the Arduino to handle maybe? This is my code:

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(7, 8, 9, 10, 11, 12);

int s = 13; // Speaker
int r = 6;  // Red LED
int y = 5;  // Yellow LED
int g = 4;  // Green LED
int b1 = 3; // Red button
int b2 = 2; // Yellow button
int b3 = 1; // Green button - I don't know if pin 1 works.

void setup() {
  lcd.begin(16, 2);
  pinMode(s, OUTPUT);
  pinMode(r, OUTPUT);
  pinMode(y, OUTPUT);
  pinMode(g, OUTPUT);
  pinMode(b1, INPUT);
  pinMode(b2, INPUT);
  // pinMode(b3, INPUT); Does pin 1 work?
}

void loop() {
  lcd.print("Press any button");
  lcd.setCursor(4, 1);
  lcd.print("to play!");
  while (true) {
    if (digitalRead(b1) == HIGH) {
      break;
    }
    delay(50);
  }
  lcd.clear();
  delay(1000);
  lcd.setCursor(1, 0);
  lcd.print("Simon's turn!");
  delay(1000);
  while (true) {
    // For now, I don't want to loop. I will finish the program when this     problem is resolved.
    delay(50);
  }
}

```

Does anyone know the solution to this problem?

# Answer
Arduino play around from time to time. Which one do you use.

Unplug it and plug it back in. If Pin D0 and D1 are occupied, you may have problems with uploading.
> 1 votes

# Answer
Remove anything that is connected to the Tx and Rx pin(communication pins)

And try uploading the code and it might possibly work
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: Arduino Uno still boots and runs but no serial communication over USB
After having the Arduino Uno running for a short period of time, it seems to no longer communicate over the USB port when connected to the computer. It still seems to turn on and run the program uploaded. However, it no longer receives or outputs any data and any attempts to re-upload code are met with timeout errors in the Arduino IDE. The TX/RX lights do not blink at all, but the "L" light always flashes right after the Arduino is plugged in.

I have the Arduino/Genuino Uno board selected in the Arduino IDE.

This is a legitimate board that I bought directly from Arduino.

Loopback test fails.

Nothing is connected to any of the pins on the Arduino whatsoever.

I have an Arduino Nano that communicates fine with my Windows 10 PC so that rules out the drivers and the PC itself.

My computer still recognizes the USB device as an Arduino Uno and assigns it to COM5.

Leaving it plugged in for a solid 15 minutes shows no chips on the board getting hot to the touch.

I have tried resetting the board before, during, and after attempting to upload code, no dice.

Are there other steps that I can take to try to fix the board, or am I going to have to accept that I fried the ATMEL16 chip on my Uno?

# Answer
As @Juraj mentioned, if it's enumerating as a serial port, the atmega16u2 is fine.

You may be able to replace the atmega328p/au. It will take some doing; you'll need to remove the chip, insert a new one, and use another Arduino as an ArduinoISP to program the bootloader into your new blank atmega328p.

Any chance you might have uploaded a sketch that is spamming the serial port on startup? If so, try this procedure (h/t to the Arduino forums, it has saved my bacon a number of times):

* Disconnect the usb connection
* Begin holding the Reset button
* Connect the Arduino
* Initiate upload (while still holding Reset continuously)
* As soon as you see the RX light flash, release the Reset button.
* The first attempt to upload will fail, but with luck, the second try will occur before the 2-second bootloader delay ends (and your sketch begins to execute).

If this works, I'd suggest including a `delay(3000);` or similar in your `setup()`.
> 1 votes

# Answer
try changing the baud rate according to the code...

the standard baud rate is 9600
> 0 votes

# Answer
it happened to me. Try reinstalling the arduino board, that is, enter the board manager, remove the board and the link from your board, restart the computer and then enter the link and update the board, it is a driver problem. Greetings.
> 0 votes

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


title: How do I code delay inside a ISR?

text:
# Question
Title: How do I code delay inside a ISR?
I have built a basic obstacle avoidance robot. When the sensor senses an obstacle it gives a RISING interrupt to pin 2. At this moment I want the robot to come back for 2 seconds and turn right for 2 seconds.

I have code to turn back and rotate right but I cannot use the delay() function inside the ISR so how do I code this?

# Answer
> 5 votes
An ISR should be kept as short as possible, since while it runs, no other interrupts can be handled (including the one powering the `delay()` function. Thus you cannot delay that easy inside an ISR and you shouldn't do it either.

Instead you should set a simple flag variable in the ISR and then check this flag inside your `loop()` function. If the flag is set, you can execute the corresponding code inside the main code instead of inside an ISR.

A typical flag definition is a single byte (since then every read/write action is atomic and cannot be interrupted by an ISR). Be sure to set it volatile, so that the compiler knows, that this variable may change any time.

```
volatile byte interrupt_flag = 0;

```

In the ISR you can set this variable to 1 for example and then in your main `loop()` function:

```
if(interrupt_flag){
    // Do whatever you need to do here
    interrupt_flag = 0; // reset the flag variable
}

```

---
Tags: interrupt, robotics
---


# Question
Title: How long will program stay in memory without power?
Let's say we program an arduino uno or nano and then stop using it for a while. How long can we expect the program to last on the arduino?

# Answer
> 5 votes
More than 20 years, and probably more than 100 years.

That's the guaranteed minimum:

> Data retention: 20 years at 85°C/100 years at 25°C(1)
>
> (1) Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85°C or 100 years at 25°C.

# Answer
> 1 votes
Practically forever. Rather make sure the contacts don't become too rusty. ( 83.7 % of Arduino problems are mechanical and contact issues :) )

Will your grandchildren still have a legacy USB cable and be interested in that thing and your c++ coding skills then?

# Answer
> 0 votes
upto 20 years at 85°C and upto 100 years at 25°C

---
Tags: arduino-uno, arduino-nano, memory
---


# Question
Title: fixing drifting issue for elechouse voice recog module v3.1 and MPU6050 sensor for head mouse even after doing sensor calibration?
For my head mouse project which is based on the voice recognition module V3.1 for left click, double click, right click operations, MPU 6050 accelerometer and gyroscope for cursor movement, I am facing a problem. When I just use the MPU 6050 accelerometer and gyroscope sensor for cursor movement, the mouse cursor moves smoothly (calibration has been done). But when I integrate it with the voice recognition module, the cursor starts to drift. My code is given in this post too.

I have been using an arduino pro micro for this project. Please help. I have calibrated my MPU6050 , so it does not drift while working alone. But after integration with voice recog module (including calibration) , the drifting problem returns. I am powering the setup using a USB cable connected from the laptop to the arduino.

N.B: This is a project from a client. According to requirements, I need to make the head mouse wireless. I need suggestions for that too.

```
#include <SoftwareSerial.h>
#include "VoiceRecognitionV3.h"
#include <Mouse.h>
#include <Wire.h>
#include <I2Cdev.h>
#include <MPU6050.h>

VR myVR(8,9);    // 9:RX 8:TX

uint8_t records[7]; // save record
uint8_t buf[64];

MPU6050 mpu;
int16_t ax, ay, az, gx, gy, gz, oax, oay, oaz, ogx, ogy, ogz;
int vx, vy;

#define leftRecord    (0)
#define rightRecord   (1)
#define doubleRecord  (2)

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf     --> command length
           len     --> number of parameters
*/
void printSignature(uint8_t *buf, int len)
{
  int i;
  for(i=0; i<len; i++){
    if(buf[i]>0x19 && buf[i]<0x7F){
      Serial.write(buf[i]);
    }
    else{
      Serial.print("[");
      Serial.print(buf[i], HEX);
      Serial.print("]aurav");
    }
  }
}

/**
  @brief   Print signature, if the character is invisible,
           print hexible value instead.
  @param   buf  -->  VR module return value when voice is recognized.
             buf[0]  -->  Group mode(FF: None Group, 0x8n: User, 0x0n:System
             buf[1]  -->  number of record which is recognized.
             buf[2]  -->  Recognizer index(position) value of the recognized record.
             buf[3]  -->  Signature length
             buf[4]~buf[n] --> Signature
*/
void printVR(uint8_t *buf)
{
  Serial.println("VR Index\tGroup\tRecordNum\tSignature");
  Serial.print(buf[2], DEC);
  Serial.print("\t\t");

  if(buf[0] == 0xFF){
    Serial.print("NONE");
  }
  else if(buf[0]&0x80){
    Serial.print("UG ");
    Serial.print(buf[0]&(~0x80), DEC);
  }
  else{
    Serial.print("SG ");
    Serial.print(buf[0], DEC);
  }
  Serial.print("\t");

  Serial.print(buf[1], DEC);
  Serial.print("\t\t");
  if(buf[3]>0){
    printSignature(buf+4, buf[3]);
  }
  else{
    Serial.print("NONE");
  }
  Serial.println("\r\n");
}

void setup()
{
  /** initialize */
  Wire.begin();
  if (!mpu.testConnection()) {
    while (1);
    }

  myVR.begin(9600);
  Serial.begin(115200);
  Serial.println("Elechouse Voice Recognition V3 Module\r\nControl LED sample");

  if(myVR.clear() == 0){
    Serial.println("Recognizer cleared.");
  }else{
    Serial.println("Not find VoiceRecognitionModule.");
    Serial.println("Please check connection and restart Arduino.");
    while(1);
  }

  if(myVR.load((uint8_t)leftRecord) >= 0){
    Serial.println("leftRecord loaded");
  }

  if(myVR.load((uint8_t)rightRecord) >= 0){
    Serial.println("rightRecord loaded");
  }

  if(myVR.load((uint8_t)doubleRecord) >= 0){
    Serial.println("doubleRecord loaded");
  }

}

void loop()
{
  int ret;
  ret = myVR.recognize(buf, 50);

  mpu.getMotion6(&ax, &ay, &az, &gx, &gy, &gz);

  oax = ax-265;
  oay = ay+387;
  oaz = az+474;
  ogx = gx-109;
  ogy = gy+35;
  ogz = gz+150;

  vx = gx/120;
  vy = -gz/120;

  Mouse.move(vx, vy);

  if(ret>0){

  switch(buf[1]){

    case leftRecord:
    Mouse.click(MOUSE_LEFT);
    delay(100);
    break;

    case rightRecord:
    Mouse.click(MOUSE_RIGHT);
    delay(100);
    break;

    case doubleRecord:
    Mouse.click(MOUSE_LEFT);
    Mouse.click(MOUSE_LEFT);
    delay(100);
    break;

    default:
    Serial.println("Record function undefined");
    break;
    }
    /** voice recognized */
    printVR(buf);
  }
}

```

# Answer
> 1 votes
Your problem is most likely the use of SoftwareSerial for your VR module communication. SoftwareSerial is notorious for breaking things. It disables interrupts, and hogs the CPU.

You should be using the hardware serial port instead which, on the Pro Mini, is completely separate to USB communication.

---
Tags: mpu6050, arduino-pro-micro
---


# Question
Title: What sensors can measure 3-axis acceleration?
I'm currently measuring vibration, temp and noise using an Arduino and various inexpensive sensors. The acceleration sensor i found was sensors that measured the gravity on 3-axis of the sensor. But i'd like to measure acc, not gravity, as it moves in the direction of the sensor. For example, if an object is moving front-dir in a horizontal location, the x-directional acc is measured.

Could you tell me if you know the acc soensor i want.

# Answer
> 1 votes
> The acceleration sensor i found was sensors that measured the gravity on 3-axis of the sensor

Gravity *is* acceleration.

An accelerometer measures acceleration - or more accurately, it senses the resistance to acceleration (inertia) and equates that to acceleration.

By holding an accelerometer still you are causing it to resist the pull of gravity, and it's that "resistance" that it measures - a constant 9.8m/s²

If you let the accelerometer freefall it won't be resisting gravity any more, and will measure 0 for the Z axis.

So you simply have to "ignore" gravity, by removing that constant 9.8m/s² ("1g") of acceleration from the Z axis. And you do that by simply subtracting it.

It is normal to calibrate an accelerometer by keeping it at rest and reading the "idle" values. Those values are then subtracted from the readings to give you the actual value.

---
Tags: arduino-uno
---


title: How to exit while loop using keypad?

text:
# Question
Title: How to exit while loop using keypad?
I can't seem to be able to escape a while loop using a keypad button. I've tried the solution from this thread: https://forum.arduino.cc/index.php?topic=79932.0

Here's my code:

```
void alarm(){
  char customKey = customKeypad.getKey();

  while (customKey == NO_KEY){
    customKey = customKeypad.getKey();
    lcd.noDisplay();
    delay(750);// change for faster flash
    lcd.display();
    delay(750);// change for faster flash
  }
  lcd_home_screen();
}

```

I tried both == and != for the while (customKey == NO\_KEY)

Additional info: I am calling this alarm function from another function inside my Loop. Here's the complete code:

```
void loop() {
  // keypad
  char customKey = customKeypad.getKey();
  if (customKey == 'A'){
    main_program(5);
  }
}

int main_program(int duration){
  timer(duration);
  alarm();
}

```

# Answer
Because you're using `delay()` within your `while` loop you have to ensure that you are pressing the key at the precise moment it is read.

You should not use `delay()`.

Instead take a look at the *BlinkWithoutDelay* example in the IDE. And also consider implementing a Finite State Machine to know both if you're blinking and what state you're blinking currently is in.
> 1 votes

# Answer
To elaborate on Majenko's answer, you can create some enumeration types for the states, e.g.

```
enum EAlarmState
{
   On,
   Off
};

EAlarmState _alarmState = EAlarmState::Off;

enum EBlinkState
{
    BlinkOn,
    BlinkOff,
};

EBlinkState _blinkState = EBlinkState::BlinkOff;

unsigned int long _lastBlinkTime = 0;

```

The `_blinkState` and `_lastBlinkTime` state will not be checked when `_alarmState` is off.

Now you can use something like this to check the states and the keypad (pseudo code):

```
void loop()
{
    checkKeypad();

    switch (_alarmState)
    {
    case EAlarmStateOn:
       if (millis() - _lastBlinkTime) >= 750)
       {
          `Blink off code`
          switch(_blinkState)
          {
          case EBlinkStateOn:
             _lastBlinkTime = millis();
             'Blink off code'
             _blinkState = EBlinkState::Off;
             break;

          `same for case EBlinkStateOff'
             break;

          default: // Error
             break;
          }
       }

```

And also create state checking and changing for the alarm itself.

It looks like a lot of code (and it will be), so split it in sub functions. But the most important is that the code is fairly easy to read (and thus maintain).
> 0 votes

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


# Question
Title: Arduino not writing full NMEA sentence to SD-card file
I'm currently building a small GPS-box that's supposed to track my location and write the full NMEA sentence to an sd card.
(I want to pars it afterwards at my pc)
I'm using the Arduino Nano and the NEO-6M GPS Module to get the data.

What works: getting the NMEA data from the module, writing to the SD-card.
Outputting the data to the serial output over Serial.write works fine.

Now I have the problem that it looks like the Arduino can't write the data fast enough to the SD-card and desyncs with the GPS module. This occasionally produces things like this: `$G3,3,09,32,20,248,*4D`

I have some ideas on how to fix this:
1. write the data faster
2. always wait till the data is fully written before acquiring the next fix
3. only write every second GPS fix

I tried to implement these but failed every time (sorry I'm new to this).

Here is my current code:

```
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

SoftwareSerial GPS_Serial(4, 3); // GPS Module’s TX to D4 & RX to D3
File GPS_File;
int NBR = 1;  //file number

void setup() {
  Serial.begin(9600);
  GPS_Serial.begin(9600);
  SD.begin(5);                  //SD Pin

  //write data to a new file
  bool rn = false;
  while (rn == false) {
    if (SD.exists(String(NBR) + ".txt")) {
      NBR = NBR + 1;
    }
    else {
      GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);
      GPS_File.write("START\n");
      GPS_File.close();
      rn = true;
    }
  }
}

int x = 0;
int temp = 0;
char gpsData;
char buff[300];

void loop() {

  //collect data and write to buffer
  while (GPS_Serial.available() > 0) {
    gpsData = GPS_Serial.read();
    x++;
    buff[x] = gpsData;
  }

  temp = x;
  x = 1;

  GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);

  //copy from buffer to sd
  while (x <= temp) {
    GPS_File.print(buff[x]);
    x++;
  }

  GPS_File.close();

  x = 0;
  temp = 0;
}

```

# Answer
After trying different approaches I decided to dumb it down to its most basic level.
Without any fancy coding or buffers, I'm now just writing the data directly to the SD-card and flushing every 15 seconds which has the risk to loose up to 15 seconds of data i.e. 15 GPS-fixes (1 per second) when cutting off power.

The only other time where a potential data loss can happen is observed when the program flushes the accumulated data to the SD. This doesn't happen every time though.

To pars the NMEA-sentences into usable data I use GPSBabel. It automatically ignores the broken lines. After converting to .gpx I view it with Google Earth.

This is the "finished" code:

```
#include <SoftwareSerial.h>
#include <SPI.h>
#include <SD.h>

SoftwareSerial GPS_Serial(4, 3);  // GPS Module’s TX to D4 & RX to D3
File GPS_File;
int NBR = 1;                      //file number

unsigned long TimerA;             //save timer
bool sw = false;                  //save timer switch

void setup() {
  Serial.begin(9600);
  GPS_Serial.begin(9600);
  SD.begin(5);                    //SD Pin

  //write data to a new file
  bool rn = false;
  while (rn == false) {
    if (SD.exists(String(NBR) + ".txt")) {
      NBR = NBR + 1;
    }
    else {
      GPS_File = SD.open(String(NBR) + ".txt", FILE_WRITE);
      GPS_File.write("START\n");
      rn = true;
    }
  }
}

void loop() {
  while (GPS_Serial.available() > 0) {
    GPS_File.write(GPS_Serial.read());
  }

  //set up timer
  if ( sw == false) {
    TimerA = millis();
    sw = true;
  }

  //save every 15 seconds
  if (millis() - TimerA >= 15000UL) {
    GPS_File.flush();
    sw = false;
  }
}

```
> 0 votes

---
Tags: serial, arduino-nano, sd-card, gps, sd.h
---


# Question
Title: Unreliable communication with low baudrate on Leonardo
I am using an Arduino Leonardo (more precisely this product), to communicate with servo-motors) using RS485.

Everything works fine as long as I don't go below a baud rate or 115200bps. If I go below, as 57600 or 9600, I start to get ill-formed packets from my motors: the 4 first bytes are usually correct, but the end of the packet contains incoherent data, and the checksum is obviously wrong.

I am using IndustrialShields (my PLC/Arduino vendor) library for RS485, and I don't see any mention of this problem. I am using Half-duplex communication, with U2X if I correcly understand the source code of the library.

Note that the documentation of the servo-motors mentions there is a small error margin on the clock for low baud rates, but since it works with 115200bps, which has the highest error margin, it shouldn't be a problem.

Also the motors seems to understand the packet I send, but I do not receive their packet correctly.

Is there an edge-case I am not aware of? Sorry for the lack of details, I am not sure what else I can say.

# Answer
> 1 votes
I suspect that the RS-485 interface in your servo is what is at fault. Nothing to do with the Arduino or your communication, or software.

Without knowing more about the servos and how they are wired internally it's hard to be certain, but I can assume:

* The servo has some kind of controller in it which communicates over the bus
* That controller may or may not directly control the direction pin on its interface

It's the latter that is critical. There is a way of wiring up a MAX485 that automatically controls the direction pin - immediately you start sending data it asserts it into TX mode. The trouble comes when switching back to RX mode - there's a few ways of doing that:

1. Shortly after the last bit of a certain value (0 or 1) has been sent (the bit stream keeps a capacitor charged)
2. A certain time after the start of communication.

The first method is usually more reliable across multiple baud rates, but can be sensitive to the values of the bytes sent - if it relies on a 1 being sent to keep the capacitor charged and a number of 0 bytes are being sent it won't see the 1 that keeps the transmit mode open, and it can close prematurely.

The second method is more reliable for fixed length packets, but will only work for a certain (or small range) of baud rates. If sending a packet takes longer than the allotted window then it will truncate regardless.

However if the controller in the servo is itself directly controlling the data direction pin then it could be that there is a bug in its firmware. Maybe it's working on a delay principle and they got the time calculations wrong. Maybe it's working on a "queue being empty" principle and they forgot about there being a hardware buffer that also needs to empty, but high baud rates just manage to squeeze through in time.

It's impossible to be sure, but going by the symptoms you describe those seem to be the most logical scenarios.

---
Tags: arduino-leonardo, rs485
---


# Question
Title: What are the main differences between Arduino and mbed?
I have been working a lot with the Arduino platform over the last year. Arduino makes it very easy for beginners (in my opinion) to get started and has a large community and a lot of libraries for all kinds of peripherals.

Now, I am considering to have a look at mbed, too. What are the main differences I would face, both practical and conceptually?

# Answer
> 8 votes
As both an Mbed user and an Arduino user, this is my perspective on the differences between the platforms.

1. The IDEs are completely different. The Mbed IDE is an in-browser compiler that allows you to easily import other people's source code. It is a full c/c++ IDE that saves your code to your online Mbed account. You must be signed in to do any development work (requires internet access). Code completion exists, but is clunky. Project format more closely mirrors c/c++ programming than does Arduino's environment.
2. Programming the board is different. The Mbed uses a custom boot loader. The Mbed shows up as a flash drive when you plug it into your computer via USB. You compile your code using the online IDE, download the .hex file, and copy it to the Mbed. It's actually pretty neat, but more time consuming than clicking the 'Upload' button in the Arduino IDE.
3. The Hardware is different. This means different pinouts, as well as different capabilities. Take a look at the Mbed platforms and compare them to the Arduinos. Mbeds are generally more powerful than Arduinos (cpu speed, mem size, build in capabilities).

I use my Mbed when my Arduino isn't powerful enough or fast enough. It would replace Arduinos for me if it wasn't for the online IDE. The IDE is a little awkward to use, and it takes too long to program the board (downloading/copying and pasting is much more inconvenient).

I'm able to use all my same sensors and peripherals that I purchased for the Arduino with my Mbed (Except for shields due to the physical layout differences). I sometimes have to rewrite code to get it to work on the Mbed, but that's a good learning exercise.

# Answer
> 1 votes
Mbed is so cool.The code is written everywhere that can get internet access. You doesn't like online IDE, you can get offline IDE such as Keil, GCC. You can get other kind of interface such as Matlab and LabView. Component and library is express together at main website. We can import lib: directly to workplace. If you have an idea, it is good to implement your idea quickly and best for prototyping. I also like Arduino but I like mbed than Arduino.

# Answer
> 1 votes
You can run mbed offline. I do my development in VSCode using the mbed-cli to compile and pyopenOCD for debugging. The instructions on the website didn't seem to work out of the box on Windows. Wasn't too difficult to set-up, though.

---
Tags: mbed
---


title: Adafruit 128x64 OLED not turning on

text:
# Question
Title: Adafruit 128x64 OLED not turning on
I ordered a 128x64 pixel OLED display from Adafruit and wired it according to their guide. (To an Arduino Uno) I'm using SPI right now and the display will not turn on or do anything. I haven't tried i2C, but I don't think that should make a difference. Maybe I will if nothing else works. I've installed the two libraries from the guide and am running the SPI 128x64 example. I've tried to find people with this same issue but I haven't found that much about it. Any help would be greatly appreciated!

Edit: Added pictures. I've used header pins in the past in case anyone is wondering if the connection using these wires isn't good, but the pins did not work either, so it's not a bad connection.

# Answer
Wiring is your problem. Use soldering iron/solder and flux. Solder your wires. Intermittent connections and accidental shortages with current setup may damage your Arduino and display (and possible your PC/laptop).
> 3 votes

# Answer
I know this issue and understand it well.

If the module is genuine from Adafruit then it should definitely work, if not then once try this library https://github.com/olikraus/U8glib\_Arduino

This library has very good documentation. Further if it does not work, attach the picture of wiring.
> 0 votes

# Answer
Its not every time fault of hardware, check the program as well. Load example test program and try again. https://iotforgeeks.com/i2c-oled-display-not-working/ helped me to resolve the same issue.
> 0 votes

---
Tags: arduino-uno, display
---


# Question
Title: Establishing wireless comm. between PC and arduino pro micro to exchange speech and gyro data
I have a client project to make a wireless head-mounted mouse. What wireless module should I use so that I can exchange data between my laptop and the arduino pro micro through the USB port like a wireless mouse? I am using an MPU6050 accelero+gyroscope sensor for cursor movement and Electrohouse Voice Recognition module V3.1 for speech recognition. To exchange such data between PC and arduino, I found a lot of options. Hence, I am confused. Please help me decide what to use so that cost efficiency and effectiveness can be acheived. Should I use bluetooth, RF shield , XBEE or any other module?

# Answer
> 1 votes
The wireless medium you choose is largely irrelevant. The important thing to realise is that it's not (in most cases) the wireless medium that is communicating with the computer.

Most wireless mice use the nRF24L01+ (or rather the integrated SoC equivalent) to communicate. They use a USB dongle plugged into the computer for that communication. The computer has no clue what an nRF24L01+ is, but it does know what a USB mouse is. So there is a microcontroller in the dongle which receives data from the nRF24L01+ and interprets it, and sends the right instructions over USB to make the computer think it's a USB mouse.

What the data is that's sent over the wireless, and exactly what form that wireless connection takes, is completely irrelevant as far as the computer is concerned. In general one if the SoC equivalent to the nRF24L01+ (such as the nRF52810) is chosen because it's a single chip solution with a simple to use wireless protocol, which makes for cheap and easy development and implementation.

The only exception to this general rule (and there is always an exception to every rule) is Bluetooth. This is because there is the concept (as far as the computer is concerned) of a Bluetooth mouse. So it is possible, using the right Bluetooth adaptor on your Arduino, for the computer itself to see the Arduino as a Bluetooth mouse. This can be harder to implement using small microcontrollers, but results in a potentially lower cost solution with fewer components.

The simplest solution for you, though, is probably:

* One Arduino that has a native USB connection (Pro Micro, Leonardo, etc - anything ATMega32U4 based)

This will be connected directly to the computer and programmed to emulate a USB mouse

* One Arduino that best suits your sensors (probably doesn't really matter what for this. Mini? Micro? Nano? Uno? They would probably all do fine).

To this you attach your sensors, your voice recognition, etc.

* A pair of wireless connectivity modules of some form

I'd recommend the nRF24L01+ - simple to use, has a very convenient packet-based protocol, cheap, and there's plenty of examples and libraries out there. These are connected to both Arduinos and are used to communicate between them.

Then it's up to you to decide what information gets sent between the Arduinos to make the one connected directly to the PC send the right mouse movements.

---
Tags: wireless, mpu6050, arduino-pro-micro
---


# Question
Title: SoftwareSerial data being corrupted - looking for suggestions
I'm having problems running a serial communication between a NodeMCU ESP8266 and an Arduino Uno. I'm using the "standard" SUART setup, i.e. pins D1&D2 on the ESP are hooked up with GPIOs 2&3 on the UNO; the tx from UNO to ESP is fed through a voltage divider to step it down to 3.3V.

The setup used to work fine; suddently - yeah I've read it before, *my setup suddently doesn't work*, but honestly that's what happened - data is being corrupted. The devices exchange a json formatted string:

```
{"action":"position","lat":123,"lon":123}

```

and it just worked. Now what I receive is something like:

```
{"⸮⸮⸮⸮⸮⸮":"pos⸮⸮⸮onb,"l⸮tF:0,"lo⸮":0,"⸮⸮s⸮⸮":0⸮

```

Both SUART are on 115200 baudrate, physical connections have been checked and are fine, both devices are grounded on the same reference level.

I've tried swapping the ESP with another one and changing TX/RX pins on the UNO - no results.

So I'm looking for suggestions what to do next to debug the issue, what to check and what could be wrong. Thank you in advance.

Below are UNO and ESP code snippets.

**ESP8266**

```
SoftwareSerial SUART(4, 5);

int16_t last_fetch = 0;
int16_t last_serial = 0;

double azimut, elevation;

#define DATA_FETCH_TIME_INT 3
#define SERIAL_TRASMISSION_TIME_INT 5

void setup() {
  Serial.begin(115200);  //enable Serial Monitor
  SUART.begin(115200);   //enable SUART Port

  WiFi.begin(ssid, password);

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

  Serial.println();
  Serial.println(WiFi.localIP());
}

void loop() {
  if (secs() - last_fetch >= DATA_FETCH_TIME_INT) {
    last_fetch = secs();
    fetchData();
  }

  if (secs() - last_serial >= SERIAL_TRASMISSION_TIME_INT) {
    last_serial = secs();
    sendDataViaSerial();
    }
}

void fetchData() {
  //connects to server and fetches data
}

void sendDataViaSerial() {
  int lat_i = (int) elevation;
  int lon_i = (int) azimut;
  int checksum = lat_i + lon_i;

  const int capacity = 200;
  StaticJsonDocument<capacity> doc;

  doc["action"] = "position";
  doc["lat"] = lat_i;
  doc["lon"] = lon_i;
  doc["cksum"] = checksum;

  Serial.println("Sending data via serial: ");
  serializeJson(doc, Serial);

  //SUART.flush();
  //serializeJson(doc, SUART);
  // works the same

  String outstring;
  serializeJson(doc, outstring);
  SUART.println(outstring);
}

```

**ARDUINO UNO**

```
SoftwareSerial SUART(2, 3);
#define arraySize 150
char inData[arraySize];

void setup() {
  pinMode(STATUS_LED, OUTPUT);
  digitalWrite(STATUS_LED, HIGH);

  Serial.begin(115200);
  SUART.begin(115200);

  Serial.println("Ready to go.\n");
}

void loop() {
  readSerial();
}

void readSerial() {
  short index = 0;
  char inChar;

  if (SUART.available() > 0) {
    while (SUART.available() > 0 && index < arraySize - 1) {
      inChar = SUART.read();
      inData[index] = inChar;

      index++;
      inData[index] = '\0';  // Add a null at the end
    }

    SUART.flush();
    String myData = (String)inData;
    Serial.println(myData);

    // consume data
    //parseIncomingData(inData);
  }
}

```

# Answer
> 1 votes
As @Juraj mentions in the comments, don't use 115200 baud with SoftwareSerial.

The problem is that the AVR isn't fast enough to handle incoming data at that speed reliably. Yes, it can receive a byte fine at that speed, but what it can't necessarily do is store that byte away in the receive buffer in time to be ready to receive the next byte - so it misses the first few bits and corruption ensues.

Running at a lower baud rate (such as 9600 baud) simply gives it more time to process the data as it arrives.

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


title: I2C OLED conflicts with Interrupt

text:
# Question
Title: I2C OLED conflicts with Interrupt
I'm using Nmradcc.h in combination with a OLED I2C.

The nrmadcc.h is using a interrupt 0 on Pin 2, the OLED uses A4 and A5.

After initialisation of the OLED and the Function

The problem is, I can use the Funktion with the Interrupt or the OLED, Not together. But i want to. Can I stop the interrupt function with nointerrupt and than I2C and otherwise, or is there a better war?

Thanks Bert

---

```
#include <SPI.h>                  ////
#include <Wire.h>                 ////
#include <Adafruit_GFX.h>         ////
#include <Adafruit_SSD1306.h>     ////
#include <DCC_Decoder.h>
#define kDCC_INTERRUPT 0

Adafruit_SSD1306 display(128, 64, &Wire, -1);   ////

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fill in the number of accessories / functions you want to control
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
const byte maxaccessories=1;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

typedef struct {
  int               address;          // Address to respond to
  byte              mode;             // 0=continuous, 1=oneshot, 2=flasher
  byte              output;           // State of accessory: 1=on, 0=off (for internal use only)
  int               outputPin;        // Arduino output pin
  byte              highlow;          // State of outputpin: 1=HIGH, 0=LOW
  boolean           finished;         // Memory location that says the oneshot is finished
  int               durationonMilli;  // oneshot or flasher on time in ms
  int               durationoffMilli; // oneshot or flasher off time in ms
  boolean           isAnalog;         // false=digital, true=analog, sends analogValue to out pin.
  byte              analogValue;      // pulse with modulation (pwm) value that is written to pin. Range: 0 - 255
                                        // goto http://arduino.cc/en/Reference/AnalogWrite to see which pins support analog pwm output
  unsigned long     onMilli;          // for internal use
  unsigned long     offMilli;         // for internal use
}
DCCAccessoryAddress;
DCCAccessoryAddress accessory[maxaccessories];

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Fill in the attributes for every accessory / function
// COPY - PASTE as many times as you have functions. The amount must be same as in line 17 above!
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void ConfigureDecoderFunctions() // The amount of accessories must be same as in line 26 above!
{
  accessory[0].address = 1;    // DCC address
  accessory[0].mode = 0;       // Continuous. HIGH until DCC switches the address off again.
  accessory[0].outputPin = 13; // Arduino pin where function is connected to.
  accessory[0].output = 0;     // Initial state (0 or 1) of output after startup.

  for(int i=0; i<maxaccessories; i++)
  {
    if (accessory[i].outputPin)
    {
      pinMode( accessory[i].outputPin, OUTPUT );
      // Set initial state (only for mode 0, continuous)
      if (!accessory[i].mode && accessory[i].output) digitalWrite(accessory[i].outputPin, HIGH);
      else digitalWrite (accessory[i].outputPin, LOW);
      }
    }
  }  // END ConfigureDecoderFunctions

  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  // DCC accessory packet handler
  //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  void BasicAccDecoderPacket_Handler(int address, boolean activate, byte data)
  {
    // Convert NMRA packet address format to human address
    address -= 1;
    address *= 4;
    address += 1;
    address += (data & 0x06) >> 1;

    boolean enable = (data & 0x01) ? 1 : 0;

    for (int i=0; i<maxaccessories; i++)
    {
      if (address == accessory[i].address)
      {
        if (enable) accessory[i].output = 1;
        else accessory[i].output = 0;
      }
    }
  } //END BasicAccDecoderPacket_Handler

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Setup (run once)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void setup()
{
  DCC.SetBasicAccessoryDecoderPacketHandler(BasicAccDecoderPacket_Handler, true);
  ConfigureDecoderFunctions();
  DCC.SetupDecoder( 0x00, 0x00, kDCC_INTERRUPT );
  pinMode(2,INPUT_PULLUP); //Interrupt 0 with internal pull up resistor (can get rid of external 10k)
  pinMode(13,OUTPUT);
  digitalWrite(13,LOW); //switch off Arduino led at startup
  for (int n=0; n<maxaccessories; n++) accessory[n].output = 0; //all servo's to min angle and functions to 0

  display.display();
  display.clearDisplay();

} // END setup

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Main loop (run continuous)
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
void loop()
{
  static int addr = 0;

  DCC.loop(); // Loop DCC library

  if( ++addr >= maxaccessories ) addr = 0; // Next address to test

  if (accessory[addr].output == 1)
  {
    if (accessory[addr].mode == 0) accessory[addr].highlow=1; // continuous

    if (accessory[addr].mode == 1) // oneshot
    {
      if (!accessory[addr].highlow && !accessory[addr].finished)
      {
        accessory[addr].highlow = 1;
        accessory[addr].offMilli = millis() + accessory[addr].durationonMilli;
      }
      if (accessory[addr].highlow && millis() > accessory[addr].offMilli)
      {
        accessory[addr].highlow = 0;
        accessory[addr].finished = true;
      }
    }

    if (accessory[addr].mode == 2) // flasher
    {
      if (!accessory[addr].highlow && millis() > accessory[addr].onMilli)
      {
        accessory[addr].highlow = 1;
        accessory[addr].offMilli = millis() + accessory[addr].durationonMilli;
      }
      if (accessory[addr].highlow && millis() > accessory[addr].offMilli)
      {
        accessory[addr].highlow=0;
        accessory[addr].onMilli = millis() + accessory[addr].durationoffMilli;
      }
    }

      display.setCursor(90, 50);  ////
      display.setTextSize(2);     ////
      display.print(F("ON")) ;    ////

  }
  else // accessory[addr].output == 0
  {
    accessory[addr].highlow=0;
    if (accessory[addr].mode == 1) accessory[addr].finished = false;

      display.setCursor(90, 50);  ////
      display.setTextSize(2);     ////
      display.print(F("OFF")) ;    ////

  }

  if (accessory[addr].highlow)
    {
      if (accessory[addr].isAnalog) analogWrite (accessory[addr].outputPin, accessory[addr].analogValue);
        else digitalWrite (accessory[addr].outputPin, HIGH);
    }
  else
    {
      if (accessory[addr].isAnalog) analogWrite (accessory[addr].outputPin, 0);
        else digitalWrite( accessory[addr].outputPin, LOW);
  }
  display.display();
} //END loop

```

In this sample is the I2C OLED not working. When I change the spot of

```
Adafruit_SSD1306 display(128, 64, &Wire, -1);

```

and

```
DCC.SetupDecoder( 0x00, 0x00, kDCC_INTERRUPT );

```

The DCC interrupt is not working, the OLED does work.

# Answer
I2C requires precise timing to work. If interrupts fire while the Arduino is trying to read or write to the I2C bus, it will fail. I suspect you'll have to disable interrupts each time you read/write to the I2C bus and then re-enable them when you are done.
> 3 votes

---
Tags: i2c, interrupt
---


# Question
Title: Where is the documentation for the Emoro GLAM pro module?
My 11-year-old son recently brought out an Emoro robot he got for his birthday. We had some temporary confusion with the robot, but got it to work. He is now trying to connect to his computer via Bluetooth from the Emoro, but cannot find any documentation on Emoro Bluetooth.

Where is the documentation for Emoro Bluetooth?

# Answer
What you are searching can be found via googling, if you know, what to google for. I write a formal answer to this, because there is neither a link on the product page of the manufacturer, nor is it very easy to find for a beginner.

Have you seen this repository `emoro-2560-library` on github? It seems to incorporate libraries for nearly ever function of the Emoro, including the bluetooth functionality of the GLAM board. You can find examples in the GLAM examples folder.

How did I found it? I googled for "emoro github". A better search phrase would be "emoro 2560 github" (Since Emoro 2560 is somewhat the extended name of the robot). I used the term "github", since most libraries for Arduinos and their derivates/variants are hosted on github. If you are search for a library, you can first search for them on github. Most times you will find something. Often these libraries also serve as a kind of documentation (as real and good documentation can be rare to find).

---

Now somewhat unneeded, but from the library code and the pictures on the product page of the GLAM module, I think, that a serial bluetooth module with AT firmware like HC-05 is used. If you ever want to look past the bluetooth library for the robot, you would need to go that way. (How a Hc-05 is controlled can also be googled)
> -1 votes

---
Tags: documentation
---