# Question
Title: I'm using too much RAM. How can this be measured?
I would like to know how much RAM I am using in my project, as far as I can tell, there's no way to actually work that out (other than going through and calculating it myself). I have got to a stage in a rather large project where I have determined that I am running out of RAM.

I have determined this because I can add a section and then all hell breaks loose **somewhere else in my code** for no apparent reason. If I `#ifndef` something else out, it works again. There is nothing programatically wrong with the new code.

I suspected for a while that I was getting to the end of available RAM. I don't think I'm using too much stack (although it's possible), what is the best way to determine how much RAM I am actually using?

Going through and trying to work it out, I have problems when I get to enums and structs; how much memory do they cost?

*first* edit: ALSO, I have edited my sketch so much since starting, these are not the actual results I initially got, but they are what I am getting now.

```
  text     data     bss     dec     hex filename
 17554      844     449   18847    499f HA15_20140317w.cpp.elf
 16316      694     409   17419    440b HA15_20140317w.cpp.elf
 17346      790     426   18562    4882 HA15_20140317w.cpp.elf

```

The first line (with text 17554) was not working, after much editing, the second line (with text 16316) is working as it should.

*edit: the third line has everything working, serial reading, my new functions, etc. I essentially removed some global variables and duplicate code. I mention this because (as suspected) it's not about this code per sae, it has to be about the RAM usage. Which brings me back to the original question, "how to best measure it" I'm still checking out some answers, thanks.*

How do I actually interpret the above information?

So far my understanding is:

```
`TEXT` is program instruction memory
`DATA` is variables (unitialised?) in program memory
`BSS`  is variables occupying RAM

```

since BSS is considerably less than 1024 bytes, why does the second work, but the first doesn't? If it's `DATA+BSS` then both occupy more than 1024.

***re-edit:* I edited the question to include the code, but now I've removed it because it really had nothing to do with the problem (other than maybe poor coding practices, variable declarations and the like). You can review the code by looking back through the edits if you *really* want to see it. I wanted to get back to the question at hand, which was more based around: How to measure RAM usage.**

# Answer
You can use the functions provided AVRGCC: Monitoring Stack Usage

The function was intended to check the stack usage but what it reports is the actual RAM that has never been used (during execution). It does so by "painting" (filling) the RAM with a known value (0xC5), and then checking the RAM area counting how many bytes have still the same initial value.
The report will show the RAM that has not been used (minimum free RAM) and therefor you can calculate the max RAM that has been used (Total RAM - reported RAM).

There are two functions:

* **StackPaint** is executed automatically during initialization and "paints" the RAM with the value 0xC5 (can be changed if needed).
* **StackCount** can be called at any point to count the RAM that hasn't been used.

Here is an example of usage. Doesn't do much but is intended to show how to use the functions.

```
// -----------------------------------------------------------------------------
extern uint8_t _end;
extern uint8_t __stack;

void StackPaint(void) __attribute__ ((naked)) __attribute__ ((section (".init1")));

void StackPaint(void)
{
#if 0
    uint8_t *p = &_end;

    while(p <= &__stack)
    {
        *p = 0xc5;
        p++;
    }
#else
    __asm volatile ("    ldi r30,lo8(_end)\n"
                    "    ldi r31,hi8(_end)\n"
                    "    ldi r24,lo8(0xc5)\n" /* STACK_CANARY = 0xc5 */
                    "    ldi r25,hi8(__stack)\n"
                    "    rjmp .cmp\n"
                    ".loop:\n"
                    "    st Z+,r24\n"
                    ".cmp:\n"
                    "    cpi r30,lo8(__stack)\n"
                    "    cpc r31,r25\n"
                    "    brlo .loop\n"
                    "    breq .loop"::);
#endif
}

uint16_t StackCount(void)
{
    const uint8_t *p = &_end;
    uint16_t       c = 0;

    while(*p == 0xc5 && p <= &__stack)
    {
        p++;
        c++;
    }

    return c;
}

// -----------------------------------------------------------------------------

void setup() {

Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
Serial.println(StackCount(), DEC);  // calls StackCount() to report the unused RAM
delay(1000);
}

```
> 15 votes

# Answer
The main issues you can have with memory usage at runtime are:

* no available memory in the **heap** for dynamic allocations (`malloc` or `new`)
* no room left on the **stack** when calling a function

Both are actually the same as the AVR **SRAM** (2K on Arduino) is used for both (in addition to **static data** which size never changes during program execution).

Generally, dynamic memory allocation is seldom used on MCUs, only a few libraries typically use it (one of them is `String` class, which you mentioned you don't use, and that's a good point).

The stack and the heap can be seen in the picture below (courtesy of Adafruit):

Hence, the most expected issue comes from stack overflow (i.e. when the stack grows towards the heap and overflows on it, and then -if the heap was not used at all- overflows on the static data zone of the SRAM. At that time, you have a high risk of either:

* data corruption (i.e. the stack ovewrites heap or static data), giving you ununderstandable behavior
* stack corruption (i.e. the heap or static data overwrites stack content), generally leading to a crash

In order to know the amount of memory that's left between the top of the heap and the top of the stack (actually, we might call it the bottom if we represent both the heap and the stack on the same image as depicted below), you can use the following function:

```
int freeRam () {
  extern int __heap_start, *__brkval;
  int v;
  return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

```

In the code above, `__brkval` points to the top of the heap but is `0` when the heap has not been used, in which case we use `&__heap_start` which points to `__heap_start`, the first variable that marks the bottom of the heap; `&v` points of course to the top of the stack (this is the last variable pushed on the stack), hence the formula above returns the amount of memory available for the stack (or the heap if you use it) to grow.

You can use this function in various locations of your code to try and find out where this size is getting dramatically reduced.

Of course, if ever you see this function return a negative number then it is too late: you have already overflown the stack!
> 10 votes

# Answer
When you figure out how to locate the generated .elf file in your temporary directory, you can execute the command below to dump a SRAM usage, where `project.elf` is to be replaced with the generated `.elf` file. The advantage of this output is the ability to inspect *how* your SRAM is used. Do all the variables need to be global, are they really all required?

```
avr-objdump -S -j .bss project.elf

project.elf:     file format elf32-avr

Disassembly of section .bss:

00800060 <__bss_start>:
        ...

00800070 <measurementReady>:
        ...

00800071 <cycles>:
        ...

00800073 <measurement>:
  800073:       00 00 00 00                                         ....

00800077 <measurementStart>:
  800077:       00 00 00 00                                         ....

0080007b <timerOverflows>:
  80007b:       00 00 00 00

```

Notice that this doesn't show stack or dynamic memory use as Ignacio Vazquez-Abrams noted in the comments below.

Additionally a `avr-objdump -S -j .data project.elf` can be checked, but none of my programs output anything with that so I can't tell for sure if it is useful. It supposed to list 'initialized (non-zero) data'.
> 7 votes

# Answer
> I suspected for a while that I was getting to the end of available RAM. I don't think I'm using too much stack (although it's possible), what is the best way to determine how much RAM I am actually using?

It would be best to use a combination of manual estimation and by using the `sizeof` operator. If all your declarations are static, then this should give you an accurate picture.

If you are using dynamic allocations, then you may run into a problem once you start deallocating the memory. This is due to memory fragmentation on the heap.

> Going through and trying to work it out, I have problems when I get to enums and structs; how much memory do they cost?

An enum takes as much space as an `int`. So, if you have a set of 10 elements in a `enum` declaration, that would be `10*sizeof(int)`. Also, every variable that uses an enumeration is simply an `int`.

For structures, it would be easiest to use `sizeof` to find out. Structures occupy a (minimum) space equal to sum of its members. If the compiler does structure alignment, then it may be more, however this is unlikely in the case of `avr-gcc`.
> 3 votes

# Answer
There is a program called Arduino Builder that provides a neat visualization of the amount of flash, SRAM and EEPROM your program is using.

The Arduino builder makes up part of the CodeBlocks Arduino IDE solution. It can be used as either a standalone program or through the CodeBlocks Arduino IDE.

Unfortunately Arduino Builder is a little old but it should work for most programs and most Arduinos, such as the Uno.
> 1 votes

---
Tags: sram
---


# Question
Title: Can I make a 455Khz Sine Wave with the Arduino UNO?
Can any one help me, I need to make a sine-wave of 455Khz for use in aligning a Super 7 - AM Radio.

I looked into buying a function generator but I have an Arduino UNO. Can this do the tasks?

# Answer
> 1 votes
The Arduino does not has a DAC (digital analog converter), so you cannot make an output varying in voltage (except for 0V / 5V) by default.

The PWM outputs use 0V/5V with duty cycle but this is not a sine wave.

So you need additional hardware anyway.

Also, regarding speed if you have a DAC. Assume 16 MHz for the Arduino, having a 455 Khz sinewave, you have about 35 clock cycli per complete sine wave. The sine values you can store in a table, but you need probably at least 3 or 4 clock cycli per sine wave value (to fetch the value from the table and to send it to the DAC), this results in about 8 values which will give a very rough sine wave.

So I would go for a separate sine wave generator.

# Answer
> 0 votes
If you don't want to buy a chip, and you do have a few other parts laying around, it would not be hard to do a simple oscillator with Op Amps and get a nearly true sine wave. Alternatively an inverter (74ls04, or any inverting gate chip cmos or ttl) with an R-C can be made into a square wave generator, and another RC or two could get it to approximate a sine wave.

---
Tags: arduino-uno
---


# Question
Title: Sensor to measure distance on inverted pyramid filled with maize
I'm struggling with the following problem:

I have an inverted pyramid, supported in four points, filled with maize up to 600KG.

I want to keep track of the level of maize inside the inverted pyramid.

I've thought about using a load cell but this can be expensive and I need a cheap solution to implement. I also thought about using a sensor centred on top of the inverted pyramid.

The problem here is that I really dont't know what kind of sensor can be used to get correct values. Can ultrasonic sensors give me bad values? The pyramid form is tricky...

PS: Theoricly can mill be too reflective and influence the result of measures?

I'm sorry for the English :P. I'm still learning.

If anyone can help I really appreciate.

Best Regards

# Answer
The surface of corn is hard enough to reflect sound from an ultrasonic sensor. It reflects from fabric, skin and of course, plastic, and corn fits into the realm of reflectivity.

An Arduino with an ultrasonic sensor may scatter a good bit of the reflection, but some of it will get back to the receiver in sufficient condition to be registered.

The components necessary to test this are low enough cost to suggest a prototype. A simple pail or bucket filled with the grain and attached to a rope and pulley will give you distance information, and that would be for a relatively small surface area.

Ultrasonic sensors typically have a minimum distance and of course, a maximum distance. If your concern is for both full and empty conditions, dual sensors placed a sufficient distance apart with suitable range considerations are likely to work. The code would be written to avoid cross-pulse readings, which is likely to be trivial, as these devices operate at the speed of sound.

Lasers are point devices and may not necessarily reflect to the sensor for reading.

I have constructed a DME (distance measuring equipment) that displayed passing vehicles within a range of ten feet (~3 meters) down to slightly less than three feet (\<1 meter) with good results. There was tremendous lag in the reading, but that's due to code ignorance, not hardware problems. I suspect the depth finder is not going to have much lag in determining its value to this application.
> 1 votes

# Answer
You can let the sensor "sense" 20 times and let your Arduino figure out the average. More on Using the HC-SR04 Ultrasonic Distance Sensor with Arduino.

Maybe the ultrasound also scares rodents. I am using IR sensor Sharp GP2Y0A02YK which reaches from 20-150 cm
> 0 votes

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


# Question
Title: Uploading to a CH340 "Nano" board using a Mac with Osx High Sierra
I recently purchased some inexpensive Nano boards, but they give an error signal and won't upload from my Mac with OSX High Sierra... I am able to upload to Unos and Megas without issues. I am selecting the correct board and the Atmega 328P and the dev/cu.bluetooth-incoming-port.I have also installed the CH341SER\_MAC drivers using the H34X\_INSTALL\_V1.3 pkg. The error msg is as follows: Can you help???

```
/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-gcc" -Wall -Wextra -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p  -o "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/sketch/Blink.ino.cpp.o" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/core/core.a" "-L/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522" -lm
"/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0  "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.eep"
"/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avr-objcopy" -O ihex -R .eeprom  "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.elf" "/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.hex"
Sketch uses 948 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.Bluetooth-Incoming-Port -b57600 -D -Uflash:w:/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/arduino_build_850522/Blink.ino.hex:i

avrdude: Version 6.3, compiled on Jan 17 2017 at 12:01:35
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/private/var/folders/sv/y8kh1rhd4sz23xbxsnppbp700000gn/T/AppTranslocation/B0792E1F-FE26-4369-9DFF-D54AC5E75F46/d/Arduino.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/daniellecomte/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.Bluetooth-Incoming-Port
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.
Invalid library found in /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC: /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC
Invalid library found in /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC: /Users/daniellecomte/Documents/Arduino/libraries/CH341SER_MAC

```

# Answer
> 4 votes
If your clones come with a CH340G-chip you might proceed as follows: Download the latest driver with Hi Sierra compatibility here: Select Driver version 1.4 !!

Install the driver by double clicking the downloaded file - the installation will stop, issuing an error message as it is an unsigned driver - but if you downloaded the driver via the GitHub link, it is ok. So open Tools, Security and you will be asked by OS X's security system if you want to install the driver anyway - YES!

After restarting your Mac connect your Nano clone and start a copy of the Arduino IDE. Assuming you got version 1.8.5: under Tools/Port you should see something like /dev/cu.wchusbserialXXX - select this port. Now update your board manager, close and restart the IDE again. Under Tools select "Board: Arduino Nano" and "Processor: ATmega 328P (Old Bootloader)".

Now you should be ready to upload your sketch.

Background information: Since January 2018 all original Nanos come with the Optiplex bootloader (which is also incorporated in other Arduinos like the Uno. Clones will most likely have the old bootloader pre-loaded, that's why the Processor selection must be set to ".... (Old Bootloader)".

Hope that helps to get along.

---
Tags: clones, ch340
---


# Question
Title: Serial.parseFloat() reads 0 despite me entering different value
I'm trying to make a robot that asks the user for the longitude and the altitude form the user and then using the data the GPS collects to go to the wanted location, however when I use Serial.parseFloat() to get the location from the user, i get the right value for the latitude and the longitude returns zero for some reason here's the code i wrote

```
#include "Adafruit_FONA.h"

// standard pins for the shield, adjust as necessary
#define FONA_RX 2
#define FONA_TX 3
#define FONA_RST 4
#define PIN13 13
#define IN1 6      //IN1
#define IN2 7        //IN2
#define ENA 5          //ENA
#define ENB 10        //ENB
#define IN3 8          //IN3
#define IN4 9          //IN4
#define trigger1 A3      //Trigger
#define echo1 A2        //Echo
#define trigger2 A4
#define echo2 A5
#define trigger3 A0
#define echo3 A1

// We default to using software serial. If you want to use hardware serial
// (because softserial isnt supported) comment out the following three lines
// and uncomment the HardwareSerial line
#include <SoftwareSerial.h>
SoftwareSerial fonaSS = SoftwareSerial(FONA_TX, FONA_RX);
SoftwareSerial *fonaSerial = &fonaSS;
int counter;
char serialData;
int duration;
float distance1, distance2, distance3;
float latitudeDestination, longitudeDestination;

// Hardware serial is also possible!
//  HardwareSerial *fonaSerial = &Serial1;
Adafruit_FONA fona = Adafruit_FONA(FONA_RST);
// Have a FONA 3G? use this object type instead
//Adafruit_FONA_3G fona = Adafruit_FONA_3G(FONA_RST);

void getLatitude(){
    Serial.println("Enter the latitude destination :");
    while (Serial.available() == 0){}
    latitudeDestination = Serial.parseFloat();
}

void getLongitude()
{
    Serial.println("Enter the longitude destination :");
    while (Serial.available() == 0){}
    longitudeDestination = Serial.parseFloat();
}

void securityPassed()
{
    Serial.println("You need to pass security first");
    while (Serial.available() ==0){}
    serialData = Serial.read();
    if (serialData == '1')
    {
        Serial.println("Passed") ;
    }
    else {}
}

void setup() {
    pinMode(PIN13, INPUT);
    pinMode(trigger1, OUTPUT);
    pinMode(echo1, INPUT);
    pinMode(trigger2, OUTPUT);
    pinMode(echo2, INPUT);
    pinMode(trigger3, OUTPUT);
    pinMode(echo3, INPUT);
    pinMode(IN1 , OUTPUT);
    pinMode(IN2, OUTPUT);
    pinMode(IN3, OUTPUT);
    pinMode(IN4, OUTPUT);
    pinMode(ENA, OUTPUT);
    pinMode(ENB, OUTPUT);

    digitalWrite(ENA , HIGH);
    digitalWrite(ENB, HIGH);

    Serial.begin(9600);

    getLatitude();
    getLongitude();
    securityPassed();

    Serial.println(F("Adafruit FONA 808 & 3G GPS demo"));
    Serial.println(F("Initializing FONA... (May take a few seconds)"));
    fonaSerial->begin(4800);
    if (! fona.begin(*fonaSerial)) {
        Serial.println(F("Couldn't find FONA"));
        while (1);
    }
    Serial.println(F("FONA is OK"));
    // Try to enable GPRS
    Serial.println(F("Enabling GPS..."));
    fona.enableGPS(true);
}

void loop() {
    delay(2000);

    float latitude, longitude, speed_kph, heading, speed_mph, altitude;
    float latitudeDistance = latitudeDestination - latitude ;
    float longitudeDistance = longitudeDestination - longitude;

    // if you ask for an altitude reading, getGPS will return false if there isn't a 3D fix
    boolean gps_success = fona.getGPS(&latitude, &longitude, &speed_kph, &heading, &altitude);
    if (gps_success) {
      Serial.print("GPS lat:");
      Serial.println(latitude, 6);
      Serial.print("GPS long:");
      Serial.println(longitude, 6);
      Serial.print("GPS speed KPH:");
      Serial.println(speed_kph);
      Serial.print("GPS speed MPH:");
      speed_mph = speed_kph * 0.621371192;
      Serial.println(speed_mph);
      Serial.print("GPS heading:");
      Serial.println(heading);
      Serial.print("GPS altitude:");
      Serial.println(altitude);
      Serial.print("Latitude Distance: ");
      Serial.println(latitudeDistance);
      Serial.print("Longitude Distance: ");
      Serial.println(longitudeDistance);

      if ( latitudeDistance < 0.00001 && latitudeDistance > -0.00001)
      {

        if ( longitudeDistance < 0.00001 && longitudeDistance > -0.00001)
        {
          Serial.print("Arrived");
          stopm();
        }
        else
        {
          if (!counter == 1 && longitudeDistance > 0 )
          {
            moveRight();
            Serial.println("Turning Right");
            counter =1;
          }
          else if ( !counter == 1 && longitudeDistance < 0 )
          {
            moveLeft();
            Serial.println("Turning Left");
            counter=1;

          }
          moveForward();
        }
      }
      else
      {
        moveForward();
        Serial.print("Going To Destination");
      }
    }
    else {
      Serial.println("Waiting for FONA GPS 3D fix...");
    }
}

```

# Answer
> 2 votes
It is certainly possible that a person typing (or an automated system feeding data in packets over a spotty link) might fail to provide a valid number in the (default 1 second) time before `parseFloat()` times out.

However, given this is the *second* value to be read, there's a more complex possibility.

It's likely that the sequence actually sent might be something like

`123.45\r\n`

In this case `123.45` and the first non-value character `\r` will be consumed by the first `parseFloat()`.

But that leaves a remaining `\n` in the serial buffer, so the `serialAvailable()` check is satisfied *immediately* and the next `parseFloat()` begins before the user has even *started* typing. Unless they're very quick to respond, it may time out before they even begin.

If the user is supposed to use a terminal program that sends a carriage return and/or newline, you should probably change input processing to either consume until the end of the line before processing.

Or you can make your code flexible by being sure to consume any trailing line end characters (after checking for them with `Serial.peek()`) before you decide that the user has begun entering a new value and starting your next `parseFloat()` call.

You could also make your own more sophisticated `parseFloat()` using a different algorithm.

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


# Question
Title: When is it necessary to use "float" instead of "int"?
I'm very new to Arduino and I am making a code for a pedometer. I have a lot of variables and I have used "int" multiple times, but I just came across a code with "float". Now because my coding background is next to none, I don't really understand the concept of a float and when it's appropriate to use one. Could someone please give me an explanation. Thanks!

# Answer
> 4 votes
An integer is a whole or natural number. Computers use integers for counting and comparisons. Computers can count precisely using integers and comparisons of two integers can be absolutely true or false.

To make a float or floating-point number, a computer uses two integer numbers. It uses one integer as the mantissa and the other as the exponent. Computers use floats for calculations involving very large, very small or fractional values. In other words the set of real numbers. Computers can not count very well using floats. Computer can not even compare two floats very well. That is to say, you may get different results from different computers when testing if two different floats are the same or not. This is due to rounding error.

Consider that the set of real numbers between 0 and 1 to be infinite. However, intuitively, we know computers can not keep track of an infinite number of unique values between 0 and 1. After all, computers use a float to do this and a float has a finite number of bits in it's mantissa and exponent. The difference, if any, between the actual real number from, say, a calculation and the next possible float value is commonly referred to as the roundoff error. In a program, a difference, for example, in the order of operation is enough to cause different roundoff errors to occur resulting in two slightly different float value results.

Rounding errors are what we end up with for allowing float values to grow very large or very small or to contain factional amounts. Fortunately, floats are exactly what we need when computers are asked to calculate very large, very small or fractional numbers.

In embedded programming we rarely use floats. They take up more of our limited RAM space than integers. And it is rare that we need to calculate very large or very small numbers. Usually, in embedded programming, we are counting events or measuring sensors. Usually integers are preferred or are sufficient for our purposes.

Addressing your specific application (pedometer):

It is anticipated you would prefer to track distances in miles. And it is practical to assume a good pedometer displays factional miles. You can use floats to calculate this value. A rigorous programmer would cast their integers as floats when mixing them in equations to make it clear to the compiler what is desired.

# Answer
> 3 votes
"int" means integer. It's either one whole number (forgive me, mathematicians, for the sloppy definition!) or the next or previous.

A "float" is a floating-point number - that is, a number and part of a number.

3 is an int

3.14 is a float

If you need to store/represent a value that can be between integers, you could use a float.

Floats use more RAM than integers, and there is a limit to the precision they can represent. Don't use a float unless you have a need.

# Answer
> 0 votes
There are much more details on both data types, but to keep it easy, just a rough explanation:

**`integer`** data types only allow a range from -2,147,483,648 to 2,147,483,647 with 4 Bytes of memory per variable.
If your results exceed that numbers, an over- or underflow will occur. If you don't take care, bad things can happen.
And you can only use whole numbers, there is no decimal point.

**`float`** instead allows you to do your calculations directly typing decimal values (like 1.25, 3.14, ...), just like you do on paper.
Plus: You usually don't have to care for range checks, because that data type covers a huge value range (-3.4028235E+38 to 3.4028235E+38 with also only 4 Bytes of memory per variable!

So why not use `float` by default?
One big drawback is that handling this number format requires a special piece of hardware ("Floating Point Unit", FPU) to be efficient.
If your microcontroller doesn't have an FPU (and the small Arduinos don't have one), every calculation using `float` operands requires to call certain functions which use some rules to convert your `float` operands into `integer` data types, do the calculation on `integer` basis and convert the result back to `float`.
This consumes some memory and a lot of CPU cycles, which can slow down calculation speed to about 1/10 compared to using an FPU.

There are some other issues which make working with `float` a little bit tricky, so if your calculation can be done using `integer`, use this instead.

"And what if i *need* decimal numbers?"
You can't type 3.14 in `integer`, but you can multiply it to a value big enough to consider enough decimal places for your application. You just have to define the factor and imagine the decimal point. For instance, multiply your values by 1000, then 3.14 * 1.256 = 3.94384 becomes 3140 * 1256 = 3943840 internally.

# Answer
> 0 votes
> When is it necessary to use “float” instead of “int”?

IMHO **in Arduino world it is never necessary to use float** ; well unless you want to do something very fancy like building a space ship route calculation with Arduino. In which case you will have someone on your team who understands the problem in full detail who can decide it is better to use float for some calculations.

> How do I deal with behind the comma numbers?

As integers does not allow you to work behind the coma and you won't use float you may wonder how to work with pi (3.1415..radians). In most cases you will only work with a specific number of digits behind the comma. Lets say you want 3 digits behind the comma. In this case you simply work with milli radians instead of radians ( 3145 milli radians=3.145 radians; For the Americans it might be time to look at the metric system for a better understanding)
Because of this change in "base value", no more floats are needed to calculate. There are 3 drawbacks:

* when out-putting information formatting may be needed/desired to convert to a user "base value".
* when in-putting information formatting may be needed/desired to
convert to a user "base value".
* When using methods that use float conversions are needed In and output are normally very small in arduino. The Serial.print() is probably the biggest thing.
If you need to use a method like cos() you do as follows:
long result=DECIMALDIGITS\*cos((float)corner/DECIMALDIGITS);
Where DECIMALDIGITS= (float)10^numdigits;

As type I advice to use long on a 8 bitter as int (-32,768 to 32,767) is very likely to get out of range.

**More background behind the dirty details of float**
It is pretty obvious that float supports behind the comma values, but what are the disadvantage of float?

* float is CPU/RAM intensive
* float introduces a rounding problem.
* multiple types int/float can cause casting issues

Lets go through the disadvantages one by one:
**float is CPU/RAM intensive**
IMHO In many Arduino projects there is plenty of CPU/RAM left so I don't think this is a real issue.
To prove this point look at how many Arduino projects contain a delay(x00) in the loop; so if things go to slow simply decrease this number to release some CPU cycles ;-).

**float introduces a rounding problem.**
\*When using floats A * B / A does not guarantee to be equal to B!!!\* It will be close but ...
This is my main argument to avoid floats. Sooner or later this will hit you and you'll have a hard time finding out why. (I speak from experience here)
Basically 0.1 can not be represented 100% exactly in float. So in float 0.1+0.2 is not equal to 0.3!!!

**multiple types int/float can cause casting issues** In C/C++ it is pretty hard to predict the casting that will happen in a formula like:

```
float z;
byte r;
uint32 t;
...
int a=z*r/t*1.5;

```

I consider myself very experienced in C/C++ and I always convert code like this into something like

```
float z;
byte r;
uint32 t;
...
byte rfloat=r;
uint32 tfloat=t;
int a=(int)(z*rfloat/tfloat*1.5);

```

I prefer not to explain this to a newbie Arduino user :-s.
More in depth details can be found at floating-point-gui.de

# Answer
> 0 votes
> I'm very new to Arduino and I am making a code for a pedometer.

others have answered the difference between float and int.

but your project offers an interesting challenge in that it covers a wide range: the pedometer likely counts in miles and have to keep track of total steps, which the increments are done in single steps - much shorter than miles.

what you could do instead of using floats is to use multi-byte types. for example, a 32-bit/4-byte type can support 2 million miles; you can add additional msb to it to create a proprietary data type. a 5-byte type for example would support 5 million miles, and a 128 billion miles for a 6-byte type.

you will need to create your own math routines -\> not difficult at all.

the point is that float is a simple solution to simple problems only.

# Answer
> 0 votes
`int` stands for **Integer** and `float` stands for **floating point** number. For more reference check this out https://www.arduino.cc/reference/en/language/variables/data-types/float/

---
Tags: variables, float
---


# Question
Title: Schematic for the adafruit motor shield v2.3
I am trying to locate a schematic for the Adafruit motor shield v2.3. It has many ports and currently I have found little to no explanation of what is on the board. I located this picture which highlights the motor ports, servo ports, and Arduino Pins. But what about everything else?

What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins? What is the PWMs 0,1,14,15? How is the big empty board in the center setup?

# Answer
> 5 votes
Everything can be found out by reading the schematic which, incidentally, is the first hit on Google when you search for "Adafruit motor shield 2.3 schematic":

> What are the pin holes above and below the Arduino pins? Are they secondary positions for the pins?

Yes. They're just there to make it easy to solder wires and jumpers to.

> What is the PWMs 0,1,14,15?

They are connected to PWM pins 0, 1, 14 and 15 of the PCA9685.

> How is the big empty board in the center setup?

It's just holes. Known as a "matrix prototyping board" for you to solder your own components and things into. Nothing there is connected to anything at all, it's up to you to make the connections with solder and wires.

As you can see from the schematic the only Arduino pins used are SDA/SCL (A4 and A5) and two PWM pins D9 and D10. Everything else comes from the on-board I2C PWM chip.

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


# Question
Title: I get a redefinition of "..." on every single line, of every variable, class, function, etc
When I compile my program I get an error message saying redefinition of "..." on every single line, of every variable, class, function, etc.

What am I doing wrong?

```
int incomingByte = 0;   // for incoming serial data

int byteCount = 0;

bool decision = false;

bool last_debounce = false;

bool test_running = false;

bool ready_freq_enable = false;

int cur_cavity_address = 0;

char serBuffer[256] = {0};

unsigned long previousMillis_enable = 0;
const long interval_online = 1000 / 100;

unsigned long previousMillis_debounce = 0;
const long interval_debounce = 50;

void setup() {
  // put your setup code here, to run once:
 /* pinMode(22, OUTPUT);//address bit 1
  pinMode(24, OUTPUT);//address bit 2
  pinMode(26, OUTPUT);//address bit 3

  pinMode(36, INPUT);

  pinMode(40, OUTPUT);
  pinMode(48, OUTPUT);
  pinMode(52, OUTPUT);*/

  pinMode(2, OUTPUT);//address bit 1
  pinMode(3, OUTPUT);//address bit 2
  pinMode(4, OUTPUT);//address bit 3

  pinMode(5, OUTPUT);
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);

  pinMode(10, INPUT);

  Serial.begin(9600);
}

int seekChar(char c){
  for (int x = 0; x < 256; x++) {
    if (serBuffer[x] == c){
      return x;
    }
  }
  return -1;
}

void return_error(){
  Serial.println("ERROR!");
}

void loop() {
  if (Serial.available() > 0) {
          // read the incoming byte:
         int incomingByte = Serial.read();
          serBuffer[byteCount] = incomingByte;
          byteCount++;

          if (serBuffer[strlen(serBuffer)-1] == '\r'){
            serBuffer[strlen(serBuffer)-1] = 0; //remove the last carriage return

            int charIdx = seekChar(' ');
            char value[32] = {0};
            byteCount = 0;
            Serial.flush();

            if (charIdx != -1){
              memcpy(value, serBuffer + charIdx + 1, sizeof(value));
              memset(serBuffer + charIdx, 0, sizeof(serBuffer) - charIdx);
            }

            if (strcmp(serBuffer, "run") == 0){
              if (ready_freq_enable == true){
                test_running = strcmp(value, "true") == 0;
                if (test_running){
                  decision = 0;
                }
              } else {
                return_error();
              }

            } else if (strcmp(serBuffer, "reset") == 0){
              cur_cavity_address = 0;
              decision = false;
            } else if (strcmp(serBuffer, "decision") == 0){
              decision = strcmp(value, "true") == 0;
            } else if (strcmp(serBuffer, "enable") == 0){
              ready_freq_enable = strcmp(value, "true") == 0;

            } else if (strcmp(serBuffer, "address") == 0){
              if (abs(atoi(value)) > 8){
                return_error();
              }
              cur_cavity_address = abs(atoi(value));
            }

            memset(serBuffer, 0, sizeof(serBuffer));
            memset(value, 0, sizeof(value));

          }
  }

  test_running &= ready_freq_enable;
  update_io();
  check_status();
}

void check_status(){
  unsigned long currentMillis = millis();
  bool new_debounce =  digitalRead(10);
  if (new_debounce != last_debounce){

    if (currentMillis - previousMillis_debounce >= interval_debounce) {

    // save the last time you blinked the LED
      previousMillis_debounce = currentMillis;

      Serial.print( new_debounce );
      last_debounce = new_debounce;
    }

  } else {
    previousMillis_debounce = currentMillis;
  }
}

void update_io(){
  //digitalWrite(48, !digitalRead(48) );

  digitalWrite(7, test_running);

  digitalWrite(3, (cur_cavity_address & 0b001) != 0);
  digitalWrite(2, (cur_cavity_address & 0b010) != 0);
  digitalWrite(4, (cur_cavity_address & 0b100) != 0);

  unsigned long currentMillis = millis();
  //Serial.println(ready_freq_enable);
  if (currentMillis - previousMillis_enable >= interval_online) {
    // save the last time you blinked the LED
    previousMillis_enable = currentMillis;
    digitalWrite(5, !digitalRead(5) & ready_freq_enable);
    if (ready_freq_enable == false){
      cur_cavity_address = 0;
    }
  }

  digitalWrite(6, decision & ready_freq_enable);
}

```

# Answer
> 2 votes
Apparently I had a duplicate ino file on my same folder. Must of happened accidentally when I was creating a copy as backup. Thanks Chris!

---
Tags: arduino-uno, compilation-errors
---


# Question
Title: Print with round towards zero instead of round to nearest
When printing with one decimal place, Arduino's `Serial.println()` rounds numbers like `123.89` to “123.9”. Is there any way to change the rounding mode? For some reasons I want the value to be rounded towards zero (i.e., truncated) to one decimal place, like `123.89` → “123.8”.

here is the code

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

}

void loop()
{
float A = analogRead(A0);
A = (A/1023)*5.0;
Serial.print("A = ");
Serial.println(A,3);
float B = A*10;
Serial.print("A * 10 = ");
Serial.println(B,1);
delay(1000);
}

```

the output is

```
A = 2.473
A * 10 = 24.7
A = 2.488
A * 10 = 24.9
A = 2.517
A * 10 = 25.2
A = 2.527
A * 10 = 25.3
A = 2.507
A * 10 = 25.1

```

instead I want the output to be like this

```
A = 2.473
A * 10 = 24.7
A = 2.488
A * 10 = 24.8
A = 2.517
A * 10 = 25.1
A = 2.527
A * 10 = 25.2
A = 2.507
A * 10 = 25.0

```

is it possible ?

# Answer
A cheap trick to round a number to one decimal place (in "chop-off mode") is to multiply it by 10, convert it to an integer, and divide by `10.0f` again:

```
float myVal = 123.89f;
myVal = (long)(myVal * 10) / 10.0f;
// = ((long)1238.9) / 10.0f
// = 1238 / 10.0f
// = 123.8

```

You can then print this modified number to the serial monitor.

This method can also be generalized to other precisions. For 2 decimal places, we just have to multiply by 10^2 (100) and divide by 10^2. A macro would be:

```
#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

```

Note: You don't have to actually dynamically compute `pow(10, numDecimalPlaces)`, you can also create macros for each decimal precision from 1 to `x` and simply precompute that value (100, 1000, 10000, ..).

The same can also be achieved by using the standard library function `trunc` from `math.h`:

```
#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

```

See http://www.cplusplus.com/reference/cmath/trunc/.

Here's a small sketch in which it is demonstrated:

```
#include <Arduino.h>

#define TRUNCATE(val, numDecimalPlaces) \
    (float)(((long)((double)(val) * pow(10, (numDecimalPlaces) * 1.0f))) / (pow(10, (numDecimalPlaces)* 1.0f)))

#define TRUNCATE_TO_ONE(val) \
    (trunc((val) * 10.0f) / 10.0f)

void printValueFormatted(float value, int numDecimalPlaces) {
    //format correctly
    char buf[20];
    char* res = dtostrf(value, sizeof(buf)-1, numDecimalPlaces, buf);

    //skip over empty chars
    while(*res == ' ')
        res++;

    //print buffer
    Serial.println(res);
}

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

void loop(void)
{
    float myVal = 123.8978f;
    printValueFormatted(myVal, 4);
    printValueFormatted(TRUNCATE(myVal, 1), 1);
    printValueFormatted(TRUNCATE(myVal, 2), 2);
    printValueFormatted(TRUNCATE(myVal, 3), 3);
    printValueFormatted(TRUNCATE(myVal, 1), 4);
    printValueFormatted(TRUNCATE(myVal, 2), 4);
    printValueFormatted(TRUNCATE(myVal, 3), 4);
    delay(1000);
}

```

Prints

```
123.8978
123.8
123.89
123.897
123.8000
123.8900
123.8970

```
> 8 votes

# Answer
Use the given \[function\] for your problem. This function works on a pre-defined \[algorithm\].

```
int roundTowardZero(float number, int decimal_place) {
    float round_number = round(number);
    if(round_number > number) round_number = round_number - 1;
    float deci = (number - round_number) * pow(10, decimal_place);
    float round_decimal = round(deci);
    if(round_decimal > deci) round_decimal = round_decimal - 1;
    round_decimal = round_decimal / pow(10, decimal_place);
    total_number = round_number + round_decimal;
    return total_number;
}

```

Place this function above `int setup()`

like:

```
int roundTowardZero( ... ) {
    ...
}
void setup() {
    ...
}
void loop() {
    ...
}

```

Function syntex is like this : `roundTowardZero([Enter a Decimal Value], [Enter Round Place Value])` Example :`roundTowardZero(123.89, 1) //Output : 123.8`

Please comment below is you find any problem or face any error.
> 0 votes

---
Tags: arduino-uno, c, float
---


title: USB Mouse Passthrough

text:
# Question
Title: USB Mouse Passthrough
I am currently doing research for a project of mine. My goal is simple: I want to pass input from a physical mouse, to a microcomputer to process the input and modify, and send the input in the form of USB HID to a PC.

> Mouse ---\> Microcomputer (input modified) ---\> PC

The Microcomputer preferably should be able to both send data to the PC (in the form of USB HID inputs as a mouse) and receive data from the PC.

I found the arduino Leonardo can act as a USB slave and emulate mouse movement, half of what I want. I need some microcomputer with capabilities to act both as a USB host and as a USB slave. I don't have experience with microcomputers, and I don't know how to find something with this feature.

# Answer
> -1 votes
The cleanest solution to this problem would be to use an MCU with dual USB interfaces, one capable of being a USB host. There are a few such parts in the STM32F4 lineup, and likely other brands as well, but not immediately clear if there are any with existing Arduino support. Hardware wise, I believe you can do it with an inexpensive STM32F446 "Nucleo" board, though the pins of the USB interface are only available on headers, which you would need to wire to USB connectors.

A USB host shield is a possibility, but it's a bit "tacky" as a solution since it involves hanging a fairly sophisticated controller off a more primitive MCU, making an "upside down" architecture, and more expensive than an all-in-one solution, but it could be where you'll find the most existing code to support your effort.

One of the simplest things you could actually do would be to use a ps/2 mouse instead of a USB one, and interface that by bit-banging its simple serial interface. Then you could use a board like a Leonardo or one of the Teensy series which has a customizable USB device interface, to present to the host computer as a USB mouse.

# Answer
> 2 votes
Plug a USB Host Shield into the Leonardo.

```
USB mouse --- USB Host Shield --- Leonardo --- PC

```

USB Host Shield Library

Circuits@Home Project

```
/*
 * USB Mouse pass through. Works at HID report level. HID report is not decoded.
 * Tested on Leonardo with Arduino USB host shield, IDE 1.8.5, and Logitech Marble
 * trackball/mouse. This is a proof of concept so is not guaranteed to work with
 * all USB mice/trackballs.
 */
// USB host mouse from USB Host Shield Library. Install using Library Manager
#include <hidboot.h>

// USB device mouse library included with Arduino IDE 1.8.5
#include <Mouse.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

class MouseRptParser : public MouseReportParser
{
protected:
    void Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
};

void MouseRptParser::Parse(USBHID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
{
  Serial.print("MouseRptParser::Parse");
  // Show USB HID mouse report
  for (uint8_t i = 0; i < len ; i++) {
    Serial.print(' '); Serial.print(buf[i], HEX);
  }
  Serial.println();

  // On error - return
  if (buf[2] == 1)
    return;

  if (len > 2) {
    uint8_t mouseRpt[4];
    mouseRpt[0] = buf[0];
    mouseRpt[1] = buf[1];
    mouseRpt[2] = buf[2];
    mouseRpt[3] = 0;
    HID().SendReport(1,mouseRpt,sizeof(mouseRpt));
  }
}

USB     Usb;
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser Prs;

void setup()
{
  Serial.begin( 115200 );
#if !defined(__MIPSEL__)
  while (!Serial) delay(1); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  Serial.println("Start");

  if (Usb.Init() == -1) {
    Serial.println("USB host shield did not start.");
  }
  delay( 200 );

  HidMouse.SetReportParser(0, &Prs);

  Mouse.begin();
}

void loop()
{
  Usb.Task();
}

```

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


# Question
Title: Arduino RFID with motor and limit switches
Thanks for looking into my Arduino code. I'm building an automated sliding draw, and I'm trying to activate the motor with a RFID scanner. The scanner waits for the token, and once it detects a token the motor turns and waits for a limit switch to be detected and stops the motor, then it does the same thing when it detects another RFID token but instead the motor travels in the opposite direction and waits for the opposite limit switch to be hit. I have 2 sets of code. One is just the RFID scanner code which works fine, but it only switches a relay on and off. The other code is for the motor with 2 limit switches with a activation button. That code works too, and the draw opens and closes when you press a button, but it doesn't work with a RFID scanner. So my goal is to implement the RFID scanner code into the automated draw code in order to have a motor that turns and reverses with a RFID token and stops with a limit switch. I'm using an Arduino UNO board, 2 limit switches, a L298N H Bridge motor driver, and a MFRC522 RFID scanner.

Here is a schematic picture:

Here is the code for the automated draw using 3 buttons (2 limit switch, 1 activation button) and the DC motor:

```
// constants won't change. They're used here to set pin numbers:
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin3 = 1;     // the number of the pushbutton pin
const int buttonPin2 = 2;     // the number of the pushbutton pin
const int motorPin =  5;      // the number of the LED pin
const int motorPin2 =  6;      // the number of the LED pin

// variables will change:
boolean buttonState = 0;         // variable for reading the pushbutton status
boolean buttonState2 = 0;         // variable for reading the pushbutton status
boolean buttonState3 = 0;   // variable for reading the pushbutton status

int drawPosition = 2;  // Tells progam what position the draw is in

/**
 *  setup inputs for switches and outs for motor pins
 *  serial begin to read the switches to test for errors
 */
void setup() {
    // initialize the pin as an inputs:
    pinMode(motorPin, OUTPUT);
    pinMode(motorPin2, OUTPUT);
    // initialize the pushbutton pin as an input:
    pinMode(buttonPin, INPUT);
    pinMode(buttonPin2, INPUT);
    pinMode(buttonPin3, INPUT);
    Serial.begin(9600);
}

/**
 * this function turns motor foward
 */
void drawForward() {
     // turn motor foward:
     digitalWrite(motorPin, LOW);
     digitalWrite(motorPin2, HIGH);
}

/**
 * this function turns motor backwards
 */
void drawBackward() {
     // turn motor in other direction:
     digitalWrite(motorPin, HIGH);
     digitalWrite(motorPin2, LOW);
}

/**
 * Stop the motor form moving
 */
void stopDrawFromMoving() {
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);

}

/**
 *
 */
void loop() {
   // read the state of the pushbutton value:
     buttonState = digitalRead(buttonPin);
     buttonState2 = digitalRead(buttonPin2);
   buttonState3 = digitalRead(buttonPin3);

   // check if the pushbutton is pressed. If it is, the buttonState is HIGH:
   if (buttonState == HIGH) {
      drawPosition = 2;
      Serial.println(F("Front button state is high draw is open"));
      stopDrawFromMoving();
   }else if (buttonState2 == HIGH) {
      drawPosition = 1;
      stopDrawFromMoving();
  }

  if (buttonState3 == HIGH) {
    if( drawPosition  == 1 ){
      drawBackward();
      delay(100);
      drawPosition = 2;
      delay(100);
    }else if (drawPosition == 2 ) {
      delay(100);
      drawForward();
      delay(100);
      drawPosition = 1;
    }

  }
}

```

And that code you just read works fine, but it only activates the motor with a push button, but I'm trying to use RFID scanners.

Here is the code where I attempted to put the RFID code and the automated draw code together:

```
#include <EEPROM.h>     // We are going to read and write PICC's UIDs from/to EEPROM
#include <SPI.h>        // RC522 Module uses SPI protocol
#include <MFRC522.h>  // Library for Mifare RC522 Devices

//setting up inputs for limit switches and outputs for H Bridge motor driver
const int buttonPin = 4;     // the number of the pushbutton pin
const int buttonPin2 = 2;     // the number of the pushbutton pin
const int motorPin =  6;      // the number of the motors H Bridge (L298N) pin
const int motorPin2 =  5;      // the number of the motors H Bridge (L298N) pin

// variables for the state of the limit switches
boolean buttonState = 0;
boolean buttonState2 = 0;
int drawPosition = 2;  // Tells progam what position the draw is in

//this is the function to be called inside the loop. it makes the motor turn foward
void drawForward() {
  // turn H Bridge motor driver on in the foward polarity
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, HIGH);
}
// and this function turns the motor backwards
void drawBackward() {
  // turn H Bridge on with the REVERSED polarity
  digitalWrite(motorPin, HIGH);
  digitalWrite(motorPin2, LOW);
}
//This function is called when the motor needs to STOP moving
void stopDrawFromMoving() {
  //turn H Bridge motor driver OFF by turning both pins to LOW
  digitalWrite(motorPin, LOW);
  digitalWrite(motorPin2, LOW);
}

// Just stuff for the RFID to work
boolean match = false;          // initialize card match to false
boolean programMode = false;  // initialize programming mode to false
int successRead;    // Variable integer to keep if we have Successful Read from Reader
byte storedCard[4];   // Stores an ID read from EEPROM
byte readCard[4];   // Stores scanned ID read from RFID Module
byte masterCard[4];   // Stores master card's ID read from EEPROM
#define SS_PIN 10
#define RST_PIN 9
MFRC522 mfrc522(SS_PIN, RST_PIN); // Create MFRC522 instance.

///////////////////////////////////////// Setup ///////////////////////////////////
void setup() {
  // Setting up the digital read for limit switches
  buttonState = digitalRead(buttonPin);
  buttonState2 = digitalRead(buttonPin2);

  //Protocol Configuration for RIFD scanner
  Serial.begin(9600);  // Initialize serial communications with PC
  SPI.begin();           // MFRC522 Hardware uses SPI protocol
  mfrc522.PCD_Init();    // Initialize MFRC522 Hardware
  // This sets the RFID range to Maximum
  mfrc522.PCD_SetAntennaGain(mfrc522.RxGain_max);
  Serial.println(F("BlueCore Tech Acces Control"));   // For debugging purposes

  // Check if master card defined, if not let user choose a master card
  if (EEPROM.read(1) != 143) {
    Serial.println(F("No Master Card Set"));
    Serial.println(F("Scan A RFID Card to Set as Master Card"));
    do {
      successRead = getID();            // sets successRead to 1 when we get read from reader otherwise 0
    }
    while (!successRead);                  // Program will not go further while you not get a successful read
    for ( int j = 0; j < 4; j++ ) {        // Loop 4 times
      EEPROM.write( 2 + j, readCard[j] );  // Write scanned PICC's UID to EEPROM, start from address 3
    }
    EEPROM.write(1, 143);                  // Write to EEPROM we defined Master Card.
    Serial.println(F("Master Card Set"));
  }
  Serial.println(F("-------------------"));
  Serial.println(F("Master Card's UID = "));
  for ( int i = 0; i < 4; i++ ) {          // Read Master Card's UID from EEPROM
    masterCard[i] = EEPROM.read(2 + i);    // Write it to masterCard
    Serial.print(masterCard[i], HEX);
  }
  Serial.println("");
  Serial.println(F("-------------------"));
  Serial.println(F("Everything Ready"));
  Serial.println(F("Waiting for Keys or cards to be scanned"));
  cycleLeds();    // Everything ready lets give user some feedback by cycling leds
}
///////////////////////////////////////// Main Loop ///////////////////////////////////
void loop () {

//this first chunk of "if" is always setting the variable from iether "1" or "2" depending on what limit switch is closed, this allows the program to REMEMBER what the position of the draw is.
  if (buttonState == HIGH) {   //if the back limit switch is closed, the draw is in the closed (or backward) position
    drawPosition = 2;    //sets the variable to "2" meaning the draw is in the closed position
    Serial.println(F("Front button state is high so draw is open"));
    stopDrawFromMoving();  //this also stopes the motor form moving foward any further
  } else if (buttonState2 == HIGH) { // same principle applies here but its just reversed:
    drawPosition = 1;
    Serial.println(F("Back button state is high draw is open"));
    stopDrawFromMoving();
  }

// THERE IS A ERROR HERE I CANNOT FIX ////////////////////////////////////////////////////////////////////////////THERE IS A ERROR HERE I CANNOT FIX/////////////////////////////////////////THERE IS A ERROR HERE I CANNOT FIX///////////////////////////////////////
//   'getID' was not declared in this scope exit status 1      this happens anywhere inside the loop where there is a mention of the 'getID' function. I though this only happens if you calling a function but it doesnt exist, but it clearly does exist becuase its at the bottom
  do {
    successRead = getID();  // sets successRead to 1 when we get read from reader otherwise 0
    if (programMode) {
    }
    else {
      normalModeOn();     // Normal mode, blue Power LED is on, all others are off
    }
  }
  while (!successRead);   //the program will not go further while you not get a successful read
  if (programMode) {
    if ( isMaster(readCard) ) { //If master card scanned again exit program mode
      Serial.println(F("Master Card Scanned"));
      Serial.println(F("Exiting Programming Mode"));
      Serial.println(F("-----------------------------"));
      programMode = false;
      return;
    }
    else {
      if ( findID(readCard) ) { // If scanned card is known delete it
        Serial.println(F("I know this key, removing..."));
        deleteID(readCard);
        Serial.println("-----------------------------");
      }
      else {                    // If scanned card is not known add it
        Serial.println(F("I do not know this key, adding..."));
        writeID(readCard);
        Serial.println(F("-----------------------------"));
      }
    }
  }
  else {
    if ( isMaster(readCard) ) {   // If scanned card's ID matches Master Card's ID enter program mode
      programMode = true;
      Serial.println(F("Hello Master - Entered Programming Mode"));
      int count = EEPROM.read(0);   // Read the first Byte of EEPROM that
      Serial.print(F("I have "));     // stores the number of ID's in EEPROM
      Serial.print(count);
      Serial.print(F(" record(s) in DATABASE"));
      Serial.println("");
      Serial.println(F("Scan a Card or key to ADD or REMOVE"));
      Serial.println(F("-----------------------------"));
    }
    else {
      if ( findID(readCard) ) {  // If not, see if the card is in the EEPROM
        Serial.println(F("Welcome, Acces Granted"));
        //this is another part from the other code that im trying to implement into the RFID code
        if ( drawPosition  == 1 ) { //if the variale is saying the draw is currently in the FOWARD position
          drawBackward();  //then return it to the BACKWARD position
          delay(100);
          drawPosition = 2;  //then make the variable a "2" so the code remembers what the position of the draw is for next time the RFID scanner is activated
          delay(100);
        } else if (drawPosition == 2 ) {  //same principle under here but its just reversed for when the draw is found in the opposite position and needs to return to the opposite position
          delay(100);
          drawForward();
          delay(100);
          drawPosition = 1;
        }
      }
      else {   // If the token is unknown, show that the ID was not valid and dont do anything else
        Serial.println(F("Acces Denied!"));
      }
    }

  }
  ///////////////////////////////////////// Get PICC's UID ///////////////////////////////////
  int getID() {
    // Getting ready for Reading PICCs
    if ( ! mfrc522.PICC_IsNewCardPresent()) { //If a new PICC placed to RFID reader continue
      return 0;
    }
    if ( ! mfrc522.PICC_ReadCardSerial()) {   //Since a PICC placed get Serial and continue
      return 0;
    }
    // There are Mifare PICCs which have 4 byte or 7 byte UID care if you use 7 byte PICC
    // I think we should assume every PICC as they have 4 byte UID
    // Until we support 7 byte PICCs
    Serial.println(F("Scanned KEY's UID:"));
    for (int i = 0; i < 4; i++) {  //
      readCard[i] = mfrc522.uid.uidByte[i];
      Serial.print(readCard[i], HEX);
    }
    Serial.println("");
    mfrc522.PICC_HaltA(); // Stop reading
    return 1;
  }
  ///////////////////////////////////////// Show reader details ///////////////////////////////////
  void ShowReaderDetails() {
    // Get the MFRC522 software version
    byte v = mfrc522.PCD_ReadRegister(mfrc522.VersionReg);
    Serial.print(F("MFRC522 Version: 0x"));
    Serial.print(v, HEX);
    if (v == 0x91)
      Serial.print(F(" = v1.0"));
    else if (v == 0x11)
      Serial.print(F(" = BlueCore Tech. RFID Acces v2.0"));
    else
      Serial.print(F(" (unknown)"));
    Serial.println("");
    // When 0x00 or 0xFF is returned, communication probably failed
    if ((v == 0x00) || (v == 0xFF)) {
      Serial.println(F("WARNING: Communication failure, is the RFID-MFRC522 properly connected?"));
      while (true); // do not go further
    }
  }
  //////////////////////////////////////// Read an ID from EEPROM //////////////////////////////
  void readID( int number ) {
    int start = (number * 4 ) + 2;    // Figure out starting position
    for ( int i = 0; i < 4; i++ ) {     // Loop 4 times to get the 4 Bytes
      storedCard[i] = EEPROM.read(start + i);   // Assign values read from EEPROM to array
    }
  }
  ///////////////////////////////////////// Add ID to EEPROM   ///////////////////////////////////
  void writeID( byte a[] ) {
    if ( !findID( a ) ) {     // Before we write to the EEPROM, check to see if we have seen this card before!
      int num = EEPROM.read(0);     // Get the numer of used spaces, position 0 stores the number of ID cards
      int start = ( num * 4 ) + 6;  // Figure out where the next slot starts
      num++;                // Increment the counter by one
      EEPROM.write( 0, num );     // Write the new count to the counter
      for ( int j = 0; j < 4; j++ ) {   // Loop 4 times
        EEPROM.write( start + j, a[j] );  // Write the array values to EEPROM in the right position
      }
      successWrite();
      Serial.println(F("Succesfully added ID record to DATABASE"));
    }
    else {
      failedWrite();
      Serial.println(F("Failed! There is something wrong with ID or bad DATABASE"));
    }
  }
  ///////////////////////////////////////// Remove ID from EEPROM   ///////////////////////////////////
  void deleteID( byte a[] ) {
    if ( !findID( a ) ) {     // Before we delete from the EEPROM, check to see if we have this card!
      failedWrite();      // If not
      Serial.println(F("Failed! There is something wrong with ID or bad DATABASE"));
    }
    else {
      int num = EEPROM.read(0);   // Get the numer of used spaces, position 0 stores the number of ID cards
      int slot;       // Figure out the slot number of the card
      int start;      // = ( num * 4 ) + 6; // Figure out where the next slot starts
      int looping;    // The number of times the loop repeats
      int j;
      int count = EEPROM.read(0); // Read the first Byte of EEPROM that stores number of cards
      slot = findIDSLOT( a );   // Figure out the slot number of the card to delete
      start = (slot * 4) + 2;
      looping = ((num - slot) * 4);
      num--;      // Decrement the counter by one
      EEPROM.write( 0, num );   // Write the new count to the counter
      for ( j = 0; j < looping; j++ ) {         // Loop the card shift times
        EEPROM.write( start + j, EEPROM.read(start + 4 + j));   // Shift the array values to 4 places earlier in the EEPROM
      }
      for ( int k = 0; k < 4; k++ ) {         // Shifting loop
        EEPROM.write( start + j + k, 0);
      }
      successDelete();
      Serial.println(F("Succesfully removed ID record from DATABASE"));
    }
  }
  ///////////////////////////////////////// Check Bytes   ///////////////////////////////////
  boolean checkTwo ( byte a[], byte b[] ) {
    if ( a[0] != NULL )       // Make sure there is something in the array first
      match = true;       // Assume they match at first
    for ( int k = 0; k < 4; k++ ) {   // Loop 4 times
      if ( a[k] != b[k] )     // IF a != b then set match = false, one fails, all fail
        match = false;
    }
    if ( match ) {      // Check to see if if match is still true
      return true;      // Return true
    }
    else  {
      return false;       // Return false
    }
  }
  ///////////////////////////////////////// Find Slot   ///////////////////////////////////
  int findIDSLOT( byte find[] ) {
    int count = EEPROM.read(0);       // Read the first Byte of EEPROM that
    for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
      readID(i);                // Read an ID from EEPROM, it is stored in storedCard[4]
      if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
        // is the same as the find[] ID card passed
        return i;         // The slot number of the card
        break;          // Stop looking we found it
      }
    }
  }
  ///////////////////////////////////////// Find ID From EEPROM   ///////////////////////////////////
  boolean findID( byte find[] ) {
    int count = EEPROM.read(0);     // Read the first Byte of EEPROM that
    for ( int i = 1; i <= count; i++ ) {    // Loop once for each EEPROM entry
      readID(i);          // Read an ID from EEPROM, it is stored in storedCard[4]
      if ( checkTwo( find, storedCard ) ) {   // Check to see if the storedCard read from EEPROM
        return true;
        break;  // Stop looking we found it
      }
      else {    // If not, return false
      }
    }
    return false;
  }
  ///////////////////////////////////////// Write Success to EEPROM   ///////////////////////////////////
  void successWrite() {
    Serial.println(F("Write to EEPROM is Succsusful"));
  }
  ///////////////////////////////////////// Write Failed to EEPROM   ///////////////////////////////////
  void failedWrite() {
    Serial.println(F("Failed to write to EEPROM"));
  }
  ///////////////////////////////////////// Success Remove UID From EEPROM  ///////////////////////////////////
  void successDelete() {
    Serial.println(F("Removed from EEPROM"));
  }
  ////////////////////// Check readCard IF it is masterCard   ///////////////////////////////////
  // Check to see if the ID passed is the master programing card
  boolean isMaster( byte test[] ) {
    if ( checkTwo( test, masterCard ) )
      return true;
    else
      return false;
  }

```

So there's 2 main errors in the second code (the code implementing RFID with my limit switch logic and motor functions.) The first one was quite obvious in the code when I said "ERROR HERE" and the error is a "exit status 1 getID was not declared in this scope." Not sure why this happens, I cant make sense of it. Once that's fixed I can look at the main issue, and that's actually making it work. I have tested the code before I was getting that exit status error and the logic wasn't working. There is probably a better way of putting these to bits of code together but I'm fairly new to programing and I cant figure it out.

Thanks so much for your help ( :

# Answer
C++ and C only reads function declarations and globals from top to bottom, it will not look ahead to see if any others were defined.

You can put a declaration of the functions you want to use above where you want to use it.

```
//...
int getID();
///////////////////////////////////////// Main Loop ///////////////////////////////////
void loop () {
//...

```
> 2 votes

---
Tags: rfid, l298n
---


# Question
Title: String class summation disappears the right operand
I intend to create a function to jsify sensors' content and save it on a SD-card or send through a http client. Except for the `Serial.println`'s, the function is transcripted below.

```
String jsonificar(vector<vector<String>> sujeito){
  String json_txt = String(""), chave, valor;
  String chave_str, valor_str;

  json_txt+=String("{");
  for(unsigned int i = 0; i<sujeito.size(); i++){
    if(sujeito[i].size() != 2){
        Serial.println("Cada conteudo deve conter 2 textos!");
    }
    else{
        chave = sujeito[i][0];
        valor = sujeito[i][1];
        Serial.println(chave);
        Serial.println(valor);
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += chave;
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += ":";
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);
        json_txt += valor;
        Serial.println(json_txt);
        json_txt += "\\\"";
        Serial.println(json_txt);

        if(i != sujeito.size() - 1){
          json_txt += String(",");
        }
    }
  }

  json_txt+="}";
  Serial.println(json_txt);

  return json_txt;
}

```

The output on serial follows:

```
Output:

Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"    <===
{\"Chave1\":\"Valor1\",\"\"
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\": <===
{\"Chave1\":\"Valor1\",\"\":}

```

The arrows show the spots where the logs are different from expected: the keys and values provided are "Chave1", "Valor1", "Chave2", "Valor2". So, the key-value should be "Chave2":"Valor2". Would you have a grasp of this behaviour? I look forward for the answer!

# Answer
Your "disappearing string" has the following cause: Out-of-Memory.

You are constructing lots of `String` objects in your code and are concatinating to one. That uses memory on the heap for each `String` (and `realloc()` when the String memory must be expanded).

Consider the following test sketch which includes your code but also adds a memory leak by 150 bytes in each iteration:

```
#include <Arduino.h>
#include <ArduinoSTL.h>
using namespace std;

extern unsigned int __heap_start;
extern void *__brkval;

/*
 * The free list structure as maintained by the
 * avr-libc memory allocation routines.
 */
struct __freelist {
    size_t sz;
    struct __freelist *nx;
};

/* The head of the free list structure */
extern struct __freelist *__flp;

/* Calculates the size of the free list */
int freeListSize() {
    struct __freelist* current;
    int total = 0;
    for (current = __flp; current; current = current->nx) {
        total += 2; /* Add two bytes for the memory block's header  */
        total += (int) current->sz;
    }
    return total;
}

int freeMemory() {
    int free_memory;
    if ((int) __brkval == 0) {
        free_memory = ((int) &free_memory) - ((int) &__heap_start);
    } else {
        free_memory = ((int) &free_memory) - ((int) __brkval);
        free_memory += freeListSize();
    }
    return free_memory;
}

String jsonificar(vector<vector<String>> sujeito) {
    String json_txt = String(""), chave, valor;
    String chave_str, valor_str;

    json_txt += String("{");
    for (unsigned int i = 0; i < sujeito.size(); i++) {
        if (sujeito[i].size() != 2) {
            Serial.println("Cada conteudo deve conter 2 textos!");
        } else {
            chave = sujeito[i][0];
            valor = sujeito[i][1];
            Serial.println(chave);
            Serial.println(valor);
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += chave;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += ":";
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);
            json_txt += valor;
            Serial.println(json_txt);
            json_txt += "\\\"";
            Serial.println(json_txt);

            if (i != sujeito.size() - 1) {
                json_txt += String(",");
            }
        }
    }

    json_txt += "}";
    Serial.println(json_txt);

    return json_txt;
}

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

String myStr = "";

void loop(void) {

    Serial.print(F("Free Memory:"));
    Serial.println(freeMemory());

    //force a memory leak by allocating appending to a global String
    myStr +=
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
            "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

    vector<vector<String>> v =
            { { "Chave1", "Valor1" }, { "Chave2", "Valor2" }, };

    jsonificar(v);
    delay(1000);
}

```

From the output we can see the exact point where we have enough memory and the result is correct, and where we don't have enough memory and the string just "disappears" because there was not enough memory to allocate it:

```
Free Memory:911
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"Valor2\"}
Free Memory:761
Chave1
Valor1
{
{\"
{\"Chave1
{\"Chave1\"
{\"Chave1\":
{\"Chave1\":\"
{\"Chave1\":\"Valor1
{\"Chave1\":\"Valor1\"
Chave2
Valor2
{\"Chave1\":\"Valor1\",
{\"Chave1\":\"Valor1\",\"
{\"Chave1\":\"Valor1\",\"Chave2
{\"Chave1\":\"Valor1\",\"Chave2\"
{\"Chave1\":\"Valor1\",\"Chave2\":
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"
{\"Chave1\":\"Valor1\",\"Chave2\":\"

```
> 3 votes

---
Tags: string, json
---


# Question
Title: How do I get LEDs to turn on according to a continuous Python input?
I'm trying to make a tuner. 3 LEDs are connected to the Arduino board, each one corresponding to one situation (too high, low or correct).

Python handles the detecting of a note according to the mic input, and determines which led should be turned on, but as it's a live tuner, Python sends the information pretty fast.

I've figured out how to turn a led on one at a time and keep it on as long as the input doesn't change, but it only works at a low speed when I do it manually, with a Python program like this :

```
code=1
while code!=0:
    code=input("Code?")
    ser.write(code.encode('utf-8'))

```

If I try it with a Python code such as :

```
code= '5'
while 1:
ser.write(code.encode('utf-8'))

```

then the LEDs just stay off.

Here is my Arduino Code :

```
int hauteur = 0;

void setup() {
    pinMode (2, OUTPUT); //red pin
    pinMode (6, OUTPUT); //green pin
    pinMode (5, OUTPUT); //yellow pin
    Serial.begin(9600);
}

void loop() {
    if(Serial.available ()) {
        hauteur = Serial.parseInt();

        while (hauteur==2) {
            (digitalWrite(2,HIGH));
            if (Serial.available ()) { hauteur=Serial.parseInt(); }
        }
        digitalWrite(2,LOW);

        while (hauteur==5){
            (digitalWrite(5,HIGH));
            if (Serial.available ()) { hauteur=Serial.parseInt(); }
        }
        digitalWrite(5,LOW);

        while (hauteur==6){
            (digitalWrite(6,HIGH));
            if (Serial.available ()) { hauteur=Serial.parseInt(); }
        }
        digitalWrite(6,LOW);

        Serial.flush();
    }
}

```

If 2, 5 or 6 are received with enough time in between them, then the board does what it's supposed to do and turns on the according LED. How can I reduce that necessary lapse of time to get a real time change of lights like a live tuner?

# Answer
> 1 votes
You don't need to parseInt for one digit. Use Serial.read().

```
  hauteur = Serial.read() - 48; // 48 is ascii code of '0'

```

or better send bytes from python, not digit characters

---
Tags: arduino-uno, serial, led, communication, python
---


# Question
Title: How to make my servo slow down in it´s movement
I want to make my servo react on the data that my light sensor tells him by the amount of light that it is catching. I want the servo to go fast to the left when there is shadow/darkness and then I want it to go slowly back to the right when the light is back.

This is the code I´m now using for my 180 degrees servo. I also want this to work on my 360 degrees servo but because I am a beginner, I can´t figure it out...

```
#include <Servo.h>

Servo s;

void setup() {
  // put your setup code here, to run once:
  //pinMode(9,OUTPUT);
  pinMode(A0, INPUT);
  Serial.begin(9600);
  s.attach(9);
}

void loop() {
   float l = analogRead(A0);
   Serial.print(l);
   Serial.print(" ");
   int v = map(l,0,1024,0,179);
   s.write(v);
   Serial.println(v);

}

```

# Answer
The servo's rotation speed is controlled by its internal circuitry. Once you send it a new target position, it drives at it's maximum speed toward that position and decelerates as it approaches.

The best you can do to slow it down is to change its target stepwise, until you reach the target position, instead of setting the final target all at once. If you move it in several large steps, the motion will be jerky; if you send smaller steps at shorter intervals (so the total travel time will be same), the motion will get smoother.

If your application needs the smoothest motion possible, send it many tiny steps rapidly, again, observing your required total travel time. You should be able keep the servo constantly at (or closer to) it's approach speed.
> 2 votes

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


title: Firmata C++ library for host?

text:
# Question
Title: Firmata C++ library for host?
Firmata seems to be a popular protocol for communicating between the Arduino and host computer. However, there only seems to be C/C++ libraries for the Arduino. Most Firmata libraries for the host appear to be in Python. I've found a few C/C++ Firmata libraries for the host, but they seem incomplete and unmaintained. Is anyone aware of a full-featured C++ Firmata library designed to run on the host computer?

# Answer
> 3 votes
openFrameworks appears to have this capability. It's written in C++.

From openFrameworks - Communication:

> **Arduino and other serial devices communication**
>
> The communication module has classes to communicate with other devices by now through the serial protocol. This mainly allows to communicate with devices like the Arduino. There's 2 classes in this module, ofSerial which allows to communicate with any device through the serial protocol. It can be used to send custom commands to for example an Arduino sketch that will receive them and do something in response like turn an LED on, move a motor... It also works the other way around, you can send messages from the Arduino (or any other serial device), for example the read from a temperature sensor to openFrameworks.
>
> The second class, ofArduino, is specific to the arduino, it uses a protocol called **firmata** to send messages to and from the arduino that way you don't need to care about implementing the communication protocol from the Arduino sketch to openFrameworks and viceversa but instead you can just send and read values directly to and from any pin in the Arduino.

---
Tags: serial, firmata
---


# Question
Title: How to avoid calling multiple times Wire.begin() in libraries?
it's all in the title ; I'm developping a library and use \*TwoWire pointers in this library ; but I am using an external library that calls Wire.begin(). I've seen something about TWCR register in arduino but I don't know what it is exaclty.

Thanks in advance :)

# Answer
> 1 votes
What you are interested in is this bit of the Wire library:

```
TWCR = _BV(TWEN) | _BV(TWIE) | _BV(TWEA);

```

The important bit is the `TWEN` bit - TwoWire ENable.

If that bit is set in the TWCR register than Wire.begin() has been called already and you don't need to call it again:

```
if (TWCR & _BV(TWEN) == 0) {
    Wire.begin();
}

```

However, it really doesn't matter if you call it multiple times.

---
Tags: library, wire-library
---


title: Is the Arduino library so slow?

text:
# Question
Title: Is the Arduino library so slow?
I have a plan to operate 5MP camera module with the arduino Due. But I wonder if I can use the arduino libraries that include digitalRead, digitalWrite and so on. But some people said that it is a bad idea. Especially I found that people wrote values on registers instead of using the library, when they control ov7670 with Uno.

Contrary to this, ArduCam uses the libraries, even for OV5642!. Here is the link https://github.com/ArduCAM/Arduino/blob/master/ArduCAM/examples/mini/ArduCAM\_Mini\_OV5642\_Video\_Streaming/ArduCAM\_Mini\_OV5642\_Video\_Streaming.ino

So could anyone please let me know, if it is okay to use such library and never to use register directly? With 'register' I mean arduino's register, not camera's.

I guess the system clock and existence of FIFO would affect the answer. But still I don't know how to evaluate their effect analytically.

# Answer
Unless you have a really large number of read/write operations and very tight time constraints, I doubt you are going to have any significant advantage in terms of speed.

Accessing the bits in a port together, rather than individually is certainly more efficient, both in terms of time and space, but it might cost in readability, depending on how comfortable you are with leaving the Arduino libraries behind.

You can have also a look at this thread.

Notice that the maximum gain happens only when all the pins you have to read or write belong to the same register.
> 1 votes

# Answer
You can use ANY and ALL libraries (if their LICENCies allows it) you want, or none library at all.

More important is, if the result does what you need.

For some kinds of problems even very slow library is fast enought. For some kinds only highly optimized library can do. Some problems are so complex, that any Arduino cannot do it even with the best effort and total optimization of code and HW resources. (Well, for some problems even todays best supercomputers are not good enough)

Lot depends on what exactly you plan to do with such camera - if you need some simple controls (like START, STOT, change sesitivity ...) maybe anything is good. If you want to make some autonomous system navigated by vison system which would learn from experience and will recognize all your face expression, than there is no Arduino with needed computing power at all.

Just try find any project vaguelly similar to yours, look, what they are using and what they say about it (excelent, barely usable, we found it impossible) and try library/approach based on that. If it works somehow, make it better and be celebrity too :) If it does not work at all and does not yeld any usable results, maybe try something different.

A lot can be done, if you enhance Arduinos capabilities with external modules (commercial or home made) be it in form of shield or in form of totally different platform.
> 0 votes

---
Tags: library
---


# Question
Title: Library to send large amount of data over 433 MHz
I am trying to communicate between two Arduinos using two RF 433 MHz modules (transmitter receiver). I found that the library `Wildewire.h` allows a maximum of 77 bytes so is there any another library that allows to send a more than that?

# Answer
Radio modules send packets of data (and for very good reasons) so, if the total size of the data you want to send is greater than the packet limit, you have to engineer a higher level system (called a protocol) that can split your bigger message up into chunks that can be handled by the .h file.

I'm not saying one isn't available and indeed you may find one but, if you don't find one, you are facing the design of a protocol to handle bigger messages. It's not too difficult - imagine splitting the data you wish to send into 64 byte chunks and appending a single byte at the start of the data that describes the packet payload: -

* As being a full message
* As being a start of message (message overruns 64 bytes)
* As being a mid message
* As being an end of message (i.e. the last few bytes of data in the message)

This is enough information for your receiver code to reconstruct the original message but make sure you do good error checking if there isn't sufficient in the .h code. And also make sure your receiver "acknowledges" each packet received as being error free.

You might also wish to embed an address that makes your transmission and reception more robust or even add a packet count to the mid message marker byte. You have a maximum of 77 bytes for the payload so you have a few bytes spare for improving integrity but, the minimum payload system is 1 byte header and 76 bytes of payload (which may include other checks like CRC).
> 7 votes

---
Tags: rf
---


# Question
Title: How does an LED in an LED-strip like WS2811 know when it should be on or off
I was experimenting with an Arduino board and an LEDstrip WS2811 it works all perfect, but I do not understand how a particular led knows when it is called or adressed. Does every led have a unique address?

# Answer
The WS2811 is the driver chip, that is embedded into the strip. In principle it is some kind of shift register, that outputs PWM values, and on the strip they are daisy-chained (data output of one is connected to data input of the next). With the Arduino you shift out a stream of bytes, when using a RGB strip 3 bytes per LED (1 byte per color). The first WS2811 reads these 3 bytes, sets it's outputs (PWM) according to them and outputs the rest of the datastream to another pin, so that it can reach the next WS2811. The LEDs on the strip are connected to the WS2811's outputs.

So all in all the WS2811 chip saves the current desired state of it's LED, which it got through the data stream from the Arduino. The chips don't have a direct address, but can be identified by their position in the strip. So you cannot only write to the 5th LED without also writing values to the LEDs before it. But, if you don't want to set the whole strip, you can output less data, than the strip as LEDs, effectively ignoring the LEDs at the end.

---

EDIT:

> but How does it recognize the first led?

The strip has somewhat like a data line. When you look at the markings for this line on both ends of the strip, you normally should see something like "DI" and "DO", which means Data In and Data Out, each at one end of the strip. Each LED has it's own Data In and Data Out, which are chained to the next and the previous LED. The first and last LED expose their Data In or Data Out (respectively) to the outside of the strip. You feed the data into Data In of the first LED driver, which outputs the rest of the data at it's Data Out pin, where the data can go to the next driver. So the direction, in which the data flows through the strip is already defined and hardwired. You cannot send data in the other direction through the strip. So the first LED is that one, that is directly attached to the Data In line of the strip and will be connected to the Arduino.

Keep in mind, that this is not an address. You can cut the strip at an appropriate place (so that you don't destroy the circuit. Most strips have these pieces regularly after every or every third LED) and get a new first LED, if you now connect the Data In, where you cut the strip, to the Arduino. An LED strip with WS2811's is not an array or a matrix of LEDs, it is a chain of LEDs. This difference is important in how you control them.
> 8 votes

# Answer
The LED units don't have any unique addresses of their own, instead they are indexed by their position in the string of LEDs. When you feed data into the first LED, you put the entire sequence of color values into the first one. It will then set its own color to the first one in the sequence, and then output all the rest to the next LED in the series.

None of the LEDs actually "know" where in the strip they are located, they only take the first value that comes in and set their own color to that value, and then output the rest of the values to the next LED in the series.
> 5 votes

---
Tags: rgb-led
---


# Question
Title: How to track a pressure sensor from analog inputs?
I am a beginner with arduino. I have been researching pressure sensors composed of 2 conductors that sandwich a layer of velostat. My understanding is the velostat when compressed creates resistance between the conductive plates meaning when stepped on the charge decreases. I wanted to inquire about a wiring scheme for connecting these sensors to my analog inputs of a arduino nano with ideally 8 sensors connected to the 8 analog inputs. What is the wiring scheme? I would like to detect a gradation in sensitivity as best as possible for tracking someone applying pressure to that sensor. I have not built the sensors yet so that aspect of the project is open ended. Thanks for your attention in the matter. I am new to the world of electronics so please explain in elementary terms.

# Answer
It is not really clear, what exactly is your question here.

You are correct: The resistance of the velostat goes down, as pressure is applied to it. You have to build a voltage divider with the sensor and a normal resistor. The best value for that resistor highly depends on the sensor you build, because the way and the size you build it will control it's resistance. Then you can feed the middle pin of that voltage divider to an analog input.

The precision depends on many factors, including the sensor itself and the noise, that gets introduced into the analog input. Try and tweak your circuit, until it suits your needs.
> 0 votes

---
Tags: sensors, arduino-nano, pressure
---


# Question
Title: Need help with converting Celsius to Fahrenheit in the code
I'm new to Arduino and trying to figure out how to convert Celsius to Fahrenheit with the parameters listed below. Do I need to create a separate file for the calculations? If so, can someone help me on how I can go about doing that?

```
#include <DHT.h>
#include <DHT_U.h>

int SENSOR = 2;
int TEMPERATURE;
int HUMIDITY;

DHT dht(SENSOR, DHT11);

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

void loop() {
  TEMPERATURE = dht.readTemperature();
  HUMIDITY = dht.readHumidity();
  Serial.print("Temp: ");
  Serial.print(TEMPERATURE);
  Serial.println(" celsius ");
  Serial.println(" ");
  Serial.print("Humidity: ");
  Serial.println(HUMIDITY);
  delay(2000);

  //Built In LED
  digitalWrite(LED_BUILTIN, HIGH);  // turn the LED on (HIGH is the voltage level)
  delay(250); // wait for a second
  digitalWrite(LED_BUILTIN, LOW); // turn the LED off by making the voltage LOW
  delay(250);
}

```

# Answer
If you are using the Adafruit DHT sensor library, then you can get a Fahrenheit reading by passing `true` as an argument to `readTemperature()`. C.f. the comment in the source code. For example:

```
Serial.print("Temp: ");
Serial.print(dht.readTemperature(true));  // true -> Fahrenheit
Serial.println(" deg. F");

```

Note that this library offers also the conversion functions `convertCtoF()` and `convertFtoC()`.
> 2 votes

# Answer
You could add a function to your sketch.

```
// Celsius to Fahrenheit conversion
double Fahrenheit(double celsius){
  return 1.8 * celsius + 32;
}

```

Then add this code to your loop().

```
Serial.print("Temp: ");
Serial.print(Fahrenheit(TEMPERATURE));
Serial.println(" fahrenheit ");

```
> 1 votes

---
Tags: arduino-uno, temperature-sensor
---


# Question
Title: What is a simple way to measure the ambient light?
I want to install some LED stripes on my motorcycle, i.e. as brake light and indicators. I use WS2812 LED stripes which can be very bright - especially with many LEDs on at the same time.

I want to measure the ambient light so that in the bright sun I can light the LEDs with, let's say, 100%. But in the night maybe just with 30% intensity. I want to detect the ambient light to change the intensity.

I don't need high resolution and I don't need high speed. If the ambient light is measured i.e. once per second with 4 bit resolution that would be already good enough.

Which ambient light sensor (or photo diode or whatever) makes sense for this little project and how to connect it? Does it make sense to use more than one light sensor for a better average ambient light value (just in case one sensor is in the shadow, another in the sun)?

I found these sensors form a Chinese supplier:

https://www.banggood.com/CJMCU-9930-APDS-9930-Digital-Proximity-And-Ambient-Light-Sensor-For-Arduino-p-1103139.html

https://www.banggood.com/GY-49-MAX44009-Ambient-Light-Sensor-Module-For-Arduino-p-1196674.html

But an I2C interface seems to be overkill for my simple project.

Any suggestions?

# Answer
> 4 votes
Perhaps a LDR and a 10k ohm resistor might work.

```
#define LDRpin A0
unsigned int LDRvalue = 0;

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

void loop(){
  LDRvalue = analogRead(LDRpin);
  Serial.println(LDRvalue);
  delay(1000);
}

```

# Answer
> 2 votes
You can also use an LED. Connect the LED and its resistor between two port pins. Then, when you want to measure ambient light in your program, do this:

1. Make sure any pullups/pulldowns are disabled.
2. To discharge the LED, start with switching it on for a short moment (a clock cycle is enough) by setting the pins to output and setting anode high and cathode low.
3. Reverse the polarity by setting the anode pin low and the cathode pin high.
4. Set the cathode pin to input.
5. Using a timer and a pin change interrupt, measure the time it takes for the cathode pin to become low.

Since the capacity of the LED varies with light intensity, the time it takes for the LED to discharge through its resistor and the pin resistance is is an indication of light intensity.

---
Tags: sensors
---