# Question
Title: MQTT - Can lastwill be sent to multiple topics?
I'm using an ESP8266 as an IOT device, with MQTT to send status messages. Each device have its own availability topic, to state its `online` or `offline` state ( needed for `Home Assistant` indication on web GUI )

Since multiple devices are present- I was wondering if a lastwill status can be sent for a joint topic to be monitored ( for example :"`device_id:offline`" )

my relevant part of the code defining a lastwill for devices topic is : `mqttClient.connect(deviceName, user, passw, availTopic, 0, true, "offline")`

**EDIT1:** using `PubSubClient.h`

# Answer
The "Last Will & Testament" facility of MQTT is controlled by the server, not the client.

The topic and payload are specified when the client connects as part of the connection handshaking. When the client disconnects this stored information is published automatically by the server.

The specification only allows for one topic and payload to be set.

Of course, you can specify the same topic for many clients and give each one its own distinct payload, but you can't also have a unique topic for each client at the same time.

This is according to the specification - however that doesn't stop a broker implementing its own extensions to the specification to allow such things - but I know of no such extensions being implemented. But, given the open-source nature of many MQTT implementations (PubSubClient.h and Mosquitto, for example), there is no reason you couldn't extend the protocol to implement your own requirements (at the cost of compatibility with other systems of course).
> 2 votes

---
Tags: esp8266, mqtt
---


# Question
Title: Docs for using i2C LCD with Newliquidcrystal_1.3.5 library?
I bought a 20x4 I2C LCD from OddWires. (https://www.oddwires.com/20x4-lcd-display-with-i2c-interface/) It came with ZERO specs or documentation. After some hair-pulling I was able to figure out how to get it working. (I had to use the commands

```
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);  // Set the LCD I2C address and pin assignments, including the backlight pin and polarity

```

and

```
  lcd.begin(20,4);               // initialize the lcd to 20 characters, 4 lines

```

To get the LCD working (The tricky bit was figuring out the pin assignments. They're not documented.)

I'm assuming this LCD unit is a lot like all the others out there.

It works, and If found the basic commands to clear the screen, position the cursor, and print text.

I've also found commands `lcd.cursor()` and `lcd.noCursor()` that let me show/hide the cursor.

I'd like to know if I can do things like blink characters between normal and inverse, underline text, etc using the standard LCD library (I've seen code that uploads custom character maps, so I assume I could upload an alternate underlined character set, but that sounds like a LOT of work for something I'm hoping is built in to the library.)

Can somebody point me to docs on the full suite of commands commonly available for these LCD units in the Arduino Newliquidcrystal\_1.3.5 library?

(Sorry to be vague on the specifics of my LCD module. I did not get specs from the vendor, so I have had to guess as to how to use it.)

I'm using the I2C LCD NewLiquidCrystal LCD library. (https://github.com/fmalpartida/New-LiquidCrystal)

# Answer
> 1 votes
Often in software development, the code **is** the documentation. The merits of this are debated *ad nauseam* elsewhere.

As you have provided a link to the GitHub repository of the library you are using, you have all you need, though the provided `utility/docs` path doesn't fully document the I2C interface.

The function prototype (that is, the function, its return type, and parameters, but without the actual code) is found in *header files* which usually have the `.h` suffix.

Since you have an LCD with a I2C interface, you can look at the GitHub repo for the file `LiquidCrystal_I2C.h`

Within this file, you can see that the class is defined with name `LiquidCrystal_I2C` and has multiple constructors, each with a different list of parameters. The particular class constructor used is the one that matches the count and type called in your *declaration* of the object of that class.

The code in the header file is well documented. The first prototype listed includes good commenting:

```
/*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    */
   LiquidCrystal_I2C (uint8_t lcd_Addr);
   // Constructor with backlight control
   LiquidCrystal_I2C (uint8_t lcd_Addr, uint8_t backlighPin, t_backlighPol pol);

```

This block shows the first 2 constructor options: With a `uint8_t` type that defines the I2C address of an I/O expansion module (which is what many "LCD backpacks" are -- that, or shift registers), and one with an I2C address, a backlight pin, and the polarity of the backlight.

Proceeding down, we find the one with 10 parameters, which is what you ended up using:

```
  /*!
    @method
    @abstract   Class constructor.
    @discussion Initializes class variables and defines the I2C address of the
    LCD. The constructor does not initialize the LCD.

    @param      lcd_Addr[in] I2C address of the IO expansion module. For I2CLCDextraIO,
    the address can be configured using the on board jumpers.
    @param      En[in] LCD En (Enable) pin connected to the IO extender module
    @param      Rw[in] LCD Rw (Read/write) pin connected to the IO extender module
    @param      Rs[in] LCD Rs (Reset) pin connected to the IO extender module
    @param      d4[in] LCD data 0 pin map on IO extender module
    @param      d5[in] LCD data 1 pin map on IO extender module
    @param      d6[in] LCD data 2 pin map on IO extender module
    @param      d7[in] LCD data 3 pin map on IO extender module
    */
   LiquidCrystal_I2C(uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7 );
   // Constructor with backlight control
   LiquidCrystal_I2C(uint8_t lcd_Addr, uint8_t En, uint8_t Rw, uint8_t Rs,
                     uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7,
                     uint8_t backlighPin, t_backlighPol pol);

```

That last constructor is used to override the default pin mappings from the I/O Expander to the LCD. This is tricky -- what were the mappings based on? An I/O expander is basically a way to access multiple pins on an external chip through a single two-wire interface (I2C). How an LCD is connected depends on what pins of the I/O Expander are connected to which pins of the LCD. There is not a formal standard, though there may be convention.

Reading the GitHub page, you see that this is a

> Clone of the new liquid crystal library from: https://bitbucket.org/fmalpartida/new-liquidcrystal

Following that link takes us to some kind of documentation, noting that one of the connection types is:

> I2C IO bus expansion board with the PCF8574\* I2C IO expander ASIC such as I2C LCD extra IO.

A link to that hardware is helpfully provided! We can follow the link to see that the hardware is discontinued, but helpfully documented with some schematics and PCB layouts that tell us which pins of the I/O expander are connected to which pins of the LCD:

`P0` is pin 0 of the I/O expander -- the top row are the I/O expander pins. `Vo`, `RS`, `R/W`, etc. are the LCD pins.

```
LCD Pin  |  I/O Expander Pin
     En  |  P4
    R/W  |  P5
E (rst)  |  P6
     D4  |  P0
     D5  |  P1
     D6  |  P2
     D7  |  P3

```

(And the backlight is a passthrough pin, not on the I/O Expander. It appears the definition of the backlight pin and polarity refer to I/O Expander pins.)

This is the point where you have to find out if the I/O expander on your purchase has the same pinout as the product for which this library was written.

Your "working" instance is called as (with annotations to the constructor being called)

```
LiquidCrystal_I2C lcd(
  0x27,       // lcd_Addr
  2,          // En (enable pin)
  1,          // Rw (read/write pin)
  0,          // Rs (reset pin)
  4,          // d4 (data)
  5,          // d5 (data)
  6,          // d6 (data)
  7,          // d7 (data)
  3,          // backlight
  POSITIVE    // backlight polarity
);

```

This indicates that the I/O expander on your LCD **does not** have the same pin connections as that for which the library was written, which is why you had success only when remapping them in the constructor.

All that to just re-state the hair-pulling you had to do!

The actual functions available are noted to be:

> This library provides the same interface to applications as the LiquidCrystal library sourced by the Arduino SDK.

But to be absolutely sure, you can also see their prototypes in the header file: https://github.com/fmalpartida/New-LiquidCrystal/blob/master/LCD.h

It provides scrolling, blinking, enable/disable, etc.

---
Tags: i2c, lcd
---


# Question
Title: Control multiple WS2812B strips with different leds count
First of all, my English is not that good so sorry if I made any mistake.

I'm using the WS2812FX, an awesome WS2812 effect library base on Adafruit NeoPixel library to make a small controller for the lightning in my bedroom.

The question here is how do I use this library to control multiple WS2812b led strip with different leds count, like one strip with 30 leds the other with 55 leds but the effect will just cycle through each individual led of each strip.IF somehow I can add one more output pin to this.

Example : There is an effect call "Larson Scanner" will light up one led then it run from the first led to the last led and go back, I want it to do the same on both strips, on the 30 leds strip it goes from first led to 30th led then go back & on the 55 leds strips it goes from first led to the 55th led at the same time.

Hope you guys understand what I'm asking :(

Link to the library : https://github.com/kitesurfer1404/WS2812FX

# Answer
The WS2812 chip requires *highly* timing dependent pulses to work, as I describe on my page about Neopixels. We are talking about pulse widths of 350 ns.

I suggest it would be impossible to add another strip "if I can add one more output pin to this". It's not a question of adding pins, it's being able to output pulses that fast. You can't do it, at least not on the AVR Arduinos, and I doubt that the ones with faster chips would do it either.

What you *could* do is connect the various strips together so it is really one long strip (assuming they aren't too far away from each other). The different strips could usefully have their own power supplies, but the **data** and **ground** would need to go from the Arduino into the first strip, then out to the second one, and so on.

Something like this:

As for synchronizing the strips, well that is just programming. If you want the first LED on the 30-LED strip to light at the same time as the first LED on the 55-LED strips, then you actually would need to light LED #1 and LED #31 at the same time.

---

## Possible alternative

Actually what might work would be to send to strip #1 first, and then strip #2 after changing pins. That means you would have to interleave the sends. For example to make a pixel seem to run backwards and forward on two strips you make it move one pixel on the first strip, then one pixel on the second strip, and so on.

I'm not sure if the library you mentioned supports that, since the LED count is in the constructor. It looks like it might, as you can change the number of LEDs and the pin number.

You might be able to make two instances of the library object (with different names), initialize them both, and then interleave the sends between them.
> 3 votes

# Answer
The library repo itself already describes "segments". So you simply connect the 55-part strip's data-in to the data-out of the 30-part strip. Instantiate as one 85-part strip, and then define the segments and set patterns on each as appropriate.
> 0 votes

# Answer
I had the same question! =\> **Use an arduino per LED strip** :) and, if it is necessary to interconnect them to synchronize them In short, work around the problem

*translated by Google :(*
> -1 votes

---
Tags: neopixel, led-strip, ws2812
---


# Question
Title: Two serials can't work on the same speed
I have a device which sits on pins 10/11 of Arduino UNO. I am trying to send commands from my PC using Arduino to relay my commands to the device via Serial.

The problem is that if I use speed 9600 both for device and USB communication, then my commands gets damaged. Some letters are replaced by strange symbols, etc. The device uses 9600 baud rate.

If I change speed of the PC communication to 4800 (or any speed other than 9600), everything is fine. But I have to use different speeds for the communication.

I am not comfortable with the workaround, because I don't understand what's going on. Could somebody explain why the same serial port speeds causes problems?

Here is my code:

```
#include <SoftwareSerial.h>

#define rxPin 11
#define txPin 10

SoftwareSerial mySerial =  SoftwareSerial(rxPin, txPin);

 void setup()
 {
   digitalWrite(4,HIGH); // 1 - disable
   mySerial.begin(9600);
   Serial.begin(19200);
   while (!Serial) {;}  // wait for serial port to connect. Needed for native USB port only
   Serial.println("Begin");
 }

 void loop()
 {
  if (mySerial.available())
  {
    char c = mySerial.read();
    Serial.write(c);
  }
  if (Serial.available())
  {
    char c = Serial.read();
    mySerial.write(c);
  }
 }

```

# Answer
> 1 votes
I spent some time playing with your code and it seems your code actually loops the serial therefore if they are both set at 9600 as example and you print what the other one is sending like in your code you end up in a loop if you want to read what your serial is sending it is better put that values in a variable and send it

if you load your code you will get the following message in the arduino IDE once you try to connect to the serial monitor:

`Error opening serial port 'COM8'. (Port busy),`

your port is busy because the one serial port is reading the other all the time

one more thing I would use the following if you want to repeat a serial port:

```

  if (mySerial.available())
  {
    //char c = mySerial.read();
    Serial.write(mySerial.read());
  }

```

Hope this hels you

# Answer
> 0 votes
If you are confident with the device you connected to your Arduino Uno in terms of it has a reliable serial communication firmware running on it, You might need some buffering before relaying your commands;

```
#define RECORD_SIZE 100
void loop()
{
    RelayDataIfAvaliable();
}
void RelayDataIfAvaliable() {
    static char buffer[RECORD_SIZE];
    if (Serial.available())
    {
        if (readline(Serial.read(), buffer, RECORD_SIZE) > 0) {
            mySerial.write(buffer);
        }
    }
}
//Reads entire incoming data into buffer once
int readline(int readch, char *buffer, int len)
{
    static int pos = 0;//This was zero initially. But, it was missing first character!
    int rpos;
    //Serial.print(readch);
    if (readch > 0) {
        switch (readch) {
        case '\n': // Ignore new-lines
            break;
        case '\r': // Return on CR
            rpos = pos;
            pos = 0;  // Reset position index ready for next time
            return rpos;
        default:
            if (pos < len - 1) {
                buffer[pos++] = readch;
                buffer[pos] = 0;
            }
        }
    }
    // No end of line has been found, so return -1.
    return -1;
}

```

---
Tags: arduino-uno, serial, softwareserial, baud-rate
---


title: Can't get software serial to work

text:
# Question
Title: Can't get software serial to work
So I have two Arduinos (Arduino Nano) and I'm trying to get them to communicate via SoftwareSerial. I have the 'sending' Arduino's D10 pin connected to the 'recieving' Arduino's D11 pin, and vice versa. On my sending Arduino, I have the following code:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(10, 11);

void setup() {
  pinMode(2, OUTPUT);
  mySerial.begin(9600);
}

void loop() {
  if (mySerial.isListening()){
    digitalWrite(2, HIGH);
  }
  mySerial.write(5);
}

```

and on my receiving Arduino, I have:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(11, 10);

void setup() {
  pinMode(2, OUTPUT);

  Serial.begin(9600);

  mySerial.begin(9600);
}

void loop() {
  mySerial.listen();
  if (mySerial.available()>0) {
    digitalWrite(2, HIGH);
    char inByte = mySerial.read();
    Serial.write(inByte);
  }
  digitalWrite(2, LOW);
}

```

(with D2 being hooked up to an LED for both).

I can't get it to read anything. Nothing seems to be available for the receiving Arduino (the LED is off). What am I doing wrong?

# Answer
> 1 votes
Sender:

```
SoftwareSerial mySerial(10, 11);  // Rx, Tx

```

Receiver:

```
SoftwareSerial mySerial(11, 10);  // Rx, Tx

```

> I have the 'sending' Arduino's D10 pin connected to the 'receiving' Arduino's D11 pin, and vice versa.

So you have the sending Arduino's Rx connected to the receiving Arduino's Rx. Therefore it won't work. You need to connect Rx to Tx.

---

```
  mySerial.listen();

```

You don't need that in this simple example.

# Answer
> -1 votes
I agree with Nick above but want to add this simplify your code like this:

```

if (mySerial.available()) {
    digitalWrite(2, HIGH);
    Serial.write(mySerial.read());
  }

```

I have had to catch serial data from a printer feed before and this turned out to be the best way to catch all the data if you place it in a variable first it has to change the variable every time that you receive a byte but this way it places all in a buffer then sends it out

BTW I had to save to a F-RAM device and that worked the same way but instead of sending it I had it saved to a variable while using ReadString() in stead of read().

---
Tags: serial, c++, softwareserial, software
---


# Question
Title: How can I reduce the memory usage on my code?
I wrote this code to control my christmas tree. It takes up the majority of the memory on my Arduino Uno:

```
Sketch uses 31822 bytes (98%) of program storage space. Maximum is 32256 bytes.
Global variables use 1882 bytes (91%) of dynamic memory, leaving 166 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.

```

Does anyone know how I can reduce the memory usage?

Code:

```
#include <SPI.h>
#include <SdFat.h>
#include <SdFatUtil.h>
#include <SFEMP3Shield.h>

#define TREEONE 3
#define TREETWO 4
#define TREETHREE 5
#define TREEFOUR 10

SdFat sd;
SFEMP3Shield MP3player;

const uint8_t volume = 10; // MP3 Player volume 0=max, 255=lowest (off)
//10 for basement 50 for testing

const uint16_t monoMode = 1;

int song = 3;
int num = 0;
int count = 0;

//put arrays here
byte arrayTree[] = {17,16,9,8,3,2,5,4,17,16,9,8,3, ...etc };

void setup() {
  initSD();
  initMP3Player();

  pinMode(TREEONE, OUTPUT);
  pinMode(TREETWO, OUTPUT);
  pinMode(TREETHREE, OUTPUT);
  pinMode(TREEFOUR, OUTPUT);

  digitalWrite(TREEONE, HIGH);
  digitalWrite(TREETWO, HIGH);
  digitalWrite(TREETHREE, HIGH);
  digitalWrite(TREEFOUR, HIGH);
}

void loop() {
  if(!MP3player.isPlaying()){
    MP3player.playTrack(song);
    MetallicaChristmas();
  }
}

void initSD() {
  if(!sd.begin(SD_SEL, SPI_HALF_SPEED))
    sd.initErrorHalt();
  if(!sd.chdir("/"))
    sd.errorHalt("sd.chdir");
}

void initMP3Player() {
  uint8_t result = MP3player.begin();
  MP3player.setVolume(volume, volume);
  MP3player.setMonoMode(monoMode);
}

void treeFunc() {
    //delay(arrayTimes[i]);
    num = arrayTree[count];

    //TREEONE
    if(num>15){
      if((num%2)==0){
        digitalWrite(TREEONE,HIGH);
      }else{
        digitalWrite(TREEONE,LOW);
      }
    }
    //TREETWO
    if((num%16)>7){
      if((num%2)==0){
        digitalWrite(TREETWO,HIGH);
      }else{
        digitalWrite(TREETWO,LOW);
      }
    }
    //TREETHREE
    if((num%8)>3){
      if((num%2)==0){
        digitalWrite(TREETHREE,HIGH);
      }else{
        digitalWrite(TREETHREE,LOW);
      }
    }
    //TREEFOUR
    if((num%4)>1){
      if((num%2)==0){
        digitalWrite(TREEFOUR,HIGH);
      }else{
        digitalWrite(TREEFOUR,LOW);
      }
    }
  count = count + 1;
}

void MetallicaChristmas()
{
  //event 1
  delay(670);
  treeFunc();
  delay(248);
  treeFunc();
  //event 2
  delay(116);
  treeFunc();
  delay(248);
  treeFunc();
  //event 3
  delay(100);
  treeFunc();
  delay(248);
  treeFunc();
  //event 4
  delay(132);
  treeFunc();
  delay(248);
  treeFunc();
  //event 5
  delay(125);
  treeFunc();
  delay(248);
  treeFunc();
  //event 6

  ...etc.

```

# Answer
As well as `PROGMEM` (as described in the comments), there are a couple of other efficiencies that you can make:

* A function call is expensive (takes a lot of code space), and you are performing a LOT of them!

+ The repetitious calls to `delay()` followed by `treeFunc()` are wasteful. Your commented-out line

    ```
    //delay(arrayTimes[i]);

    ```

    looks like you were going to do the right thing, so I’d restore that (use `count` instead of `i`) and put the `delay()` numbers in a new `int arrayTimes[]` array.

    `PROGMEM` this array too, of course!
    + Once you’ve done this, you can remove all the calls to `delay()`. You’ll be left with nothing but repeated calls to `treefunc()`, which you can replace with a single loop:

    ```
    for (count=0;count<sizeof(arrayTree);++count) {
       treeFunc();
    } // for

    ```

    Don’t forget to get rid of the `count = count + 1;` line from `treeFunc()` \- it’s now in the `for` loop.
* Also expensive is calling the same function twice except with different parameters in both sides of the `if` in `treeFunc()`. Instead of:

```
if (<condition>) {
   Function(1);
} // if
else {
   Function(0);
} // else

```

you can instead do:

```
Function(<condition>);

```

For this to work, you need to know that `HIGH` has the value `1` and `LOW` has the value `0` \- and that a `true` condition has the value `1` and a `false` condition has the value `0`.

So, you need to change the `if ()` slightly:

```
digitalWrite(THREEONE, (num%2)>0);

```
* Finally, the mod `%` operator itself is very expensive, since it is effectively a division, and the Arduino chip doesn’t know how to divide - so the code to do so is large. But the code you’ve written is using binary arithmetic, which the Arduino can do instantly - you just have to write it as such.

+ Instead of `(num%2)>0` use `num & B0001`.
    + Instead of `(num%4)>1` use `num & B0010`.
    + Instead of `(num%8)>3` use `num & B0100`.
    + Instead of `(num%16)>7` use `num & B1000`.

You’ve probably copied the guts of this code from somewhere else, and while it works it isn’t very efficient. Writing the code as above will greatly reduce your code size, exchanging repeated calls for much smaller `PROGMEM` arrays.
> 3 votes

---
Tags: arduino-uno, memory-usage
---


title: Need Basic Help with Software Serial

text:
# Question
Title: Need Basic Help with Software Serial
I am testing the basic Software Serial example on the arduino website, but I cant get the myserial to print

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  // Open serial communications and wait for port to open:
  Serial.begin(57600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

 Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(4800);
  mySerial.println("Hello, world?");
}

void loop() { // run over and over
  if (mySerial.available()) {
    Serial.write(mySerial.read());
  }
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

```

# Answer
In the example, digital pins 10 and 11 (mySerial) on your Arduino board are used as virtual RX and TX serial lines. The virtual RX pin (pin10)is set up to listen for anything coming in on the hardware RX serial line, and to then echo that data out the virtual TX line (pin11). Conversely, anything received on the virtual RX (pin10) is sent out over the hardware TX.
> 1 votes

# Answer
You would need to connect something to the pins 10 and 11 like a FT232RL breakout or another serial device. If you have another Arduino, connect the RX of that Arduino to pin 11 on the Arduino connected to the USB and give the other a simple program like:

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

void loop(){
  Serial.println("Testing mySerial on Other Arduino");
  delay(500);
}

```

Once the above code is loaded to second Arduino, put that example code on first Arduino and connect the two together like mentioned above; tx to rx and rx to tx and load the code on first Arduino and see results.
> 0 votes

---
Tags: softwareserial
---


# Question
Title: How is this simple transistor circuit suppose to work?
I've tried to replicate this circuit today.

1. My motor is a computerfan, they apperntly don't need a flyback diode since there are no brushes.
2. I used a 12V power source for my arduino and hooked it up via VIM.
3. I used the arduino ground as external power source.
4. I verified that the transistor worked as expected with a voltmeter.

Here is the transistor I used:

As I understand this, the transistor is stimulated to "steal" electrons away from the motors circuit. But it seems connected to the base. Why would you do that?

# Answer
> 2 votes
There are many bad schematics and pictures online, and these pictures are really bad.

Do not try to make that. You may damage the Arduino board and the transistor.

* Even the picture of the BC548 is wrong. The BC548 is always called "BC548" and never "BC-548".
* The BC548 is not a good choice to drive a motor. It can only do 100 mA continuous.
* The DC barrel socket has plus and minus wrong connected. The 12V plus is connected to the Arduino GND. That is not okay.
* The transistor in the first picture is probably a transistor with the pins in BCE order.
* A resistor is missing to the base of the transisor.
* Because of the missing resistor, the Arduino board can be damaged.
When the breadboard has a bad connection to GND, the 12V can go to pin 9 of the Arduino board.

@Dorian, there are no mystical higher alien intelligent thoughts for that schematic. It is obvious a wrong circuit that is meant to drive a motor with PWM using a transistor.

And last but not least:
There are a few different types of computer fans. Some have a capacitor inside and some will only accept a PWM signal to a PWM input.
Are you sure that your fan is able to accept PWM for the 12V power?

# Answer
> 0 votes
This looks like a circuit to monitor the power loss in the motor supply. If the motor is powered and the circuit is not interrupted then the collector will poll Arduino pin 9 to GND.

---
Tags: arduino-uno, electronics, transistor
---


# Question
Title: Cannot get pins on esp 8266 adafruit wifi module to read HIGH on pin 15
I have an esp8266 and I cannot get the value to read HIGH when 3.3v is applied to directly to pin by hand. I have an Arduino Uno powering the esp8266. It connects to the WiFi like it should, and now all I want is to manually see that when I apply 3v that the state will change from 0 to 1. Does anyone know how I can do this.

When I apply 3 volts directly to pin 15 it outputs 0. Even if I try digitalWrite on the pin and set it to HIGH it still says 0 and i serialPrint. My end goal if to use the arduino uno to fire and ouput on pin 8. On the arduino UNO side I am using a super sonic sensor. When the sensor is triggered I want to turn pin 8 on. From there I want to take pin 8 to feed pin 15 on the 8266 as an input. Before I did that I just wanted to see that when you manually apply 3v that the pin would read 1 or HIGH but no matter I do it wont change value. Once I get that value as HIGH I can send a second request to the server like im already but now I want to say that there was an intruder. Im not sure why the value wont change but being a beginner with arduino Im trying to keep it simple and ideally would like to wire it in this manner.

```
#include <SoftwareSerial.h>
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

const char* ssid = "********";
const char* password = "********";

HTTPClient http;

static const uint8_t D8 = 15;
int featherPin = D8;

//int trigPin = 13;
//int echoPin = 12;
//int ledPin = 10;
//int hornPin = 11;
//
//int spaceIntruded;
//
//long duration, cm, inches;

void setup() {
  Serial.begin(115200);
  pinMode(featherPin,INPUT);

  WiFi.begin(ssid, password);

  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.println("Waiting for connection");
 }

//  Serial.begin (9600);
//  pinMode(trigPin, OUTPUT);
//  pinMode(echoPin, INPUT);
//  pinMode(ledPin, OUTPUT);
//  pinMode(hornPin, OUTPUT);
//  delay(5000);
//  Serial.println("Armed...");

}

void loop() {

  if (WiFi.status() == WL_CONNECTED) {
    Serial.println("yay connect");

    http.begin("http://10.150.40.121:3000/");
    http.addHeader("Content-Type", "text/plain");

    int httpCode = http.POST("Message from ESP8266");
    String payload = http.getString();
    Serial.println(payload);
    http.end();

    } else {
      Serial.println("Error in Wifi connection");
    }
//    digitalWrite(featherPin, HIGH);
    int sensorValue = digitalRead(featherPin);
    Serial.print(sensorValue);

//    if (digitalRead(featherPin) == HIGH) {
//      http.begin("http://10.150.40.121:3000/home");
//      http.addHeader("Content-Type", "text/plain");
//
//      int httpCode = http.POST("Message from ESP8266");
//      String payload = http.getString();
//      Serial.println(payload);
//      Serial.print("hi");
//      http.end();
//      } else {
//        Serial.print(featherPin);
//        Serial.println("I am not hot");
//      }

//  digitalWrite(trigPin, LOW);
//  delayMicroseconds(1);
//  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(2);
//  digitalWrite(trigPin, LOW);
//
//  pinMode(echoPin, INPUT);
//  duration = pulseIn(echoPin, HIGH);
//
//  inches = (duration / 2) / 74;
//  Serial.println(inches);
//
//  spaceIntruded = inches;
//
//  if (spaceIntruded <= 50 || spaceIntruded >= 900){
//      digitalWrite(ledPin, HIGH);
//      digitalWrite(hornPin, HIGH);
//      Serial.println("Intruder Detected!");
//      Serial.println("Sending text Notification...");
//      delay(500);
//      Serial.println("Armed...");
//  }
//
//  else{
//    digitalWrite(hornPin, LOW);
//    digitalWrite(ledPin, LOW);
//  }
    delay(30000);

}

```

# Answer
Pin 15 is one of the boot configuration pins (0, 2, 15) and must be LOW at boot. To ensure it, dev boards with esp8266 have external pull-down on pin 15 (and pull-up on 0 and 2). To read the pin HIGH you must overcome the pull-down.

Adafruit Feather HUZZAH has 4.7kOhm resistor for the pull-down, so it is a 'strong' pull down. NodeMcu has 12kOhm resistor on io 15.

From schematics of Adafruit Feather HUZZAH

Note: setting pin as OUTPUT and HIGH doesn't make it read HIGH in code. Only INPUT pin state can be read with digitalRead (only on some MCUs digitalRead reads the same register set by digitalWrite).
> 1 votes

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


# Question
Title: Multiple definition error when linking firmware.elf
I just can't wrap my head around on how to properly work with multiple files. My code has been getting quite big so I decided to split all the classes into one file each. So I'm left with 6 files:

```
dataHandler.cpp
fileHandler.cpp
header.cpp
main.cpp
request.cpp
sensorData.cpp

```

*header.cpp includes all the header files, and main.cpp the setup() and loop() functions.*

Visual Studio Code shows me no errors while compiling. The includeguards have the name convention: CLASSNAME\_INCG

So in my main.cpp for example I have something like:

```
#ifndef HEADER_INCG
#include "header.cpp"
#define HEADER_INCG
#endif

#ifndef SENSORDATA_INCG
    #include "SensorData.cpp"
    #define SENSORDATA_INCG
#endif

#ifndef DATAHANDLER_INCG
    #include "DataHandler.cpp"
    #define DATAHANDLER_INCG
#endif

setup()
{
    ...
}

...

```

When going into a class-file I have it defined in the following way (fileHandler.cpp):

```
#ifndef HEADER_INCG
#include "header.cpp"
#define HEADER_INCG
#endif

#ifndef FILEHANDLER_INCG
#define FILEHANDLER_INCG

class FileHandler{
    ...
}

#endif

```

**So in summary** I include the headerfile into every file, with includeguards arround. If I wouldn't include it I would get errors that crucial libaries like Serial etc. are missing. But when including the header into every file compiliing works just fine, but when it comes to linking the files togehter I get an error of multiple definitions.

*So how can I define the headerfile just once for all files albeit I need it in every file?*

# Answer
> 2 votes
1. Rule #1:
Header file extension is ".h". Files with ".cpp" are ususally compiled as separate compilation units into the object file. If you have any function definition (= declaration + implementation) or any global variable in more object files, it'll fail to link.
2. Rule #2:
No definitions in headers - variables and functions will cause this error if you include .h file into more .cpp files. If you need super global variable, you have to use declaration with extern modifier and you have to define it in one of the .cpp files. But only one! Also there can be only function prototypes (declarations) in header file. Implementation have to be only once in one of the ".cpp" files.

It's usually in the first chapter of books about learning C/C++.

Really short example:

```
// myLib.h
#ifndef _myLib_h_guard_
#define _myLib_h_guard_

void myFunction(); // function prototype (declaration)

extern int mySuperGlobalVariable;  // variable declared as extern, there must be definition somewhere

class MyClass {
public:
  int someMethod(); // method declaration

  int anotherMethod() { return 1; }  // definition inside of class works, but sometimes is less readable
};

#endif

```

```
// myLib.cpp
#include "myLib.h"

void myFunction() { // function implementation (definition)
  // do something...
}

int mySuperGlobalVariable; // definition

int MyClass::someMethod() { return 2; } // method definition

```

```
// main.cpp
#include <myLib.h>

int main() {

  mySuperGlobalVariable = 10;

  myFunction();

  MyClass instance;
  int first = instance.someMethod();
  int second = instance.anotherMethod();
}

```

---
Tags: compile, compilation-errors, makefile, mkr-gsm-1400
---


# Question
Title: Arduino Nano Midi to cv convertor interesting issue
I created the circuit in this schematic on protoboard,

and the code, https://github.com/elkayem/midi2cv

I use a dual opamp and a single dac, because i only need note and velocity. The opto i use is, H11L1

It works but has a strange issue that i can not figure out.

The author says the code supports midi notes from 21 to 108.

When I send midi notes to test the device,

(Arduino powered with +12, TL082 Opamp powered with +15 to GND )

The notes \<= 36 gives +15V in the output of the opamp. The note 37 gives +3.43V The note 38 gives +1.7V . . .then it increments as expected until note 108 which gives +7.52 V

Also to add I have +1.5V DC offset on the both outputs of the opamp. (This, i can live with but i would love it not to happen. )

I would be very happy if you help me on this, thank you.

# Answer
> 1 votes
I changed the opamp to LM358 and all problems solved it works perfectly!

If you have enough motivation and time please explain me why, but i will research and learn anyway.

---
Tags: arduino-nano, midi, op-amp
---


title: ILI9163C screen not working properly

text:
# Question
Title: ILI9163C screen not working properly
I've just tried out my new TFT\_ILI9163C display with TFT\_ILI9163C library but I'm having an issue with it. The graphics has moved down (the "hello world" should be in the top left) and the leftover space looks like there was no signal. Can be seen in the photo. What could be wrong?

# Answer
I had the same board and problem as you, what fixed is was changing the board setting to black even though it is phyiscally red.

Inside

```
Arduino\libraries\TFT_ILI9163C\_settings\TFT_ILI9163C_settings.h

```

Change

```
//  ---> SELECT HERE <----
#define __144_RED_PCB__//128x128
//#define __144_BLACK_PCB__//128x128
//#define __22_RED_PCB__//240x320

```

to

```
//  ---> SELECT HERE <----
//#define __144_RED_PCB__//128x128
#define __144_BLACK_PCB__//128x128
//#define __22_RED_PCB__//240x320

```
> 3 votes

# Answer
I wrote my own driver for DisplayCore for that very same board a while back and found the exact same problem.

The issue is just the setting for the offset of the GRAM which it looks like there is a setting for in the library you are using. Get that value right and you will have a proper display.
> 1 votes

# Answer
1. Open the file

`{sketchbook folder}/libraries/TFT_ILI9163C/_settings/TFT_ILI9163C_settings.h`

in a text editor. You can find the location of the sketchbook folder in the Arduino IDE at **File \> Preferences \> Sketchbook location**.
2. Change:

```
#define __OFFSET      32

```

to:

```
#define __OFFSET      0

```
3. Save the file.
4. Upload the sketch to the Arduino board again.
> 1 votes

---
Tags: display
---


# Question
Title: Value of uninitialized EEPROM in ESP8266?
In my limited testing it appears that the EEPROM in the Wemos D1 is not initialized to 255 like the specs say is the case for AtMega based Arduinos. In fact, the values look to be more-or-less random. Presumably this is because the ESP8266 doesn't actually contain EEPROM, but instead emulates it using flash. Is there a way to initialize the EEPROM region when flashing?

(This is pretty much the same question as here, which has not been answered.) Since I need only a few bytes of data, I'd prefer not to have to use the SPIFS.

Update:

Use case: I'm using the WiFiManager library to select the network to connect a Wemos D1 mini to the web to upload data to Thingspeak. I'd like to use WiFiManager to request the api-key and channel id from the user. However, once the user has entered these, I'd prefer not to make them enter the values again. (The api key is 16 random looking chars and difficult to enter correctly.) This means that the device has to store the values persistently between boots - the main use case for EEPROM. But how do you tell that the values in EEPROM (actually flash on an ESP device) are uninitialized crap, not the previous value? As suggested in the comments, setting flag values in a number of vars make it statistically unlikely to the random values from uninitialized memory. On an AtMega device, unless previously used, the values will be 255 in each byte.

# Answer
> 2 votes
Calculate a checksum for the data and store as part of the data. Recalculate the checksum when you read the (questionable) data back again. If the checksum fails, it's invalid. If it passes, the data is valid to some statistical level of confidence.

A 16-bit checksum would make false acceptance highly unlikely, but make it long enough for your own comfort level. What would be the worst consequence of a false acceptance: inconvenience (user has to re-enter a number)? Loss of money or property? Loss of life? Choose the complexity of your solution accordingly.

# Answer
> 1 votes
Rather than use EEPROM, which is a real pain considering that it's shared between all stored data and you need to remember offsets and lengths, use SPIFFS.

By including `FS.h` in your program (or the include file that needs to store the data, if you are trying to be modular), you can store several megabytes of data as strings in a named file (much like fprintf() or open() would let you do in C++).

Call `SPIFFS.begin();` in setup(), and then use the following sections of code to read or write data to the file:

(assuming you want to store `start` and `end` in SPIFFS, but this works for any datatype known to Arduino, and probably anything with the printable attribute)

Read saved config:

```
Serial.println(F("Loading config"));
File f = SPIFFS.open("/ACTIVE_TIMES.cnf", "r");
if (!f) {
  //File does not exist -- first run or someone called format()
  //Will not create file; run save code to actually do so (no need here since
  //it's not changed)
  Serial.println(F("Failed to open config file"));
  start = 8;
  end = 20; // defaults
  return;
}
while (f.available()) {
  String key = f.readStringUntil('=');
  String value = f.readStringUntil('\r');
  f.read();
  Serial.println(key + F(" = [") + value + ']');
  Serial.println(key.length());
  if (key == F("START_TIME")) {
    start = value.toInt();
  }
  if (key == F("END_TIME")) {
    end = value.toInt();
  }
}
f.close();

```

Save configuration:

```
Serial.println(F("Saving config"));
File f = SPIFFS.open("/ACTIVE_TIMES.cnf", "w+");
if (!f) {
  //It's cases like this when calling SPIFFS.format() might be a good idea,
  //but you would not want to do so here, since if it's an error for a
  //different reason it would delete all your data. Make it manual or a prompt
  //instead.
  Serial.println(F("Failed to open config file"));
  return;
}
f.print(F("START_TIME="));
f.println(start);
f.print(F("END_TIME="));
f.println(end);
f.flush();
f.close();
Serial.println(F("Saved values"));

```

You may also call `SPIFFS.format()` to reset the filesystem (say, for a factory reset), but this will cause issues on attempting to read any stored data, since the file *will not exist*. Thus, have a section that sets reasonable defaults (or just prompts the user to set the values).

Note: Since this is for storing an API key and such, just have it fail, since the API key not working is a good notice the user needs to configure it, and you do NOT want to ship a product with a *working* API key that belongs to you rather than the user.

Final warning: Note carefully the use of `F()` around certain items in that code. This macro, specific to Arduino, allows one to store data in Flash ONLY, where strings normally consume RAM as well (once the system boots, it loads to RAM, since most code expects it there). The *benefit* of `F()`, rather than a progmem directive, is that many functions native to Arduino can read it directly thanks to overloads, or you can wrap `String()` around the `F()` to convert it to a string at runtime if the function does not allow that overload. The end result is that, as I've written it, this code should consume RAM only when it is actually running, as good code should (otherwise, it's really easy to use up all your RAM on such embedded devices if you add enough strings).

I have not bothered to do the latter with the filename passed to `open()` since it is used only once per load or save operation, does not support F() (thus I'd need to use the `String()` trick), and I'm fairly sure the compiler then shares the memory location, reducing the RAM used to only one edition of that filename.

# Answer
> 0 votes
I've done this in the past by simply checking for a string (array of characters if you prefer) at a specific memory location. I used "INITIALIZED". It would be very unlikely for the ROM to have this sequence of characters by accident. If I find the string I read the variables from ROM. If I don't, I write the string and set default values for the variables.

I found a slightly different example that uses the same technique:

```
// EEPROM library.
#include <EEPROM.h>
// Persistent Shoe State.
byte shoeState = 0;
// Number of Shoe States.
#define SHOE_STATE_MAX 3

// setup() runs once at reset.
void setup() {
  // EEPROM Init Code Base Address
  #define EEPROM_INIT_CODE_ADDR 0x00
  // Check EEPROM Init Code
  byte shoeStateInit[] = {0xde, 0xad, 0xbe, 0xaf, 0xaa};
  for(int b = EEPROM_INIT_CODE_ADDR; b < EEPROM_INIT_CODE_ADDR + sizeof(shoeStateInit); b++) {
    // EEPROM = Init Code?
    if(EEPROM.read(b) != shoeStateInit[b]) {
      // No, Write Init Code to EEPROM.
      EEPROM.write(b, shoeStateInit[b]);
      // Set Not Initialized Flag.
      shoeState = -1;
    }
  }
  // EEPROM Init Code?
  if(shoeState == 0) {
    // Yes, Read Shoe State from EEPROM.
    shoeState = EEPROM.read(sizeof(shoeStateInit));
  }
}

```

The only variable being saved to ROM is shoeState.

---
Tags: esp8266, arduino-ide, eeprom
---


# Question
Title: Newbe needing help with fixed string length
im trying to build a bit of test equipment that will talk to some software and it needs to send a fix string. when the voltage changes the string length does as well. i need to cap the results to 4 in length. (sorry for not knowing the correct terminology. this is the output i need - Where,

```
X = Flag CP Value
_ = Space
P = Polarity
C = CP Received value
Y = Flag Field Gradient
F = Field Gradient Received value
Z = Flag Contact CP
T = Contact CP Received value

```

There is also a line feed and carriage return present at the end of each string. The polarity indicator will only display a minus sign ‘-‘ if the received value is negative otherwise no assignation will be transmitted. Although the overall string length is constant the values for each measurement are right justified and hence a space will be present should the value of the measurement not necessitate the utilisation of all allocated character spaces. Sample Outputs

```
< X -89 Y -1989 Z -1096 >
< X 1039 Y 8 Z 78 >

```

this is my code so far

```
#include <Wire.h>
#include <Adafruit_ADS1015.h>

Adafruit_ADS1115 ads1(0x48);     // Use this for the 16-bit version
Adafruit_ADS1115 ads2(0x49);

void setup(void) {

  Serial.begin(9600);

  ads1.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV
  ads2.setGain(GAIN_ONE);        // 1x gain   +/- 4.096V  1 bit = 2mV

  ads1.begin();
  ads2.begin();
}

void loop(void) {

  int16_t results01,results02,results03;

  results01 = ads1.readADC_Differential_0_1();
  results02 = ads1.readADC_Differential_2_3();
  results03 = ads2.readADC_Differential_0_1();

  Serial.print("X ");
  Serial.print(round(results01 * multiplier));

  Serial.print(" Y ");
  Serial.print(round(results02 * multiplier));

  Serial.print(" Z ");
  Serial.print(round(results03 * multiplier));

  Serial.println();              // send a cr/lf
  delay(500);
}

```

Any help pointing me in the right direction would be Amazing. Thanks in advance

Joe

# Answer
> 1 votes
The printf() family of functions comes handy when you need this kind of control over the formatted output:

```
/*
 * Format a number as 5 characters.
 * Returns the string in a statically allocated buffer.
 */
char * format5(int x)
{
    static char buffer[6];  // 5 chars + terminating NUL
    snprintf(buffer, sizeof buffer, "%5d", x);
    return buffer;
}

void setup() {
    Serial.begin(9600);
    Serial.println(format5(15));
    Serial.println(format5(-15));
    Serial.println(format5(-1500));
    Serial.println(format5(1500));
}

void loop(){}

```

output:

```
   15
  -15
-1500
 1500

```

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


title: Does UNO and Nano have the same pins?

text:
# Question
Title: Does UNO and Nano have the same pins?
Do Arduino Nano Atmega328p have the same pins as Arduino/Gizduino Uno Atmega328p?

# Answer
The '328P uC on the boards is the same die. The 328P in DIP has 4 fewer pins brought out (Vcc, Gnd, A6, A7) compared to the surface mount parts. The boards themselves then bring the pins out to edge connectors in physically different locations.
> 1 votes

---
Tags: arduino-mega, arduino-nano
---


title: Reading Multiple Analog Input Pins

text:
# Question
Title: Reading Multiple Analog Input Pins
I am having a bit of trouble trying to read multiple Analog Input Pins (A0 and A3, in this instance). I am using a Pololu A-Star 32U4 LV Robot Controller (https://www.pololu.com/product/3116), and am using the Arduino IDE to program the board; it is recognized as a Arduino Leonardo. I am using the Joystick Library (https://github.com/MHeironimus/ArduinoJoystickLibrary/tree/version-2.0) to have the controller be recognized by Windows as a Game Pad (irrelevant to the issue I am seeing, I believe).

I am simulating an Axis by using a potentiometer, with the data line running into the Analog Input, the 5V baseline coming from the board, and the Ground on the opposite of the Analog Input. This does indeed cause the values to change.

The issue that I am specifically running into is when I attempt to get the analog value for each pin that I am monitoring, it appears that the values of the other pins change at the same time. Because I am trying to use the Analog Pin values to drive an X/Y Axis, this issue manifests itself in an X/Y graph that appears linear with some sort of defined slope (with an X change leading to a Y change); rather than the expected X Horizontal only movement and Y Vertical only movement.

Further.. when I remove the second Axis (ie. only using X or only using Y), it appears to track as I expect, with the Pot moving the axis (changing the value of the Analog Input).

Here is where I check the pins in the loop:

```
  // Read the Analog Pins and update the controller
  for(uint8_t a = 0; a < TOTAL_AXIS_PINS; a++) {
    checkAnalogAxisState(a, axisPins, axisPinVals);
    delay(10);
  }

```

And here is where I attempt to send the X/Y Axis changes based off of the readings coming from the Analog Pins:

```
// Checks the Analog Pin for a value to be used as the Axis value. Only updates the state if it
// has been found to have changed. Will update the Joystick Axis based on which pin it is currently
// looking at
void checkAnalogAxisState(uint8_t pinIndex, uint8_t analogPins[], int analogPinVals[]) {
    uint8_t analogPin = analogPins[pinIndex];

    // The trick when using multiple analog sensors is to read them twice, with a small delay after each read (10ms is good)
    // then discard the first reading. This is because the ADC multiplexer needs switching time and the voltage needs
    // time to stabilize after switching.
    int currentState = analogRead(analogPin);
    delay(10);
    currentState = analogRead(analogPin);
    delay(10);

    if(currentState <= analogPinVals[pinIndex] - 5 || currentState >= analogPinVals[pinIndex] + 5) {
        if(analogPin == X_AXIS_PIN) {
            Joystick.setXAxis(currentState - ANALOG_ADJUSTMENT);
        } else if(analogPin == Y_AXIS_PIN) {
            Joystick.setYAxis(currentState - ANALOG_ADJUSTMENT);
        }
        analogPinVals[pinIndex] = currentState;
    }
}

```

I try to keep the Pin and the Value of that pin in an array, but even when I do this with 2 separate variable and function calls, I still see that the Analog values change at the same time.

Here is the full sketch, I can include the full contents of ControllerDefines.h and ControllerFunctions.h if they will be helpful, but I have pulled the relevant functions from each:

```
#include <AStar32U4.h>
#include <Joystick.h>
#include "libraries/ControllerDefines.h"
#include "libraries/ControllerFunctions.h"

void setup() {
  // Setup pins for the Axis controls
  for(uint8_t a = 0; a < TOTAL_AXIS_PINS; a++) {
    pinMode(axisPins[a], INPUT);
  }

  // Setup Joystick
  Joystick.begin();
  Joystick.setXAxisRange(-ANALOG_ADJUSTMENT, ANALOG_ADJUSTMENT);
  Joystick.setYAxisRange(-ANALOG_ADJUSTMENT, ANALOG_ADJUSTMENT);

  // Setup Serial Comm
  Serial.begin(9600);
}

void loop() {
  // Read all button states and update the controller
  for(uint8_t b = 0; b < TOTAL_BUTTONS; b++) {
    checkButtonState(b, buttons, buttonStates);
  }

  // Read the Analog Pins and update the controller
  for(uint8_t a = 0; a < TOTAL_AXIS_PINS; a++) {
    checkAnalogAxisState(a, axisPins, axisPinVals);
    delay(10);
  }

  // Delay before polling buttons again
  delay(50);
}

```

Edit:

I have taken a plot of the 2 Array values over time, as can be seen here. This is with the Pot hooked up to A3, which is `axisPinVals[0]`:

Moving the Pot to A0 gives the following:

Using the modified code below:

```
  // Read the Analog Pins and update the controller
  for(uint8_t a = 0; a < TOTAL_AXIS_PINS; a++) {
    checkAnalogAxisState(a, axisPins, axisPinVals);
    delay(10);
  }

  // For the plotter
  Serial.print(axisPinVals[0]);
  Serial.print(",");
  Serial.println(axisPinVals[1]);

```

As you can see, the two values track together. This same behavior is not present in the buttons presses, and multiple buttons can be held at the same time with no issue.

I would expect each variable (line) to track independently of one another, when the Pot is moved from A0 to A3.

# Answer
> 1 votes
I can't reproduce your problem. Your code is a bit lengthy to say for certain whether or not A0 and A3 clash when read in quick succession. Try this test code and see what results you get:

```
void setup() {
 Serial.begin (115200);
 while (!Serial) {}  // wait for Serial

 Serial.println ("Starting");
}

void loop() {

int a, b;

  a = analogRead (0);
  b = analogRead (3);

  Serial.print ("A0 = ");
  Serial.println (a);
  Serial.print ("A3 = ");
  Serial.println (b);
  delay (100);
}

```

I found on my Micro (which has the same processor) that the two inputs were completely independent. For example changing A3:

```
A0 = 0
A3 = 195
A0 = 0
A3 = 453
A0 = 0
A3 = 680
A0 = 0
A3 = 879

```

And then changing A0:

```
A3 = 0
A0 = 64
A3 = 0
A0 = 292
A3 = 0
A0 = 427
A3 = 0
A0 = 474
A3 = 0
A0 = 294
A3 = 0
A0 = 48

```

This was with two potentiometers connected at all times. If you only had one you might get a "floating" input.

I suggest you try the code above and confirm whether or not you get similar results. If you do, then the problem is not "Reading Multiple Analog Input Pins" but something else entirely, like logic in your code.

Even when I changed the delay in my code to 10, the figures reported were still independent. That is, one pot did not influence the other at all.

# Answer
> 0 votes
Try reading each input twice in a row, and use the value from the 2nd read. The input source may need additional time to charge up the sample & hold cap that is read by the ADC in the uC.

---
Tags: analogread, loop, joystick
---


# Question
Title: Advanced ADC setup on Due (SAM3X8E) to increase precision
I want to make some precise measurements with Arduino Due. Although I'm using very good external voltage reference (LTC6655) measured data is still jumping around, especially significant when I'm trying to measure low voltages (0.1-0.05V). Can I improve ADC accuracy by changing it's settings?

The default Arduino Due ADC settings are:

```
// Initialize Analog Controller
pmc_enable_periph_clk(ID_ADC);
adc_init(ADC, SystemCoreClock, ADC_FREQ_MAX, ADC_STARTUP_FAST);
adc_configure_timing(ADC, 0, ADC_SETTLING_TIME_3, 1);
adc_configure_trigger(ADC, ADC_TRIG_SW, 0); // Disable hardware trigger.
adc_disable_interrupt(ADC, 0xFFFFFFFF); // Disable all ADC interrupts.
adc_disable_all_channel(ADC);

```

So, with `adc_init` we can configure frequency and startup time. And with `adc_configure_timing` we configure tracking time, settling time and transfer time. But how to select those values? Does increasing of that times improves precision?

Useful links:

Datasheet \- ADC description starts on page 1317.

Atmel Software Framework \- see adc.h and adc.c.

# Answer
> 2 votes
Generally speaking the input BandWidth of the analog signal is a major cause of noise in a ADC circuit as well as improper ground and reference generation and layout techniques. Be very careful that ALL of the analog paths do not have any digital current return paths. Remember that at 12 bit for a 1.25V reference an LSB is ~300uV. I have not ever measured the SNR of the SAM ADC but I doubt that it is the specified ~60db (i.e. 10bit) unless absolute care is taken during the layout/routing. Recommend: 1) Limit input BW to the correct channel ground. (well below Nyquist BW if possible to avoid alliasing) 2) Oversample if possible. 3) Insure low digital I/O of peripherals during sample period.

# Answer
> 0 votes
Default resolution is 10b because of backward compatibility, so you can start with setting `analogReadResolution(12);` as stated on Arduino analogReadResolution Refference page.

If it's still not enough you can use GAIN setting for used ADC channel. For single ended input GAIN can be set up to 4. But it means you can mesaure voltages up to 1/4 of Uref

# Answer
> 0 votes
> measured data is still jumping around

it will always jump around -\> that's why adc modules are such a great random number generators (using its lsb). jumping around 8 - 9 lsb isn't that rare. anything beyond that should be investigated.

a few things to watch for:

1. use a good reference;
    2. allow sufficient time;
    3. pay attention to layout;
    4. make sure that the source impedance isn't too great;
    5. put a signal conditioning circuit on the input. a 1k/.1uf filter can do wonders;
    6. pick the right oscillator for the adc module - see some c8051f350 code for example;
    7. write the right code;
    8. oversampling.

---
Tags: arduino-due, analogread, adc
---


# Question
Title: Cannot get esp8266 - 12 wifi module to always read analogRead incoming voltage accurately
So I have and arduino uno that is firing an output on pin 8. This code is not in this file just to be clear. From there Im taking that output and using it to fire pin 0 on the wifi module. Im using pin 0 because from what I understand all other pins have a pullup or pulldown resistor. When pin 0 is hot I want to print that value. Sometimes it works when I do it other times the analog values reads very low. I am using the 3.3v from the arduino uno and I plan to get a voltage regulator for the wifi module but would this cause this kind of issue? I am very very new to arduino so if anyone has any ideas I would appreciate a very dumbed down explanation. Thanks a lot. Also the reason why I have the delay turned down so low is because it seemed to make the analog signal pick up more often. Im not sure why this would matter but at a delay of 3000 it would almost never change analog value but when I turned the delay down to one the value came through much more consistently. Currently the code just outputs low analog numbers and occasionally pops up 1023 when voltage is applied but not consistently. And sometimes it just stops altogether until I keep trying for a while. I am getting voltage to the pin however so I know I have a complete circuit and power.

# include

```
#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>

const char* ssid = "ENDOWED Underwear";
const char* password = "endowwear";

HTTPClient http;

static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t D9   = 3;
static const uint8_t D10  = 1;

int featherPin = D3;

void setup() {
  Serial.begin(115200);
  pinMode(featherPin, INPUT);

  WiFi.begin(ssid, password);

  while(WiFi.status() != WL_CONNECTED) {
    delay(10);
    Serial.println("Waiting for connection");
  }
}

void loop() {
  int sensorValue = analogRead(featherPin);

  if (WiFi.status() == WL_CONNECTED) {
        Serial.println("yay connect");

        http.begin("http://10.150.40.121:3000/");
        http.addHeader("Content-Type", "text/plain");

        int httpCode = http.POST("Message from ESP8266");
        String payload = http.getString();
//        Serial.println(payload);
        http.end();

    } else {
        Serial.println("Error in Wifi connection");
    }

    if (sensorValue > 850) {

      http.begin("http://10.150.40.121:3000/home");
      http.addHeader("Content-Type", "text/plain");

      int httpCode = http.POST("Message from ESP8266");
      String payload = http.getString();
      Serial.println(payload);
      Serial.print("hi");
      http.end();
      } else if (sensorValue < 850) {
        Serial.print(sensorValue);
//        Serial.println("I am not hot");
      }

//  digitalWrite(trigPin, LOW);
//  delayMicroseconds(1);
//  digitalWrite(trigPin, HIGH);
//  delayMicroseconds(2);
//  digitalWrite(trigPin, LOW);
//
//  pinMode(echoPin, INPUT);
//  duration = pulseIn(echoPin, HIGH);
//
//  inches = (duration / 2) / 74;
//  Serial.println(inches);
//
//  spaceIntruded = inches;
//
//  if (spaceIntruded <= 50 || spaceIntruded >= 900){
//      digitalWrite(ledPin, HIGH);
//      digitalWrite(hornPin, HIGH);
//      Serial.println("Intruder Detected!");
//      Serial.println("Sending text Notification...");
//      delay(500);
//      Serial.println("Armed...");
//  }
//
//  else{
//    digitalWrite(hornPin, LOW);
//    digitalWrite(ledPin, LOW);
//  }
    delay(1);

}

```

# Answer
> 1 votes
Analog to Digital conversion is one aspect1 where the ESP8266 is very poor. It has a single ADC pin which can read a maximum of 1V.

That pin is the only pin you can use with `analogRead()`. Any attempts to use any other pin just use that pin instead. The parameter (pin number) to `analogRead(pin)` is ignored and no matter what you do that one single ADC pin is what is being read. Also the pin cannot be used for anything else. None of the digital functions can be used with it since the pin doesn't have a GPIO number associated with it.

Some boards include a simple voltage divider on the ADC pin to allow higher voltages to be read, such as the NodeMCU:

If your board doesn't have such a divider you will have to implement it (or something similar) to be able to read the 3.3V incoming voltage.

---

1 The ESP8266 is great for WiFi but pretty poor for everything else. It is seriously starved of internal peripherals (it doesn't even have I²C). For a more feature-rich solution you might consider upgrading to the ESP32.

---
Tags: arduino-uno, esp8266, analogread, analogwrite
---


title: Detect power interruption on NodeMCU

text:
# Question
Title: Detect power interruption on NodeMCU
Im using a 5v 1A power supply and connected to VIN pin on the NodeMCU. I also use 18650 battery to keep NodeMCU running in case the power supply shuts off due to power interruption.

I'm planning to use the 5V from power supply, convert it to 3.3V with voltage divider and connect it to the gpio to detect power interruption.

Is it possible? Can the NodeMCU handle the current from the power supply?

# Answer
> 1 votes
Yes, you can. You need to convert the 5V down to 3.3V with a voltage divider. You also need to consider how you are going to operate the ESP8266 when there is no power.

---
Tags: esp8266, pins, nodemcu, current, voltage
---


# Question
Title: ESP8266 + DHT11 AWS IOT Thing not updating thing shadow - was working before
I was able to get this working - https://www.youtube.com/watch?v=8hpro1olRK0 \- send an SMS and email of temperature and humidity data from AWS IOT using esp8266 + dht11 but all of a sudden it stopped updating the shadow.

Here is the code

```
#include <ESP8266WiFi.h>
#include <DHT11.h>
#include <AmazonIOTClient.h>
#include <ESP8266AWSImplementations.h>

Esp8266HttpClient httpClient;
Esp8266DateTimeProvider dateTimeProvider;

AmazonIOTClient iotClient;
ActionError actionError;

const char* ssid = "";
const char* password = "";

// Pin 2 will be used to read sensor data
int pin = 2;

// Initializing the sensor
DHT11 dht11(pin);

//Function to convert Celsius to Fahrenheit
double Fahrenheit(double celsius) {
  return ((celsius * 9 / 5) + 32);
}

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

  // Connecting to Wi-Fi
  WiFi.mode(WIFI_STA);
  Serial.println();
  Serial.println();
  Serial.println("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  iotClient.setAWSRegion("us-west-2");
  iotClient.setAWSEndpoint("amazonaws.com");
  iotClient.setAWSDomain("al1x5kb4rzh0x.iot.us-west-2.amazonaws.com");
  iotClient.setAWSPath("$aws/things/esp8266/shadow/update/accepted");
  iotClient.setAWSKeyID("AKIAJJQ6ASLIDIPBE4PQ");
  iotClient.setAWSSecretKey("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");
  iotClient.setHttpClient(&httpClient);
  iotClient.setDateTimeProvider(&dateTimeProvider);
}

void loop() {
  int err;
  float temp, humi;

//Reading the sensor data
  if ((err = dht11.read(humi, temp)) == 0) {
    Serial.print(" temperature:");
    Serial.print(temp);
    Serial.print(" humidity:");
    Serial.print(humi);
    Serial.println();
  } else {
    Serial.println();
    Serial.print(" Error No :");
    Serial.print(err);
    Serial.println();

  }
// Converting the float data to char arrays
  char sTemp[10], sHumi[10];
  dtostrf(humi, 6, 2, sHumi);
  dtostrf(temp, 6, 2, sTemp);

// Creating the thing shadow to be sent to aws iot
  char shadow[100];
  strcpy(shadow, "{\"state\":{\"reported\": {\"Humidity\":");
  strcat(shadow, sHumi);
  strcat(shadow, ", \"Temperature\":");
  strcat(shadow, sTemp);
  strcat(shadow, "}}}");
  Serial.print(shadow);

  char* result = iotClient.update_shadow(shadow, actionError);
  Serial.print(result);

  delay(60000);
}

```

Output as expected

```
Connecting to
NETGEAR53
.........
WiFi connected
 temperature:31.00 humidity:32.00
{"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
443
POST $aws/things/esp8266/shadow/update/accepted HTTP/1.1
Content-Type: application/json
Connection: close
Content-Length: 65
Host: al1x5kb4rzh0x.iot.us-west-2.amazonaws.com
x-amz-content-sha256: 923ed1ae613a9e14b45e4d080b092daf5cf61118041dc5225956299d5b0f8d49
x-amz-date: 20180323T034259Z
Authorization: AWS4-HMAC-SHA256 Credential=AKIAJJQ6ASLIDIPBE4PQ/20180323/us-west-2/iotdata/aws4_request,SignedHeaders=content-type;host;x-amz-content-sha256;x-amz-date,Signature=a10f0969043e609743412478567c10290b8c000185f2824e4a9cf07bb96cf279

{"state":{"reported": {"Humidity": 32.00, "Temperature": 31.00}}}

```

# Answer
I was facing a similar problem: trying to update a thing's shadow on AWS IoT with no success. After some research, I found out that I was using an **outdated library**. In this question they advise to use *heskew*'s `aws-sdk-arduino`, on `iot-get-shadow-and-cleanup` branch:

https://github.com/heskew/aws-sdk-arduino/tree/iot-get-shadow-and-cleanup.

Additionally, I think you have a little error on your code. As far as I know, `AWSPath`, it should look like:

```
iotClient.setAWSPath("/things/esp8266/shadow");

```

At least that works for me, and they use it this way on this video.

That's all I can tell... I am learning at this moment as well. Hope it helps!!
> 1 votes

# Answer
Just Change the Aws topic : it should be $aws/things/esp8266/shadow/update

and you have to add the certificate path also
> 1 votes

---
Tags: esp8266, iot
---


# Question
Title: SSD1306 allocation failed when adding a constant
I am trying to get this code working:

```
#include <Button.h>
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <RTClib.h>

#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 32 // OLED display height, in pixels

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
RTC_DS1307 RTC;

// when I remove this part it works...
int mode = 1;
const String periodicSystem[60] = {
    "H", "He", "Li", "Be", "B", "C", "N", "O",
    "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S",
    "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr",
    "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge",
    "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb",
    "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn",
    "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd"
};
/////////////////////////////////////////////////////////////////////

Button button1(7);

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

  // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) { // Address 0x3C for 128x32
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // Don't proceed, loop forever
  }

  RTC.begin();
  if (! RTC.isrunning()) {
    Serial.println("RTC is NOT running!");
    // This will reflect the time that your sketch was compiled
    RTC.adjust(DateTime(__DATE__, __TIME__));
  }

  display.display();
}

void loop() {
  DateTime now = RTC.now();
  if(button1.pressed()) {
      display.clearDisplay();
      display.setTextSize(1); // Draw 2X-scale text
      display.setTextColor(WHITE);
      display.setCursor(10, 0);
      display.print(now.second());
      display.display();
  }
}

```

Whenever I try to add the constant `periodicSystem`, I get the error `SSD1306 allocation failed` over Serial. The error also goes away when I remove the part with `button1.pressed()`. Basically I am not able to add the constant `periodicSystem` and read out a digital pin at the same time. To me it seems to be some sort of memory issue (I am only adding the constant, I am not doing anything else with it), but my IDE tells me I am only using 52% of the available storage. What am I doing wrong?

Here is my wiring (in reality I am using a 128x32 display, I didn't have the correct part for Fritzing; my display is labeled SDA, SCK, VCC, GND instead of SDA, SCK, VDD, GND; the RTC Module I am using is a DS1307 AT24C32 RTC Module):

# Answer
> 2 votes
Your display needs 624 bytes of RAM for its internal buffer (`128 * ((32 + 7) / 8)`). The `periodicSystem` array needs a massive 360 bytes of RAM just for the objects. That doesn't include the memory used to store the actual string data, which by my reckoning is 168 bytes.

So far we're up to 624+360+168 = 1152 bytes of a maximum of 2048. Over half way and we haven't touched on the serial buffers or other objects that you're using.

An array (`const` or otherwise) of `String` objects is by far the least efficient way possible of storing constant string data on an Arduino. You're using 528 bytes of RAM to store what could be stored in 121 bytes of flash.

Personally I would store the data thus:

```
const char periodicSystem[] PROGMEM = "H HeLiBeB C N O F NeNaMgAlSiP S ClArK CaScTiV CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY ZrNbMoTcRuRhPdAgCdInSnSbTeI XeCsBaLaCePrNd";

```

Each symbol consists of exactly two bytes, and the `PROGMEM` forces it to stay in flash and never be copied to RAM.

You can get the two bytes of each symbol with:

```
char b1 = pgm_read_byte(periodicSystem + (i * 2));
char b2 = pgm_read_byte(periodicSystem + (i * 2) + 1);

```

Then either print them separately, or combine them into a C string:

```
char symbol[3] = { b1, b2, 0 };

```

That will include the space character, of course. So you could remove that if you like:

```
if (symbol[1] == ' ') symbol[1] = 0;

```

Theoretically you could also change the spaces in the original data to be character 0 if you like - depending on what you do with it, it shouldn't cause any issues:

```
const char periodicSystem[] PROGMEM = "H\0HeLiBeB\0C\0N\0O\0F\0NeNaMgAlSiP\0S\0ClArK\0CaScTiV\0CrMnFeCoNiCuZnGaGeAsSeBrKrRbSrY\0ZrNbMoTcRuRhPdAgCdInSnSbTeI\0XeCsBaLaCePrNd";

```

---
Tags: arduino-nano, i2c, display, rtc
---


# Question
Title: Newbie question: Set servo at certain degrees when something happens
I am trying to set my servo at f.e. 90 degrees when the friendlyValue of the soil sensor is \< 50%. The servo isn't moving at all, is it because the code is running too fast and the servo doesn't have time to reposition in between? I tried putting in delays but that didn't work, how do I fix this? I am new to Arduino and would appreciate any help.

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

int dryValue = 1024; // max
int wetValue = 0; // min

int friendlyDryValue = 0; // %
int friendlyWetValue = 100;

int sensor = A0;
int sensorValue;

void setup() {

  Serial.begin(115200);

  pinMode(A0, INPUT);
  pinMode(D6, OUTPUT);
}

void loop() {

  int rawValue = analogRead(A0); // soil sensor

 Serial.print("Raw: ");
  Serial.print(rawValue);
  Serial.print (" | ");

   int friendlyValue = map(rawValue, dryValue, wetValue,     friendlyDryValue, friendlyWetValue);

  Serial.print("Friendly: ");
  Serial.print(friendlyValue);
  Serial.println("%");

if (friendlyValue <50)
{
  myservo.write(9);
  }
  else
  {
    myservo.write(90);
    }
  }

```

# Answer
From your statement `pinMode(D6, OUTPUT);`, It looks you're using pin6 for the servo - ? If so, you need instead: `myservo.attach(6);` to prepare a servo object to use that pin to drive a servo. Not having done this is the reason why your servo wasn't moving. There is an example program to drive a servo using the servo library on the Arduino site.

Your code will run very fast, but since soil moisture can't change rapidly, the value being read from the soil sensor shouldn't either - unless there is electrical noise (and there will always be some; it's a question of how much). Your print statements should show you how consistent the readings are.

There are a couple of things you can do about it:

1. Delay for a second or so at the bottom of the loop() function so the servo updates will come less frequently and the servo will have time to track them. This really doesn't help with a noisy signal though, and you probably don't want it to track noise. Also, I don't usually suggest using delays but in so uncomplicated a program as this one, it is really the most straightforward approach.
2. Calculate the servo position from an average of a few sensor readings rather than using just one. This will help with noise so the servo should only have to track real data rather than data+noise.
3. Do both. Update less frequently and average a few readings taken a few 10s of milliseconds apart. This will both reduce noise and keep the servo updates to within its tracking ability.
> 1 votes

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


title: How to upload Arduino C code to mBot?

text:
# Question
Title: How to upload Arduino C code to mBot?
I am trying to program mBot using Arduino IDE. I am connected to the mBot using USB on `COM7`, I am able to upload a code created in mBlock 3.4.11 fine, using "Arduino Mode" as the editing mode. I would like to proceed to more complex coding now and for this I want to be able to edit the source code directly. The source code seen in the MBlock application seems to be read only, there is a button which should allow editing the code, called "Edit with Arduino". When I press this button, the Arduino IDE opens and I am able to edit the code. The trouble is I seem to be unable to send the code edited this way into the mBot.

When I use the Arduino IDE Sketch/Upload menu item, the code is compiled, but when sending it, I always get following error:

> avrdude: stk500v2\_ReceiveMessage(): timeout

Note: I was editing and uploading Arduino code before with both Ardino IDE and VisualStudio visualMicro (now Arduino IDE for Visual Studio) without any issues.

I do not know exactly how is the mBlock application handling the upload, but while doing so a folder with the project is created, which contains the following buildprefs.txt - perhaps this could help to understand what it is doing:

```
build.arch = AVR
build.board = AVR_UNO
build.core = arduino
build.core.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\cores\arduino
build.extra_flags =
build.f_cpu = 16000000L
build.mcu = atmega328p
build.path = X:\Users\UserName\AppData\Local\Temp\build3998294614124133332.tmp
build.project_name = project_followLineAuto0_0.cpp
build.source.path = X:\Users\UserName\AppData\Roaming\com.makeblock.Scratch3.4.11\Local Store\scratchTemp\project_followLineAuto0_0
build.system.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\system
build.usb_flags = -DUSB_VID={build.vid} -DUSB_PID={build.pid} '-DUSB_MANUFACTURER={build.usb_manufacturer}' '-DUSB_PRODUCT={build.usb_product}'
build.usb_manufacturer = "Unknown"
build.variant = standard
build.variant.path = X:\Users\UserName\mblockExe\Arduino\hardware\arduino\avr\variants\standard
build.verbose = true
build.warn_data_percentage = 75
compiler.S.extra_flags =
compiler.S.flags = -c -g -x assembler-with-cpp
compiler.ar.cmd = avr-ar
compiler.ar.extra_flags =
compiler.ar.flags = rcs
compiler.c.cmd = avr-gcc
compiler.c.elf.cmd = avr-gcc
compiler.c.elf.extra_flags =
compiler.c.elf.flags = {compiler.warning_flags} -Os -Wl,--gc-sections
compiler.c.extra_flags =
compiler.c.flags = -c -g -Os {compiler.warning_flags} -ffunction-sections -fdata-sections -MMD
compiler.cpp.cmd = avr-g++
compiler.cpp.extra_flags =
compiler.cpp.flags = -c -g -Os {compiler.warning_flags} -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -MMD
compiler.elf2hex.cmd = avr-objcopy
compiler.elf2hex.extra_flags =
compiler.elf2hex.flags = -O ihex -R .eeprom
compiler.ldflags =
compiler.objcopy.cmd = avr-objcopy
compiler.objcopy.eep.extra_flags =
compiler.objcopy.eep.flags = -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0
compiler.path = {runtime.tools.avr-gcc.path}/bin/
compiler.size.cmd = avr-size
compiler.warning_flags = -w
compiler.warning_flags.all = -Wall -Wextra
compiler.warning_flags.default =
compiler.warning_flags.more = -Wall
compiler.warning_flags.none = -w

```

# Answer
> 1 votes
Be sure to select correct board (Arduino UNO) and port.

See this guide for details: https://www.arduino.cc/en/Guide/ArduinoUno#toc5

---
Tags: arduino-ide, mbot
---


title: upcoming voltage from a button

text:
# Question
Title: upcoming voltage from a button
i use this simple code for arduino :

```
const int buttonPin = 2;
const int ledPin =  13;

int buttonState = 0;

void setup() {
  pinMode(ledPin, OUTPUT);
  pinMode(buttonPin, INPUT);
  Serial.begin ( 9600 ) ;
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH);
    Serial.println ( buttonState ) ;
  } else {
    digitalWrite(ledPin, LOW);
    Serial.println ( buttonState ) ;
  }
}

```

it's so basic program, I've seen some people work with Resistors when they use buttons, so i wanted to know why, i plugged in one side of the button to the pin 2 , no matter if i plugged in the other side of the button or no to the 5 volte source, the arduino started giving me some ones and zeroes therefore the blinking of the led, so basically that means there's a certain voltage comming from the button to the pin 2, I wonder why and what's the reason for this ?

# Answer
> 2 votes
I see you are new to Arduino, so let's start: 1) if you say it works you might be using an circuit like this:

which is not all bad but you might find trouble. I explain:

**1.** When you set pinMode(pin,**INPUT**); you tell arduino to enable a **high-impedance state** on that pin: it's equivalent to **100Mohm** resistor in series in front of that pin, good for getting sensor readings, but when you use a switch the state/reading of that pin (HIGH or LOW) is "floating" when the switch is opened which will give unpredictable readings. That's why you need to use a "pull-down" resistor, which means you pull down the value of that pin when the switch is OPENED by using GND as reference value for LOW so you are sure it goes down when switch is opened. The resistor also serves as protection (10Kohm is recommended) when the switch is CLOSED as it stops the high current flow/drain (!!5V pin connected to GND!!) that arduino can't support without (aka short-circuit).

**2.** So you end up with something like this: I would personally put the resistor and the GND wire between the button and the digital pin wire. I hope I was useful! If you need/want more documentation check those two links out:

https://www.arduino.cc/en/Reference/Constants look into "Defining Digital Pins modes" section

https://www.arduino.cc/en/Tutorial/DigitalReadSerial here you have an practical example.

# Answer
> 1 votes
Note that there is another, easier way to do this. If instead of setting your pin to INPUT, you set it to INPUT\_PULLUP then internally the input line is connected through a resistor to +5 volts. Then when nothing is connected to the pin, it reads as HIGH. You connect your input to a switch, and connect the other pin of the switch to ground Now when you press the switch it grounds the input pin, pulling it low. No resistors needed, but it does mean the state of your switch is reversed (HIGH = switch not pressed, LOW = pressed)

---
Tags: arduino-uno, button
---


# Question
Title: Is it okay to short IN and GND pins of relay module with controller ground?
I have this relay module that is attached to an ESP8266 (Wemos D1 Mini). Currently, I operate the relay by shorting the IN and GND pins to ground (relay module uses low state to energize) with a transistor hooked to my D1 pin. Relay 5V comes from an external power supply

The circuit diagram can be found here.

The module works fine and all but I am wondering: is it okay to operate it like this ?

# Answer
It is not okay. The base-emitter of an NPN transistor acts as a diode. That means pin D1 is shorted to GND via a "diode". You need a resistor to the base of the transistor.

The relay module has already a transistor to drive the relay and also a flyback diode. The control signal that is needed depends on the relay module. The explanation "*5VDC to 12VDC (some boards may work with 3.3)*" on the page of the relay does not sound reliable.
The relay module on that page is not the module that you have. You have a different module that is activated with a low signal.
Nevertheless, I think that a transistor can be used when the IN and GND of the relay module are connected to the collector of the transistor.

Could you please not try to make the schematic as small as possible. A schematic should explain how everything is connected.

Could try to connect the collector only the IN pin? As in the schematic below.

In your circuit diagram, the mains "neutral" is connected to an earth ground symbol. I hope you are not going to connect a mains wire to ground.

---

When the IN and GND are connected, then the resistor to the transistor needs to be lower. The ESP8266 can output 12 mA. Let's use 10 mA for safety: (3.3V - 0.5V)/10mA = 280 Ω. I suggest using a resistor of 330 Ω or more.
> 0 votes

# Answer
You mean that you pull your Arduino relay control pin LOW, causing it to ground the pin? Yes, that sounds correct. (And you would set it HIGH to not energize the relay.) You might need a low value resistor between the relay's logic pin and the Arduino output if the relay is sinking too much current through the Arduino logic pin. A 100 ohm resistor would prevent sinking too much current through the Arduino logic pin. Try it and see if the relay still energizes.

## EDIT:

When I posted my answer the image wasn't loading, so I had to guess as to what you were describing. My guess was wrong, and thus my answer was wrong too.

Since you're driving the gate of a transistor you will need a current limiting resistor or you will overload the logic pin on your microcontroller. (As Jot says in their answer.)

There are 3.3v versions of these logic-driven relay modules readily available, and some even include optical isolation, so why not use one of those?

Take this one for example: https://www.adafruit.com/product/3191 (I don’t think that one has optical isolation.)
> 0 votes

---
Tags: esp8266, relay
---


title: strcat char concatenation trouble

text:
# Question
Title: strcat char concatenation trouble
Still don't understand about char concatenation.

```
void setup() {

  testCounter(3);

}

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

char testCounter(int countx){
  char a[10];
  strcpy(a, "COUNTER: ");
  strcat(a, printDigits(countx));
  return a;
}

char printDigits(int digits){
  char a[3];
  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {
    sprintf(a,"%d",digits);
  }
  return a;
}

```

Error: *invalid conversion from 'char' to 'const char*' \[-fpermissive\]\* in `testCounter` line:

```
strcat(a, printDigits(countx));

```

Don't understand this part of error.

`printDigits` function return char, so... `strcat` should be work. But why still error?

Please help...

# Answer
```
char printDigits(int digits){

```

You are telling the compiler you will return **one** character.

```
 char a[3];

```

`a` is three characters. Thus the declaration doesn't match.

---

You could change the declaration to:

```
char * printDigits(int digits){

```

But even that would be bad because `a` would go out of scope after the function returns.

---

```
 char a[3];

```

That's a little short for putting an integer into. An integer might be 5 characters, plus possibly a minus sign, and you need a trailing "null" at the end. Seven bytes would be safer.

---

The simplest way of doing what you seem to be wanting is:

```
void setup() {
  Serial.begin (115200);
  testCounter(3);
}

void loop() {
}

char testCounter(int countx){
  char a[15];
  sprintf (a, "COUNTER: %02d", countx);
  Serial.println (a);
}

```

---

Also, here:

```
  if(digits < 10) {
    strcpy(a, "0");
    sprintf(a,"%d",digits);
  } else {

```

That won't work because you are putting "0" into `a` and then **overwriting** it with `sprintf`.

---

> `printDigits` function return `char`, so... `strcat` should be work. But why still error?

Look at the prototype for `strcat`:

http://www.cplusplus.com/reference/cstring/strcat/

It expects `char *` not `char`. They are different things. One is a pointer, one isn't.
> 2 votes

---
Tags: arduino-ide
---


# Question
Title: How to differentiate between 2 Micros on Linux
I have 2 Arduino Micro based devices that I want to use on my Ubuntu Linux machine. I need them to have unique serial ports. Unfortunately, both have the same serial number which makes identification through udev rules difficult (if not impossible).

This is the serial number that I get for both:

```
$ udevadm info -a -p  $(udevadm info -q path -n /dev/ttyACM0) | grep -i serial
  ATTRS{serial}=="0000:00:14.0"

```

Is there any way to manually set the serial number on an Arduino Micro? Or is there any other unique identifying properties I can use for udev rules?

Typically, I do something like this in my `/etc/udev/rules.d/99-usb-serial.rules` file:

```
SUBSYSTEM=="tty", ATTRS{product}=="Arduino Uno", ATTRS{serial}=="64936333936351911191", SYMLINK+="MyDevice"

```

Side note: I also have a Due, that has the same serial number as the Micros, but since ATTRS{product} is different, I can differentiate it.

# Answer
The USB VID, PID and Serial Number are all programmed into the chip when you upload your sketch. The VID and PID are tied to the board, and the serial number is always the same regardless of which board.

So no matter which board you program it will get the same details as any other board of the same kind.

There's no option to change the serial number (there is, IIRC, actually no serial number defined) but the VID and PID are provided as a pair of macros on the compilation command line: `USB_VID` and `USB_PID`.

So you could (cheakily) create a new board definition (based on the existing Micro one) that is "The other Micro" and provide a different (unofficial) PID to that board. You can then differentiate the two boards in udev using the VID/PID combination.

Of course, you have to then ensure that you have the right board selected when you program them, and the act of entering the bootloader on the "other" board would revert back to the old PID which is programmed into the bootloader, but I'm sure you can cope with that.
> 3 votes

# Answer
That "0000:00:14.0" isn't the serial number for the Arduino: udevadm is printing info for more than one device, and that's for the USB controller chip.

Arduinos built on the ATMEGA32U4 don't get a serial number: I have some Leonardos giving me the same problem you're having. When the bootloader was originally designed, the programmer didn't have it report one. I found a modified bootloader that does, but I haven't tried it yet: http://forum.arduino.cc/index.php?topic=503703.0

Genuine Arduinos with an FTDI chip report unique serial numbers. Some of the knock-offs either don't set it in the chip, or may set it to some non-unique number(skipping that step to save a few cents of manufacturing cost). Ones that use a 16U2 chip for the USB interface (like the Uno R3) are *supposed* to get a unique serial number. The Chinese ones I just bought did, but it's possible that other makers of them are cutting corners like some users of FTDI chips do.

Arduinos that use the Chinese CH340 USB chip also don't report a serial number: the chip doesn't support it. I *think* that's also true for the CP2102, but I'm not certain.

You *may* be able to fix the problem with that modified bootloader (I hope so: I have half-a-dozen Leonardos, and it's a hassle anytime I have more than one connected simultaneously. Fortunately, I don't normally use them as "PC peripherals"). Or you could buy another of the "tiny" Arduinos with a 328P that uses a USB-to-serial chip, and base the udev rules on VID and PID to distinguish them.
> 1 votes

---
Tags: arduino-micro, linux
---


# Question
Title: Debugging a Nordic MCU (feather NRF52) using Segger J-Link
I have an Afafruit NRF52 board with SD 132 and 5.1 dual fw bootloader. I implemented RTT logging and controlling (input) and the code is compiled using arduinoBuilder with RTT and debug level 3. The device uses to control DALI lights but sometimes it hangs, I can see that it does not responses to input and light level never changes.

I want to debug it, maybe getting a stacktrace to see where it hangs, hoping it's a software issue.

Any leads on how to do that ? Tutorial maybe ?

# Answer
> 0 votes
I haven't tried this, but OpenOCD supports both the nRF52 and the JLink. Something like (on Linux):

```
openocd -f /usr/share/openocd/scripts/interface/jlink.cfg -f /usr/share/openocd/scripts/target/nrf52.cfg

```

might start OpenOCD.

You can then connect with (nRF52 flavour of) gdb (arm-none-eabi-gdb).

You can find information about using gdb with OpenOCD here and here.

---
Tags: debugging, nrf51
---


title: ESP8266 Switching firmware on the fly

text:
# Question
Title: ESP8266 Switching firmware on the fly
Can you help me out to understand if this is possible with ESP8266 / 32 ?

I have a main binary that i upload to the chip, let's call it **A** \- that's done from arduino.

**A** starts to work, but communicates every couple of minutes with central server polling for a *task*.

If there is a task - let's call it **B**

**A** downloads it and stores it on SPIFFS.

Now what should happen is that **A** uploads it, reboots and **B** starts to work.

When **B** finishes it loads up again **A** and the circle closes - this process goes on forever.

Questions:

1) Is it possible that a stored on SPIFFS binary file can be uploaded to the chip? Like OTA does via www.

2) Can i somehow store **A** onto the SPIFFS, so that when **B** finishes i reupload **A** ?

Thanks for any input into this

# Answer
> 0 votes
I think i've found an answer to my question here

https://www.esp8266.com/viewtopic.php?f=32&t=11324

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

#include "FS.h"

void setup() {
  Serial.begin(115200);
  Serial.println();
  SPIFFS.begin();
  Dir dir = SPIFFS.openDir("/");

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

  File file = SPIFFS.open("/blinkESP.bin", "r");

  uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
  if (!Update.begin(maxSketchSpace, U_FLASH)) { //start with max available size
    Update.printError(Serial);
    Serial.println("ERROR");
  }

  while (file.available()) {
    uint8_t ibuffer[128];
    file.read((uint8_t *)ibuffer, 128);
    Serial.println((char *)ibuffer);
    Update.write(ibuffer, sizeof(ibuffer));

  }

  Serial.print(Update.end(true));
  digitalWrite(BUILTIN_LED, HIGH);
  file.close();
}

void loop() {

}

```

Will give it a try and revert back to confirm if it answers my question.

# Answer
> 0 votes
The esp8266 Arduino package has 3 libraries for firmware update.

* ArduinoOTA for upload from Arduino IDE
* ESP8266HTTPUpdateServer for upload with web browser
* **ESP8266httpUpdate library to check a web server for new version of the firmware**

---
Tags: esp8266, esp32
---


# Question
Title: Analog vs Digital Accelerometers - pro's and con's?
For my project i need to measure accelerations up to 16g. My options are either digital accelerometers such as the MPU6050 or MPU9250 or an analog accelerometer such as the ADXL326.

What are any major pro's and con's of each. number of wires would be almost equal. the digital accelerometer is less pins on the board but i could easily use analog to digital convertors to bypass that. sampling rate is lower at 550Hz for the analog vs 4000Hz for the MPU9250. However i believe 550Hz would be more than adequate. And the biggest difference for me. £2 for an MPU9250 and £12 for the ADXL326!

Does anyone have any general advice on the main differences when choosing between analog and digital? I am measuring suspension motion on a motorcycle and need 5 of these accelerometers.

# Answer
> 3 votes
The biggest difference is where the measurement (the conversion to digital) is done. On the digital accelerometer, it is done in the accelerometer itself. On the analog one it is done at the MCU.

For simple arrangements where the accelerometer is near the MCU that makes no difference. However the analog one is more susceptible to noise. With longer wires / traces between the accelerometer and the MCU you can get less accurate results with an analog one since it picks up noise which you are then sampling and including in your results.

The digital one is more immune to that kind of interference - instead it is susceptible to digital noise - corruption of the data as it traverses long wires. But that is less of a problem since it takes far more induced voltage to corrupt a digital signal than an analog one.

One other main difference is that you are limited to the ADC that is in the digital accelerometer. If you want a different resolution you have to use a different accelerometer. With analog, since it has no inherent resolution, you sample at the resolution of your MCU's ADC.

Digital is also easier to interface in modern systems. Many SoCs don't have analog inputs. So adding an analog accelerometer would mean adding an ADC chip as well - and you don't really want to do that in something like a mobile phone.

So in summary:

* Digital is the most convenient, reliable and suitable for current basic uses
* Analog is more of a niche product that is rarely used in consumer electronics

# Answer
> 0 votes
The ADXL326 is only an accelerometer.
When you have one, you can measure the output of the sensor with a oscilloscope. For the final project a digital sensor is preferred as @Majenko has explained in his answer.

The MPU-9250 is an accelerometer, gyro and magnetometer. That makes it possible to use sensor fusion (combining the sensors with software calculations for a much improved result).

Are there vibrations involved? An accelerometer is sensitive for vibrations. I doubt if an accelerometer can be used to measure the suspension motion.

By the way, I'm ignoring the MPU-6050 and so should you. The MPU-9250 is less noisy.

---
Tags: arduino-due, accelerometer, digital
---