# Question
Title: NRF24L01 Transmission Problems between Arduino UNO and Arduino Nano
I'm a beginner in using NRF24L01 tranceiver module. I tried sending a simple "Hello world" using Arduino Nano and a Arduino UNO with the use of two NRF24L01 modules. I don't get any output in the serial monitor at the receiver side. I checked the wire connection numerous times. Also checked the baud rate of both receiver code and the serial monitor are same and adddresses of the tranceiver code and the receiver code are same. Looking for a solution. Thanks in advance.

This is my tranceiver code:

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}
void loop() {
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay(1000);
}

```

And this is my Receiver code:

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}
void loop() {
  if (radio.available()) {
    char text[32] = "";
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

```

# Answer
I had the same problem and when I tried the isChipConnected () function, it told me that one of the nrf24l01 was not connected to the SPI and I assumed that one was bad. I bought 2 nrf24l01 with antenas and they work well (mostly). ( Here is the link to the library reference. Also, make sure you are using the TMRh20 version of the library, This one. This is more updated and better as far as I'm aware.

Like everyone would suggest, try to solder a 10uF capacitor between GND and VCC (that module requires more power sometimes). And the last thing I tried was to use one of this socket adaptors for the 2 modules here to use the 5v output from the arduino since it can deliver more mA and thus the module can work better. This guide help me a little bit, I'll drop it here I don't see anything wrong in the code, but I'm a newbie like you so (It seems we are using the same adress in our codes)
> 1 votes

# Answer
@Erick Navarrte @dragonflyrobotics Thank you so much for your response, I've tried each an every option you've mentioned, but for an unknown reason it didn't work out for me. Then I researched more on and found out the NRF24L01 base module.This NRF24L01 base module help you to fix 8 pin NRF24L01 series RF module without any problem. And also this module comes with 3.3V regulator and a built in capacitor and easy pin connection to connect PIC or arduino. Using NRF24L01 module and NRF24L01 base module I was successfully able to transmit data.Thanks again for taking time in answering, highly appreciate it.
> 1 votes

# Answer
I use Chinese clone nRF24L01. It has very narrow voltage tolerance. My Arduino is also clone. The 3.3V output voltage was 3.27. The nRF24L01 was not working. I added a 3 terminal regulator between Arduino 5V output pin and nRF24L01. The voltage was 3.303V. Then nRF24L01 was working normally.

```
///////////////////////////////////////////////
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);
const byte rxAddr[6] = "00001";
void setup()
{
  radio.begin();
  radio.setRetries(15, 15);
  radio.openWritingPipe(rxAddr);
radio.stopListening();
pinMode(4,OUTPUT);
}
void loop()
{
  const char text[] = "Kawasaki_JP";
  radio.write(&text, sizeof(text));

  delay(1000);
}
////////////////////////////////////////////////

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);
const byte rxAddr[6] = "00001";
void setup()
{
  Serial.begin(9600);
  while (!Serial);
  radio.begin();
  radio.openReadingPipe(0, rxAddr);
   radio.startListening();
}
void loop()
{
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

////////////////////////////////////////////

```

library ; https://downloads.arduino.cc/libraries/github.com/TMRh20/RF24-1.4.0.zip
> 1 votes

# Answer
You can also try using the NRFLite library. It is a lot easier to use. Also make sure you have a minimum of 3.3V and 0.5A power at the radio pin. If not, it may not transmit.

Here is a TX and RX example of sending text using the NRFLite. It worked perfectly for me!

TX:

```
/*

Demonstrates sending and receiving packets of different length.

Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND

*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 1;
const static uint8_t DESTINATION_RADIO_ID = 0;
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket1
{
    uint8_t FromRadioId;
    uint8_t Counter;
};

struct RadioPacket2
{
    uint8_t FromRadioId;
    char Message[31];    // Note the max packet size is 32, so 31 is all we can use here.
};

NRFLite _radio;
RadioPacket1 _radioData1;
RadioPacket2 _radioData2;

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

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }

    _radioData1.FromRadioId = RADIO_ID;
    _radioData2.FromRadioId = RADIO_ID;
}

void loop()
{
    // Pick a number from 0 - 60,000.
    uint16_t randomNumber = random(60001);

    if (randomNumber > 30000)
    {
        // Send RadioPacket1.

        _radioData1.Counter++;

        Serial.print("Sending ");
        Serial.print(_radioData1.Counter);

        if (_radio.send(DESTINATION_RADIO_ID, &_radioData1, sizeof(_radioData1)))
        {
            Serial.println("...Success");
        }
        else
        {
            Serial.println("...Failed");
        }
    }
    else
    {
        // Send RadioPacket2.

        // Create a message and assign it to the packet.
        // Strings need to be converted to a char array and note they cannot be longer
        // than 31 characters since that is the size of _radioData2.Message.
        String msg = "Hello " + String(randomNumber);
        msg.toCharArray(_radioData2.Message, msg.length() + 1);

        Serial.print("Sending '");
        Serial.print(msg);
        Serial.print("'");

        if (_radio.send(DESTINATION_RADIO_ID, &_radioData2, sizeof(_radioData2)))
        {
            Serial.println("...Success");
        }
        else
        {
            Serial.println("...Failed");
        }
    }

    delay(1000);
}

```

RX:

```
/*

Demonstrates sending and receiving packets of different length.

Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND

*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 0;
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket1
{
    uint8_t FromRadioId;
    uint8_t Counter;
};

struct RadioPacket2
{
    uint8_t FromRadioId;
    char Message[31];    // Note the max packet size is 32, so 31 is all we can use here.
};

NRFLite _radio;
RadioPacket1 _radioData1;
RadioPacket2 _radioData2;

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

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }
}

void loop()
{
    // 'hasData' returns the size of the packet that was received, or 0 if there is no data.
    uint8_t packetSize = _radio.hasData();

    if (packetSize == sizeof(RadioPacket1))
    {
        _radio.readData(&_radioData1);

        Serial.print("Received ");
        Serial.print(_radioData1.Counter);
        Serial.print(" from radio ");
        Serial.println(_radioData1.FromRadioId);
    }
    else if (packetSize == sizeof(RadioPacket2))
    {
        _radio.readData(&_radioData2);

        String msg = String(_radioData2.Message);

        Serial.print("Received '");
        Serial.print(msg);
        Serial.print("' from radio ");
        Serial.println(_radioData2.FromRadioId);
    }
}

```
> 0 votes

---
Tags: arduino-uno, arduino-nano, nrf24l01+
---


title: Using OR with a while loop

text:
# Question
Title: Using OR with a while loop
I am trying to get two limits to or on the same while statement. Can this be done?

```
while (digitalRead (home_limit)) {

```

This works for one(1) limit, But when I try using two(2) limits is does not work. I can't find the proper configuration. I tried this.

```
while (digitalRead (home_limit1) || (home_limit2)) {

```

I also tried other combinations with no luck. Does anyone know how to do an or (||) statement with a while digital read?

# Answer
> 2 votes
`digitalRead()` is a function. It takes one parameter (the pin number) and returns the state of that pin. It's *that* return value that you want to OR with another. Which means you have to read the state of *both* pins, separately, and OR the results together:

```
while (digitalRead(home_limit1) || digitalRead(home_limit2)) {
    ....
}

```

---
Tags: arduino-uno
---


# Question
Title: How to properly handle the Arduino String
I've read that the Arduino String is bad as it causes memory fragmentation, so I try to avoid them mostly. But I still have some occurences where I'm not quite sure if they are ok after all.

The first is in print statements:
I have a function which prints a success or error message to the serial port, like so: `Serial.println("Success");`. Is this ok or should I (for example) pre define the String using `#define SUCCESS "SUCCESS"`?

Which leads me to the next case, defines:
I'm using MQTT and have the topics defined like above, e.g. `#define TOPIC_COLOR "light/color"`. Is this fine?

A third one is with ArduinoJSON:
I'm using Strings as keys, like so `lights["red"] = redVal;`. This call is made at multiple places so I assume the string would be created multiple times? A workaround/improvement I've thought of is using an enum defining the properties and using that as key.

Thanks for all comments, tips and explanations!

# Answer
> 2 votes
+1 to @majenko's comments. I tend to avoid the `String` class, as I like to know what is actually going on, and I stick to `char *` and `char []` in general (and the `stdlib` functions like `sprintf`, `strlen`, etc).

Couple of notes on your question:

1. `"foo/bar"` is fine. Some characters have special meanings in the C language itself, so you need to escape them with the `\`. For example if `"` was part of your literal string, you'd write `"foo\"bar\""`
2. I tend to use `ArduinoJSON` to *parse*. If my app is just *sending* JSON payloads, I just build it with `sprintf` or `print` which results in smaller programs. But, I guess it is a matter of choice. It is a great library.

---
Tags: string, memory, json
---


# Question
Title: Where is all of the Arduino Documentation?
Aside from the main website, I have noticed that it is hard to find documentation for specific Arduino add-ons, such as (This is just one example):

https://www.amazon.com/gp/product/B00OGYXN8C/ref=ppx\_yo\_dt\_b\_asin\_title\_o04\_s01?ie=UTF8&psc=1#descriptionAndDetails

Is this fairly normal or are you just expected to "just know what to do" with every Arduino component after a while? I realize that the IDE does have samples, but they don't always help.

# Answer
> 2 votes
> **Where is all of the Arduino Documentation?**

## Arduino

So far as I know, the Arduino name is owned by the Italian company Arduino AG.

Arduino AG provide documentation on the website arduino.cc for the products they manufacture.

Arduino AG have no responsibilities for documenting products designed and manufactured by other businesses.

## Other businesses

There are many other businesses that design and, in some cases, manufacture products that are designed to be compatible with or to work with products manufactured by Arduino AG. They don't need permission from Arduino AG unless they are using the trademarks or other intellectual property of Arduino AG. In addition, Arduino AG make many designs available under a permissive licence that does not give Arduino AG any control over or responsibility for documentation of cloned or derivative products manufactured or marketed by other businesses.

Examples include Adafruit, Sparkfun and many others.

These businesses provide documentation for the products they manufacture.

Some other businesses might choose to manufacture products without providing documentation or without providing documentation in English. For example a small Chinese manufacturer might only provide documentation in Chinese or provide none at all, expecting users to make use of documentation provided by the community or by the designer whose open-source designs they are using or whose proprietary designs their product is functionally equivalent to.

## Open Source Designers

Many hobbyists and small-scale makers provide documentation for use of their designs for products.

# Answer
> 5 votes
I'd like to add to what JRobert said of finding the information the "hard way"(i.e. looking into the datasheet of the chip it used, and understand how it works from schematic).

In the Arduino world, a lot of hardware/shields are so called Open Source Hardware, meaning that many companies can produce the same hardware with the schematic that is released under Open Source hardware license. China happened to be the country where it has the complete value-chain from components, to manufacturing and cheap labour. They are good in producing such products at large quantity and selling at low price, and they are not necessary good in developing original product, and certainly not in documentation (especially in English). These products are not necessary China "knock-off" as many people call it.

Since it is open hardware products, there are multiple vendors producing it and there are many information available on the internet, and take the example you provide, it is "1602 LCD Keypad Shield", and if your google it with this phase, you will soon find this pdf which is not exactly from the same company of your shield, but it is remarkably similar that you can try.

This applied to many hardware/shields that are available in the market. I hope this provide a general guidance and an "easy way" to find the information in your tinkering journey. Of course, if you want to learn more, go dig out the datasheet and schematic as JRobert mentioned.

# Answer
> 4 votes
To be fair, you're really talking about non-Arduino (capital-A) parts from a multitude of suppliers. And yes, the documentation varies in its depth, quality of translation if it wasn't originally written in English, and even availability at all. Taking the part you linked (from a retailer that storefronts for sellers (sometimes not in this country), who sell from component builders (often not in this country, who build with of parts from supplied factories definitely not in this country, ..., you get the idea. There may or may not exist any documentation specifically for this LCD/keypad combination shield.

But just by reading Amazon's seller's part description, I found that it consists of (at least) a 1602 LCD module and an HD44780 LCD controller chip, for both of which I can quickly find and download datasheets. The sixth image to the left of the description is a schematic of the board which shows that the left, right, up, down, and select buttons are 'multiplexed onto an output called AD0. I might have confirm that that is - or isn't - the Arduino's Analog-0 pin, but in any case, now I know what I have to write to decode which button was pressed from the board's analog output.

All this, and the part costs under US$7.00. For that price (and an assumption that these shields aren't being made in huge quantities), a maker couldn't possibly be able to create a custom datasheet for the shield as a whole, but they did supply a schematic, and their board's components are identified, and those components do, in fact have datasheets online.

Slightly awkward, perhaps, especially if one is thinking in terms of parts like MCUs such as the Atmega328 family, that *are* made in huge enough quantities that its datasheet runs to nearly 700 pages of engineering-ese. Still, the information is there and accessible, without requiring a way lot of digging.

That's part of being an experimenter.

# Answer
> 1 votes
With this particular board, you're quite fortunate in finding a supplier with an actual website and description: HiLetGo LCD1602 Input/Output expansion board LCD Keypad Shield for Arduino. The fact that the photos of the HiLetGo site show the DFRobot logo — the company that hcheung already referred to — shows just how radically open Open Hardware can get! In this case, DFRobot has pretty decent documentation: LCD KeyPad Shield For Arduino: SKU DFR0009 - DFRobot — but even they don't link to the official LiquidCrystal documentation, but a much older archived version.

The Arduino team admits that they “… never entirely got to grips with Arduino documentation”. Their own "Find in Reference" tool in the IDE will sometimes dead-end to error pages on the arduino.cc site. For example, "find in reference" for *Serial* will take you to a local copy of the documentation that has broken links for the Arduino Leonardo documentation.

It's not always the case, but typically if an Arduino shield costs less than $10 on Amazon then the cost of "just know\[ing\] what to do" is passed on to you, the user.

---
Tags: arduino-ide, documentation
---


# Question
Title: Weight scale with Arduino: calibration step
I'm not an expert about Arduino and I'm studying to create a project related to the bees remote monitoring.

I would like to monitor the internal humidity and temperature and the weight of the beehive boxes.

About the weight parameter my idea is to make a structure with 4 load cells.

I watched some video tutorials related to the creation of a weight scale with Arduino. I saw that it's necessary to calibrate the scale without any weight on the scale every time that Arduino will be started.

I'm not able to understand if there is a way to have this calibration in a different way: I mean, I will place the beehives on my weight scales only one time and Is not possible to remove and put them back for each calibration step.

Is it really necessary or is there a way to have the calibration with the weight on the scales also?

# Answer
> 1 votes
It may be that in this application (beehive monitoring) it is not required to re-calibrate your load sensors before each use. When a person is observing a scale to measure their own weight they will be sensitive to the scale reading zero before each use. Even though being, say, a lb off is likely less than a 1% error when measuring their total body weight. This site talks about load cell calibration and "recommends a yearly recalibration interval". They also talk about temperature compensation.

As temperature and humidity will be monitored. And nonlinear load sensor response to weight can be compensated in software, consider testing your setup under different conditions to determine what considerations need to be taken into account to provide the desired accuracy.

This image is from https://www.futek.com/load-cell-calibration-services

# Answer
> 0 votes
What I can find about calibrating load cells is that they are subject to "electrical influence, mechanical effects, instrumentation faults and loose cables etc."

In the case of beehives, I'd add temperature, water, ice, snow, dirt & dust, and debris from the bees. The calibration suggestions I found were to calibrate "periodically", which suggests to me that the suggestion to calibrate at every startup assumes that the calibration will be lost at every power-down. That does not have to be the case - it can be store in a non-volatile memory such as EEPROM.

What I do think you'll need to do is calibrate each cells at 0%, 10%, ..., etc., of its full load, probably to 120% or 130% to allow for wind loading and asymmetric loading within the hive, and at a range of temperatures, make a set of force vs. cell output and temperature, from which to interpolate to get the 4 partial hive-weights.

They probably will need to recalibrated periodically, but for your application, a tare-value, measured at a reproducible hive condition, may be sufficient, if all you need is a differential weight.

---
Tags: arduino-mega
---


# Question
Title: Arduino Due - wireless programming via Xbee
I would like to integrate an Arduino Due into a project, which probably will evolve over time and will need some re-programming. Instead of having to disconnect and pull out the Arduino Due out from the enclosure, I was wondering whether it can be set up for wireless programming via an Xbee in a similar way as for the Arduino Fio (like described here: http://arduino.cc/en/Main/ArduinoBoardFioProgramming).

Has anyone tried that already or succeeded doing that?

# Answer
> 1 votes
Theoretically, it is possible I have not tried to do it on an Arduino but I did work something similar with a pic controller. Usually, when we program the board with the firmware file we break the firmware file and send it as multiple packets over the serial com port to be written to on a certain flash memory location on the controller.

In your case, you can try an experiment by using 2 XBee modules that are connected together with the appropriate channel and network ID settings wirelessly. connect one XBee to your computer using a serial to USB cable. On the Arduino side, you have to connect to power it and use the second XBee to connect to it on the UART port. This way the XBee acts as a simple wireless data transfer channel to send and receive data wirelessly (if I am right this should be achievable in the transparent mode on XBee).

One thing to note is to check the Arduino schematic to see how exactly the data over USB is sent to the controller. If it is on UART then this should work straightforward if not then you may have to figure out something else for it.

---
Tags: arduino-due, xbee
---


# Question
Title: Wirelessly (but fast) transfer STEP and DIR output from Arduino to stepper driver
**Very short version:** Looking for a way to wirelessly get STEP and DIR signals (only those two signals) from an Arduino to a DRV8825 stepper driver about a meter away:

`Arduino -> STEP and DIR IO pins -> transmitter ) ) ( ( receiver -> DRV8825`

***edit Jan. 2024**: Just to follow up on this; in the end I decided to simplify the whole setup I had, and moved all electronics, except for the power supply, to the moving part. A custom slip ring connects a PSU that is on the floor to the rotating platform that holds the Arduino, steppers, etc.*

**Long version:** For a project I've mounted an Arduino to a wooden board. The Arduino has a GRBL shield (basically a breakout board to four motor drivers for stepper motors (in my case the DRV8825)). Connected to this setup is a stepper motor. The power supply (NOT on the wooden board) for the motor is 24v, and I'm using a buck converter to take it down to 5v for the Arduino. This whole board is rotating and the 24v gets passed to it using a custom sliding-contact with two contacts (24v and gnd).

Now this all works fine, but the problem is this: I have a second motor which I want to control from the same GRBL shield. But this motor is NOT on the rotating board. If I place the motor driver next to this motor and power it from the same power supply (parallel to the sliding-contact) I have everything I need, except for the STEP and DIR signals from the Arduino.

Because there is no way I can add 2 more contacts to the sliding-contact (plus the signal would probably be too noisy anyway) I'm looking for a way to basically add a wireless bridge between the STEP and DIR output pins on the Arduino, and the STEP and DIR input pins on the motor driver. The motor and driver are about a meter away from the Arduino, so signal strength shouldn't be a problem.

I believe those well known 433Mhz transmitters are too slow for something like this, but I read most nRF24L01 modules are faster. Before I order some for a test setup, I was wondering if anyone already knows if this could work or not, knows a useful alternative, or has some suggestions for keywords to search for when trying to find another solution. I can find a lot of 'wireless' motor drivers online, but most are completely standalone units where the microcontroller is on the board, it's just controllable over wifi/bluetooth.

# Answer
> -1 votes
(Moved to "answer" for space; it's definitely not an answer. Sorry all!)

Minor points:

* It's a motor controller shield; the GRBL is on the Arduino.
* You'll need a motor controller at each motor; not clear if that's understood.
* I'd also consider optical comms, although it has a different set of problems.

Ultimately I might approach this in a different way: instead of a single GCode box attempting to synchronize and control itself and an (essentially) independent system, I'd consider having a single GCode box (GBOX) controlling two independent systems (M1, M2).

GBOX would be a laptop/RPi/whatever that processes the "real" GCode. Based on the GCode commands, which in the end just tell motors what to do, I'd send each GCode command to its associated M1/M2 system.

How well this works depends a lot on the GCode, however; diagonals, arcs, etc. require motor cooperation, so a command like `G02 X2Y0 R2` might cause problems, even though we can pull out the `X` and `Y` data. How the GCode is generated matters, but note that GBOX could also interpolate "tricky" commands to break them into something a dual-target system might be able to understand.

The "meaning" of the moves also matters: there's "getting from one place to another" and "getting from one place to another while drawing a line": the former may (or may not) have requirements around what that actually means, while the latter requires coordinated motion, and even if you're splitting the commands up correctly, even a fraction of a second difference in receive/action time will matter. Of course, you could also transmit both motors' commands to both motors and rely on timing or cross-M*n* synch for starting their respective commands.

In the end it may be the only real way to make this work would be to have the "independent" systems be able to synchronize *with each other*, so that they know they're (a) ready to start, and (b) starting at the same time. GBOX could also potentially handle that synchronization as a "Go!!!" command is about as deterministic as it gets, especially if M1/M2 can receive a broadcast signal at the same time.

https://www.zikodrive.com/motor-control-case-studies-and-applications-2/a-remote-controlled-and-synchronised-stepper-motor-controller/ (very) briefly discusses the issues around synchronizing remote motors where their relative positions matter.

---
Tags: motor, pins, wireless, wires, stepper-motor
---


# Question
Title: Conditional compilation depending on sizeof(double)
Is there a macro (#define ...) somewhere in the bowels of Arduino IDE or core header files which tells me at compile time(!), if the `double` data type for a given platform/board is a true double precision floating point number (64 bit width) or "only" an alias for a single precision float (32 bit width)?

With Arduino, both can be the case. 8-bit AVR boards have `double` equal to `float`, ARM-based boards (like Arduino Zero) support "true" double precision.

I am working on a library which implements some bit-banging of floating point numbers (both single and double precision). Due to the low-level nature of the problem, there must be separate functions for `float` and `double`. I would like to do somthing like that:

```
uint32_t function_for_float(float f) {
    // function body here...
}

#if defined(HAS_64_BIT_DOUBLE)
uint64_t function_for_double(double d) {
    // function body here...
}
#endif

```

That way, a compile time error would be generated if somebody tried to use the "double" version on platforms which do not support the "true" double data type. I *want* the compiler error to be generated, because `function_for_double()` will do silently "the wrong thing" when fed a single precision float, leading potentially to difficult-to-debug problems.

Right now, I am defining a macro constant for every relevant board I own, like this:

```
#if defined(ARDUINO_SAMD_ZERO) \
 || defined(SAMD_FEATHER_M0_EXPRESS) \
 || defined(ADAFRUIT_FEATHER_M4_EXPRESS)
    #define HAS_64_BIT_DOUBLE
#endif

```

But this is ugly and not future-proof (new boards can/will become available...).

Any suggestions?

# Answer
The `double` data type is almost universally 8-bytes long, so you could simply

```
#if !__AVR__
# define HAS_64_BIT_DOUBLE
#endif

```

Gcc provides a more specific macro though: `__SIZEOF_DOUBLE__`, which has the same value as `sizeof(double)`. But I do not know whether it is provided by other compilers.
> 4 votes

---
Tags: arduino-ide, compile, data-type
---


title: HG-C 1100 measurement sensor

text:
# Question
Title: HG-C 1100 measurement sensor
I am using two HG-C 1100 measurement sensor for measuring the width of the metal. In the top of the sensor I will be having the measurement value. The sensor is capable of measuring the dimensions from -35mm to 35mm. So I am using the formula:

```
int First_sample = analogRead(6);
int Second_sample = analogRead(7);
float First_sensor = (map(First_sample, 1023, 0, -3500, 3500) / 100.0);
float Second_sensor = (map(Second_sample, 0, 1023, -3500, 3500) / 100.0);
Serial.print("First_sensor:");
Serial.println(First_sensor, 3);
Serial.print("Second_sensor:");
Serial.println(Second_sensor, 3);
Final_sensor = (First_sensor - Second_sensor);
Serial.println(Final_sensor, 4);

```

If I use this code, I will get the proper width of the metal. But when I place the metal in between the sensor, I am getting the exact width in the serial monitor. But at the top of the sensors the values are different. I don't why the analog values are different on the serial monitor and the top of the sensors. But the output of the sensor is perfect in the serial monitor. Can anyone help me with this?

# Answer
> -1 votes
The HG-C1100 has a resolution of 70 μm (= 0.07 mm) over a measuring range of 70 mm. You quote errors of 0.28 and 0.38 mm, which is worse than can be expected (±0,07 mm). The resolution is 1‰ of the measuring range. Therefore the 10 bits range (1024) of the Arduino's Analog-Digital Converter (ADC) is sufficient.

You map the ADC output of 0-1023 to a range of -3500 to +3500 which results in a value in 0,01 mm. Then you divide by 100.0 resulting in a value in mm.

According to Arduino's Reference the function map() uses integer arithmetic, but the arguments are longs and the calculation order is such that maximal accuracy is maintained. This provides sufficient accuracy for this purpose. I am only not sure if you constants should be post fixed wit an "L".

So far everything looks all right.

The errors you mention correspond to about 5 counts of the ADC. I assume the solution lies in taking measures to prevent noise entering your signals (signal conditioning).

Addition:
When you read the same sensor repeatedly do you get stable readings? You could try to use an average over multiple readings. Did you look at the signal(s) with an oscilloscope?

---
Tags: arduino-uno, sensors, arduino-nano, shift-register
---


# Question
Title: Saving Arduino output to a text file in append mode
I used the code below to save output from an Arduino Uno to a text file.

The problem is whenever I run the code the old data in the text file is deleted.

I don't want the old data to be deleted, what should I change?

```
import processing.serial.*;
Serial mySerial;
PrintWriter output;
void setup() {
   mySerial = new Serial( this, Serial.list()[0], 9600 );
   output = createWriter( "data.txt" );
}
void draw() {
    if (mySerial.available() > 0 ) {
         String value = mySerial.readString();
         if ( value != null ) {
              output.println( value );
         }
    }
}

void keyPressed() {
    output.flush();  // Writes the remaining data to the file
    output.close();  // Finishes the file
    exit();  // Stops the program
}

```

# Answer
There are a couple of ways to append to a text file.

1. You can either read the entire file in a temporary variable, then append the new data to it and then write to file.
2. you can implement using printWriter instead like mentioned here: https://processing.org/discourse/beta/num\_1267767630.html

Let me know if it works.
> 1 votes

---
Tags: processing-lang
---


title: Motor not switching with 2N3904

text:
# Question
Title: Motor not switching with 2N3904
I have a small motor, it powers fine from the 3V3 and GND output of the arduino nano ble 33. However I need to be able to switch it on and off. My first attempt was to use an output pin, but that doesn't supply enough power. I'm trying to use a 2N3904 transistor (my first time attempting to use one, so sorry if I've done something stupid). I've tried wiring it as follows, but no luck:

Is this possible, or do I need something more substantial like a reed switch?

# Answer
> -1 votes
* 1st : you have to put an appropriate resistor between the output of your arduino and transistor Base pin
* 2nd : you have to connect you motor and biased transistor to \>\>\>\> a suitable power supply (which has enough current (Amps) on it's output)

you can use this circuit instead of yours :

* 3rd : don't forget to use the diode in the schematic; it protects transistors from you motor coil's spikes you can use 1n4147 ( it depends on the size of your motor but i think, it works for you ( i wasn't successful to take a look at your motor and it's specifications )
* 4th : ignore the number of transistor, you can use your transistor (2N3904) instead of it
* 5th :NOTICE : this circuit has a problem, you have to connect appropriate power supply and replace "arduino 5 volts" by the + of your power supply in this circuit schematic

good luck

---
Tags: motor, transistor
---


# Question
Title: Customizing system settings with defines?
I have written a library that contains a statically allocated buffer (f.g. `struct taskList proc[TBL_SIZE];`)

TBL\_SIZE is a macro currently defined in my .h file.

I have heard that there's a way to set or reset the define statement inside the .ino file to customize this setting for some libraries, but I don't know how to do this myself, and by the time I realized that this was a problem I had forgotten what library allowed this setting.

This would be extremely useful as currently I have to edit my library every time I build a new project (or worse, am working on several at once with different settings).

My guess was a variant on an include guard, like this

```
#ifndef TBL_SIZE
#define TBL_SIZE 16 /*(or whatever)*/
#endif

```

block, but that failed to work. I tried it during a final project, so my memory is fuzzy from lack of sleep (and time, now), but I'm fairly sure I got an "undefined" error.

I don't know what this is called to search for it otherwise, so I'm hoping someone can help.

---

Here is more information about my specific issue:

In my .h (at the top, after the regular include guard):

```
#ifndef TBL_SIZE
#define TBL_SIZE 16
#endif

```

(Note that everything works if I just set this directly without the defines)

Further down the .h, inside my class:

```
struct task processes[TBL_SIZE];

```

In the main .ino file before the library includes:

```
#define TBL_SIZE 6
#include <CoRTOS.h>

```

---

Debug output of the build (I know from experience it built with 16 instead of 6 entries in that table from the memory size. The low memory warning is another big clue.)

```
Linking everything together...
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\sketch\\ECE554_ASP.ino.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\CoRTOS\\CoRTOS.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\glcdfont.c.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\Adafruit_GFX.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\Adafruit_GrayOLED.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_GFX_Library\\Adafruit_SPITFT.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_BusIO\\Adafruit_BusIO_Register.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_BusIO\\Adafruit_I2CDevice.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_BusIO\\Adafruit_SPIDevice.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Wire\\Wire.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Wire\\utility\\twi.c.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\Adafruit_SSD1306\\Adafruit_SSD1306.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\SPI\\SPI.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761\\libraries\\SparkFun_BME280_Arduino_Library-master\\SparkFunBME280.cpp.o" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/core\\core.a" "-LC:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761" -lm
C:\Users\rdrag\Documents\Arduino\libraries\CoRTOS\src/CoRTOS.h:38:7: note: array types have different bounds
 class cortos_class {
       ^
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.eep"
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf" "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.hex"
Multiple libraries were found for "Adafruit_GFX.h"
 Used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_GFX_Library
 Not used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit-GFX-Library-master
Multiple libraries were found for "Adafruit_I2CDevice.h"
 Used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_BusIO
 Not used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_BusIO-master
Multiple libraries were found for "Adafruit_SSD1306.h"
 Used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_SSD1306
 Not used: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_SSD1306-master
Using library CoRTOS at version 0.2.0 in folder: C:\Users\rdrag\Documents\Arduino\libraries\CoRTOS
Using library Adafruit_GFX_Library at version 1.10.7 in folder: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_GFX_Library
Using library Adafruit_BusIO at version 1.7.3 in folder: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_BusIO
Using library Wire at version 1.0 in folder: C:\Users\rdrag\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3\libraries\Wire
Using library Adafruit_SSD1306 at version 2.4.5 in folder: C:\Users\rdrag\Documents\Arduino\libraries\Adafruit_SSD1306
Using library SPI at version 1.0 in folder: C:\Users\rdrag\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.8.3\libraries\SPI
Using library SparkFun_BME280_Arduino_Library-master at version 2.0.9 in folder: C:\Users\rdrag\Documents\Arduino\libraries\SparkFun_BME280_Arduino_Library-master
"C:\\Users\\rdrag\\AppData\\Local\\Arduino15\\packages\\arduino\\tools\\avr-gcc\\7.3.0-atmel3.6.1-arduino7/bin/avr-size" -A "C:\\Users\\rdrag\\AppData\\Local\\Temp\\arduino_build_258761/ECE554_ASP.ino.elf"
Sketch uses 28172 bytes (91%) of program storage space. Maximum is 30720 bytes.
Global variables use 1609 bytes (78%) of dynamic memory, leaving 439 bytes for local variables. Maximum is 2048 bytes.
Low memory available, stability problems may occur.

```

# Answer
> I have heard that there's a way to set or reset the define statement inside the .ino file to customize this setting for some libraries, but I don't know how to do this myself

There are many ways to achieve what you want, you might not even need the `#ifndef` macro, use your library class construct to allow user to pass in the list size as an argument and but set the argument with a default value.

**YourLibrary.h**

```
class YourLibrary
{
private:
  size_t _userSize;
public:
  YourLibrary::YourLibrary(size_t listSize = 16) {
    _userSize = listSize;
  }
  ...
}

```

**User's sketch .ino**

```
#include <YourLibrary.h>

#define LIST_SIZE 32;

YourLibrary instance(LIST_SIZE);  // instance() would set the _listSize to 16

setup() {

}

loop() {

}

```
> 1 votes

---
Tags: library
---


# Question
Title: How to I make the Tx and Rx pins on an ESP-8266-01 into GPIO pins?
When programming an ESP-01 with Arduino IDE, how can I make the Tx and Rx into a generic I/O pins reliably? I think there's a command to swap the Tx and Tx with other pins. I tried `serial.swap()` but it didn't work. So how to get done with Arduino IDE or is it even possible?. I am using an ESP-01, which means there will be four GPIO pins once this question in answered.

I want to achieve same as in the video, How to add more GPIOs to ESP8266 (ESP-01), but without soldering wire.

# Answer
Add this to your code at the beginning of set `void setup()`:

```
//********** CHANGE PIN FUNCTION  TO GPIO **********
//GPIO 1 (TX) swap the pin to a GPIO.
pinMode(1, FUNCTION_3);
//GPIO 3 (RX) swap the pin to a GPIO.
pinMode(3, FUNCTION_3);
//**************************************************

```

You will no longer be able to use the Serial Monitor as TX will now be a GPIO pin and not transmit Serial data. You can still Flash your device as when you boot the device in flash mode it converts GPIO1 and GPIO3 back to TX/RX. Once you reboot into regular running mode GPIO1 and GPIO3 will go back to being GPIO pins.

To change GPIO1 and GPIO3 back to being TX/RX for regular Serial Monitor use add this to your code at the beginning of set `void setup()`:

```
//********** CHANGE PIN FUNCTION  TO TX/RX **********
//GPIO 1 (TX) swap the pin to a TX.
pinMode(1, FUNCTION_0);
//GPIO 3 (RX) swap the pin to a RX.
pinMode(3, FUNCTION_0);
//***************************************************

```

If I understand the ESP-01 correctly the pins CANNOT be both TX/RX and GPIO pins at the same time.
> 20 votes

# Answer
Tx = GPIO 1

Rx = GPIO 3

Should work but be careful cause if they burn, you won't be able to program or even talk to the ESP anymore.
> 5 votes

# Answer
To work TX RX as GPIO Serial.begin() must be deleted from code.
> 3 votes

# Answer
Maybe a little late but it might helps someone else.

ESP-01 GPIO pins (1&3)
> 1 votes

# Answer
One thing I noticed is that if you're trying to use the Tx/Rx pins for the main serial comm (1 & 3) as a GPIO then you must not use any Serial commands in your code, such as Serial.begin.

I was having my GPIO digital reads randomly read high (they had their mode set as INPUT\_PULLUP) while I had a source pulling them low (I verified that input was indeed pulled low while the ESP8266 digitalRead was reading high)

Removing all Serial commands (begin, print and println) fixed that for me.
> 1 votes

---
Tags: esp8266, ide
---


# Question
Title: How esp8266 gets response from server..?
```
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200);
  delay(2000);
}

void printResponse() {
  String s="";
  while (ESP8266.available()) {
    s+=ESP8266.readStringUntil('\n');
  }

  Serial.println(s);
  // now here you can parse and look for "+IPD" look for another line ending (if there is) and then extract the numeric value.
}

void loop() {

  ESP8266.println("AT+CIPMUX=1");
  delay(1000);
  printResponse();

  ESP8266.println("AT+CIPSTART=4,\"TCP\",\"www.tcpss.000webhostapp.com\",80");
  delay(1000);
  printResponse();

  String cmd = "GET /test.html HTTP/1.1";
  ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
  delay(1000);

  ESP8266.println(cmd);
  delay(1000);
  ESP8266.println();
  delay(1000);
  printResponse();

  delay(5000);
}

```

i have run this code and i am able to get this response from server like "+ipd 4,41".... what does it mean? here is the response after run the code in arduino......

```
WIFI GOT IP
AT+CIPLUX=1

OK
AT+CHPSTART=4,"TCP","www.tcpss.000webhostapp.com",80

4,CONNEC
AR)CR5NB⸮b⸮⸮k

j⸮L⸮⸮
Recv 27 bytes

SEND OK

+IPD,4,41

```

Thanks in advance.....

# Answer
There's two things to know here:

1. You're seeing corruption in your output because SoftwareSerial is not capable of working reliably at 115200 baud. You need to reconfigure your ESP8266 to operate at a lower baud rate (such as 9600) to be able to use it with an Arduino that doesn't have enough physical UARTs.
2. The response `+IPD,4,41` is telling you *about* the response. It's not itself the response.

It means "IP Data on channel 4 of length 41". It is then your responsibility to request that data from the ESP8266 using whatever AT command the ESP8266 requires.

Personally I would scrap the AT firmware and program the ESP8266 directly. That way you solve both problems: you can choose what baud rate to communicate at (if you even need to communicate to an Arduino at all), and you have no AT commands to parse or craft. It is a far more efficient way of working with the ESP8266 that trying to fudge things with the AT firmware and an Arduino.
> 1 votes

# Answer
`SoftwareSerial` does not works well for baud rate higher than 9600bps, you need to change your Arduino and ESP8266 to operate at 9600bps.

1. Use the `AT+UART_DEF=9600,8,1,0,0` to set the ESP8266 to 9600Baud, with 8 bit, 1 stop bit and no parity. And also remember to configure the Arduino accordingly. The AT command with \_DEF suffix means it will only need to be set once and the configuration will be saved in the ESP8266. ESP8266 AT Command Set would be handy when programming the ESP8266 with AT Commands.
2. Add longer delay after sending `AT+CIPSEND` and `Get` request as those network activities sometime take longer time to establish.
3. The `+IPD,4,41` means that Connect 4 (which you established with `AT+CIPSTART` is connected and there are 41 bytes payload waiting to be read. You can refer to ESP8266 AT Command Examples for more information.
> 1 votes

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


title: Read from lux hangs in bright light

text:
# Question
Title: Read from lux hangs in bright light
I am using VMEL6040 sensors and occasionally under bright light the read can hang, rather than using a wdt to recover I would like to ask some questions about the library.

as for debugging the sensors run stabley (several days at reads every 250 ms) in low light, but over 6k lux they can crash.

I am using wire.h here

in the header

```
TwoWire *_i2cPort;

```

the read value calls the ReadRegister function:

```
uint16_t SparkFun_Ambient_Light::_readRegister(uint8_t _reg)
{

  uint16_t _regValue;

  _i2cPort->beginTransmission(_address);
  _i2cPort->write(_reg); // Moves pointer to register.
  _i2cPort->endTransmission(false); // 'False' here sends a restart message so that bus is not released
  _i2cPort->requestFrom(_address, static_cast<uint8_t>(2)); // Two reads for 16 bit registers
  _regValue = _i2cPort->read(); // LSB
  _regValue |= uint16_t(_i2cPort->read()) << 8; //MSB
  return(_regValue);

}

```

is there a reason they are not checking the return of the `_i2cPort->endTransmission(false);`call? I am wondering if I should check that and not call the `requestFrom` if it does, i.e.:

```
uint16_t SparkFun_Ambient_Light::_readRegister(uint8_t _reg)
{

  uint16_t _regValue;

  _i2cPort->beginTransmission(_address);
  _i2cPort->write(_reg); // Moves pointer to register.
  if (_i2cPort->endTransmission(false) == 0) { // 'False' here sends a restart message so that bus is not released
      _i2cPort->requestFrom(_address, static_cast<uint8_t>(2)); // Two reads for 16 bit registers
      _regValue = _i2cPort->read(); // LSB
      _regValue |= uint16_t(_i2cPort->read()) << 8; //MSB
      return(_regValue);
  }
  else
      return 0;
}

```

Or could my error be from the static casting do int?

# Answer
so I think I got it, the problem was that on a fail wire.read() returns an int -1 when that gets converted to a unint16 its a big number then it gets left shifted and overflows

the solution was:

```
uint16_t SparkFun_Ambient_Light::_readRegisterLight(uint8_t _reg)
{
    int lsb;
    int msb;

    _i2cPort->beginTransmission(_address);
    _i2cPort->write(_reg); // Moves pointer to register.
    if (_i2cPort->endTransmission(false) == 0) { // 'False' here sends a restart message so that bus is not released

        unsigned long tstamp = millis();
        while ((_i2cPort->available() < 2) && ((millis() - tstamp) < 10));

        if ((_i2cPort->available() < 2)) {
            _i2cPort->requestFrom(_address, 2); // Two reads for 16 bit registers
            lsb = _i2cPort->read(); // LSB
            msb = _i2cPort->read(); //MSB

            if ((lsb >= 0) && (lsb <= 256) && (msb >= 0) && (msb <= 256)) {
                _regValue = lsb + msb * 256;
            }
        }

        return(_regValue);
    }
    else
        return _regValue;//last read
}

```

This contains some extra error handling I added, but will leave in such as:

1. timeout on waiting for a response
2. checking on properly closing the bus in end transmission
3. checking for errors from the read

I didn't do error handling as I would need to rewrite the whole library, and for my application repeating the last reading is sufficient.
> 1 votes

---
Tags: i2c
---


# Question
Title: Differential voltage measurement using Arduino
I have a electrolysis cell in which the anode is hanging using a Structure in a electrolyte. The cathode is at the bottom of the cell with electrolyte above it and anode being dipped into this electrolyte (not completely, a portion of the anode is dipped). The cell operates at 7 volts DC and 90000 amperes of current flowing through it. This is a typical electrolysis process of producing aluminium from alumina powder in a aluminium smelter. The cell is called a pot. Now the question is I need to measure a potential drop on the anode rod. We usually take a meter to measure the potential drop on the anode rod and typically the reading are in millivolts. As the readings are in millivolts, it just indicates the drop in rod voltage due to resistance of rod. Now can I measure this millivolts drop using Arduino provided the voltage at one point of anode is 5 volts with respect to ground and the voltage at the other point is 4.95 volts with respect to ground, however the difference between these voltages is 0.5 volts and this is voltage I need to measure using Arduino and some arrangements as add on to it. How can I do this? Can anyone help. If you want more details, please comment. I will also provide more details.

So far I have done is tried measuring 1.5 volts on a pencil cell using Arduino by connecting A0 analog pin on Arduino to positive directly to the positive of 1.5 volts battery and ground of Arduino to the negative of Arduino.

Can I do the same for this millivolts measurements? I understand that the ground of Arduino and the 2nd point of anode measurement will not be at same potential, so shouldn't be connected together. I am scared to burn my board, so didn't try practically and wanted to get some opinion.

# Answer
As you do it with the multimeter: connecting ground to the lower potential (4.95 Volts in your example) and the volt probe to the higher potential (in your case 5.0 V), you can also connect the Arduino between the two potentials: Arduino GND to the lower (!) potential and A0, A1, ... or A7 to the higher (!) potential.

As long as you use the correct polarisation and the difference between the potentials is less than VCC of the ADC (5V Arduino ADCs) you should be save.

The resolution of the Arduino might be a problem. I don't know what resolution you need; 5V divided by 1024 is about 5 mV per step.

You might want to provide a reference Voltage at Vin of -let's say- 1 Volt if you need a better resolution. That would improve the resolution to about 1 mV per step. But then the meassured voltage must no exceed the 1 Volt reference voltage.

**EDIT (Gerben's comment)**

You could use the 1.1V internal reference of the ATMega328P (analogReference(INTERNAL))

And please let me give you a security advice: If the resistence in any part of your meassuring setup is significantly lower than the resistance between the messuring points (e.g you shorten the probe wires), then there is a chance that 90000 A running through this setup. That could burn away your hand, arm or even your life. Amperes kill; not Voltage. I've seen a wrench that was vaporized (ok, melted, ok glowing ;-) ) in a second, when it had fallen between the poles of a car battery (12 V; 300 Amps). An you operate with 90000 Amps. !
> 1 votes

# Answer
This is obviously a significant project, not something to economize on. I would recommend you use a separate difference amplifier to get a single-ended output referenced to the Arduino ground and scaled to maximize the 10-bit range use. The diff amp can use its own supplies (+/-7.5 or +/-15, say) with the ground tied to the Arduino ground. That way the Arduino only sees the difference, never the full 7 V no matter what.
> 1 votes

---
Tags: arduino-uno, voltage
---


title: Arduino Pro Micro not recognized by PC

text:
# Question
Title: Arduino Pro Micro not recognized by PC
so I've got myself a Arduino Pro Micro ATmega32U4 5V 16MHz and my PC (Win10 64bit) won't recognize it. So, after I firstly plugged it in, it was detected as a Leonardo, rather than a Pro Micro, afterwards I installed hte drivers as noted by Sparkfun, and added the board to the IDE. Afterwards, my Arduino got detected as an unknown device where I can't use it anymore. I tried installing the drivers as given by sparkfun over the "unknown device" and no luck by trying, I always get an error saying that Windows has already the best drivers for it already installed.

And later, I uninstalled the "uknown device" in hope that it will re-install itself upon pluggin it back it, and it actually disappeard totally and got repalced by "Unknown USB Device (Device Descriptor Request Failed)" under USB controllers in the Device manager.

And I'm stuck here. In the IDE, the Pro Micro is detected as being on "COM1" no matter what COM port it really is, or is it even plugged it at all. Uploading a code results in the bar being filled up and "Uploading..." message, while maybe after a few minutes a very long error pops up without anything specific since you can plug out the board and get the same error.

I also tried a different PC with Windows 7 64bit on it, and instead of getting recognized as a Leonardo, this time it came straight to becoming a "Unknown device". I tried installing drivers multiple times with no luck, also again tried manually overiding the drivers in the Device manager and it always says that the best drivers are already installed.

I'm really stuck here. Pics of the board: https://postimg.cc/gallery/rwCDRfv

# Answer
It was wrong of you to try and install the driver as this board SHOULD be recognized as Leonardo. I would try to reinstall the Arduino IDE, it will also reinstall the drivers (hopefully)
> 2 votes

# Answer
I got similar problem, I was trying to burn some HEX files and somehow, my windows wasn't able to recognize my atmega32u4 anymore, not even in Device Manager. I found that the bootloader was "bricked", and to fix it, you need to burn a valid HEX file, like the simplest led blink code. I've done that by the prompt command, using avrdude. So you reset twice, and you have 8 seconds to upload the hex file. It's faster doing that with prompt command than arduino software. After I uploaded the LED blink code successfully, the windows naturally recognized my atmega32u4 instantly, I could identify it in Device Manager as PCOM 4 since then. So you need to revive your bricked atmega's bootloader. I guess there's nothing to do with the drivers in this case.
> 2 votes

---
Tags: usb, arduino-pro-micro
---


# Question
Title: Looking for an accurate and fast updating range sensor
I need to purchase a distance sensor that will be fixed in place and used to determine distance to the top of a fairly fast moving piston along the axial direction in line with the sensor. The top of the piston can be covered in whatever material works best for sensor accuracy, and the entire apparatus can operate in the dark if needed. Distance will range from 50mm to 500mm. Position measurement must have an accuracy range below 1.5mm. Update rate must be 1000hz or greater (i.e. update every 1ms or faster).

I see there are many options for me at high cost, but I'm limiting my budget to $500 and below for the next few days while I research more. This does not mean I won't spend whatever is needed however. As of now I've seen nothing acceptable for under that price, but it's hard to tell as many companies won't publish prices for these types of sensors.

I'm happy to explain more about the implementation if needed.

## UPDATE

I wish more people were reading this post, because I have great suggestions for DIYers after researching a lot of options the past few days. Currently I'm looking at offerings from Turck.com relating to reading a magnetized strip. This would read position from the side rather than from above or below as I describe in my original question. Turck calls it their "LM-2 line" and some options look pretty affordable and quite a bit under $500. Here's a brochure they provide - it documents how they read a magnetic strip: https://www.turck.us/attachment/B1027.pdf

## NOTE

There is one answer here related to a different sort of solution involving a device which reads a code every 0.5mm or 1.0mm taped to a rod which is attached to the piston. Device would read in direction perpendicular to direction of motion. This would probably be my 2nd or 3rd choice if I'm unable to find an affordable sensor as described in my question.

## NOTE 2

If I had time I'd implement the following solution which I wish I had thought of a month ago: tape a 300mm strip of reflective material which varies in reflectivity along its length. shine a laser on the tape and detect amount of light which reflects. simple solution, easy to calibrate and (if I knew where to get the tape) should be low cost.

# Answer
Inside an inkjet printer, I've found a clear plastic strip with photo-engraved (loose approximation) lines perpendicular to the length of the strip. This strip passes through an optical pair, one side illuminates, the other reads. The strip stretches the entire width of the printer and if I recall correctly, the reading module is on the print head carriage. Consider that many printers are described as 600 dots per inch, which would create a resolution on the strip of 1/600" / 0.04 mm.

Additionally, I've discovered circular plastic encoders on which the rings of black/clear alternated the segment counts with each expanding ring. That is to say, the first ring was half black, half clear. The next ring out was 1/4 black/white alternating, the one following was 8 segments, then 16, etc.

This required a reader for each ring, but provided an absolute reference rather than a relative reference as is the case with the linear strip. One could create a linear strip which would work in a similar manner. One level would be half black, half clear, the next layer would be 1/4 black/clear, etc.

The requirement for 500 mm fits into a binary 512 value, which would require 9 stripes and provide for the accuracy noted in the post.

The aspect I can't answer is the speed of the encoding, although I suspect that any design based on an optical reader could be optimized to work.

I found an article at rp-photonics.com

> When light is diffracted at the traveling refractive index grating in an acousto-optic modulator, the diffracted light experiences a shift of optical frequency which is plus or minus the acoustic (or drive) frequency. That effect (which can be interpreted as a Doppler shift) is exploited in acousto-optic frequency shifters.
>
> Drive frequencies are typically between some tens and hundreds of megahertz, rarely more than 1 GHz. The resulting change of optical wavelength is quite small. For larger frequency shifts, or for realizing very small frequency shifts (e.g. only a few MHz), one may cascade two or more devices. It is also possible to use a double pass through a single device in order to obtain twice the frequency shift.

I think from reading that excerpt that the long strip in the inkjet printer is the traveling refractive index grating. I had not considered that a low-power laser could be substituted for a simple optical pair. Doing so would provided even better resolution.

If your project allows for a strip of sufficient length to be attached to the piston, with assurance that it won't buckle under acceleration and jam in the sensor, you'd probably make it work.

But wait, there's more. I can picture the rod on the piston alternately obscuring and uncovering a digital design, which is constantly scanned by a laser. This reduces the number of parts in close contact and possibly the moving mass.
> 2 votes

---
Tags: sensors
---


title: Arduino lcd displays random chracters

text:
# Question
Title: Arduino lcd displays random chracters
I have connected arduino nano every to my lcd display. It works perfect when i put all my code in setup() part. But when i put the code in loop() it does werid things. I have to put my code in loop(), because i am reading from load cell and displaying the values that are constantly changing. The delay can't be more than 250 ms.

This works well.

```
#include <LiquidCrystal.h>
int Contrast=30;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup(){
    analogWrite(6,Contrast);
    lcd.begin(16, 2);
    lcd.setCursor(0, 0);
    lcd.print("testing");
}

void loop(){

 }

```

When I do this next thing it works well for few seconds and then it starts to display random weird characters and stops displaying anything after some time.

```
#include <LiquidCrystal.h>
int Contrast=30;
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

void setup(){
    analogWrite(6,Contrast);
    lcd.begin(16, 2);
    lcd.setCursor(0, 0);

}

void loop(){

  lcd.clear();
  lcd.setCursor(0, 0);
  lcd.print(millis()/1000);
  delay(250);
 }

```

I have tried removing lcd.clear() it didn't help. I thought it was a problem with wiring first, but it's not. What am I doing wrong?

Any help would be great, thanks.

# Answer
> 2 votes
1. `lcd.setCursor(0, 0);` \- you dont really need this funtion. `lcd.clear()` will always bring the cursor into the (0,0) position, automatically.
2. check your wiring. The code seems to be correct
3. Increase the delay to 500 ms or more. You don't have to write faster than 1 seconds to the LCD anyway

---
Tags: display
---


title: Arduino nano IoT antenna broke

text:
# Question
Title: Arduino nano IoT antenna broke
I have an Arduino Nano 33 IoT and have used it for a good time now. I was using it when the antenna snapped off. Is there any way to fix it by either an external antenna or some other method? I tried to just hold the antenna in place as I tried to connect to wifi but it failed to connect.

# Answer
The problem that I see in the photo is that the pads from the PCB are pulled off and attached to the antenna. So now there is nothing to solder the antenna back to.

While it's possible to rework this with some solder rework tools, I suspect you don't have those. There is really not much else you can do but replace the Nano with a new one. You should still be able to use this one for an application that doesn't need WiFi.

It looks like the two active leads (the two in the upper right-hand side of the green module may be those) are still intact. If you have a small tip soldering iron and a steady hand you may be able to put a tiny drop of solder on both of them and then resolder the antenna to them. You could support the antenna with some silicone caulk or other non-conductive adhesive after you get it attached.

Keep in mind, that this is tricky to solder by hand but there is little to lose since that part of the module is not non-functional anyway.
> 3 votes

# Answer
It is still possible to get work. I see the copper pads have been pulled off so you need to use extra amount of solder and hopefully it attaches to the remained copper wire.

My case is even worse because the antenna is lost, so I have to remade one.

And it works.
> 3 votes

---
Tags: wifi, bluetooth, ble, arduino-nano-33-iot
---


# Question
Title: Is this circuit damaging my arduino/components?
I'm building a system as follows:

* There are two pumps which lower and raise the level of the water
* There is an ultrasound detector which measures the level of the water
* While the water is too high, water is pumped out
* While it's too low, water is pumped in

There are thresholds to prevent micro-adjustments, the system doesn't flip-flop back and forth.

However after a short while the ultrasound sensor stops working, until I power the system off and on again. My electronics knowledge is *extremely* rudimentary, but I know motors can be nasty to other components?

I've included my circuit diagram, should I be doing anything about that? I'm using reed switches to turn them off and on, but the ground and 5v rails are all tied together, and powering the arduino too via VIN.

# Answer
Motors are inductive loads (they contain coils) that generate voltage spikes when switched off. These voltage spikes can indeed be nasty to other components.
You need to add a **flyback diode** in parallel with the motor, with the cathode connected to Vcc.
It will normally not conduct current, but when the motor is switched off, because the voltage spike is negative, it will provide a path for the current and allow to dissipate it through the coil's internal resistance.

As pointed out in the comments, it's also a good idea to (always) add an electrolytic capacitor (\> 100 µF) close to the ultrasonic detector to filter out this kind of spikes.
> 3 votes

# Answer
Hopefully you are powering the Arduino Vin with at least 7 volts. We know the Arduino a power supply it is NOT so where does the 5V come for the motors? You need to post technical links to the hardware items you are using. Are you calling relays reed switches? D11 and D12 sound like port pins, normally they cannot drive relays unless they are designed appropriately. I would suggest you either buy another set of electronic parts or stop using it until the problems can be determined. As far as a circuit diagram does not show the information needed. A schematic, not a frizzy thing is much better.
> 0 votes

---
Tags: motor
---


# Question
Title: Everything is ready for project . I have one doubt! I am using transmitter + Arduino *Uno*..and receiver + arduino *nano* will it work?
Everything is ready for project except hardware!

I have one doubt!

I am planning to use transmitter of Arduino *Uno* and receiver of Arduino *Nano*. Will it work? Both Uno and Nano obey for same program? (The transceivers used are Nrf24lO1 pa+lna!)

# Answer
Yes, it will work, in much the same way that you can send an email from a Mac to a Windows PC. The type of PC doesn't matter as long as they use the same protocol. As you haven't shared any details in that direction, I would say that if you have coded correctly, then it will work.
> 2 votes

# Answer
That cannot be determined until a much better description of your project is given. The parts you named are compatible with both processors. It could fail for a simple software mistook or a bad connection. Generally speaking the UNO and Nano are interchangeable electrically but not mechanically. The nano gives you two additional analog channels. Start by getting the RF to work, this probably will be the most problematic to get going. Use seperate power supplies for the RF devices.
> 0 votes

---
Tags: arduino-uno, arduino-nano, nrf24l01+
---


title: What current is safe for Wemos d1?

text:
# Question
Title: What current is safe for Wemos d1?
I've got 12V / 400mA power supply for my Wemos D1 R1, and I'm using VIN output(I need 12V for led strip). I need to change this power supply because of color, and I can't find similiar with the same parameters. The question is - Is power supply with 12V / 1A - 2A safe to use?

# Answer
> 1 votes
With very few exceptions, electronic devices only draw as much current as they need, limited by their resistance.

The current rating on a power supply is the MAX current it can provide before the voltage drops. Having a higher current power supply may waste energy, but won't hurt anything.

According to Ohms law, V = IR

Where V = Voltage I = current, in amps R = resistance, in ohms

(voltage = current times resistance.)

Or, solving for current:

```
I = V/R

```

current = voltage divided by resistance.

So if you have a 12 volt power supply, and a 100 ohm resistor, you'll get 12/100, or 0.12 amps, flowing through the resistor.

# Answer
> 0 votes
I am a bit confused you state: VIN output, that is the voltage input to the onboard regulator. For the power supply use one of the same voltage but capable of more current. Current is the maximum a power supply will give reliably. Current is the current needed by a load so if the load is less then the source and the voltages are the same it is a go. The answer is yes either is ok but be sure you have enough current from the power supply + some to cover all of the LEDS.

---
Tags: esp8266, power, nodemcu, current
---


# Question
Title: Storing data in Arduino Portenta H7's SDRAM
I am working on storing data from Portenta H7's ADC through a high sample rate (\>100kSa/sec) per channel. I am using 2 ADC channel for my work. Through the forum, I learned that the serial. print command reduces the sampling rate. Therefore one of the suggestions was to use the onboard available Portenta H7's 8MB SDRAM to store the sample values and then retrieving them after the sampling period. My sampling time is between 3-5 seconds so it is well within the storage limit of this SDRAM.

However, since I have no previous experience with microcontrollers, I am struggling to find a starting point for accessing this SDRAM for saving my data? Any suggestions from your side are most welcomed.

Please do recommend If you have any other ideas about managing the data for faster sampling.

You can find the Portenta H7 information here. https://store.arduino.cc/usa/portenta-h7. Portenta has STM32H747 dual-core processor.

Thank you all.

# Answer
```
#include <SDRAM.h>

SDRAMClass ram;
uint8_t *b;
void setup() {
  ram.begin();
  b = (uint8_t *)ram.malloc(320 * 240 * sizeof(uint8_t));
}

```

The way to do it is to use the SDRAM library for the portenta. Above you see an example for a uint8 array.
> 2 votes

---
Tags: serial, programming, arduino-ide, adc, arduino-portenta-h7
---


# Question
Title: Sending a request with a NodeMCU when a key is pressed
I want to send a request to a server with the GET method with URL parameters when a key is pressed on the NodeMCU. But I can't get this to work; I get the below error in the serial monitor:

```
 ets Jan  8 2013,rst cause:4, boot mode:(3,7)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v951aeffa
~ld

```

My main code:

```
#include <ESP8266WiFi.h>

const char* ssid = "MobinNet1365";
const char* password = "G12229M1Q64";
const char* host = "webhook.site";

const int button = 8;
int temp = 0;

void setup() {
  Serial.begin(115200);
  pinMode(button, INPUT);
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

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

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  temp = digitalRead(button);
  if (temp == HIGH) {
    Serial.println(host);
    WiFiClient client;
    const int httpPort = 80;

    String url = "/df35c8cd-0398-4c92-b55f-b9e36629b309";
    url += "?switche=";
    url += "1";

    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  }
}

```

My request sending code is below:

```
#include <ESP8266WiFi.h>

const char* ssid = "your-ssid";
const char* password = "your-password";
const char* host = "";

void setup() {
    Serial.begin(115200);
    delay(10);
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);
    WiFi.mode(WIFI_STA);
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

int value = 0;

void loop() {
  delay(5000);
  ++value;
  Serial.print("connecting to ");
  Serial.println(host);
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

  String url = "/";
  /* url += "?param1=";
  url += param1;
  url += "?param2=";
  url += param2;
  */
  Serial.print("Requesting URL: ");
  Serial.println(url);
  client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0) {
    if (millis() - timeout > 5000) {
      Serial.println(">>> Client Timeout !");
      client.stop();
      return;
    }
  }

  while (client.available()) {
    String line = client.readStringUntil('\r');
    Serial.print(line);
  }

  Serial.println();
  Serial.println("closing connection");
}

```

And my key press detector code is below:

```
const int button = 8;
int temp = 0;

void setup() {
  Serial.begin(9600);
  pinMode(button, INPUT);
}

void loop() {
  temp = digitalRead(button);

  if (temp == HIGH) {
    Serial.println("LED Turned ON");
    delay(1500);
  }
  else {
    Serial.println("LED Turned OFF");
    delay(1500);
  }
}

```

My circuit is:

NodeMcu =\> MicroSwitch

VIN =\> C

D0 =\> NO

G =\> 10k =\> NO

How can I make it so that when the key is pressed it sends a request?

# Answer
> 1 votes
IMHO, some consideration :

1. const int button = 8; const int button = 5; // CHANGE TO Pin "D1 GPIO5"

GPIO8 is used to connect the flash chip, you may change to Pin "D1" which is GPIO 5.

* Check with your board's pinout.

2. to prevent non-stop keep calling within in the loop, you may use millis();

for example :

```
void GetUrl() {
    temp = digitalRead(button);
  if (temp == HIGH) {
    Serial.println(host);
    WiFiClient client;
    const int httpPort = 80;

    String url = "/df35c8cd-0398-4c92-b55f-b9e36629b309";
    url += "?switche=";
    url += "1";

    String link = String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n";
//    Serial.println( "link : " + link );
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host + "\r\n" + "Connection: close\r\n\r\n");
  }
}

unsigned long previousMillis = 0;
const long interval = 1000 * 0.5; // 500ms (0.5 sec)

void loop() {
  unsigned long currentMillis = millis();
  if (currentMillis - previousMillis >= interval) {
    GetUrl();
  }
}

```

Reference :

https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay

https://iotbyhvm.ooo/gpio-pins-esp8266/

---
Tags: arduino-ide, wifi, nodemcu
---


# Question
Title: How to read from and write to rs232 device from/to Arduino
I would like to read data from a rs232 device (SL-5868P Sound Level Meter).
protocol and more : https://sigrok.org/wiki/Colead\_SL-5868P.

I already have a Python script to read the data with a TTL to USB converter (without Arduino). Now I also want to be able to read the meter via the Arduino.

I've bought a RS232 to TTL Converter (MAX3232). I get either very weird characters (baud rate set correctly), or not logical numbers. With the MAX chip I get no data at all.

1. To see if there is data ready, 0x10 must be sent by the meter.
2. To get the data, send 0x20.

Would someone be willing to help me out a bit? That would be really nice. Maybe there is someone who has experience with reading (and writing to) RS232. The only thing that matters is how I can retrieve the data. I know the rest what needs to be done with software (conversion, etc.). I'm not that familiar with Arduino's .

The code below is an example from SoftwareSerial (a little bit modified). I'm using the Arduino Uno.

```
#include <SoftwareSerial.h>

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

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

  Serial.println("Goodnight moon!");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(2400);
}

void loop() { // run over and over
  if (mySerial.read() == 0x10) {
    //mySerial.write(0x20);
    Serial.println("Data available");
    Serial.println(mySerial.read());
  }

  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
  //delay(300);
}

```

And the current schematic (sorry for my drawing skills)

# Answer
> 4 votes
You didn't show how you connected the MAX3232, so I cannot say anything about that. But I can write something about your code and how the data gets received on the PC.

* **On the PC:** Here it is important how you are reading the serial data on the PC. The Serial Monitor for example expects ASCII encoded text. It cannot correctly display binary data. That is the reason, that you get weird characters with the correct baudrate. The data is correctly received, but it doesn't represent ASCII characters. It is just binary data and interpreting it as ASCII characters will not make any sense.

Also it just sends ASCII encoded text, no binary data. So when you are sending "10" it will send the bytes `0x31` and `0x30`, plus any line ending, that you have selected (`\n` aka `0x0A` if you selected newline as line ending). As your device speaks in binary data you might wanna speak binary to it. So you either need to decode the ASCII data on the Arduino, before sending it to the device, or you need to use a different serial program, which can handle binary data.
* **Your code:** First look at this line

```
  Serial.println(mySerial.read());

```

Here you are reading exactly **one byte** from the SoftwareSerial interface and then you are printing it. `Serial.read()` or `SoftwareSerial.read()` only read one single byte from the buffer, but the data from your device spans over multiple bytes, as described on the wiki page, that you linked. Look at the table titled "Data structure". The returned data consists of 10 bytes in total (numbered from 0 to 9), where bytes 3 to 7 contain the actual data. The rest gives configuration and status data, a header as packet start and a checksum to check for transmission errors. So reading only one byte isn't enough you need to read all of them.

Then you are `Serial.print()`ing the data. The `print()` function and its siblings are formatting the data human readable. That might help you here, but you need to make sure, that the resulting output is really readable for you, especially when you are reading multiple bytes (as you need to do, as explained above). Here you need to make a decision: Either

+ you could decode and format the binary data from the device on the Arduino and send the human readable format over Serial
    + or you could send the binary data straight to the PC and decode it there with a fitting program (either a Serial program, which can handle binary data, or your own program, for example with python or processing)

If you go the first way, you should first read the different parts of the message and then print these parts with additional text, that explains, what data means what. Otherwise you would have just a long line of numbers, which are also rather difficult to read. Also you might wanna decide on a number base. I think only decimal or hexadecimal are really relevant here. For that you could use `Serial.print(value, DEC)` or `Serial.print(value, HEX)`, which tells the Serial library to use the specified number base.

**Now about the actual data format:** The data format is described with

> BCD-encoded value, one byte per digit 0x00-0x09. 0x0a means ignored digit. The last digit represents the decimal.

on the linked wiki site. So while this is still binary data (not ASCII encoded), each byte represents a decimal digit of the actual value. You could decode it accordingly. So I guess a byte sequence of `0x01 0x00 0x02 0x09 0x07` would mean `1029.7`. As you wrote, that you already know how to convert the data, I will not go deeper about this here.

And lastly you need to rethink your program structure. The workflow with your device is the following:

```
  Arduino waits for device to send data ready byte (0x10)
  device sends 0x10
  Arduino sends 0x20 (command to send data)
  Arduino waits for device to send at least 10 bytes of data
  device sends a complete data packet with 10 bytes
  Arduino interprets the data in the received packet and acts accordingly
  repeat

```

You need to follow this workflow and also anticipate, that the data transmission takes some time (especially at the really slow 2400 baud). For this a Finite State Machine (FSM) is a good fit (there are many extended descriptions about FSMs on this site, for example my answer to this question or this question, though there are many more, which you just need to search for). We just track at which part of the workflow we are currently and execute the according code. Something like this:

```
  enum ReceiveState {IDLE, RECEIVING};
  ReceiveState rec_state = IDLE;

  void loop(){
      if(mySerial.available()){
          switch(rec_state){
              case IDLE:
                  if(mySerial.read() == 0x10){
                      // data is ready, command to send data
                      mySerial.write(0x20);
                      // change state to receiving
                      rec_state = RECEIVING;
                  }
                  break;
              case RECEIVING:
                  if(mySerial.available() >= 10){// only read data, if a full packet was received, at least 10 bytes
                      // Here you need to decode the binary data and handle it accordingly (for example printing in the wanted format)
                      // Reset rec_state afterwards to be ready for the next time, that data is ready to read
                      rec_state = IDLE;
                  }
                  break;
              }
          }
      }
  }

```

That might seem like a bit of overkill, but the concept is very important in the Arduino world and it is very powerful. Also it makes it easier to accommodate workflow structures.

# Answer
> 2 votes
Hi and welcome to the wonderful world of Arduino. It appears that you have picked-up Arduino with ease. Your program is almost there. Your wiring connection diagram looks to be correct.

When I am doing a project like this, I won't write my full application first. Instead I write a series of test programs to make sure each chunk is performing exactly as I want it to.

I would start by writing a program that just passes the serial information recieved from the Sound Level Meter and displays it on the serial monitor. Something similar to this:

```
#include <SoftwareSerial.h>

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

void setup()
{
  // Open USB serial communications
  Serial.begin( 2400 );
  Serial.println("USB Serial is up and running");

  // set the data rate for the SoftwareSerial port
  mySerial.begin( 2400 );
}

void loop()
{
  if ( mySerial.available() )
  {
    // Write the serial from the S.L.M. to the USB (debug) serial port
    Serial.write( mySerial.read() );
  }

  if ( Serial.available() )
  {
    // Write the serial from the USB (debug) serial port to the S.L.M.
    mySerial.write( Serial.read() );
  }
}

```

This program should be enough to communicate with the Sound Level Meter. But this leads me to my first concern - choice of serial monitor.

While the Arduino built in serial monitor is adequate it is only really good for sending/recieving text. (Plus it sends a CR/LF every time you hit enter.) I can see straight away that you require to send/recieve hex numbers. Hex numbers won't display well on the serial monitor.

Instead I prefer to use a terminal program by "der-hammer" called hterm. (Screenshot here). It lets you view the input in ASCII, hex, bin and decimal. Likewise it lets you send ASCII, hex, bin and decimal or a mixture of each. When sending information, you can configure it so that it finishes the data with either a line feed, a carriage return, both or none.

By the sound of it, you don't want a CR or LF at the end of the data you send. So in the "Input Options" set the "Send on enter" to "None".

For the recieved data, you need to view that in hex so make sure the "hex" box is checked just above the recieved data. (Uncheck "ASCII".)

You could create a loop-back test by removing the Sound Level Meter and instead link the RS232 Rx to the RS232 Tx. This will allow you to see on hterm exactly what the Sound Level Meter sees when you send data.

---

**Issues with your program**

```
  if (mySerial.read() == 0x10) {
    //mySerial.write(0x20);
    Serial.println("Data available");
    Serial.println(mySerial.read());
  }

```

The section of code will only read one byte of data after it has detected `0x10` (See the Serial.Read() reference page). Anything more than that will get consumed by the next time the `if` statement checks the serial line for `0x10`.

I notice in the line `Serial.println(mySerial.read());` that you are reading the data in (which is in hex format) but then trying to write it out in ASCII by using the `println()` function. This will not give you the output you desire.

Also, after detecting `0x10` it reads the software serial line for one more byte - meaning if there is nothing following the `0x10` then the `mySerial.Read()` command will hang for 1s until it timeouts.

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

```

As others have pointed out, using the serial monitor will send this as ASCII characters (and include a CR/LF character(s)) instead of the hex value that you want. Kudos is given to you, that you chose `mySerial.write()` instead of `mySerial.println()`.

---

**My Take on Your Program**

*The follwoing code is untested.*

```
#include <SoftwareSerial.h>

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

void setup()
{
  // Open serial communications and wait for port to open:
  Serial.begin(2400);
  // The wait for serial port to connect is not needed for Arduino Uno
  Serial.println("USB Serial is up and running");

  // set the data rate for the SoftwareSerial port
  mySerial.begin(2400);
}

void loop()
{
  if ( mySerial.available() )
  {
    int recievedByte = mySerial.read();
    Serial.write(recievedByte);    // Send to USB serial - assuming using hterm in hex
    if ( recievedByte == 0x10 )
    {
      mySerial.write(0x20);
    }
  }

  // You could remove the following code - data must be in hex.
  if ( Serial.available() )
  {
    mySerial.write(Serial.read());
  }
}

```

---
Tags: arduino-uno, softwareserial, rs232, max232
---


title: Cannot successfully implement singleton

text:
# Question
Title: Cannot successfully implement singleton
I have spent the better part of today trying to figure out why I can't get this to work...

I have this project where, because of previous design considerations, have implemented a singleton class that initializes a bunch of separate sensors in this system that I am running.

The system was originally built for the Particle Boron, but now I am trying to make it work with the Adafruit Feather M0, so I have had to refactor several things and omit lots of lines of Particle RTOS specific things.

However, in doing this, I find that my singleton class no longer works.

**Sensors.h:**

```
.
.
.

class Sensors{

    static Sensors *instance;

public:
    static Sensors *getInstance() {
        if (!instance) {
            instance = new Sensors;
        }
        return instance;
    }

}

private:
    Sensors();

.
.
.

```

**Sensors.cpp:**

```
.
.
.

Sensors::Sensors() : dht22(DHTPIN, DHTTYPE) {
#ifdef PLATFORM_ID
    sensorLog("app.Sensors");
#endif
}

.
.
.

```

**main.ino:**

```
.
.
.

// Sensors
Sensors *Sensors::instance = nullptr;
Sensors *allSensors = allSensors->getInstance();

void setup(){

.
.
.

```

As I try to compile this with ArduinoISP, no matter what I try, I get the following error:

```
sketch/main.ino.cpp.o: in function `Sensors::getInstance()':
sketch/lib/Sensors/src/Sensors.h:23: undefined reference to `Sensors::Sensors()'
collect2: error: ld returned 1 exit status
exit status 1
[Error] Exit with code=1

```

I have tried things like changing the line

```
instance = new Sensor;

```

to

```
instance = new Sensor();

```

making the `instance` public, changing the Sensor constructor, but all of this to no avail. Could this be a compiler issue? Why would this work on a Particle board, but not an Adafruit Feather M0?

# Answer
> 1 votes
I had the same problem when referencing classes from multiple files, remember to put at the top of your header file (ending in .h) `#pragma once` on files that get referenced more than once!

Edit1: Also after you declare your class you need to specify where your static variable will be stored. After the class declaration write:

type \*Class::variable;

To declare the static variable.

For example:

```
#pragma once
//#includes

class Screen
{
protected:
  static void (*StateMachineStep)(int);
  static SSOLED *oled;
  static Player *player;

public:
  Screen() {}

};

void (*Screen::StateMachineStep)(int);
SSOLED *Screen::oled;
Player *Screen::player;

```

Edit2: formatting

# Answer
> 0 votes
Singletons aren't a thing in Arduino. Sure, you *could* do it, but in general you'd make a class then instantiate a global object for that class. Most often that global object is instantiated in the library itself, not the sketch.

Unless you're using an advanced chip with an RTOS (such as ESP32) and making use of the threads of that RTOS heavily there is no benefit to having a singleton.

But to answer your actual question: it's probably because you are trying to use the `Sensors()` constructor at a time before the compiler knows what the `Sensors()` constructor is. You would have to add some form of forward declaration so that the compiler knows what you mean when you talk about the `Sensors()` constructor. In general a simple:

```
class Sensors;

```

at near the top of your header before the class is actually defined can help in these situations;

---
Tags: programming, c++, adafruit, arduinoisp, feather
---


# Question
Title: How do I temporarily disable TIMER5 Interrupts?
I have a fairly complex autonomous robot program that is getting into trouble when executing controlled turns. I constructed a very small program to test just the turns, and this works fine. When I port the turn algorithm into the main program, however, it behaves erratically, and I suspect the culprit is a TIMER5 interrupt ISR that is in the main program but not in the test program.

To troubleshoot, I added the TIMER5 ISR code to the test program, and I want to be able to enable and disable the ISR using keyboard commands, to see if I can cause the anomalous behavior with the ISR enabled, and prevent it by disabling the ISR.

From reading about TIMER interrupts, it appears that setting TIMSKx (TIMSK5 in my case) to 0 will disable the ISR, and setting bit 0 to 1 (using TIMSKx |= OCIExA) will enable it. I have a 'CheckForUserInput()' routine which allows me to input commands from the keyboard, so I added a 'T' command, as follows:

```
switch (incomingByte)
{
case 0x54: //ASCII 'T'
case 0x74: //ASCII 's'
    Serial.println(F("Toggle TIMER5 Enable/Disable"));
    if (TIMSK5 == 0)
    {
        Serial.println(F("Enable TIMER5"));
        TIMSK5 |= OCIE5A;
        mySerial.printf("TIMSK5 = %x\n", TIMSK5);
    }
    else
    {
        Serial.println(F("Disable TIMER5"));
        TIMSK5 = 0;
        mySerial.printf("TIMSK5 = %x\n", TIMSK5);
    }
    break;

```

I have an LED set up to blink each time the ISR fires, and I can see that I can stop the ISR from firing reliably with the first 'T' input, but I can't reliably restart it with the second 'T' command, even though I can tell from the printouts that the proper piece of code executed, like in the following output

```
Opening port
Port open

Checking for MPU6050 IMU at I2C Addr 0x69
MPU6050 connection successful
Initializing DMP...
Enabling DMP...
DMP ready! Waiting for MPU6050 drift rate to settle...
MPU6050 Ready at 0.52 Sec
End of test - Stopping!
I received: 63
ENTERING COMMAND MODE:
0 = 180 deg CCW Turn
1 = 180 deg CW Turn
A = Back to Auto Mode
S = Stop
F = Forward
R = Reverse

       Faster
    8
Left 4  5  6 Right
    2
       Slower
Got D
Got A
Got 74
Toggle TIMER5 Enable/Disable
Disable TIMER5
TIMSK5 = 0
Got D
Got A
Got 74
TEnabling DMP...
DMP ready! Waiting for MPU6050 drift rate to settle...
MPU6050 Ready at 0.52 Sec
End of test - Stopping!
I received: 63
ENTERING COMMAND MODE:
0 = 180 deg CCW Turn
1 = 180 deg CW Turn
A = Back to Auto Mode
S = Stop
F = Forward
R = Reverse

       Faster
    8
Left 4  5  6 Right
    2
       Slower
Got D
Got A
Got 74
Toggle TIMER5 Enable/Disable
Disable TIMER5
TIMSK5 = 0
Got D
Got A
Got 74
Toggle TIMER5 Enable/Disable
Enable TIMER5
TIMSK5 = 1
Got D
Got A

```

I'm sure I'm doing something wrong in the way I am attempting to re-enable the TIMER5 ISR, but I really can't see it. Anyone have a clue?

TIA,

Frank

# Answer
> 3 votes
You wrote:

> ```
> TIMSK5 |= OCIE5A;
>
> ```

You mean

```
TIMSK5 |= _BV(OCIE5A);

```

or, equivalently,

```
TIMSK5 |= 1 << OCIE5A;

```

---
Tags: atmega2560, isr
---


# Question
Title: How to switch HC-05 from DATA mode to AT mode?
I am asking how to enter from the data mode to the AT command mode without restarting and disconnecting any power supply. In other words, I am trying to make a driver to handle HC-05 module and now I have to switch between DATA mode to AT mode. When I try to switch backwards, it worls ( by putting off the EN pin and then send “AT+RESET” ) but from DATA mode to AT Mode I can’t reset the module. Anyhelp please ?

# Answer
> 1 votes
I am pretty certain there is no way to enter command mode from data mode without resetting the whole module. The only way to enter command mode is by setting the KEY pin high, and that pin is only read during the initialization phase of the module - and that means either a power cycle / reset, or a command-initiated reset.

You could either:

* Provide a power control circuit which turns the module on and off (MOSFETs are good for this), or
* Modify the module to attach a wire to pin 11, the RESET pin, and pulse that LOW to reset into command mode (I assume LOW, since that's the most common, though I haven't found anything to confirm it yet).

---
Tags: arduino-uno, hc-05, stm32
---


# Question
Title: Use chars in quotes in const char* as name of function
I have been trying for a long time how to use a word declared as `const string* word = "xxx"` as name of void function declared somewhere below in my code.

Here is example with `ssid`:

```
const char* ssid = "name_of_ssid";

void (*name of ssid*) () {

⠀//some code

}

```

I want to use word declared in `const char*` in quotation marks as name of function. It can not be written just `void ssid()`. Yes, I can set a name of void function manually, when `const char* ssid = "CoffeeWifi"` I can type `void CaffeeWifi()` but I want to do that by this way because my code is specific for this option and explaining this code here would be very difficult. When I change array of `const char*` word from `"xxx"` to `"yyy"` I want to change the name of void from `void xxx()` to `void yyy()` as well.

How to do that? What function should I use?

Thank you!

# Answer
> 1 votes
Such a thing is impossible (unless you keep striving; neither have I tried it yet). Judging from your intention, one thing you can do is to create an array of the names of the functions you'd like to use, another array carrying the pointers to the functions and a programme to call the function according to the input text. I haven't tried it myself, so perhaps I may not sound sensible, but that is the only thing that came to my mind.

An example:

```
String function_names[3] = {"foo", "bar", "quux"}; /* I am not sure of this syntax;
                                                corrections are welcome */
int *functions[3] = {&foo, &bar, &quux};

String input;

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

void loop(){
        while(Serial.available()){
              String temp_input = Serial.readString()
              input = (temp_input == "")? String("Nothing here") : temp_input;
              execute(input);
        }
        delay(1000);
}

void execute(String func_name){
        for(int i = 0; i < 3; i++){
              if(function_names[i] == func_name){
                     *functions[i]();
              }
         }
}

int foo(){
    Serial.println("foo");
    return(0);
}

int bar(){
    Serial.println("bar");
    return(0);
}

int quux(){
    Serial.println("quux");
    return(0);
}

```

# Answer
> 0 votes
Being a const char, you can set it at compile time with a define and then use it.

```
#define fstring(x) #x

const char* ssid = fstring(SSID_NAME) ;

void setup() {
  Serial.println("Start");
  Serial.println(ssid);
  SSID_NAME();

}

void loop() {}

void SSID_NAME (){
  Serial.println(ssid);
}

```

Instead of using quotes, this uses the stringize operator.

---
Tags: c++, wires
---