title: Unable to burn bootloader with avrisp

text:
# Question
Title: Unable to burn bootloader with avrisp
I want to burn the arduino `optiboot_atmega328.hex` bootloader but it doesn't work. I remember that I was able to burn the BL using the arduino IDE which was quite easy, this time I'm having some problems.

I'm always using an avrispv2 programmer to flash my atmegas and it was also this programmer I used once to burn the BL. When I try, the IDE gives the following output:

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

         System wide configuration file is "/home/xxx/Downloads/arduino-1.8.7-linux64/arduino-1.8.7/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/home/xxx/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM2
         Using Programmer              : stk500v1
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x00
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00

avrdude done.  Thank you.

Fehler beim Brennen des Bootloaders.

```

After this didn't work I tried to manually upload the `optiboot_atmega328.hex` with avrdude on the commandline (following this guide). The output of avrdude is as follows:

```
avrdude -b 19200 -c avrispv2 -p m328p -v -e -U efuse:w:0x05:m -U hfuse:w:0xD6:m -U lfuse:w:0xFF:m -P /dev/ttyACM2

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

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/tabaluga/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM2
         Using Programmer              : avrispv2
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500V2
         Description     : Atmel AVR ISP V2
         Programmer Model: STK500
         Hardware Version: 10
         Firmware Version Master : 2.10
avrdude: stk500v2_command(): command failed
avrdude: stk500v2_getparm(): failed to get parameter 0x9a
         Topcard         : Unknown
         Vtarget         : 3.3 V
         SCK period      : 17.4 us
         Varef           : 3.3 V
         Oscillator      : Off

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: erasing chip
avrdude: reading input file "0x05"
avrdude: writing efuse (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of efuse written
avrdude: verifying efuse memory against 0x05:
avrdude: load data efuse data from input file 0x05:
avrdude: input file 0x05 contains 1 bytes
avrdude: reading on-chip efuse data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0xfd != 0x05
avrdude: verification error; content mismatch

avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: safemode: efuse changed! Was 5, and is now fd
Would you like this fuse to be changed back? [y/n] y
avrdude: safemode: Wrote efuse to 5, read as fd. 9 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 8 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 7 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 6 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 5 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 4 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 3 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 2 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 1 attempts left
avrdude: safemode: Wrote efuse to 5, read as fd. 0 attempts left
avrdude: and COULD NOT be changed
avrdude: safemode: Fuses not recovered, sorry

avrdude done.  Thank you.

```

As I'm unable to set the fuses it's no wonder that the actual upload doesn't work as well:

```
avrdude -b 19200 -c avrispv2 -p m328p -v -e -U flash:w:optiboot_atmega328.hex -U lock:w:0x0F:m -P /dev/ttyACM2

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

         System wide configuration file is "/etc/avrdude.conf"
         User configuration file is "/home/tabaluga/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/ttyACM2
         Using Programmer              : avrispv2
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500V2
         Description     : Atmel AVR ISP V2
         Programmer Model: STK500
         Hardware Version: 10
         Firmware Version Master : 2.10
avrdude: stk500v2_command(): command failed
avrdude: stk500v2_getparm(): failed to get parameter 0x9a
         Topcard         : Unknown
         Vtarget         : 3.3 V
         SCK period      : 17.4 us
         Varef           : 3.3 V
         Oscillator      : Off

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: erasing chip
avrdude: reading input file "optiboot_atmega328.hex"
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: writing flash (32768 bytes):

Writing | ################################################## | 100% 0.00s

avrdude: 32768 bytes of flash written
avrdude: verifying flash memory against optiboot_atmega328.hex:
avrdude: load data flash data from input file optiboot_atmega328.hex:
avrdude: input file optiboot_atmega328.hex auto detected as Intel Hex
avrdude: input file optiboot_atmega328.hex contains 32768 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: 32768 bytes of flash verified
avrdude: reading input file "0x0F"
avrdude: writing lock (1 bytes):

Writing | ################################################## | 100% 0.01s

avrdude: 1 bytes of lock written
avrdude: verifying lock memory against 0x0F:
avrdude: load data lock data from input file 0x0F:
avrdude: input file 0x0F contains 1 bytes
avrdude: reading on-chip lock data:

Reading | ################################################## | 100% 0.00s

avrdude: verifying ...
avrdude: verification error, first mismatch at byte 0x0000
         0xcf != 0x0f
avrdude: verification error; content mismatch

avrdude: safemode: hfuse reads as D9
avrdude: safemode: efuse reads as FD
avrdude: safemode: Fuses OK (E:FD, H:D9, L:62)

avrdude done.  Thank you.

```

I personally doubt that the µC or my programmer are bricked because I'm able to upload program code via ISP as I always used to, also I've tried two different ATmega328p.

Do you see what I'm doing wrong? Why does one actually have to change fuses before flashing the bootloader (just curious)?

# Answer
I can see you are on Linux so I won't give you instructions for using AVR Studio - but do know that if you have access to a Windows machine that is another option you could try.

I can't tell you exactly why it is not working through the Arduino IDE - it could be that the settings are not set correctly or any number of reasons. What I can say is that it is not seeing the AVRISPmkII. Try turning on verbose mode in the Arduino SE settings.

However when using avrdude, you are requesting the efuse be set to 0x05. The value of 0x05 (or b0000 0101) means that you are requesting a brownout detection of 2.7V. But because only the last 3 bits of the fuse are relevant, the chip fills the rest of the bits with 1 not 0. So b0000 0101 (aka 0x05) becomes b1111 1101 (aka 0xFD), hence you get a mismatch.

Also, according to my `\Arduino-x.x.x\hardware\arduino\avr\boards.txt` file, the fuses for the Arduino/Genduino Optiboot are:

* low\_fuses=0xFF
* high\_fuses=0xDE
* extended\_fuses=0xFD

Change your avrdude command to the following:

```
avrdude -b 19200 -c avrispv2 -p m328p -v -e -U efuse:w:0xFD:m -U hfuse:w:0xDE:m -U lfuse:w:0xFF:m -P /dev/ttyACM2

```

The last block of output in your question shows that you are trying to load the optiboot hex file. That part works so it seems, as it writes and verifies successfully. The interesting part is the lock bit fails verification. It is reading 0xCF which means it is in bootloader protection mode #3: LPM and SPM prohibited in boot loader section.

From the datasheet:

> SPM = Store Program Memory instruction
> LPM = Load Program Memory instruction

And

> SPM is not allowed to write to the Boot Loader section, and LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section.

But it appears that these lock bits can be removed by doing a chip erase:

> The Boot Lock bits can be set in software and in Serial or Parallel Programming mode, but they can be cleared by a Chip Erase command only.

And

> The Chip Erase will erase the Flash and EEPROM(1) memories plus Lock bits. The Lock bits are not reset until the program memory has been completely erased. The Fuse bits are not changed. A Chip Erase must be performed before the Flash and/or EEPROM are reprogrammed.

So it looks like you need to do a full chip erase with avrdude.

---

For reference I use the following fuse calculators:
> 2 votes

---
Tags: arduino-uno, atmega328, bootloader, isp, programmer
---


# Question
Title: Can I disable the TX pin by setting its mode to INPUT while still receiving data on the RX pin of a UART?
I'm using the ATmega328PB in a personal project with MiniCore. My board streams data in on the RX pin from another microcontroller, but my board also has a DIP switch connected to the TX pin, that's used for configuration. My board has already been manufactured, so a hardware solution means a board redesign and extra cost/time.

This DIP switch is connected between TXD (Arduino pin "1") and GND. Upon startup, I read the value of this pin when in mode INPUT\_PULLUP. However, when I go to start the Serial, if this switch is in the closed position, it shorts the TXD pin to GND.

**Is it possible to disable the TX pin by putting it into INPUT mode while still receiving data on the RX pin?**

# Answer
Well, I ended up answering my own question in a few minutes of forum research.

You can disable the TX pin of the hardware UART with:

```
UCSR0B &= ~bit (TXEN0);

```
> 2 votes

---
Tags: pins, uart, port-mapping
---


# Question
Title: invalid conversion from 'const char*' to 'char*' [-fpermissive]
With WebSocket various messages arrive.

Task:

1. Find message "setBrightness: 15"
2. Extract the value "15" from the message (the value can be any)
3. Convert this value to uint8\_t

My code:

```
#include <string.h>

String payload_str = "setBrightness: 15"; // WebSocket message
const char* payload = payload_str.c_str(); // Convert string to char

const char* value; // Message value
uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
   value = strtok(payload, " ");
   value = strtok(NULL," "); // Get value (15)
   brightness = (uint8_t)atoi(value); // Convert to uint8_t
  }
}

void loop() {}

```

Compilling error:

> error: invalid conversion from 'const char\*' to 'char\*' \[-fpermissive\]
>
> error: initializing argument 1 of 'char\* strtok(char\*, const char\*)' \[-fpermissive\]

Maybe I'm doing it completely wrong and not safe. How can this be fixed?

# Answer
> 1 votes
`strtok` modifies the char buffer entered as first parameter. It replaces the delimiters with terminating zeros. To parse a constant string with `strtok`, you must first copy it into a working char buffer.

For your test you can initialize a char array as in following example.

```
char payload[] = "setBrightness: 15";

uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
   strtok(payload, " ");
   const char* tok = strtok(NULL," "); // Get value (15)
   brightness = (uint8_t) atoi(tok); // Convert to uint8_t
  }
}

void loop() {}

```

---

if you know the 'name' part of the name:value string, you can skip it for `atoi` this way:

`brightness = (uint8_t) atoi(payload + strlen("setBrightness: "));`

(`strlen("setBrightness: "` will be evaluated at compile time to a constant number)

```
const char payload[] = "setBrightness: 15";

uint8_t brightness;

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

  if(strncmp(payload, "setBri", 6) == 0) { // Search message
     brightness = (uint8_t) atoi(payload + strlen("setBrightness: ")); // Convert to uint8_t
  }
}

void loop() {}

```

---
Tags: arduino-uno
---


title: why data value is 0

text:
# Question
Title: why data value is 0
i want to apply formula. but getting 0 at output.

```
#include "HX711.h"
int data;
HX711 scale(A1, A0);		// parameter "gain" is ommited; the default value 128 is used by the library

void setup() {
  **Serial**.begin(38400);

  scale.set_scale(2280.f);
  scale.tare();

}

void loop() {
  **Serial**.print("one reading:\t");
  data==(scale.get_units()/10);
  **Serial**.println(data);

		        // put the ADC in sleep mode
  delay(500);

}

```

# Answer
> 2 votes
It's zero because you never assign it a value.

Here you are comparing the current value of `data` (0) with the results of your calculation:

```
data==(scale.get_units()/10);

```

I think you intended to use the assignment, not comparison, operator `=`:

```
data = (scale.get_units()/10);

```

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


# Question
Title: Can I use this board to control multiple vibration motors?
I am looking at this: https://learn.adafruit.com/16-channel-pwm-servo-driver

Although it’s meant for servos, I was wondering if I could use them to control vibration motors.

Motors like these: Diameter Flat Button Type 3V-4.5V Cellphone Micro Vibration Motor (Pack of 3) https://www.amazon.in/dp/B07CQXZBZD/ref=cm\_sw\_r\_cp\_tai\_yzSvDb8V7JAF4

Any suggestions? I would like to control about 200 motors with minimal number of controllers.

Each motor should be controllable individually.

# Answer
Not directly, no. Those boards are designed to generate a low power PWM signal for passing to a servo with a built-in controller. To use that output directly with a motor you will need to add a transistor to each output to control the motor.

simulate this circuit – Schematic created using CircuitLab
> 1 votes

---
Tags: motor
---


title: Arduino PWM 1kHz and 10-bit resolution

text:
# Question
Title: Arduino PWM 1kHz and 10-bit resolution
As the title says, I need 1khz frequency signal with 10-bit resolution. But I am not good with uControllers and complicated programming.

I need a simple code for this task.

I tried using this Interactive PWM from arduinoslovakia.eu but I dont know what the frequency is at 10-bit resolution and how to set frequency in this code.

# Answer
> 2 votes
I see you are talking about using the 16-bit timer, which is Timer 1 on the Uno.

Assuming you are using a Uno this code will do it:

```
// Clock frequency divided by 1 kHz frequency desired
const long timer1_OCR1A_Setting = F_CPU / 1000;

const byte outputPin = 10;  // Timer 1 "B" output: OC1B

void setup()
 {
  pinMode (outputPin, OUTPUT);

  // set up Timer 1
  // Fast PWM top at OCR1A
  TCCR1A = bit (WGM10) | bit (WGM11) | bit (COM1B1); // fast PWM, clear OC1B on compare
  TCCR1B = bit (WGM12) | bit (WGM13) | bit (CS10);   // fast PWM, no prescaler
  OCR1A =  timer1_OCR1A_Setting - 1;                 // zero relative
  OCR1B =  (timer1_OCR1A_Setting / 2) - 1;           // 50 % duty cycle
  }  // end of setup

void loop()
  {
  }

```

You can change the 1000 in the calculation for timer1\_OCR1A\_Setting, within reason, to get other frequencies.

See my page about timers for more background information.

---
Tags: pwm
---


# Question
Title: how to interrupt the loop function and restart it?
I have a project with some NeoPixels and other LEDs and an Arduino UNO. Once switched on, the `defaultLEDAnimation` with colors and blinking, etc. starts.

I want to trigger some other animations, so I connected two buttons to the Arduino. Whenever you press `button1`, the Arduino should stop everything it is doing and run `animation1`. The same goes for `button2`. if you press it, the Arduino should run `animation2`. All animations are quite complex and run for several seconds and even minutes.

**Now for the challenge**: How do I use the two buttons to immediately stop every animation happening and display the appropriate animation?

The tried using interrupts and connected the two buttons to pin 2 and 3. **However, when I press the buttons, the animation starts after several seconds delay.** Is there any way to restart the loop function immediately after the interrupt has been made? Or is there another way to trigger my animations with those two buttons?

The code looks something like this:

```
#define button1 2
#define button2 3

volatile bool shouldPerformButton1Action = false;
volatile bool shouldPerformButton2Action = false;

void setup() {
    attachInterrupt(digitalPinToInterrupt(button1), button1Pressed, RISING);
    attachInterrupt(digitalPinToInterrupt(button2), button2Pressed, RISING);
}

void loop() {
    if (shouldPerformButton1Action) {
        doAnimation1();
        shouldPerformButton1Action = false;
    } else if (shouldPerformButton2Action) {
        doAnimation2();
        shouldPerformButton2Action = false;
    } else {
        runDefaultAnimation();
    }
}

void button1Pressed() {
    shouldPerformButton1Action = true;
}

void button2Pressed() {
    shouldPerformbutton2Action = true;
}

void doAnimation1() {
    for(int i=0; i<10; i++){
        neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(255, 0, 0, 255));
        neoPixelStrip.show();
        delay(100);
    }
    delay(1000);
    for(int i=0; i<10; i++){
        neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(0, 0, 0, 0));
        neoPixelStrip.show();
        delay(100);
    }
}

```

The function `doAnimation1` is just an example. It will be much more complex.

# Answer
Basically you have to make the animation loops return if the condition is met, for example:

```
void doAnimation1() {
    for(int i=0; i<10; i++){
        if (digitalRead (button1) == HIGH)  // Time to stop?
           return;
        neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(255, 0, 0, 255));
        neoPixelStrip.show();
        delay(100);
    }
    delay(1000);
    for(int i=0; i<10; i++){
        if (digitalRead (button1) == HIGH)  // Time to stop?
           return;
        neoPixelStrip.setPixelColor(neoPixelArray[i], neoPixelStrip.Color(0, 0, 0, 0));
        neoPixelStrip.show();
        delay(100);
    }
}

```

If you don't want to wait for the 100 ms delay (or the 1000 ms delay) then you could replace that with code that waits for 100 ms to elapse, but also checks the button.

Interrupts are not the way to do it. Interrupts let you briefly stop doing something, do something else, then go back to what you were doing before. They don't "interrupt" your entire workflow.

For example, you might interrupt your movie watching to answer the phone, you don't "interrupt" your movie watching to go out to dinner with a friend. That is just a case of doing a different thing.
> 1 votes

# Answer
"How to interrupt the loop function and restart it?"

You don't. That's not how you write Arduino code. You need to have your loop function call a series of non-blocking functions that check to see if it's time to do something, do a very small bit of work if it is time, or just return if it's not time yet.

What I've done is to create a class ArduinoObject that has a setup function, a start function, a stop function, a loop function, and a boolean property `running`. My main program has a global variable that holds an array of `ArduinoObject`s.

Every time through the loop, I check all the `ArduinoObject`s in the array, and call their loop functions.

The first thing each object does is check its `running` flag. If `running==false`, it exits immediately.

Each object uses unsigned long values to track the next `millis()` time count when it should do something.

Let's say the object does an animation, so it has an unsigned long `nextAnimationStepTime`. In the `loop()` function, if `nextAnimationStepTime<millis()`, it doesn't do anything. If instead `nextAnimationStepTime>=millis()`, the object advances the animation to the next step, and sets `nextAnimationStepTime = millis() + animationStepDuration`. That way, next time the object is called, it will wait until it's time to advance the animation yet another step.

Each object is written to only do a tiny bit of work on each pass through the loop, and return as quickly as possible.

With this design, I can add an arbitrary number of objects/tasks to my loop, and all of them get attention on every pass through the loop. Most objects simply decide they're not running, or it's not time to do anything, and return.

You can then add control logic that starts and stops individual objects based on things like button presses.

With this approach you'd have your button 1 press stop animation 2 if it was running and run animation 1. Conversely, pressing button 2 would stop animation 1 if
> 1 votes

---
Tags: arduino-uno, interrupt, button, isr
---


# Question
Title: SPIMemory does not write always correctly
I'm using a WinBond 25Q128FVIQ (Flash 128 mbit, 3.3V) in combination with the Marzogh SpiMemory library on my Arduino Nano (also 3.3V).

After using the default example, I found out what was read, did not always fully match what I wrote. So I created a slightly alternative example writing 16 bytes:

```
#include<SPIMemory.h>

uint32_t address;

#define BAUD_RATE 115200
#define RANDPIN A0

//SPIFlash flash(SS1, &SPI1);       //Use this constructor if using an SPI bus other than the default SPI. Only works with chips with more than one hardware SPI bus
SPIFlash flash;

bool readSerialStr(String &inputStr);

void setup() {
  Serial.begin(BAUD_RATE);
#if defined (ARDUINO_SAMD_ZERO) || (__AVR_ATmega32U4__)
  while (!Serial) ; // Wait for Serial monitor to open
#endif

  flash.begin();
  Serial.println(F("Flash Test"));
  Serial.print(F("Capacity: "));
  Serial.println(flash.getCapacity());

  char writeBuffer[16] = "0123456789ABCDEF";
  char readBuffer[17];

  for (int n = 0; n < 5; n++)
  {
    memset(readBuffer, 17, 0);
    randomSeed(analogRead(RANDPIN));
    address = random(0, flash.getCapacity() - 16);
    bool err = flash.writeAnything(address, writeBuffer, true);
    delay(50);
    Serial.print(F("Write: "));
    Serial.println(err);
    for (int m = 0; m < 10; m++)
    {
      if (flash.readAnything(address, readBuffer, true))
      {
        Serial.print(m);
        Serial.print(F(", read: "));
        Serial.print(readBuffer);
        Serial.print(F(", from address: "));
        Serial.println(address);
      }
      delay(50);
    }
  }
}

void loop() {

}

//Reads a string from Serial
bool readSerialStr(String &inputStr) {
  if (!Serial)
    Serial.begin(115200);
  while (Serial.available()) {
    inputStr = Serial.readStringUntil('\n');
    Serial.println(inputStr);
    return true;
  }
  return false;
}

```

Short explanation: 5 times I write a string (hex numbers), and I read this 5 times. The result is: (one example, differs every time):

```
 Flash Test
Capacity: 8388608
Write: 1
0, read: 0123456789ABCDEF, from address: 6252204
1, read: 0123456789ABCDEF, from address: 6252204
2, read: 0123456789ABCDEF, from address: 6252204
3, read: 0123456789ABCDEF, from address: 6252204
4, read: 0123456789ABCDEF, from address: 6252204
5, read: 0123456789ABCDEF, from address: 6252204
6, read: 0123456789ABCDEF, from address: 6252204
7, read: 0123456789ABCDEF, from address: 6252204
8, read: 0123456789ABCDEF, from address: 6252204
9, read: 0123456789ABCDEF, from address: 6252204
Write: 1
0, read: 0123456789ABCDEF, from address: 5680766
1, read: 0123456789ABCDEF, from address: 5680766
2, read: 0123456789ABCDEF, from address: 5680766
3, read: 0123456789ABCDEF, from address: 5680766
4, read: 0123456789ABCDEF, from address: 5680766
5, read: 0123456789ABCDEF, from address: 5680766
6, read: 0123456789ABCDEF, from address: 5680766
7, read: 0123456789ABCDEF, from address: 5680766
8, read: 0123456789ABCDEF, from address: 5680766
9, read: 0123456789ABCDEF, from address: 5680766
Write: 0
0, read: , from address: 5277398
1, read: , from address: 5277398
2, read: , from address: 5277398
3, read: , from address: 5277398
4, read: , from address: 5277398
5, read: , from address: 5277398
6, read: , from address: 5277398
7, read: , from address: 5277398
8, read: , from address: 5277398
9, read: , from address: 5277398
Write: 0
0, read: , from address: 4941258
1, read: , from address: 4941258
2, read: , from address: 4941258
3, read: , from address: 4941258
4, read: , from address: 4941258
5, read: , from address: 4941258
6, read: , from address: 4941258
7, read: , from address: 4941258
8, read: , from address: 4941258
9, read: , from address: 4941258
Write: 0
0, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
1, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
2, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
3, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
4, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
5, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
6, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
7, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
8, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153
9, read: ⸮⸮⸮⸮⸮l⸮څ⸮w⸮r⸮0123456789ABCDEF, from address: 4689153

```

Conclusion: The write seems to be the problem as the read consequently returns the same value (either garbage or the correct string).

What do I wrong?

Actually, I even don't want the 50 ms delay (and when I remove it, the result is the same).

# Answer
> 1 votes
I made a stupid mistake; I accidentally removed the next line at the end of the application which takes care of erasing the sector. If this is omitted, then the next time write actions will fail (or fail sometimes):

```
flash.eraseSector(address);

```

---
Tags: arduino-nano, library, flash
---


# Question
Title: Problem “Didn't find PN53x board” Arduino NFC Card Reader
i am using the elechouse PN532 RFID Module with an Wemos D1 mini in the Arduino IDE. I use the ISO1443a\_uid example from the elechouse library. All works fine if i plug the USB Cable into the wemos and the demo runs. But if i press the reset button on the Wemos D1 mini then the Serial brings this output:

```
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v0fd86a07
~ld
Hello!
Didn't find PN53x board

```

Sometimes it works fine but mostly comes this error.

Here is the sample code (i am using the I2C Mode):

```
* When the number after #if set as 1, it will be switch to SPI Mode*/
if 0
 #include <SPI.h>
 #include <PN532_SPI.h>
 #include "PN532.h"

 PN532_SPI pn532spi(SPI, 10);
 PN532 nfc(pn532spi);

* When the number after #elif set as 1, it will be switch to HSU Mode*/
elif 0
 #include <PN532_HSU.h>
 #include <PN532.h>

 PN532_HSU pn532hsu(Serial1);
 PN532 nfc(pn532hsu);

* When the number after #if & #elif set as 0, it will be switch to I2C Mode*/
else
 #include <Wire.h>
 #include <PN532_I2C.h>
 #include <PN532.h>
 #include <NfcAdapter.h>

 PN532_I2C pn532i2c(Wire);
 PN532 nfc(pn532i2c);
endif

oid setup(void) {
 Serial.begin(115200);
 Serial.println("Hello!");
 pinMode(D2,INPUT_PULLUP);
 pinMode(D1,INPUT_PULLUP);
 nfc.begin();

 uint32_t versiondata = nfc.getFirmwareVersion();
 if (! versiondata) {
   Serial.print("Didn't find PN53x board");
   while (1); // halt
 }

 // Got ok data, print it out!
 Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
 Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
 Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

 // Set the max number of retry attempts to read from a card
 // This prevents us from waiting forever for a card, which is
 // the default behaviour of the PN532.
 nfc.setPassiveActivationRetries(0xFF);

 // configure board to read RFID tags
 nfc.SAMConfig();

 Serial.println("Waiting for an ISO14443A card");

oid loop(void) {
 boolean success;
 uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID
 uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)

 // Wait for an ISO14443A type cards (Mifare, etc.).  When one is found
 // 'uid' will be populated with the UID, and uidLength will indicate
 // if the uid is 4 bytes (Mifare Classic) or 7 bytes (Mifare Ultralight)
 success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);

 if (success) {
   Serial.println("Found a card!");
   Serial.print("UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");
   Serial.print("UID Value: ");
   for (uint8_t i=0; i < uidLength; i++)
   {
     Serial.print(" 0x");Serial.print(uid[i], HEX);
   }
   Serial.println("");
   // Wait 1 second before continuing
   delay(1000);
 }
 else
 {
   // PN532 probably timed out waiting for a card
   Serial.println("Timed out waiting for a card");
 }

```

What is wrong? why is it not alltimes working after a reset?

# Answer
> 1 votes
EDIT: Try using Elechouse library, it worked better for me.

---

This might be irrelevant, but I wanted to share.

I had a similar issue, not related to the sketch code.

So make sure:

1. Connect wires to the NFC module at **90 degrees** \- there should be angular headers included. Also the wires should be **above the antenna** \- the white strip.
2. There shouldn't be any wires underneath the NFC module or they should on significant distance.
3. Soldered wires work better on the NFC module.

---
Tags: esp8266, arduino-ide, rfid, code-review
---


title: avrdude/stk500 protocol error

text:
# Question
Title: avrdude/stk500 protocol error
I'm running into a bizarre problem. I've got a custom board using an Atmega328P, running off the internal oscillator. From Atmel studio, I've successfully uploaded the standard optiboot bootloader (`optiboot_atmega328.hex`) and burned the appropriate fuses (`hfuse = 0xDE`, `lfuse = 0xE2`, `extended_fuse = 0x05`). As per an arduino forum post, I added the following entry to `boards.txt`: atmega328\_384\_8.name=ATmega328 Optiboot @ 38,400baud w/ 8MHz Int. RC Osc.

```
atmega328_384_8.upload.protocol=arduino
atmega328_384_8.upload.maximum_size=30720
atmega328_384_8.upload.speed=57600
atmega328_384_8.upload.tool=avrdude

atmega328_384_8.bootloader.low_fuses=0xE2
atmega328_384_8.bootloader.high_fuses=0xDE
atmega328_384_8.bootloader.extended_fuses=0x05
atmega328_384_8.bootloader.path=optiboot
atmega328_384_8.bootloader.file=optiboot_atmega328.hex
atmega328_384_8.bootloader.unlock_bits=0x3F
atmega328_384_8.bootloader.lock_bits=0x0F

atmega328_384_8.build.mcu=atmega328p
atmega328_384_8.build.f_cpu=8000000L
atmega328_384_8.build.core=arduino
atmega328_384_8.build.variant=standard

```

Note here, I've modified the upload speed to 57600 baud to "fool" it into the right upload speed given an 8MHz oscillator.

I can now successfully upload sketches from the Arduino IDE (1.6.3) on the lab windows machine, but when I try from my Mac (various IDE versions have been tried), I get the following protocol error:

`avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0`

Here's the full trace:

```
/Applications/Arduino-1.6.8.app/Contents/Java/hardware/tools/avr/bin/avrdude -C/Applications/Arduino-1.6.8.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf -v -patmega328p -carduino -P/dev/cu.usbserial-AH02F0KI -b57600 -D -Uflash:w:/var/folders/db/hw2v9r6j7qj_w9gh3qkhh_580000gr/T/build53eb1895270295360d41549eaf6e0624.tmp/sketch_apr19a.ino.hex:i

avrdude: Version 6.0.1, compiled on Apr 14 2015 at 16:30:25
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "/Applications/Arduino-1.6.8.app/Contents/Java/hardware/tools/avr/etc/avrdude.conf"
         User configuration file is "/Users/npisenti/.avrduderc"
         User configuration file does not exist or is not a regular file, skipping

         Using Port                    : /dev/cu.usbserial-AH02F0KI
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00
         Hardware Version: -1538883332
         Firmware Version: 6291456.-1538883332

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0
         Vtarget         : 322122165.6 V
         Varef           : 275608114.4 V
         Oscillator      : 0.001 Hz
         SCK period      : 368336.6 us

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0xe0

avrdude: stk500_getparm(): (a) protocol error, expect=0x14, resp=0x00
avrdude: stk500_initialize(): (a) protocol error, expect=0x14, resp=0xe0
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude: stk500_disable(): protocol error, expect=0x14, resp=0xe0

avrdude done.  Thank you.

Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

```

On Windows, the "successful" full trace from avrdude is:

```
Sketch uses 1,974 bytes (6%) of program storage space. Maximum is 30,720 bytes.
Global variables use 192 bytes of dynamic memory.
C:\arduino-1.6.3\hardware\tools\avr/bin/avrdude -CC:\arduino-1.6.3\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM10 -b57600 -D -Uflash:w:C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex:i

avrdude: Version 6.0.1, compiled on Mar 30 2015 at 14:56:06
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2009 Joerg Wunsch

         System wide configuration file is "C:\arduino-1.6.3\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM10
         Using Programmer              : arduino
         Overriding Baud Rate          : 57600
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.01s

avrdude: Device signature = 0x1e950f
avrdude: reading input file "C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex"
avrdude: writing flash (1974 bytes):

Writing | ################################################## | 100% 0.77s

avrdude: 1974 bytes of flash written
avrdude: verifying flash memory against C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex:
avrdude: load data flash data from input file C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex:
avrdude: input file C:\Users\GENERA~1\AppData\Local\Temp\build1097250116669309732.tmp/sketch_apr19a.cpp.hex contains 1974 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.86s

avrdude: verifying ...
avrdude: 1974 bytes of flash verified

avrdude done.  Thank you.

```

In both cases, I'm using the FTDI friend from Adafruit; at first I figured it must be a driver issue, but I've installed the latest FTDI drivers and doesn't seem to help. Besides, I can successfully get text dumped from the ucontroller onto the serial port from a sketch previously uploaded on the windows machine.

Any help would be greatly appreciated!

# Answer
> 1 votes
I managed to figure this out after hours of searching. I wanted to flash the new Nano bootloader to my Nano, but it would fail with the same error as you.

For some reason, after Arduino 1.8.5, AVR boards with "Arduino as ISP" were changed so that they no longer work for me.

The solution for me was to revert `programmers.txt` to what it was on 1.8.5, i.e. change the `arduinoasisp` lines to:

```
arduinoasisp.protocol=stk500v1
arduinoasisp.speed=19200
arduinoasisp.program.protocol=stk500v1

```

This uses the stk500v1 protocol instead of the arduino protocol (you can see the `-carduino` option in your command line) and makes everything work for me.

---
Tags: bootloader, avrdude
---


# Question
Title: strcat parameters throwing pointer errors in my tcp server / parser application
I am attempting to use an Arduino Uno WiFi Rev2 board to integrate some lonely data. I will use the NINA WiFi chipset and associated libraries to start a server that will periodically request and receive client information hosted on multiple types of devices that will run concurrently; thus it's pretty much divided in 2 sections: 1.) Manage the client connections and their character arrays 2.) Parsing the information and responding accordingly from a control aspect

This is what I have so far, and what I was just compiling the other day:

```
#include <stdlib.h>
#include <SPI.h>
#include <WiFiNINA.h>

char ssid[] = "***";                // House -- Network SSID (name)
char pass[] = "***";              // House -- SSID password (WPA2-PSK)

#define MAX_CLIENTS 5
#define MAX_LINE_LEN 50
char inputs[MAX_CLIENTS][MAX_LINE_LEN] = {0}; // Instantiate 2D array of
client/received data
int msg_array[] = {0,0};
int net_status = WL_IDLE_STATUS;              // The Wifi radio's status
WiFiServer server(80);           // Create server object on port of WiFi
                                 // server, which will be used to
                                 // respond to commands

WiFiClient *clients[MAX_CLIENTS] = {NULL};    // Create client objects
                                              // limited to size of
                                              // MAX_CLIENTS

byte mac[] = {0xDE,0xAD,0xBE,0xEF,0xFE,0xED}; // Arduino's physical MAC
byte ip[] = {192,168,9,25};              // IP of this controller
byte gateway[] = {192,168,0,1};          // Router address (internet)
byte subnet[] = {255,255,0,0};           // Subnet mask

unsigned long wd_Dside, wd_Cside = millis();   // Gather current tstamp
unsigned long wd_Delap, wd_Celap = 0;          // Create an elapsed time
                                               //counter

void setup(){

   pinMode(4, OUTPUT);                 // pin selected to control D SIDE
   pinMode(5, OUTPUT);                 // pin selected to control C SIDE

   //enable serial data print
   Serial.begin(9600);
   while (!Serial){
       Serial.println("No serial.");
   }

      Serial.println("Serial.begin was initiated.");

   if (WiFi.status() == WL_NO_SHIELD) {  // check for the WiFi module:
      Serial.println("Wi-Fi: Communication with NINA has failed!");
      // do nothing here
      while (true);
   }

   String fv = WiFi.firmwareVersion();
   if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
      Serial.println("Please upgrade the firmware");
   }

   while (net_status != WL_CONNECTED) {
      Serial.print("Attempting to connect to WPA SSID: ");
      Serial.println(ssid);

      // Connect to WPA/WPA2 network:
      net_status = WiFi.begin(ssid, pass); // Attempt to join this SSID

      // wait 5 seconds for connection:
      delay(5000);

      listNetworks();

      server.begin();                      // Start Wi-Fi server
      Serial.print("Server started on ");
      Serial.println(WiFi.localIP());
    }
}

void loop() {

    delay(5);

    WiFiClient newClient = server.available(); // Begin listening for
                                               // client messages
    if (newClient) {
        Serial.println("New client discovered."); // Could use this as
                                                  // an ACK/handshake on
                                                  // client-side host
        for (int i=0; i<MAX_CLIENTS; i++) {
          if (clients[i] == NULL) {
            clients[i] = new WiFiClient(newClient);
            break;
      }
   }
}

    for (int i=0; i<MAX_CLIENTS; i++){      // Check client for data
      if (clients[i] != NULL && clients[i]->available()){
         // If the data isn't garbage and the data is available..

        char newChar = clients[i]->read();
        // Read the data

        if (newChar == 'x') {
        // Check for a termination character for separation

        // Now parse with strtok in order to get parameterization
          char delimiters[] = ",";
          char* valIndex;
          valIndex = strtok(inputs[i], delimiters);
          for (int j=0; j < 2; j++){
            // Expand later to largest anticipated character count
            msg_array[j] = atoi(valIndex);
            Serial.print(msg_array[j]);
            valIndex = strtok(NULL, delimiters);
          }

          switch(msg_array[0]) {
          // Determine type of message received (Character 0 parsed as
          // Message Type)

            case '3':
            // Examine string for client cmds to turn sides on or off.
            if(msg_array[1] == '1')
            // Msg type 3, Instruction 1: Turn D side ON
              {
                digitalWrite(4, HIGH);
                // Set pin 4 high
                Serial.println("Dside started.");
                wd_Delap = 0;
                // Reset elapsed time watchdog time value for D side.
                wd_Dside = millis();
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '2')
            // Msg type 3, Instruction 2: Turn D side OFF
              {
                digitalWrite(4, LOW);
                // Set pin 4 low
                Serial.println("Dside stopped");
                wd_Delap = 0;
                // Reset elapsed time watchdog time value for D side.
                wd_Dside = millis();
                // Last good heartbeat from client device on D side.
              }
            if(msg_array[1] == '3')
                // Msg type 3, Instruction 3: Turn C side ON
              {
                digitalWrite(5, HIGH);
                // Set pin 5 high
                Serial.println("C side started.");
                wd_Celap = 0;
                // Reset elapsed time watchdog time value for C side.
                wd_Cside = millis();
                // Last good heartbeat from client device on C side.
              }
            if(msg_array[1] == '4')
                // Msg type 3, Instruction 4: Turn C side OFF
              {
                digitalWrite(5, LOW);
                // Set pin 5 low
                Serial.println("C side stopped.");
                wd_Celap = 0;
                // Reset elapsed time watchdog time value for C side.
                wd_Cside = millis();
                // Last good heartbeat from client device on C side.
              }
            break;

            case '6':

                // Examine string for another message type TBD
            break;

            default:
              Serial.println("Default break. Received crap.");
            break;

          }

        inputs[i][0] = '\0';
        // Clear out this array element for the next message
        // clients[i]->stop();
        // By default, kill client session, just wait for new TCP open
        // delete clients[i];
        // Remove client element's data
        // clients[i] = NULL;
        // Reset to NULL

        }

        else {

           if (strlen(inputs[i]) > MAX_LINE_LEN) {
                // First check for size compliance
           Serial.println("Max line length exceeded from client.");
           inputs[i][0] = '0';
                // Clear out this array element for the next message
           }
           else {
           **strcat(inputs[i], newChar);**
                // Add character to the received string
           }

          Serial.println();
          Serial.println(newChar);
        }
      }

    // Update watchdog timers

    wd_Delap += (millis()-wd_Dside);
    wd_Celap += (millis()-wd_Cside);

    if (wd_Delap>=60000)
          {
            Serial.print("Elapsed time on watchdog, D side: ");
            Serial.println(wd_Delap);
            Serial.print("Last message received: ");
            Serial.println(wd_Dside);
            digitalWrite(4, LOW);    // set pin 4 low
            Serial.println("D side didn't hear from a client in 60s;
                           defaulting to OFF.");
          }

    if (wd_Celap>=60000)
          {
            Serial.print("Elapsed time on watchdog, C side: ");
            Serial.println(wd_Celap);
            Serial.print("Last message recieved: ");
            Serial.println(wd_Cside);
            digitalWrite(5, LOW);    // set pin 5 low
            Serial.println("C side didn't hear from a client in 60s;
                            defaulting to OFF.");
          }

   }
}

```

I previously had this compiling and running, though with issues that I intedned on iteratively troubleshooting. Now it won't compile because of the following error:

> arduino:302:37: error: invalid conversion from 'char' to 'const char\*' \[-fpermissive\]
>
> strcat(inputs\[i\], newChar); // Add character to the received string

..which I have attempted to bold above in the final else clause. I realize these parameters require pointers, but it seems like some of the other functions like strtok and strlen which ask for pointers as well seem to work okay in my code.

Are there any suggestions or alternatives to strcat() as to how I could make this work? I have mostly stuck with character arrays instead of declaring String objects. I am also obviously pretty rusty at C(++) as I haven't been actively working with it in a while.

Thank you

# Answer
> 1 votes
`strcat` is a function to concatenate strings. It expects a char array as second parameter. You have only a single char `newChar` to add to your string.

```
size_t l = strlen(inputs[i]);
inputs[i][l] = newChar;
inputs[i][l + 1] = 0;

```

Note: It would be better to track the length of the `inputs` then use `strlen`. `strlen` iterates over the array until terminating zero.

---
Tags: arduino-uno, wifi, arduino-uno-wifi, strlen
---


# Question
Title: Understanding datasheet of a HCHO gas sensor
I have a gas sensor whose datasheet is attached:
DS-HCHO

Now it says that UART communication is needed (P2P) where it (module) waits for Data Frame before tx the data frame to host which I need.

All i know is that I can send start bit in I2C but how shall I proceed. Also if I have multiple sensors how shall I connect them to ESP-32?

# Answer
First, you need to be communicating by UART, *not* I2C. That means using Serial or some similar object (On ESP32 you can define your own on whatever pins you want). However, the datasheet omits one vital piece of information: the baud rate it communicates at - so you will have to guess that and try various different standard baud rates until you find the one that works.

Then you have to send the "Give me the data" instruction. The module then responds with the data.

For example (untested):

```
HardwareSerial mySerial(1);

#define PIN_RX 21
#define PIN_TX 22

void setup() {
    Serial.begin(115200);
    mySerial.begin(9600, SERIAL_8N1, PIN_RX, PIN_TX); // This is the one you need to guess since the DS omits it...
}

void setup() {

    // Once a second send the request to get the data

    static uint32_t ts = millis();
    if (millis() - ts > 1000) { // Once a second
        ts = millis();
        // "Give me the data"
        mySerial.print("\x42\x4d\x01\x00\x00\x00\x90");
    }

    // When 10 or more bytes have arrived then assume that they are correctly
    // framed and print them.  Really it should read one byte at a time and
    // look for the correct start sequence of 0x42 0x4d 0x08 and read only
    // from there, but this will server for demonstration purposes.

    if (mySerial.available() >= 10) { // We expect 10 bytes returned
        uint8_t packet[10];
        mySerial.readBytes(packet, 10);
        Serial.print("ID:   ");
        Serial.println(packet[3]);
        Serial.print("UNIT: ");
        Serial.println(packet[4]);
        Serial.print("VH:   ");
        Serial.println(packet[5]);
        Serial.print("DHH:  ");
        Serial.println(packet[6]);
        Serial.print("DLL:  ");
        Serial.println(packet[7]);
        Serial.print("LRCH: ");
        Serial.println(packet[8]);
        Serial.print("LRCL:   ");
        Serial.println(packet[9]);
    }
}

```
> 0 votes

---
Tags: sensors, i2c, uart
---


# Question
Title: to increase the reading and writing/printing speed of data from Arduino Nano to Raspberry Pi 3B+
In my project, I have to read the input pin number(send by RPi), where 8 sensors are attached to Arduino Nano, after reading Arduino Nano send the real-time values of all sensors through serial USB communication. All is fine, but my problem is that I need to speed up the sending of data since it takes to long to read from Rasberry pi. I put the delay of 70 milliseconds but if I try to reduce more than that, I encounter a problem i.e data overwrites. My baud rate is 115200. Kindly help me with the code to make it fast.

```
int analogInputPin;
float voltage;

void setup() {
  // initialize serial communications at 9600 bps:
  Serial.begin(115200);
}

void loop() {
  // if any data on the serial port are available
  // read it and try to update the analogInputPin
  // based on the number that was read on the serial
  if (Serial.available() > 0) {
    analogInputPin = Serial.parseInt();
  }

  // read the analog value:
  int analogInputPinValue = analogRead(analogInputPin);
  voltage=(5./1023.)*analogInputPinValue;

  // print the results to the serial port:
  // the output should have the following form: INPUTPIN:VALUE
  // followed by a newline character
  Serial.print(analogInputPin);
  Serial.print(":");
  Serial.print(voltage);
  Serial.println("");

  // wait 50 milliseconds before the next loop
  delay(50);
}

```

# Answer
`parseInt` reads digits and stops after a non-digit characters occurs or the function times out because no next characters arrives. The timeout is at default 1 second. So this is where you loose time.

Simplest solution for your code is to send some non-digit character after the number sent from Raspberry. This will terminate parseInt immediately. Usual is to send a new line character. It will separate the numbers nice if you debug the communication with prints to serial terminal.

Not a very good option, but I mention it, is to set the timeout of blocking read functions like the `parseInt` to a smaller time with `Serial.setTimeout(ms)`.

To really speed up the communication you would send the numbers in binary form and not as text like you do now.
> 1 votes

---
Tags: arduino-nano
---


# Question
Title: How to return Char Array Value in Arduino IDE Function?
**Function**

```
char* getConnectDetail(int starting){
  String data;
  for(int i=0;i< 1024 ;i++) {
    if(EEPROM.read(i+starting) != 0){
    data += char(EEPROM.read(i+starting));
    }
   }

   int str_len = data.length() + 1;
  char char_array[str_len];
  data.toCharArray(char_array, str_len);
  return char_array;
}

```

When I call it I get the garbage value... without creating the function there isn't any error.. Kindly solve it. I just want to know whats wrong with my returning method.

# Answer
> 1 votes
`char char_array[str_len];` is local to the function - it is created on function entry and its memory is released on function exit. The contents of that memory are undefined once it has been released and its data may or may not be valid.

If the caller creates `data` and passes it to the function, it survives the entire function call-and-return, and the caller will find the correct data in it. Another (less elegant) way to do it is to make `data` a global object, which again, gives it a lifetime greater that that of the function, but globals are subject to accidental over-writes and abuse by other functions, so they are not recommended unless they are truly the best solution in a given situation.

---
Tags: arduino-uno, arduino-ide, array, functions
---


title: Motor with sinusoidal motion

text:
# Question
Title: Motor with sinusoidal motion
I need to run a motor to have a harmonic motion with specified amplitude and frequency ( harmonic motion mean that the angular position of the motor is a sine function of the time). I’m Looking to do a specified number of sinusoidal oscillations. I don't know how to tell the motor that I want the speed to be a sine function of the time. Any ideas? Also, I’m still beginning of the project? Hence I’m pretty flexible to choose any motors (DC/servo/stepper/ brushless motor) or any controller but the system has to be precise. If you guys know what controllers that allow that kind of motion, please let me know! Thank you :)

**EDIT**: so what I'm trying to do is making rheometer which measures the rheological properties of a material. Basically, there are two measuring methods available: Rotational tests and oscillatory tests. With rotational measurements, the measuring bob turns in one direction. In an oscillatory test, the measuring bob "oscillates" around the axis.

what my focus is to with oscillatory tests with set sinusoidal oscillation. The basic principle of an oscillatory rheometer is to induce a sinusoidal shear deformation in the sample and measure the resultant stress response; the time scale probed is determined by the frequency of oscillation, ω, of the shear deformation. In a typical experiment, the sample is placed between two plates, as shown in the below image While the top plate remains stationary, a motor rotates the bottom plate, thereby imposing a time-dependent strain γ(t)=γ ·sin(ωt) on the sample. Simultaneously, the time-dependent stress σ (t) is quantified by measuring the torque that the sample imposes on the top plate.

So to able to do above testing I need to run the motor with sinusoidal oscillation with exact angle.Hope you get it what im trying to say? does anyone know any motor controllers that allow that kind of motion ? or any hints how do i wet my feet? cheers!!

# Answer
Your best option would be:

* To have a DC motor with a reduction box so that it spins at lower speeds (Lets say 300 rpm) and have an encoder to count the steps. Either put the encoder before the reduction box (here it can be used a low resolution encoder, like 16 positions) or after the reduction (here you would like a more precise one, such as those 1024 positions).
* To have a Stepper motor, which will give a good angular control as long as it doesn't misses steps (if there is too much torque it will halt its movement, and you will lose count of the angle you have already displaced).

Now, to get the motor to move in a way that its angular position is of the form theta(t) = A\*sin(ωt) you would have to write some code that moves the motor to each position you want. And the difficulty of it will depend a lot on the amplitude (A) and angular speed (ω) you require.

Obs: feel free to alter/add info here
> 1 votes

---
Tags: motor, arduino-due, stepper-motor
---


# Question
Title: Why Won't my Serial Read value stay the same
I am trying to write to serial to control the brightness of an LED. When I initially type in a value such as '50' or '100', the LED lights up, but then the 'ppm' value drops down to '10' and just stays there (regardless of what I enter in initially. **Any idea why this is occurring?**

```
int ledpin1 = 3;
int pwm = 0;

void setup() {
  // initialize serial communication at 9600 bits per second:
  Serial.begin(9600);
  pinMode(ledpin1, OUTPUT);
}

// the loop routine runs over and over again forever:
void loop() {
  // reads input to serial monitor
  if (Serial.available() > 0) {
    pwm = Serial.read();
  }

  analogWrite(ledpin1, pwm);
  Serial.print("PWM value is: ");
  Serial.println(pwm);
  delay(1000);

}

```

# Answer
When you type "100" you aren't sending the number 100. You're sending the characters "1", "0", "0", and whatever selected line ending you have (CR, LF, or CR and LF).

So if you have CR+LF for your line ending you're reading the numbers 49, 48, 48, 13 then 10.

You need to read the characters as they arrive and group them into a representation of the number (up until you get the line ending), then convert that representation into an actual number.
> 3 votes

---
Tags: serial, pwm
---


# Question
Title: How to delegate code compilation to a remote machine?
Sometime I write Arduino code on a slow Windows laptop that I use for controlling hardware projects and 3D printing.

My main Windows computer and also my Linux home server are located somewhere else but are much faster and I would like to use those for compilation.

Remote Desktop or equivalent are not practical due to different screen resolutions. Also, my main Windows machine is not always on, only the server is, but it has no GUI installed.

The sources are already located on a shared network folder and I use an external editor for the code. Arduino IDE just does compilation and sometimes upload (which often I could do via OTA).

How to delegate compilation of Arduino projects to a remote machine?

# Answer
If you don't have a GUI, you can still compile and upload sketches by using the Arduino CLI. With it you can do most things, that you can do with the Arduino IDE. I'm using this myself to upload new code to a Nano, that is connected to a Raspberry Pi in a project in use.

You can connect via ssh to the remote server and let it compile/upload the sketch. I wrote a simple bash script to first copy the source to the server (since you are using a network share, this is not necessary for you) and invoke the compilation and upload.

Note: Before you can actually compile with the Arduino CLI, you have to download the correct core for your chip. This is described in the README of the linked github project.
> 0 votes

---
Tags: arduino-ide, compile
---


# Question
Title: How to connect LED lights for 3D Printed Robot
I'm new here and a newbie in electronics. I have a project to create a 3d printed robot with lights. I came across neopixels led's and the ardruino microcontrollers recently and find it to be a great possible sollution for what I need.

For my project, the 3d printed toy will have several parts that would need lights and I plan to use roughly over 40 LEDs connected to one source. I' m thinking of using the WS2812B LEDs.

I plan to use one neopixel ring for the robot's chest similar to Iron-Man's arch reactor.. While the head head will have 2x LEDs for the eyes, a smaller neopixel ring for the headpiece, another 2x LEDs for on the side of the robot mouth and 3x LEDs inside each vents on both sides of the robots head.

I need all the LEDs to turn on with a white light with a switch and turn red with another button. Although, I'd still be happy if they can only work with white.

For the power source, I was thinking about using a small powerbank or 2x 18650 batteries as the power source.

As mentioned, I'm very new to electronics and based on my research so far, i get confused really fast from all the jargons used and I'm not sure how to proceed.

Hopefully, i can get some answers here.

So.... My question is, is it possible to connect all the LEDs i plan to use on one microcontroller (ie: Ardruino Uno or Nano)

Most of the examples I can see on youtube are projects using LED strips. Are they diffrences in the way they are connected?

Another problem is coding for the ardruino..i'm totally clueless.

Any suggestions or help would be very much appreciated.

# Answer
The key point for WS2812B LEDs is, that they can be daisy chained. This means, that everyone of them has one data input and 1 data output. If you connect the data output of one LED to the data input of the other, you created a short strip with 2 LEDs. Doing this multiple times creates a bigger LED strip. It's not relevant, if the LEDs are arranged into a physical strip, or arranged into complex forms. The LEDs are addressed by their position in the strip. The microcontroller sends a data stream to the first LED. It will read the first 3 bytes (1 byte per color) and forward the rest of the stream to it's data output, so to the next LED.

So you can wire all the LEDs on your robot in a way, that you basically only have 1 LED strip. In this case you only need 1 pin on your Arduino (plus Vcc and ground of course).

Or, if it's to cumbersome to wire all LEDs together, you can make multiple strips, divided by zones on your robot (like 1 strip for the face, 1 strip for the chest, ...). Every strip will need it's own pin on the Arduino.

Which way you go is your decision and also depends on how many pins you have free.

> My question is, is it possible to connect all the LEDs i plan to use on one microcontroller (ie: Ardruino Uno or Nano)

Yes, one microcontroller is plenty enough for this. As I wrote, for 1 strip you only need 1 data pin.

> Most of the examples I can see on youtube are projects using LED strips. Are they diffrences in the way they are connected?

This depends on what strips they have. If they use WS2812B strips, it is all the same. As said, the physical arrangement of the LEDs doesn't matter. But there are also other types of strips, for example the not-individually-addressable-single-color types, or the not-individually-addressable-RGB types (which often have one PWM line per color).

> Another problem is coding for the ardruino..i'm totally clueless.

Have a look at the Adafruit Neopixel library or the FastLED library (both on github). They are libraries, that will hide most of the complexity from you and will make it easy to control the LEDs. They both have examples, that you can use to get started. Adafruit also has good tutorials for this. You can google them.

> For the power source, I was thinking about using a small powerbank or 2x 18650 batteries as the power source.

I don't know, how much current these batteries can give you. I will leave that to you for your research. But be sure, that you can always provide the needed current. One WS2812B LED can draw up to 60mA (20mA per color), if you set them to full brightness white. So 40 WS2812B LEDs, can draw up to 2.4A. I guess, that your robot also has motors, which can also draw a big amount of current. So keep the total current draw in mind and don't ever try to draw this current through the Arduino (since this might fry the voltage regulator).
> 1 votes

---
Tags: led
---


# Question
Title: ESPAsyncWebServer how do you escape the % character?
% characters are used for template processing but I want it to just send the % through. How do you tell it to do that?

# Answer
> 2 votes
You'd use `%%` to get a single `%` as output.

From the source code: double percent sign encountered, this is single percent sign escaped.

---
Tags: programming
---


# Question
Title: Why does a function inside void set up is repeating after some minutes
I am trying to time sync my arduino hardware to NTP server. I have a \`setSyncProvider(getNtpTime)´ function to do it and called inside the void setup. I have another function (mainFunction) inside the main loop, that calls every minute. I have added a function to display time inside this mainFunction so that time will update every minutes. Code works fine for first five minutes. Then it calls the getNtpTime again even though it is not inside the loop. Why is it happening?

```
time_t getNtpTime()
{
  while (Udp.parsePacket() > 0) ; // discard any previously received packets
  Serial.println("Transmit NTP Request");
  sendNTPpacket(timeServer);
  uint32_t beginWait = millis();
  while (millis() - beginWait < 1500) {
    int size = Udp.parsePacket();
    if (size >= NTP_PACKET_SIZE) {
      Serial.println("Receive NTP Response");
      Udp.read(packetBuffer, NTP_PACKET_SIZE);  // read packet into the buffer
      unsigned long secsSince1900;
      // convert four bytes starting at location 40 to a long integer
      secsSince1900 =  (unsigned long)packetBuffer[40] << 24;
      secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
      secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
      secsSince1900 |= (unsigned long)packetBuffer[43];
      return secsSince1900 - 2208988800UL + timeZone * SECS_PER_HOUR;
    }
  }
  Serial.println("No NTP Response :-(");
  return 0; // return 0 if unable to get the time
}

```

# Answer
> 1 votes
The `setSyncProvider` function of the TimeLib sets a function which will be called by the library every `interval` seconds. The `interval` is set with `setSyncInterval`. Default interval is 300 seconds.

---
Tags: arduino-mega, time
---


# Question
Title: LED fader function freezes and becomes unresponsive after a few cycles
My LED controller has a color fader mode that I am making. The controller's loop() function grabs incoming serial data to set the amount of colors, fade speed, mode, and other info then runs the correct mode with the colors that it read from the serial port

When in color fader mode, the controller "freezes" at a certain color and becomes unresponsive to further input until I unplug it and plug it back in or reupload the code (the latter means that it still responds to something).

For testing purposes I am using red, green, and blue in that order. This stopping color can happen anywhere from in the middle of the transition from red to green in the first cycle to going through multiple cycles and stopping on blue depending on the fade speed. This only became a problem after I switched from using delay() to millis(). Why is that and what can I do to fix it?

The reason I switched to using millis is because the delays would stack infinitely and the arduino would become unresponsive to commands

Here is my relevant code:

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

#define NUMPIXELS 60
#define DATAPIN    4
#define CLOCKPIN   5

Adafruit_DotStar strip(NUMPIXELS, DOTSTAR_BRG);

// Variables
int mode;
int numColors;
int fadeSpeed;
int BBCC;
int R[100];
int G[100];
int B[100];
int Bright[100];

int currColor;

void setup() {

#if defined(__AVR_ATtiny85__) && (F_CPU == 16000000L)
  clock_prescale_set(clock_div_1); // Enable 16 MHz on Trinket
#endif
  strip.begin(); // Initialize pins for output
  strip.show();  // Turn all LEDs off ASAP

  currColor = 0;
}

void loop() {
  strip.show();                     // Refresh strip
  delay(20);                        // Pause 20 milliseconds (~50 FPS)

  getData();

  switch (mode)
  {
    case 1:                  // Mode 1: Solid Color
    {
      for (int i = 0; i < NUMPIXELS; i++)
      {
        if (i % 2 == 0)
          strip.setPixelColor(i, G[0], R[0], B[0]);// Sets whole strip to Color 1
      }
      strip.setBrightness(Bright[0]);
      strip.show();
      break;
    }
    case 2:                  // Mode 2: Multi Color Fader
    {
      colorFade();
      break;
    }
    case 3:                  // Mode 3: Multi Color Pattern
    {
      int j = 0;
      for (int i = 0; i < NUMPIXELS; i++)
      {
        if (i % 2 == 0)
        {
          strip.setPixelColor(i, G[j], R[j], B[j]); // sets a repeating pattern
          if (j == (numColors - 1))
            j = 0;
          else
            j++;
        }
      }
      strip.setBrightness(Bright[0]);
      strip.show();
      break;
    }
    case 4:                  // Mode 4: Music-Reactive Wave Form
    {

      break;
    }
    case 5:                  // Mode 5: Music-Reactive Color Jump
    {

      break;
    }
    default:                 // Default Mode: Incandecent Simulation
    {
      for (int i = 0; i < NUMPIXELS; i++)
      {
        if (i % 2 == 0)
          strip.setPixelColor(i, 150, 200, 40); // Sets whole strip to default value
      }
      strip.setBrightness(255);
      strip.show();
      break;
    }
  }

}

void colorFade()
{
  int del = 100;     // 100 milisecond
  if (currColor >= numColors - 1)
  {

    int steps = fadeSpeed * del;
    int Rdiff, Gdiff, Bdiff, BrightDiff;

    Rdiff = R[0] - R[currColor];
    Gdiff = G[0] - G[currColor];
    Bdiff = B[0] - B[currColor];
    BrightDiff = Bright[0] - Bright[currColor];

    for (int i = 0; i <= steps + 5; i++)
    {
      for (int j = 0; j < NUMPIXELS; j++)
      {
        if (j % 2 == 0)
          strip.setPixelColor(j, (G[currColor] - (Gdiff * i)), (R[currColor] - (Rdiff * i)), (B[currColor] - (Bdiff * i))); // Sets whole strip to value
      }
      //strip.setBrightness((Bright[currColor] - (BrightDiff * i)));
      strip.show();
      //delay(del);
      int timer = millis() + del;
      while(millis() < timer)
      {

      }
    }
    currColor = 0;
  }
  else
  {
    int steps = fadeSpeed * del;
    int Rdiff, Gdiff, Bdiff, BrightDiff;

    Rdiff = R[currColor + 1] - R[currColor];
    Gdiff = G[currColor + 1] - G[currColor];
    Bdiff = B[currColor + 1] - B[currColor];
    BrightDiff = Bright[currColor + 1] - Bright[currColor];

    for (int i = 0; i <= steps + 5; i++)
    {
      for (int j = 0; j < NUMPIXELS; j++)
      {
        if (j % 2 == 0)
          strip.setPixelColor(j, (G[currColor] - (Gdiff * i)), (R[currColor] - (Rdiff * i)), (B[currColor] - (Bdiff * i))); // Sets whole strip to value
      }
      //strip.setBrightness((Bright[currColor] - (BrightDiff * i)));
      strip.show();
      //delay(del);

      int timer = millis() + del;
      while(millis() < timer)
      {

      }
    }
    currColor++;
  }
}

```

# Answer
> 0 votes
The problem with the above code lies with overflow. timer should be an unsigned long, because millis() outputs an unsigned long. This causes the freeze because after timer hits its upper limit, This setup works better:

```
unsigned long timer = (unsigned long)millis() + del;
      while((unsigned long)millis() < timer)
      {
        //wait for as long as del says to
      }

```

This setup should be able to run for a long time without overflowing

---
Tags: rgb-led, led-strip
---


# Question
Title: I fried the AMS1117 voltage regulator on my Arduino Clone, is this the cause?
I had the 12V DC power jack plugged-in all the time, and "to make things more exciting" I also plugged-in the "data" USB whenever I had a new sketch to upload. Is this combination a big no-no, or is my step-up converter to blame?

I am completely new to this stuff but now when thinking of it those 12V from the power jack + 5V from the "data" USB probably violate this clause:
*If using more than 12V, the voltage regulator may overheat and damage the board.*

# Answer
> 5 votes
The "problem" with the AMS1117 voltage regulator is the amount of current they can safely provide drops as the input voltage rises. I'm a Arduino noob, so I looked at the data sheet for the AMS1117 series of voltage regulators. There is a formula: PD=(VIN-VOUT)(IOUT) and Note 2: which says the maximum power dissipation for the SOT-223 package is 1.2 W.

The best case scenario is to use an input voltage of 6.5 volts. (6.5-5)(0.8)=1.2W. This gives you 0.8 amps maximum output. If you use a 12 volt power supply: (12-5)(0.1714)=1.2W. This only gives you 0.1714 amps maximum output.

I'm not sure what kind of power jack you are using, so I'll give you an example of one that I used in a project. It says input 120VAC, output 12VDC, 200ma. The problem is, it actually puts out 20VDC open circuit with no load.

The data sheet gives a maximum input voltage of 15 volts but that would only provide a maximum of 120 mA output.

# Answer
> 3 votes
Probably not. There is nothing fundamentally wrong with what you're doing - it's within the design parameters. In particular:

* 12V is within the 7-12V recommended range specified for that input. Yes, it means the regulator will get hotter, but the AMS1117 is supposed to be current limited and thermally limited so should just start shutting down if it supplies too much current or gets too hot. As this answer suggests, it would be wise to limit it to 1.2W, which is 171mA. That's plenty for the Arduino itself, so you'd only be running into trouble if you have other peripherals to power.
* The Arduino Uno has circuitry specifically designed to disconnect the USB's 5V rail if the external power supply is present. This is really only to protect the USB supply from being damaged by the external power supply - the Arduino doesn't care as long as it is getting 5V from somewhere. The USB data function is independent of whether the 5V comes from the USB's 5V rail or the 5V generated from the external supply you provide. The AMS1117 itself, according to its (various) datasheet, has no design susceptibility to an alternate 5V supply being on the output.

Finally, there's an alternate reason for the failure. We've also been using an Arduino Uno clone with the AMS1117, and have also been supplying 5V external (directly to the 5V rail in our case) as well as connecting to USB for programming. We've also had an AMS1117 fail, despite operating everything within normal limits. Our symptoms are that the OUT pin is shorted to the GND pin. Removing the regulator restores full functionality.

Based on various reports around the Internet of suspect behaviour and doubtful provenance of these chips on the clone boards, I would suggest that a faulty IC might be the root cause.

---
Tags: power, clones
---


# Question
Title: 3.3 V Arduino Pro Mini and nRF24L01 issues
I have a 3.3 V Pro Mini connected to nRF24l01 as xmtr. The nRF24L01 does not respond to the Pro Mini. Any help will be appreciated.

I have attached the print detail output:

```
Transmitter 2  Started
STATUS       = 0xff RX_DR=1 TX_DS=1 MAX_RT=1 RX_P_NO=7 TX_FULL=1
RX_ADDR_P0-1     = 0xffffffffff 0xffffffffff
RX_ADDR_P2-5     = 0xff 0xff 0xff 0xff
TX_ADDR      = 0xffffffffff
RX_PW_P0-6   = 0xff 0xff 0xff 0xff 0xff 0xff
EN_AA        = 0xff
EN_RXADDR    = 0xff
RF_CH        = 0xff
RF_SETUP     = 0xff
CONFIG       = 0xff
DYNPD/FEATURE    = 0xff 0xff
Data Rate    = 1MBPS
Model        = nRF24L01
CRC Length   = 16 bits
PA Power     = PA_MAX

Transmitter 2 Started
STATUS       = 0x0e RX_DR=0 TX_DS=0 MAX_RT=0 RX_P_NO=7 TX_FULL=0
RX_ADDR_P0-1     = 0xe8e8f0f0e2 0xc2c2c2c2c2
RX_ADDR_P2-5     = 0xc3 0xc4 0xc5 0xc6
TX_ADDR      = 0xe8e8f0f0e2
RX_PW_P0-6   = 0x20 0x00 0x00 0x00 0x00 0x00
EN_AA        = 0x3f
EN_RXADDR    = 0x03
RF_CH        = 0x73
RF_SETUP     = 0x07
CONFIG       = 0x0e
DYNPD/FEATURE    = 0x03 0x06
Data Rate    = 1MBPS
Model        = nRF24L01+
CRC Length   = 16 bits
PA Power     = PA_MAX
voltage = 3.97 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.97
voltage = 3.85 V
voltage = 3.79 V
voltage = 3.75 V
voltage = 3.73 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.73
voltage = 3.70 V
voltage = 3.68 V
voltage = 3.65 V
voltage = 3.62 V
0
RSLT (1 = success) 0
Data Sent 3.00  0.00  3.62
voltage = 3.58 V
voltage = 3.54 V
voltage = 3.50 V
voltage = 3.45 V
0

```

The top transmitter output is before I changed the nRF24L01 module which appeared to be bad. The second transmitter started output. Module is good but nRF24L01 would not connect to receiver with 3.3 V Pro Mini. It connects if I use a Nano.

# Answer
> voltage = 3.97 V 0 RSLT (1 = success) 0 Data Sent 3.00 0.00

nrf24l01 is a 3.3V device, Where'd that come from?
> 1 votes

# Answer
LM317T set to 3.25 Volts and 220uF tantalum on the nrf24L01.

Pro mini and nrf24L01 powered by 3.25V works a treat. :-)

Problem with arduino nano is that the USB from laptop is 5V and that is a killer for the nrf24L01! If using serial.write to send data to a serial monitor through the nano's USB insure that the power and levels are not 5V on the nrf24L01.
> 0 votes

# Answer
Promini 3.3V regulator is also only good for 150mA. I think the nrf24L01 needs more current than that.
> -1 votes

---
Tags: nrf24l01+
---


title: Mega2560 has 2 Crystal Oscillator?

text:
# Question
Title: Mega2560 has 2 Crystal Oscillator?
Who knows this Mega2560 with two Crystal Oscillators: 12 000 MHz and 16 000 MHz? What is the use of them?

# Answer
There are two devices on an Arduino board than need a clock source:

* The ATMega328 / ATMega2560 main MCU (16MHz)
* The USB interface.

The USB interface crystal speed depends on what device is used on your board. Genuine Arduino boards use an ATMega16U2 which uses a 16MHz crystal. Cheap Chinese clones use a CH340G which takes a 12MHz crystal.

Note that normally it's one crystal and one ceramic resonator. USB requires very precise timing, so a crystal is used for that. The main MCU doesn't need quite such precise timing, so a cheaper (and less accurate) ceramic resonator is used.
> 1 votes

---
Tags: arduino-mega
---


# Question
Title: How to program micro chips directly with USB
Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?
Where can i find information on the protocols/standards to do such a thing?

More specifically, I want to be able to make a custom pcb for my Attiny85 chips with a usb connector. I would prefer not to use the arduino IDE.
Is it possible to program this chip like so?

# Answer
> 2 votes
> Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

The bare chip? Generally, no.

*Some* chips that include USB hardware also may include a DFU bootloader in ROM. If your chosen chip has this, then yes you can - you just need to wire it up and use a suitable DFU firmware upload program to install your compiled code into the chip.

However chips that don't have USB will *never* have a USB DFU bootloader in them. In such cases is is *your* responsibility to create (or otherwise obtain) a suitable bootloader that *you* will install into the chip.

Digispark and Adafruit both do that. They take a chip that doesn't have USB and install software that tries to (poorly) emulate USB over GPIO pins1.

For chips that do not have actual USB hardware in them it is far more common to use a UART-based bootloader - simply because this is a much lighter and more "correct" way of doing it.

If you want to use a direct USB connection for your device you should be selecting a chip that has USB built into it (AVR "U" series2, most PIC32, many ARM-based chips) which will allow you to have *proper* USB communication instead of slow HID and custom (non-standard) protocols only3.

Note that at no point does your choice of bootloader, or method of communication with the bootloader, tie you in to using the Arduino IDE. The IDE just compiles the code then runs an external program that communicates with the bootloader (different bootloaders need different programs to communicate with them). How you compile the software is up to you. How you execute the bootloader upload program is up to you.

---

1. Personally I think that's a *horrible* idea and should *NEVER* be done. I'm a purist though.
2. Such as the ATMega32U4 used on the Leonardo and Micro boards.
3. VUSB can only (barely) run fast enough for USB 1.1. That means only HID protocols are officially supported (keyboard and mouse), and anything else is non-standard and requires special supporting software to work with it.

# Answer
> 1 votes
> Is it possible to program chips like the Arduino uno's Atmega328P directly with USB serial from your computer?

Put a bootloader on the chip first, then an offboard USB/Serial adapter can be used for the serial programming. That's basically what a ProMini is - a bootloaded '328P (in SMD form) with a resonator & decoupling caps and a small voltage regulator - and a header to accept an FTDI Basic for programming serially. If you notice the Black and Green colors next to the FTDI header, those are to match the wire colors on the the FTDI cables that were originally used, before seperate USB cable and FTDI modules became more popular.
https://www.sparkfun.com/products/9718

Instead of the 6-pin FTDI header, you could make an adapter board to go from FTDI to a USB-A 5-pin connector, then on your board have a USB-B-Mini or USB-B-Micro 5-pin connector to bring in the FTDI's 5V, Gnd, DTR, Tx, and Rx signals.

USB wouldn't be coming in directly, but you would have the spacing advantage of the small USB connector, and could program serially from a PC USB port.

Too bad you don't want to use the Arduino IDE, there are supported core codes to add to the IDE for the Attiny85 and other chips like that. Attiny85 with bootloader could then be serially programmed with an offboard USB/Serial adapter.

https://github.com/SpenceKonde/ATTinyCore

> ATtinyCore Universal
>
> This core supports the following processors - essentially every ATtiny processor that makes sense to use with Arduino. Click the processor name for part-specific information:
>
> ATtiny2313, 4313
>
> ATtiny24, 44, 84 (With or without Optiboot bootloader)
>
> ATtiny25, 45, 85 (With or without Optiboot bootloader)
>
> ATtiny261, 461, 861 (With or without Optiboot bootloader)
>
> ATTiny87, 167 (with or without Optiboot bootloader)
>
> ATTiny48, 88 (With or without Optiboot bootloader)
>
> ATTiny441, 841 (With or without Optiboot bootloader)
>
> ATTiny1634 (With or without Optiboot bootloader)
>
> ATTiny828 (With or without Optiboot bootloader)
>
> ATtiny43 (no bootloader)

---
Tags: arduino-uno, serial, usb, serial-data, attiny85
---


# Question
Title: Dc motor backvoltage, how to place the diode correctly?
My previous questions have been anwsered, so thank you all for that!

I make a new question post because I have some other problems with my setup. I use a esp12s 8266 chip. It sends a PWM signal to a n-channel mosfet, so I can regulate the speed of the dc motor that is attached to the drain of the mosfet. The DC motor has extra power from a 9v battery and this battery negative is connected to the GND of the 8266. I can control it with bluetooth hc-05 module, it has 3 options, 40%, 0% (off) and 100% (full power).

Here's the problem: I can control everything and it seems like it works all fine, but when the motor starts spinning I see a yellow led flashing on my 8266 chip and I can't control it anymore. I read about backvoltage from the motor. So I think maybe the backvoltage is causing the chip not to function anymore. To make it work again I need to disconnect and reconnect the chip for it to work again.

So my question is: could this be the backvoltage or something else? And if it's the backvoltage how do I need to connect the diode (1n4001) in this circuit?

I read when a motor stops then the backvoltage happens, but in my case the led on the 8266 starts flashing when it spins. So maybe I hooked something the wrong way. here I have some pictures of the different setups I tried.

Of course I will solder everything nicely, but for now it's just to get a quick impression of the hookup.

Hopefully someone can help me out, thanks in advance!

# Answer
> 0 votes
> I read when a motor stops then the backvoltage happens,

That is not true. With a brushed DC motor the back-EMF ("backvoltage") occurs at least twice (often more, depending on the number of commutator segments) per revolution of the motor. Brushed DC motors are *very* noisy.

While you *can* use a diode (connected as you would for a relay) it's not the best solution. Instead you really need a proper EMI-absorbing circuit.

This consists of three capacitors - all very small values, in the range 1-10nF, which connect all parts of the motor together and bleed off any induced voltages safely.

The first capacitor connects directly across the terminals. This will safely remove the back-EMF created in the windings as the voltages switch back and forth due to the rotation of the commutator.

The other two capacitors each connect from one terminal to the metal housing of the motor (one to each side of the housing). This will safely couple the housing to the rest of the circuit and cause it to act as a shield containing the magnetic fields better within the motor.

# Answer
> 0 votes
You're looking for something called a "flyback diode."

What happens is, during "normal use" (when the DC motor is being powered by the system), you have a DC motor. But, when the system stops giving input, and the DC motor "spins down," it can become a power generator -- generators and motors are actually very much the same, it just depends on if they're generating the power, or using the power.

The idea with the flyback diode is that it doesn't let that generated current "back" into the system, and burn up your MCU. I've seen them in series with a small resistance, to help quickly bleed off any current/voltage the DC motor ends up generating. With it in series, the diode stops any power from being "wasted," as current will never flow "backwards" through the diode, and thus the resistor.

When you "cut the power" to the DC motor, current can then flow through the "mini-loop" and decay through the resistor (which is not pictured in this example).

# Answer
> 0 votes
Okay, I'm not sure what you're trying to accomplish, electrically, but the diagram you added doesn't make sense. It also doesn't match any of the pictures you've posted. In the diagram, you have your emitter and collector tied together with a diode... but your pictures don't have **ANYTHING** attached to your emitter leg... you have things "wrapped" around your heatsink/ground, for some reason?

So we'll ignore the pictures that don't make actual circuits, and focus on your diagram. In the diagram, you've accomplished this:

If you look at this, the diode is doing nothing -- your BJT already has Miller resistance between the emitter and collector, so the diode does nothing for you, here. You also don't need any capacitors, as you are not looking to **store** any power, for any reason. Because of this, I've changed it to a resistor (R4).

What you're really looking for is something more along these lines:

With this, your 9V battery will only power the motor when the BJT is on (your Pin10 is HIGH). This completes the circuit, and current flows through your motor. The diode (D1) prevents any current from flowing through the resistor (R2), and no power is lost.

When you turn your motor "off" by setting Pin10 to LOW, kinetic energy will cause your motor to "continue spinning" a little bit -- it's not going to just stop dead, since that energy needs to go somewhere. This little bit of remaining spin turns your DC motor into a DC generator, and it provides its own power. This current/voltage needs to go somewhere, or you'll burn things up.

This is where the diode (D1) and resistor (R2) come in handy. That current can now flow through the mini-loop, and bleed-off this induced power -- or flyback voltage spike -- which is why it's called a "flyback diode." You're trying to bleed-off that power, not store them, so you need a resistor instead of a capacitor.

So lose the caps, substitute with a resistor, and move your flyback diode.

---
Tags: esp8266, motor, battery, mosfet
---


title: expected initializer before 'RF24'

text:
# Question
Title: expected initializer before 'RF24'
The code i make is this \*/

```
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
#include <Servo.h>
#define CE_PIN   9
#define CSN_PIN 10

const uint64_t pipe = 0xE8E8F0F0E1LL;
int servoy;
int servox;
Servo Yservo;
Servo Xservo;

RF24 radio(CE_PIN, CSN_PIN);

int joystick[2];

void setup()RF24
{
  Serial.begin(9600);
  delay(1000);
  radio.begin();
  radio.openReadingPipe(1,pipe);
  radio.startListening();
  Xservo.attach(3);
  Yservo.attach(5);
}

void loop()
{
  if ( radio.available() )
  {
    bool done = false;
    while (!done)
    {
done = radio.read( joystick, sizeof(joystick) );
servox= joystick[0]/5.683;
servoy= joystick[1]/5.683;
      Serial.println(servoy);
      Yservo.write(servoy);
      Serial.println(servox);
      Xservo.write(servox);
    }
  }
  else
  {
      Serial.println("NO RADIO CONECTION");
  }

}

```

and i don't know what happen it's said that

```
 sketch_aug20b_rc_rc_rc_22:33:13: error: expected initializer before 'RF24'

 void setup()RF24

             ^

C:\Users\ASUS\Documents\Arduino\sketch_aug20b_rc_rc_rc_22\sketch_aug20b_rc_rc_rc_22.ino: In function 'void loop()':

sketch_aug20b_rc_rc_rc_22:51:6: error: void value not ignored as it ought to be

 done = radio.read( joystick, sizeof(joystick) );

      ^

exit status 1
expected initializer before 'RF24'

```

# Answer
You have two problems:

```
sketch_aug20b_rc_rc_rc_22:33:13: error: expected initializer before 'RF24'

void setup()RF24

         ^

```

It's basically saying "I don't understand what you mean by RF24 here". That `RF24` in that line should not exist. I assume you made some kind of typo or copy-pasta error.

Second:

C:\Users\ASUS\Documents\Arduino\sketch\_aug20b\_rc\_rc\_rc\_22\sketch\_aug20b\_rc\_rc\_rc\_22.ino: In function 'void loop()':

```
sketch_aug20b_rc_rc_rc_22:51:6: error: void value not ignored as it ought to be

 done = radio.read( joystick, sizeof(joystick) );

```

That is saying that `radio.read` doesn't return a value - yet you are trying to assign that value that doesn't exist to something.

According to the documentation for `RF24::read()`:

> Read the available payload
>
> The size of data read is the fixed payload size, see getPayloadSize()
>
> **Note**
>
> I specifically chose 'void\*' as a data type to make it easier for beginners to use. No casting needed.
>
> No longer boolean. Use available to determine if packets are available. Interrupt flags are now cleared during reads instead of when calling available().
>
> **Parameters**
>
> * `buf` Pointer to a buffer where the data should be written
> * `len` Maximum number of bytes to read into the buffer
>
> if(radio.available()){ radio.read(&data,sizeof(data)); }
>
> **Returns**
>
> No return value. Use available().
> 1 votes

---
Tags: nrf24l01+
---