# Question
Title: Is using malloc() and free() a really bad idea on Arduino?
The use of `malloc()` and `free()` seems pretty rare in the Arduino world. It is used in pure AVR C much more often, but still with caution.

Is it a really bad idea to use `malloc()` and `free()` with Arduino?

# Answer
> 51 votes
My general rule for embedded systems is to only `malloc()` large buffers and only once, at the start of the program, e.g., in `setup()`. The trouble comes when you allocate and de-allocate memory. Over a long run session, memory becomes fragmented and eventually an allocation fails due to lack of a sufficiently large free area, even though the total free memory is more than adequate for the request.

(Historical perspective, skip if not interested): Depending on the loader implementation, the only advantage of run-time allocation vs. compile-time allocation (intialized globals) is the size of the hex file. When embedded systems were built with off the shelf computers having all volatile memory, the program was often uploaded to the embedded system from a network or an instrumentation computer and the upload time was sometimes an issue. Leaving out buffers full of zeros from the image could shorten the time considerably.)

If I need dynamic memory allocation in an embedded system, I generally `malloc()`, or preferably, statically allocate, a large pool and divide it into fixed-size buffers (or one pool each of small and large buffers, respectively) and do my own allocation/de-allocation from that pool. Then every request for any amount of memory up to the fixed buffer size is honored with one of those buffers. The calling function doesn't need to know whether it's larger than requested, and by avoiding splitting and re-combining blocks we solve fragmentation. Of course memory leaks can still occur if the program has allocate/de-allocate bugs.

Update 02/16/23:

> I'm curious why the Arduino library's malloc implementation doesn't implement some coalescing of the free blocks like a full OS would.

That's interesting to think about, but let's first be clear that in C/C++, malloc() and free() are implemented as library functions at the application-level not the OS level, even in major OSes. And they are based on fragmenting the heap, just as the Arduinos' malloc() functions do.

Embedded systems, are relatively new, at least as an influential force in the design of OSes, languages, and libraries' design. Which is to say, programs that had to run "forever" without failing (other than, perhaps the OS itself) were outliers. Most programs we run on our desktops or (once upon a time) ran on mainframes, were started, processed a batch of data, and exited.

Secondly, the malloc()/free() method of memory allocation/deallocation was simple, where anticipating the sizes of memory requests was not; and some allocations are used briefly and returned, where some are kept for the duration of the run. How is a library designer to provide for coalescing currently free and newly deallocated memory with no knowledge of the allocate/deallocate usage and sizes of requests? The fixed-size buffer scheme I described above doesn't suffer the fragmentation problem that "malloc() an arbitrary number of bytes" scheme does. It is still limited to available memory but within that limitation, could meet the "run forever" requirement. There may be algorithms that split and coalesce memory, but probably only for a few - statistically predictable - patterns of allocation and deallocation.

Update 02/18/23:

@edgarbonet points out that Arduino's `free()` does try to coalesce free blocks. This is a good example of an algorithm that works for certain cases: Properly done, it would work for "last-out / first-in" cases, and to some extent for some other cases.

The trouble is, most of our use patterns are not very regular, if they're regular at all. An alogrithm that does no splitting, but merely allocates & deallocates fixed-size pieces (rather like loaning library books) can still run out of memory but won't end up with fragmented resources. In fact, because it doesn't split, it *will* need more memory to meet the same random-sized requests than even a coalescing `malloc()` and `free()`.

# Answer
> 21 votes
I have taken a look at the algorithm used by `malloc()`, from avr-libc, and there seems to be a few usage patterns that are safe from the point of view of heap fragmentation:

## 1. Allocate only long-lived buffers

By this I mean: allocate all you need at the beginning of the program, and never free it. Of course, in this case, you could as well use static buffers...

## 2. Allocate only short-lived buffers

Meaning: you free the buffer before allocating anything else. A reasonable example might look like this:

```
void foo()
{
    size_t size = figure_out_needs();
    char * buffer = malloc(size);
    if (!buffer) fail();
    do_whatever_with(buffer);
    free(buffer);
}

```

If there is no malloc inside `do_whatever_with()`, or if that function frees whatever it allocates, then you are safe from fragmentation.

## 3. Always free the last allocated buffer

This is a generalization of the two previous cases. If you use the heap like a stack (last in is first out), then it will behave like a stack and not fragment. It should be noted that in this case it is safe to resize the last allocated buffer with `realloc()`.

## 4. Always allocate the same size

This will not prevent fragmentation, but it is safe in the sense that the heap will not grow larger than the maximum *used* size. If all your buffers have the same size, you can be sure that, whenever you free one of them, the slot will be available for subsequent allocations.

# Answer
> 19 votes
Typically, when writing Arduino sketches, you will avoid dynamic allocation (be it with `malloc` or `new` for C++ instances), people rather use global -or `static`\- variables, or local (stack) variables.

Using dynamic allocation can lead to several problems:

* memory leaks (if you lose a pointer to a memory you previously allocated, or more likely if you forget to free the allocated memory when you don't need it anymore)
* heap fragmentation (after several `malloc`/`free` calls) where the heap grows bigger thant the actual amount of memory allocated currently

In most situations I have faced, dynamic allocation was either not necessary, or could be avoided with macros as in the following code sample:

**MySketch.ino**

```
#define BUFFER_SIZE 32
#include "Dummy.h"

```

**Dummy.h**

```
class Dummy
{
    byte buffer[BUFFER_SIZE];
    ...
};

```

Without `#define BUFFER_SIZE`, if we wanted `Dummy` class to have a non-fixed `buffer` size, we would have to use dynamic allocation as follows:

```
class Dummy
{
    const byte* buffer;

    public:
    Dummy(int size):buffer(new byte[size])
    {
    }

    ~Dummy()
    {
        delete [] bufer;
    }
};

```

In this case, we have more options than in the first sample (e.g. use different `Dummy` objects with different `buffer` size for each), but we may have heap fragmentation issues.

Note the use of a destructor to ensure dynamically allocated memory for `buffer` will be freed when a `Dummy` instance is deleted.

# Answer
> 10 votes
I disagree with people who think you shouldn't use it or it is generally unnecessary. I believe it can be dangerous if you don't know the ins and outs of it, but it is useful. I do have cases where I don't know (and shouldn't care to know) the size of a structure or a buffer (at compile time or run time), especially when it comes to libraries I send out into the world. I agree that if you're application is only dealing with a single, known structure, you should just bake in that size at compile time.

Example: I have a serial packet class (a library) that can take arbitrary length data payloads (can be struct, array of uint16\_t, etc.). On the sending end of that class you simply tell the Packet.send() method the address of the thing you wish to send and the HardwareSerial port through which you wish to send it. However, on the receiving end I need a dynamically allocated receive buffer to hold that incoming payload, as that payload could be a different structure at any given moment, depending on the application's state, for instance. IF I'm only ever sending a single structure back and forth, I'd just make the buffer the size it needs to be at compile time. But, in the case where packets may be different lengths over time, malloc() and free() are not so bad.

I've run tests with the following code for days, letting it loop continuously, and I've found no evidence of memory fragmentation. After freeing the dynamically allocated memory, the free amount returns to its previous value.

```
// found at learn.adafruit.com/memories-of-an-arduino/measuring-free-memory
int freeRam () {
    extern int __heap_start, *__brkval;
    int v;
    return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}

uint8_t *_tester;

while(1) {
    uint8_t len = random(1, 1000);
    Serial.println("-------------------------------------");
    Serial.println("len is " + String(len, DEC));
    Serial.println("RAM: " + String(freeRam(), DEC));
    Serial.println("_tester = " + String((uint16_t)_tester, DEC));
    Serial.println("alloating _tester memory");
    _tester = (uint8_t *)malloc(len);
    Serial.println("RAM: " + String(freeRam(), DEC));
    Serial.println("_tester = " + String((uint16_t)_tester, DEC));
    Serial.println("Filling _tester");
    for (uint8_t i = 0; i < len; i++) {
        _tester[i] = 255;
    }
    Serial.println("RAM: " + String(freeRam(), DEC));
    Serial.println("freeing _tester memory");
    free(_tester); _tester = NULL;
    Serial.println("RAM: " + String(freeRam(), DEC));
    Serial.println("_tester = " + String((uint16_t)_tester, DEC));
    delay(1000); // quick look
}

```

I haven't seen any sort of degradation in RAM or in my ability to allocate it dynamically using this method, so I'd say it's a viable tool. FWIW.

# Answer
> 9 votes
Using dynamic allocation (via `malloc`/`free` or `new`/`delete`) isn't inherently bad as such. In fact, for something like string processing (e.g. via the `String` object), it's often quite helpful. That's because many sketches use several small fragments of strings, which eventually get combined into a larger one. Using dynamic allocation lets you use only as much memory as you need for each one. In contrast, using a fixed-size static buffer for each one could end up wasting a lot of space (causing it to run out of memory much faster), although it depends entirely on the context.

With all of that being said, it's very important to make sure memory usage is predictable. Allowing the sketch to use arbitrary amounts of memory depending on run-time circumstances (e.g. input) can easily cause a problem sooner or later. In some cases, it might be perfectly safe, e.g. if you *know* the usage will never add up to much. Sketches can change during the programming process though. An assumption made early-on could be forgotten when something is changed later, resulting in an unforeseen problem.

For robustness, it's usually better to work with fixed-size buffers where possible, and design the sketch to work explicitly with those limits from the outset. That means any future changes to the sketch, or any unexpected run-time circumstances, should hopefully not cause any memory problems.

# Answer
> 4 votes
> Is it a really bad idea to use malloc() and free() with Arduino?

The short answer is yes. Below are the reasons why:

It is all about understanding what an MPU is and how to program within the constraints of the available resources. The Arduino Uno uses an ATmega328p MPU with 32KB ISP flash memory, 1024B EEPROM, and 2KB SRAM. That is not a lot of memory resources.

Remember that the 2KB SRAM is used for all global variables, string literals, stack and possible usage of the heap. The stack also needs to have head room for an ISR.

The memory layout is:

Todays PC/laptops have more than 1.000.000 times the amount of memory. A 1 Mbyte default stack space per thread is not uncommon but totally unrealistic on an MPU.

An embedded software project has to do a resource budget. This is estimating ISR latency, necessary memory space, compute power, instruction cycles, etc. There are unfortunately no free-lunches and hard real-time embedded programming is the most difficult of programming skills to master.

# Answer
> -1 votes
Ok, I know this is an old question but the more I read through the answers the more I keep coming back to an observation that seems salient.

## The Halting Problem Is Real

There seems to be a link with Turing's Halting Problem here. Allowing dynamic allocation increases the odds of said 'halting' so the question becomes one of risk-tolerance. While it is convenient to wave off the possibility of `malloc()` failing and so forth, it is still a valid outcome. The question the OP asks only appears to be about technique, and yes the details of the libraries used or the specific MPU do matter; the conversation turns towards reducing the risk of the program halting or any other abnormal end. We need to recognize the existence of environments that tolerate risk vastly differently. My hobby project to display pretty colors on a LED-strip won't kill someone if something unusual happens but the MCU inside a heart-lung machine likely will.

## Hello Mr. Turing My Name is Hubris

For my LED-strip, I don't care if it locks up, I'll just reset it. If I were on a heart-lung machine controlled by an MCU the consequences of it locking up or failing to operate are literally life and death, so the question about `malloc()` and `free()` should be split between how the intended program deals with the possibility of demonstrating Mr. Turing's famous problem. It can be easy to forget that it is a mathematical proof and to convince ourselves that if only we are clever enough we can avoid being a casualty of the limits of computation.

This question should have two accepted answers, one for those who are forced to blink when staring The Halting Problem in the face, and one for all others. While most uses of the arduino are likely not mission critical or life-and-death applications, the distinction is still there regardless of which MPU you may be coding.

---
Tags: programming, sram, eeprom
---


# Question
Title: Why does a variable size struct not compile in the Arduino IDE?
This sketch does not compile in the Arduino IDE

```
void setup() {
  // put your setup code here, to run once:

}

struct test {
  int i;
  char variable[];
};

typedef struct test test;

test t = {
  0, "hi"
};

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

}

```

Arduino throws

```
sketch_may09a:16: error: initializer-string for array of chars is too long [-fpermissive]

 };

 ^

exit status 1
initializer-string for array of chars is too long [-fpermissive]

```

However compiling with g++ works just fine. How can I fix it? Or is there a principle reason why flexible array members are not supported?

# Answer
*Flexible array member* is a C feature. It does not exist in C++. On top of that, the way you use it to declare and initialize a static struct of flexible size is non-standard even for C.

**However**, GNU-C language supports it as an extension. Also, newer versions of GCC (6 and higher) allow this in GNU-C++ code as an extension as well. But GCC 5.4.0 used by Arduino IDE doesn't support this non-standard feature in C++ code.

If you flip through different GCC versions on Godbolt (https://godbolt.org/z/Iul7hD) you'll see that support for this feature has always been present in C code, but for C++ code it first appeared in GCC 6.

This is why you were able to compile it with your standalone `g++` compiler (which is apparently a much later version), but were unable to compile it in Arduino IDE.

It means that if you really want this non-standard code to compile in the current version of Arduino IDE, you have to place it into a `.c` file. Or just specify the array size explicitly.
> 5 votes

# Answer
Maybe you've compiled it in g++ without any warnings enabled (or maybe it yeld warnings but was compiled). The arduino uses flags to consider all warnings as an error, so it won't compile. It may wary for different platforms, I've got -fpermissive used (and I don't like it at all).

That's because size of struct must be known compile time and if you provide `char variable[];` you'll get zero sized array. Therefore anything biiger than nothing you'll try to initialize for is too long.

Maybe you're looking for something like this:

```
struct test {
  int a;
  const char * ptr;
};

test paramx {1, "some string"};
test paramy {2, "another string"};

test array[] = {{3,"three"}, {4, "four"}, {5,"five"}};

```
> 2 votes

---
Tags: programming, array, struct
---


# Question
Title: How to use PROGMEM in a .h/.cpp file instead of a .ino file?
I want to use a lot of `.h`/`.cpp` files to be used by my `ino` sketch. In one of these .cpp files (and later more) I want to use constant arrays (like lookup tables). To save SRAM I want to use `PROGMEM`.

What worked before in the Ino sketch is:

```
const uint8_t _red[]   PROGMEM = { 0, 9, 10, 220, 230, 240, 255 };

```

But when I put the line above in a `.h` or `.cpp` file I get the error:

```
Par.h:13:25: error: expected initializer before 'PROGMEM'

```

Should I include something or can't I use `PROGMEM` in a `.h`/`.cpp` file?

# Answer
I already found the answer.

Include:

```
#include <avr/pgmspace.h>

```

**Update**

See also remark of AnT, which is a more generic (and in most cases better solution):

```
#include "Arduino.h"

```

(just to help others with the same problem).
> 1 votes

---
Tags: programming, progmem
---


# Question
Title: How do I make a stepper motor compass cross 360° to 0°?
I am building a wet compass for a flight simulator. I currently have a stepper motor functioning well with the simulator but at the point of crossing 360° to 0° the stepper does a full reverse 360° to get into position.

My question... can anyone please assist me in creating code that makes the linear cross from 360° to 0° work in both directions?

The simulator feeds a `float val` that is a degree out of 360° e.g. 172.13. My stepper has 4076 steps per full revolution. You will see the math in the code below. I am using the `AccelStepper` library.

```
void ProgOut(byte id, float val) {
switch (1) {
case 1:

if (val)
        { stepper1.moveTo(val * 11.3222222);         }

        stepper1.run();

break; }}

```

I have tried something like this:

```
void ProgOut(byte id, float val) {
switch (1) {
case 1:
if ( stepper1.distanceToGo () >= 4064){
          stepper1.moveTo(4076);
          stepper1.setCurrentPosition(0);
}
    else if (val)
        {

                stepper1.moveTo(val * 11.3222222);
        }

        stepper1.run();

break; }}

```

# Answer
> 1 votes
Two options (for starters):

1. Use the `move()` class rather than the `moveTo()` class. This will allow you to do relative moves rather than absolute.
2. Use `setCurrentPosition()` (which sets the current position to zero) followed by `moveTo()` with a destination which is `newPos - prevPos`.

For either to work you will need to keep track of the current position of the needle.

To work out the relative move you will need to do some kink of modulo arithmetic but this will require some trickery to generate negative values for anti-clockwise moves.

```
// delta is the angular adjustment required.
delta = (currHeading + 180 - prevHeading) % 360 - 180;
setCurrentPosition();        // Zero the motor.
moveTo(delta);               // Move absolute from the new zero.
prevHeading = currHeading;   // Keep track.

```
* The code assumes that you will never have to make a heading adjustment of more that 180° in one step.
* Adding in the 180° before the modulo calculation and subtracting it again afterwards is a trick to allow negative results from the modulo arithmetic.

# Answer
> 1 votes
Also working on making a compass for flight simulator. Hopefully the following code will help answer the question. This is a working code that I have tested using serial monitor... Note: For Flight Sim use, I did find that to get enough speed and smooth movement for the X27-168 gauge motor you need to use a stepper driver with microstepping rather than driving the X27-168 directly from the Nano I/O pins. You will have to adjust Max speed & acceleration and also edit the firmware for micro-stepping with using a stepper driver. Note: When using a stepper driver chip, you need to use the correct type for 6 step coil energising that the X27-168 stepper uses eg. AX1201728SG. Polulu (A4988) type stepper drivers use 8 steps coil energisation which will not move the gauge motor correctly - while it will move the gauge motor it creates a lot of noise and is not ideal.

I did have to add the following to get both left and right movements through North. I used Movement rather than delta -
if(Movement( \< -180){Movement = Movement + 360;}

A single movement of 180 degrees defaults to CCW direction. however with Flight simulator data extraction, you shouldn't get a single movement of that amount.

---

---

```
/*Analog Compass Gauge.**
This uses an Arduino Nano processor that has four of its I/O's directly connected to an X27-168 geared stepper motor(Gauge indicator motor).
While it works, there should really be four sets of protection diodes across each of the I/O pins - diode to +5V & diode to 0V to eliminate spikes over 5v and below 0v on each I/O pin.
The X27-168 geared stepper motor has had the internal stop cut off on the main output shaft gear to allow full 360 degree movement.
A 55mm dia plastic round plate has been fitted to the X27-168 geared stepper motor 1mm diameter drive shaft and a printed label attached to the plate to show compass direction.
The plastic plate has a small Neodymium magnet (1mm dia x 2mm long) which can pass near a Hall Effect sensor (A3144)to provide a homing reference signal.
+5v,0v and I/O signal pin is connected directly to the Hall Effect sensor. The Nano internal I/O resistor is used to provide a pullup voltage for the Hall effect sensor signal.  The firmware uses the AccelStepper library.
PC Serial Monitor is used to enter new compass headings.
The X27-168 geared stepper motor is referred to as "stepper1" in the firmware.
*/
    #include "AccelStepper.h"
        AccelStepper Stepper1(AccelStepper::FULL4WIRE, 3, 4, 5, 6);   // Define stepper I/O pins (Using I/O pins connected directly to X27-168 Geared Stepper Motor)
       //AccelStepper Stepper1(AccelStepper::DRIVER, 2, 5); // Defines I/O pins when using a stepper driver e.g. AX1201728SG Quad driver chip -  Dir pin - Stepper pin
       #define Home_Sensor      2   // Pin 2 - Connected to Home Sensor - Hall Effect A3144- (0v when sensed)
       int Offset = -67;   // ****** Adjust this setting to ensure North facing when at Home Position(0)  ******
       int MaxSpeed = 80;   // ****** Adjust this setting for Max Speed of Stepper as to not miss steps    ******
       int Acceleration = 25   // ****** Adjust this setting for Acceleration of Stepper as to not miss steps ******
       int    Move_finished =   1;   // Used to check if move is completed
       long   Initial_Homing = -1;   // Used to Home Stepper at startup
       String InputString =    "";   // String to hold incoming data from serial monitor
       bool   StringComplete = false;   // Whether the string is complete
       int    LastHeading = 0;   // Register for Last heading
       int    NewHeading  = 0;   // Register for New heading
       int    Movement;   // Register for difference between Last and New heading
       void setup() {
       Serial.begin(9600);   // Start the Serial monitor at 9600 Baud
       pinMode(Home_Sensor, INPUT_PULLUP);   // Using internal pullup for Hall Effect sensor
       delay(5);   // Wait for stepper Driver wake up (if used)
       Stepper1.setMaxSpeed(MaxSpeed);   // Intial Homing Max Speed of Stepper (Slower to get better accuracy)
       Stepper1.setAcceleration(Acceleration );   // Intial Homing Acceleration of Stepper
       Serial.println("........ Homing Stepper ........");

       while (digitalRead(Home_Sensor)) {   // Make the Stepper1 move CW until the sensor is activated
       Stepper1.moveTo(Initial_Homing);   // Set the position to move to
       Initial_Homing--;   // Decrease by 1 for next move if needed
       Stepper1.run();   // Start moving stepper1
       delay(5);
       }
       Stepper1.setCurrentPosition(0);   // Set the current position as zero for now
       Initial_Homing=1;
       while (!digitalRead(Home_Sensor)) {   // Make the Stepper1 move CCW until the sensor is deactivated
       Stepper1.moveTo(Initial_Homing);
       Stepper1.run();
       Initial_Homing++;
       }
       //**** Should now be Homed to Magnet position which may not be North as per label. Below allows tuning to correct position of label ****
       Stepper1.setCurrentPosition(0);
       Stepper1.setMaxSpeed(MaxSpeed);   // Intial Homing Correction Max Speed of Stepper1
       Stepper1.setAcceleration(Acceleration );   // Intial Homing Correction Acceleration of Stepper1

       Stepper1.moveTo(Offset);   // To correct to have North as Home position
       while(Stepper1.distanceToGo() != 0){Stepper1.run();}   // Step to adjusted home position
       Stepper1.setCurrentPosition(0);   // Set Home position that will be used for all further movements..
       Serial.println("........ Homing Completed ........");
       Serial.println(" *** Enter Compass Heading 0 - 259 Degrees ***");
       // ---------   End of intial Homing Setup  ------------
       }
       void loop() {
       while (Serial.available() > 0) {   // Read serial input:
       int InChar = Serial.read();
       if (isDigit(InChar)) {InputString += (char)InChar;}   // Convert the incoming byte to a char and add it to the string
       if (InChar == '\n') {   // If you get a newline,
       NewHeading = (InputString.toInt());   // Convert input heading string to int value heading
       NewHeading = (NewHeading/2)*2;   // Eliminates 1 degree movements. Reduces movement errors with small movements
       Serial.print(NewHeading);

       if(NewHeading > 359 ||NewHeading < 0) {   // Displays error message if input is out of range
       NewHeading = LastHeading;   // No change due to incorrect data entered
       Serial.println("Input Error. Enter value between 0 - 259 Degrees ");
       }
       else { Serial.print("Heading "); Serial.print(NewHeading); Serial.println("...  Enter New Heading");

       }
       InputString = "";   // Clear the string for new input:
       Movement = ((NewHeading + 180 - LastHeading) % 360) - 180;   // Allows movement from North East to North West
       if(Movement < -180){Movement = Movement + 360;}   // Allows movement from North West to North East
       Stepper1.setCurrentPosition(0);   // Zero the motor.
       Stepper1.setMaxSpeed(MaxSpeed);   // Set Max Speed of Stepper1
       Stepper1.setAcceleration(Acceleration );   // Set Acceleration of Stepper1

       Stepper1.move(Movement*2);   // Set new move to position of Stepper1
       LastHeading = NewHeading;   // New heading now becomes last heading
       }
       }
       while(Stepper1.distanceToGo() != 0){Stepper1.run();   // Keep updating AccelStepper for current movement
       int XInChar = Serial.read();XInChar = Serial.read();}   // Keep clearing serial buffer- Only allow new heading input once movement finished.
       }

```

---
Tags: stepper-motor
---


# Question
Title: Cannot connect through /dev/ttyACM0 (Ubuntu 18.04)
I am using an Arduino UNO which worked fine until today. My system: Ubuntu 18.04

Now, the IDE can no longer connect to it:

* Cannot do any sketch upload
* Cannot ask for board info
* No USB ports shown in tools --\> port (only 2 serial ports shown)
* `ttyyACM0` not showing up in `/dev`

However, both `lsusb` and `dmesg` show that the board is recognized somehow.

`lsusb` output:

`Bus 001 Device 012: ID 03eb:2fef Atmel Corp.`

`dmesg` output:

```
[ 2922.171042] usb 1-1.3: new full-speed USB device number 12 using ehci-pci
[ 2922.282047] usb 1-1.3: New USB device found, idVendor=03eb, idProduct=2fef
[ 2922.282052] usb 1-1.3: New USB device strings: Mfr=0, Product=1, SerialNumber=0

```

The problem is the same on 2 different computers, which leads me to suspect that there is something wrong with the board. Is it possible that a board be shown by both `dmesg` and `lsusb` and still be malfunctioning ?

# Answer
> 1 votes
The board was bad. I just replaced it and it now works.

So, to answer my own question, an Arduino board can show up on `lsusb` and `dmesg` and yet be faulty. This is what the `dmesg` output is for a healthy board:

```
[10492.388028] usb 1-1.4: new full-speed USB device number 13 using ehci-pci
[10492.500520] usb 1-1.4: New USB device found, idVendor=2341, idProduct=0043
[10492.500526] usb 1-1.4: New USB device strings: Mfr=1, Product=2, SerialNumber=220
[10492.500529] usb 1-1.4: Manufacturer: Arduino (www.arduino.cc)
[10492.500533] usb 1-1.4: SerialNumber: 55736323739351010292
[10492.520354] cdc_acm 1-1.4:1.0: ttyACM0: USB ACM device
[10492.520832] usbcore: registered new interface driver cdc_acm
[10492.520835] cdc_acm: USB Abstract Control Model driver for USB modems and ISDN adapters

```

And here is the `lsusb` output:

```
Bus 001 Device 013: ID 2341:0043 Arduino SA Uno R3 (CDC ACM)

```

Judging on the difference with the previous outputs from both commands (when the faulty board was connected), it seems that my board had reverted to the basic Atmel USB interface and that the Arduino specific USB handshake was not working. Can anyone confirm ?

---
Tags: usb, communication, uploading, linux, ubuntu
---


# Question
Title: How can I tell which fuses are set on an ATtiny?
Following on from this question, Problem with programming an ATtiny85: Error - avrdude: Yikes! Invalid device signature, if the response from `avrdude` is `0x000000` then the internal oscillator is probably not being used and an external one (be that crystal or clock signal) is required.

However, as this menu, from Engbedded Atmel AVR® Fuse Calculator, shows, there are a *lot* of options:

So, instead of having to configure circuits for *each* of the options, in turn, until the ATtiny responds, is there any way that I can read which of the `CKSEL` and `SUT` fuses are set?1

---

### Background

I am using a Nano/Uno as an ISP programmer, and the ATtiny is on a dev board like this (although it would be the same issue if I were to use a breadboard):

I know for sure that the connections are fine as I have checked them from pin to pin of the two ICs (ATmega328PU to ATtiny85), using a DMM.

I am receiving `0x000000` as in:

```
     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

```

because the ISP programmer can't read the ATtiny, because an external clock source has been set via the fuses. However, I wish to know how to read *which* clock source has been specified, without having to manually try *all* of the circuit permutations.

I don't think that just connecting a crystal (and two ceramic capacitors) will work if the exact setting, i.e. external clock, has been selected. However, if a 16MHz crystal works for all, or any, of the external clock settings then that would be great, but I'm sure it doesn't work like that, as you can have a crystal attached but the it might not be used, see Does device signature 0x000000 mean the atmega is bad:

> Even though you have a crystal connected, that does not mean it is oscillating. For example, IF you set fuses for "External Oscillator", that will turn the crystal oscillator off.

When I move the ATtiny85 to a breadboard and add a crystal (16 MHz) and two 22 pF capacitors, the error has changed for the better (at least now it sees that a ATtiny is connected)

```
avrdude: Device signature = 0xff0000
avrdude: Expected signature for ATtiny85 is 1E 93 0B
         Double check chip, or use -F to override this check.

```

Interestingly the signature varies:

* `0xff0000`
* `0x00ffff`
* `0xff00ff`

When I add an external power supply to the ATtiny on the breadboard, following advice from Atmega (any chip) Device Signature issues and stk500\_getsync()(resolutions), then unfortunately the device signature in the response returned by `avrdude` reverts back to `0x000000`

```
     avrdude: Device signature = 0x000000
     avrdude: Yikes!  Invalid device signature.
     Double check connections and try again, or use -F to override
     this check.

```

---

1 This is, admittedly, a bit chicken-and-egg, as if I can't communicate with the ATtiny, due to the incorrect clock setting, then how can I read which fuses have been set..? It's a bit like saying "If I don't have petrol in my car, then how can I drive to the petrol station to fill up?" - but I was hoping that there might be some sort of time saving measure

# Answer
This seems to be an X -\> Y problem, with X being the missing clock source on your ATTiny, which prevents communication.

If you have a second Uno or other AVR device, you can use that to generate a clock signal on any of the digital pins:

```
void setup() {
  DDRB = 0b00100000;
}

void loop() {
  PINB = 0b00100000;
}

```

This creates a square(~ish) signal on Pin 13 with a frequency of 1.6 MHz. Depending on the IDEs optimization level (platform.txt), a frequency of 4 MHz is also achievable (at `-O3` instead of `-Os`).

Connecting this to the `XTAL1` pin of your ATTiny85 should allow you to communicate with the board. Make sure to interconnect all grounds.
> 2 votes

# Answer
You need a Programmer that connects to the ISP pins

http://ww1.microchip.com/downloads/en/DeviceDoc/Atmel-2586-AVR-8-bit-Microcontroller-ATtiny25-ATtiny45-ATtiny85\_Datasheet.pdf

The programmer will hold Reset low, then communicate via the SCK/MOSI/MISO pins to read/update the fuses, read/program memory, and optionally read/program the EEPROM.

Section 20.2 discusses the 3 fuse bytes.

I use an older Atmel AVR-ISP MKii. Atmel stopped making them, there seem to be plenty of replacement choices available, and Atmel Studio 7 when I struggle with Atmega328P, '1284P, and 2560. I haven't used an Attiny in a project yet.

https://www.microchip.com/mplab/avr-support/atmel-studio-7
> 0 votes

---
Tags: attiny85
---


# Question
Title: What is wrong with my code? RGB potentiometer
Arduino programming has been a huge learning curve for me and I am trying to create a project with an rgb that's color is determined by a potentiometer. To where the further I turn it, the further across the rainbow spectrum it goes. I can't figure out how to do all values in between because I am not educated enough but I came up with this basic code...

```
int redpin = 6;
int greenpin = 3;
int bluepin = 5;
int potPin = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin, OUTPUT);
  pinMode(bluepin, OUTPUT);
  pinMode(greenpin, OUTPUT);
  pinMode(potPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int wavecolor = analogRead(potPin);
  Serial.print(wavecolor);
  {
    if (wavecolor = 0) {
      setColor(255, 0, 0);  // red
    }
    if (wavecolor > 0 or wavecolor < 333) {
      setColor(0, 255, 0);  // green
    }
    if (wavecolor > 333 or wavecolor < 667) {
      setColor(0, 0, 255);  // blue
    }
    if (wavecolor > 667 or wavecolor < 1022) {
      setColor(255, 255, 0);  // yellow
    }
    if (wavecolor = 1023) {
      setColor(80, 0, 80);  // purple
    }
  }
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redpin, red);
  analogWrite(greenpin, green);
  analogWrite(bluepin, blue);
}

```

And for some reason, where the light should change colors once the potentiometer goes past a certain number, the light just flickers and only changes colors to white when it is all the way up or down. Also, it has a weird flickery yellow color. Since I am new to this, can one of you better educated people be willing to assist me?

# Answer
* Equality comparison in C and C++ is expressed by `==` operator. `==`, not `=`. This

```
if (wavecolor = 0) {

```

actually *assigns* zero to your `wavecolor` variable, thus destroying the value you just read.
* The common sense says that you actually need `and` in your conditions, not `or`

```
if (wavecolor > 0 and wavecolor < 333) {

```

The `or` conditions that you curently use are simply *always true*, which makes them nonsensical.
* This is valid syntax

```
wavecolor > 0 or wavecolor < 333
wavecolor > 0 and wavecolor < 333

```

but you might want to try using more "canonical" forms

```
wavecolor > 0 || wavecolor < 333
wavecolor > 0 && wavecolor < 333

```

`or` and `and` are "alternative" forms of `||` and `&&` operators, introduced a long time ago for reasons that are all but obsolete today.
* Assuming that you meant `and` instead of `or`, in your conditions you managed to "exclude" such values as `333`, `667` and `1022` \- they wouldn't match any of `and` conditions. Changing some strict comparisons to non-strict ones might be in order.
* As a side note, in a single-file program all file-scope variables should be either `const` or `static`. In your case

```
const int redpin = 6;
const int greenpin = 3;
const int bluepin = 5;
const int potPin = 0;

```
> 6 votes

# Answer
Try this code below. This will give you the desired output!

```
int redpin = 6;
int greenpin = 3;
int bluepin = 5;
int potPin = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(redpin, OUTPUT);
  pinMode(bluepin, OUTPUT);
  pinMode(greenpin, OUTPUT);
  pinMode(potPin, INPUT);
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:
  int wavecolor = analogRead(potPin);
  Serial.print(wavecolor);
  {
    if (wavecolor == 0) {
      setColor(255, 0, 0);  // red
    }
    else if (wavecolor > 0 && wavecolor < 333) {
      setColor(0, 255, 0);  // green
    }
    else if (wavecolor >= 333 && wavecolor < 667) {
      setColor(0, 0, 255);  // blue
    }
    else if (wavecolor >= 667 && wavecolor < 1022) {
      setColor(255, 255, 0);  // yellow
    }
    else if (wavecolor >= 1022) {
      setColor(80, 0, 80);  // purple
    }
  }
}

void setColor(int red, int green, int blue)
{
#ifdef COMMON_ANODE
  red = 255 - red;
  green = 255 - green;
  blue = 255 - blue;
#endif
  analogWrite(redpin, red);
  analogWrite(greenpin, green);
  analogWrite(bluepin, blue);
}

```

Read up on logical and relational operators in Arduino (`||`, `&&`, `>`, `<`, `==`, `>=`, `<=`) etc.
I will leave the logic development to you as it is what develops your coding ability and trust me logic is the most important and fun part of writing a code!
> 0 votes

---
Tags: sketch
---


title: Running a 7 pin OLED with 4 pins (I2C)

text:
# Question
Title: Running a 7 pin OLED with 4 pins (I2C)
I have an OLED with this 7 pin pinout:

I want to use an existing code i found that makes use of U8Glib. But in the example, use uses 4 pins to control the OLED via I2C. This is the pinout he uses:

Is it possible to control my OLED via 4 pins and use U8Glib to simplify my project by making use of the example code i found?

EDIT: Here is also a picture of the back of the OLED PCB that mentions how to use IIC but i do not understand it!

# Answer
This page has the answer to your questions. For reference:

> Setting up SPI/I2C Connection with GMS096A OLED Module
>
> Being a new entry to the market, only limited resources are available on this small piece of miracle (GMS096A). I2C/SPI configuration always demands helpful resources as in any case. For the SPI setup, the module comes in 4 wire SPI configuration by default and to make it work with the arduinos you can use these libraries from Adafruit.
>
> For the I2C setup it demands a little bit of work on the module. Actually it was one of our customers who shared these simple configuration steps with us, start with resoldering the resistor from position R3 to R1 and then short the R8 resistor with some solder tin (0 Ohm resistor). The R6 and R7 pullup resistors are already soldered, nothing to do there. Once done, the module is ready for I2C communication! The CS Pin is not necessarily needed, so just connect it to GND. The DC Pin selects the address. For standard address wire it to GND. The RES-pin needs a low pulse at startup and high voltage during operation (as in SPI mode), a 100nF capacitor to GND and a 10k res to VCC would be ideal!

Your module might differ sightly. But you should be able to figure it out from there. The pulse on the RES-pin needed at startup took me a while to figure out!
> 2 votes

# Answer
Yes, it works IIC as described above, with my Arduino MEGA. You can also connect RST Pin at Arduino RESET signal, so no need of extra R and C components
> 2 votes

# Answer
That is a SPI interface. Often the CS is missing, but you seem to have that pin. I suggest to start with the software PCI mode of the U8Glib.

This is the best explanation that I can find: Github: SSD1306 based OLED connected to Arduino

Would you consider using the newer U8g2 library ?
It is easier to use with Arduino boards that have more memory. But it has also the same mode for low memory usage, just like the U8Glib.
> 1 votes

# Answer
> Is it possible to control my OLED via 4 pins and use U8Glib to simplify my project by making use of the example code i found?

i'm sure somewhere there is an i2c-\>spi bridge. if not, you can always code your arduino to behave like one.

short of that, you can simply code to control the board via spi.
> 0 votes

---
Tags: i2c, library, pins, display
---


# Question
Title: How to stabilize magnetic levitation system?
I followed everything from this project but still, the magnet is not levitating - https://www.hackster.io/jsirgado/magnet-levitation-with-arduino-eeeee4

The best I can do is to make the magnet jump up and down fast but it never levitates. Have tried changing PID setting from the project as aggressive and mild but still didn't achieve the final result.

I need advice from an expert to tell me what I am doing wrong here. All components are in good condition and 5v electromagnet is strong enough.

So what am I missing here? will implementing fast PWM mode be helpful?

# Answer
The answer to the solution was quite simple. I just had to comment out all serial port reading and Arduino processing became 60 times faster which helped to levitate the magnet. Thanks to everyone who helped me here :)
> 1 votes

---
Tags: arduino-uno, pid
---


# Question
Title: Project wont compile when I place functions below function calls
I use VSCode, not the Arduino IDE. I saw and tried to use a lot of code snippets which are provided for Arduino projects...

So when I copy/paste these examples into my VSCode and try to compile it fails. (I won't believe that people offer non-working examples.)

When I place the functions above the function calls it compiles.

Is this normal behavior or do I have to add some settings to get this working as provided?

**Fails in VSCode** (works in Arduino IDE):

```
#include "Arduino.h"
void setup() {
}
int zero = 0;

void loop() {
  zero = myfunction();
}

int myfunction(){
  return 0;
}

```

**Works in VSCode** (Works in Arduino IDE):

```
#include "Arduino.h"

void setup() {
}
int zero = 0;

int myfunction(){
  return 0;
}

void loop() {
  zero = myfunction();
}

```

# Answer
You need to declare your function before you use it. So either the whole function body needs to be before the usage, or you must add a function prototype declaration.

```
void myfunction();

myfunction();

void myfunction(){
  return 0;
}

```
> 5 votes

# Answer
Just make the the abstract method declaration before writing your code after the header files.

```
#include<Arduino.h>
void myfunction();
void setup();
void loop();

```

After this you write your code in any order
> 0 votes

---
Tags: compile, compilation-errors, visualstudio
---


title: Arduino Strings concatenation

text:
# Question
Title: Arduino Strings concatenation
I am working on an arduino mega 2560 sketch. I have to parse http query strings.

My program is concatenating strings for each http request. And i have an http request every second during all day.

I have read that this kind of work may cause ram memory fragmentation. I am very upset about this because my program will randomly crash if there are no free ram memory.

Do you know if there is a way to initialise a string with a given memory length ?

I do not want to work with char arrays because i need indexof, substring functions and comparison with ==

Thanks

# Answer
> 1 votes
There is a way to initialize an Arduino `String` with a given memory length: see `reserve()` method. It will generally greatly reduce or entirely eliminate memory fragmentation, if you can afford reserving a sufficient amount of memory in advance.

Just keep in mind that this is a "soft" boundary: once your string gets longer than the reserved amount, `String` will quietly resume reallocating memory with all those typical consequences.

It is not clear what you plan to do if the pre-reserved amount of memory proves to be insufficient. Fall back to "memory fragmentation"? Anything more elaborate than that will be pretty much as complex as performing manual management of a `char[]` array.

All the functionalities you requested are present for `char[]` arrays as well, might just require a few more lines of code. And it is not clear why one might "need" comparisons to be `==` specifically.

This might also be an XY problem. Why are you trying to concatenate all these requests in memory? What are you planning to do with them once you are done "concatenating"?

---
Tags: arduino-mega
---


title: Return constant string

text:
# Question
Title: Return constant string
Look at this code :

char * function1() { return « hello » }

Where is stored hello string ? Is there a copy ?

What i want to avoid is to have a memory leak or accessing to another string instead of hello

Thanks

# Answer
String literals in C and C++ are stored in static memory, which in case of Arduino platform is ordinary data memory.

If we overlook the typos, your code is essentially equivalent to

```
char *function1()
{
  static char literal[6] = { 'h', 'e', 'l', 'l', 'o', '\0' };
  return literal;
}

```

with a remark that in C and C++ you are not allowed to modify string literals. (Some nuances also depend on the specific language - C vs. C++ - which you failed to specify). Regardless of the language, it is always a better idea to use `const char *` pointers (as opposed to `char *`) to point to string literals.

There's no dynamic memory allocation here, and therefore no memory leaks possible. What you mean by "accessing another string" is not clear.
> 1 votes

# Answer
```
const char* function1() { return "hello"; }

```

> Where is stored hello string ? Is there a copy ?

The string is compiled into the program memory. Before setup() is called the constant values are copied to the data memory (aka SRAM).

The function will return the pointer to the same string (memory location).

To save data memory the string literal can be access directly in program memory.

```
__FlashStringHelper* function1() { return F("hello"); }

```

Cheers!

Ref.

1. https://en.cppreference.com/w/cpp/language/string\_literal
2. https://www.nongnu.org/avr-libc/user-manual/pgmspace.html
> 0 votes

---
Tags: arduino-mega
---


# Question
Title: The Ultrasonic sensor just detects the same distance
```
int tPin = 11;
int ePin = 12;
long duration, inches, cm;

void setup()
{
    Serial.begin(9600);
    pinMode(tPin, OUTPUT);
    pinMode(ePin, INPUT);
    pinMode(2, OUTPUT);
}

void loop()
{
    digitalWrite(tPin, LOW);
    delayMicroseconds(5);
    digitalWrite(tPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(tPin, LOW);
    duration = pulseIn(ePin, HIGH);
    cm = (duration / 2) / 29.1;
    inches = (duration / 2) / 74;
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if (inches <= 10) {
        digitalWrite(2, HIGH);
        delay(50);
        digitalWrite(2, LOW);
        delay(50);
    }
    else {
        digitalWrite(2, HIGH);
        delay(500);
        digitalWrite(2, LOW);
        delay(500);
    }
}

```

The serial print displays the same distance that it first detects. How can I fix this?

# Answer
First of all you need to make cm, inches and duration float to be more precise. Second, you need to make the delay 2 and 10 microseconds between triggers. Overall, if I'm not wrong you can use the code below without changing your circuit.

```
int tPin = 11;
int ePin = 12;
float duration, inches, cm; //floating numbers to make the result more precise

void setup()
{
    Serial.begin(9600);
    pinMode(tPin, OUTPUT);
    pinMode(ePin, INPUT);
    pinMode(2, OUTPUT);
}

void loop()
{
    digitalWrite(tPin, LOW);
    delayMicroseconds(2);         //Delay 2 microseconds
    digitalWrite(tPin, HIGH);
    delayMicroseconds(10);        //Delay 10 microseconds
    digitalWrite(tPin, LOW);
    duration = pulseIn(ePin, HIGH);
    cm = duration / 58.2;          //Instead of duration/2/28.1
    inches = cm / 2.54;            //You can use cm that was created before for conversion
    Serial.print(inches);
    Serial.print("in, ");
    Serial.print(cm);
    Serial.print("cm");
    Serial.println();
    delay(100);

    if (inches <= 10) {
        digitalWrite(2, HIGH);
        delay(50);
        digitalWrite(2, LOW);
        delay(50);
    }
    else {
        digitalWrite(2, HIGH);
        delay(500);
        digitalWrite(2, LOW);
        delay(500);
    }
}

```
> 1 votes

---
Tags: arduino-uno
---


# Question
Title: Reading multiple NTC temperature sensors with Arduino
Hej..I am building a project with four NTC 10k ohm temperature sensor with Arduino. It is easy to measure only one NTC temperature sensor. There is many examples for NTC measurement for example code written with Steinhart-Hart Equation or reading ADC Thermistor with Lookup Table.

I found one example with Steinhart-Hart Formula. I am not so good at coding with Arduino but I Manage and build to write code for only one NTC sensor and read it with Nokia LCD 5110. The question is how to do code for Multiple NTC sensors?

```
/* NTC temperature mesurment 13-08-2017
 *
 *  Using Nokia LCD 5110
 */

#include "LCD5110_Graph.h"
LCD5110 myGLCD(8, 9, 10, 12, 11);  // Setup Nokia 5110 Screen SCLK/CLK=5, DIN/MOSI/DATA=6, DC/CS=7, RST=8 Chip Select/CE/SCE=9,
extern uint8_t SmallFont[];
extern uint8_t MediumNumbers[];

int tempPin = 0;   // A0 analog input
int Vout, charTc ;
float R1 = 10000; //otpornost na sobnoj temperaturi 10K ili 10000 oma
float R2, Tk, Tc;
float Ac = 1.009249522e-03, Bc = 2.378405444e-04, Cc = 2.019202697e-07;
char charBuffer[10];

void setup(){
myGLCD.InitLCD(); //initialize LCD with default contrast of 70
myGLCD.setContrast(68);
myGLCD.setFont(SmallFont); // Set default font size. tinyFont 4x6, smallFont 6x8, mediumNumber 12x16, bigNumbers 14x24
myGLCD.clrScr();

myGLCD.print("Temp test",CENTER,0);
myGLCD.print("Check",CENTER,12);
myGLCD.print("Please Wait",CENTER,24);

myGLCD.update();
delay(5000);
myGLCD.clrScr();
}

void loop() {
  Vout = analogRead(tempPin);
  R2 = R1 * (1023.0 / (float)Vout - 1.0); // konvertovanje iz analogne u digitalnu
  Tk = (1.0 / (Ac + Bc*log(R2) + Cc*log(R2)*log(R2)*log(R2))); // Temperature in Klven
  Tc = Tk - 273.15; //temperature converted to celcious

charTc=dtostrf(Tc, 3, 2, charBuffer);

  myGLCD.clrScr();
  //myGLCD.print("Discharging",CENTER,0);
  //myGLCD.print("Temperature:",CENTER,0);
  myGLCD.print("Temp1:",0,0);
  //myGLCD.print( charTc,CENTER,20 );
  myGLCD.print( charTc,36,0 );
  myGLCD.print("Temp2:",0,10);
  myGLCD.print("Temp3:",0,20);
  myGLCD.print("Temp4:",0,30);
  myGLCD.update();
  delay(2000);
  myGLCD.clrScr();
}

```

# Answer
> 1 votes
The row `int tempPin = 0; // A0 analog input` specify which analog input that should be used as input for reading the NTC value.

Then you can expand the code with the analog inputs that is needed.

# Answer
> 1 votes
---

Arduino UNO has 6 Analog pins ..

Sequentially Read ADC every 2 seconds either by calling the Respective ADC functions inside a TIMER\_INTERRRUPT\_VECTOR() or if high Accuracy is not Required you can restrict your main loop() to be small and write all ADCs inside it. Also make sure that you sample your ADC if writing inside loop to make sure that its accurate.

# Answer
> 1 votes
As I understand, you have multiple analog sensors you want to read. So your code should look something like this:

```
// assuming sensors are on A0, A1, A2, Ax

sensorPins [] = {A0, A1, A2};
int sensorNum = 3;

for(int x = 0; x < sensorNum; x++){
  readSensor(x);
}

```

Something like that should work for you.

# Answer
> 0 votes
1. Put in multiple analog input pins and read them sequentially;
2. Put in multiple analog input pins and scan them in the adc interrupts.

the first approach is quite simple and the 2nd approach requires a thorough read of the datasheet.

# Answer
> 0 votes
This is pretty simple. Create an array of uint\_8 variables that contains your pin numbers.

Then write a function that takes a pin number as an input, reads the ADC, does the math, and returns a value.

```
sensorPins [] = {A0, A1, A2, A3};

float readTemp(int tempPin) {
  int Vout = analogRead(tempPin);
  float R2 = R1 * (1023.0 / (float)Vout - 1.0); // konvertovanje iz analogne u digitalnu
  float Tk = (1.0 / (Ac + Bc*log(R2) + Cc*log(R2)*log(R2)*log(R2))); // Temperature in Kelven
  Tc = Tk - 273.15; //temperature converted to Celsius
  return Tc;
}

```

Then write a loop that loops through your array of pin numbers and calls the readTemp function.

---
Tags: programming
---


# Question
Title: How to programme a button per colour for a neopixel strip?
I am trying to make a particular pixel in a neopixel strip, turn green, red or blue depending which button has been pressed and to stay on until pressed off again (like a toggle), but currently when I press one of the buttons it flashes the correct colour when button is pressed down but isn't acting as a toggle switch and then goes to a white light.

```
#include <Adafruit_NeoPixel.h>
#ifdef __AVR__
#include <avr/power.h> // Required for 16 MHz Adafruit Trinke
#endif

#define BUTTON_PIN1  2
#define BUTTON_PIN2  10
#define BUTTON_PIN3  11
#define PIXEL_PIN    6  // Digital pin 6 connected to the NeoPixels.

#define PIXEL_COUNT 13  // Number of NeoPixels

// Declare our NeoPixel strip object:
Adafruit_NeoPixel strip(PIXEL_COUNT, PIXEL_PIN, NEO_GRB + NEO_KHZ800);

boolean oldState1 = HIGH;
boolean newState1 = HIGH;

boolean toggle1 = LOW;

boolean oldState2 = HIGH;
boolean newState2 = HIGH;

boolean toggle2 = LOW;

boolean oldState3 = HIGH;
boolean newState3 = HIGH;

boolean toggle3 = LOW;

void setup() {
Serial.begin(9600);
pinMode(BUTTON_PIN1, INPUT_PULLUP);
pinMode(BUTTON_PIN2, INPUT_PULLUP);
pinMode(BUTTON_PIN3, INPUT_PULLUP);
strip.begin(); // Initialize NeoPixel strip object (REQUIRED)
strip.show();  // Initialize all pixels to 'off'
}

void loop() {
updateButtonState1();
updateButtonState2();
updateButtonState3();

}

void updateButtonState1() {

 // Get current button state.
 newState1 = digitalRead(BUTTON_PIN1);

 if ((newState1 == LOW) && (oldState1 == HIGH)) {
 delay(50);
 newState1 = digitalRead(BUTTON_PIN1);
 if (newState1 == LOW) {
   toggle1 = !toggle1;
  }
 }
 oldState1 = newState1;

if (toggle1 == HIGH) {
strip.setPixelColor(2, 245, 15, 15); //electrical/fire hazard (red)
} else {
strip.setPixelColor(2, 0, 0, 0);
}
strip.show(); // Update strip with new contents
}

void updateButtonState2() {

// Get current button state.
 newState2 = digitalRead(BUTTON_PIN2);

if ((newState2 == LOW) && (oldState2 == HIGH)) {
 delay(50);
 newState2 = digitalRead(BUTTON_PIN2);
 if (newState2 == LOW) {
   toggle2 = !toggle2;
   }
  }
 oldState2 = newState2;

  if (toggle2 == HIGH) {
  strip.setPixelColor(2, 13, 50, 190); //Leak (blue)
  } else {
  strip.setPixelColor(2, 0, 0, 0);
  }
 strip.show(); // Update strip with new contents
 }

 void updateButtonState3() {

 // Get current button state.
 newState3 = digitalRead(BUTTON_PIN3);
 if ((newState3 == LOW) && (oldState3 == HIGH)) {
  delay(50);
  newState3 = digitalRead(BUTTON_PIN3);
  if (newState3 == LOW) {
    toggle3 = !toggle3;
  }
 }
 oldState3 = newState3;

 if (toggle3 == HIGH) {
 strip.setPixelColor(2, 58, 233, 65); //bins/recylcing (green)
 } else {
   strip.setPixelColor(2, 0, 0, 0);
  }
  strip.show(); // Update strip with new contents
}

```

# Answer
> 1 votes
You do not really have to use an array for this, though I do agree that it's the cleanest solution.

Here is a simplified version of your code, do mind you'll still have to do the button handling yourself (by setting buttonpressed to 'true' when the button is pressed.

Also, when adding more colors to the array, you'll have to manually adjust 'totalColors'.

```
void setup() {
  //Color/pixel declarations based on https://learn.adafruit.com/adafruit-neopixel-uberguide/arduino-library-use
  uint32_t magenta = strip.Color(255, 0, 255);
  uint32_t greenishwhite = strip.Color(0, 64, 0, 64);

  //https://www.arduino.cc/reference/en/language/variables/data-types/array/
  uint32_t colors[] = {magenta, greenishwhite};
  unsigned char totalColors = 2;
  unsigned char currentColor = 0;
}

void loop() {
  if (buttonpressed) {
    //Change the "currentColor" index every time the button is pressed, but make it start at 0 when it reached the end.
    currentColor++;
    if (currentColor >= totalColors) {
      currentColor = 0;
    }

    //From the array of colors, pick the one with the index "currentColor" and show it.
    ledstrip.fill( colors[currentColor] , 0, strip.numPixels() - 1);
    ledstrip.show();

    buttonpressed = false; //Reset flag, so this doesn't get executed until next time button is pressed.
  }
}

```

You should be able to replace the first 3 lines (setting up the array) with a single:

```
uint32_t colors[] = {strip.Color(255, 0, 255,  strip.Color(0, 64, 0, 64)};

```

But I had it split up to better show the idea of the array.

Alternatively you could do:

```
switch(currentColor){
  case 0:
    //Color RED
  break;
  case 1:
    //Color GREEN
  break;
  case 2:
    //Color BLAUW
  break;
}

```

---
Tags: button, array, neopixel
---


# Question
Title: How does input from IR receiver to Arduino UNO board work?
I have a very simple circuit with an Elegoo IR receiver module connected to an Arduino UNO. The three wires are connected correctly with the data wire (Y) connected to pin 8. The code works fine, as every time I press button on the remote, the Serial Monitor displays the corresponding button description.

However, I do not understand how Arduino's pin 8 knows which IR button has been pushed. My understanding is that pin 8 can read either 5V or 0V, but to know which of 20+ remote buttons has been pushed it would have to read PWM. But pin 8 does not the PWM icon next to it and yet it works fine. Unless the PWM icon applies only to pin output? Or is there another way I have failed to find info about?

Thanks!

# Answer
> 4 votes
You confuse the different technologies here.

1. PWM is only an output, not an input. So every pin marked with the PWM symbol can OUTPUT a PWM signal. Reading a signal is a totally different task with different hardware involved.
2. The IR receiver does not output a PWM (meaning Pulse Width Modulation) signal to the Arduino. It ouputs the demodulated IR signal.

So here is what happens: The remote a code, that consists of different periods of "light on" and "light off" (giving pulses of different length, which encode the data from binary format). Since you want to seperate the remotes signal from any other IR signal, that might roam through the air, the remote also modulates the pulses with a special frequency (often this is 38kHz, but might be another frequency around that). This means that every pulse will be chopped into shorter pulses at the specified frequency. This translates to something like: "light on and off with 38kHz for duration x" --\> "light off" --\> "light on and off with 38kHz for duration y" --\> ...

The receiver module senses the IR light comming in and will electronically discard all signals, that don't have the special frequency, and does the demodulation on this. The outputted signal does not have the 38kHz frequency in it anymore. Just the pulses of different length, that encode the data, meaning

The Arduino then reads the length of the pulses (that only consists of sequences of 0V and 5V) and decodes them into a number. This number represents the pressed button.

A proper library for the Arduino can read the different data protocols used in common IR remotes.

# Answer
> 1 votes
The remote control emits encoded IR-bursts (each button has its own code) which are transformed into electrical pulses by the sensor (ref. 6. in here: http://eeshop.unl.edu/pdf/VS1838-Infrared-Receiver-datasheet.pdf). On the arduino those pulses are decoded using a proper library. That means pin 8 is not reading any analog or pwm signal, but TTL-logic at 5V.

---
Tags: pwm, ir, infrared
---


# Question
Title: Send Strings via SPI both ways using two Arduino UNOs(Master to Slave & Slave to Master)
I need to create a two way String exchanger via SPI with two Arduino UNOs. Strings and their lengths are independent variables of the main loop and they can change with every iteration. I need both of the Arduinos to communicate with each other regardless of what the strings contain. I want to see basically the same screen with the serial monitor.

It is kind of working. I am not sure how to explain it, I'll just show it below.

Basically the main idea for both of the Arduino's is like this:

```
Master: hey
Slave: hi

```

---

Instead I get this on the master:

```
Slave:
Slave:
Master: hey
Slave: y
Slave:
Slave:
.
.
.
Slave: i
Slave:
Slave:
.
.

```

And the slave displays only itself:

```
Slave: hi

```

I have created for loops to transfer every char of the string seperatly and respectively but this is still the case. I couldn't find any sample code online for independent string transfering via SPI. I know I probably have many mistakes but how can I fix them to work just as I intend to?

---

**Connections:**

Arduino1.pin13 --- Arduino2.pin13

Arduino1.pin12 --- Arduino2.pin12

Arduino1.pin11 --- Arduino2.pin11

Arduino1.pin10 --- Arduino2.pin10

---

**Master Code**

```
//MASTER

#include<SPI.h>

String textSend="", textReceive="";

void setup(){

  Serial.begin(115200);

  SPI.begin();
  SPI.setClockDivider(SPI_CLOCK_DIV8);    //Sets clock for SPI communication at 8 (16/8=2Mhz)
  digitalWrite(SS,LOW);
}

void loop(){

  textSend=""; textReceive="";
  textSend = Serial.readString();
  if(textSend != ""){
    for(int i = 0; i < textSend.length(); i++){
      delayMicroseconds (20);
      SPI.transfer(textSend[i]);
    }

    Serial.print ("Master: ");
    Serial.println (textSend);
  }else{
    int i = 0;
    char c;
    do{
      delayMicroseconds (20);
      c = SPI.transfer(1);
      textReceive += c;
      i++;
    }while(textReceive[i] != 0);

    if(textReceive[i] == 0){
      Serial.print ("Slave: ");
      Serial.println (textReceive);
      textReceive = "";
    }
  }
}

```

---

**Slave Code**

```
//SLAVE

#include<SPI.h>

String textSend="";
String textReceive="";

void setup (void){
  Serial.begin(115200);
  pinMode(MISO, OUTPUT);
  SPCR |= _BV(SPE);
  SPCR |= _BV(SPIE);
  SPI.attachInterrupt();

}

ISR (SPI_STC_vect){ //Interrupt Service Routine

  byte c = SPDR;

  if(c != 1){ //Slave receives
    for(int i = 0; i < textReceive.length(); i++){
      textReceive += SPDR;
    }
    if(textReceive.length() > 0){
      Serial.print("Master: ");
      Serial.println(textReceive);
      textReceive = "";
    }
  }else{
    for(int i = 0; i < textSend.length(); i++){
      delayMicroseconds(20);
      SPDR = textSend[i];
    }
    if(textSend != ""){
      Serial.print("Slave: ");
      Serial.println(textSend);
      textSend = "";
    }
  }
}

void loop() {
  if(textSend == "")
    textSend = Serial.readString();

}

```

# Answer
> 2 votes
It's not trivial to have both arduinos communicating "with each other" as SPI is a master-slave bus. That means the slave cannot start a transmission, communication must always be initiated by the master instead. Another thing with SPI is that you can't read the slave without writing to it. SPI works like a shifting register: on every clock cycle both devices transmit the byte in their SPDR to each other. So, to read a long string from the slave the master has to transmit the exact same number of dummy-bytes and simultaniously read the incoming stream. This is great if only a specific number of bytes need to be transmitted (e.g. exchanging variables which always consist of the same number of bytes), but becomes complicate when the number of bytes varies. You will then need to implement some protocol that is able to read a variable amount of bytes from the slave (e.g. you will have to tell the master the number of bytes that have to be read).

I think serial communication like UART is perfect for your purpose as communication is real full-duplex, it's no master-slave-system and the common protocol uses a terminating character to end a data stream which makes it ideal to transmit strings. Also the arduino can run several serial interfaces (you might need another for debug output).

---
Tags: arduino-uno, serial, spi, string
---


# Question
Title: My Arduino code will not compile, when I can't see anything wrong with it
It keeps on giving me the error:

```
Error compiling for board Arduino/Genuino Mega or Mega 2560.

```

Other sketches work fine, but this one will not compile, even though I have all the libraries.

Here is the link for the code: https://drive.google.com/open?id=0B3R5NMiGZ3RPSk9WS0Y1amtEYms

The full error:

```
Arduino: 1.8.3 (Windows 10), Board: "Arduino/Genuino Mega or Mega 2560, ATmega2560 (Mega 2560)"

Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':

(.text+0x0): multiple definition of `__vector_13'

libraries\IRLibRecv\IRLibRecv.cpp.o (symbol from plugin):(.text+0x0): first defined here

d:/arduino/hardware/tools/avr/bin/../lib/gcc/avr/4.9.2/../../../../avr/bin/ld.exe: Disabling relaxation: it will not work with multiple definitions

collect2.exe: error: ld returned 1 exit status

exit status 1 Error compiling for board Arduino/Genuino Mega or Mega
2560.

This report would have more information with "Show verbose output during compilation" option enabled in File -> Preferences.

```

# Answer
> 3 votes
There are a number of issues with your code besides the actual error:

* You are dividing an unsigned long by an integer which results in an unsigned long, then rounding it. Makes no sense.
* You are assigning (I assume - without seeing your code I can't be sure) long constants (eg `0xFFE01F`) to an integer - which overflows and whinges.

However your main problem is that you have two interrupt service routines (ISRs) for the same interrupt (vector 7). What that interrupt is I can't say, since it is different on different chips, and you don't seem able to make your mind up if you're using an Uno or a Mega (you tagged your question both for some reason). So you will have to change code and/or libraries to use different interrupts or combine the two together to use just one ISR.

# Answer
> 0 votes
I can't see you code, but my guess is that you are passing an unsigned value into `round()`.

`millis()` returns an unsigned long, this means it can never be negative, so if you test `millis() >= 0` it will always be true. That is your issue.

Write you own round function that doesn't check its greater than 0.

# Answer
> 0 votes
just some warnings about generally unsafe/unsound code pieces.

the major issue (potentially unresolvable) is the vector-7 error. you should look into the datasheet to see what interrupt vector it is referring to first. There are more than one of such ISRs declared in your code.

# Answer
> 0 votes
I searched but couldn't find an answer, then I suddenly released my Arduino external power caused this problem. When I shut down the external power I could install it in my device. I hope it works for your problem.

---
Tags: arduino-mega, arduino-ide
---


# Question
Title: Variable declared inside void setup() is forgotten in void loop()
If I declare a variable in `void setup()` and try to do something with it in `void loop()`, it just says that the variable is undeclared. Here is the code:

```
#include "Servo.h"

void setup() {
  Servo servo1;
  int x_key = A0;
  servo1.attach(2);
  pinMode(A0, INPUT);
  pinMode(2, OUTPUT);

  int x_position = 90;
}

void loop() {
  if (analogRead(A0) < 512) {
    x_position++;
    servo1.write(x_position);
  }
}

```

# Answer
Yes, that is how C and C++ (and most other C-like languages) work. Variables have "scope". Any variable define inside a pair of curly braces (between a `{` and a `}`) is only visible inside those braces.

If you want to reference a variable in both `setup()` and `loop()`, you have to make it a global variable, defined at the top of your code.

```
#include "Servo.h"
Servo servo1;
int x_position = 90;  //Define your global var(s) here

void setup() {
    int x_key = A0;  //This var only exists inside the setup function
    servo1.attach(2);
    pinMode(A0, INPUT);
    pinMode(2, OUTPUT);

}

void loop() {
    if (analogRead(A0) < 512) {
        x_position++;
        servo1.write(x_position);
    }
}

```
> 7 votes

---
Tags: arduino-uno, programming, c++, variables
---


title: HTTP myphp request error RFID

text:
# Question
Title: HTTP myphp request error RFID
This program is a program which readings of rfid are saved to myphp database. I have a problem when running the code The wifi is connected but when the code doesn't save im assuming that the problem is in this part of the code client.print("GET /rfid/nodemcu\_rfid/rfid\_read.php?allow="); Since i have done a wire shark capture and notice a **Bad Request error 400** as shown in the screen shot.

**IP Addresses: 192.168.0.14 Is the php server , 192.168.0.19 is the nodemcu**

ALL THE CODE :

```
#include<SoftwareSerial.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <SPI.h>
#include <MFRC522.h>

const char* ssid = "ARRIS-84AB";
const char* password = "your SSID password ";
//WiFiClient client;
char server[] = "192.168.0.14";   //eg: 192.168.0.222
#define SS_PIN 2 //FOR RFID SS PIN BECASUSE WE ARE USING BOTH ETHERNET SHIELD AND RS-522
#define RST_PIN 15
#define No_Of_Card 3

 WiFiClient client;

//WiFiServer server(80);
SoftwareSerial mySerial(8,9);
MFRC522 rfid(SS_PIN,RST_PIN);
MFRC522::MIFARE_Key key;
byte id[No_Of_Card][4]={
  {44,153,22,219},             //RFID NO-1
  {112,224,72,84},             //RFID NO-2
  {151,94,80,84}              //RFID NO-3
};
byte id_temp[3][3];
byte i;
int j=0;
void setup()
{
 Serial.begin(115200);
  delay(10);
  mySerial.begin(115200);
  SPI.begin();
  rfid.PCD_Init();

    for(byte i=0;i<6;i++)
  {
    key.keyByte[i]=0xFF;
  }

  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  // Start the server
//  server.begin();
  Serial.println("Server started");
  Serial.print(WiFi.localIP());
  delay(1000);
  Serial.println("connecting...");
 }
void loop()
{  // Check if a client has connected
  int m=0;
  if(!rfid.PICC_IsNewCardPresent())
  return;
  if(!rfid.PICC_ReadCardSerial())
  return;
  for(i=0;i<4;i++)
  {
   id_temp[0][i]=rfid.uid.uidByte[i];
             delay(50);
  }

   for(i=0;i<No_Of_Card;i++)
  {
          if(id[i][0]==id_temp[0][0])
          {
            if(id[i][1]==id_temp[0][1])
            {
              if(id[i][2]==id_temp[0][2])
              {
                if(id[i][3]==id_temp[0][3])
                {
                  Serial.print("your card no :");
                  for(int s=0;s<4;s++)
                  {
                    Serial.print(rfid.uid.uidByte[s]);
                    Serial.print(" ");

                  }
                  Serial.println("\nVALID");
                  Sending_To_DB();
                  j=0;

                            rfid.PICC_HaltA(); rfid.PCD_StopCrypto1();   return;
                }
              }
            }
          }
   else
   {j++;
    if(j==No_Of_Card)
    {
      Serial.println("inVALID");
      Sending_To_DB();
      j=0;
    }
   }
  }

     // Halt PICC
  rfid.PICC_HaltA();

  // Stop encryption on PCD
  rfid.PCD_StopCrypto1();
 }

 void Sending_To_DB()   //CONNECTING WITH MYSQL
 {
   if (client.connect(server, 80)) {
    Serial.println("connected");
    // Make a HTTP request:
    Serial.println("GET /rfid/rfidread.php?allow=");     //YOUR URL /rfid/rfidread.php?allow
    client.print("GET /rfid/nodemcurfid/rfidread.php?allow=");     //YOUR URL /rfid/rfidread.php?allow  /var/www/html/rfid/rfid_read.php
    if(j!=No_Of_Card)
    {
      Serial.println('1');
      client.print('1');
    }
    else
    {
      Serial.println('0');
      client.print('0');
    }
    Serial.println("&id=");
    client.print("&id=");
    for(int s=0;s<4;s++)
                  {
                    Serial.println(rfid.uid.uidByte[s]);
                    client.print(rfid.uid.uidByte[s]);

                  }
    client.print(" ");      //SPACE BEFORE HTTP/1.1
    client.print("HTTP/1.1");
    client.print("Host: ");
     client.println(server);
    client.println("Host: 192.168.0.14");//eg: 192.168.0.222
    client.println("Connection: close");
    client.println();
  } else {
    // if you didn't get a connection to the server:
    Serial.println("connection failed");
  }
  client.stop();
 }

```

# Answer
Your problem is here:

```
client.print(" ");      //SPACE BEFORE HTTP/1.1
client.print("HTTP/1.1");
client.print("Host: ");
 client.println(server);
client.println("Host: 192.168.0.14");//eg: 192.168.0.222
client.println("Connection: close");
client.println();

```

That ends up with:

```
....(your request)... HTTP/1.1Host: 192.168.0.14
Host: 193.168.0.14
Connection: close

```

Not only are you sending the Host header twice, but you're not adding the line ending after the HTTP version.

Instead it should look more like:

```
client.print(" ");      //SPACE BEFORE HTTP/1.1
client.println("HTTP/1.1"); // <-- Note the use of println not print
client.print("Host: ");
client.println(server);
client.println("Connection: close");
client.println();

```
> 1 votes

---
Tags: nodemcu, rfid, web-server, http, web-service
---


# Question
Title: NRF24L01+ Getting Started Acknowledge Failed
I have followed numerous guides and tutorials for getting the NRF24L01+ modules working with an Arduino Uno. I have swapped to a genuine Arduino and tried 4 different NRF modules. All without luck.

I am trying to get the most basic example from Simple nRF24L01+ 2.4GHz transceiver demo to work.

Hardware Connections:

Simple TX Test Code:

```
// SimpleTx - the master or the transmitter

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

#define CE_PIN   9
#define CSN_PIN 10

const byte slaveAddress[5] = {'R','x','A','A','A'};

RF24 radio(CE_PIN, CSN_PIN); // Create a Radio

char dataToSend[10] = "Message 0";
char txNum = '0';

unsigned long currentMillis;
unsigned long prevMillis;
unsigned long txIntervalMillis = 1000; // send once per second

void setup() {

    Serial.begin(9600);

    Serial.println("SimpleTx Starting");

    radio.begin();
    radio.setDataRate( RF24_250KBPS );
    radio.setRetries(3,5); // delay, count
    radio.openWritingPipe(slaveAddress);
}

//====================

void loop() {
    currentMillis = millis();
    if (currentMillis - prevMillis >= txIntervalMillis) {
        send();
        prevMillis = millis();
    }
}

//====================

void send() {

    bool rslt;
    radio.stopListening();
    rslt = radio.write( &dataToSend, sizeof(dataToSend) );
        // Always use sizeof() as it gives the size as the number of bytes.
        // For example if dataToSend was an int sizeof() would correctly return 2

    Serial.print("Data Sent ");
    Serial.print(dataToSend);

    if (rslt) {
        Serial.println("  Acknowledge received");
        updateMessage();
    }
    else {
        Serial.println("  Tx failed");
    }
}

//================

void updateMessage() {
        // so you can see that new data is being sent
    txNum += 1;
    if (txNum > '9') {
        txNum = '0';
    }
    dataToSend[8] = txNum;
}

```

Serial monitor:

Using `radio.printDetails( );` returns:

Please let me know what I'm missing.

# Answer
The Arduinos 3V3 does not privide enough current. To eliminate this as a source of your problem you can use a ceramic capacitor of 100µF across VCC and GND pins of the nRF24L01+ module or buy a 5V to 3V3 step down converter specially made for nRF24L01.
> 1 votes

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


# Question
Title: How to convert digital signal to analog value
I have spwm output from arduino, and when i read on analogread it shows only 1023 and 0, because it is digital signal. Is there any way to convert these spwm value into analog value reading

# Answer
The problem seems to be clear to you: for slow systems a pwm signal can be considered analog, but measuring at higher rates and without a filter reveales the digital nature behind pwm and all you see is either logic high (1023) or low (0). Possible solutions are:

1. apply a filter in hardware (LC low-pass)
2. apply a filter in software (e.g. by calculating a running mean)
3. attach interrupts to the rising/falling edge of your signal and measure the high/low time to calculate the duty cycle

Which of those options to choose will mainly depend on the PWM frequency you want to measure. For low frequency I recommend option 3 (special cases are duty cycles around 0% and 100% as there are no edges), for higher frequencies I would use option 1/2.
> 4 votes

---
Tags: analogread, digital-analog-conversion
---


title: Can't connect to serial port

text:
# Question
Title: Can't connect to serial port
I'm trying to make my Arduino's LED blink for the first time, but when I try to upload the code I get the following error in the Serial Monitor:

> Error opening serial port '/dev/ttyACM0'.
> Try consulting the documentation at http://playground.arduino.cc/Linux/All#Permission

BTW, I have `serial.debug_rate=9600`, so I don't think that's the problem. Can anyone help me with this please?

# Answer
It seems your serial does not have the right permissions to be opened in *user mode*. Try adjusting that by typing

```
sudo chmod a+rw /dev/ttyACM0

```

on the console (open it by `CTRL``ALT``T`).
> 3 votes

# Answer
That issue is due to your username not being in the dialout group. Try: `sudo usermod -a -G dialout yourusername` and rebooting to load the changes, then check again if the problem still persists...

I wrote an article about that here: Solving Arduino IDE upload problem, and serial monitor error on Ubuntu.
> 1 votes

---
Tags: serial, led
---


title: Arduino Hardware serial pins with RS485

text:
# Question
Title: Arduino Hardware serial pins with RS485
I tried asking a question in my earlier post - SerialEvent with RS485 communication it helped me understand Hardware serial and Software serial but i had few more questions for which i started this new thread. Now i didn't write any code yet, but i will be using same code as my earlier post if i get expert inputs.

My Project - I have 6 Arduino nano which will do some simple task, mostly its one way communication at a time, like once master send message to slave i don't want immediate response slave will push button or something and then it will send response to master. So its rare that i will have two way communication at same time.

RS485 - I am going to use RS485 as distance is around 40ft.

Now my questions -

1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.

2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.

3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.

I would appreciate your inputs, which will make me decide to go on right path. Sorry i didn't post any code because my post is more to understand correct path to be followed...

# Answer
> 1 votes
> 1 - Can i use Hardware serial pins with RS485 for 40ft distance, i tested code and it does work but i couldn't test that for 40ft. So not sure if it works or not.

Yes.

> 2 - Is it good idea to use hardware serial pins for my project i explained, as i see plus and minus over internet and making me confuse. I see majority people recommend Hardware pins though.

Yes. SoftwareSerial is awful.

> 3 - Is there limitation connecting multiple arduino nano with this approach, i only did this with 2 so far.

Yes. The MAX485 and similar chips can only handle up to about 30 devices on one bus. The exact number is in the datasheet for the chip.

---
Tags: arduino-nano, hardware, uart, rs485
---


# Question
Title: How to drive Arduino UNO as a counter triggered by 555 timer's output (astable mode)
I have an Arduino Uno and a 555 timer configured to astable mode.

What I'm trying to do is to program my Arduino to increase a "counter" variable (counter++) everytime it gets triggered by 555 timer's output (through analogIN pin).

**My problem is** that Arduino takes 555 timer's output as a continuous triggering and increases my counter as long as the pulse in the analogIN lasts. So instead of incrementing by 1, it is increased by approximately 97 (sometimes more or less).

I need to take the analog in as a "packet" so everytime analogIN is triggered, no matter how long the pulse lasts, it will be treated as a single event and not as continuous triggering.

What do I have to change?

My code:

```
int counter = 0;

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

}

void loop() {
  if(analogRead(A0) > 250) {
    counter++;
    Serial.println(counter);
  }

}

```

Thanks

# Answer
You need to create a finite state machine with 2 states:

1. Waiting for input from 555 to go high. When this happens increment the counter & advance to the next state.
2. Waiting for the input from the 555 to go low. When this happens advance to the next state. That is, the first state.

In the following Arduino "State Change Detection (Edge Detection) for pushbuttons" example / tutorial you do not need the complex code to debounce the switch. However, the edge detection and state machine portion of the code can likely be applied to your project.
> 0 votes

# Answer
I recommend using one of the atmega's counter modules. That way you can count the pulses synchronuously to your program (real paralellism!) and you also don't have to implement any edge-detection youself as the counter module already provides this feature.

A search for "pulse counter" will lead to many tutorials on how to do that.
> 0 votes

---
Tags: timers, analogread
---


title: Voltage measure range of an arduino?

text:
# Question
Title: Voltage measure range of an arduino?
I recently thought of using an Arduino to measure voltage and I stumbled across the problem that what is the max voltage I can measure??? It is an Arduino Uno and I am thinking that I would also display the voltage measured on a 16 * 2 LCD screen.My guess is max of 5 volts but if this is correct how can I increase its range?

# Answer
> 3 votes
Without any further configuration, the ADC (Analog Digital Converter) of the Atmega328P (which is build onto the Arduino Uno) uses Vcc as voltage reference (meaning 5V in the case of the Arduino Uno). A voltage of 5V will result in the maximal value (which is 1023, since this is a 10bit ADC). So the voltage range in this case is 0 to 5V.

The Arduino Uno has an extra pin, where you can supply an own reference voltage. But it's limit is tied to the ADCs supply voltage `AVcc`, which is 5V for the Arduino Uno rev3 (as shown in the schematics of the Uno). The reference voltage should then be in the range of 1V to `AVcc`. So this still gives you only a range of 0V to 5V or smaller.

When you use a standalone Atmega328P, you can make `AVcc` a bit higher than the chips supply voltage `Vcc`, but at maximum `Vcc + 0.3V`.

You can check all these numbers by looking into the datasheet of the Atmega328P, chapter 28.9 (Electrical Characteristics --\> ADC Characteristics).

---

How to increase this range depends greatly on your requirements. If you simply need a constant higher range, you can simply put a voltage divider in front of the analog input. Or you can use a more complex circuit involving an op-amp (amplifier ciruit, here with amplification factor below 1). You can even build this to be variable.

Should it be, that your wanted voltage range exceeds the 5V greatly, for example, if you want to measure mains voltage (230V for most europe, 110V in USA), you should definitely take great care and never connect this directly to electronic like the Arduino. High voltages (especially at high possible currents) should always be handled with great care.

# Answer
> 2 votes
The ATmega328's (it's the microcontroller on the uno) absolut maximum rating is `Vcc + 0.5V` for any pin (except the reset pin) while Vcc must not be higher than 6V.

In order to measure higher voltages you have to use a voltage divider (read this) to adjust the input voltage to the range `0V - Vcc`.

---
Tags: arduino-uno
---


# Question
Title: How to find out the maximum used stack space?
I am creating an Arduino sketch which involves quite some classes, and I want to check if it will run on an Arduino Uno or Mega (2 KB vs 8 KB SRAM).

So far my global variables take up around 1,200 bytes, and I expect this will rise. However, beyond that I need to make sure the stack memory is not using up too much. **How can I find the maximum used stack size?**.

I can check manually by calculating the maximum function stack and calculating all parameters + local variables, but this is a very tedious job (especially since my application changes still a lot).

Or another way: I know it is possible to get the free space, but should I add this in 'strategic' locations or in the beginning of all functions and continue from there? (there will be many of them).

Or is there preferable some static way of checking this?

The application works within Visual Studio C++ as stand alone too, so maybe that helps for some solution.

I expect the stack size easily to be a few hundred bytes (which is quite a lot for the Arduino Uno SRAM).

# Answer
Knowing the stack size is pretty easy: the stack pointer is initially set to `RAMEND` and goes down as the stack grows. Thus:

```
static inline size_t stack_size()
{
    return RAMEND - SP;
}

```

> should I add this in 'strategic' locations \[...\]

Obviously, the result will depend on where this is evaluated. Ideally you should test this in the deepest parts of your call chain, as this is where the stack will be at its maximum size. Note that ISRs stack on top of all your regular code.

**Edit**: There is no easy way to know the *maximum* stack size. You could get an approximation by sampling the stack at regular intervals, e.g.:

```
#include <util/atomic.h>

volatile size_t min_sp = RAMEND;

ISR(TIMER0_COMPA_vect)
{
    if (SP < min_sp)
        min_sp = SP;
}

static inline size_t max_stack_size()
{
    size_t min_sp_copy;
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        min_sp_copy = min_sp;
    }
    return RAMEND - min_sp_copy;
}

```

If you enable `TIMER0_COMPA` interrupt in `setup()`:

```
TIMSK0 |= _BV(OCIE0A);

```

then the stack size will be sampled every 1.024 ms. Note, however, that this ISR is itself using some stack space for its own purposes (9 bytes in my experiment), and that this is not sampling other ISRs or critical sections.
> 7 votes

# Answer
Initialize the entire SRAM space from the top of the heap to the bottom of the stack, either during setup, or in a modified version of the Arduino-provided main() function, with some unlikely pattern, such as {0x55, 0xAA, ...} or "UnusedUnused...".

After your program has run a while, examine memory for dirty footprints, reading up from the top of heap to find the highest heap excursion, and down from the stack-pointer to find the lowest address used by stack. You could use a debugger if you have one, or just a hex & ASCII dump to the terminal. Pick through it with whatever tools you have handy on your PC. If there's been no collision and you're using a memory dump, it's pretty easy to start somewhere in the middle that wasn't disturbed, and scroll in either direction. The place where your initialized pattern has been overwritten usually stands out very plainly.
> 7 votes

---
Tags: arduino-uno, arduino-mega, memory
---


# Question
Title: SdFat: Why does the first write to the file take so long?
I have tested this problem on 6 micro-SDHC cards of 3 different types. 3 are 32-GB Sandisk, 2 are 16-GB Kingston, and 1 is 16-GB Samsung. These cards are used in data loggers and typically contain hundreds or thousands of 5-MB text files whose names are formatted like FILE1234.TXT.

The problem is that when a logger containing such a card (containing data) is started, the first write takes a long time--from 7 to 30 seconds. Opening the file (the smallest available filename) doesn't take too long. Subsequent writes don't take long. Just the first write.

Now, the plot thickens: this delay can be eliminated by first opening FILE0000.TXT and immediately closing it. Further, once this is done, that disk is never affected by this delay again. This has happened with each of the disks.

Here is some minimal code demonstrating the issue:

```
#include <SdFat.h>
SdFat sd;
SdFile file;

void setup(){
  Serial.begin(57600);
  sd.begin();
  int m = millis(); // just to time everything

  // critical line that prevents delays
  file.open("FILE0000.TXT", O_WRITE | O_TRUNC | O_CREAT); file.close();

  // file we actually want to write to
  file.open("FILE6005.TXT", O_WRITE | O_TRUNC | O_CREAT);
  Serial.println(millis()-m); // print how long it took to open

  file.println(F("test"));
  Serial.println(millis()-m); // print how long it took to write
  file.close();
}
void loop(){
}

```

When the "critical line" in the code is commented out, I get a big delay in the first write to the file. When it's uncommented, there's no delay, and I never get a delay on that disk again even with the line commented. I saw this on all six disks.

One further bit of mystery: at first, this did not work on one of the cards. I checked and found that this card alone had a hidden ".Trash-1000" directory. I removed that directory and tried again, and this fix did work that time.

Does anyone have any idea what's going on here?

# Answer
> 1 votes
Most file systems exhibit poor performance if you store many files in one directory. 'Normal' desktop computers are perhaps so fast, that you don't notice the performance impact, but accessing the file system from a relatively slow micro-controller, which also have limited means of caching the file system data structures in RAM, you may have to consider for this and either write a smaller number of files or build a tree of directories, so that you only have a limited number of files in each directory.

# Answer
> 1 votes
I have observed this as well, but with bare-metal programming rather than arduino. I use an STM32F7 chip to write to a class 10 SD card using block writes from the SD card standard. I use a custom file system rather than FAT. My first write to the SD card takes roughly 8-10 times longer than all of my other writes. This is each time I remove power and resupply power to the device. This doesn't happen if I reset the processor without removing the power supply. If I only reset the processor (which means I reconfigure and initialize the SD card) this write delay doesn't happen.

The only thing that doesn't happen to the SD card before the first write is the configuration of the data path state machine (DPSM). Could the DPSM being in a state that isn't conducive to writing on start-up be the culprit?

---
Tags: sd-card
---


# Question
Title: How to compose an HTTP GET request URL with key/value parameters
I am experimenting with some code running on an ESP8266 board to retrieve data using a web API. I would like to store the host address and key/value parameters (API key etc.) of the GET request as constants/variables (I'm not sure which is better) and then use them to compose the full GET URL.

**How can I compose the full URL from separate strings/char arrays including the correct syntax for the key/values pairs?**

EDIT: Just adding that I am using the ESP8266HTTPClient library.

The example I have been following uses a basic API URL with no parameters and stores the host URL as follows:

```
const char* host = "http://somehost.com/dir/1";

```

(Side question: please explain the difference between `const char* host` and `const char *host` if there is one)

Using this simple URL I can successfully retrieve the JSON data using this method:

```
HTTPClient http;
http.begin(host);
int httpCode = http.GET();
Serial.print("HTTP RESPONSE: ");
Serial.println(httpCode);
if (httpCode > 0) {
  String payload = http.getString();
  Serial.println("PAYLOAD:");
  Serial.println(payload);
}
http.end()

```

I am looking into using the "ArduinoJson" library to manage the json data instead of String, but am more interested in figuring out how to compose the URL at the moment.

What I would like to achieve is adding key/value parameters stored as variables to the host URL e.g.:

```
const char* host = "http://somehost.com/dir/1";
char* app = "123";
char* user = "123456"
char* api_key = "XXXXXXXXXXXXX";

```

And then join them with strings or char arrays to create the full URL, or simply pass the host address plus the parameter values to a function that composes the URL or sends the full GET request(with the parameter "key=var", question mark, and ampersands etc.):

```
http://somehost.com/dir/1/?appid=123&userid=123456&key=XXXXXXXXXXXXX

```

This was very easy to achieve in python using the "requests" HTTP library. I was able to store the key/value parameters as a dict and then pass the host address and the parameter dict to the `requests.get` function and it would compose the URL automatically.

I guess there is more than one question buried in there, but the main one is "what is the best way to compose the full URL without hard coding the whole thing?" An example would be so I could change some parameters such as appid by user input before making the GET request.

I am unsure if I am using the right approach using the character arrays, constants or variables, whether I am using the right approach by trying to compose it manually, and in general what the best practices are for doing this efficiently and avoiding memory fragmentation (which is a problem when using string variables?). This device will be required to run constantly and periodically make these GET requests.

# Answer
> Side question: please explain the difference between const char\* host and const char \*host if there is one

There is no difference; n.b. the arduino IDE uses C++! If you don't know C or C++ you should learn that first.

> "what is the best way to compose the full URL without hard coding the whole thing?"

This is basically the same question as how do you manipulate, i.e. compose, composite, concatenate, C strings. c string functions

here is a quick example, without error checking, etc.:

```
const char* host = "http://somehost.com/dir/1";
char* app = "123";
char* user = "123456"
char* api_key = "XXXXXXXXXXXXX";

char urlout[255];

// we are going to start here
strcpy(urlout, host);
strcat(urlout, "/?appid=");
strcat(urlout, app);
strcat(urlout, "&userid=");
strcat(urlout, user);
strcat(urlout, "&key=");
strcat(urlout, api_key);

// urlout == "http://somehost.com/dir/1/?appid=123&userid=123456&key=XXXXXXXXXXXXX"

```
> 0 votes

---
Tags: esp8266, string, http
---


# Question
Title: exit status 1 'mySerial' does not name a type
I just can't make it work for some reason. I tried `#include <SoftwareSerial.h>` and I tried `#include "SoftwareSerial.h"`. Can someone help me?

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

uint16_t buf[256];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  for(int i = 0; i < 256; i++)
    buf[i] = (uint16_t)i;
}
  mySerial.begin(4800);
  mySerial.println("Hello, world"); //printLn  L, not I

void loop() {
  Serial.write((uint8_t*)buf, 512);
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

```

# Answer
> 2 votes
simple mistake mySerial.begin(4800); mySerial.println("Hello, world"); lines was out of void {}

```
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

uint16_t buf[256];

void setup() {
  Serial.begin(9600);
  while(!Serial);
  for(int i = 0; i < 256; i++)
    buf[i] = (uint16_t)i;
   mySerial.begin(4800);
  mySerial.println("Hello, world"); //printLn  L, not I
}

void loop() {
  Serial.write((uint8_t*)buf, 512);
  if (Serial.available()) {
    mySerial.write(Serial.read());
  }
}

```

---
Tags: programming, arduino-nano
---