message:
How to make Arduino react to serial information?

I want to write a program that allows me to control the LED connected to pin 13 of the Arduino. When the program is started, the LED should be off. The user should open the serial monitor to communicate with the Arduino. If the user sends the character '1' through the serial monitor then the LED should turn on. If the user sends the character '0' through the serial monitor then the LED should turn off.

So I tried:

    void setup()
    {
      pinMode(13, OUTPUT);
    }

    void loop()
    {
      int bytenum = Serial.available();
      if (bytenum != 0)
      {
        int bval = Serial.read();
        if (bval != 0)
        {
      digitalWrite(13, HIGH);
        }
      }
      digitalWrite(13, LOW);
    }

But when launching it the LED never light up:

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/WwLeG.gif

body:
I see two issues:

**1. Sketch**

The line:

    digitalWrite(13, LOW);

is always executed, meaning the LED (which might be broken, see below), is on for a very small time, probably not enough to be visible.

You can use the next sketch (for 0 and 1 to switch it off/on):

    const uint8_t LED = 13;

    void setup()
    {
      pinMode(LED, OUTPUT);
      digitalWrite(LED, LOW);
    }

    void loop()
    {
      while (available_characters != 0)
      {
        switch (Serial.read())
        {
          case '0':
            digitalWrite(LED, LOW);
            break;

          case '1':
            digitalWrite(LED, HIGH);
            break;

          default:
            // Ignore
            break;
        }
      }
    }

You can make this sketch smaller in case you want '0' for off, and anything else for on:

    const uint8_t LED = 13;

    void setup()
    {
      pinMode(LED, OUTPUT);
      digitalWrite(LED, LOW);
    }

    void loop()
    {
      while (Serial.available() != 0)
      {
        digitalWrite(LED, Serial.read() == '0' ? LOW : HIGH);
      }
    }

**2. Lack of a resistor**

I think your LED is now broken, and hopefully only the LED and not your Arduino.

Always use a resistor just before or after the LED when connecting a LED. As a guideline, use e.g. 220R or 330R.

Remember as formula:  V = I * R

The tricky thing is that LEDs have a forward voltage (Vf), so the actual formula is:

     (V - Vf) = I * R

Now most LEDs can handle mostly 20 mA, but 10 mA is more than enough to make them bright.

Below is a list of typical values for the forward voltage. Let's assume it's 1.8V as you are using a red one in your example.

[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/5dlYs.png

The MINIMUM resistor value to be used is:

    (5 V - 1.8 V) = 0.01 A * R <=>
    3.2 V = 0.01 A * R <=>
    R = 320 ohm

So use a 330 ohm resistor. (note that 220 ohm will still result in less than 20 mA).


sender: user

message:
UNO R3 + WiFi ATmega328P+ESP8266 (32Mb memory) USB-TTL CH340G For Arduino Uno - External ESP8266 Pins

[This][1] board have pins to ESP8266's GPIOs.

What is `Tout` pin ?
On the back of the board it label pins :`GPIO12`, `GPIO02`, and **another** `GPIO02` ? a continuity test shows that they are not connected. So what is it ?

[![pic][2]][2]

  [1]: https://www.aliexpress.com/item/33006588335.html?spm=a2g0s.12269583.0.0.5c4c4e9fviBsDu
  [2]: https://i.stack.imgur.com/LLKZz.png

sender: assistant

body:
From esp8266 datasheet:

>TOUT - ADC pin. It can be used to test the power-supply voltage of VDD3P3 (Pin3 and Pin4) and the input power voltage of TOUT (Pin 6). However, these two functions cannot be used simultaneously.

from [the pinout PDF][1] of [the Uno+WiFi board][2]:

[![enter image description here][3]][3]

  [1]: https://robotdyn.com/pub/media/0G-00005215==UNO+WiFi-R3-AT328-ESP8266-CH340G/DOCS/PINOUT==0G-00005215==UNO+WiFi-R3-AT328-ESP8266-CH340G.pdf
  [2]: https://robotdyn.com/uno-wifi-r3-atmega328p-esp8266-32mb-flash-usb-ttl-ch340g-micro-usb.html
  [3]: https://i.stack.imgur.com/DIuTT.png


message:
Serial Monitor stops working when using PinMode

I'm having a lot of trouble with my recent Arduino sketch. I need to reset an IC by setting a pin high then low. I also am using the serial monitor for some testing but as soon as I try and do a Serial.print, nothing appears. My Arduino is also on a custom PCB, where D7 is connected to the IC's (MAX3421) reset pin, and also to the Arduino's reset pin.
To try and make my issue clearer, ill post some code and the serial monitor output below:

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

      pinMode(7, OUTPUT);
    }

    void loop()
    {
      Serial.println("TEST");
    }

[nothing in serial monitor]

-----------

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

      //pinMode(7, OUTPUT);
    }

    void loop()
    {
      Serial.println("TEST");
    }

[lots of TESTs]

Any help is appreciated,
Thomas

body:
My issue was that pin 7 was connected to the reset pin on the Arduino, meaning every time it was set to output, the Arduino was reset.
You can see this here:

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

      Serial.println("a");

      delay(100);

      pinMode(7, OUTPUT);
    }

    void loop()
    {
      Serial.println("test");
    }

which outputs a stream of a's separated by 100ms (plus a bit)


message:
4 Bit Counter up and down

we are asked to create an Arduino code that would run a 4 Bit Binary UP counter once a push button switch is pressed and then 4 Bit Binary Down counter on the second click. Then vice versa. This should be done using only one switch. I figured out the Count up portion but I don't know how to add the count down code for the same switch. Can someone help me with this. Thank you.
**please see below for my program**
[![enter image description here][1]][1]

```
int buttonState = 0;
int timer = 300;
int pin8 = 8;
int pin9 = 9;
int pin10 = 10;
int pin11 = 11;

void setup()
{
pinMode(7,INPUT);
pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);

}

void loop()
{
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
buttonState = digitalRead(7);

if(buttonState == HIGH)
{
digitalWrite(pin8, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
delay(timer); //bit 1
digitalWrite(pin9, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
delay(timer); //bit 2
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
delay(timer); //bit 3
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin10, LOW);
delay(timer); //bit 4
digitalWrite(pin8, HIGH);
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin10, LOW);
delay(timer); //bit 5
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
delay(timer); //bit 6
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
delay(timer); //bit 7
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin11, LOW);
delay(timer); //bit 8
digitalWrite(pin8, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 9
digitalWrite(pin9, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 10
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 11
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 12
digitalWrite(pin8, HIGH);
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin8, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 13
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 14
digitalWrite(pin8, HIGH);
digitalWrite(pin9, HIGH);
digitalWrite(pin10, HIGH);
digitalWrite(pin11, HIGH);
delay(timer);
digitalWrite(pin9, LOW);
digitalWrite(pin9, LOW);
digitalWrite(pin10, LOW);
digitalWrite(pin11, LOW);
delay(timer); //bit 15
}
}
```

  [1]: https://i.stack.imgur.com/Qy3Vm.png

body:
Currently you are just setting the LEDs manually one after another in your code. That is not actually a binary counter (as it is most likely wanted by the exercise), but only looks like one.

First you need to understand, what a counter really is: Basically it is just a variable, that holds a number. Where exactly this variable is saved, is not important. For your case you would use a variable in your code. The Counter/Timer hardware in the Arduino uses a fixed SFR (Special Function Register) for it.

That the counter is 4bit, means, that its value is hold by only 4 bits. That gives you a value range from 0 to 15 (`2^4` values). So a 4bit counter variable would count from 0 to 15. You could just have a counter variable, that you could increment or decrement (depending on the direction, that you want to count).

    // Declare counter variable and initialize with zero
    int counter_variable = 0;
    // Increment
    counter_variable++;
    // or Decrement
    counter_variable--;

For the "binary" part: Here it is important to understand, that the decimal number from 0 to 15 is already saved in the variable as binary (since microcontrollers/computers only know binary, nothing else). So you can write out the state of the 4 least significant bytes of the counter variable:

    digitalWrite(pin8  ,counter_variable & 0b0001);
    digitalWrite(pin9  ,counter_variable & 0b0010);
    digitalWrite(pin10 ,counter_variable & 0b0100);
    digitalWrite(pin11 ,counter_variable & 0b1000);

The `&` is a bitwise AND. The result of the operation will only leave bits set, when they are set on both sides. So here we are isolating the corresponding bits. `digitalWrite()` will interpret anything but zero as HIGH. Thus the pin is set HIGH, if the corresponding bit is set in `counter_variable`. But you see, that we are repeating us here. We could use a for loop and define our pins in an array:

    // at global scope
    int led_pins[4] = {8, 9, 10, 11};

    // in the button if statement
    for(int i=0; i<4; i++){
        digitalWrite(led_pins[i], counter_variable & (1 << i));
    }

We have organized the pins of the LEDs in an array, so they can be easily indexed. Then we are looping through the pins array and setting the pins similar to the last version. But now we are using `(1 << i)`. The `<<` operator shifts the bits of the number before it by the number of digits, that comes after it. Decimal `1` is binary `0b0001`. So, when `i` is 2 (for example), this would shift the bits 2 digits to the left, giving you `0b0100`. We are just generating the same bit patterns as in the last version.

But we can even optimize further via direct port manipulation. Inside the microcontroller the output pins are controlled via simple Special Function Registers. They work somewhat like a variable. All output pins are organized into socalled "Ports" (groups of up to 8 pins). Each port has one `PORTx` registers (where `x` stands for the character associated with that port), which sets the state of the pins, if they are in output mode. Setting the corresponding bit in the correct `PORTx` register will set the pin to HIGH. Clearing the bit (setting to zero) will set the pin to LOW.

You are using the Arduino pins 8 to 11. If you look at a pinout diagram of the Arduino Uno, you will see, that these pins are also marked as `PB0` to `PB3`, which stands for "Port B, pins 0 to 3 (inside that port)". The corresponding `PORTx` register is `PORTB`. So we can set all pins of the port at once by assigning a new value to that register. The following code would set an alternating on/off pattern for all 8 pins of PORTB:

    PORTB = 0b10101010;

Now we only want to use the lowest 4 bits and set them to the values, that our counter variable has. So we are masking away the 4 higher bits with the bitwise AND operator and then assign that value to the register:

    PORTB = counter_variable & 0b00001111;

So now the if statement in `void loop()` might look like this (using a for loop):

    if(buttonState == HIGH){
        // count up counter variable
        for(int counter_variable=0; counter_variable < 16; counter_variable++){
            // write out to the pins
            PORTB = counter_variable & 0b00001111;
            // delay a bit to show the value
            delay(timer);
        }
    }

And now we want that each consecutive button to count in the other direction than before. So we can declare another variable as direction and then use another if statement, to switch between two for loops:

    // On global scope
    int direction = 1;

    // in void loop()

    if(buttonState == HIGH){
        if(direction == 1){
            // count up counter variable
            for(int counter_variable=0; counter_variable < 16; counter_variable++){
                // write out to the pins
                PORTB = counter_variable & 0b00001111;
                // delay a bit to show the value
                delay(timer);
            }
            // change direction
            direction = -1;
        } else {
            // count up counter variable
            for(int counter_variable=15; counter_variable >= 0; counter_variable--){
                // write out to the pins
                PORTB = counter_variable & 0b00001111;
                // delay a bit to show the value
                delay(timer);
            }
            // change direction
            direction = 1;
        }
    }

Note:

- This is probably not the most efficient way, but I think it is quite understandable (which is also important).
- This still uses much `delay()` calls, just as your code. That will make your button unresponsive. The counter must first finish, before the button will react again. That might be ok for you. If not, you need to restructure the program for using a non-blocking coding style like in the `BlinkWithoutDelay` example from the Arduino IDE (using `millis()`). There are lots of tutorials about that on the web.
- When using a non-blocking coding style, you also need to check the button for the transition to HIGH, instead for the state high. Otherwise the code would run only, while the button is pressed.
- Buttons bounce, when being pressed. So there are many transitions between HIGH and LOW for a few ms, when the button is pressed. In the code above this is not important, because the started counter needs so long, that every bounce is finished after the counter finished. With code, that needs less than a few ms, you might get into problems there. I would suggest the `Bounce2` library for that. It handles the bounce detection for you.


message:
Calculate battery (18650 Li-ion) voltage using ESP8266-12E

i am trying to calculate the battery voltage using ESP-12E module. I am using a voltage divider circuit to calculate the same. Here is how my circuit looks like:

[![enter image description here][1]][1]

And here is how my code looks like:

    float volt =0.0;
    float temp=0.0;
    float r1=320000.0;
    float r2=100000.0;

    void setup(){
        Serial.begin(115200);
        Serial.println(String(VoltageCalculator()).c_str());
    }

    float VoltageCalculator(){
      for (int thisReading = 0; thisReading < numReadings; thisReading++) {
        readings[thisReading] = 0;
      }
      Serial.println(analogRead(A0));
      for(int i = 0;i<=10; i++){
        total = total - readings[readIndex];
        // read from the sensor:
        readings[readIndex] = analogRead(A0);
        // add the reading to the total:
        total = total + readings[readIndex];
        // advance to the next position in the array:
        readIndex = readIndex + 1;

        // if we're at the end of the array...
        if (readIndex >= numReadings) {
          // ...wrap around to the beginning:
          readIndex = 0;
        }

        // calculate the average:
        float analogvalue = total / numReadings;

        //  int analogvalue = analogRead(A0);
        temp = (analogvalue * 3.3) / 1024.0;
        volt = temp / (r2/(r1+r2));
      }

      if(DEBUG_ENABLE){
        Serial.println();
        Serial.print("Actual Voltage : ");
        Serial.print(volt);
        Serial.println();
      }

      float volt_percent;

      if(volt == 3.1){
        volt_percent = 0;
      } else{
        float volt_diff = volt - 3.1;
        volt_percent = (volt_diff/1.1)*100;
        if(DEBUG_ENABLE){
          Serial.println();
          Serial.print("Voltage percentage : ");
          Serial.print(volt_percent);
          Serial.println();
        }
      }
      return volt_percent;
    }

When i use this circuit with NodeMCU it works very fine, but when it comes to ESP-12E module it do not show the proper voltage. on `Serial.println(analogRead(A0));` always shows 1024.

Any suggestions why this is happening and how can i do this to achieve the most accurate value?

  [1]: https://i.stack.imgur.com/kMJwp.png

body:
Everything was correct and my circuit is also good. The only difference i found is to this below line:

`temp = (analogvalue * 3.3) / 1024.0; `

Which should be

`temp = (analogvalue * 1.0) / 1024.0;`

We are multiplying because we are referencing the voltage from voltage divider circuit as 1 volt.

After doing this, i am getting the exact values battery voltage which then i convert to percentage.

Thank you!


message:
Error Compiling for board Arduino Nano while using Adafruit GFX

Whys is this happening to me??
I have to meet a deadline please help!!
Here is my code.

    #include <SPI.h>
    #include <Wire.h>
    #include <Adafruit_GFX.h>
    #include <Adafruit_SSD1306.h>

    #define SCREEN_WIDTH 128 // OLED display width, in pixels
    #define SCREEN_HEIGHT 64 // OLED display height, in pixels

    // Declaration for SSD1306 display connected using software SPI (default case):
    #define OLED_MOSI   11
    #define OLED_CLK   12
    #define OLED_DC    9
    #define OLED_CS    8
    #define OLED_RESET 10
    Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT,
      OLED_MOSI, OLED_CLK, OLED_DC, OLED_RESET, OLED_CS);
    void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color);
    void setup()
    {
      Serial.begin(9600);

      // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
      if(!display.begin(SSD1306_SWITCHCAPVCC)) {
        Serial.println(F("SSD1306 allocation failed"));
        for(;;); // Don't proceed, loop forever
    }

      display.display();
      delay(2000);

      display.clearDisplay();

      display.drawPixel(10, 10, SSD1306_WHITE);

      display.display();
      delay(2000);
      display.invertDisplay(true);
      delay(1000);
      display.invertDisplay(false);
      delay(1000);

      }
    void loop()
    {
    drawLine(20,60,5,50,256);

    }
The Error

> C:\Users\hp\AppData\Local\Temp\ccyB6dO1.ltrans0.ltrans.o: In function
> `loop':
> C:\Users\hp\Desktop\Sunfox\Sunfox\BP_Plus_ECG\February_11\OLED_Testing_w_Adafruit\Test_2\Test_2/Test_2.ino:51:
> undefined reference to `drawLine(unsigned int, unsigned int, unsigned
> int, unsigned int, unsigned int)' collect2.exe: error: ld returned 1
> exit status exit status 1 Error compiling for board Arduino Nano.

body:
Currently, you defined a forward declaration for `drawLine`, however I assume you want to call the method (function) inside `display`.

So change

    drawLine(20,60,5,50,256);

into

    display.drawLine(20,60,5,50,256);

And you can remove the forward declaration, because this method is already defined in the library.

    void drawLine(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, uint16_t color);

Note, if you call `drawLine` without an instance (which is `display`), then the linker tries to find the `drawLine` function which it cannot find, so you get a linker error (see `ld returned` in your error, together with `undefined reference`).


message:
Programming custom Arduino Mega with Arduino Uno

I'm making a custom board with AtMega2560-16AU as MCU and CH340G as bootloader (schematic can be seen in the picture).  I have printed the custom PCB and soldered everything in place now I want to program the bootloader.

[![pcb schematic][1]][1]

I connected my Arduino UNO with my custom board like shown in the fritzing schematic below. My custom pcb doesn't look like Arduino MEGA but the connections are the same.

[![connections][2]][2]

I go to Arduino IDE and upload the ArduinoISP example (baudrate:115200) while choosing programmer as "Arduino as ISP".
[![step 1][3]][3]

And when I upload the example I get a response like this:

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

             System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM4
             Using Programmer              : arduino
             Overriding Baud Rate          : 115200
             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.00s

    avrdude: Device signature = 0x1e950f (probably m328p)
    avrdude: reading input file "C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex"
    avrdude: writing flash (4354 bytes):

    Writing | ################################################## | 100% 0.68s

    avrdude: 4354 bytes of flash written
    avrdude: verifying flash memory against C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex:
    avrdude: load data flash data from input file C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex:
    avrdude: input file C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex contains 4354 bytes
    avrdude: reading on-chip flash data:

    Reading | ################################################## | 100% 0.53s

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

    avrdude done.  Thank you.

As far as I know so far there's no problem.

And now I move to step 2 which now requires me to switch the board to ArduinoMega from tools. And click burn bootloader.
[![enter image description here][4]][4]

When I click burn bootloader I get a response like this:

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

             System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

             Using Port                    : COM4
             Using Programmer              : stk500v1
             Overriding Baud Rate          : 19200
             AVR Part                      : ATmega2560
             Chip Erase delay              : 9000 us
             PAGEL                         : PD7
             BS2                           : PA0
             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    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
               flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
               lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
               lock           0     0     0    0 no          1    0      0  9000  9000 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 : STK500
             Description     : Atmel STK500 Version 1.x firmware
             Hardware Version: 2
             Firmware Version: 1.18
             Topcard         : Unknown
             Vtarget         : 0.0 V
             Varef           : 0.0 V
             Oscillator      : Off
             SCK period      : 0.1 us

    avrdude: AVR device initialized and ready to accept instructions

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0xffffff (probably .avr8x_mega) (retrying)

    Reading | ################################################## | 100% 0.02s

    avrdude: Device signature = 0x000000 (retrying)

    Error while burning bootloader.
    Reading | ################################################## | 100% 0.02s

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

    avrdude done.  Thank you.

Now when I clicked burn the bootloader I got a response saying invalid signature.
So far I tried to:

 1. Change baudrates and try the same steps.
 2. Tried to change the avrdude.txt file. I tried to change the
    signature that was searched for which I couldn't change it because
    windows 10 wouldn't allow me even though I gave myself all the admin
    permissions.

So as a solution to this signature problem people have put an electrolytic capacitor that has 10nF or 10uF value between GND and RST pins of the programmer Arduino.

Also when I tried this for the first time I got a value different than "Off" for oscillator in the 2nd step.

So what should I do? Do I need to change my oscillator and try again or do I need that polarized 10uF capacitor?

Sorry for poorly formatting this post. Thank you so much for reading. Any answers would be appreciated.

  [1]: https://i.stack.imgur.com/zmrEi.png
  [2]: https://i.stack.imgur.com/jHzx3.png
  [3]: https://i.stack.imgur.com/8KPIz.png
  [4]: https://i.stack.imgur.com/jEGpX.png

body:
I finally found the problem with this board. I had a 22pF capacitor between RST and GND on the board I had ordered.

You should not have a capacitor there or it should be 100nF, values such as 22pF or 10nF will cause the board to malfunction and therefore you can't burn the bootloader.


message:
How can I stop my servo looping when my sensor doesn't detect movement?

I have this project with my Arduino UNO where I want my servo motor SG90 to go full speed to 180 degrees when the PIR sensor sends HIGH value and go slowly back to zero when the value is LOW.

I have this code working where the servo goes full speed back to zero:

```c++
#include <Servo.h>

Servo myservo; //creates a servo object
int pos = 0; //variable to store servo position
//amount of time we give the sensor to calibrate(10-60 secs according to the datasheet)
int calibrationTime = 30;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pir = 12; //digital pin connected to the PIR's output
int pirPos = 13; //connects to the PIR's 5V pin

void setup() {
  myservo.attach(4); //attaches servo to pin 4
  Serial.begin(9600); //begins serial communication
  pinMode(pir, INPUT);
  pinMode(pirPos, OUTPUT);
  digitalWrite(pirPos, HIGH);
  //time for calibration

  Serial.println("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
  }
  Serial.println();
  Serial.println("done");

  //this waits until the PIR's output is low before ending setup
  while (digitalRead(pir) == HIGH) {
    delay(500);
  }

  Serial.print("SENSOR ACTIVE");
}

void loop() {
  if (digitalRead(pir) == HIGH)
    myservo.write(180);              // tell servo to go to position in variable 'pos'
  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    myservo.write(0);              // tell servo to go to position in variable 'pos'
  Serial.print("Motion ended!");
}
```

I'd like the servo to go slowly back to zero, so I tried this :

```c++
#include <Servo.h>

Servo myservo; //creates a servo object
int pos = 0; //variable to store servo position
//amount of time we give the sensor to calibrate(10-60 secs according to the datasheet)
int calibrationTime = 30;
//the time when the sensor outputs a low impulse
long unsigned int lowIn;
//the amount of milliseconds the sensor has to be low
//before we assume all motion has stopped
long unsigned int pause = 5000;
boolean lockLow = true;
boolean takeLowTime;
int pir = 12; //digital pin connected to the PIR's output
int pirPos = 13; //connects to the PIR's 5V pin

void setup() {
  myservo.attach(4); //attaches servo to pin 4
  Serial.begin(9600); //begins serial communication
  pinMode(pir, INPUT);
  pinMode(pirPos, OUTPUT);
  digitalWrite(pirPos, HIGH);

  //time for calibration
  Serial.println("calibrating sensor ");
  for (int i = 0; i < calibrationTime; i++) {
    Serial.print(calibrationTime - i);
    Serial.print("-");
    delay(1000);
  }
  Serial.println();
  Serial.println("done");

  //this waits until the PIR's output is low before ending setup
  while (digitalRead(pir) == HIGH) {
    delay(500);
  }

  Serial.print("SENSOR ACTIVE");
}

void loop() {
  if (digitalRead(pir) == HIGH)
    myservo.write(180);              // tell servo to go to position in variable 'pos'

  Serial.print("Motion detected!");

  if (digitalRead(pir) == LOW)
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      delay(15);                       // waits 15ms for the servo to reach the position
    }

  Serial.print("Motion ended!");
}
```

The problem is with this code the servo does go slowly back to zero but then goes full speed back to 180 and again and again ....

Any idea? I'm a beginner in Arduino, so I assume it must not be that hard to figure out.
Thanks.

body:
Don't set the pos to 180 in the `(digitalRead(pir) == LOW)` branch if you do not want it to repeatedly jump up to 180 for as long as the condition is true.

    void loop() {
      if (digitalRead(pir) == HIGH)
         pos = 180;
      myservo.write(pos);              // tell servo to go to position in variable 'pos'

      Serial.print("Motion detected!");

      if (digitalRead(pir) == LOW)
        for (; pos > 0; pos -= 1) { // decay to 0 degrees
          myservo.write(pos);              // tell servo to go to position in variable 'pos'
          delay(15);                       // waits 15ms for the servo to reach the position
        }

      Serial.print("Motion ended!");
    }

Alternately, you could use `pos` as a state variable and simplify things:

    void loop() {
      if (digitalRead(pir) == HIGH)
         pos = 180;
      elif (pos > 0 ){
         pos--;
         delay(15);
      }
      myservo.write(pos);
    }


message:
Issue with simple timer based on millis()

Sorry to bother but I am at my wits end. I'm experimenting with timers, and starting very simple. The following code is supposed to print the content of a variable each time an interval of time has passed, then update that variable. But for some reason I'm getting no output on the serial monitor.

I have used the serial monitor before on other projects without issue, so I'm not sure what the problem could be.

Is there any error in my code?

```
unsigned long previousMillis = 0;
unsigned long currentMillis = millis();
const long interval = 1000;

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

void loop() {
  if (currentMillis - previousMillis >= interval) {
    Serial.println(previousMillis);
    previousMillis = currentMillis;
  }
  else {
    ;
  }
}

//  previousMillis += interval;
```

body:
Since `currentMillis` is just a simple variable, it will not automatically update. In fact the initialization with `millis()` in global scope is unnecessary. Just initialize the value with 0. At the time, where the global variables are created, the time is 0ms anyways.

You need to update the `currentMillis` variable everytime, before using it. So just insert

    currentMillis = millis();

right at the start of the `loop()` function.


message:
How to make car turn 90 degrees?

I have an elegoo car model and am trying to make it turn 90 degrees whenever it gets to a 90 degree turn. This model has line tracing and it works fine on curved surfaces but doesn't work so on 90 degree turns.

        /Line Tracking IO define
    #define LT_R !digitalRead(10)//connected to pin 10. Value is inverted
    #define LT_M !digitalRead(4)
    #define LT_L !digitalRead(2)

    #define ENA 5//input to enable motor A. Controls speed
    #define ENB 6//input to enable motor B
    #define IN1 7//Control spinning direction of motor A. If one of them is high motor spin(an OR gate)
    #define IN2 8//Same motor A
    #define IN3 9//3 and 4 are for motor B
    #define IN4 11

    #define carSpeed 100

    void forward(){ //car goes forward
      analogWrite(ENA, carSpeed);
      analogWrite(ENB, carSpeed);
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);
      Serial.println("go forward!");
    }

    void back(){ //car goes backwards
      analogWrite(ENA, carSpeed);
      analogWrite(ENB, carSpeed);
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, HIGH);
      digitalWrite(IN3, HIGH);
      digitalWrite(IN4, LOW);
      Serial.println("go back!");
    }

    void left(){ //goes left
      analogWrite(ENA, carSpeed);
      analogWrite(ENB, carSpeed);
      digitalWrite(IN1, LOW);
      digitalWrite(IN2, HIGH);
      digitalWrite(IN3, LOW);
      digitalWrite(IN4, HIGH);
      Serial.println("go left!");
    }

    void right(){ //goes right
      analogWrite(ENA, carSpeed);
      analogWrite(ENB, carSpeed);
      digitalWrite(IN1, HIGH);
      digitalWrite(IN2, LOW);
      digitalWrite(IN3, HIGH);
      digitalWrite(IN4, LOW);
      Serial.println("go right!");
    }

    void stop(){ //power is shut off
       digitalWrite(ENA, LOW);
       digitalWrite(ENB, LOW);
       Serial.println("Stop!");
    }

    void setup(){
      Serial.begin(9600);
      pinMode(LT_R,INPUT);//takes input from all the sensors
      pinMode(LT_M,INPUT);
      pinMode(LT_L,INPUT);
    }

    void loop() {

      if(LT_M){
        forward();
        while(LT_M);
      }
      else if(LT_R) {
        right();
        while(LT_R);
      }
      else if(LT_L) {
        left();
        while(LT_L);
      }

      else if (LT_M && LT_R && !LT_L) {
      delay(500);
      right();
      }

      else if (LT_L && LT_R && !LT_R) {
       delay(500);
       left();
        }

body:
First: Your code as 2 problems:

- As stated in the comments by PeterPaulKiefer, when you use

        pinMode(LT_R,INPUT);

    That is not working as intended by you. `LT_R` is defined at the top as

        #define LT_R !digitalRead(10)

    Thus the compiler will see

        pinMode(!digitalRead(10), INPUT);

    `digitalRead()` will return zero or one, thus you are configuring pin 0 or pin 1 here (depending on the state of the sensor at startup). Instead you need to directly use the pin number (10) or use another define for the pin number itself. Your code only works, because all the pins are configured as INPUT (tristate) at startup of the microcontroller, so that they don't break something with a wrong signal. You got lucky there.

- The last two else if statements are never executed:

        else if (LT_M && LT_R && !LT_L) {
            delay(500);
            right();
        }
        else if (LT_L && LT_R && !LT_R) {
            delay(500);
            left();
        }

    The conditions here will first evaluate `LT_M` (in the first statement) and `LT_L` (in the second statement) respectively. Only if these are true, the rest of the expression will be evaluated. But you already checked for both of them being true above. When they are, the following else if statements don't get executed (thats the logic of if else statements). And if they are false, the code will also not be executed.

    When you get to a 90° right corner, the middle and right sensor will trigger. Currently this will lead to the robot just keeping going forward.

So you need to change your code to actually check every every possible combination of the sensor states.

Also keep in mind, that a sharp corner needs way more turning, than a curve. Depending on the width of the line are the distance between your sensors, you might or might not be able to distinguish between those two cases. You should analyze, which sensor states you would have in which situations, write that down and then write code for every state. You could also put all sensor states into one single number, so that it is easier to check for it in the code. Something like this:

    byte all_states = digitalRead(2) + 2*digitalRead(4) + 4*digitalRead(10);

Each combination will give you a unique number to work with. Effectively this stores the states of the sensors in one bit of the number each. Bit 0 is for pin 2, bit 1 is for pin 4 and bit 2 is for pin 10. You can also write this with bitwise operators:

    byte all_states = digitalRead(2) | (digitalRead(4)<<1) | (digitalRead(10)<<2);

For example: If the right sensor is triggered, but not the others, you would get a binary number `0b00000100`, which is decimal `4`. If the left and the middle sensor are triggered, but not the right one, this results in `0b00000011`, which is decimal `3`. Then you could check with a switch statement:

    switch(all_states){
        case 0: //No sensors triggered
            break;
        case 1: // Left sensor triggered
            break;
        case 2: // middle sensor triggerd
            break;
        case 3: // middle and left sensor triggered
            break;
        ...
    }

You see how it works. The code for each case then goes inbetween of each case and break line.


message:
100 hz Square Wave of 50% duty cycle in digital pin 3 and verifying with pin 4

I am stuck on this for a while, I am trying to generate a 100 hz square wave with 50% duty cycle in pin 3 and trying to verify it with wire at pin 4; I am getting 64000 but not 100 in serial monitor.

```

#define LEDPIN 3

uint16_t val2= pulseIn(4, HIGH);

ISR(TIMER1_COMPA_vect) { digitalWrite(LEDPIN, !digitalRead(LEDPIN)); }
void setup() {
Serial.begin(9600);
pinMode(LEDPIN, OUTPUT);
// initialize Timer1 (the 16-bit timer) using channel A output compare
noInterrupts(); // disable global interrupts
// TIMER 1 for interrupt frequency 100 Hz:
cli(); // stop interrupts
TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
TCNT1 = 0; // initialize counter value to 0
// set compare match register for 100 Hz increments
OCR1A = 19999; // = 16000000 / (8 * 100) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);
// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei(); // allow interrupts
//TCCR1A = 0; // Timer/Counter Control Register 1A
//TCCR1B = 0; // (both control registers need to be configured)
//// set compare match register to desired timer count:
//OCR1A = 15624; // Output Compare Register 1A (i.e., for channel A)
//TCCR1B |= (1 << WGM12); // CTC (Clear Timer on Compare Match) mode
//TCCR1B |= (1 << CS10); // for 1,024 prescaler; UNO has a 16 MHz clock
//TCCR1B |= (1 << CS12);
//TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt
interrupts(); // enable global interrupts:
}
void loop() {
uint16_t val = OCR1A/8;

ICR1 = val -1;
OCR1A = val/2 - 1 ; // 50% duty cycle for pin 3
//OCR1B = val/2 - 1 ; // 50% duty cycle for pin 4
//uint16_t val2= pulseIn(4, HIGH);
Serial.print(val2);
delay(1000);
Serial.print("\n");

}

```

body:
You wrote:

```c++
uint16_t val2 = pulseIn(4, HIGH);
```

It makes no sense to call this here, as the timer has not been
initialized. You probably cannot expect anything but a timeout in this
context.

```c++
noInterrupts();
cli();
```

These two are synonyms. No need to repeat yourself. Actually, no need to
block interrupts at all.

```c++
sei();
interrupts();
```

Ditto.

```c++
OCR1A = 19999; // = 16000000 / (8 * 100) - 1
```

This is supposed to fire interrupts at 100 Hz. But if you want a
100 Hz output signal, you should fire the interrupts at 200 Hz
(two interrupts per cycle). Thus:

```c++
OCR1A = 9999; // = (16 MHz / 8) / (2 * 100 Hz) - 1
```

Then,

```c++
// Set CS12, CS11 and CS10 bits for 8 prescaler
TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);
```

This is configuring Timer 1 for an external clock source. If you
want ÷8 prescaler, you should only set bit `CS11`. Check the datasheet.

```c++
uint16_t val = OCR1A/8;
ICR1 = val -1;
OCR1A = val/2 - 1 ; // 50% duty cycle for pin 3
```

This doesn't make any sense to me. Why are you setting `ICR1`? Why are
you changing `OCR1A` although it was already configured in `setup()`?
You can remove all this. Here is the `loop()` I used for testing:

```c++
void loop() {
    Serial.println(pulseIn(3, HIGH));
    delay(1000);
}
```

And it repeatedly printed `4955`, which is quite close to the expected
value (namely 5000).


message:
How do I set up communication between the "Seeeduino Xiao" and the "Adafruit Bluefruit LE UART Friend - Bluetooth Low Energy (BLE)"?

I've seen normal Arduino boards connecting to it no problem (Uno, Nano, etc.). I'm trying to connect it to my Seeeduino Xiao. It has UART compatible pins, so I'm fairly certain wiring isn't an issue. I think I'm having a hard time with the coding.

body:
Nevermind, I figured it out. For anyone that has this problem to:

First, use the "blueart_cmdmode" example file. Then, follow these steps:

HOW TO GET THE SEEEDUINO XIAO TO WORK WITH THIS

1) Make sure the "Adafruit_BluefruitLE_UART ble(Serial1, BLUEFRUIT_UART_MODE_PIN);"
line of text above the "void error" line is UNCOMMENTED. Everything else in that
block is to still be commented.

2) Define the pins in "BluefruitConfig.h" as such:
#define BLUEFRUIT_SWUART_RXD_PIN       6    // Required for software serial!
#define BLUEFRUIT_SWUART_TXD_PIN       7    // Required for software serial!
#define BLUEFRUIT_UART_CTS_PIN         0    // Required for software serial!
#define BLUEFRUIT_UART_RTS_PIN         -1   // Optional, set to -1 if unused

3) Wire the pins as defined above.

4) Make sure the Bluefruit is switched to "CMD" mode.


message:
Where to define web server callback functions so they can access server object? (ESP8266WebServer library)

I want my ESP8266-based device to create an accesspoint that allows the user to input their home ssid and password. There is a device object that holds most of the data defined elsewhere.

I'm trying to use the ESP8266WebServer library. It requires me to define parameterless callback functions. Where should I declare and define these callback functions so that they can access the server object? In all the example code, the server object is global. I'd want to avoid that, and I'd also like to avoid having a server object as a permanent Device class member.

How should I go about this? It is not allowed to define the callback functions inside Device::getWifiCredentials, and if I declare them outside then server isn't in scope.

```
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>

// Function to create AccessPoint to get ssid and password
int Device::getWifiCredentials() {

    ESP8266WebServer server(80);
    server.begin();

    // define callbacks
    server.on("/", handleRoot); // initial page

    server.on("/ssid", handleCredentials); // catch response from initial page

    // wait for credentials to be delivered
    server.handleClient();

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

    return ACTION_SUCCESSFUL;

}

// **Where can these functions be defined to allow them to access the server object?**

void handleRoot() {
};

void handleCredentials() {

    String ssid;
    String pw;

    if( server.hasArg() ){
        ssid = server.arg("ssid");
        pw = server.arg("pw");
    }
};
```

body:
put your server declaraition outside the constructor and call a class callback :

    #include <Arduino.h>
    #include <ESP8266WiFi.h>
    #include <ESP8266WebServer.h>

    ESP8266WebServer server(80);

    // Function to create AccessPoint to get ssid and password
    int Device::getWifiCredentials() {
    server.begin();

        // define callbacks
        server.on("/", std::bind(&Device::handleRoot, this); // initial page

        server.on("/ssid", std::bind(&Device::handleCredentials, this); // catch response from initial page

        // wait for credentials to be delivered
        server.handleClient();

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

        return ACTION_SUCCESSFUL;
    }


message:
Forcing bootloader startup through program

I am trying to find out if it is possible to trigger programmatically the *double-tap on reset button* function, implemented in modified version of Atmel's SAM-BA bootloader. The board of interest is Arduino Zero.
In case this is not possible using the stock board setup, if this can be achieved by hardware or bootloader modifications.

body:
Theoretically it is quiet easy to fake that double-tap with software, but there might be some obstacles in practice.

The bootloader uses an unsigned long value in RAM memory to indicate if the double tap happend. The actual bootloader for the zero uses the following definitions.

    // zero specific; but other boards use the same values AFAIK
    // (in board_definitions_arduino_zero.h)
    #define BOOT_DOUBLE_TAP_ADDRESS  (0x20007FFCul)
    #define BOOT_DOUBLE_TAP_DATA  (*((volatile uint32_t *) BOOT_DOUBLE_TAP_ADDRESS))

    // for all bootloader (in main.c)
    #define DOUBLE_TAP_MAGIC 0x07738135

When the bootloader is started after a reset, it checks, if that was a power on reset (POR) or not. If it has been a POR, it sets the indicator value to 0 `BOOT_DOUBLE_TAP_DATA = 0;`.

If it does not detect a POR, the bootloader continues with checking the indicator value whether it is set to the tap magic.

If the magic can be found  the indicator value is set back to 0 and the bootloader is started. Otherwise the value is set to the "double tap magic": `BOOT_DOUBLE_TAP_DATA = DOUBLE_TAP_MAGIC`. The bootloader waits for 500 ms to let the user reset the zero a second time (double tap) and resets the indicator value after that time interval.

-------

**How to:**

To simulate a double tap, you just need to set the indicator variable with the magic value from within you program. Use the definitions above. Then perform a software reset.

-------

**The caveats:**

* If the bootloader was changed, that could make you code useless.
* I have not the time to test my ideas, so this is just an unverified method. It might fail for some reasons, I do not see actually.
* You have to find a method to reset the zero with the program. Iknow some methods but I've not tried any of them so far.

-------

**Reset Methods:** (as a starting point for your search)

I've read somewhere that the zero supports the CMSIS method `NVIC_SystemReset`.

This is a method often used for M0 ARM controllers (like SAMD11).

    SCB_AIRCR = SCB_AIRCR_VECTKEY(0x5FA) | SCB_AIRCR_SYSRESETREQ_MASK;

-------

Here is my code "idea" (untested):

    #define BOOT_DOUBLE_TAP_ADDRESS  (0x20007FFCul)
    #define BOOT_DOUBLE_TAP_DATA  (*((volatile uint32_t *) BOOT_DOUBLE_TAP_ADDRESS))
    #define DOUBLE_TAP_MAGIC 0x07738135

    // lots of code ....

    void resetWithDoubleTap()
    {
       BOOT_DOUBLE_TAP_DATA = DOUBLE_TAP_MAGIC;
       NVIC_SystemReset();
    }

-------

I would be lucky, if you succeed with this. Please let us know your outcomes, either write your own answer or tell me what you've done and I will correct my answer if necessary. Good luck.


message:
Firmata.SendString doesn't work with specific `char` variables

I have a Firmata sketch, that accepts string messages, partitions them and sends its' parts back to a Firmata client program. My problem is certainly at the sketch's side. The problem is that `Firmata.sendString(argument1)` and `Firmata.sendString(argument2)` methods don't send anything. More information is found in the sketch's code. How can I get the `sendString` methods to work?

```lang-CPP
/*
 * This sketch accepts strings in the following form:
 * CMDn(arg1,arg2)
 * CMDn — command name,
 * arg1 и arg2 — unnecessary arguments.
 * Each argument's length can be from 1 to 4 characters,
 * They're saved to separate variables.
 *
 * This sketch sends back the parsed commands partially:
 * the command name, argument #1 (if present), argument #2 (if present)
 */

#include <Firmata.h>

void stringCallback(char *received) {
  //CMDn(arg1,arg2)
  //CMDn(arg1)
  //CMDn(1)
  //CMDn()
  //012345678901234
  //          11111

  //This scheme up there is just for
  //understanding the indexes of the chars in the string
  //in its various possible variations

  //Let's declare all the necessary variables
  char methodName[5];
  char argument1[5];
  char argument2[5];
  byte commaLocation = 0;

  //If the received string doesn't match the strings' syntax,
  //send an error message
  if (!(received[4] == '(' && strlen(received) <= 15)) {
    Firmata.sendString("ERR;");
    return;
  }

  //Let's take the 0-3 chars in the string and send it back.
  //It's probably the command name
  for (int i = 0; i < 4; i++) {
    methodName[i] = received[i];
  }
  methodName[4] = '\0'; //does or doesn't the compiler add the terminator automatically?
  Firmata.sendString(methodName); //send it
  //This string is being sent without problems.

  //If there is some arguments in the string,
  //it is detectable if the string char 5 is not ')'/
  if (received[5] != ')') {
    //Lent's find out if the input string has a `comma`
    //inside the parentheses. If it does, it means that
    //there are two arguments in the string.

    Firmata.sendString("46 passed");
    for (int i = 6; i < (strlen(received) - 1); i++) {
      //If there is a comma, save its' index and break the loop
      if (received[i] == ',') {
        commaLocation = i;
        break;
      }
    }

    //If a comma is not present, its location variable equals 0,
    //sincerely we just collect all the chars between the parentheses
    //to the 'argument1' variable and send it.
    if (commaLocation == 0) {
      Firmata.sendString("61 passed");
      for (int i = 5; i < ; i++) {
        argument1[(i - 5)] = received[i];
      }

      argument1[strlen(argument1)] = '\0'; //Either this is executed or not, the outcome doesn't change

      Firmata.sendString(argument1); //This very command doesn't work. It just does not send anything.
                                     //Looks like 'argument1' is empty, but I'm awfully sure that it must
                                     //not be empty. Anyway, the 'argument1' does not show up in the client
    }

    //If there is a comma present, then write chars before the comma
    //to 'argument1', and after the comma - to 'argument2'
    if (commaLocation != 0) {
      Firmata.sendString("77 passed");
      //let's write what is before the comma:
      for (int i = 5; i < commaLocation; i++) {
        argument1[i - 5] = received[i];
        Firmata.sendString("81 iterator");
      }

      //let's write what's after the comma;
      char argument2[5];
      for (int i = (commaLocation + 1); i < (strlen(received)); i++) {
        argument2[(i - (commaLocation + 1))] = received[i];
        Firmata.sendString("87 iterator");
      }

      argument1[strlen(argument1)] = '\0'; //Either this is executed or not, the outcome doesn't change
      argument2[strlen(argument2)] = '\0';

      Firmata.sendString(argument1); //Not working
      Firmata.sendString(argument2); //Not working
    }
  }
}

void sysexCallback(byte command, byte argc, byte *argv) {
  Firmata.sendSysex(command, argc, argv);
}

void setup() {
  Firmata.setFirmwareVersion(FIRMATA_FIRMWARE_MAJOR_VERSION, FIRMATA_FIRMWARE_MINOR_VERSION);
  Firmata.attach(STRING_DATA, stringCallback);
  Firmata.attach(START_SYSEX, sysexCallback);
  Firmata.begin(57600);
}

void loop() {
  while (Firmata.available()) {
    Firmata.processInput();
  }
}
```

Expected output:

| What I send | What I receive (excluding the debug messages, `;` stands for newline) |
| ----------- | ------------------------------------------ |
| `DHTt()` | `DHTt` |
| `DHTt(1)` | `DHTt`; `1` |
| `DHTt(1,2)` | `DHTt`; `1`; `2` |

Real output:

| What I send | What I receive (excluding the debug messages) |
| --------    | -------------- |
| `DHTt()`    | `DHTt` *as long as there are no arguments, there are no problems. But the arguments are necessary for my task* |
| `DHTt(1)` | `DHTt` *the argument are not sent* |
| `DHTt(1,2)` | `DHTt` *two arguments are not sent neither* |

body:
Here's a simplified version of your command parser using cstrings and pointers:

```
void parseArgs(char * rec){
  char cmd[32];
  char arg1[32]= {0};
  char arg2[32]= {0};
  char * ptr; // this is a re-usable workhorse pointer
  char * ptrDelim; // another workhorse to split arguments

  // first copy all of it to cmd
  strcpy(cmd, rec);
  // find end of command
  ptr = cmd;
  while( isalpha(ptr[0]) ) ptr++;
  ptr[0] = '\0'; // mark end of command string

  // find first arg
  ptr = strchr(rec, '(')+1; // set ptr to char to right of open paren
  strcpy(arg1, ptr); // copy stuff after open paren to arg1:
  ptr = strchr(arg1, ')');// find max extent of arg1
  if(ptrDelim=strchr(arg1, ',')){
    ptrDelim[0]='\0'; // end arg1's string at delim
    ptrDelim++; // move right one char
    strcpy(arg2, ptrDelim); // copy stuff after comma
    arg2[strlen(arg2)-1] = '\0'; // chop off ")"
  }else{
    ptr[0]='\0';
  }//end if comma?

 Serial.println("\nGiven:" + String(rec)+";");
 Serial.println("Command:" + String( cmd )+";");
 Serial.println("Arg1:" + String( arg1 )+";");
 Serial.println("Arg2:" + String( arg2 )+";");

}
```

Examples:

    parseArgs("CMDn()");
    parseArgs("CMDn(arg1)");
    parseArgs("CMDn(arg1,arg2)");


body:
`Firmata.sendString` does not send anything to the client in two cases:
- If the message is empty;
- **If the message does not contain the `\0` terminator in it**.

In this case, while you're sending `methodName`, you're manually assigning the terminator to the string; and the sender works:
```c++
methodName[4] = '\0';
```

The only thing necessary to do to solve this argument problem is making each `char` variable end with a null terminator. Here you can see the solved code:
```c++
#include <Firmata.h>

//setup() and loop() won't be here, there are no changes in them

unsigned long charIndex(const char * findIn, unsigned int symbol) {
  //Find 'symbol' in char array 'findIn'. Unlike
  //strchr(), returns unsigned long or 0 if 'symbol' not found

  char * pointer = strchr(findIn, symbol);
  if (pointer != NULL) return (pointer - findIn);
  if (pointer == NULL) return 0;
}

void stringCallback(char *received) {
  //Let's declare all the necessary variables
  char methodName[5];
  char argument1[5];
  char argument2[5];
  int commaLocation = 0;
  int lasti;

  byte nullTerminatorIndex = strlen(received); //For understanding

  //If the received string doesn't match the strings' syntax,
  //send an error message
  if (!(received[4] == '(' && strlen(received) <= 15)) {
    Firmata.sendString("ERR;");
    return;
  }

  //Let's take the 0-3 chars in the string and send it back.
  //It's probably the command name
  for (int i = 0; i < 4; i++) {
    methodName[i] = received[i];
  }
  methodName[4] = '\0'; //**The compiler doesn't add terminators automatically**.
  Firmata.sendString(methodName); //send it
  //This string is being sent without problems.

  //If there is some arguments in the string,
  //it is detectable if the string char 5 is not ')'/
  if (received[5] != ')') {
    //Lent's find out if the input string has a `comma`
    //inside the parentheses. If it does, it means that
    //there are two arguments in the string.

    Firmata.sendString("46 passed");
    if (charIndex(received, ',') != 0) commaLocation = charIndex(received, ',');

    //If a comma is not present, its location variable equals 0,
    //sincerely we just collect all the chars between the parentheses
    //to the 'argument1' variable and send it.
    if (commaLocation == 0) {
      Firmata.sendString("61 passed");
      for (int i = 5; i < (nullTerminatorIndex - 1); i++) {
        argument1[(i - 5)] = received[i];
        lasti = (i - 5);
      }

      argument1[(lasti + 1)] = '\0';
      lasti = 0;

      Firmata.sendString(argument1);
    }

    //If there is a comma present, then write chars before the comma
    //to 'argument1', and after the comma - to 'argument2'
    if (commaLocation != 0) {
      Firmata.sendString("77 passed");
      //let's write what is before the comma:
      for (int i = 5; i < commaLocation; i++) {
        argument1[i - 5] = received[i];
        lasti = (i - 5);
      }

      argument1[(lasti + 1)] = '\0';
      lasti = 0;

      //let's write what's after the comma;
      char argument2[5];
      for (int i = (commaLocation + 1); i < (nullTerminatorIndex - 1); i++) {
        argument2[(i - (commaLocation + 1))] = received[i];
        lasti = (i - (commaLocation + 1));
      }

      argument2[(lasti + 1)] = '\0';
      lasti = 0;

      Firmata.sendString(argument1);
      Firmata.sendString(argument2);
    }
  }
}
```


message:
Extracting .hex from Arduino Due

I have an Arduino Due that was programmed by the Arduino IDE, to cut things short I lost access to the original sketch (.ino) file, there is no way of recovering it no matter what.

I know that in the 8-bit MCUs I can read the .hex file from the flash memory, I already did that with PIC and AVR MCUs with their software programmer utilities.

My question is: Can I use a software programmer utility on Windows PC to extract the hex file to reprogram other Arduino Due with it? If yes, please help me.
I've read about the Bossac utility, it looks promising, but I have no experience in the ARM MCUs field at all.

again: I am NOT interested in C or Assembly code, I just want the .hex file.

body:
You can use JTAG and probably should.  But, it can also be done with bossac *if* you are **very** careful.  If you're not, you'll end up erasing your flash on your source board.

Using bossac
==============

This would maybe not be preferred over JTAG because it is probably easier to screw up (see warnings below), but it can be done.  I may add some on JTAG programming later, and if I do it may be above this section for that reason.  The main advantage here is just that you don't need a JTAG programmer.  The one caveat is that your existing sketch, or rather the image of the sketch that has been burned onto what I'm calling the "source board" has to be functioning well enough that it can cooperate in being placed back into the ROM bootloader.  I fully expect this is not a problem for you, or for pretty much any normal Arduino sketch that has been burned to a board.

WARNINGS
--------

* Under **NO circumstances** do you want to connect to the **PROGRAMMING port** of your **source board** at **1200** baud.
Doing so **will erase your board**, and then that's the end of it.

* In the below you *will* be connecting to the *Native USB* port at 1200, **NOT** the programming port.
**Connect only one port** at a time to your computer so there is no possibility of selecting the wrong one.

* **Practice** this whole procedure with a board you don't care about **first**.

Locate your BOSSAC command.
---------------------------

On my Windows machine, it was in:
```none
C:\Users\username\AppData\Local\Arduino15\packages\arduino\tools\bossac\1.6.1-ardunio\bossac.exe
```

It may be under a different version number.  It's possible that it will be in a completely different location.

```cmd
cd %USERPROFILE%
dir bossac.exe /s/b/p/a
```
Should locate it it, eventually, in any case.

On Linux it will be under ~/.arduino15 somewhere:

```sh
find ~/.arduino15 -name bossac
```

On a Mac it will probably be under a /Library/ directory under the user account somewhere.  You get the idea, locate it, make sure you can run it.

NOTE: There's a bossa program that is the GUI version where bossa**c** is a command-line program.  Unfortunately the IDE board support files don't ship the GUI program.  If you're having trouble with the command-line and want to try that instead, go for it.  But test it on a board you don't care about beforehand.  I have not tried it.

Connect to the Native Header
----------------------------

Connect your native USB port on the source board and only to that port.
[![Picture indicating native USB port][1]][1]

Enable boot to ROM
------------------

Open a terminal emulator of your choice at a rate of 1200 baud to the native USB port, wait a couple seconds and then close the port.  You can use the Serial Monitor from the IDE to do this if you want:

* Select the correct port from Tools/Port.

* Open the Serial Monitor

* Switch the baud rate to 1200 baud.

* You're not going to type anything and you're not going to see anything once you're connected at 1200 baud.

* Close the Serial Monitor

* You probably should:

  * See if the port has changed COM#, if so select the new one.

  * Re-open the serial monitor

  * Change the baud rate again to anything-but-1200-baud

  * Close the serial monitor again.
    This is not strictly necessary but the IDE remember the last chosen baud rate, and for what we're doing this is a slightly dangerous thing.

* Close the IDE as well.

What [connecting at 1200 baud][2] does is activate the code inside the core part of the programmed sketch that [changes the board to boot from the internal ROM bootloader][3].  It doesn't need traffic.  It just needs to see a request for 1200 baud.  More specifically, it needs to see the DTR "signal" go inactive, which happens when the port is closed, when the effective rate was 1200 baud.

NOTE: if you **screw up** here and connect to the programming port at 1200 baud instead, you'll wind up [causing the ATMega16U2 to **erase**][4] **your source board**.  The IDE remembers your last chosen baud rate, which makes this easy to screw up as well.  Hence the weird little dance in the above instructions regarding reopening the serial monitor and changing to something other than 1200 baud.  It's just putting an extra barrier up to accidentally doing this.

Once you've connected to the native USB port at 1200 baud and closed the port, your board will not run your sketch any more.  It's still there, it's just not running it.  The board has been told to sit in the ROM based bootloader, waiting for bootloader commands.

Saving your existing sketch's image
-----------------------------------

What we're going to do is run the bossac command you found earlier like so:

```cmd
bossac --read saved-sketch-image.bin --boot --reset
```

I'm assuming you either changed directory to where bossac.exe is, or alternately you're going to specify the necessary path to it found earlier.  I've found this command locates the correct COM port automatically.

This command:

* Downloads all of flash, 512 kbyte, and takes while, 128 seconds in one test.  Weirdly the same version under Linux takes closer to 10 seconds;  I haven't looked into why the difference, but I'm also unconcerned.
So **you now should have a 512 kbyte raw binary file containing your sketch image.**

* It re-enables the boot-from-FLASH so that on the next reset it will go back to running your sketch

* It resets your board, so it will begin running your old sketch.  If you don't want it to do that until you power cycle it, you could just as easily leave off the `--reset` part.

*As said, this is a raw binary file.  But you mentioned a HEX.  I'm assuming you didn't mean that literally, so I'm not going to detail how to convert the .bin file to a HEX format.  Though, if you want to do that, you should know that it needs to be offset to 0x80000, because that's where flash starts on the Due.*

Disconnect your source board from USB.

Making your clone (target) board
--------------------------------

Connect to your target board via the programming port.

[![Picture indicating connection to target board's programming port][6]][6]

* Hold the erase button for a few seconds to make sure the target board is erased.  Usually this would be done by the IDE connecting to the port for a while at 1200 baud.  But since we're using bossac at the command line, we need to do that step manually; it's just easier to use the button this time.

* Reset the board with the reset button.  Your target board is now sitting in its ROM bootloader awaiting commands.

* Put your image on the new board with:
```cmd
bossac --write saved-sketch-image.bin --boot --reset
```

*  Again, it's programming the whole 512 kbytes.  In one test on Windows it took about 100 seconds; no difference between Windows and Linux.  We're using the USART (programming port) which is slower than USB and we're flashing rather than reading which is slower; I haven't bothered to figure out which thing is the bottleneck.

* Like before `--boot` sets the board to boot from flash (your sketch) on next reset.

* And again `--reset` just resets the board.

Your target board should now be be behaving identically to the original source board.

  [1]: https://i.stack.imgur.com/wLRrs.jpg
  [2]: https://github.com/arduino/ArduinoCore-sam/blob/0840aa/cores/arduino/USB/CDC.cpp#L136
  [3]: https://github.com/arduino/ArduinoCore-sam/blob/0840aa277a7a6519147fcf041b0b3c5ae5dcbac1/cores/arduino/Reset.cpp#L31
  [4]: https://github.com/arduino/ArduinoCore-sam/blob/0840aa277a7a6519147fcf041b0b3c5ae5dcbac1/firmwares/atmega16u2/arduino-usbserial/Arduino-usbserial.c#L302
  [5]: https://i.stack.imgur.com/aZNvN.jpg
  [6]: https://i.stack.imgur.com/yPjSj.jpg


message:
Receiver sleep mode RDA5807M

Good afternoon guys!
I have a radio receiver connected to an arduino and I want it not to work all the time, but to turn on by the arduino timer for a certain time, and the rest of the time the receiver must be turned off by software.
I have a working sketch that allows you to tune this receiver, and it also allows you to re-tune the receiver (set the volume and frequency) by calling a function.

    #include <Wire.h>

    #define RDA5807M_RANDOM_ACCESS_ADDRESS 0x11
    // registers
    #define RDA5807M_REG_CONFIG 0x02
    #define RDA5807M_REG_TUNING 0x03
    #define RDA5807M_REG_VOLUME 0x05
    // flags
    #define RDA5807M_FLG_DHIZ 0x8000
    #define RDA5807M_FLG_DMUTE 0x4000
    #define RDA5807M_FLG_BASS 0x1000
    #define RDA5807M_FLG_ENABLE word(0x0001)
    #define RDA5807M_FLG_TUNE word(0x0010)
    //masks
    #define RDA5807M_CHAN_MASK 0xFFC0
    #define RDA5807M_CHAN_SHIFT 6
    #define RDA5807M_VOLUME_MASK word(0x000F)
    #define RDA5807M_VOLUME_SHIFT 0
    #define RDA5807M_RSSI_MASK 0xFE00
    #define RDA5807M_RSSI_SHIFT 9

    //uint8_t volume; // 0..15
    //uint16_t freq = 1077; // 107.3FM
    uint16_t reg02h, reg03h, reg05h, reg0Bh;

    void setup() {
      Serial.begin(9600);
      Nastroika(1, 4, 1077); // Receiver setting: incl. or off (on, off), volume (0 ... 15), frequency MHz * 10 (107.7 = 1077)
    }

    void loop() {
      Nastroika(1, 4, 1077);
      delay(5000);
      Nastroika(0, 4, 1077); // Nastroika(0)
      delay(5000);
    }

    void setRegister(uint8_t reg, const uint16_t value) {
      Wire.beginTransmission(0x11);
      Wire.write(reg);
      Wire.write(highByte(value));
      Wire.write(lowByte(value));
      Wire.endTransmission(true);
    }

    uint16_t getRegister(uint8_t reg) {
      uint16_t result;
      Wire.beginTransmission(RDA5807M_RANDOM_ACCESS_ADDRESS);
      Wire.write(reg);
      Wire.endTransmission(false);
      Wire.requestFrom(0x11, 2, true);
      result = (uint16_t)Wire.read() << 8;
      result |= Wire.read();
      return result;
    }

    void Nastroika(byte Key, uint8_t volume, uint16_t freq) // Receiver configuration after power failure
    {
      Wire.begin();
      // Регистр 02h - inclusion, settings
      if (Key == 1)
      {
        reg02h = reg02h | RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
      }
      else if (Key == 0)
      {
        reg02h = reg02h & ~RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;

      }
      setRegister(RDA5807M_REG_CONFIG, reg02h);
      // Регистр 03h - radio station selection
      // After reset in register 03h, the default value is 0
      // Thus BAND = 00 (87..108MHz), STEP = 00 (100kHz). Let's leave them as they are
      reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT; // chan = (freq - band) / space
      setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

      //Register 05h. Set the volume, do not change the rest of the beats
      reg05h = getRegister(RDA5807M_REG_VOLUME); // Reading the current value
      reg05h &= ~RDA5807M_VOLUME_MASK; // Resetting the bits VOLUME
      reg05h |= volume << RDA5807M_VOLUME_SHIFT; // Setting a new volume
      setRegister(RDA5807M_REG_VOLUME, reg05h);
    }

I need to modify this sketch and add the ability to wake up the receiver and put it into sleep mode. There is "RDA5807M_FLG_ENABLE" here. As I understand it, you need to change it?

*Added later:*

The method of turning off the receiver for a while, suggested in the comments, works.
However, for everything to be correct, when calling the function when the receiver is disconnected, we will send **Nastroika(0, 4, 1077);** that is, when turning off, we still specify the volume and frequency, although these parameters are superfluous here. It would be correct to write simply **Nastroika(0);** , But this cannot be done just like that, because there should be exactly three input arguments for the function, and not one.

body:
Switch off:

    reg02h = reg02h & ~RDA5807M_FLG_ENABLE;
    setRegister(RDA5807M_REG_CONFIG, reg02h);

Switch on:

    reg02h = reg02h | RDA5807M_FLG_ENABLE;
    setRegister(RDA5807M_REG_CONFIG, reg02h);

**EDIT:** (to answer a comment of Антон)

Nastroika (настройка) means "tuning". Is that right? Then I would use this method only for tuning. Create two methods one for switching off and one for switching on.

    void switchOff()
    {
       reg02h = reg02h & ~RDA5807M_FLG_ENABLE;
       setRegister(RDA5807M_REG_CONFIG, reg02h);
    }

    void switchOn()
    {
       reg02h = reg02h | RDA5807M_FLG_ENABLE;
       setRegister(RDA5807M_REG_CONFIG, reg02h);
    }

In the `Nastroika` Method you should only perform the tuning and let the module of. If you insist to switch on at the same time you could use your old version.

Example:

    void Nastroika(uint8_t volume, uint16_t freq)
    {
       // !!!!! This is the wrong place for Wire begin
       // move it to the setup method.
       // Wire.begin();
       reg02h = reg02h | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
       // or if you insist / you want to keep the module be started here
       // reg02h = reg02h | RDA5807M_FLG_ENABLE | RDA5807M_FLG_DHIZ | RDA5807M_FLG_DMUTE;
       setRegister(RDA5807M_REG_CONFIG, reg02h);
       reg03h = (freq - 870) << RDA5807M_CHAN_SHIFT;
       setRegister(RDA5807M_REG_TUNING, reg03h | RDA5807M_FLG_TUNE);

       reg05h = getRegister(RDA5807M_REG_VOLUME);
       reg05h &= ~RDA5807M_VOLUME_MASK;
       reg05h |= volume << RDA5807M_VOLUME_SHIFT;
       setRegister(RDA5807M_REG_VOLUME, reg05h);
    }

Usage:

    void setup()
    {
       Serial.begin(9600);
       Wire.begin();
       Nastroika(4, 1077);
    }

    void loop()
    {
      switchOff();
      delay(5000);
      switchOn();
      delay(5000);
    }


message:
Memory for inputs?

When a button is pressed, the Arduino might be busy with something (like drawing the screen). When the Arduino has finally time to check the button input, the uses might have release it already.

Is there a way that can store the input until the Arduino has time to check it?
It would be awesome if there was ic that could take care of this.

Thanks for the help!

body:
The basic guidance when writing Arduino applications is to do a small amount of work on every pass through the loop function, then do a little bit more on the next pass. Check all your inputs, execute logic in response to those inputs, set up `unsigned long` variables with future `millis()` values, check those values to see if a future time has arrived, and repeat.

Do **not** use `delay()`. It is the death of a cooperative system like an Arduino. When your Arduino executes a call to `delay()`, everything stops until the delay time has passed.


body:
> Is there a way that can store the input until the Arduino has time to check it?

No, there is no way to remember/buffer input changes within the Arduino (You could use a flipfop IC like JRobert wrote. That can give you that functionality). But there are interrupts, that you can use with pins. A triggered interrupt will really interrupt the main code from running and execute its corresponding ISR (Interrupt Service Routine), to handle the interrupt cause, and then returning to execute the main code. A microcontoller has many different interrupts, each one connected to its special hardware. There are interrupts for the Serial interface, for SPI, I2C, and also some connected to the External Interrupt pins or the PinChange Interrupt (these last two could be used with your button). So this would not "store" the input change, but it will interrupt the main code to immediately act upon the input change. So that's a different principle.

If you want to bind your button to an interrupt, you could just stay in the Arduino Framework and use the `attachInterrupt()` function. There are many tutorials online for that. Keep in mind, that you should never do long things inside an ISR, and functions like `delay()` won't work there.

---

That said, most likely it is not really needed to use interrupts with buttons. Humans are rather slow, thus each button press will last in the ballpark of 100ms or longer.

You could now say, that your code is doing things longer than 100ms. But here the rabbit is buried (literal translation of a german saying, meaning "there is the problem"). When starting with Arduino, one is doing many blocking things, like `delay()` or blocking while loops. These are often very easy to implement, but nothing else will be running during these things.

Instead you should divide up your actions into small parts. When it is time to do something, you are doing that small part and exit fast. This enables other code to run in between. A good example is the `BlinkWithoutDelay` example. The normal blink example uses `delay()`, which blocks everything else. Instead you can use the `millis()` function as a clock and only take action, when it is time to do so, otherwise to further fast. Much like you would bake a pizza in your oven. You won't sit in front of the oven, waiting for the pizza to be ready. You would do something else and regularly look at your clock, if it is time to take the pizza out.

You didn't show your code, so we cannot advice you more in that direction. But you can find many tutorials about it, if you search for terms like `Arduino blink without delay` or `Arduino millis tutorial`.


body:
The answer to your direct question, is there an IC to store an input, is yes. It's called a Set-Reset (or SR) Flip-Flop. I don't know if they're packaged standalone in an IC but they're really simple to make with a pair of [cross-connected NAND gates][1].

But that's not really the right solution to your problem. Your code should not be so "busy" that it misses a slow input like a push-button. I quoted "busy" because it is usually delay() calls, not computations, that occupy the processor for any large amounts of time, and delay()s are to be avoided if your code has any more than 1 thing to do.

Look up the Blink Without Delay example-sketch in the Arduino IDE for the unvarnished, basic approach to doing this. Then there are libraries that can help with the low-level details of doing it - [SimpleTimer][2], is one such. Or, if your code is stuck waiting for slow external events, don't wait for them but check for them frequently and move on immediately to something else, if they haven't taken place yet.

  [1]: https://circuitglobe.com/rs-flip-flop.html#TheNANDGateRSFlipFlop
  [2]: https://github.com/jfturcot/SimpleTimer/blob/b30890b8f7046bf3b0258e5870e5dda78ac5c71a/SimpleTimer.cpp


message:
I am trying to up the frequency everytime button is press by 100 Hz, I am using the Input pull registor

The frequency should be increased by 100 Hz whenever an external push-button on UNO digital pin 5 is depressed and then released. I think I might missing something critical.
```
#define LEDPIN 3
float highTime;
float lowTime;
int freq;
float period;

//uint16_t val2= pulseIn(4, HIGH);

ISR(TIMER1_COMPA_vect) { digitalWrite(LEDPIN, !digitalRead(LEDPIN)); }
void setup() {
Serial.begin(9600);
pinMode(LEDPIN, OUTPUT);
// initialize Timer1 (the 16-bit timer) using channel A output compare

TCCR1A = 0; // set entire TCCR1A register to 0
TCCR1B = 0; // same for TCCR1B
TCNT1 = 0; // initialize counter value to 0
// set compare match register for 100 Hz increments
OCR1A = 9999; // = 16000000 / (8 * 100) - 1 (must be <65536)
// turn on CTC mode
TCCR1B |= (1 << WGM12);
// Set CS12, CS11 and CS10 bits for 8 prescaler
 TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

// enable timer compare interrupt
TIMSK1 |= (1 << OCIE1A);
sei(); // allow interrupts
interrupts(); // enable global interrupts:
}
void loop() {

highTime =(pulseIn(4, HIGH));
lowTime=(pulseIn(4, LOW));
period = highTime+lowTime;
freq=1000000/period;       //getting frequency with totalTime is in Micro seconds
Serial.print(freq);
delay(1000);

Serial.print("\n");
```
Basically I want to turn the above code which display "100" in serial monitor with raises the frequency by 100 by a button press.

```
#define LEDPIN 3
const int buttonPin = 5;    // the number of the pushbutton pin

//uint16_t val2= pulseIn(4, HIGH);
// Variables will change:
int ledState = HIGH;         // the current state of the output pin
int buttonState;             // the current reading from the input pin
int lastButtonState = LOW;   // the previous reading from the input pin

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastDebounceTime = 0;  // the last time the output pin was toggled
unsigned long debounceDelay = 50;    // the debounce time; increase if the output flickers

ISR(TIMER1_COMPA_vect) { digitalWrite(LEDPIN, !digitalRead(LEDPIN)); }
void setup() {
  Serial.begin(9600);
  pinMode(LEDPIN, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
  // initialize Timer1 (the 16-bit timer) using channel A output compare

  TCCR1B = 0; // same for TCCR1B
  TCNT1 = 0; // initialize counter value to 0
  // set compare match register for 100 Hz increments
  OCR1A = 9999; // = 16000000 / (8 * 100) - 1 (must be <65536)
  // turn on CTC mode
  TCCR1B |= (1 << WGM12);
  // Set CS12, CS11 and CS10 bits for 8 prescaler
  TCCR1B |= (0 << CS12) | (1 << CS11) | (0 << CS10);

  // enable timer compare interrupt
  TIMSK1 |= (1 << OCIE1A);
  sei(); // allow interrupts
  interrupts(); // enable global interrupts:

}
void loop() {
  int reading = digitalRead(buttonPin);
   // If the switch changed, due to noise or pressing:
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }
  if (reading != lastButtonState) {
    // reset the debouncing timer
    lastDebounceTime = millis();
  }

  if ((millis() - lastDebounceTime) > debounceDelay) {
    // whatever the reading is at, it's been there for longer than the debounce
    // delay, so take it as the actual current state:

    // if the button state has changed:
    if (reading != buttonState) {
      buttonState = reading;

      // only toggle the LED if the new button state is HIGH
      if (buttonState == HIGH) {
        ledState = !ledState;
      }
    }
    lastButtonState = reading;

    Serial.print(reading);
    delay(1000);
    Serial.print("\n");

  }
}
```

body:
Your button input pin is set to INPUT_PULLUP mode so that pin will always read HIGH unless you ground it. Your button should connect the pin to ground when it is pressed.

If you do that, then the pin will read HIGH when the button is not pressed, and LOW when the button is pressed. Near the bottom of your loop() function, you test the button and toggle the LED with:

      if (buttonState == HIGH) {
          ledState = !ledState;
      }

But this toggles the LED when the button is released. Is that really what you meant?


message:
What is the purpose of putting a data type in brackets before a calculation?

sorry for the nooby question but I can't seem to find the answer to this anywhere, probably because I'm unsure what to search for with this problem!

I'm just wondering what the reason is for including a data type in brackets before a calculation takes place? In the code below, all the variables have already been declared at the top of the program, so I'm unsure what the reason / effect of including the (float) has. acc_y and angle_pitch_acc have been declared as floats and acc_total_vector has been declared as long

    angle_pitch_acc = asin((float)acc_y/acc_total_vector)* 57.296;

Thanks!

body: It's called *casting*. It changes the data type temporarily. In this instance it's being used to change an integer type into a floating point type, which means that the whole calculation is done using floating point mathematics. However `acc_y` is supposedly already a float, but maybe it wasn't at the time the author wrote that line. Maybe things, as they often do in a program, evolved. Only the author knows.


message:
What is the pinout of the Arduino MKR motor carrier when using external power supply, not the Li-Po battery

I see there is a blue terminal connector an the tags below the PCB Vin, 5V, 3,3V and GND, but I am unsure where should I supply voltage to power up the board.
Also, in the product page it says the power can range from 6.5 to 11v, so what is those 5V and 3.3V all about?
Thanks

body:
`Vin` means "Voltage Input". That's where you provide your power. That is the input to the voltage regulator.

5V and 3.3V are what the board uses internally and are provided for you to also use should you want to. These are outputs from the voltage regulators.

It's exactly the same (though more efficient and higher current) as almost every other Arduino.


message:
Make an LED less bright

As an exercise to learn rather then the most efficient way to accomplish a goal.... (i'm a hands on hardware guy, but I need to get my Sh!T together and learn some coding)

I would like to make an LED less bright within a project.  I have a nano set up to control a relay to control a dc load when a momentary switch is pressed (this is kinda needlessly complicated solely to allow me to use a particular momentary switch I wanted to use for a bunch of not that great reasons ;-)

Anyway... the code i'm using is this:

```
int pbuttonPin = 2;// connect output to push button
int relayPin = 10;// Connected to relay (LED)

int val = 0; // push value from pin 2
int lightON = 0;//light status
int pushed = 0;//push status

void setup() {
  // Robojax.com code and video tutorial for push button ON and OFF
  Serial.begin(9600);
  pinMode(pbuttonPin, INPUT_PULLUP);
  pinMode(relayPin, OUTPUT);
 digitalWrite(relayPin, HIGH);// keep the load OFF at the begining. If you wanted to be ON, change the HIGH to LOW
}

void loop() {
// Robojax.com code and video tutorial for push button ON and OFF
  val = digitalRead(pbuttonPin);// read the push button value

  if(val == HIGH && lightON == LOW){

    pushed = 1-pushed;
    delay(100);
  }

  lightON = val;

      if(pushed == HIGH){
        Serial.println("Light ON");
        digitalWrite(relayPin, LOW);

      }else{
        Serial.println("Light OFF");
        digitalWrite(relayPin, HIGH);

      }

// Robojax.com code and video tutorial for push button ON and OFF

  delay(100);
```

The above code is straight up cut and paste... i'm clueless

I have a LED cathode on pin 10, (so i know the relay is on more easily from a distance).  however the application is on a boat, and at night it is too bright and distracting.  So i want to make the LED dimmer... I know I could add a larger value resistor, but i want to expand my understanding and would like suggestions on other ways PWM maybe....

cheers:

body:
There are two methods of dimming a LED : by PWM or by a limiting current resistor.
1. PWM code

        `//Initializing LED Pin
        int led_pin = 10;
        void setup() {
        //Declaring LED pin as output
                pinMode(led_pin, OUTPUT);
        }
        void loop() {
                analogWrite(led_pin, 127); // half intensity
                delay(5);
        }`
2. Hardware. Use following schematic
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/atpIK.png


body:
If you want to decrease the brightness in general, the easiest solution would in deed be to use a high value resistor.

If you want to use PWM - for example to change brightness programmatically - you just need to replace the calls to `digitalWrite(HIGH|LOW)` with calls to `analogWrite(x)` ([ref][1]), where `x` represents the duty cycle/brightness. The range of `x` depends on your microcontroller.

Note, that PWM (which is used by `analogWrite()`) only works on dedicated pins.
On the other side, there are microcontrollers wich have analog pin with a "true" analog output. On such an analog pin - though it is possible to use `analogWrite()` - the brightness will not be linear and have an offset, which makes it pretty much useless for dimming an LED.

  [1]: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/


body:
Follow this tutorial. It doesn't get any better than this.
https://www.arduino.cc/en/Tutorial/BuiltInExamples/Fade