# Question
Title: Why is it considered bad practice to use the 'new' keyword in Arduino?
I previously asked this question:

*Is it required to delete variables before going to sleep?*

On that question, @Delta\_G posted this comment:

> ... Really on a microcontroller I would create the object in a smaller scope and try to do **everything in my power to avoid having to use `new` or any other form of dynamic allocation.** .... etc.

That comment got three likes and when I google about dynamic allocation using Arduino, everyone also tries to stay away from that. In summary from all the research I did, my conclusion is now **Do not allocate memory unless you really really have to**.

I am using the Visual Studio IDE to create my C++ libraries that I intend to use with Arduino. On the Arduino IDE I just reference those libraries and the code compiles great. Visual Studio is very powerful and it enables me to create really nice code, because I can test it on my computer before running it on Arduino. For example, I created this library:

```
// MyQueue.h

typedef struct QueueItem
{
    void* item;

    QueueItem* next;

    QueueItem()
    {
        item = nullptr;
        next = nullptr;
    }

} QueueItem;

class Queue
{
public:
    unsigned char count;        /* Number of items on queue */
    QueueItem* first;           /* Points to first item on the queue */

    Queue()                     /* Constructor */
    {
        count = 0;
        first = nullptr;
    }

    void enqueue(void* item)    /* Enqueue an object into the queue */
    {
        count++;

        if (first == nullptr)
        {
            first = new QueueItem();
            first->item = item;

            // Log message because we are using the "new" keword. We need to make sure we dispose QueueItem later

            #ifdef windows

            std::cout << "Creating " << first << endl;

            #endif // windows
        }
        else {

            // Find last item
            QueueItem* current = first;
            while (current->next != NULL)
            {
                current = current->next;
            }
            QueueItem* newItem = new QueueItem();
            newItem->item = item;

            // Log message because we are using the "new" keyword. We need to make sure we dispose QueueItem later
            #ifdef windows
            std::cout << "Creating " << newItem << endl;
            #endif // windows

            current->next = newItem;
        }
    }

    void* dequeue()
    {
        if (count == 0)
            return nullptr;

        QueueItem* newFirst = first->next;

        void* pointerToItem = first->item;

        // Log message we are deleting an object because we created it with the 'new' keyword
        #ifdef windows
        std::cout << "Deleting " << first << endl;
        #endif // windows

        delete first;
        first = newFirst;
        count--;

        return pointerToItem;
    }

    void clear()                /* Empty queue */
    {
        while (count > 0)
        {
            dequeue();
        }
    }

    ~Queue()                    /* Destructor. Dispose everything */
    {
        clear();
    }
};

```

Now on my Arduino sketch, I can have the following code if I reference that header file.

```
typedef struct Foo
{
    int id;
} Foo;

void someMethod()
{

    Queue q;

    // Create items
    Foo a;
    a.id = 1;

    Foo b;
    b.id = 2;

    // Enqueue a,b and c
    q.enqueue(&a);
    q.enqueue(&b);

    // Deque
    Foo * pointerTo_a = (Foo*)q.dequeue();
    int x = pointerTo_a->id; // =1

    Foo * pointerTo_b = (Foo*)q.dequeue();
    int y = pointerTo_b->id; // =2

    // Error
    Foo * test = (Foo*)q.dequeue();
    // test == null pointer
}

```

---

Most people say do not use void pointers. Why!? Because I am using void pointers I can now use this queue class with whatever object I want!

## **So I guess my question is: Why is everyone trying to stay away and avoid code like this?**

I am using the NRF24L01 radio module to send messages to several Arduinos. It is convenient to have a queue of messages to be sent. **I would be able to code the same program without allocating memory and avoiding the `new` keyword. But that code will look ugly in my opinion.**

In this quarantine I decided to learn C++ and that has changed the way I code Arduino. The moment I learned C++ I stopped using the Arduino IDE. I been a backed developer for 12 years, and that is the reason why I learned C++ in a couple of months. Arduino is just a hobby for me. **I am still very new to microcontrollers and I will like to understand why people stay away from the full power of C++ when it comes to microcontrollers**. I know I have only 2 kilobytes of RAM. I will not be allocating that much memory. I still want to take advantage of the C++ programming language by using the `new` , `delete` , `poineters` and destructors\`. I want to keep using Visual Studio to write powerful C++ libraries.

In C++ I write interfaces like this

```
// Note I use uint32_t instead of 'unsigned long' because an unsigned long is different size on Windows than on Arduino. Also I use an unsigned short instead of an int because an unsigned short is the same size on Windows and Arduino.

class IArduinoMethods
{
public:

    // Unsigned long in Arduino
    virtual void delay(uint32_t delayInMilliseconds) = 0;

    virtual void print(const char* text) = 0;

    virtual uint32_t millis() = 0; // Get elapsed time in milliseconds
};

```

And I then implement the classes like this. For example, this is the class that I will use when testing my code on a windows computer:

```
// Class to be run on Windows.
class ArduinoMockWindows : public IArduinoMethods
{
public:

    // Inherited via IArduinoMethods
    virtual void delay(uint32_t delayInMilliseconds) override
    {
        // This code will be different on Arduino, and that is why I need this dependency
        Sleep(delayInMilliseconds); // Windows
    }

    virtual uint32_t millis()
    {
        //clock_begin = std::chrono::steady_clock::now();

        std::chrono::steady_clock::time_point now = std::chrono::steady_clock::now();
        auto duration = now.time_since_epoch();
        // etc..
        return someDuration;

    }

};

```

Because a Windows computer cannot send NRF24 radio messages, I can implement an interface (dependency) that will write to a file, for example instead of sending a real radio packet just for testing.

The caveat is that my libraries will require these dependencies. For my library to work, I will have to pass it an object of type `IArduinoMethods` and `INrfRadio`. If I am running my code on Windows I will pass it a class that will implement those methods that can run on windows. **Anyways the point is not to show how C++ works. I am just showing how I use pointers and allocate memory for a lot of things.**

Because I allocated memory I was able to test my library on Windows and on Arduino for example. I may also create unit tests. I see so many benefits by allocating memory. If I am organized and remember to free the objects I no longer use, I can gain all this benefits. **Why people do not code like this when it comes to Arduino?**

---

## Edit 1

---

Now that I understand how heap fragmentation works, I know I have to be careful when using the `new` keyword.

I hate when people do what they are told to do without understanding how things work. For example, the answer https://arduino.stackexchange.com/a/77078/51226 from **Why is the queue library in this question for starters?**. There are going to be times when a ring buffer works better and other times when the `new` keyword works better. Probably the ring buffer will work best for most cases.

Take the following scenario where you only have 1 KB of memory left.

1. There is a hierarchy of nodes where a node have a child and a sibling. For example, node A can have child B and sibling C. Then child B can have another child, etc.

(I will be storing this in memory)

2. I have a queue of work that needs to be done.

(I will have to store this work somewhere)

3. I will have a queue of events

(I will have to store this somewhere)

**If I use what most people say I should do then I will be have to:**

1. Reserve 500 kB to be able to store nodes (I will be limited to n number of nodes)
2. Reserve 250 kB for the queue of work that needs to be done.
3. Reserve 250 kB for the queue of events.

*This is what most people will do* and it will work great with no problems of heap fragmentation.

**Now this is what I will do**

1. Ensure that everything that I allocate is of size 12 bytes. A node only has its id (unsigned int), child (pointer), type (unsigned char), etc.. with a total of 12 bytes.
2. Ensure that all the work that will be enqueued is of size 12 bytes as well.
3. Ensure that all the events that will be enqueued is of size 12 bytes as well.

Now if I have more work than events, this will work. I just have to program in my code that I never allocate more than 70 items. I will have a global variable that has that count of allocations. My code will be more flexible. I will not have to be stuck with strictly 20 events, 20 work and 30 nodes. If I have fewer nodes then I will be able to have more events. \**Anyways my point is that one solution is not better than the other. There are going to be scenarios when one solution is better.

In conclusion, just understand how heap fragmentation works and you will gain a lot of power by using the new keyword. Do not be a sheep and do what people tell you to do without understanding how things work.\**.

---

## Edit 2

---

Thanks to @EdgarBonet, I ended up storing Nodes on the stack. Here is why:

I have a hierarchy of nodes that can be represented as:

```
typedef struct Node
{
   unsigned short id;
   Node * sibling;
   Node * child;
} Node;

```

As you can see every node is only 6 bytes. That is another reason why I did not care to much about allocating Nodes at the beginning. If I allocate this node on the heap I will be losing 2 more bytes (33%) for every allocation because on every allocation the size of the node has to be stored. As a result I created these two methods and a buffer:

```
// For this to work a node can never have an id of 0 !!!

Node nodeBuffer[50];                     /* Buffer to store nodes on stack */

Node* allocateNode(Node nodeToAllocate)  /* Method to store a node */
{
    // Find first available spot where a node can be saved
    for (char i = 0; i < 50; i++)
    {
        if (nodeBuffer[i].id == 0)
        {
            nodeBuffer[i] = nodeToAllocate;
            return & nodeBuffer[i];
        }
    }
    return nullptr;
}

void freeNode(Node* nodeToFree)          /* Method to delete a node */
{
    nodeToFree->id = 0; // If the id of a node is 0 this is my convention of knowing it is deleted.
}

```

And on my code I used to have things like:

```
Node * a = new Node();
a->id = 234423;
// ....
// .. etc
// ..
delete a;

```

Now I just have to replace that code with:

```
Node * a = allocateNode({});
a->id = 234423;
// ....
// .. etc
// ..
freeNode(a);

```

And my code works exactly the same without having to use the `new` keyword. I thought it was going to be complicated to refactor the code and create a buffer.

I made this modification because I wanted to be able to store more nodes on my code. By loosing that 33% I was not going to be able to create that many. **If I only allocate objects of the same size and I do not allocate that many it is perfectly fine to use the `new` keyword.** \> Also in the case of the queue I will allocate and delete objects very fast. Because the objects will not persist on memory for too long, and the chances of having heap fragmentation are very low.

# Answer
Most Arduinos (like the Uno or Nano) have very few RAM, thus you first need to make sure that you never allocate too much memory. Dynamically allocating memory can also lead to heap fragmentation (heap being the part of memory where dynamic allocation happens).

In most cases you would want to allocate memory of different sizes (for example arrays of different sizes) or just different objects (with each having it's own size) (!!! This is the key point here). Then you are going to delete some of these objects which will create holes inside the memory. They can be filled again with objects with the same or less size. As time passes and more allocation and deleting happens these holes tend to get smaller, up to the point where none of your new to allocate objects can fit in there. That memory then is unusable. This phenomenon is called heap fragmentation.

These holes appear naturally also on a PC but there are 2 key differences:

1. The Arduino has such little RAM that the holes can fill up your memory very very fast.
2. While the PC has an operating system, which manages the RAM (defragmenting it or putting unused stuff away into a paging/swap file), the Arduino does not have an OS. So noone keeps an eye on the real available RAM and noone tidies up the memory once in a while.

That does not mean that you cannot use dynamic allocation on an Arduino, but that is very risky depending on what exactly you are doing and how long the program should work without failing.

Considering this big caveat, you are very limited on how to use dynamic allocation. Doing it too much will result in very unstable code. The remaining possibilities, where it might be safe to use it, can also be easily done with static allocation. For example take your queue, which is basically a linked list. Where is the problem with allocating an array of `QueueItem`s at the start. Each item gets a way to determine if it is valid. When creating a new item you just pick the first element in the array, which has a non-valid item, and set it to the desired value. You still can use the data via the pointers, just as before, but now you have it with static allocation.

You might find that the code looks uglier that way but you need to adapt to the platform that you use.

Note that this does **not** apply when you are going to create **only objects with the same size**. Any deleted object will leave a hole where any new object can fit into. The compiler uses that fact. So in that case you are safe. Just every object that you dynamically create in your program needs to be the exact same size. That of course also includes objects that are created inside different libraries or classes. For this reason it can still be a bad design choice, as you or others (if you want to publish your code), may want to pair your library with other code.

Another way to be safe is to only create and delete objects in closed cycles, meaning, that a created object needs to be deleted before the next object is created. Though that is not fitting for your application.

---

'Bigger' microcontrollers, for example the non-Arduino boards with the ESP32, have much more memory. Thus the use of dynamic allocation is not that bad on them. Though you still don't have an OS to manage the RAM.
> 17 votes

# Answer
Dynamic allocation is generally discouraged in embedded applications because you cannot guarantee that you do not exceed (attempt to allocate more than) the available memory. Static allocation will generally have this guarantee although out-of-memory bugs may still be possible.

Additionally, far fewer services or tools are available to automatically manage and mind the memory for you. Any service that does so will consume computational resources.

This means that you inherently create a mechanism in your device that would cause a memory (heap) overflow and possible undefined behavior (UB). This is true **even if your code is bug-free and has no memory leaks.**

In non-critical, exploration, learning, and prototype applications this may not be important.

Consider that without careful consideration undefined behavior can result in hardware failures and unsafe performance, for example if the device reconfigures GPIO through an errant write to the correct registers during a crash.
> 7 votes

# Answer
### For starters, fix your library

As noted by @crasic, dynamic memory allocation is generally not recommended for embedded systems. It may be acceptable for embedded devices which have a larger amount of free memory - embedded Linux is commonly used, for example, and all Linux apps/services will tend to use dynamic memory allocation - but on small devices such as an Arduino there simply is no guarantee that this will work.

Your library illustrates one common reason why this is a problem. Your `enqueue()` function creates a `new QueueItem()` but does not check that the allocation succeeded. The result of failed allocation may either be a C++ `bad_alloc` exception, or it may be returning a null pointer, which when you reference it will give a system memory access exception (SIGSEGV signal in Linux, for example). It is nearly universal in Linux and Windows programming to ignore memory allocation failure (as encouraged by most textbooks), because the massive amount of free RAM and the existence of virtual memory makes this very unlikely, but this is unacceptable in embedded programming.

More generally though, as @crasic says, memory fragmentation can leave even non-buggy code unable to allocate memory. The result will be a failure to allocate memory, but the code will at least know this has happened and will probably be able to continue.

### But better, use a fixed-size FIFO queue instead

Your code relies on dynamic allocation to add and remove elements in a queue. It is perfectly possible (and equally easy coding-wise) to create a fixed-size array for the queue, so the various failure modes of dynamic allocation simply do not apply. An item to be queued is simply copied into the next free queue slot, and a queue slot is marked free when it has been used. (Don't forget to use a mutex when adding and removing items from the queue, because adding and removing will often be called from different places.)

The queue can be made whatever size you feel is appropriate (allowing for how much RAM you have). With a fixed size, you are forced to make a design decision on what should happen if the queue overflows - do you delete the oldest data to make room for the new value, or do you ignore the new value? This may seem an unwelcome new feature, but it is a ***good*** thing, because the third option which you've currently got is that your code goes "Aaaarrggghhh I don't know what to do!" and crashes fatally, and we don't really want that.
> 5 votes

# Answer
I'm adding this not so much to add to the answer as to add some real world implications for those that may be down this particular rabbit hole. It's nice to talk about what could happen theoretically, but a new programmer may still be tempted to think that he can out-think these limitation and still do something useful. Here is some real world talk about why that is foolish even if you are capable.

Let's say we're developing code on an Arduino UNO. We've got 2K of RAM to work with. We have a class that loads a list of names, maybe it's a building access device or something. Anyways, this hypothetical class has a name field to store someone's name. And we decide to use the String class to hold the name as a String.

Let's say after our program is all there and doing what it's doing that there is 500 bytes left for this list of objects, each with a name field that could be of varying length. So we run along nicely for years with a crew of 14 or 15 people with an average name length of 30 characters or so.

But one day a new guy signs up. And his name is really long. Let's say it takes 100 characters. Even if we're smart coders and only have one copy of this String in memory, we've got it there and suddenly it doesn't fit. Now a program that has worked for years suddenly fails. And nobody knows why.

So the solution is easy right? Enforce a maximum limit on the length of the name. Some simple code that checks the name length and we can write a great piece that still allows the variable name length and won't let you create a new user if there's less than that much left. Seems simple enough, but then Becky in accounting gets married and her last name changes from Smith to Wolfeschlegelsteinhausenbergerdorff and suddenly our program breaks again for no reason.

So the solution is simple right? We'll enforce a maximum length and we'll be sure to reserve enough memory for each object that it can afford to have the maximum length name. And that's something that we do most efficiently without dynamic allocation since we already know the size of the object.

I hear what you're saying, "but Delta-G, if we have all those short names in there, why are we going to waste all that memory on them when we don't have to. Let's only save space for a long one if we have a long one." And I like your thinking, this is good thinking. But it doesn't help anything to save that memory. If you do save some, what are you going to do with it? If your program uses it, then there is no longer room for the longer case and suddenly you have to enforce an even shorter maximum length to accommodate that usage.

Say for instance we have 500 bytes of room and we enforce a maximum length of 50 bytes for 10 users. And let's say that when the names are short we want to let the program use some of that saved space. If the program can encroach 100 bytes into that space when the names are short, then why wouldn't the same situation happen with long names? So really since the program can use all but 400 bytes then there's really only 400 bytes of room and we have to enforce a 40 byte maximum for 10 users or 50 bytes for 8.

Since you're going to have to make that sacrifice anyway, then it only makes sense to remove the work of dynamic allocation and just make things fixed sizes or use fixed size buffers.

If we had a PC with gigabytes of memory, we wouldn't even be thinking about this. But on an Arduino UNO with 2K bytes of memory it can become a big problem really fast.

The other problem is that these bugs are so insidious. If out of memory bugs just caused a simple crash and the thing no longer worked then it wouldn't be nearly so scary. But that's not how out of memory bugs work on a microcontroller. It all depends on how things are arranged in memory by the compiler.

These bugs often manifest as something that seems to work most of the time but has some funny bugs nobody can explain. Maybe there's only a problem if someone has a name that is exactly 26 characters long and tries to open the door on a Wednesday. Or maybe the issue will only arise if Becky logs in immediately after Bob. Maybe it just garbles three letters on the screen but other than that everything works. Maybe with a different name changed that suddenly turns into our lock opens for anyone. There's no guessing or explaining out of memory bugs. So we have to be super careful to avoid even the remote possibility of running into one.

And that's why we avoid using dynamic allocation on small microcontrollers. At the end of the day, there's nothing you can save with it, and even if you could the consequences of getting something a little wrong are terribly frustrating. With these types of programs you almost always have to end up enforcing some sort of limit on everything and once you're enforcing limits there's no use for dynamic allocation anymore.
> 2 votes

---
Tags: c++, memory-usage, pointer
---


title: How to use "+" character as a String

text:
# Question
Title: How to use "+" character as a String
Well I am trying to save phone number as a string. For ease of use I want to add "+" character programmatically. Like this:

```
String cepNo ="+" + "901234567";

```

But program gives this error.

```
exit status 1
invalid operands of types 'const char [2]' and 'const char [13]' to binary 'operator+'

```

How to add "+" beginning of the string.

# Answer
> 4 votes
You cannot add C strings (i.e. NUL-terminated arrays of `char`) with the `+` operator. It only works with `String` objects. You can, though, add a String object and a C-string, because in this case the compiler implicitly converts the C string into a String object:

```
String phone_number = "901234567";
phone_number = "+" + phone_number;

```

The last line is interpreted by the compiler as

```
phone_number = String("+") + phone_number;

```

That being said, I encourage you to try to avoid String objects if possible. These use dynamic memory allocation which carries the risk of heap fragmentation. The same thing can be achieved with plain C strings:

```
char phone_number[] = "901234567";
char full_phone_number[strlen(phone_number) + 2];
strcpy(full_phone_number, "+");
strcat(full_phone_number, phone_number);

```

Note the size of the second string: `strlen(phone_number) + 2`. You need one extra `char` for the `+` sign, and another one for the NUL string terminator.

Now, with C strings you can do better, and avoid copying: reserve enough room in an array for the full number (“+” included), and then fill the digits starting from the second slot in the `char` array. You can then add the `+` sign later:

```
char phone_number[16];
strcpy(phone_number + 1, "901234567");
phone_number[0] = '+';

```

Although I personally would write the “+” sign and a NUL while initializing the array:

```
char phone_number[16] = "+";
strcat(phone_number, "901234567");

```

# Answer
> 2 votes
use `String cepNo = String("+") + "901234567";` or `String a = "+"; String cepNo = a + "901234567";`

---
Tags: arduino-uno, string
---


# Question
Title: dot matrix arduino turn off the intermittent led
I made a dot matrix that contain 10 row and 12 column , total 120 led.

I want to turn on the leds like this picture but when I open ground 1 , 2 and pin 0 , 1 , 2

6 leds light together.what kind of structure should I build?

Sheme :

I tried row by row like this:

```
 clear_cube();
 regWrite(cube[0][0], HIGH);
 set_array(4);
 //delay(10);

clear_cube();
regWrite(cube[1][0], HIGH);
set_array(3);
//delay(10);

clear_cube();
regWrite(cube[0][0], HIGH);
set_array(2);
//delay(10);                                                                                When I decrease the delay 5 leds blinking.

```

100 50 10 0 delay Youtube

# Answer
> 1 votes
You can't just turn them on like that.

Instead you have to turn one row on. Then the next row. Then the next. Very fast.

So you first display:

```
O@OO
OOOO
OOOO

```

Then you display

```
OOOO
OO@O
OOOO

```

Then you display

```
OOOO
OOOO
O@OO

```

And you cycle through that very fast. Usually using a timer to run it all. The fact that you're using '595s will slow you down and make it harder to update fast enough to look non-flickery.

# Answer
> 0 votes
You want to multiplex them by rows or columns. If you do it by columns, then do the following: Set all columns to open circuit. (everything off.)

Set the row value pins for the first column, then activate the column pin for the first column. The LEDs for the first column light up.

Now delay for a brief period (say 20 ms) and go on to the next column. (Obviously you'd use a loop for this.) Repeat.

You should write your code as a state machine using `millis()` rather than using delay, or you will paint yourself into a corner and you'll write code that totally blocks the machine just to display the LED grid. If you use `millis()` and a sate machine you'll be able to do other things at the same time you loop through the LEDs

---
Tags: arduino-nano, led, spi, shift-register
---


# Question
Title: cannot get low power with Adafruit Trinket
I want to get as low power use during sleep as possible with an Adafruit Trinket. Based on results presented on various places in the internet (blogs etc), I expect to be able to go down to 50 - 100 micro amps on the ATTiny85 of the Trinket. I am aware of the fact that using a board such as Trinket may add a bit of consumption, and I physically removed the power LED and the power regulator. I am feeding 5V directly on the 5V pin.

I am using the simplest sketch I can think about for low power, with nothing connected to any pin:

```
#include <avr/sleep.h>          // library for sleep

#define adc_disable() (ADCSRA &= ~(1<<ADEN)) // disable ADC (before power-off)

void setup() {
  // put your setup code here, to run once:
  delay(10000);

  // power_all_disable();
  set_sleep_mode(SLEEP_MODE_PWR_DOWN);
  adc_disable();
  sleep_enable();
  sleep_mode();

}

void loop() {

}

```

But I cannot get less than around 1.3 milli amps consumption during sleep. Do you know what may be the cause of using ~1mA instead of ~100 microA? Any idea how I can decrease this further?

*Edit 1: it should be even much less than ~50 - 100 micro Amps*: ATtiny85: Power consumption vs clock speed ; even though this the libraries are maybe primary intended for the ATMega328P, it looks like it should work also with ATTiny85 as well: http://www.technoblogy.com/show?KX0

*Edit 2: I had an ATMega328P-based Adafruit Metro Mini lying around. I took away the ON LED, and then using exactly this sketch, feeding power directly on the 5V pin of the Metro Mini, leads to a power consumption of around 150 micro Amps during sleep, which is more like what I expect. Strange it is 10 times more with the ATtiny while it should have been less (?). Am I missing something or is it maybe just broken library on ATtiny? This is a bit ironic, as I went for the lesser ATtiny85 based board for saving current compared with the ATMega328P...*

# Answer
> 2 votes
Please have a look at the schematics:

https://cdn-learn.adafruit.com/assets/assets/000/010/774/original/adafruit\_products\_trinket5.png?1378223478

The USB connector uses a resistor (1500 Ohms) against the 5V net and a 3.6 Volt Z-Diode on it's (D-)-Pin. In addition to the current that is drawn by the microcontroller, this part of the circuit draws some extra current. (5\[V\] - 3.6\[V\])/1500\[ohm\] = 0.0009333... ~= 0.001 \[A\].

Even though I'm not completely sure without making some tests, that seams plausible to me.

**EDIT** (Answer to the OPs comment below.)

The schematics uses a normal diode symbol but has a 3.6 Volt label next to it. I assume that it should be a Zener diode with a reverse voltage drop of 3.6 Volts. If I'm right, the Diode is used to limit the 5 Volts to 3.6 Volts (for what reason ever). The Zener Diode effectively limits the Voltage over it to 3.6 Volts. The rest of the voltage of 5 Volts must be dropped over the resistor. i.e. 5V - 3.6V = 1.4V. This voltage drop tells us by Ohms Law that the current through the resistor is:

```
I = U / R
I[A] = 1.4[V] / 1500[Ohm]  = (about) 1 mA.

```

This value is very reasonable for your observations and the current is drawn from the 5V connect, hence you can measure it, even if you would desolder the microcontroller.

---
Tags: power, attiny, adafruit
---


# Question
Title: How are locations in FLASH memory addressed?
There is an external FLASH memory (W25Q80DV) that I want to use with the Arduino. This memory has 4096 pages of 256 bytes each.

I want to make multiple writes per page to use memory evenly and erase less.

Test code:

```
#include <SPI.h>

#define readStatusReg_1 0x05
#define readArrayReg 0x0B
#define writeEnableReg 0x06
#define pageProgramStatusReg 0x02

#define FLASH_SELECT_CHIP 33

// # Select / Unselect chip
void selectChip(bool state) {
  switch (state) {
    case true:
     digitalWrite(FLASH_SELECT_CHIP, HIGH);
     digitalWrite(FLASH_SELECT_CHIP, LOW);
      break;
    case false:
     digitalWrite(FLASH_SELECT_CHIP, HIGH);
      break;
  }
}

// # Wait flash ready state
void notBusy() {
  uint16_t whileCounter;
  selectChip(true);
  SPI.transfer(readStatusReg_1);
  while((SPI.transfer(0) & 1) && whileCounter < 45000) { whileCounter++; }
  selectChip(false);
}

// # Send command and address
void sendCommandAndAddress(const byte command, const unsigned long address) {
  SPI.transfer(command);
  SPI.transfer((address >> 16) & 0xFF);
  SPI.transfer((address >> 8) & 0xFF);
  SPI.transfer(address & 0xFF);
}

// # Write enable
void writeEnable() {
  notBusy();
  selectChip(true);
  SPI.transfer(writeEnableReg);
  selectChip(false);
}

// # Write FLASH page
bool writeFlashData(const unsigned long address, byte * data) {
  writeEnable();
  selectChip(true);
  sendCommandAndAddress(pageProgramStatusReg, address);
  uint16_t len = sizeof(data);
  for(uint16_t i = 0; i < len; i++) {
    SPI.transfer(*data++);
  }
  selectChip(false);
  notBusy();
  return true;
}

void setup() {
  // SPI
  pinMode(FLASH_SELECT_CHIP, OUTPUT);
  digitalWrite(FLASH_SELECT_CHIP, HIGH);
  SPI.begin();
  SPI.setDataMode(0);
  SPI.setBitOrder(MSBFIRST);

  // Write FLASH
  #define TESTADDRESS 0x1000
  byte msgData[] = "Hi all!";
  writeFlashData(TESTADDRESS, msgData);
}

void loop() {}

```

Here, the address **#define TESTADDRESS 0x1000** (4096) is specified for writing data.

I'm not clear if this is the page address or the byte address from which I will start recording?

I would like to actually split one page into multiple blocks and write data for them separately.

# Answer
> 1 votes
> I'm not clear if this is the page address or the byte address from which I will start recording?

That is the byte address. As the data sheet in section 8.5.13 says:

> If an entire 256 byte page is to be programmed, the last address byte (the 8 least significant address bits) should be set to 0. If the last address byte is not zero, and the number of clocks exceed the remaining page length, the addressing will wrap to the beginning of the page.

In other words: if you want to write an entire page then start at the beginning of the page. If you don't and you write more than there is room left in the page you will wrap round back to the beginning of the page again.

So if you write two bytes starting with address 0x10FF you will actually write one at 0x10FF and the second at 0x1000, not 0x1100, since you wrap at the page boundary.

---
Tags: flash
---


title: Question About The Error In This Code

text:
# Question
Title: Question About The Error In This Code
Could someone point out what exactly I'm screwing up here and provide a specific solution. Here's the error message:

```
Arduino: 1.8.13 (Windows 10), Board: "Arduino Uno"

sketch_jul24g:38:11: error: expected ')' before '(' token
 (  pinMode(led, OUTPUT);     )
           ^

sketch_jul24g:38:30: error: expected unqualified-id before ')' token
 (  pinMode(led, OUTPUT);     )
                              ^

sketch_jul24g:39:1: error: expected declaration before '}' token
 }
 ^

exit status 1

expected ')' before '(' token

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

```

And here's the code:

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

// Which pin on the Arduino is connected to the NeoPixels?
#define PIN        6 // On Trinket or Gemma, suggest changing this to 1

// How many NeoPixels are attached to the Arduino?
#define NUMPIXELS 16 // Popular NeoPixel ring size

// When setting up the NeoPixel library, we tell it how many pixels,
// and which pin to use to send signals. Note that for older NeoPixel
// strips you might need to change the third parameter -- see the
// strandtest example for more information on possible values.
Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);

#define DELAYVAL 0 // Time (in milliseconds) to pause between pixels

// Pin 13 has an LED connected on most Arduino boards.
// give it a name:
int led = 13;

// the setup routine runs once when you press reset:
void setup() {
  // These lines are specifically to support the Adafruit Trinket 5V 16 MHz.
  // Any other board, you can remove this part (but no harm leaving it):
#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000)
  clock_prescale_set(clock_div_1);
#endif
  // END of Trinket-specific code.

  pixels.begin(); // INITIALIZE NeoPixel strip object (REQUIRED)
}

  // initialize the digital pin as an output.
(  pinMode(led, OUTPUT);     )
}

// the loop routine runs over and over again forever:
void loop() {
   pixels.clear(); // Set all pixel colors to 'off'

  // The first NeoPixel in a strand is #0, second is 1, all the way up
  // to the count of pixels minus one.
  for(int i=0; i<NUMPIXELS; i++) { // For each pixel...

    // pixels.Color() takes RGB values, from 0,0,0 up to 255,255,255
    // Here we're using a moderately bright green color:
    pixels.setPixelColor(i, pixels.Color(255, 255, 255));

    pixels.show();   // Send the updated pixel colors to the hardware.

    delay(DELAYVAL); // Pause before next pass through loop
  }
  pixels.setPixelColor(i, pixels.Color(255, 255, 255)); // turn the LED on (HIGH is the voltage level)
  delay(3);               // wait for a second
  pixels.setPixelColor(i, pixels.Color(0, 0, 0));    // turn the LED off by making the voltage LOW
  delay(8000);               // wait for a second
}

```

Like I said-what's going on? Thanks!

# Answer
> 1 votes
use `{ pinMode(led, OUTPUT); }` to create a new scope and if you don't need new scope just remove `(`, `)`

---
Tags: arduino-uno, c++, led
---


# Question
Title: Arduino - Playing WAV files with a buzzer
I have developed an Arduino program that plays a **WAV** file from the **SD** card using a **speaker**.

This is the circuit schematic

The sketch I'm using is based on **TMRpcm** library and **PWM** output

```
#include <TMRpcm.h>
#include <SD.h>
#include <SPI.h>
int sdpin=10;
TMRpcm tmrpcm;

void setup()
{
    Serial.begin(9600);
    pinMode(sdpin, OUTPUT);
    tmrpcm.speakerPin=9;
    tmrpcm.setVolume(3);
    SD.begin();
}

void loop()
{
    if(Serial.available()>0)
    {
        String data=Serial.readString();
        if(data=="pause")
        {
            if(tmrpcm.isPlaying()==1)
            {
                tmrpcm.pause();
            }
        }
        else if(data=="stop")
        {
            if(tmrpcm.isPlaying()==1)
            {
                tmrpcm.stopPlayback();
            }
        }
        else
        {
            String path="/Music/"+data;
            if(tmrpcm.isPlaying()==1)
            {
                tmrpcm.stopPlayback();
            }
            tmrpcm.play(path.c_str());
        }
    }
}

```

At first I could play the music with the speaker but then it stopped working and because I don't have enough skill to make one myself, I would like to know if I can use a **buzzer** for that.

I know that buzzers can be used to generate melody using the **tone()** function but I'm not sure if I can use them to play wav files using PWM output.

Any help will be appreciated.

# Answer
When driving a passive buzzer, you should always have the signal output from the Arduino go to a transistor tied between the ground and the (-) negative side of the buzzer. Also, if you use a regular NPN transistor, you should also have a small resistor between the Arduino and the transistor base.

The transistor is providing two functions; it's potentially amplifying the signal (if the (+) positive side of the buzzer is at a higher voltage than the Arduino) and it's also isolating (partially) that voltage from the Arduino. This helps save pins!

The resistor is to limit the current going through the transistor and helps keep both your Arduino and the transistor healthy. Voltage thrills, current kills and resistors limit current. If you use a MOSFET you want to change this from a low-ohm series resistor to a high-ohm pull-down resistor -- 4.75K or 10K is fine. A MOSFET is much higher impedance than an NPN transistor and should not be left floating.

Additionally, you want to add a diode between the (+) and (-) terminals on the buzzer. This may be the most important part of the circuit! When oscillating, the buzzer (whether magnetic or piezo) acts like an inductor and will accumulate a charge over time. This will be heard as a slowly diminishing volume from the buzzer. This charge will eventually overcome the protection diodes built into the GPIO pin (or any transistor) and destroy it! The diode blocks that charge loop and saves your chips.
> 3 votes

# Answer
There are different kinds of buzzers. The simplest one is just a piezoelectric transducer in a plastic casing. You can drive it directly by an arduino pin since its impedance is high. It will work fairly well for high frequencies, but don't expect any bass from it.

Another type of buzzer is a piezoelectric transducer connected to a simple oscillator circuit that will generate a waveform with a frequency typically between 1 and 4 kHz. This type of buzzer most likely won't work since the signal produced by your Arduino will be used to power the oscillator circuit rather than drive the piezoelectric transducer.

Please note that the pin you used to drive the speaker is possibly no longer operational. The impedance of the speaker was likely low enough to draw more current than what the pin of the microcontroller is rated for which probably caused damage to it. A non-piezoelectric speaker should never be connected to an Arduino without an amplifier in between.
> 1 votes

---
Tags: audio, buzzer, speaker
---


# Question
Title: Extra "zero" displayed on LCD when integer sent from PC to Arduino through serial port
Every time I send an integer from computer to Arduino an extra zero is displayed on the LCD connected to Arduino. I don't know the reason. Why?

Here is the code:

```
#include <LiquidCrystal.h>

int en = 2, rs = 3, d4 = 7, d5 = 6, d6 = 5, d7 = 4;
int a;
LiquidCrystal lcd(rs,en,d4,d5,d6,d7);

void setup() {
    Serial.begin(9600);
    lcd.begin(16,2);

}

void loop() {
    Serial.println("Enter a number");
    while(Serial.available()==0){}
    a=Serial.parseInt();
    lcd.print(a);
}

```

The result is as follows:

* Enter a number
* When I enter the number `1`
* The result `10` is displayed instead of `1`

# Answer
The `Serial.parseInt` returns zero when it can not find a number within a timeout. That timeout is default one second.
When a number is typed in the serial monitor, often a linefeed is added to it. That linefeed is read by `Serial.parseInt`. It can not make a number out of that and waits until the timeout and returns zero.

There is no way to tell if the `Serial.parseInt` returns zero because the number was zero, or if it returns zero because there was a timout.

You can try the next sketch to show the problem. Set the line ending in the serial monitor to linefeed or carriage return or both or nothing and see what happens.

```
int a;

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

void loop() {
  Serial.println("Enter a number");
  while(Serial.available()==0){}
  a=Serial.parseInt();   // it returns zero with a linefeed !
  Serial.println(a);
}

```

The easiest way to fix this, is to use a number that is only a single digit. The function `isdigit` is used to check the incoming characters.

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

  Serial.println("Enter a number (a single digit)");
}

void loop() {
  if (Serial.available() > 0) {
    int inChar = Serial.read();
    if (isdigit(inChar)) {
      int value = inChar - '0';
      Serial.println(value);
    }
  }
}

```

The `Serial.parseInt` is not completely useless, but the number zero can not be used. The next sketch ignores the input when `Serial.parseInt` returns zero.

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

  Serial.println("Enter a integer, but not zero, with a linefeed at the end");
}

void loop() {
  if (Serial.available() > 0) {
    int value = Serial.parseInt();
    if (value != 0) {
      Serial.println(value);
      Serial.println("Enter a integer, but not zero, with a linefeed at the end");
    }
  }
}

```

To be able to allow to type the number 0, the `Serial.parseInt` can no longer be used. To avoid waiting and delays, every character is immediately put into a buffer. The sketch becomes larger, but there is no other way. Either use `Serial.parseInt` or do it right.

```
#define BUFFER_SIZE 40
char buffer[BUFFER_SIZE];
int index;

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

  Serial.println("Enter a integer, with a linefeed at the end");
}

void loop() {
  if (Serial.available() > 0) {
    bool ready = false;

    int inChar = Serial.read();
    buffer[index] = (char) inChar;
    index++;
    if (index >= BUFFER_SIZE) {
      index = BUFFER_SIZE - 1;
      ready = true;
    }

    if (inChar == '\n' || inChar == '\r') {
      ready = true;
    }

    if (ready) {
      if (isdigit(buffer[0]) || buffer[0] == '-') {
        buffer[BUFFER_SIZE - 1] = '\0';
        int value = atoi(buffer);
        Serial.println(value);
        Serial.println("Enter a integer, with a linefeed at the end");
      }
      index = 0;
    }
  }
}

```
> 3 votes

# Answer
2 things:

1. use lcd.println() instead of lcd.print().
2. Once you open the serial monitor, set it to "No line ending" instead of "newline".

if you do step 1 but miss step 2 the 0 will print on the next line.
> 1 votes

---
Tags: lcd
---


title: Convert string to array

text:
# Question
Title: Convert string to array
I have a project and i need to convert string (contain numbers and letters) to array

```
String name = "s111, s222, bbbb,cccc ";

```

and i want

```
array[0] = s111;
array[1] = s222;
array[2] = bbbb;
array[3] = cccc;

```

here is the code :

```
 String name = "s111, s222, bbbb,cccc ";
 int array[50];
 int r=0,t=0;

 for(int i=0;i<name.length();i++){
      if(name.charAt(i) == ','){
          array[t] = name.substring(r,i);
          r = (i+1);
          t++;
         }
 for(int k=0 ;k<=t ;k++){
   Serial.println(array[k]);
  }

```

When I compile I get just zeros like :

```
array[0] = 0;
array[1] = 0;
array[2] = 0;
array[3] = 0;

```

# Answer
> 0 votes
When you declare `int array[50];` you declare an array of numbers so only numbers can be stored inside it. If you really want an array of strings then declare an array of strings like `String array[50];` There was also a a problem that sometime you split the `name` by comma, sometime by space, and sometime by comma+space. Also your code was missing closing bracket.

The algorithm has to split both by comma and my space and then take only values that have length more than one to avoid inserting empty strings.

```
String name = "s111, s222, bbbb,cccc ";
String array[50];
int r=0,t=0;

for(int i=0;i<name.length();i++)
{
  if(name[i] == ' ' || name[i] == ',')
  {
    if (i-r > 1)
    {
      array[t] = name.substring(r,i);
      t++;
    }
    r = (i+1);
  }
}

for(int k=0 ;k<=t ;k++)
{
  Serial.println(array[k]);
}

```

---
Tags: string
---


# Question
Title: What are the correct techniques for implementing functional client access to an asynchronous serial interface?
This is not a question for beginners.

I am implementing a functional interface to an asynchronous serial device connected to the Serial1 port on a mega.

To ensure clarity, I want to implement a series of functions thus:

```
    {param} CallInterface({param1},{param2},...) {
        sendRequestPacket();
        ....{await Response or timeout}....
        return Response;
     }

```

Obviously, when "awaiting Response" we are blocking the operational thread and have to allow an additional thread processor access in order to retrieve and parse the response.

On a multithreaded platform, this would be trivial to implement using semaphores and other multi-threading techniques, but on Arduino,AVR the solution is possibly less obvious, or not.

So, the question is, what is the best and most effective way to implement a pattern such as this on the Arduino platform?

# Answer
> 0 votes
The typical way I handle this kind of thing is to have one "master" function that controls everything using a finite state machine in a non-blocking way.

That function *could* contain all the logic to do things, or it could be simpler and just handle the basic communication and then pass details on to a callback function that is specified in the action function call.

So the flow could be:

1. You call a function that just sets up things:

* It stores details of the request to be made
* It records the address of a "callback" function

2. You execute your "run" function repeatedly from `loop()`

* It sends the command to the target
* It receives and parses the response storing it internally somewhere
* When the response is complete it executes the callback function passing it the response

Not all of 2 would happen each iteration of `loop()`, so write it in a non-blocking way (using `.available()` etc) and only call the callback when everything is complete.

So in that way you can set up a chain of things to happen:

1. You submit request 1 with callback A.
2. Callback A submits request 2 with callback B.
3. Callback B submits request 3 with callback C.

... etc ...

As an example this is how a modem control could look:

```
Modem.command("AT+CREG?", testRegistration);
>>> send         AT+CREG?
<<< store        +CREG: 0,2
<<< store
<<< identify     OK
--- Execute testRegistration(true, "+CREG: 0,2\n\n");

```

Or maybe if it goes wrong:

```
Modem.command("AT+CROG?", testRegistration); // Oops, made a typo...
>>> send         AT+CROG?
<<< identify     ERR
--- Execute testRegistration(false, "");

```

---
Tags: serial, arduino-mega
---


title: Better cycling through the RGB colors

text:
# Question
Title: Better cycling through the RGB colors
I have been trying to achieve a way to tap into the 16 million colors RGB provides for this LED strip. I thought of using `LEDS.setBrightness();` but I have not been successful in my attempts. I have read the documentation on color fading, but I have not been able to write this to my Arduino Leonardo. Here is my code below, which cycles through the initial rainbow of 0-255. I was wondering how to get more than 0-255 if not all the colors.

```
#include <FastLED.h>

#define LED_COUNT 60
#define LED_OUT       13
#define BUTTON_IN     10
#define ANALOG_INPUT  A9
#define EXTRA_PIN_A    7
#define EXTRA_PIN_B   11

struct CRGB leds[LED_COUNT];
int wait_time = 5;

void setup() {
  Serial.begin(57600);
  LEDS.addLeds<WS2812B, LED_OUT, GRB>(leds, LED_COUNT);
  LEDS.show();
}

void loop() {
  //start from red
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = 255;
    int g = 0;
    int b = colorStep;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }

  //into blue
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = colorStep;
    int g = 0;
    int b = 255;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //start from blue
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = 0;
    int g = colorStep;
    int b = 255;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //into green
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = 0;
    int g = 255;
    int b = colorStep;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //start from green
  for(int colorStep=0; colorStep <= 255; colorStep++) {
    int r = colorStep;
    int g = 255;
    int b = 0;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
  //into yellow
  for(int colorStep=255; colorStep >= 0; colorStep--) {
    int r = 255;
    int g = colorStep;
    int b = 0;
    // Now loop though each of the LEDs and set each one to the current color
    for(int x = 0; x < LED_COUNT; x++) {
      leds[x] = CRGB(r,g,b);
    }
    // Display the colors we just set on the actual LEDs
    delay(wait_time);
    LEDS.show();
  }
} //end main loop

```

# Answer
I think it's worth noting that the three 255 values for RGB colour space is just one way to encode the 255^3 (16,581,375) colours. These include each and every brightness level too.

If you are trying to get a rainbow effect, you may have more success or find it easier to use a HSL or HSV colour space.

HSV uses Hue, Saturation and Value instead of RGB. FastLED has optimized it's implementation of HSV to use a 0-255 addressing for Hue (instead of 360), keeping it fast for animations run on microcontrollers:

https://github.com/FastLED/FastLED/wiki/FastLED-HSV-Colors
> 2 votes

# Answer
I've included a simple sketch that will cycle a single RGB led using the sine fade technique

```
// Cycle a single RGB led using the sine fade technique
// For common cathode led

const uint8_t lights[360]={
  0, 0, 0, 0, 0, 1, 1, 2, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 15, 17, 18, 20, 22, 24, 26, 28, 30, 32, 35, 37, 39,
 42, 44, 47, 49, 52, 55, 58, 60, 63, 66, 69, 72, 75, 78, 81, 85, 88, 91, 94, 97, 101, 104, 107, 111, 114, 117, 121, 124, 127, 131, 134, 137,
141, 144, 147, 150, 154, 157, 160, 163, 167, 170, 173, 176, 179, 182, 185, 188, 191, 194, 197, 200, 202, 205, 208, 210, 213, 215, 217, 220, 222, 224, 226, 229,
231, 232, 234, 236, 238, 239, 241, 242, 244, 245, 246, 248, 249, 250, 251, 251, 252, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255, 254, 254, 253, 253,
252, 251, 251, 250, 249, 248, 246, 245, 244, 242, 241, 239, 238, 236, 234, 232, 231, 229, 226, 224, 222, 220, 217, 215, 213, 210, 208, 205, 202, 200, 197, 194,
191, 188, 185, 182, 179, 176, 173, 170, 167, 163, 160, 157, 154, 150, 147, 144, 141, 137, 134, 131, 127, 124, 121, 117, 114, 111, 107, 104, 101, 97, 94, 91,
 88, 85, 81, 78, 75, 72, 69, 66, 63, 60, 58, 55, 52, 49, 47, 44, 42, 39, 37, 35, 32, 30, 28, 26, 24, 22, 20, 18, 17, 15, 13, 12,
 11, 9, 8, 7, 6, 5, 4, 3, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};

const byte redpin = 3;
const byte greenpin = 5;
const byte bluepin = 6;
int loopdelay = 5000; // ms
int displaylength = 50; // ms

boolean showiterations = false;

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

void loop() {
for (int k=0; k<360; k++)
{
    if (showiterations) {
    Serial.print(k);
    Serial.print(F(","));
    }
analogWrite(redpin, lights[(k+120)%360]);
analogWrite(greenpin, lights[k]);
analogWrite(bluepin, lights[(k+240)%360]);
delay(displaylength);
}
if (showiterations) {
Serial.println("  ");
}
delay(loopdelay);
}

```

This sketch is derived from an Instructables posting entitled "How to Make Proper Rainbow and Random Colors With the RGB Color Model", http://www.instructables.com/id/How-to-Make-Proper-Rainbow-and-Random-Colors-With-/
It additionally provides information and rationale behind different techniques for cycling colours.

---

If you are trying to stagger the colours along the strip whilst creating a rainbow effect, I have another sketch \[from Adafruit, I believe\] that will do this. I've used it effectively with different Neopixel ring configurations. The sketch demonstrates a number of different techniques. I have currently commented out the invocations of all but the theaterChaseRainbow, but you may wish to explore them all.

```
#include <Adafruit_NeoPixel.h>
// following atatement should be wrapped with an ifdef for __AVR__, but this facility botches it up.
// As it is, formatting for the sketch is not quite right, and I do not have a solution for that.
  #include <avr/power.h>

const  byte PIN = 7;

// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
//   NEO_KHZ800  800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
//   NEO_KHZ400  400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
//   NEO_GRB     Pixels are wired for GRB bitstream (most NeoPixel products)
//   NEO_RGB     Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
//   NEO_RGBW    Pixels are wired for RGBW bitstream (NeoPixel RGBW products)
// Adafruit_NeoPixel strip = Adafruit_NeoPixel(60, PIN, NEO_GRB + NEO_KHZ800)`
Adafruit_NeoPixel strip = Adafruit_NeoPixel(16, 6, NEO_GRB + NEO_KHZ800);

// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel.  Avoid connecting
// on a live circuit...if you must, connect GND first.

void setup() {
  // This is for Trinket 5V 16MHz, you can remove these three lines if you are not using a Trinket
  #if defined (__AVR_ATtiny85__)
    if (F_CPU == 16000000) clock_prescale_set(clock_div_1);
  #endif
  // End of trinket special code

  strip.begin();
   colorWipe(strip.Color(0, 0, 0), 50); // blank
  strip.show(); // Initialize all pixels to 'off'
}

void loop() {
  // Some example procedures showing how to display to the pixels:
//  colorWipe(strip.Color(255, 0, 0), 50); // Red
//  colorWipe(strip.Color(0, 255, 0), 50); // Green
//  colorWipe(strip.Color(0, 0, 255), 50); // Blue
//colorWipe(strip.Color(0, 0, 0, 255), 50); // White RGBW
  // Send a theater pixel chase in...
//  theaterChase(strip.Color(127, 127, 127), 50); // White
//  theaterChase(strip.Color(127, 0, 0), 50); // Red
//  theaterChase(strip.Color(0, 0, 127), 50); // Blue

//  rainbow(20);
//  delay(50000);
//  colorWipe(strip.Color(0, 0, 0), 50); // blank
//  rainbowCycle(10);
//  delay(5000);
//    colorWipe(strip.Color(0, 0, 0), 50); // blank
//   delay(5000);
  theaterChaseRainbow(50);
//  delay(5000);
//    colorWipe(strip.Color(0, 0, 0), 50); // blank
//   delay(5000);
}

// Fill the dots one after the other with a color
void colorWipe(uint32_t c, uint8_t wait) {
  for(uint16_t i=0; i<strip.numPixels(); i++) {
    strip.setPixelColor(i, c);
    strip.show();
    delay(wait);
  }
}

void rainbow(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256; j++) {
    for(i=0; i<strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel((i+j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

// Slightly different, this makes the rainbow equally distributed throughout
void rainbowCycle(uint8_t wait) {
  uint16_t i, j;

  for(j=0; j<256*5; j++) { // 5 cycles of all colors on wheel
    for(i=0; i< strip.numPixels(); i++) {
      strip.setPixelColor(i, Wheel(((i * 256 / strip.numPixels()) + j) & 255));
    }
    strip.show();
    delay(wait);
  }
}

//Theatre-style crawling lights.
void theaterChase(uint32_t c, uint8_t wait) {
  for (int j=0; j<10; j++) {  //do 10 cycles of chasing
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, c);    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

//Theatre-style crawling lights with rainbow effect
void theaterChaseRainbow(uint8_t wait) {
  for (int j=0; j < 256; j++) {     // cycle all 256 colors in the wheel
    for (int q=0; q < 3; q++) {
      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, Wheel( (i+j) % 255));    //turn every third pixel on
      }
      strip.show();

      delay(wait);

      for (uint16_t i=0; i < strip.numPixels(); i=i+3) {
        strip.setPixelColor(i+q, 0);        //turn every third pixel off
      }
    }
  }
}

// Input a value 0 to 255 to get a color value.
// The colours are a transition r - g - b - back to r.
uint32_t Wheel(byte WheelPos) {
  WheelPos = 255 - WheelPos;
  if(WheelPos < 85) {
    return strip.Color(255 - WheelPos * 3, 0, WheelPos * 3);
  }
  if(WheelPos < 170) {
    WheelPos -= 85;
    return strip.Color(0, WheelPos * 3, 255 - WheelPos * 3);
  }
  WheelPos -= 170;
  return strip.Color(WheelPos * 3, 255 - WheelPos * 3, 0);
}

```
> 1 votes

# Answer
You can make a smooth transition/sliding rainbow effect by using a sine wave lookup table, then phase shifting green and blue by 120 and 240 degrees.

```
#define RED 9
#define GREEN 10
#define BLUE 11

uint8_t sins[360] = {
  127,129,131,134,136,138,140,143,145,147,149,151,154,156,158,160,162,164,166,169,171,173,175,177,179,181,183,185,187,189,191,193,195,196,198,200,
  202,204,205,207,209,211,212,214,216,217,219,220,222,223,225,226,227,229,230,231,233,234,235,236,237,239,240,241,242,243,243,244,245,246,247,248,
  248,249,250,250,251,251,252,252,253,253,253,254,254,254,254,254,254,254,255,254,254,254,254,254,254,254,253,253,253,252,252,251,251,250,250,249,
  248,248,247,246,245,244,243,243,242,241,240,239,237,236,235,234,233,231,230,229,227,226,225,223,222,220,219,217,216,214,212,211,209,207,205,204,
  202,200,198,196,195,193,191,189,187,185,183,181,179,177,175,173,171,169,166,164,162,160,158,156,154,151,149,147,145,143,140,138,136,134,131,129,
  127,125,123,120,118,116,114,111,109,107,105,103,100,98,96,94,92,90,88,85,83,81,79,77,75,73,71,69,67,65,63,61,59,58,56,54,
  52,50,49,47,45,43,42,40,38,37,35,34,32,31,29,28,27,25,24,23,21,20,19,18,17,15,14,13,12,11,11,10,9,8,7,6,
  6,5,4,4,3,3,2,2,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,2,2,3,3,4,4,5,
  6,6,7,8,9,10,11,11,12,13,14,15,17,18,19,20,21,23,24,25,27,28,29,31,32,34,35,37,38,40,42,43,45,47,49,50,
  52,54,56,58,59,61,63,65,67,69,71,73,75,77,79,81,83,85,88,90,92,94,96,98,100,103,105,107,109,111,114,116,118,120,123,125
};

void setup() {
  pinMode(RED, OUTPUT);
  pinMode(GREEN, OUTPUT);
  pinMode(BLUE, OUTPUT);
}

void loop() {
  for (int i = 0; i < 360; ++i)
  {
    analogWrite(RED, sins[i]);
    analogWrite(GREEN, sins[(i+120)%360]);
    analogWrite(BLUE, sins[(i+240)%360]);
    delay(2);
  }
}

```
> 1 votes

# Answer
If you want to display every one of the about 16 million possible colours, you will have to nest your for loops like in this example:

```
x = 1 ;  // only for testing
for ( int redx = 0 ; redx <= 255 ; redx ++ ) {
    for ( int greenx = 0 ; greenx <= 255 ; greenx ++ ) {
        for ( int bluex = 0 ; bluex <= 255 ; bluex ++ ) {
             leds[ x ] = CRGB(redx,greenx,bluex);
             delay(wait_time);
             LEDS.show();
        }
    }
}

```
> 0 votes

# Answer
You should consider making it non-blocking :)

```
loop(){
   //if(millis() > previous+100){//uncomment this part to only do a step of the rainbow effect every 100ms
   rainbowEffect();
   //previous = millis();
   //}

   //you can do other stuff, like check a buttons' state here.
   //using the same structure as above, you can choose to give it a higher or lower priority.
}

unsigned char r,g,b;
void rainbowEffect(){
   if(r>254){
      r=0;
      g++;
   }
   if(g>254){
      g=0;
      b++;
   }
   if(b>254){
      b=0;
   }
   r++;
   ledStrip.set(r,g,b);
}

```
> 0 votes

# Answer
I think @Mazaryk was correct, HSV is the way to go for this. RGB's 16+ million colors include brightness, and some of them just won't display on the strip, so I found a way to at least better fade thru:

```
int thissat = 255;           //- LOOPS DELAY VAR
int idex = 0;                //-LED INDEX
int ihue = 0;                //-hue (0-255)

void rainbow_fade() {
    ihue++;
    if (ihue > 255) {ihue = 0;}
    for(int idex = 0 ; idex < LED_COUNT; idex++ ) {
      leds[idex] = CHSV(ihue, thissat, 255);
    }
    LEDS.show();
    delay(wait_time);
}

```
> 0 votes

# Answer
You could take advantage that the rgb color could be represented in a unsigned long. And use a counter. But have patience looping through 16 mio colors with 1ms at iteration take some time :-). (around 4-5 hours: 16581375/(1000\[ms\] * 60\[m\] * 60\[h\]) = 4,6 )

```
void loopThrougAllColors(){
  // The trick here is to use a unsigned long value as the color representation.
  // Each byte represent a color (except the first)
  //          none, R  G  B
  //          0x00 00 00 00
  // Note: static means it is a global variable - but only seen in thisfunction.
  static unsigned long ledColor = 0;
  static int ledIndex = 0;

  ledColor++;
  ledColor &= 0x00FFFFFF; /* Overflow preventing (instead of if sentence checking the boundaries). */

  leds[0] = ledColor;

  FastLED.show();
  FastLED.delay(1);
  //delay(10);
}

```
> 0 votes

---
Tags: c++, arduino-ide, led, arduino-leonardo, rgb-led
---


# Question
Title: avrdude: stk500_recv(): programmer is not responding, arduino pro
I'm trying to upload a sketch to upload the blink sketch to an arduino pro using a SparkFun Serial Basic Breakout (on Ubuntu 18.04).

## setup

Within the arduino IDE I have the following set-up:

* Tools -\> Board: *Arduino Pro or Pro mini*
* Tools -\> Port: */dev/ttyUSB0*
* Tools -\> Programmer: *USBasp*

I have connected:

* DTR sparkfun to DTR on arduino
* RX1 sparkfun to RX1 on arduino
* TX0 sparkfun to TX0 on arduino
* VCC sparkfun to VCC on arduino
* GND sparkfun to GND on arduino

## the error

The error that I get is as follows

```
Arduino: 1.8.13 (Linux), Board: "Arduino Pro or Pro Mini, ATmega328P (5V, 16 MHz)"

Sketch uses 924 bytes (3%) of program storage space. Maximum is 30720 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2039 bytes for local variables. Maximum is 2048 bytes.
/home/cmhughes/Desktop/arduino-1.8.13/hardware/tools/avr/bin/avrdude -C/home/cmhughes/Desktop/arduino-1.8.13/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/ttyUSB0 -b57600 -D -Uflash:w:/tmp/arduino_build_457079/cmh-Blink.ino.hex:i

avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "/home/cmhughes/Desktop/arduino-1.8.13/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/cmhughes/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyUSB0
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
...

```

The error message continues, and tries 10 attempts.

## the question

I've tried many different things, including: changing the RX1 to TX0 connections, using a different FTDI serial adapter, trying a different USB cable, trying on Windows operating system.

What else can I try to see if I can progress this?

## arduino pro

## SparkFun Serial Basic Breakout - CH340C and USB-C

# Answer
The upload procedure needs to reset the ATmega328 by use of DTR. This invokes the bootloader code in the ATmega328. If there is a problem with your DTR connection, you have to instead manually press the RESET button at the appropriate time.

So probably your connection to DTR was faulty or. less likely, there could be a fault in the onboard capacitor between the Pro-Mini's "DTR" header and the ATmega328 RESET pin

https://store.arduino.cc/arduino-pro-mini -\> Documentation

> **Automatic (Software) Reset**
> Rather then requiring a physical press of the reset button before an upload, the Arduino Pro Mini is designed in a way that allows it to be reset by software running on a connected computer. One of the pins on the six-pin header is connected to the reset line of the ATmega328P **via a 100 nF capacitor**. This pin connects to one of the hardware flow control lines of the USB-to-serial convertor connected to the header: RTS when using an FTDI cable, DTR when using the Sparkfun breakout board. When this line is asserted (taken low), the reset line drops long enough to reset the chip. The Arduino software uses this capability to allow you to upload code by simply pressing the upload button in the Arduino environment. This means that the bootloader can have a shorter timeout, as the lowering of the reset line can be well-coordinated with the start of the upload.
> 2 votes

# Answer
Might have to do with the usb chip on that being not as widely supported as the official chip Arduinos use on their Uno’s, Mega’s, etc. the ch340C one sometimes needs drivers so look online for those drivers and download them.
> 0 votes

---
Tags: serial, arduino-pro-mini
---


# Question
Title: What is the name of this chip on Arduino Mega ? I am not finding its datasheet 56 TI MSP?
What is the using purpose of this chip?

# Answer
> 3 votes
There is only one 8-pin SMD IC on the top side of the Arduino Mega 2560.

From the schematic it appears to be the "LMV358IDGKR" a TI dual op-amp used for two separate functions on the Mega.

* Selecting power source - VIN vs USB.
* Illuminating the built-in "L" LED (on D13) without loading PB7

---
Tags: arduino-mega
---


# Question
Title: Use callbacks in Arduino with pointers to functions (will functions persist in memory?)
As I been learning Arduino (micro controllers, c++, etc) I have learned that memory is very limited. I already understand how memory works when it comes to variables. But I do not understand how memory works when it comes to functions. Since I am a backed developer I try to stay away from interrupts and instead use callback functions. Another reason why I prefer to use callback functions is because I love the visual studio IDE. I create my core functionality of whatever project I am building on a c++ project targeted for Windows. Once my algorithms/logic works the way I want it I reference those libraries on Arduino.

Anyways I am using lambdas to pass functions to my helper libraries. That way I do not use the delay function to wait for a response and I am always listening for events. **Basically my question is if it is correct to have code like this (function SendEvent):**

```
/* MyRadioLibrary.h */
// I am not including all the code of `MyRadioLibrary` because that makes it hard to
// understand what I am asking. Instead I will try to use a lot of pseudo-code. Let me
// know if you want me to post the code as an edit.

class MyRadioLibrary
{

public:

    static void SendEvent(int typeOfEvent, void(*onEventCompleted)(bool x))
    {
        // I have an array of pointers to functions
        void(*onEventCompletedBuffer[10])(bool x);

        // I enqueue that event with a queue helper class

        // Send event ....

        // DO NOW WAIT FOR RESPONSE SINCE CALL BACK IS ALREADY SAVED
    }

    static void loop() {

         // listen for radio messages
         if(radio.available()){
                // get response
                // dequeue pointer to call back
                // execute call back
          }

    }
};

```

And my arduino sketch contains this code:

```
#include <MyRadioLibrary.h>

void setup()  {
    // setup pins etc..
}

void loop()
{

    if (isButton1Pressed())
    {
        MyRadioLibrary::SendEvent(1, [](bool didEventCompletedSuccessfully) {

            if (didEventCompletedSuccessfully)
            {
                // turn on green LED
            }
            else {

                // turn on red led
            }

        });
    }
    else if (isButton2Pressed())
    {
        MyRadioLibrary::SendEvent(2, [](bool didEventCompletedSuccessfully) {

             // call back function

        });
    }

    MyRadioLibrary::loop(); // listen for response events. When we get one fire call back.
}

```

## Now the question

When I call the `SendEvent` function I am passing 2 things (1) an integer and (2) a pointer to a function that is the call back. The integer (1) is passed as value and that will be part of the stack of the `SendEvent` function. The pointer (2) will be stored on an array of pointers. **But what about the lambda function?** where will that be stored? Instead of using a lambda function should I declare those functions in global scope and pass the global function instead of a lambda? **Will I run the risk of the pointer (2) pointing to a function that no longer exists if I use this way of coding?**

# Answer
> 2 votes
Your functions won't cease to exist. All of the code in your compiled and linked code image gets loaded into code-memory (Flash) and it stays there throughout the run, through resets, and through power-cycles, until another image is loaded over it.

Are you confusing pointers to functions with pointers to a function's local variables which occupy RAM memory, specifically within the function's stack-frame which *is* transient, being created and "destroyed" as the function gets called and returns - and successive stack-frames won't necessarily be created in the same place.

---
Tags: c++, callbacks, lambda
---


title: can i convert a pin into ground

text:
# Question
Title: can i convert a pin into ground
i recently started using Arduino uno , but to my despair , the ground pin , without which i cant do any project (or can i ) , so i thought of a possible solution , what if i could program the board to make a pin act as a ground , so what to do straight 2 questions , what to do to convert any pin into ground or can i ignore using the provided ground pin . i have already tried fixing the pin but it cant be fixed because a detached pin has got stuck into it

# Answer
> 1 votes
> **Can I convert any pin into ground**

Any of the digital outputs can be set LOW but there is a limit on how much current they can sink,

This makes this approach unsuitable for most use cases other than charlieplexing LEDs and similar low-current applications.

It would be better to

* use any of the other ground connections.
    + two between `Vin` and `5V`
    + one between `Aref` and `13`
    + one on the 2x3-pin `ICSP` header for the 328
    + one on the unlabelled 2x3-pin ICSP header for the 16U2
    + one in the power jack
* replace the damaged header using solder-wick and a soldering-iron.
* solder a wire from a suitable ground pad on the PCB
    + e.g. from the ground pad for the 2.1mm power connector.

---

The ATmega328P data sheet says

> Although each I/O port can sink more than the test conditions (20mA at VCC = 5V, 10mA at VCC = 3V) under steady state conditions (non-transient), the following must be observed:
> ATmega328P:
> 1\] The sum of all IOL, for ports C0 - C5, should not exceed 100mA.
> 2\] The sum of all IOL, for ports B0 - B5, D5 - D7, XTAL1, XTAL2 should not exceed 100mA.
> 3\] The sum of all IOL, for ports D0 - D4, should not exceed 100mA.
> If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition

So no more than 20mA from or into any single pin over a long time. And no more than a total of 100 mA from or into a group of pins.

---
Tags: arduino-uno, pins
---


# Question
Title: Can it time between blips, store the time between blips, subtract one time from the other and divide one time by another and display it?
I am counting rotations of a shaft and timing events that occur during that rotation. I wish to display the event timing as a percentage of ~1/4 of the rotation timing. This would involve recording the rotation time, dividing that number by 3.6 and dividing that number by the value of the event timer, then displaying that percentage on an LCD array.

# Answer
> 1 votes
What you are looking for is the millis() function. It returns the time that passed in milliseconds since the board power up.

With this function you can find the time delta, and achieve all the described calculations.

For more information

---
Tags: timers, display
---


# Question
Title: How can I burn the bootloader onto atmega328 (not atmega328p)?
Hi I bought some atmega328 chips (not to be confused with atmega328p). They are very similar but the atmega328p chips are just more power efficient, so I've read. Anyways, my goal is to burn the arduino bootloader onto these chips so that I can make some breadboard arduinos. I used the arduino ISP sketch and hooked up everything like so -\>

I was following instructions from the following link -\>

https://www.arduino.cc/en/Tutorial/ArduinoToBreadboard

However, when I press the Burn Bootloader button under Tools, it keeps telling me that it can't verify that my chip is an atmega328p. Well it is not atmega328p but everywhere online says it does not matter since they are the same architecture. The error also tells me that I can override by typing -F, but it doesn't tell me where to input this. I'm pretty sure that may fix the issue, but I am not sure where I'm supposed to put the -F.

Also I saw another post that was similar to this one but the answer said that the problem is the atmega328 chip itself. Is it even possible to add the bootloader to these chips??? Other sources said it is, but I can't seem to do it.

# Answer
> **How can I burn the bootloader onto ATmega328 (not ATmega328*P*)?**

As Juarj commented, For a variety of standalone AVR microcontrollers you can add new "cores" to the Arduino IDE using it's board manager.

This provides the Arduino IDE with information about your specific chip and this means the IDE can instruct the `avrdude` program appropriately and select a bootloader image that was written to support your specific chip

The Minicore documentation says it supports all variants of ATmega328

Other well-known examples of cores for bare AVR microcontroller chips include ATtinycore which supports a wide range of ATtiny microcontroller chips like the popular ATtiny85.
> 0 votes

---
Tags: atmega328, bootloader, arduinoisp
---


title: How can I stop my Servo rotating?

text:
# Question
Title: How can I stop my Servo rotating?
I have a continuous servo motor connected to my Arduino UNO. I want it to react to the Hexadecimal code received by an Infrared remote. I want the motor to rotate once in one direction and then rotate once in the reverse direction and then stop until triggered by the remote again. At the moment, the remote will cause the the motor to rotate once in one way but then it rotates continuously in the reverse direction. Any help would be much appreciated!

```
#include "IRremote.h"
#include <Servo.h>

int receiver = 11; // Signal Pin of IR receiver to Arduino Digital Pin 11

Servo servoMain;
IRrecv irrecv(receiver);
decode_results results;

void setup()
{
  Serial.begin(9600);
  Serial.println("IR Receiver Button Decode");
  irrecv.enableIRIn(); // Start the receiver
  servoMain.attach(10);
}

void loop()
{
  if (irrecv.decode(&results)) // have we received an IR signal?

  {
    translateIR();
    irrecv.resume(); // receive the next value
  }
}

void translateIR() // takes action based on IR code received

// describing Remote IR codes
{

  switch (results.value)

  {

    case 551520375: servoMain.write(180); delay(1000); servoMain.write(0);     delay(1000); break;
    default: break;

  }

  delay(500); // Do not get immediate repeat

} //END translateIR

```

# Answer
Unlike a normal servo motor where the argument of the Arduino's servo.write(angle) method represents a position, a continuous servo motor uses the argument for speed and direction. Most continuous servo motors interpret stop to be approximately 90 degrees. Full, say, reverse as 0 degrees. And full, say, forward as 180 degrees. As stated in the above link:

> On a continuous rotation servo, this will set the speed of the servo (with 0 being full-speed in one direction, 180 being full speed in the other, and a value near 90 being no movement).

Also of interest, most continuous servo motors have an adjustment to set the "90 degree position" (full stop). That is to say, servo motor control signals are analog, not digital! It follows that the processor's interpretation of the "90 degree position" may not be the same as the servos' interpretation of the "90 degree position". Hence the ability to adjust the servos' interpretation.

This picture from the parallax servo tutorials web site shows how this is done:
> 2 votes

# Answer
I am posting that may help others in future. I have MG996R Servo Motors, this motor when I opened and inside I didn't find LOCK at main wheel and I assume its 360 degree.

I have similar problem that while testing Robotic Arm, my motor was loosing position and it was rotating 360 degree. I tried all sort of remedies but didn't find the solution.

MY SOLUTION: Connect your Servo with external power 5v supply, even connecting 5V to arduino board with round pin does not solve. once I connected with external power with 5V power my issue was solved and motors were retaining position
> 1 votes

---
Tags: motor, ir, remote-control, continuous-servo
---


# Question
Title: String(int) function stopping the Arduino
Well I am trying make an application with arduino leonardo and GSM Shield. There are conditions if, else if, else .. etc

```
  if (smsMetni.indexOf("DURUM") != -1) {
    Serial.println("SMS income");
    String temp= String(analogRead(LM35_pin) * 0.48828125);
    String temp2 = "Hava " + temp + " derece.";
    char tempSMS2[] = "";
    temp2.toCharArray(tempSMS2, 30);
    Serial.println(tempSMS2);
    Kapadokya.smsGonder(gonderilecekTelNumarasi, tempSMS2);
  }

```

After the last line "*Kapadokya.smsGonder(gonderilecekTelNumarasi, tempSMS2);*" program stopping I watching serial monitor there is no notification or error. just stopping.

If I change those lines and remove **String(analogRead(LM35\_pin) * 0.48828125)** :

```
    String temp= String(analogRead(LM35_pin) * 0.48828125);
    String temp2 = "Hava " + temp + " derece.";

```

and just write like this, it works very well.

```
String temp2 = "Hava  derece.";

```

maybe you think there is a problem with LM35, even if I change it **String(analogRead(LM35\_pin) * 0.48828125);** with **String(30);**, it doesn't work again. after the last line it is not continue.

only one sollution I've found if add **delay(500)** after each line it works but my codes looks ugly with this. are there any solution.

# Answer
You should avoid String on the Arduino. It will cause random crashes. However that's not your issue. Your issue is trying to copy the data into an array that is too small.

```
char tempSMS2[] = "";

```

That creates a one byte array which contains just a `\0`. You then try and squeeze your String data into it and it of course overflows all over the rest of your variables and data.

A better solution is to work directly in char arrays. It is a little trickier though:

First convert your float to a string:

```
char tempFloat[8];
dtostrf(analogRead(LM35_pin) * 0.48828125, -7, 3, tempFloat);

```

Then build up your string:

```
char tempSMS2[30];
strcpy_P(tempSMS2, PSTR("Hava "));
strcat(tempSMS2, tempFloat);
strcat_P(tempSMS2, PSTR(" derece."));

```
> 2 votes

---
Tags: arduino-uno, arduino-leonardo, string, sram
---


# Question
Title: Is it bad to power a arduino mega with 6V via USB?
I'm working on a project where there is no external 5V voltage regulator available but only 6V. I can not power it through the power jack because via this way I do not have enough current and get thermal shutdown.

Can I power it via 6V over USB? at the moment I'm trying this out and it works but what are the long term risks I'm prone to?

# Answer
> 1 votes
The Absolute Maximum Operating Voltage of the ATMega2560 is 6.0V. The same applies to the ATMega8u2 that does the USB to Serial on the Arduino Mega board.

Recommended maximum voltage is 5.5V

So yes, you can run it at 6 Volts, but you are right on the edge, so **I wouldn't recommend it**.

Possible risks are a decreased lifespan of the Arduino, and there might be some stability issues.

If the application isn't safety critical, and you don't mind having to replace the board after it failed in, say, two year of operation, it could be an acceptable risk (if there are no easily available alternatives)

PS you might want to measure you power supply. It may say it's 6V but could give out 6.2V. The output voltage of some supplies also vary with the load that's across it.

# Answer
> 0 votes
> **Is it bad to power a arduino mega with 6V via USB?**

Yes, the Arduino Mega is not designed to be powered that way and you are probably abusing the USB specifications. USB can supply higher voltages than 5V but only if it is properly negotiated with the device.

The schematics (see Documentation tab) show a 5V regulator powered from the 2.1 mm Power-connector or from the "Vin" header pin. If the regulator specs say it can work from 6V, you should probably use that instead. However although the 1870\_LD1117S50CTR seems to be a low-dropout (LDO) regulator, it has a dropout voltage of 1V. So I wouldn't power it from a 6V source - that seems equally marginal.

In short, I think you really need to find a more suitable power source.

---
Tags: arduino-mega, usb, current, voltage
---


title: Load website from SD card

text:
# Question
Title: Load website from SD card
I combined two different codes together, a captive portal and a SD card web server. I encountered a problem which the website in the SD card doesn't load when I connect to the AP (captive portal page). Here's the code..

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include "./DNSServer.h"
#include <SPI.h>
#include <SD.h>

const byte        DNS_PORT = 53;          // Capture DNS requests on port 53
IPAddress         apIP(10, 10, 10, 1);    // Private network for server
DNSServer         dnsServer;              // Create the DNS object
ESP8266WebServer server(80);
String responseHTML = ""
                      "<html><head><title>Captive Portal Test</title>"
                      "<style>html,body{margin:0;height:100%;overflow:hidden;}"
                      "img{ min-height:100%; min-width:100%;height:auto;width:auto;"
                      "position:absolute;top:-100%; bottom:-100%;left:-100%; right:-100%;"
                      "margin:auto;}</style></head><body><img src='test.png' /><h1>TEST</h1></body></html>";

static bool hasSD = false;
File uploadFile;

void returnOK() {
  server.send(200, "text/plain", "");
}

void returnFail(String msg) {
  server.send(500, "text/plain", msg + "\r\n");
}

bool loadFromSdCard(String path) {
  String dataType = "text/plain";
  if (path.endsWith("/")) path += "index.htm";
  if (path.endsWith(".src")) path = path.substring(0, path.lastIndexOf("."));
  else if (path.endsWith(".htm")) dataType = "text/html";
  else if (path.endsWith(".css")) dataType = "text/css";
  else if (path.endsWith(".js")) dataType = "application/javascript";
  else if (path.endsWith(".png")) dataType = "image/png";
  else if (path.endsWith(".gif")) dataType = "image/gif";
  else if (path.endsWith(".jpg")) dataType = "image/jpeg";
  else if (path.endsWith(".ico")) dataType = "image/x-icon";
  else if (path.endsWith(".xml")) dataType = "text/xml";
  else if (path.endsWith(".pdf")) dataType = "application/pdf";
  else if (path.endsWith(".zip")) dataType = "application/zip";

  File dataFile = SD.open(path.c_str());
  if (dataFile.isDirectory()) {
    path += "/index.htm";
    dataType = "text/html";
    dataFile = SD.open(path.c_str());
  }

  if (!dataFile)
    return false;

  if (server.hasArg("download")) dataType = "application/octet-stream";

  if (server.streamFile(dataFile, dataType) != dataFile.size()) {
  }

  dataFile.close();
  return true;
}

void handleNotFound() {
  if (hasSD && loadFromSdCard(server.uri())) return;
  String message = "SDCARD Not Detected\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";
  for (uint8_t i = 0; i < server.args(); i++) {
    message += " NAME:" + server.argName(i) + "\n VALUE:" + server.arg(i) + "\n";
  }
  server.send(404, "text/plain", message);
}

void setup(void) {
  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0));
  WiFi.softAP("TEST AP");
  dnsServer.start(DNS_PORT, "*", apIP);
  //PROBLEM HERE/
  server.onNotFound([]() {
  server.send(200, "text/html", responseHTML);
  });

  server.begin();

  if (SD.begin(SS)) {
    hasSD = true;
  }
}

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

```

This code replies the `responseHTML` as a Captive portal page which immediately pop-ups when I connect to the AP:

```
server.onNotFound([]() {
      server.send(200, "text/html", responseHTML);
      });

```

The `void handleNotFound()` handles the page/file request from the browser but if I use it on

```
server.onNotFound(handleNotFound);

```

The captive portal won't show but if I type the server address `10.10.10.1`, the page will appear. What seems to be the problem?

# Answer
Remove `hasSD &&` from `void handleNotFound()` function.

It worked for me.
> 1 votes

---
Tags: esp8266, spi, sd-card, web-server
---


title: Is this circuit properly made?

text:
# Question
Title: Is this circuit properly made?
I can't get to work a circuit that doesn't look that hard to copy.

This circuit was done for an Arduino extension of my DSC HS2032 system. I was trying the example "Status" on the Arduino's library DSC Keybus Interface v1.2.0.

On the example, we can see this circuit:

```
 *      DSC Aux(+) --- Arduino Vin pin
 *
 *      DSC Aux(-) --- Arduino Ground
 *
 *                                         +--- dscClockPin (Arduino Uno: 2,3)
 *      DSC Yellow --- 15k ohm resistor ---|
 *                                         +--- 10k ohm resistor --- Ground
 *
 *                                         +--- dscReadPin (Arduino Uno: 2-12)
 *      DSC Green ---- 15k ohm resistor ---|
 *                                         +--- 10k ohm resistor --- Ground

```

Here on the photos, I'm showing what I have done.

This is the HS2032 panel where (on the YEL and GRN) I connect the Arduino. I changed the Arduino's power source to be from my laptop so I could easily test it on the Serial Monitor. YEL-\>White/Green wire and GRN-\>Green wire

Now goes the Arduino's wiring.

Remember from the panel, the yellow is the white/green and the green is the green (they are coming from the right). First, each of both wires goes directly to 15kOhm resistor. Secondly, it splits between a 10kOhm resistor which then ends up into Arduino's ground, or it goes directly to the Arduino's pin 3 or 5, depending on the cable.

**Results**

The Serial Monitor shows "DSC Keybus Interface is online" and over.

If I connect green and white directly to 3 and 5, it will say sometimes "Keybus disconnected" and "Keybus connected" without any additional messages ever.

So my question is, am I missing something here? Why is the Serial Monitor not responding or what can I do to check where is the problem?

**EDIT**

This are the serial monitor readings, nothing from the Panel. I had to connect without resistances to get this output, otherwise, the only output would be "DSC Keybus Interface is online."

```
08:26:32.359 ->
08:26:32.359 -> DSC Keybus Interface is online.
08:26:35.345 -> Keybus disconnected
08:26:42.722 -> Keybus connected
08:26:47.838 -> Keybus disconnected
08:26:51.131 -> Keybus connected
08:26:54.937 -> Keybus disconnected
08:27:12.661 -> Keybus connected
08:27:17.122 -> Keybus disconnected
08:27:34.218 -> Keybus connected
08:27:41.697 -> Keybus disconnected
08:28:19.509 -> Keybus connected
08:28:22.487 -> Keybus disconnected
08:28:25.068 -> Keybus connected
08:28:28.053 -> Keybus disconnected
08:29:23.692 -> Keybus disconnected
08:29:31.175 -> Keybus disconnected
08:29:33.990 -> Keybus connected
08:29:37.005 -> Keybus disconnected

```

# Answer
> **Is this circuit properly made?**

No.

A lot of the problem is that you don't have a well-drawn schematic. I think that what you have is a couple of voltage dividers to interface a 5V arduino with a higher voltage device. I suspect a voltage divider isn't the best solution but presumably it works for someone else. So what you need is ...

simulate this circuit – Schematic created using CircuitLab

If I were you I'd pull your existing wiring apart completely and start again, arranging the components and wires so that they match this schematic as closely as possible in terms of position and orientation. Then trace the connections through carefully to make sure everything matches.
> 1 votes

---
Tags: arduino-uno, wires, resistor
---


# Question
Title: Weird RTC DS3231 Output only when saving the dates to variables
I am sorry to ask this question as I think it has more to do with my mediocre C++ programming skill than with the arduino. I do have a project where I want to use an RTC DS2131. I started out by using all the separate examples of the modules I need and put them together. But the RTC give me a headache :-(

The example ran fine where it just output the date to the serial port. Somthing along this:

```
Serial.print(RTC.getDay());
Serial.print("-");
Serial.print(RTC.getMonth());

```

Now I want these values in different variables because I want to save them on an SD card as well.

Thus I came up with this simple test program:

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

static DS3231 RTC;

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

void loop()
{
int yearNow;
int monthNow, dateNow, hourNow, minuteNow, secondNow, weekNow;

if (RTC.isRunning())
  {
    yearNow=RTC.getYear();
    monthNow =RTC.getMonth();
    dateNow=RTC.getDay();
    weekNow=RTC.getWeek();
    hourNow=RTC.getHours();
    minuteNow=RTC.getMinutes();
    secondNow=RTC.getSeconds();

    Serial.print("Weekday: ");
    Serial.print(weekNow);
    Serial.print('  Time:');
    // Finally the hour, minute, and second
    Serial.print(hourNow);
    Serial.print('-');
    Serial.print(minuteNow);
    Serial.print('-');
    Serial.print(secondNow);
    Serial.print(" ##  ");
    Serial.print("Date: ");
    Serial.print(yearNow);
    Serial.print('/');
    Serial.print(monthNow);
    Serial.print('/');
    Serial.println(dateNow);

  }
}

```

Now I would expect this output: Weekday: 4 Time:16-10-36 ## Date: 2020/7/28

But this is what I get: Weekday: 42591416-10-36 ## Date: 2020/7/28

As a sidenote the variables in this sketch are declared as "int". After having looked into the header files of the library I tried uint8\_t resp. uint16\_t for the year. But nothing changed.

I am sorry but I have no clue as what beginner mistake I am achieving this time?? :-(

Thanks for your help.

# Answer
> 1 votes
You used single quotes instead of double quotes. Single quotes are for single characters. Double quotes are for strings (or character arrays).

```
Serial.print('  Time:');

```

should be

```
Serial.print("  Time:");

```

---
Tags: arduino-uno, serial, c++, rtc
---


title: WS2812B are only white on custom board

text:
# Question
Title: WS2812B are only white on custom board
I recently designed a board for an LED project. I am using WS2812B as the LED, and an ATMEGA328P-AU as the microcontroller. I also am using an arduino nano as my ISP and using "flash with programmer". When I flashed the FastLED blink example (Code below) the LED lit up as white and stayed white when it was supposed to flash red. I tried various examples and they all had the same outcome, just white. Am I missing a crucial component in my circuit (aside from some decoupling capacitors)? Is it a software problem?

```
#include <FastLED.h>

#define NUM_LEDS 1
#define DATA_PIN 5

// Define the array of leds
CRGB leds[NUM_LEDS];

void setup() {
     FastLED.addLeds<WS2812B, DATA_PIN, GRB>(leds, NUM_LEDS);  // GRB ordering is typical
}

void loop() {
  // Turn the LED on, then pause
  leds[0] = CRGB::Red;
  FastLED.show();
  delay(500);
  // Now turn the LED off, then pause
  leds[0] = CRGB::Black;
  FastLED.show();
  delay(500);
}

```

# Answer
> 4 votes
The WS2812B chips are very sensitive to timing. They rely on pulses being just the right length for things to work.

It is common if the timing is off that you just end up with white.

Since you have a blank chip that you have never put a bootloader on the fuses will be set wrongly for your configuration. By default a chip comes configured for the internal 8MHz oscillator. That means that everything will be running at half the speed.

You need to set the fuses to use the 16MHz crystal so that it matches the `F_CPU` setting of 16000000 in the board configuration. Either that or use a board configuration that expects to run at 8MHz.

---
Tags: atmega328, rgb-led, ws2812, pcb-design
---


# Question
Title: Connecting a time on/off circuit and my adafruit neopixel light strip
I'm new to programming and hardware so be gentle.

I've used this tutorial Arduino Ultra Mega Timers to create a time on/off circuit.

I'm attempting to connect some adafruit neopixel led strips to a 5v relay. I've been trying to read up on how exactly relays work and what wires would go from **GND**, **5V**, and **Dout** to **NO** and **NC** but I've hit a brick wall because all of the schematics I've found show light bulbs connecting to the relays. A detailed explanation of exactly how to connect the LED strip to the relay and why it works would be great as I am trying to learn!

# Answer
> 1 votes
You cannot find a tutorial for controlling neopixel strips with a relay, because that just does not make any sense. You don't need a relay to control the strip.

The Neopixels consist not only of the LEDs themselves, but also of one LED driver chip per LED (WS2811 and it's siblings). These driver chips control the LEDs based on the data, that you send through the data pin. Actually one Neopixel LED consists of 3 LEDs inside a single package, one LED each for the colors red, green and blue (so that you can create all the other colors with a combination of them). The driver chip controlls the brightness of all three colors.

Thus you only need to connect your 5V power source to the strip (5V and ground) - Be sure to connect the power lines directly to your power supply, so that the LED current does not flow through the Arduino (because that can fry your Arduino) - and the data In pin of the strip to a fitting digital pin of the Arduino. You can use the Adafruit Neopixel library or the FastLED library for controlling them.

To turn the strip on, you set the needed pixels to the wanted color and then call the show method of the library (which sends out the color data through the data pin). To turn the strip off, you simply clear all the pixels (the libraries have extra functions for that), which basically means setting all pixel to black (red, green and blue components all zero).

So forget about the relay and just use the strip directly. Also Adafruit has a very good guide on how to use the Neopixels.

---
Tags: arduino-uno, led, relay, rgb-led
---