# Question
Title: OLED (I2C) and Micro SD card module not working together in Arduino
I am trying to write some data to SD card and read it back to serial monitor as well as display it to the OLED.

Both the sd card and oled work separately but they seem to be interfering with each other when combined. I have used Arduino SD and Adafruit OLED libraries.

Connections from Arduino Uno to Micro SD card module-

```
5V to SD VCC
GND TO SD GND
PIN 10 TO SD Chip Select
PIN 11 TO SD MOSI
PIN 12 TO SD MISO
PIN 13 TO SD SCK

```

Connections to OLED-

```
3.3V to OLED VCC
GND TO OLED GND
A4 TO OLED SDA
A5 TO OLED SCK

```

Here is the code -

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

File myFile;

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>

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

// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET     -1
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  while(!Serial) {
    ;
  }

  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // CODE GETS STUCK HERE. DISPLAY NEVER INITIALISES
  }
  display.clearDisplay();
  display.setTextSize(1);
  display.setTextColor(WHITE);
  display.setCursor(29,29);
  display.print("INITIALISING");
  display.display();
  delay(5000);

  if (!SD.begin(10)) {
    Serial.println("initialization failed!");
    while (1);
  }
  Serial.println("initialization done.");

  myFile = SD.open("test.txt", FILE_WRITE);

  if (myFile) {
    Serial.print("Writing to test.txt...");
    myFile.println("testing 1, 2, 3.");
    // close the file:
    myFile.close();
    Serial.println("done.");
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }

  display.clearDisplay();

  myFile = SD.open("test.txt");
  if (myFile) {
    Serial.println("test.txt:");
    while (myFile.available()) {
      Serial.write(myFile.read());
      display.setCursor(0,0);
      display.print(myFile.read());
      display.display();
      delay(5000);
    }
    // close the file:
    myFile.close();
  } else {
    // if the file didn't open, print an error:
    Serial.println("error opening test.txt");
  }
}

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

}

```

Code gets stuck at OLED initialization as mentiontioned above. If I replace these lines-

```
if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    Serial.println(F("SSD1306 allocation failed"));
    for(;;); // CODE GETS STUCK HERE. DISPLAY NEVER INITIALISES
    }

```

To this-

```
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);

```

I have run I2C scanner code on OLED so the address "0X3C" is correct.

The OLED still doesn't work and SD card initialises but arduino is writing wrong data to TXT file on SD card like this-

```
teóting 1,à2, ó®

```

Instead of -

```
testing 1, 2, 3.

```

I have also tried using U8G2 library's sketches with SD card in case Arduino was running out of RAM but it still doesn't work. I have also changed SD chip select to Arduino digital pin 4 but still same results.

On browsing and experimenting more,I found MISO OR MOSI PIN of SD maybe interfering with SDA/SCL pins of OLED. Maybe wiring needs to change.

**ANY SUGGESTIONS???**

# Answer
> 1 votes
A pullup resistor is needed for I2C, and adding them might fix some errors.

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


# Question
Title: Determining which raw IR code to use for AC
I'm new on this so go easy on me.

I'm trying to make an IR blaster to control my TV and ACs. I realized that when I capture the IR code, power button/temp up and down/mode send raw codes that are almost similar to each other.

I've searched the net(maybe missed some answers) and came through this. The raw IR code provided on the blog did turned on my AC but I wasn't able to turn it off. So I think that the code isn't the power button. That's because I remember leaving the AC off at 23°C and when I send that code, my AC started at 20°C.

So, how do I know which code to use for off, temp up etc? The codes I captured seems not to work when I send the codes to the AC. Nothing happened. No beep or anything. I'm using a GREE AC by the way.

Here's an example of the raw code that turned on my AC:

```
uint16_t irACon1[139] = {9050, 4500, 800, 1600, 750, 550, 700, 550, 700, 1600, 750, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1600, 750, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1600, 750, 1600, 750, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1600, 750, 550, 700, 1600, 750, 550, 700, 550, 700, 1600, 750, 550, 700, 19950, 750, 500, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1600, 750, 550, 700, 550, 750, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 550, 700, 1550, 800, 550, 750, 500, 700, 1600, 750};

```

And few other codes that I had captured:

```
Raw: (139) 9068, -4404, 708, -1580, 712, -488, 712, -484, 712, -1580, 712, -1580, 708, -1580, 712, -488, 708, -488, 708, -1584, 708, -1584, 708, -1580, 708, -492, 708, -488, 704, -496, 704, -492, 708, -492, 708, -492, 704, -492, 708, -492, 708, -488, 712, -488, 712, -1580, 708, -1580, 712, -488, 712, -484, 712, -488, 712, -488, 712, -484, 712, -1580, 712, -484, 712, -1580, 712, -484, 716, -484, 712, -1580, 712, -484, 712, -19848, 684, -512, 704, -496, 708, -492, 708, -488, 708, -492, 708, -488, 712, -488, 712, -488, 708, -488, 712, -488, 712, -484, 712, -488, 712, -488, 708, -1580, 712, -488, 712, -484, 712, -488, 708, -488, 712, -488, 712, -488, 708, -488, 712, -488, 708, -488, 712, -488, 712, -488, 708, -488, 712, -488, 708, -492, 708, -488, 708, -492, 708, -1584, 704, -1584, 708,

Raw: (139) 8988, -4540, 556, -1736, 564, -688, 520, -676, 524, -652, 548, -1688, 600, -1688, 604, -648, 548, -652, 548, -1688, 604, -1684, 604, -1688, 604, -648, 548, -652, 548, -648, 548, -652, 548, -652, 548, -648, 548, -652, 548, -652, 548, -648, 548, -676, 524, -1688, 600, -1688, 604, -676, 520, -676, 524, -676, 524, -672, 524, -676, 524, -1712, 576, -680, 520, -1688, 604, -756, 440, -788, 412, -1688, 600, -816, 384, -20092, 468, -840, 348, -848, 352, -848, 352, -820, 384, -812, 388, -788, 412, -784, 412, -784, 416, -760, 440, -760, 436, -760, 440, -756, 444, -756, 440, -1824, 468, -780, 416, -760, 440, -756, 444, -728, 468, -732, 468, -728, 472, -700, 496, -704, 496, -700, 496, -676, 524, -676, 520, -652, 548, -648, 552, -624, 572, -624, 576, -620, 580, -1740, 548, -620, 580,

```

PS: Sorry for my bad English. And I somehow feel that the title isn't specific so let me know if there's a better title I should put.

**UDPATE**: Now the off and temp up is working but the temp is somewhat like an on button. It instantly put my AC on 23°C and won't increase when pressed multiple time. I understand that AC's remote fires the whole setup string when a button is pressed so which means different temps has different codes?

# Answer
It appears from the data you've posted, the remote is holding the presets for what the A/C unit needs to be doing when after every button is pressed. This will keep the remote with LCD disply? in Sync with the A/C master.

Ie. The remote is sending an entire setup string EVERY time ANY button is pressed.

Can you post a capture of an ON and OFF Raw's only? Do not press any other buttons after pressing ON, or before pressing OFF.
> 1 votes

---
Tags: esp8266, ir
---


# Question
Title: How to use any module that has no library for arduino?
I am 2 years old in this Arduino world. I am currently working on a project where I am about to make use of a fingerprint sensor. Now my question is that could we be able to make use of a sensor that we usually find in our mobile phones with ATmega328p microcontroller chip. And what if that there were no libraries written for Arduino so that will make my life easier. And I wonder how these tech companies make use of any sensor they would like to use without any trouble while there is no existing textbook that taught these employees while pursuing a degree in CSE or ECE about how to write code for a particular sensor. Now I know that there are certain protocols like SPI, I2C, UART, etc. But how do they do it, and how do they know about microcontrollers and IC's that were never taught to them in any degree or course? I always scratch my head while looking at the consumer electronics, and the IC's and Chips that they have on their PCB board were never found on google, And by chance, if an IC or microcontroller is found then I barely understand the datasheet or the documentation which was written in Chinese or some other language. I hope someone could help me understand how all this happens.

# Answer
> 3 votes
About the fingerprint sensors from mobile phones: You might find the answers to this question useful. They explain in detail, why it is not really worth the effort to try interfacing such a fingerprint sensor with Arduino.

> How to use any module that has no library for arduino?

You need to read the datasheet of the module. It should explain in detail, how the module is used. When you understood, how it works, (and understanding it is really really important) you can start implementing it in code, for example by writing your own library. A library is just a wrapper around the interfacing code for that module. If the module uses common used interfaces or is even a commonly used component, you can often stand on the shoulders of giants by making use of other libraries in your library (for example using the Wire library in a library for a specific I2C sensor). That makes it easier.

> But how do they do it, and how do they know about microcontrollers and IC's that were never taught to them in any degree or course?

The engineers don't get taught to use specific controllers or ICs. They get taught the fundamental principles, including common interfaces like I2C, SPI, UART, I2S ... . In the end it all comes down to the datasheet of a component. It should explain all details, that are needed to use the component correctly, or at least reference to further documents. For example most microcontroller datasheets directly explain, how I2C is implemented in these microcontrollers. You can use that to implement I2C communication, even without a preexisting library. Yes, that can be a tedious and complex task, but it is totally possible. Keep in mind, that most Arduino libraries are not written by the manufacturer of the used component, but by third party people (sometimes the community, sometimes resellers like Adafruit, e.g.).

I would say "it is not rocket sience", but yes, it can be rather difficult to dig into the very detail of interfacing a component. Without considering myself an especially smart guy, I'm writing a library for multi-master I2C communication on Attiny's (without having any degree in that field). I could start with code from others, which made the entry easier. But it also involves much time, to dig into it, write the code and test it correctly. It is difficult, but it is possible.

> And by chance, if an IC or microcontroller is found then I barely understand the datasheet or the documentation which was written in Chinese or some other language.

Good manufacturers and resellers provide a datasheet in english for their products. That cannot be said for every product, that you can purchase. Writing documentation takes time and thus costs money. Chips directly from China (where most electronics is produced these days) might have less good or no documentation at all, though these chips are often way cheaper. As a hobbyist you should stick to the good documentated components, if you don't want to really dig into it.

> the IC's and Chips that they have on their PCB board were never found on google

PCB designs are only found in the internet, if they are published under some open source license (or if they were illegally leaked by someone). If a company doesn't want to publish it's product designs, that is totally ok.

About the components in consumer electronics: I think you refer to that the chips often don't have a googleable product number/marking to find a datasheet. That is because often these chips are custom chips, made maybe only for this company or even this specific product. Why would they want to publish a datasheet for it? They are not meant for public use for all. The design of components is often a good kept secret, that the companies are not willing to share, since it generates their revenue.

Hobbyists and small companies use publicly available, good and publicly documented parts to make their life and investment in the project easier. Big companies can easily hire people to design a custom chip, that will only contain the needed features. (With mass produced products you can save money this way, by not always needing to buy even the unused resources of a standard controller). Another reason to use a custom (maybe even a not programmable) chip is to keep the code in it secret.

---

All in all keep in mind, that the hobbyist world of Arduino and the world of consumer electronics like smart phones are rather different. Sure, they rely on the same principles, but the way, how things are done and created, is very different.

---
Tags: programming, sensors, uart, isp, icsp
---


# Question
Title: Random characters transmitted from ESP8266 to Arduino
Below is the code for getting a value from Firebase and sending the received data to arduino for performing necessary action. The code here here sends a string `"o"` to arduino once

```
//uploaded to ESP8266
.
.
.
if (cu_st == "c")
  {
    sent = 0;
  }
  cu_st = Firebase.getString("feeder");
   if (cu_st == "o")
   {
    Serial.println("\t\trecd req to feed");
    if(sent == 0)
    {
      esp.print("o");
      sent =1;
      cu_st = "c";
      Serial.println("setting feeder to close in firebase");
      Firebase.setString("feeder" ,"c");

   }
.
.
.

```

Below is the code that gets the value, carries out necessary actions.

```
//uploaded to arduino
.
.
.
void feed_cmd()
{
  while(ArduinoUno.available())
  {
    char valve = ArduinoUno.read();
    Serial.print("feeder cmd recd ");
    Serial.println(valve);
    if(valve=='o')
    {
       digitalWrite(led, HIGH);
       //feeder.write(0); //open position
       open_time = millis();
       feeder = 1 ;
       Serial.println("I am opening feeder");
    }
  }
}

void close_feed()
{

  if(feeder == 1)
  {
   close_time = millis();
   if(close_time - open_time > 5000)
  {
    feeder = 0;
    digitalWrite(led , LOW);
    Serial.println("I am closing feeder") ;
  }
  }
}
.
.
.

```

My expectation/understanding is that:

`feed_cmd()` continually checks for any data As soon as it receives data LED turns ON and after 5 sec `close_feed()` turns OFF the LED.

But what happens is that the `while()` in `feed_cmd()` continually executes showing some random data and also all of what I said above is also being carried out! (pic attached)

Why is there random serial data, even after sending only once and even after reading the sent data?

Is it bad coding / hardware?

Thanks for reading through and would really appreciate it if you can help me sort it out!!

**Edit** I found this link smthg abt pin voltages when I was looking for possible explanation for my code's behaviour, If somebody can simplify it and explain it, it'd be better !!

# Answer
The baud rates, voltages, and timing all have to match up for serial communication to work right.

So, set both of your devices to the same baudrate (you specify the number in Serial.begin()), and ensure they're connected properly. (voltages match, TX to RX, and ground is connected)

You can just read/print the serial input to the arduino with something like Serial.print(softSerial.read()) in your code if you think you don't have serial wired up right.

Also in an unrelated issue; the esp32 spits out data on its main serial line at 115200 when it boots up which you can not disable. you can use the serial port afterwards though.

Here's a copy of what gets printed out on one of mine;

```
rst:0x1 (POWERON_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:1
load:0x3fff0018,len:4
load:0x3fff001c,len:1044
load:0x40078000,len:8896
load:0x40080400,len:5816
entry 0x400806ac

```
> 1 votes

---
Tags: arduino-uno, serial, esp8266, iot, software
---


# Question
Title: No headers (.h) found in Documents\Arduino\libraries\arduino_144469 with demo code
I followed this tutorial for a demo code for the SR04 ultrasonic distance sensor (without the LCD display). I've installed the Arduino IDE and wrote the code in it and saved it in some location. Compilation of the code is successful. However when I try to upload the code, I get the message:

```
Invalid library found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469: no headers files (.h) found in C:\Users\Dame\Documents\Arduino\libraries\arduino_144469

```

There are no header files in the directory and I'm wondering if I need to download additional header files or if I should configure something else.

# Answer
If the folder is not needed then delete it.

The Arduino IDE uses the folders in the `library` folder to search for library header files (ie. `.h` files). It expects one library in each folder. When it see's a folder without any header files in it, it will count this as an invalid library.
> 2 votes

# Answer
i had similar problem and I Fix it by changing in preferences field Sketchbook location to different drive (from c:\ to d:).

This problem can ocure on system windows 10 (probably also 8) where you have sequred drive with system installed to protect you data (or system files) against some unwanted changes. Probably there is missing in Arduino some rights to make directory and save files in temporary directories, but i'm not an expert.
> -1 votes

---
Tags: arduino-uno, arduino-ide, uploading, hc-sr04
---


# Question
Title: How to calculate the RZERO value in MQ135 sensor, I have already burned it for 24 hours?
I've already burned it for 24 hours and it is now giving the constant value of 932.36,pls tell me how to calculate the RZERO value.

# Answer
> 1 votes
From the datasheet here ---\>MQ135 datasheet, It is the value of Sensing resistor at 100 PPM of Ammonia(NH3) or from the graph in Fig. 3, you can use gases that has y intercept as 1 and appropriate concentration, i.e you need atleast some known parameter to get it. The legend in the graph is also not clear (as far as getting the values from the Log - Log graph, there are tutorials in youtube).

I'm also in need of solution to this, so far this is what I read on the internet... You need a chemistry lab to do it !!!

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


# Question
Title: How to find the peak value of analog signal?
I have a question .. Please help me I don't know how Arduino can read the peak value of the sensor signal. The value I want is in the ADC value .. What I want is ... for 5 seconds there will be 1 average value from the highest peak value of the sensor, and the ADC value. I will use pin A0, but I don't know how to code the program that I want. Please help me What is the code?

# Answer
See if I understand this correctly: For a given time period you want to find the peak.

```
void setup()
{
  unsigned long int cur_time = 0 ;
  unsigned long int time_elapsed = 0;
  int peaks[20]; // say you want to find 20 peaks , 1 peak for data arriving between 5 secs
  int time_period = 5000;
  int data = 0;
  int mx=0;
}

void loop()
{
   for(int i = 0 ; i<20;i++)
   {
      cur_time = millis();
      while(cur_time - time_elapsed <=time_period)
      {
             if(mx==0)
              { mx = analogRead(A0); }
              else:
               {  data = analogread(A0);
                  mx = max(data , mx);
               }
              cur_time = millis();
        }
         time_elapsed = cur_time;
         peaks[i] = mx;
         mx = 0;
        }
  }

```

Hope this helps!!
> 0 votes

---
Tags: arduino-uno, programming, adc, analog
---


# Question
Title: Why doesn't pin 19 work when powering the EzSBC Esp32 board from batteries?
I recently got an ESP32-01 Breakout and Development Board from EzSBC.com. It is advertised as a board specifically designed for use with batteries because of it's low current draw when in sleep.

As a test I loaded the basic Arduino `blink` sketch onto the board using pin 19 as the built in test LED. When I power the board from the computer through the USB connection the LED blinks as expected, but when I connect a battery accross VIN -\> GND nothing happens.

What am I doing wrong?

# Answer
> 1 votes
There is a subtle design choice in this board that took be hours to figure out.

According the connection schematic the blue leg of the LS3528RGB LED is connected to `IO19` through a 1k resister (`R2-1`). However the power leg is connected to `Vusb` *not* `3.3V` like the other RGB LED. This means that the LED connected to IO19 is only usable when the board is connected through the micro-USB port and not when connected directly to battery.

This can be useful for programmatically reading whether the board is running on battery or USB.

---
Tags: power, esp32, battery
---


title: Why ESP8266 slower than Arduino nano?

text:
# Question
Title: Why ESP8266 slower than Arduino nano?
I'm using the same script(and standard wire and serial library only) one uploaded to Arduino nano one uploaded to ESP8266. However, despite ESP8266 running at 160MHz, 10 times faster than nano, it's taking 3.5 ms to complete the loop, compare to 2.5 ms than that of nano.

How could that be? why ESP8266 was slower?

# Answer
> However, despite ESP8266 running at 160MHz, 10 times faster than nano, it's taking 3.5 ms to complete the loop, compare to 2.5 ms than that of nano.

There's a number of reasons for that. Chiefly:

1. The ESP8266 has no I2C hardware, so has to use software "bit-banging" to emulate I2C. That is slower to execute.
2. The ESP8266 also has to manage the WiFi hardware which takes a portion of the processing power away from the user

The result is slower execution for I2C operations and "jitter" added to timings of loops and such.

> will the same thing (wire) happen to esp32?

No (or not as much). The ESP32 has hardware I2C so it doesn't need to use bit-banging to emulate it, so it will be faster. Also it is dual core and one core is used for "system management" including managing the WiFi and Bluetooth, while the second core is used to execute your sketch, so there is no (or little1) interruption by the WiFi slowing down your sketch.

---

1: Two cores accessing the same area of RAM causes some contention as only one core can access the same block of RAM at a time, so it's not perfect. You may still get slight delays, but they will be minuscule compared to the processing needed for the ESP8266's WiFi code.
> 3 votes

---
Tags: esp8266, oscillator-clock, speed
---


# Question
Title: loop() either stops working, or lcd stops working | buttons don't work
I'm using a Let's Start Coding Ultimate Kit 1 (it was a christmas present, don't ask) and I'm trying to use this as a typing sort of thing. I haven't implemented the actual letters though.

```
#include <MakerScreenXVI.h>;

MakerScreenXVI lcd;

int currentNumber = 1;
int ms = 0;
int totalMS = 0;
bool first = false;

void setup() {
  // put your setup code here, to run once:
  pinMode(A0, INPUT);
  pinMode(A3, INPUT);

  lcd.begin();
  lcd.print("Success");
  lcd.setCursor(0,1);
  lcd.print(currentNumber);

}

void loop() {
  delay(200);
  changeNumber();
  delay(200);
}

void clearLCDLine(int line) {
        lcd.setCursor(0,line);
        for(int n = 0; n < 16; n++) // 20 indicates symbols in line. For 2x16 LCD write - 16
        {
                lcd.print(" ");
        }
}

void changeNumber() {
  if (digitalRead(A0) == LOW) {
    if (first == false) {
      clearLCDLine(1);
      first = true;
    } else {
      first = false;
    }
    currentNumber++;
    if (currentNumber == 27) {currentNumber = 1;}

    lcd.print(currentNumber);
  } else if (digitalRead(A3) == LOW) {
    currentNumber = currentNumber - 1;
    if (currentNumber == 0) {currentNumber = 26;}
    //clearLCDLine(1);
    lcd.print(currentNumber);
  }
}

```

For some reason, after it deletes the 1, it stops. Nothing is printed onto the screen, and nothing is cleared from it. How can I fix this? Also, the buttons always return the `LOW` value. How can I fix this?

# Answer
The buttons will send a LOW signal when pressed if they are set with pinMode INPUT\_PULLUP.

The issue with currentNumber not displaying is that after you clear the screen with the 'for' loop, you need to reset the cursor to position 0,1 with `lcd.setCursor(0,1);` . Otherwise, the numbers are printing out of view.

If I add `lcd.setCursor(0,1);` just above each line with `lcd.print(currentNumber);` , I think the code has the behavior you're looking for.

**Edit from the person who asked the question:**
You also have to add a delay of around 150-200, or else one push will count as many.
> 0 votes

---
Tags: lcd
---


# Question
Title: avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00
So I try to compile and upload a simple code such as the Basic Blink. I have not connected it to pin 0 or pin 1.

There is an LED with the "L" label on the card that works. So I guess not the chip is damaged?

I have selected the correct model which is Arduino Uno / Genuino. I've checked the drivers several times now, even reinstalled Arduino Software twice and tried on 2 different computers.

5V works with ground, I can get the LED to light up. But I cannot compile / upload code.

```
Error MSG: avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
(this message repeats 10 times with attempts)

```

I read something about bootloader, but I have no idea how to do this / what it is. I do not have the right components for bootloading I guess.

Also the COM is correct. I've tried using all the listed COMs without any result. Is this a hardware issue? Is my chip grilled or something?

# Answer
You should re-burn the bootloader. If you have another uno, you can burn bootloader here
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: i am having Strange issues when trying to read form gps serial connection
I have an Adafruit Ultimate GPS connected to a MEGA2560. I am trying to get the data from the buffer and do other data processing at the same time, however. when i allow other processing to be done the output becomes garbled such as below. the first out is correct and then becomes garbled and outputs now useful data.

16:34:54.466 -\> $GPGGA,163453.155,,,,,0,00,,,M,,M,,\*7F

16:34:57.111 -\> $GPRMC,163453.155,V,,,,$GP$GPGGA,1$GPGGA,$GPGGA

```

    void loop()
    {

    GetTotalPressure();
      char c = GPS.read();
      Serial.print(c);
       if (GPS.newNMEAreceived()) {

        if (!GPS.parse(GPS.lastNMEA()))   // this also sets the newNMEAreceived() flag to false
          return;  // we can fail to parse a sentence in which case we should just wait for another
      }
      if (timer2 > millis())  timer2 = millis();

      if (millis() - timer2 > 1000) {
        timer2 = millis(); // reset the timer
    GPSScreenUpdate();
      SDcardSave();

      }

```

When GetTotalPressue is commented out The GPS serial output is correct when it is no the error above happens.

GetTotalPressure is below the sensor is connected to a I2C bus

```
void GetTotalPressure() {
  Totalpressure = ms5611.readPressure();

```

Many Thanks

# Answer
You are not reading the GPS often enough. The method `Adafruit_GPS::read()` is documented in the comments embedded in the source code:

> Read one character from the GPS device.
>
> Call very frequently and multiple times per opportunity or the buffer may overflow if there are frequent NMEA sentences. An 82 character NMEA sentence 10 times per second will require 820 calls per second, and once a loop() may not be enough. Check for newNMEAreceived() after at least every 10 calls, or you may miss some short sentences.
>
> returns: The character that we received, or 0 if nothing was available

Accessing the I2C bus makes `loop()` slower, slow enough that you get a buffer overflow, as explained above. I suggest that, instead of reading a single character per loop iteration, you read as many as are present in the buffer:

```
void loop()
{
    GetTotalPressure();

    // Empty the GPS port receive buffer.
    while (GPS.available()) {
        char c = GPS.read();
        Serial.print(c);
    }

    // Parse any newly received NMEA sentence.
    if (GPS.newNMEAreceived()) {  // clears the newNMEAreceived flag
        if (!GPS.parse(GPS.lastNMEA()))
            return;
    }

    // Display and log location every second.
    if (millis() - timer2 > 1000) {
        timer2 = millis(); // reset the timer
        GPSScreenUpdate();
        SDcardSave();
    }
}

```

As an aside, I removed the line

```
if (timer2 > millis()) timer2 = millis();

```

which serves no useful purpose. If you are trying to detect `millis()` overflows, you are almost certainly doing something wrong.
> 1 votes

---
Tags: serial, arduino-mega, i2c, adafruit, serial-data
---


title: Reading 4-20ma signal on arduino

text:
# Question
Title: Reading 4-20ma signal on arduino
I want to read a 4-20 mA analog signal from a 24V flowmeter. I've read the simplest way is to convert it into 1-5V signal using a 250 ohm resistor. The thing is I want my reading to be precise so my question is; is there any resolution loss when converting it to 1-5V?

I've also looked up on current to voltage converting boards similar to this one: https://www.sparkfun.com/products/14544

but I don't think they can detect 4mA signal.

I am a beginner in this so need some guidance here.

# Answer
Using a resistor is the "Normal" way, yes. 250Ω will give you 1-5V, yes, which means that you get 4/5 of the actual resolution of the ADC at your disposal.

That means instead of 0-1023 you're actually reading 204-1023, or 819 possible values. Spread over 16ma (or 4V, which are the same thing) that gives you about 20µA resolution.

If you really really care about that extra 1/5 of the resolution you can instead use a 300Ω resistor to give you 1.2 to 6V, then pass that through a subtracting amplifier (see this post) and subtract 1.1V from it (you need to create that 1.1V, of course). That will give you 0.1 to 4.9V, which then covers more of the ADC's available range (20-1002, or about 16µA resolution).

Is it worth it? Probably not. Any increase in resolution will likely be swamped by the inaccuracy of the resistor and potential drift though self heating.
> 2 votes

---
Tags: arduino-uno, arduino-mega, adc, analogreadresolution
---


# Question
Title: How to use tinygps.h library to measure distance? using NEO6mv2
any reference site for the format code for tinygps.h to measure distance? or any codes for tinygps.h for measuring distance i'm just a beginner in learning arduino thank you

# Answer
> 1 votes
You don't use the `tinygps.h` library to measure distance. You use the `tinygps.h` library to get coordinates. Over short distances those coordinates (longitude and latitude) can be equated to x,y coordinates on a plane (over greater distance - hundreds or thousands of miles - it gets a whole lot more complex).

Two sets of x,y coordinates form a line. A line is one side of a right-angled triangle (the hypotenuse).

Pythagoras (remember him from math class? That rubbish you thought you'd never need? Well, now you do...) says that the square of the hypotenuse is equal to the sum of the squares of the other two sides.

You know the other two sides - they're just the difference between the two x coordinates and the two y coordinates.

We're not going to write the code for you, and Google is probably better at finding websites with example code on than we are.

---
Tags: arduino-uno, tinygps
---


# Question
Title: Wire multiple SW-420 Vibration sensors to a single pin
I am working on installing an alarm system using Konnected IO on a NodeMCU esp8266. I have multiple bay widows which will use 4 SW-420 vibration sensors. I would like to wire all 4 of the SW-420 vibration sensors to a single pin. When any of the 4 sensors detect vibration the pin will go to high. I attempted to simply wire the d-outs from all four together and all four sensors stoped working. I'm out of ideas on how to do this any help would be greatly appreciated. I believe sensors send out a low signal when no vibration is detected and high signal when vibration is detected. Link to sensors: https://www.amazon.com/XLX-Vibration-Normally-Sensitive-High-Efficient/dp/B07V8FJRN1/

# Answer
> 0 votes
Two ideas came to my mind, first is to connect each output to four digital pins and then do something like this:

```
if(digitalRead(pinOne) == HIGH || digitalRead(pinTwo) == HIGH || ...){
do something
}

```

Or you can use an opamp or comparator for that purpose:

simulate this circuit – Schematic created using CircuitLab

In above configuration if any of the sensors output is HIGH, op amp will drag it's output to the positive rail (~5V). otherwise output is LOW (~0 V).

---
Tags: arduino-uno, nodemcu
---


# Question
Title: Is it permissible to connect 3.3V powered devices to the 5V I2C bus?
I have several devices on the I2C bus:

1. RTC DS3231SN
2. TMP100 temperature sensor
3. EEPROM 24LC256

All devices are powered by 3.3V. The voltage on the I2C bus is 5V.

**Question:** Is the voltage difference on the bus and device power normal?

# Answer
> 1 votes
There are 3.3V devices that have 5V-tolerant inputs; that may be the case for your devices, but I would not risk it. Use a level converter designed for I2C, such as https://www.adafruit.com/product/757. Or you can make your own; https://cdn-shop.adafruit.com/datasheets/an97055.pdf explains how such a level converter works. Use a BSS138 if you are comfortable with soldering SMT components; otherwise use a 2N7000.

---
Tags: i2c
---


# Question
Title: How can I make a Parallax Servomotor move a water tap correctly and prevent from vibrations?
I am using Arduino Mega 2560

I have built an structure with plastic 3D pieces to move this water tap.:

I am using the "Servomotor Parallax Inc 140 mA, 4 6 V" to rotate the tap:

Some more images to show how I mounted it:

Video 1. I tried to use the power of the arduino directly (5V). But the motor is not steady in all the positions I set, in some positions the noise you hear in the video do not stop, and my impression is that the motor will burn soon because it keeps pusshing all the time.

Video 2. Without almost any load, the motor is also making a small sound. I don't know if you can appreciate it in the video. They are like cracks or clicks

Possible solutions:

* Is there a way to cut the power supply when the motor already moved the tap? Or just to stop the motor to keep pushing?
* Using a external power should solve the problem? I found this tutorial where they use that system. Which will be the benefits of that? It will fix the problem?
* Using another stronger servomotor?
* A stepper motor?
* Is my servomotor faulty?
* Would I need some controller?

Any other suggestion?

# Answer
When you set a servo motor to be in a specific position it is constantly and actively striving to keep in that position. The feedback from the internal potentiometer is constantly being processed and the motor adjusted to ensure that it remains at the right position. Potentiometers, of course, aren't 100% perfect, and there will always be a certain amount of "noise" in the signal that means the motor will always be making really tiny adjustments.

That's perfectly normal.

The simple way to stop it trying to keep precisely to one position is to stop telling it to be in that position.

1. `.attach()` the motor
2. Move it to the desired position
3. Wait long enough for the motor to get to that position
4. `.detach()` the motor

When you call `servo.detach()` the PWM signal is terminated and the motor no longer has a position to keep to - so it just stops doing anything and goes to sleep.

The down-side of this is that if you have a load under tension (for example if you are lifting a weight with the servo) the tension is then free to move the motor.
> 2 votes

---
Tags: motor, servo, atmega2560
---


# Question
Title: Does flashing ESP8266/ESP-01 firmware mean uploading a new 'sketch' and why different firmware?
Hi I am new to IOT and I am now in love with this. However I'm a little confused right now with the jargon. My question is similar to this. But I do have some extra questions though.

1. When using ESP as standalone microcontroller, and if I uploaded a sketch written on the Arduino IDE, does that count as 'Arduino firmware' other people are referring to?
2. On the Arduino IDE, uploading sketches onto the ESP8266 seems easy by just installing extra libraries from Board Manager and selecting the right board. Is this step equivalent of doing this but for different firmwares such as AT, NodeMCU and Micropython?
3. For the NodeMCU dev boards, is the default firmware on the module NodeMCU firmware? If I were to use the Arduino IDE to upload a sketch, does that mean I have overwritten the NodeMCU firmware with my custom 'Arduino firmware' sketch?
4. To the extent of my knowledge, when using NodeMCU firmware, I would need to code in LUA language using some sort of LUA IDE and if I flashed/uploaded micropython I would need to code in micropython using exclusively the Thonny IDE. And there is no way to code in micropy or LUA from the Arduino IDE.
5. Is the reason for using other firmware is because of how the code is compiled and the language used?

If someone could clear things up for me I would greatly appreciate it. Thanks!

# Answer
> 0 votes
> When using ESP as standalone microcontroller, and if I uploaded a sketch written on the Arduino IDE, does that count as 'Arduino firmware' other people are referring to?

Yes. "Firmware" is application code running on the microcontroller.

> On the Arduino IDE, uploading sketches onto the ESP8266 seems easy by just installing extra libraries from Board Manager and selecting the right board. Is this step equivalent of doing this but for different firmwares such as AT, NodeMCU and Micropython?

Yes. "Firmware" is application code running on the microcontroller.

> For the NodeMCU dev boards, is the default firmware on the module NodeMCU firmware? If I were to use the Arduino IDE to upload a sketch, does that mean I have overwritten the NodeMCU firmware with my custom 'Arduino firmware' sketch?

Yes. "Firmware" is application code running on the microcontroller.

> To the extent of my knowledge, when using NodeMCU firmware, I would need to code in LUA language using some sort of LUA IDE and if I flashed/uploaded micropython I would need to code in micropython using exclusively the Thonny IDE. And there is no way to code in micropy or LUA from the Arduino IDE.

No. The Arduino IDE is for coding in C++ with the Arduino API extensions.

> Is the reason for using other firmware is because of how the code is compiled and the language used?

The firmware is just what runs on the chip. If that firmware provides its own programming language then you can use that to execute that programming language.

If you write your own firmware in the Arduino IDE then the chip runs that firmware. If you upload the AT firmware then the chip runs the AT firmware and you can control it with AT commands. If you upload the NodeMCU Lua firmware then the chip runs the NodeMCU Lua firmware and you control it using Lua commands and scripts.

---
Tags: esp8266, arduino-ide, nodemcu
---


# Question
Title: Does Keyboard.begin() and Keyboard.end() make my code slower?
I'm making an IR Macro keyboard, and about 10% of the code is dedicated to the `Keyboard` commands, would having `Keyboard.begin()` and `Keyboard.end()` in the method responsible for typing make any difference to the speed or size? My code:

```
void decodeCode(){ // send the macros.
  int pos = 0;
  for(int i = 0; i<output.length(); i++){
    if(output.charAt(i) == '$' && i!=output.length()-1){ //the $ is a symbol for "$pecial" characters
      i++;
      specialDecodeChar(output.charAt(i));
    }
    else if(output.charAt(i) == '%'){
      Keyboard.releaseAll();
    }
    else{
      Keyboard.press(output.charAt(i));
    }
  }
  Keyboard.releaseAll();
}

```

I currently have `Keyboard.begin()` in `setup()`.

# Answer
> 0 votes
The `Keyboard::begin()` and `Keyboard::end()` functions, if you actually look at the code are empty functions. They do nothing.

In theory the compiler should just optimise them out.

---
Tags: usb, arduino-leonardo, keyboard
---


# Question
Title: Why does per-led current consumption diminishes when more leds are on?
I'm rather new to Arduino. I've been performing some current consumption measurements lately, with a INA219 current sensor, on the blue LEDs from a starter kit.

I plugged three LEDs, on pins 2, 3, and 4 of my Arduino UNO, and wrote a simple script:

```
digitalWrite(led1, 1);
delay(2000);
digitalWrite(led2, 1);
delay(2000);
digitalWrite(led3, 1);
delay(2000);
digitalWrite(led1, 0);
digitalWrite(led2, 0);
digitalWrite(led3, 0);

```

Which turns on the leds one by one, and finally turn them off at once. I measured the current consumption of the first LED, and measured that:

* When it's the only one on, LED 1 consumes ~23.5 mA
* When the second one is on, LED 1 consumes ~21.7 mA
* When the third one is on, LED 1 consumes ~20.2 mA

Could you please tell me why it behaves that way ? Is there any source I should read that would formalize that ?

Thank you

# Answer
If using a constant voltage source it is advisable to use current limiting resistors in series with LEDs.

If these LEDs are different colors that may explain the different current readings.

Or, if all LEDs are of the same color and you are powering the project from a source with internal resistance (a battery), the more current you draw the lower the supply voltage. This may show up as a reduced incremental current increase.

Or, if using a poor power source or operating at the current capacity of the power supply - again - this may show up as a reduced incremental current increase.

Note that different generations of LEDs operate at slightly different voltages. But, in general, RED, GREEN & BLUE LEDs of the same generation operate at slightly increasing voltages respectively. Details can be found here in this wikipedia.com page:

> Typically, the forward voltage of an LED is between 1.8 and 3.3 volts. It varies by the color of the LED. A red LED typically drops 1.8 volts, but since both voltage drop and light frequency increase with band gap, a blue LED may drop from 3 to 3.3 volts.

Use the LED current (Iled) and voltage (Vled) specifications to determine the proper resistor value for a given supply voltage (Vbatt).

The following equation from this article should prove useful for this calculation:
> 1 votes

---
Tags: arduino-uno, led, current
---


title: SD Card and Lora module arduino uno

text:
# Question
Title: SD Card and Lora module arduino uno
Background: When working on the 2 modules separately they were working perfectly.

Problem: In the code attached we tried integrating them but Lora wouldn't receive any data unless we commented out parts of the SDC function. Is there a fix to this?

This is where the problem occurs:

```
Serial.print("Data received: ");
 Serial.print(received);

 if(received=="ANEMO"){

```

No matter how much we feed it with TRUE data from another Lora with these codes it simply shows blank and false.

Please Help this poor lamb. This for our school project. Hopefully, you can spare me some of your time. Thank you so much in advance.

for the CS pins: Lora: pin 10, SD: pin 5

other SPI pins follow the standard pins.

PS: In the code, we have commented out some of the lines within the SDC function as based on our observation:

```
myFile = SD.open("HG.txt", FILE_WRITE);
   myFile.close();

```

These 2 lines are the ones causing our Lora to not display the data it is receiving in the (String receive variable).

Thank you, good sir/ma'am, once again hopefully you can assist me.

Here is the complete code:

```
#include <SPI.h>
#include <SD.h>
#include <RH_RF95.h>
#define RFM95_CS 10
#define RFM95_RST 9
#define RFM95_INT 2
#define RF95_FREQ 868.0
RH_RF95 rf95(RFM95_CS, RFM95_INT);
unsigned long millisecs;
int cnt;
float valu;
String jh;
int code=1;
String received;

File myFile;

void setup(){
 Serial.begin(115200);
 if (!SD.begin(5)) {
    Serial.println("Card failed, or not present");
    while (1);
  }
  else{
  Serial.println("card initialized.");
  }

  delay(100);

 pinMode(RFM95_RST, OUTPUT);
 digitalWrite(RFM95_RST, HIGH);
 while (!Serial);
 Serial.println("Arduino LoRa RX Test!");
 digitalWrite(RFM95_RST, LOW);
 delay(10);
 digitalWrite(RFM95_RST, HIGH);
 delay(10);
 while (!rf95.init()) {
 Serial.println("LoRa radio init failed");
 while (1);
 }
 Serial.println("LoRa radio init OK!");
 if (!rf95.setFrequency(RF95_FREQ)) {
 Serial.println("setFrequency failed");
 while (1);
 }
 Serial.print("Set Freq to: "); Serial.println(RF95_FREQ);
 rf95.setTxPower(23, false);
}

void lorA(){
  while(code==1){
if (rf95.waitAvailableTimeout(1000)){
 Serial.println("dayun ");
 uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
 uint8_t len = sizeof(buf);
 if (rf95.recv(buf, &len)){
 cnt++;
 Serial.print("Data number: ");
 Serial.println(cnt);
 received=(char*)buf;
 Serial.print("Data received: ");
 Serial.print(received);

 if(received=="ANEMO"){
 uint8_t data[] = "And hello back to you";
 rf95.send(data, sizeof(data));
 rf95.waitPacketSent();
 Serial.println("Sent a reply");
 code=0;
 }
 }
 else{
 Serial.println("Receive failed");
 }
 }
 }
 }

void SDC(){
  while(code==0){
  Serial.println("SDC");
//  File dataFile = SD.open("HG.txt", FILE_WRITE);
//  String dataString="Hans";
//  if (dataFile) {
//  dataFile.println(dataString);
//  dataFile.close();
//    Serial.println("closed");
//    Serial.println(dataString);
    code=1;
//  }
//  else {
//    Serial.println("error opening datalog.txt");
//  }

  }
  }

void loop(){
  Serial.println("loop");
  lorA();
  Serial.println("mid");
  SDC();
}

```

# Answer
all of your problem can be solved through a simple trick ... Just follow it...

1. Use Sdfat library insted of SD
2. just follow SPI datasheet..

follow below code ... it works with LORA AND SD both together

```
...

#include <SdFat.h>
#include <SPI.h>
#include <RHReliableDatagram.h>
#include <RH_RF95.h>

SdFat sd;
SdFile myFile;

#define chipSelect 4

#define RFM95_CS 10 //
#define RFM95_RST 9
#define RFM95_INT 2

// Singleton instance of the radio driver
RH_RF95 rf95(RFM95_CS,RFM95_INT);
//RH_RF95 driver(5, 2); // Rocket Scream Mini Ultra Pro with the RFM95W

// Class to manage message delivery and receipt, using the driver declared above
RHReliableDatagram manager(rf95, 2);

void setup() {

  Serial.begin(9600);
  while (!Serial) {}  // wait for Leonardo

  delay(100);

  // Initialize SdFat or print a detailed error message and halt
  // Use half speed like the native library.
  // change to SPI_FULL_SPEED for more performance.
  pinMode(RFM95_CS, OUTPUT);
  digitalWrite(RFM95_CS, HIGH);
  digitalWrite(4, LOW);

  if (!sd.begin(chipSelect, SPI_HALF_SPEED)) sd.initErrorHalt();

/*

/*
 * //Open file and write  ...
 *
  // open the file for write at end like the Native SD library
  if (!myFile.open("mrinmoy.txt", O_RDWR | O_CREAT | O_AT_END)) {
    sd.errorHalt("opening test.txt for write failed");
  }

  // if the file opened okay, write to it:
  Serial.print("Writing to test.txt...");
  myFile.println("testing 1, 2, 3.");

  // close the file:
  myFile.close();
  Serial.println("done.");
  */

  /*
  // open the file for reading....

  if (!myFile.open("mrinmoy.txt", O_READ))
  {
    sd.errorHalt("opening test.txt for read failed");
  }

  Serial.println("mrinmoy.txt:");

  // read from the file until there's nothing else in it:
  int data;

  while ((data = myFile.read()) >= 0) Serial.write(data);
  // close the file:
  myFile.close();
  */

  // manual reset
  digitalWrite(RFM95_RST, LOW);
  delay(10);
  digitalWrite(RFM95_RST, HIGH);
  delay(10);

  digitalWrite(RFM95_CS, LOW);
  digitalWrite(4,HIGH);

  while (!manager.init()) {
    Serial.println("LoRa radio init failed");
    while (1);
  }
  Serial.println("LoRa radio init OK!");

 // digitalWrite(RFM95_CS, LOW);

}

void loop()
{
   uint8_t data[] = " Hi.. This is node 1.";
 //   unsigned char sd_data[50];
// Dont put this on the stack:
 // uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
   uint8_t buf[50];
  // nothing happens after setup

  //LoRa.setPins( LoRa_CS, LoRa_RST, DI0 );
  digitalWrite(4,HIGH);    //  deselet SD Card SPI
  digitalWrite(RFM95_CS, LOW);    //  SELECT (low) LoRa SPI
  SPI.begin();

  // Send a message to manager_client
  if (manager.sendtoWait((uint8_t*)data,sizeof(data),1))
  {
    Serial.print("successfully sent to: ");
    Serial.println(1);
  }
  else
  {
    Serial.println("send failed");
  }

  // receiver ....

   // Now wait for a reply from the server
   uint8_t len = sizeof(buf);
   uint8_t from;

   if (manager.recvfromAckTimeout(buf, &len, 2000, &from))
    {
      Serial.print("Got Response From : 0x");
      Serial.print(from, HEX);
      Serial.print(": ");
      Serial.println((char*)buf);
    }
    else
    {

    }
 //   digitalWrite(4, LOW);
   SPI.end();

   digitalWrite(4, LOW);    //  deselet SD Card SPI
   digitalWrite(RFM95_CS,HIGH);    //  SELECT (low) LoRa SPI
   SPI.begin();

 if (!myFile.open("mrinmoy.txt", O_READ))
  {
    sd.errorHalt("opening test.txt for read failed");
  }

  Serial.println("mrinmoy.txt:");
  char ch;
  String str;
  int i=0;
  uint8_t sd_data[50];

  while (myFile.available()>0)
  {
    ch= myFile.read();
    str+=ch;
  }

  String str2=str;
  Serial.println(str2);
  Serial.println(str2.length());

  myFile.close();
  SPI.end();

  delay(500);
}

```

use this trick ... your system will work perfectly ...
> 1 votes

---
Tags: sd-card, wireless, rf
---


# Question
Title: Does a Sparkfun Redboard Arduino Uno have built-in RTC?
I have a Sparkfun Redboard (an Arduino Uno like board based on the Atmega328P and programmed with the Arduino bootloader).

I have been trying to make an accurate clock without an RTC with an LCD screen and it's been hard.

Does the Sparkfun Redboard have built-in RTC?

# Answer
Sparkfun Redboard and Arduino Uno do not have built-in RTC.
> 2 votes

# Answer
The new "Sparkfun Redboard Turbo" does have an RTC on pins A5 and AREF
> 1 votes

---
Tags: arduino-uno, lcd, rtc
---


title: Voltage at AREF pin

text:
# Question
Title: Voltage at AREF pin
I find difficulties to measure correctly the voltage at the AREF pin. I would measure voltages with a resolution not exceeding 1 mV . nda voltage divider In one of my trials, I was using a 9V battery and a voltage divider made with a 1k resistor and a 2k one.

The battery voltage was about 8890 mV and the reference voltage was about 2960 mV (confirmed by a multimeter). I connected the output of the divider to the AREF pin of an Arduino Uno board. The output voltage value dropped to about 1800 mV. Reading the voltage value at AREF pin with a simple sketch:.

the serial monitor printed:

as if the voltage dividere did not exist. What am I doing wrong? or what I don’t understand? Thank you for your attention.

# Answer
> I was using a 9V battery and a voltage divider made with a 1k resistor and a 2k one.

Using a battery is not a good way of getting a stable voltage. A battery's voltage will change over time.

Using a voltage divider is not a good way of generating a reliable stable voltage. The output impedance is very high and will be affected by any loading you apply to it causing it to droop.

If you want 1mV per LSB then you need a 1024mV voltage reference (since there are 10 bits of resolution, or 1024 possible divisions, in the ADC). For that you want a 1024mV voltage reference, which is a standard value for precision voltage reference chips such as the LM4140CCM-1.0/NOPB from Texas Instruments. Personally I like to use a precision DAC like the MCP4821 to provide a settable analog reference voltage.

> Reading the voltage value at AREF pin with a simple sketch the serial monitor printed 8890 as if the voltage dividere did not exist. What am I doing wrong?

You cannot read anything from the AREF pin. It is merely a voltage reference, not an active pin you can read. When you use `analogRead(EXTERNAL)` you are actually doing `analogRead(0)` since `EXTERNAL` is a macro that expands to `0`. That means you are really reading from pin A0 not the AREF pin. And then you just map that to 8890 when it's at maximum anyway. Since A0 is (probably, since you don't show anything else in your circuit) floating it will most likely be above the voltage you are feeding in to AREF and will return 1023 all the time anyway.
> 2 votes

---
Tags: arduino-uno, analogreference, voltage-divider
---


# Question
Title: Will a pull up resistor help the UART transmission accuracy on Arduino nano?
On A post from Arduino forum , someone mentioned that a pull up resistor over RX/TX pin could help the reliably of UART communication.

Is that really the case for nano and uno board?

# Answer
> 1 votes
No. That is not the case. Adding a pullup resistor on a normal UART will do nothing except maybe reduce your reliability.

You only want pullup resistors on something which is "open drain" (AKA "open collector") which has no way of raising the voltage of a signal line, only lowering it - such as I2C signals, or a shared open-drain, interrupt signal.

---
Tags: arduino-nano, uart, pull-up
---


# Question
Title: Initialize object with PROGMEM constants
I have a class which has a `const char *` property:

```
    class A
    {
    public:
        const PROGMEM char* text;
    };

    void setup()
    {
        // A a{"Hello World!"};
        // A a{PSTR("Hello World!")};

        A a;
        a.text = PSTR("Hello World!");

        Serial.begin(9600);
        delay(30);
        Serial.println(a.text);
    }

    void loop()
    {
    }

```

I’d like to spare some RAM using `PROGMEM`.

How to initialize `a` object then?

Obviously, it can’t be like this:

```
    A a{PSTR("Hello World!")};

```

This will do:

```
    A a;
    a.text = PSTR("Hello World!");

```

However, I need to pass string to the constructor.

# Answer
> 2 votes
It is a shame that gcc only supports the `__flash` qualifier in C mode, not in C++, so we have to use `PROGMEM` instead. Unlike `__flash`, which qualifies a variable just like `const`, the `PROGMEM` attribute only has effect when allocating room for a variable. Once the allocation is done, the compiler forgets about the attribute. In particular, a declaration such as

```
const PROGMEM char* text;

```

does not allocate flash space, so it generates the warning

```
warning: ‘__progmem__’ attribute ignored [-Wattributes]
     const PROGMEM char* text;
                         ^

```

You can thus forget the attribute when declaring a pointer, as there is no such thing as a “pointer to `PROGMEM`”. You just use a `const char *` instead.

Now, the second issue is that, as far as `Serial.println()` is concerned, the pointer above is a plain `const char *`, so it will interpret it as an address in RAM, and print garbage. If you want `Serial.println()` to know you are giving it an address in flash, you should provide it with a `const __FlashStringHelper*` pointer.

Here is the solution I propose. Tested on an Uno-compatible board:

```
class A
{
public:
    A(const char* s)
        : text(reinterpret_cast<const __FlashStringHelper *>(s)) {}
    const __FlashStringHelper* text;
};

void setup()
{
    A a{PSTR("Hello World!")};
    Serial.begin(9600);
    Serial.println(a.text);
}

void loop(){}

```

---

**Edit**: After seeing the last version of Juraj’s answer, I must say that I agree with him. Since we are using the Arduino API, it makes more sense for the constructor to take a `const __FlashStringHelper*`, and for the caller to use the `F()` macro.

# Answer
> 3 votes
`const char* text;` is a pointer to constant not a constant pointer (`char * const text` is a constant pointer). So you can assign a pointer to a constant char array to `const char* text;` even a pointer to an array in PROGMEM.

The compiler doesn't know the difference between a PROGMEM pointer and a pointer in SRAM. It is on you to work in code with a pointer to PROGMEM the right way.

so remove PROGMEM from `const PROGMEM char* text;`

---

add constructor to initialize an object.

```
A(const char* _text) {
  text = _text;
}

```

and then

```
A a(PSTR("Hello World!"));

```

---

EDIT:

you could use Arduino's F() macro and \__FlashStringHelper type, because it is supported by Serial print and co.

```
class A
{
public:
  A(const __FlashStringHelper* _text) {
    text = _text;
  }
  const __FlashStringHelper* text;
};

void setup()
{
    A a(F("Hello World!"));

    Serial.begin(9600);
    delay(30);
    Serial.println(a.text);
}

void loop()
{
}

```

\__FlashStringHelper type is trick to distinguish PROGMEM strings from char arrays in SRAM..

---
Tags: progmem
---


title: Gauss solver for IIR filter

text:
# Question
Title: Gauss solver for IIR filter
I write a piece of code in online GDB using c++, the code calculates some coefficients for a IIR filter which tries to approximate a fractional derivative and integral for a fractional PID control. The code works as expected in the online IDE, but when I try to execute it in a Arduino Due, the results and only overflows and nan, and really don't know what's the problem so,

Here is the code in GDB online https://onlinegdb.com/rycwt62XL which gives the expected results:

Array A, Array B

1.41421,1

-0.707107,0.5

-2.12132,-1.5

0.883883,-0.625

0.883883,0.625

-0.265165,0.1875

-0.0883883,-0.0625

0.0110485,-0.0078125

And here is the code for the Arduino Due, which only change the printing method using the serial commands, https://onlinegdb.com/ByAs5xyVU, and the results are:

Array A, Array B

ovf,1.00

ovf,ovf

ovf,0.00

inf,ovf

ovf,0.00

inf,ovf

ovf,3.89

inf,ovf

And really don't know where to start for fix this results, thanks. The Method is exactly the same.

# Answer
> 1 votes
I can't find the root cause of the problem - it's probably because the Due is possibly the worst board that Arduino ever made, and the compiler / linker / support libraries barely work at the best of times.

However, some things you need to look at in your code:

```
    double* h = new double[L];
    for(int n = 0; n <= L; n++){
        for(int k = 0; k <= n; k++){
            h[n] += pow(operador,-alpha-n+k)*pow(1.0-operador,n-k)*Binomial_E(alpha,k)*Binomial(-alpha,n-k);
        }
    }

```

There you allocate `L` (15) doubles in an array. But then you go on to access array slices 0-15. That's 16 entries in an array of size 15, so you're overflowing it and corrupting other memory.

Also you have no `delete` to balance the `new`, so you have a memory leak. You would be better using:

```
double h[L+1];

```

instead of `new`.

---
Tags: arduino-ide, arduino-due
---


# Question
Title: Which board to use for wireless communication of small packages?
I was hoping to get your advice on what Arduino boards to look at for a project I'm working on. The project involves two separate boxes in different rooms of my apartment (~ 5-10 feet away from each other) and needs to allow wireless communication of very small amounts of information (think like 5 bytes). However, this transfer needs to be very rapid (within 200 milliseconds).

While I have worked a good bit with the Arduino Uno, I haven't worked with boards with Wifi capabilities.

The boards I know of are: Esp32, Esp8266, Arduino MKR 1010, Arduino Mega RobotDyn.

What would be the best board for a project like this / are there other boards that are well-suited for a project like this?

Thanks!

# Answer
> 1 votes
WiFi round trip time is about 2-50 ms (50 is the worst case), so, you can use the ESP's and the UDP/TCP.

On the other hand, you can use the NRF433 module, but in this case, you have to develop your own channel level protocol, with error detection/correction and so on.

Also, there are ZigBee module. They developed for home automation specially.

---
Tags: wifi, bluetooth, wireless
---


title: ESP-12 + FTDi + platformio

text:
# Question
Title: ESP-12 + FTDi + platformio
I have 2 questions.

1. Why we have to put our functions before void loop and void setup into VScode+platformio?
2. I switched from arduino IDE to VScode+platformio today, when I upload the sketch with platformio into my esp-12, it doesn't work. (It works with arduino IDE)

I have this Warning: `src\main.cpp:46:24: warning: large integer implicitly truncated to unsigned type [-Woverflow]
 const byte menuColor = 0XF206;`

\[EDIT\]The problem comes from these lines:

```
attachInterrupt(digitalPinToInterrupt(enA), enAin, RISING);
attachInterrupt(digitalPinToInterrupt(enB), enBin, RISING);
attachInterrupt(digitalPinToInterrupt(enBtn), enBtnIn, FALLING);

```

# Answer
> Why we have to put our functions before void loop and void setup into VScode+platformio?

Because that is how C works. The Arduino IDE hides it from you by adding *function prototypes* at the start of your code.

> I switched from arduino IDE to VScode+platformio today, when I upload the sketch with platformio into my esp-12, it doesn't work. (It works with arduino IDE)

```
const byte menuColor = 0XF206;

```

That can never work. The value 0x06 will be assigned to menuColor since a byte is only 8 bits. You need to learn to use data types that are suitable for the values you are trying to store in them.
> 1 votes

---
Tags: esp8266, ftdi
---


title: upload sketch via bluetooth for android

text:
# Question
Title: upload sketch via bluetooth for android
How can i convert file .ino to hex file so that i can compile new sketch via bluetooth. Can you help me to figure out the way to do this? thanks for helping

# Answer
It is very hard to understand exactly what you want to do, but from what I can gather you want to:

1. Write an Android application that lets you edit sketches
2. Compile those sketches on an android device, and
3. Upload those compiled sketches to an Arduino over Bluetooth

While what you are asking is *technically* possible, it is not *realistically* practical.

Writing a text editor in Android is easy enough. That's not a problem. It's the compilation of the code that is not practical.

You would need to port the compiler (a very large project written in C) to Android. That would essentially need to remain as compiled C code, and so you would have to individually port it to each possible platform you want it to run on (various different types of ARM, Intel, etc) and for different versions of android.

Unless you're a genius at Android and C programming that's just not going to happen.

A more practical way would be to write a web-based application that allows you to edit your sketches, which can then run the compiler on a real computer (no porting needed then), which can then download the compiled HEX file to your Android device, then use a pre-existing application to program that HEX file over bluetooth.

Alternatively, just use the Arduino Create website to compile and download your HEX file.
> 0 votes

---
Tags: arduino-uno, uploading, android
---


# Question
Title: NEO-6M is working but it doesnt show data
So I'm having a little bit of difficulty here in my NEO-6M. `The problem is it doesn't show any data in my serial monitor.` My NEO-6M Led is already blinking so its already ok.

```
RX -> Pin3 , TX -> Pin4 , VCC -> 3.3v , GND -> GND

```

> Serial Monitor:

Code: *https://github.com/mikalhart/TinyGPSPlus/blob/master/examples/FullExample/FullExample.ino*

# Answer
I found a solution to my problem. On my first setup, I separate my GND of NEO-6M to Arduino and put connect it in breadboard that has powerboard on it because I thought it is only for electrical purposes but it doesn't since I encounter it.

Solution:

> The GND of every module must still connect on the Arduino.
> 1 votes

---
Tags: arduino-uno, gps
---


# Question
Title: Stepper motor is only moving one step at a time with an IR sensor
I am trying to get both the motors to run simultaneously once the motion detector senses an obstacle. Both motors run fine by themselves but when I implement the sensor the motors only move one step per motion detected.

* Arduino Mega (ATMega 2560)
* (2) NEMA 17 stepper motor/ A4988
* Digital IR Sensor Module

```
#include <Arduino.h>
#include <avr/io.h>
#include <AccelStepper.h>

AccelStepper stepper(1,5,4); // w/Driver (1,Step, Direction)
AccelStepper stepper2(1,9,8);

const int pin_ir_in = 3;
int prev_state = 1;
int curr_state = 1;
int counter =0;

void setup() {
  Serial.begin(9600);
  pinMode(6,OUTPUT); // Enable
  pinMode(10,OUTPUT);

  digitalWrite(6,LOW); // Set Enable low
  digitalWrite(10,LOW);
}

void loop() {
  digitalWrite(6,LOW); // Set Enable low
  if (stepper.distanceToGo() == 0)
  {
    delay(1000);
    stepper.moveTo(100);
    stepper.setMaxSpeed(200);
    stepper.setAcceleration(100);

  }

   digitalWrite(10,LOW); // Set Enable low
     if (stepper2.distanceToGo() == 0)
  {
    delay(1000);
    stepper2.moveTo(100);
    stepper2.setMaxSpeed(200);
    stepper2.setAcceleration(100);

  }

int curr_state = digitalRead(pin_ir_in);
if (curr_state != prev_state)
{
  if (curr_state == 0)
  {
    stepper.run();  // Actually makes stepper move
    stepper2.run();
    delay(500);
  }
  prev_state = curr_state;

}

}

```

# Answer
As chrisl said, you need to call `run` repeatedly.

I tried to rewrite the code you've given, though I'm not entirely sure what it is you try to achieve.

```
void loop()
{
  stepper.run();  // Actually makes stepper move
  stepper2.run();

  int curr_state = digitalRead(pin_ir_in);
  if (curr_state != prev_state)
  {
    if (curr_state == 0) // Motion sensor activated
    {
      stepper.moveTo(100);
      stepper.setMaxSpeed(200);
      stepper.setAcceleration(100);
      stepper2.moveTo(100);
      stepper2.setMaxSpeed(200);
      stepper2.setAcceleration(100);
    }
    prev_state = curr_state;
  }
}

```
> 1 votes

---
Tags: programming
---


# Question
Title: How to change the default name of ESP8266-12E module
Is there any way to change the default name (ESP\_xxxxx) that the module generates?

# Answer
> 4 votes
The function is: `WiFi.hostname("Name");`, make sure you call it before `Wifi.begin()`

# Answer
> 3 votes
This line of code should hopefully do a difference.

```
wifi_station_set_hostname(myHostname);

```

For more information :

https://www.reddit.com/r/esp8266/comments/3zl3pi/change\_esp8266\_network\_name/

# Answer
> 1 votes
Here you are the code where you can see how you can change `network name` of your ESP8266 working in AP mode:

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

IPAddress ip(192,168,1,81);         // choose IP address
IPAddress subnet(255,255,255,0);

ESP8266WebServer server(80);

void handleRoot() {
  String page = "<!DOCTYPE html>\n";

  page += "<html>\n<body>\n<h1>Some heading</h1><br>Generated by ESP8266\n</body>\n</html>";
  server.send(200, "text/html", page);
}

// what to do when accessed through http://ip_address/something_undefined
void handleNotFound(){
  String message = "File not found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET)?"GET":"POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i=0; i<server.args(); i++){
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void){
  Serial.begin(74880);                      // so you can see debug messages automatically sent by ESP8266
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(ip, ip, subnet);        // declared as: bool softAPConfig (IPAddress local_ip, IPAddress gateway, IPAddress subnet)
  WiFi.softAP("SOME_NAME", "password", 7);  // network name, network password, wifi channel

  IPAddress myIP = WiFi.softAPIP();
  Serial.println();
  Serial.print("AP IP address: ");
  Serial.println(myIP);

  server.on("/", handleRoot);               // what to do when accessed through browser using http://IP_address

  // what to do when accessed through http://ip_address/test
  server.on("/test", [](){
    server.send(200, "text/plain", "This is another page");
  });

  server.onNotFound(handleNotFound);

  server.begin();
  Serial.println("HTTP server started...");
}

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

```

# Answer
> 0 votes
check the Erase Flash\>\> Tools \>\> Arduino IDE before uploading your sketch and select erase previous wifi settings

---
Tags: esp8266, nodemcu
---


# Question
Title: MB-102 BreadBoard Power Supply Limitation
> Does the MB-102 can handle Arduino Uno, SIM900 and 3 other modules that requires 5v? If yes, does 9v battery is enough? If no, please suggest me what should I use that uses only 1 barrel jack(if possible).

Im afraid that I might fry it if I try cause I dont have enough knowledge about electric currents.

# Answer
> 1 votes
> Does the MB-102 can handle Arduino Uno, SIM900 and 3 other modules that requires 5v?

You mean because the current requirements? The answer is yes and no. No, because the needed current must not flow through the Arduino. The SIM900 draws up to 2A, that current would fry the protection diode/voltage regulator on the Arduino (though you may get away with a bit less than that by using a big capacitor to accommodate current spikes). Depending on the version of the Uno, it can provide 200mA or 1A (in case of rev3)(including what is needed for the Uno to operate). You need to provide the 5V of these modules from outside of the Arduino, via an extra voltage regulator, which can handle the big current.

> does 9v battery is enough?

If you mean the standard 9V block battery, then no, never. These batteries are meant for low power applications and are almost never a good choice for an Arduino project (unless you have really a low power application). You need to use different batteries, for example a series of AA batteries or a LiPo pack (including the needed circuitry for such a pack).

---
Tags: arduino-uno, power, breadboard
---


# Question
Title: Can I control a 28BYJ-48 5V stepper with a DVR8825 driver?
I have a stepper motor **28BYJ-48** rated 5 V and I want to use a **DVR8825** driver so I can use the 1/32 micro-stepping feature. My problem is that DVR8825 has a minimum operating voltage of 8.2 V. Would the 28BYJ-48 stand a 10 V input?

Is there any alternative to the DVR8825 that operates at 5 V and has at least 1/32 micro-stepping?

# Answer
Stepper motors are rated in two different ways. Some provide a "rated voltage" in combination with a "DC resistance", others provide a "phase current" and a "phase resistance". The way they operate is identical.

Stepper motors such as your 28BYJ-48 are usually intended to be driven with a fixed voltage, their rated voltage. At this voltage, the maximum permittable current flows in the steppers windings - determined mostly by cooling and wire thickness. If you exceed that voltage, more current will flow and will damage / destroy the stepper motor.

The DRV8825 is a current controlled stepper motor driver - it always uses the full available supply voltage - 8.2V+ - but uses PWM to limit the current actually flowing in the stepper. This is possible because the stepper motor coils are inductors, which inhibit the flow of current.

To use your stepper motor with a DRV8825 driver, you'll have to calculate the steppers equivalent "maximum phase current". According to this datasheet, it's rated 5 V at 50 Ohms, giving us a current of 0.1 A. You can then set this current via the potentiometer on the driver chip. The Vref voltage should be set so that `Vref = Imax / 2`. Start at a Vref of 50 mV, and see how warm the motor gets and whether it's as strong as you would expect it to be.
> 2 votes

---
Tags: stepper
---


# Question
Title: HC-12 modules stopped receiving, cannot understand why
I've created a simple transmitter with an **HC-12** and an *Arduino Nano* (clone), where I send the values of *DHT11* and *LM35* sensors to a receiver unit made only of a *Wemos D1* and another **HC-12**.

Setup is really simple and worked fine for a couple of days (transmitter in the cellar 2 floors down, receiver in my living room, it was POSTing data to my own server correctly), then I unplugged the receiver and modified the transmitter to add a JSON library; when I plugged them back again the receiver is not getting anything anymore. Transmitter seems to be working fine, at least it prints the number of bytes written in the Serial Monitor.

I tried:

* reverting back to the working version (no JSON), but still the same
* tested each of the HC12 modules with a simple test code and AT commands, they all responds and are all set to factory configuration, like it was before actually (AT+DEFAULT)
* made another receiver with an Arduino Uno and a lcd screen - a setup that I was successfully using before changing to the Wemos. Strangely, now this setup doesn't work too...
* Switched the modules and what I got? The transmitter still transmits, the receiver doesn't receive, nothing changed.
    + Tried sending a simple string "Test", still no results.

Relevant code:

Transmitter:

```
#include <ArduinoJson.h>
#include <DHT_U.h>            // just Adafruit Library
#include <DHT.h>
#include <SoftwareSerial.h>
#define DHTTYPE DHT11   // DHT 11
SoftwareSerial HC12(10, 11); // HC-12 TX Pin, HC-12 RX Pin
int DHTPIN = 4;
int LMPIN = 5;
DHT dht(DHTPIN, DHTTYPE);
StaticJsonDocument<80> doc;

void setup() {
  analogReference(INTERNAL);
  Serial.begin(9600);             // Serial port to computer
  HC12.begin(9600);               // Serial port to HC12
  dht.begin();
}

void loop() {
  delay(5000);
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  int reading = analogRead(LMPIN);
  float lmt = reading/9.31;
  doc["dht_h"] = h;
  doc["dht_t"] = t;
  doc["ds_t"] = lmt;
  char result[50];
  serializeJson(doc, result);
  Serial.println(result);
  int written = HC12.print(result);
  Serial.println(written);    // it's 39 chars
}

```

Receiver (all wifi sections are removed):

```
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
#define STASSID "....."
#define STAPSK  "....."
SoftwareSerial HC12(D13, D15); // HC-12 TX Pin, HC-12 RX Pin

const char* ssid     = STASSID;
const char* password = STAPSK;
const char* host = "...........";
const uint16_t port = 3000;

void setup() {
  Serial.begin(9600);
  HC12.begin(9600);
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

void loop() {

  String content = HC12.readString();
  Serial.println(content);
  if(content.length()) {
    // This will send a string to the server
    Serial.println("sending data to server");
    if (client.connected()) {
      //....
    }
  }
  delay(1000);
}

```

I'm pretty stumped by the fact that it stopped working, and that both the HC-12 modules seem to be working fine (at least they respond to all the AT commands). I even tried purging arduino from the system and reinstalling (I now have the very latest IDE release) but nothing....

Am I missing something obvious? (I've a weak electronic background, I'm a web developer by trade). Is there a way to check if data is actually sent? How can I debug these modules?

# Answer
For what it's worth, I manage to make them working again by playing a bit with the settings of both modules.

Using a simple test sketch I issued some AT commands to both modules; I had already tried setting them to the DEFAULT setup with AT+DEFAULT, but that was fruitless. I decided to left the mode as is (FU3), same for the serial rate (B9600), but I tried switching channel so I set both modules with AT+C002.

That did the trick, maybe was some sort of external interference, or a lack of precision in the channel settings - I just know that's a week now they've been communicating just fine and that's what matters.

So, if they fail to communicate, first try to adjust their settings, don't assume the DEFAULT ones are surely working.
> 2 votes

---
Tags: serial, esp8266, arduino-nano, softwareserial, hc-12
---


title: Reading from 2 serial ports

text:
# Question
Title: Reading from 2 serial ports
I have 2 Arduino Nano, they are connected via ports 2 and A2

While I use only one port to receive, it works properly. But if I activate the second port, system crash (and even first port don't work properly)

Code of first Arduino:

```
#include <SoftwareSerial.h>
SoftwareSerial SerialPort2(2,A2);
SoftwareSerial SerialPort3(3,A3);

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

void loop() {
  delay(500);
  SerialPort2.listen();
  if(SerialPort2.available()){
    char value = SerialPort2.read();
    Serial.print(value);
    Serial.print(" First port\n");
  }
  // IF YOU REMOVE PART BELLOW, THE 'SerialPort2' WILL WORK PROPERLY
  SerialPort3.listen();
  if(SerialPort3.available()){
    char value = SerialPort3.read();
    Serial.print(value);
    Serial.print(" Second port\n");
  }
  // END OF THIS PART
}

```

Code of second Arduino:

```
#include <SoftwareSerial.h>
SoftwareSerial SerialPort2(2,A2);

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

void loop() {
  SerialPort2.write('a');
  delay(1000);
}

```

PS in real system I need to listen 6 ports

# Answer
SoftwareSerial is only a "good" choice (for certain values of "good") if you only use *one* instance, and that is the *only* serial port in the system.

Using SoftwareSerial to read from 2 ports simultaneously is not possible. Using SoftwareSerial to read data in tandem with any other hardware serial ports *will result it data loss*.

SoftwareSerial is only any real use when you are using it to request data from another device and times when you command it to happen.

To receive data in an "unsolicited" fashion SoftwareSerial is not good.

Instead you need a hardware serial port for *each* incoming signal. And obviously you can't do that with a small board like a nano. So you need to think more creatively.

If you have one real serial port you can talk to one device. But there are other communication channels at your disposal. So you take one board and have that communicate to one of your serial devices. Then you take the data read and convert it into another communication protocol that is capable of sharing time with other boards. Then that, and 5 other boards, all send their data (or get data from) one central "master" board. In effect you have 6 "UART to Protocol X" converter boards, and one "Protocol X" master board.

Alternatively choose a board that has 6 UARTs. There are many higher-end chips like some ATSAMD, SAMX, and PIC32 chips, that have 6 UARTs available to you.
> 0 votes

# Answer
`SoftwareSerial` can only listen to one port at a time. You cannot listen to both, no way. To really listen to both, you need an Arduino with more hardware Serial ports, where most of the protocol is done in hardware, thus can receive without CPU intervention. The Arduino Mega has 4 hardware Serial ports.

Or you could impose a protocol on the Serial stream to make the listening Arduino the master. You would listen to the first serial interface, send a start byte over this interface, that tells the slave Arduino to start sending. It sends and the listening interface receives (The transmission has to be delimited by either a time limit, e.g. listen for a specific time, or by a stop byte). Then you listen to the next interface, send again the start byte and receive. And so on.

With such a protocol, you could even use a single serial interface. The protocol makes sure, that only one slave is transmitting at a time. Though you should add resistors to every slave to protect their TX pins.

> in real system I need to listen 6 ports

Serial (UART) is really not the best interface type for such topology. You should consider using interfaces like SPI. It doesn't need additional electronics and is better fit for multiple slaves.
> 0 votes

---
Tags: serial, softwareserial
---


# Question
Title: Arduino Analog to Digital Conversion from 56V DC Batteries
I have a problem, I am using 56V DC combined batteries system. I get ADC values comes to Arduino like 211, 217 etc... I have to find out when the DC volt drop to 42V. How do i know the digital value for the ADC from Aruino.

# Answer
I'll assume you're using Li-Ion batteries in 14s configuration. You'll want to measure voltages up to around 60 V while charging. With a bit of safety margin, I'd set it up to measure up to 72V without damaging the Arduino - which can measure voltages up to 5 V, but the input on that pin should never exceed 5.5 V.

To bring your battery voltage down to something the Arduino can use, you'll need to use a voltage divider, as chrisl suggested.

With R1 = 10 kOhm and R2 = 680 Ohm, you'd get readings up to an input voltage of 78 Volts.

With `analogRead()` returning values between 0 and 1023, your 42 V cutoff would be around 546.
> 1 votes

# Answer
**Warning: this is going to get math-heavy**

Ok. So you have a battery with a voltage divider on it, and you are using the Aruino ADC to read the output of that voltage divider. And you want to "back-calculate" the battery voltage from the ADC reading.

First let's look at exactly what happens with a voltage divider and just how it works. For that we'll turn to good ol' Ohm's Law.

Rule number one is that two resistors in series *sum* their resistances. So if you have a 10kΩ and 680Ω resistor in series (as suggested in @towe's answer) the total resistance is 10680Ω. We'll use this arrangement as our example.

Now Ohm's Law states that the current flowing through a resistive load is directly proportional to the voltage across it. So for a fixed resistance and a given voltage we can calculate the current that will be flowing through the resistors. That formula is:

# ***I=V/R***

So for a voltage of 56V and a resistance of 10680Ω we can say that the current is 56/10680 amps - or about 5.24mA.

Great. But so what? Well, now we can reverse the formula and find the voltage across a given resistance for that specific current. Which we can do for, for example, the 680Ω resistor. We know that the same current is flowing through both resistors (since they are in series), so flipping the formula around we get:

# ***V=I×R***

So at 0.00524 amps and 680Ω that's 0.00524×680 = 3.57V. We can do the same for the 10kΩ resistor: 0.00524×10000 = 52.43V. And oh look - if we add those two voltages together, what do we get? We get 56V. The resistors have divided the voltage into two portions.

You can combine those two formulae together to give you:

# ***VOUT = VIN × (R2 / (R1 \+ R2))***

And if we move the VIN to the left hand side we get:

# ***VOUT / VIN = (R2 / (R1 \+ R2))***

And that is known as the *transfer function*, or the ratio of the input to output voltage of the voltage divider.

For a 10kΩ (R1) and 680Ω (R2) resistor pair we get 680/10680 = 0.0637.

And that is the "magic number" we want to calculate back from the ADC to the battery voltage. Whatever the voltage we read at the ADC the battery voltage is the reciprocal of that number times bigger (reciprocal is "one over the value"). The reciprocal of 0.0637 is 15.7. So if you read the value from the ADC then convert that into a voltage relative to the internal reference voltage (approximately 5V for a normal Arduino) then multiply that voltage by 15.7 you will get your battery voltage.

So next is to get the ADC voltage. And again, it's all ratios. The ADC gives you a number that is a ratio of the incoming voltage to the reference (5V) voltage. At 1023 you get "5V minus 1 LSB", so about 4.995V. We don't need that kind of accuracy for this, really, so we'll just call it 5V.

Say you read 482 from the ADC, if you convert that into a voltage you take the ratio 482/1024 and multiply it by the reference voltage (1024 is the range of a 10-bit ADC - you would change that for other types of ADC):

# ***VIN = 482 / 1024 × 5 = 2.35V***

Multiply that by our "magic number" 15.7 and you get 36.95V - and that's the battery voltage.
> 0 votes

---
Tags: arduino-uno
---


# Question
Title: How to create a USB CDC device. (I'm using stm32f103c8 black pill board) and I want to read the data through USB in my raspberry pi as a serial port
How to create a USB CDC device. (I'm using stm32f103c8 black pill board) and I want to read the data through USB in my raspberry pi as a serial port.

I am using a black pill to read RFID-rf522 to read a tag (SPI) and send it to raspberry pi through a USB (using DM and DP pins).

Quick responses are welcomed.

# Answer
You can use the one provided by generating it with STMCubeMx. This is going beyond arduino though. But it is highly feasible.
> 1 votes

---
Tags: serial, softwareserial, raspberrypi, stm32
---


title: Read amount of I/Os in code

text:
# Question
Title: Read amount of I/Os in code
I want to write an Arduino code, that runs on several different Boards. The code can perform digitalRead/Write operations, but the pin number will be set from the user/outside. I want to include a check, if the selected pin exists.

Is it possible, to read the amount of I/Os (digital and analog) of the Arduino the code is currently running on, to check if the users selection is in the given range? Or is it possible to check, if a certain pin number exists?

# Answer
It depends on the core, but most provide the macro `NUM_DIGITAL_PINS` which tells you the number of digital pins the board has. In general this doesn't equate to the actual number, but to one more than the highest number (there are boards with gaps in the pin number sequence).

So you can use:

```
if (pinNumber < NUM_DIGITAL_PINS) {
    digitalWrite(pinNumber, HIGH);
} else {
    Serial.println("Invalid pin number");
}

```

In tandem with that you also usually have `NUM_ANALOG_INPUTS`.
> 2 votes

# Answer
The number of the GPIO pins available depends on how the chip is wired on the Arduino Board and which microcontroller one is running on. For example, an Arduino Uno with a ATMega328p chip has 14 Digital I/O pins, whereas an Arduino Mega 2560 with a chip has 54 digital I/O pins.
> 0 votes

---
Tags: pins, digital
---


title: Decoding RF receiver signals

text:
# Question
Title: Decoding RF receiver signals
By using the following draft i decode the signals from an RF receiver

```
#define CH1 2
#define CH2 3
#define CH3 4
#define CH4 5
#define CH5 6
#define CH6 7

int ch1Time, ch2Time, ch3Time, ch4Time, ch5Time, ch6Time = 0;
void channels()
{
  TCNT1 = 0;
  ch1Time = 0; ch2Time = 0; ch3Time = 0; ch4Time = 0; ch5Time = 0; ch6Time = 0;

  while ((PIND & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
  {
    if (PIND & (1 << CH1))
      ch1Time = TCNT1;

    if (PIND & (1 << CH2))
      ch2Time = TCNT1;

    if (PIND & (1 << CH3))
      ch3Time = TCNT1;

    if (PIND & (1 << CH4))
      ch4Time = TCNT1;

    if (PIND & (1 << CH5))
      ch5Time = TCNT1;

    if (PIND & (1 << CH6))
      ch6Time = TCNT1;
  }
}

```

The issue is that i need also to use the 6 PWM's of the nano board. So i thought of moving the channels 1-6 to the analog pins like so..

```
#define CH1 A0
#define CH2 A1
#define CH3 A2
#define CH4 A3
#define CH5 A4
#define CH6 A5

while ((PINC & ((1 << CH1) | (1 << CH2) | (1 << CH3) | (1 << CH4) | (1 << CH5) | (1 << CH6))))
  {
    if (PINC & (1 << CH1))
      ch1Time = TCNT1;
etc...

```

but it simply does not work. Any thoughts please?

# Answer
I see two immediate problems:

1. The macros A0-A5 are the numbers 14 to 19, not the numbers 0 to 5 - so you're looking at (1 \<\< 14) for CH1 not (1 \<\< 0).
2. The analog pins are port C not port B, so you need to use `PINC` not `PINB`.
3. Your `ch?Time` variables should be `volatile`.
> 0 votes

---
Tags: arduino-nano
---


# Question
Title: Which libraries for DS1302 real time clock and WS2811 LED strip do not conflict?
I am making a custom wall-clock, and need the Arduino (Uno or Nano) to connect to a DS1302 real time clock module and a WS2811 LED chain.

So I’m using DS1302 for the clock, and FastLED for the lights. Individually these two libraries work fine, so I can either echo the time to the serial console, or I can drive the LEDs as I need.

But when I combine them there is some conflict happening and I get no LED output. The LED data goes over pin 6 and the clock uses pins 2,3,4 (these pins are customisable in code).

Even just adding a DS1302 initialisation to a working FastLED sketch causes no more LED output

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

#define NUM_LEDS 50
#define DATA_PIN 6

// Init the DS1302 - stops LEDs working
DS1302 rtc(2, 3, 4);

CRGB leds[NUM_LEDS];

void setup() {
  FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
}

void loop() {
  for (int i=0; i<NUM_LEDS;i++) {
    leds[i] = CRGB::Red;
  }
  FastLED.show();
  delay(100);
}

```

What are my troubleshooting steps - should I try alternative libraries, or could I dig into the libraries themselves and see what hardware resources they might be using?

I guess as both the lights and the clock probably operate over a serial protocol, it could be a conflict with the serial drivers - maybe both using the same time-critical operations.

Edit: inserted sketch which demonstrates the issue

# Answer
> 1 votes
I installed a library from within the IDE as StarCat suggested.

https://github.com/Makuna/Rtc

```
#include <FastLED.h>
#include <ThreeWire.h>
#include <RtcDS1302.h>

#define NUM_LEDS 50
#define DATA_PIN 6

ThreeWire myWire(3,4,2); // IO, SCLK, CE
RtcDS1302<ThreeWire> Rtc(myWire);

CRGB leds[NUM_LEDS];

void setup() {
   FastLED.addLeds<WS2811, DATA_PIN, RGB>(leds, NUM_LEDS);
   Rtc.Begin();
}

void loop() {
   RtcDateTime dt = Rtc.GetDateTime();

   for (int i=0; i<NUM_LEDS;i++) {
     leds[i] = CRGB::Red;
   }

FastLED.show();
delay(100);
}

```

I am able to get and use the time, and the LED output works.

---
Tags: serial, rtc, led-strip
---


title: serial 1 was not declared in the scope

text:
# Question
Title: serial 1 was not declared in the scope
```
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7);
#include <SoftwareSerial.h>

char Mob[20]="+923319020922";
String stringGPS = "";
String stringGPS1 = "";
char c=0;
int t=0,i;
int buzzer = 9;
int buttonState = 0;

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

//const int buttonPin1 =9 ;
int buttonState1 = 0;
int helmetstate=0;
const int relay=8;
char inByte=0;

void setup()
{
  lcd.begin(20, 4);
  lcd.setCursor(0, 0);
  pinMode(relay, OUTPUT);
  pinMode(buzzer, OUTPUT);
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial2.begin(9600);
  digitalWrite(relay, LOW);
  delay(15000);
  lcd.print("Config modem....");

  Config();

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print("Smart helmet      ");
}

void loop()
{
  if(Serial2.available())
  {
    inByte = Serial2.read();
    //Serial.write(inByte);
    if(inByte=='A'||inByte=='B'||inByte=='C'){
    inByte=0;
    SMS(Mob);

    while(Serial2.available()>0)
    {
      i = Serial2.read();
    }
  }

  if(inByte=='D')
  {
    digitalWrite(relay, LOW);
    inByte=0;
  }

  if(inByte=='E')
  {
    digitalWrite(relay, HIGH);
    inByte=0;
  }
  else
  {
  }
}

 //buttonState = digitalRead(buttonPin);
 // if (buttonState == LOW) {
 //Serial.print("ok");
 //lcd.clear();
 // lcd.setCursor(0, 0);
 //lcd.print("Sending msg       ");
 // lcd.setCursor(0, 0);
 //lcd.print("Smart helmet      ");
 // checkGPS();
 // SMS(Mob);

 //helmet();
 checkGPS();
 lcd.setCursor(0, 1);
 lcd.print(stringGPS1);
 //Serial.println(stringGPS1);
}

/*
void helmet()
{
  buttonState1 = digitalRead(buttonPin1);
  if (buttonState1 == HIGH)
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SWITCH ON  .......    ");
    digitalWrite(relay, HIGH);
  }
  else
  {
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("SWITCH OFF .......    ");
    digitalWrite(relay, LOW);
  }
}
*/

void checkGPS()
{
  // Serial.print("check gps");
  // while (Serial.available())
  // {
  if (Serial.available()>0)
  {
   // c = Serial.read();
   // stringGPS  = c;
   //Serial.print(c);
   while (c != 'R')
   {
     c = Serial.read();
     // Serial.print(c);
   }
    // if (c== 'R')
    // {
    //   Serial.print(c );
         while(t!=41)
         {
           if (Serial.available())
           {
             c = Serial.read();
             stringGPS += c;
             t++;
             //Serial.print(stringGPS );
          }
  }
  stringGPS1= stringGPS.substring(15, 41);
  // Serial.println(stringGPS1);
  t=0;
  c=0;
  stringGPS = "";
    // }
  }
  }

void SMS(char Mob[20])
{
   digitalWrite(buzzer, HIGH);
   lcd.setCursor(0, 0);
   lcd.print("Sending msg       ");
   Serial1.print("AT+CMGS=\"");     // send the SMS number
   Serial1.print(Mob);/// Send mobile number
   Serial1.print("\"\r");
   delay(4000);
   Serial1.print(stringGPS1);// send the SMS Data
   Serial1.print("\r");
   delay(2000);
   Serial1.write(0x1A);  ///Ctrl+Z
   delay(1000);
   Serial1.write(0x0A);  ///Carrige return
   delay(1000);
   Serial1.write(0x0D);    ///line feed
   delay(1000);
   stringGPS1 = "";
   lcd.setCursor(0, 0);
   lcd.print("Smart helmet      ");
   digitalWrite(buzzer, LOW);
}

void Config()/////configuration for sim900
{
  delay(4000);
  Serial1.print("ATE0\r"); ////Disable Echo
  delay(4000);
  Serial1.print("AT\r"); ///checking echo
  delay(4000);
  Serial1.print("AT+CMGF=1\r");///msg format
  delay(4000);
}

```

when i run this code it give me error that serial1 was not decleared in the scope

# Answer
The only **SoftwareSerial** you a declaring is `SoftwareSerial mySerial(10, 11); // RX, TX` (And you you didn't use it afterwards).

If the hardware serials `Serial1`, `Serial2` or `Serial3` are available
(and already declared in the `arduino.h` header depends on the board you are using.
> 1 votes

---
Tags: softwareserial
---


title: What to do with Arduino floating pins?

text:
# Question
Title: What to do with Arduino floating pins?
I have some unused pins, should I connect them together and to the ground or leave them floating?

# Answer
> 17 votes
The simplest thing to do is set them to INPUT\_PULLUP. If you want a purely hardware solution then you could connect them to GND through some resistors (10kΩ or whatever you have in that kind of order of magnitude will do).

You don't want to just tie them directly to ground, and you don't want to link them directly together - that could lead to short circuits and dead IO ports if any of the pins happened to get set as output and HIGH in software.

# Answer
> 2 votes
I saw instability with a kiosk audio player I built years ago, when I left the unused pins floating. Once I grounded them through a 10k resistor, all was OK. This was in a very dry environment so I suspect static was the problem.

# Answer
> 0 votes
Leaving them floating in most cases won't do any harm. Even touching the pins won't destroy anything. Tying extra external hardware is just unnecessary (though a 10k resistor would be harmless as well). Of course, you could also think about potential extra usages for those pins if you want to make your design a bit "future-proof". For example, adding 4k7 pull-up resistors to A4 and A5 and a connector could allow you to use the I2C interface for additional functions.

---
Tags: pins, atmega328
---


title: Line not printing int in Serial Monitor

text:
# Question
Title: Line not printing int in Serial Monitor
I'm trying to make a kernel for a macro-key maker, this is the starting page's code:

```
char m[] = "What do you want to do? Type the following commands in this "
      "terminal:\nnew  --> Creates a new Keybinding\ndelete  --> Deletes a "
      "previous Keybind\nlookup --> Find what is bound to a key\n\nTurn off the "
      "switch to go back to the normal mode.";
Serial.println(m);
Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

```

When I run it, the screen displays:

```
What do you want to do? Type the following commands in this terminal:
new  --> Creates a new Keybinding
delete  --> Deletes a previous Keybind
lookup --> Find what is bound to a key

Turn off the switch to go back to the normal mode.

```

The last line is missing. Is this a problem with object casting? `takenKeybind` is an `int`.

# Answer
> 0 votes
You should never do this:

```
Serial.println(String(takenKeybinds) + "/64 Keybinds taken.");

```

Yes, it *should* cope with it and append the strings, but that's really nasty even if it does work. And there is absolutely no call to ever do concatenation when printing to serial.

Instead just use:

```
Serial.print(takenKeybinds);
Serial.println(F("/64 Keybinds taken."));

```

Note also the use of the `F()` macro when printing a string literal. This keeps the string in flash and prevents it being copied to RAM, which is just wasteful.

The same with your big long string - it's wasting RAM, and if you never want to modify it, why have it in RAM? Better is:

```
Serial.println(F("What do you want to do? Type the following commands in this terminal:"));
Serial.println(F("new  --> Creates a new Keybinding"));
Serial.println(F("delete  --> Deletes a previous Keybind"));
Serial.println(F("lookup --> Find what is bound to a key"));
Serial.println();
Serial.println(F("Turn off the switch to go back to the normal mode."));

```

---
Tags: serial-data, print
---


# Question
Title: Arduino NANO (CH340) error while flashing bootloader
Ok. So I'm close to tearing me hair out on this one.

I have a batch of cheap Arduino Nano clones, that just straight up won't work. (I HAVE gotten one of them to work, but I suspect that was by pure coincidence)

Anyway, I feel like I've tried everything to make them work. I am consistently getting

> Device signature = 0xffffff

errors from avrdude, which I believe is a hardware problem. Up til now I have tried:

* Installed CH340 drivers, no difference
* Tried to burn bootloader using Uno as an ISP (with 10uF cap between reset and ground!)
* Tried the "(Old Bootloader)" option in the IDE

All I have left is to desolder the entire board and troubleshoot each single component, but... no, I want to keep my sanity intact, thaaank you!

Any ideas on how I should move forward here?

# Answer
Hit reset randomly in the first few seconds of uploading/burning.
> 0 votes

---
Tags: arduino-nano, bootloader, avrdude, ch340
---