message:
Weird Arduino Code Problem

I'm currently getting started with Arduino, so I do not have very much knowledge.
In this project I have a receiver and a transmitter with 2 buttons.
So, I'd like to switch something to on, when I press the A button. If A is pressed longer I'd like something else to happen.
Same thing goes on with the B button, but for some reasons, when I long press A, then B gets triggered and I have no clue why...

Btw. this code is not purely made by me, but copied and edited for my use.
If anyone could help me I'd be very happy :)

code:

    //ButtonAEvents

    long prevA = 0;
    long prevB = 0;
    int buttonStateA = 0; // 0 = not pressed   --- 1 = long pressed --- 2 short pressed
    int buttonStateB = 0; // 0 = not pressed   --- 1 = long pressed --- 2 short pressed
    int ButtonAPin = 2;
    int ButtonBPin = 3;
    int DURATION_A_IN_MILLIS = 1000;
    int DURATION_B_IN_MILLIS = 1000;

    //ONE TIME SETUP

    void setup()
    {
        pinMode(ButtonAPin, INPUT);
        pinMode(ButtonBPin, INPUT);
        Serial.begin(9600);
    }

    //LOOP BEGIN

    void loop()
    {

        //BUTTON A CHECK
        buttonStateA = 0;
        if (digitalRead(ButtonAPin)) {
            prevA = millis();
            buttonStateA = 1;
            while ((millis() - prevA) <= DURATION_A_IN_MILLIS) {
                if (!(digitalRead(ButtonAPin))) {
                    buttonStateA = 2;
                    break;
                }
            }
        }

        if (!buttonStateA) {
            // Nothin pressed
        }
        else if (buttonStateA == 1) {
            //LONG PRESS

            Serial.println("LongpressA");
            digitalWrite(A1, HIGH);
            delay(100);
        }
        else if (buttonStateA == 2) {
            //SHORT PRESS
            digitalWrite(A1, HIGH);
            Serial.println("ShortpressA");
            delay(100);
        }

        //BUTTON B CHECK
        buttonStateB = 0;
        if (digitalRead(ButtonBPin)) {
            prevB = millis();
            buttonStateB = 1;
            while ((millis() - prevB) <= DURATION_B_IN_MILLIS) {
                if (!(digitalRead(ButtonBPin))) {
                    buttonStateB = 2;
                    break;
                }
            }
        }

        if (!buttonStateB) {
            // Nothin pressed
        }
        else if (buttonStateB == 1) {
            //SHORT PRESS

            Serial.println("LongpressB");
            delay(100);
        }
        else if (buttonStateB == 2) {
            //LONG PRESS
            digitalWrite(A1, LOW);
            Serial.println("ShortpressB");
            delay(100);
        }
    }

body:
Not sure if this is just an academic exercise on your part to learn (which is totally cool), but if you're just trying to move forward and get something working you may consider one of the many excellent button libraries out there for Arduino.

I recently used a library called [ButtonKing][1] that allowed me to do some very sophisticated menu interactions on a MKR1010 with a display and single button interface.  There are several other libraries out there as well that take care of debouncing, long clicks, double clicks, etc.

  [1]: https://github.com/TanPitch/ButtonKing


sender: user

message:
Feeding microcontroller and linear actuators (motors) with the same power supply

I have already made a diagram using a motor controller. I want to use only one power supply to feed arduino and motors. I want to use MDD10 dual motor driver.

The details of the actuators each one is:

Input voltage: 12VDC,
Max Load: 750N(168.607lbs),
Stroke Length: 16 inch,
Travel Speed: 12mm/s,
Duty Cyle: 25%,
Current: 5A.

The power supply is 12V, 10A.

Could you please check if it is ok, or which would be the best solution?

Some of my concerns are:

Be sure if the feed of 12 volts for the motors, and 5 volts for Arduino are correct and can live together as shown.

Be sure if the wiring for the Arduino, driver and motors is correct since it looks kind of simple.
[![enter image description here][1]][1]
I want to know if this is the natural approach by doing it with a voltage regulator to feed the Arduino and with 12V 10A power supply to feed the motors, or if there are other, better options to make the circuit feed only using one power supply (12V, 10A).

MDD10 Datasheet Link: https://www.robotshop.com/media/files/content/c/cyt/pdf/cytron-10a-7-30v-dual-channel-dc-motor-driver-shield-datasheet.pdf

Thanks in advance

**UPDATE**

I have increased power supply to 13A, also changed the linear voltage regulator (7805) to a switching voltage regulator (OKI-78SR-5), what do you think about this approach?
[![enter image description here][2]][2]
Or I should try with the 12V DC Vin of Arduino(I understand that it works with a linear voltage regulator)? Being this option, it could be maybe with a voltage pre-regulation stage(for example from 12V to 9V) or maybe connecting directly to the jack.
[![enter image description here][3]][3]
Thanks, Best Regards.

  [1]: https://i.stack.imgur.com/NWAj9.png
  [2]: https://i.stack.imgur.com/7SEjM.png
  [3]: https://i.stack.imgur.com/RocBT.png

sender: assistant

body:
Your approach looks reasonable, but you don't have enough power. The motors will draw 10A, which is the full output of your power supply/battery. That doesn't leave any left over for your Arduino system.

You should have a high enough capacity power supply/battery for your total peak power requirement plus a little margin (say 10%-20%) The Arduino and all the other electronics on it might draw another 1/2 amp, so 10.5 total. Add 20% margin to that and you get 10.5 * 1.2, or about 12.6 A.

(When you drive a power supply up to its upper limit its output voltage can start to sag. By having a buffer it doesn't have to work as hard.)

One advantage you have in your circuit is that you're feeding unregulated 12V to your motors, and then feeding 12 into your Arduino's voltage regulator. That way even if the 12V supply droops to 10V under maximum load, the voltage regulator will still be able to maintain a clean 5V supply to your MCU.

Also note that you could feed 12V into the Arduino's V in and use its built-in voltage regulator. As long as don't draw a lot of current out of its 5V line the built-in regulator could manage the 5V voltage regulation itself. If you need ≥500 mA, though, you might want to use an external buck converter (or a high capacity linear regulator with a good heat sink.)


body:
First of all I would look to see if the two motors will actually run at the same time.
If not then the 10A power supply, is fine.
If they do run together, for how long? (you mention 25% duty cycle), power supplies usually have a over capability for a short period of time, and batteries will supply more current but at a slightly reduced voltage, so if going slightly slower isn't an issue then this would be fine.
Then there is the question of do they really use all 5Amps, I very much suspect not, unless you are fully loading the actuator(750N), they prob run at 2-3 amps at most.
Secondly
Circuit protection, fuses or thermal shutdown links for the motors is required, better still instant overcurrent protection for them set at 1.2x nominal current.
Do some worst case tests and measure the current, set the protection to 1.2 x this.
Remember if there is an issue the supply voltage will start to drop, its now that the micro will suffer if the voltage dips too much and you have no protection/sensing.

So suspect the power supply is more than ok.


message:
Stream video from camera to mobile and send control signal back from mobile to Arduino via WiFi

I want to make an Ardunio based project in which I want to stream live video from camera (which is connected to Arduino borad ) to my Android app via WiFi and send back actions/control signals from my android app to Arduino to controller servo motor which are connected to Arduino board. Right now I only have Arduino mega with me. What else components are going to be required?

body:
You need good MPU with enough buffer size and nand size for such an intense process

Search esp modules

Thanks.


message:
How to add indicator lights to button sketch

I would like to add leds to each button switch in the first code, The first code sends midi messages to a DAW I would like it to also turn on a led as an indicator light. The switch needs to turn the light on if off and off if on. The second code is an example that does this, it works well with one button. I would like to have the 3 buttons on pins 0, 1, 2 and the leds on pins 3, 4, and 5.
<!-- language-all: lang-cpp -->

    #include <Bounce.h>

    const int channel = 1;
    Bounce button0 = Bounce(0, 5);
    Bounce button1 = Bounce(1, 5);
    Bounce button2 = Bounce(2, 5);

    void setup() {
      pinMode(0, INPUT_PULLUP);
      pinMode(1, INPUT_PULLUP);
      pinMode(2, INPUT_PULLUP);
    }
    void loop() {
      button0.update();
      button1.update();
      button2.update();

      if (button0.fallingEdge()) {
        usbMIDI.sendNoteOn(60, 99, channel);  // 60 = C4
      }
      if (button1.fallingEdge()) {
        usbMIDI.sendNoteOn(61, 99, channel);  // 61 = C#4
      }
      if (button2.fallingEdge()) {
        usbMIDI.sendNoteOn(62, 99, channel);  // 62 = D4
      }

      if (button0.risingEdge()) {
        usbMIDI.sendNoteOff(60, 0, channel);// 60 = C4
      }
      if (button1.risingEdge()) {
        usbMIDI.sendNoteOff(61, 0, channel);  // 61 = C#4
      }
      if (button2.risingEdge()) {
        usbMIDI.sendNoteOff(62, 0, channel);  // 62 = D4
      }
      while (usbMIDI.read()) {
      }
    }

Second sketch:

    /*********************
    Simple toggle switch
    Created by: P.Agiakatsikas
    *********************/

    int button = 0;
    int led = 13;
    int status = false;

    void setup(){
      pinMode(led, OUTPUT);
      pinMode(button, INPUT_PULLUP); // set the internal pull up resistor, unpressed button is HIGH
    }

    void loop(){
    //a) if the button is not pressed the false status is reversed by !status and the LED turns on
    //b) if the button is pressed the true status is reveresed by !status and the LED turns off

    if (digitalRead(button) == true) {
      status = !status;
      digitalWrite(led, status);
    } while(digitalRead(button) == true);
      delay(50); // keeps a small delay
    }

body:
I'd suggest creating an array of MIDI button structs. For each entry you'd have a button object, an LED pin, and a BOOL to track the state of thate button.

Write a function that loops through the array of structs, checks the state of each one, and does the work to play/stop the notes and toggle the LED states based on the state of each button.


message:
How to upload already compiled code when no changes were made?

How do I use the Arduino IDE to upload the last compiled code? I don't want to have to wait 2 minutes to upload compiled code when there are no changes. It's a big codebase where I frequently make one or two small changes and have some issue with my MCU or USB cables. Frequently the controller on my boards are damaged due to some overcurrent issue because of the high-heat nature of **3d printing**. So having to wait an extra 2-5 minutes every time I experiment with this unacceptable.

 Obviously, there is a keyboard shortcut to do this that I'm unaware of. Because otherwise this would add hours to development.

Please tell me how I can get Arduino-IDE to just 'upload without compiling' my sketch.

body:
You can upload hex file to your board from command line without Arduino IDE.

To get the hex file, use in Arduino IDE in menu the command "Export compiled binary". It will save the hex file next to the ino file.

I assume your board in printer has AVR MCU. Then you can use avrdude from command line to upload the hex file again and again without any compilation.

The avrdude command on Windows is (if started from the sketch's folder):

    %LOCALAPPDATA%\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/bin/avrdude -C%LOCALAPPDATA%\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf -v -patmega328p -carduino -PCOM11 -b115200 -D -Uflash:w:Blink.ino.hex:i

The command line is for the Blink sketch and for AVC boards package 1.6.21


body:
This is what I have done.  In the arduino IDE settings panel, turn on the "Show verbose output during compile and upload". This way whenever you are doing verify and upload you can see all the command that Arduino has performed. Now after you hit Verify or Upload it, you can copy the last command before the upload, such as

"/Users/fang/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/bin/avrdude" "-C/Users/fang/Library/Arduino15/packages/arduino/tools/avrdude/6.3.0-arduino17/etc/avrdude.conf" -v -V -patmega32u4 -cavr109 "-P/dev/cu.usbmodem21101" -b57600 -D "-Uflash:w:/private/var/folders/xb/4609zdjx4tn3bv_6jh2nym_r0000gn/T/arduino/sketches/7972D54945A751059BF3114D2057C2B6/sketch_aug4c.ino.hex:i"

Now, when you need to upload without compiling again, just paste this line to the Terminal, it'll do the rest for you. Essentially you can see Arduino IDE is just a wrapper around these commands.

**Update:**

I also found another way which is kinda of different but more effective. If you happen to use Visual Studio Code, you can also try the PlatformIO plugin which can compile and upload code separately, I wrote an article about it here, https://windmaomao.medium.com/use-platformio-to-write-arduino-code-3c957c4e58b5


message:
Are there any standard ways of reporting a runtime error?

I'm new to Arduino but I'm an experienced programmer. I'm wondering if there are any common functions for reporting errors in Arduino programs? For example, in JavaScript we have the alert() function, or on Unix you can write a message to standard error and exit.

Ideally, if the serial port is available then an error message would be printed there, or if there is an LED then maybe we should blink it. This would need to be configurable based on what the programmer wants to do with available hardware.

Looking the example sketches, error reporting seems pretty horrible. I'm wondering if any libraries handle this better?

body:
As pointed out by Majenko in a comment, you can hardly define a standard
facility for error reporting when you don't know what kind of I/O
hardware will be available on any particular project. Printing to the
serial port is the most common method though, as it tends to always be
available during the development phase, while the Arduino is tethered to
the development computer. I personally tend to just do something like
```c++
Serial.println(F("Error: the warp field coil is busted."));
```
and be consistent with the error prefix, so that a program receiving
this can tell it's an error by matching the line against `/^Error: /`.

While it is OK for user code, reporting errors through `Serial` is
certainly _not_ a good practice for library code. Alas, it is done way
too often in Arduino libraries. I've seen at least one library (don't
remember which one) that allows the user to provide a reference to a
`Print` object (defaulting to `Serial`) to be used for this purpose.
This is way better, as it allows the user to handle the error messages
any way she chooses. It is also very easy to turn off the error
reporting altogether by implementing a do-nothing `Print`, which would
be a `/dev/null` of sorts.

Note that the avr-libc [allows you to print to `stderr`][stdio], as long
as you have first implemented `stderr->put`... While this method is the
closest you can get to the standards you are used to, it may not be
portable to non-AVR Arduinos. And it is worth noting that we tend to
avoid the `printf()` family of functions on Arduinos, as they tend to be
quite large compared to the `print()` and `println()` methods.

[stdio]: https://www.nongnu.org/avr-libc/user-manual/group__avr__stdio.html


message:
How do I use PlatformIO to flash ESP-12F (ESP8266MOD)

In PlatformIO while creating a project , in the board selection there is no ESP-12F in the boards. While there is ESP-12E. I can flash ESP-12F while choosing ESP-12E from the boards without any flashing issue. But there are some runtime issues, the one that I noticed is the LED doesn't blink when flashed from PlatformIO , but works fine, when flashed using Arduino IDE using the same code.
So there may be some difference in the configurations.

> C:\Users\USER\\.platformio\platforms\espressif8266\boards

In this directory I found the esp-12e board which is a JSON format.

    {
      "build": {
        "core": "esp8266",
        "extra_flags": "-DESP8266 -DARDUINO_ARCH_ESP8266 -DARDUINO_ESP8266_ESP12",
        "f_cpu": "80000000L",
        "f_flash": "40000000L",
        "flash_mode": "dio",
        "ldscript": "eagle.flash.4m1m.ld",
        "mcu": "esp8266",
        "variant": "nodemcu"
      },
      "connectivity": [
        "wifi"
      ],
      "frameworks": [
        "arduino",
        "simba",
        "esp8266-rtos-sdk",
        "esp8266-nonos-sdk"
      ],
      "name": "Espressif ESP8266 ESP-12E",
      "upload": {
        "maximum_ram_size": 81920,
        "maximum_size": 4194304,
        "require_upload_port": true,
        "resetmethod": "nodemcu",
        "speed": 115200
      },
      "url": "http://www.esp8266.com/wiki/doku.php?id=esp8266-module-family",
      "vendor": "Espressif"
    }

How do I add ESP-12F to the PlatformIO boards and flashing without any issue.

body:
At the PlatformIO community I asked the same question, and [pfeerick ](https://community.platformio.org/u/pfeerick) suggested to add a build flag.

> It’s most likely the onboard LED is on GPIO2, not GPIO1 so try adding
>
> **build_flags = -D LED_BUILTIN=2** to your **platformio.ini** … hopefully that
> kicks in before the **pins_arduino.h** defintion.

But It didn't did the trick.
And the compiler throws a bunch of warnings.
What I did to make it work is to ignore **LED_BUILTIN** constant and use 2 instead.

    #include <Arduino.h>
    void setup() {
     pinMode(2, OUTPUT);
    }

    void loop()
    {
      digitalWrite(2,LOW);
      delay(200);
      digitalWrite(2,HIGH);
      delay(200);
    }


message:
char buffer to String in Arduino UNO

String getAPIData()
    {
      char res_buffer[450];
      int numdata = inet.httpGET("myserver.com", 80, "/call.php?id=1&q=1&code=1001", res_buffer, 450);
      String result = String(res_buffer);
      Serial.println(result);
      Serial.println(numdata);
      return result;
    }
Output on Serial:

    15:52:07.208 ->
    15:52:07.208 -> 393

But, When I print the buffer by loop I got the below output:

    HTTP/1.1 200 OK
    Date: Mon, 16 Sep 2019 06:28:59 GMT
    Server: Apache
    X-Powered-By: PHP/7.2.20
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must-revalidate
    Pragma: no-cache
    Set-Cookie: PHPSESSID=5b21eeac22dcf61f2e4d2efd579d437c; path=/
    Upgrade: h2,h2c
    Connection: Upgrade, close
    Vary: Accept-Encoding,User-Agent
    Content-Type: text/html; charset=UTF-8

    -1
I am not sure why the char buffer is not converting to String in Arduino UNO.

Any known issues ? Please suggest if any correction required.

body:
Do not use String. And especially do not use String in the way you are using it.

You can read more about why not [here](https://majenko.co.uk/blog/evils-arduino-strings).

Instead stick to just using `char*` buffers.

The correct way of doing what you want is to define the buffer outside your function and then pass that buffer to the function to be populated:

    int getAPIData(char *buf, int maxlen) {
      return inet.httpGET("myserver.com", 80, "/call.php?id=1&q=1&code=1001", buf, maxlen);
    }

Then you call it with:

    char *my_buffer[450];
    getAPIData(my_buffer, 450);
    Serial.println(my_buffer);


message:
What do these pins mean? Where should I plug them in?

I am trying to collect data from the arduino into a SD card for the first time, so I bought the adapter at my local electronics/arduino shop. However, I could not find an explanation as to what each pin does, and the other adapters that I have seen online have different pins, so I am not sure what to do with the pins (except for the obvious ones, GND and VCC)
[![enter image description here][1]][1]

  [1]: https://i.stack.imgur.com/N5WUi.jpg

The order of pins is as follows:
CD, DO, GND, SCK, VCC, DI, CS.

Could you help me figure out what they mean and where to plug them into my arduino?

body:
This is called the SPI interface (See [Serial Peripheral Interface, Wikipedia][1]. The pin names typically used for SPI are:

- GND : Power Ground
- VCC : Power input
- CS : Chipselect
- SCK/SCLK (SD-Clock): SPI Clock
- MOSI (SD-DI, DI) : SPI Master out Slave in
- MISO (SD-DO, DO) : SPI Master in Slave out
- CD: Card Detect (see comment of rollinger below (thanks).

  [1]: https://nl.wikipedia.org/wiki/Serial_Peripheral_Interface

On an Arduino Uno the SPI pins are:

- CS – digital 10; this can be in principle any pin
- SCK – digital 13
- MOSI – digital 11
- MISO – digital 12


body:
 - CS = Chip select
 - DI = Data In (MOSI)
 -      VCC
 -      SCK = Serial Clock
 -      GND
 -      DO = Data Out (MISO)
 -      CD (not sure what it stands for, but this pin isn't used when connecting to an Arduino. I think it's used for faster transfers.)

Note that SD card run at 3.3Volt, not 5V. Also the input pins of the SD can't handle 5Volt signals. So you need to convert the 5V signals coming out of the UNO to 3.3V before connecting to the SD card.


body:
CD could be one of two things:

a) a simple mechanical switch on the socket, usually used for Card Detect.  Measure from the pin to Gnd and see if contact is open/closed when a card is plugged in.

b) the fifth IO pin to a uSD card.  See the chart on the middle of this data sheet

https://www.molex.com/pdm_docs/sd/472192021_sd.pdf

You will see there are 4 data lines for parallel operation (Dat0, Dat1, Dat2, and CD/Dat3), and the Clock and Command (CMD) pin.   Arduino uses serial operation over the SPI bus tho, so in this case CD is likely card detect from what appears to be a mechanical lever switch at the bottom of the socket.

This drawing shows how the pins are used
http://www.dotmana.com/weblog/wp-content/uploads/izQKT.png


body:
Your question's been well answered, but I just wanna point out, when you get the library code that lets you access the SD card, there will probably be instructions on what pins to wire up where. That's nearly always the case. Particularly since this one uses the SPI pins.

There's also loads of instruction websites that would take you through it. The cheap Chinese stuff is nearly always copies of designs from the West, as seen on popular websites. So the instructions usually apply. Arduino is bloody great! Good luck in your adventure.


message:
How do I extract code from an arduino?

I updated and uploaded some code on another computer that got wiped and didn't send the new code to my current computer, the updated code is still on the board but I don't have access to it. How do I get it back?

body:
The short answer: You don't.

With enough know-how, you could probably extract the executable binary from the Arduino, but the source code is not installed on the device. You would need to run a decompiler on the binary. (Or read the machine code directly.) The output of a decompiler is usually pretty ugly however, and will look quite different from the original source-code. It won't have meaningful variable names, class names, or function names, and the code structure will likely be a little different than the original source code.

## EDIT:

As mckenzm pointed out in his answer, you could download the binary image from your Arduino, and then copy it onto another Arduino, but all that would let you do is to make an exact copy of the program. You wouldn't be able to modify it at all.


body:
You never can get the actual code back ... by reading the flash you might be able to get the executable/runtime code, but this doesn't look at all similar as your code, although it's functionally the same.

For example, all function names, all variable names will be just numbers (or non recognizable names), and all C statements are converted in machine language instructions, probably so many, you will need much knowledge to find out which instructions belong to which (original) C statements.


body:
  1. You read the contents of flash and save it to a file. It can then be re-flashed if your need is not to edit, but duplicate.

    * This reads all flash, including the bootloader, and also PROGMEM data.

  2. Use avr-objdump (or similar) to disassemble the instructions.

    * Again, PROGMEM data is going to be interpreted as opcodes, and may not be valid opcodes.

    * You may want to dump the fuses as well, for redirected vectors and such.

  3. Use pattern analysis to recognise source patterns as compiled. Then iteratively compile and compare fragments.

This is harder than is looks, whilst most Arduino code is very simple, the libraries can be be wild and woolly. At least the hex file is human readable, but little endian.

It might be easier to "walk through" the assembly and perform a translation of the perceived behaviour. OK for 10 instructions, but harder for 16K of them.

You will also need the Atmel/Microchip *def.inc files for the MPU component enumerations so that you know your DDRB from you DDRC a good disasembler should know.

You can do this well enough for Blink, and recognise stack pointer initialization.

It is much easier without a bootloader, as booting should jump to main and main can start at 0 other than after the vectors.

Of course lock bits will ruin your day, and it may just be better for character to code it again.


message:
SD card example freezes at line SD.begin() what should I do?

I have a 16GB SD card which is formated with FAT32. I'm trying to run the example codes presented for SD in Arduino. The SD card is inserted in the data logging shield and the CS pin in this shield is connected to pin 10.
I first tried the Cardinfo example and this is the result:
[![Serial Output of Cardinfo][1]][1]

The SD card is not empty, there exist a few files in it but this example was unable to show this files.
I then tried the example ReadWrite and the code freezes on line SD.begin(10).
I have no Idea where this problem is coming from.

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

body:
I had the same problem when I used a big SD card, maybe because some cards have a more modern format.

If you have smaller / older cards, try them and see if those work; than you rule out it is not a circuit/connection problem.


body:
I found another SD with 16GB capacity, and fortunately it worked. So the problem was because of the SD but I don't know what was the exact problem. I post the photo of this SD cards.

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

  [1]: https://i.stack.imgur.com/QExK6.jpg


message:
Is there way to wirelessly connect a arduino drone‘s camera?

Is there way to wirelessly connect a arduino drone‘s camera and stream to a set device from 10 km away?

body: Most (commonly available) RF links' communication distance is more limited than that (10 Km). If your flying locations are within a cell service area, a cell radio aboard the drone will probably give you the most universally available connection. Note that your streaming rate may vary with the location and cell congestion at that particular time, and may sometimes be limited, especially for video.


body: You could try using the most common solution for streaming low latency drone video, called FPV. You basically connect an AV video output from a camera to a transmitter and use a receiver on the ground to receive the AV video. After this you can connect it to any AV display (or a usb AV decoder if you want to use a computer) and you'll get an almost real time video feed of what is happening on your drone. To get long range you would need to buy a powerful transmitter, good receiver and decent antennas for bout of them. You can find different configurations for different ranges online.


message:
Current mouse pointer position with Digispark attiny85

I am trying DigiMouse library for attiny85 Digispark board.

It allows to emulate the mouse quite well.
However, I also need to know the current cursor position. Is there a way to get it?

body:
There is no way for a mouse of any kind (especially not one as minimal as DigiMouse.h) to know the current cursor position - USB just doesn't provide that kind of facility.

Instead you need to implement an "absolute" mouse (aka a "tablet").  However DigiMouse doesn't implement such a facility. So you would have to implement your own tablet driver.

A normal mouse sends a "delta" for the position. That is, a difference in position from whatever the current position is.  An absolute mouse, or tablet, sends the position on the screen as a proportion of some maximum set of dimensions.  Ideally that would be the same dimensions as your screen, but doesn't have to be.

The main differences between DigiMouse and whatever you would implement for a DigiTablet would be the "HID Report Descriptor". This defines what the data that is sent means and how the computer should interpret it.


message:
#include <ESP8266WiFi.h> Error with WiFiClientSecureBearSSL.h

I am new to the Arduino world and it seems that this simple problem is keeping me at the start line.

- I use the Generic ESP8266 Module as Board
- In my sketch I just write:

<!-- language-all: lang-cpp -->

    #include < ESP8266WiFi.h >
    void setup(){}
    void loop(){}

The <b>ERROR</b> is :

BearSSLHelpers.h:148:34: error: 'virtual const unsigned char* BearSSL::HashSHA256::oid()' marked override, but does not override

     virtual const unsigned char *oid() override;

                                  ^
How am I going to solve that? Any help is appreciated.

body:
You installed the latest git version of the ESP8266WiFi library into your libraries folder and this version is not compatible with the 2.5.2 version of the esp82666 Arduino core.

The ESP8266WiFi library is part of the esp8266 boards package. It should not be installed separately. Delete the library from your libraries folder.


message:
ATtiny167 Device not recognized

I'm frustrated I feel like I am 90% there but my computer will not recognize the ATtiny167. Here i9s the list of things I have completed/tried using Windows 10 and Arduino 1.8.6;

                      1) Installed Driver USB Bootloader is complete
                      2) Device Management I see the device
                      3) Arduino Sketch select 16.5 MHz board in parameters
                      4) Led on the board flashes sound beeps and stops flashing
                      5) "Device not recognized"
                      6) I have rebooted many times. I deleted everything and started over again with same
                          results
                      7) Used a 3rd party software to look at my USB ports it see the device
                       I have tried more than one device as well

             I'm stuck at this point. I've tried running example programs however the device is not recognized.

Any suggestions?

body:
If Digispark Pro clone is not recognized, you can try to use/upload .ino programs via ArduinoISP.

note use in File -> Preferences -> Additional Boards Manager URLs:
http://drazzy.com/package_drazzy.com_index.json
instead:
http://digistump.com/package_digistump_index.json

(The first is AttinyCore by Spence Konde, the second is the normal Digistump AVR Boards)

Then selected Tools -> Boards Manager, and Find AttinyCore -> (Wait and Install).

Now you can upload File -> Example -> ArduinoISP on your Arduino connected in ISP mode with your ATtiny167.

Now select ATtiny167 Board, 16Mhz (External) and write bootloader with your Arduino connected in same manner ISP mode with your ATtiny167.

And now upload any .ino file for ATtiny167 in the same manner with your Arduino connected in ISP mode with your ATtiny167.


message:
ESP32 WiFiClient request missing response

I am facing problem with ESP32. I use basic example for WiFiClient and making request to my server. The problem is that the response should be 15000 bytes long, but very often I got only 2750 or less.

    char buffer[15000];
    while (client.available()) {
      char c = client.read();
      buffer[i++] = c;
    }
    Serial.println(i);

body:
You are assuming that all 15000 bytes are available all the time.

They won't be.

Instead of "while available read something" you need to "While not enough has been read, then if available read something".

When reading from (assuming) HTTP you first need to read and interpret the headers (the lines before a single blank line).  One of these will be the "Content-Length:" header, which will tell you exactly how many bytes are in the body of the response. Then you use that to read the right number of bytes from the body.

So the sequence is:

1. Read line by line for the headers interpreting the ones you need to, until:
2. You receive a single blank line
3. Read the data byte-wise until you have read the number of bytes indicated in the Content-Length header.

If you aren't reading from an HTTP server and you are certain that the data is exactly 15000 bytes in length then you need to skip to point 3 above. Never assume that all the data is there. If there is data then read it, and repeat until you have totalled 15000 bytes.


message:
how to do Arduino to esp8266 communication

I am trying to do Arduino to ESP8266 communication, but I am not able to send data to esp8266. However I can receive data from esp8266.

Here if my Arduino code:
<!-- language-all: lang-cpp -->

    #include <SoftwareSerial.h>
    SoftwareSerial ESPserial(0, 1); // RX | TX

    void setup()
    {
      Serial.begin(115200);     // communication with the host computer
      // Start the software serial for communication with the ESP8266
      ESPserial.begin(9600);

      Serial.println("Enter 1 to turn led high & 2 to turn led low.");
    }
    // the loop function runs over and over again forever
    void loop() {
      // listen for communication from the ESP8266 and then write it to the serial monitor
      if ( ESPserial.available() )   {
        Serial.write( ESPserial.read() );
      }

      // listen for user input and send it to the ESP8266
      if ( Serial.available() )       {
        ESPserial.write( Serial.read() );
      }

    }

Here is esp8266 code:

    void setup()
    {
      Serial.begin(9600);     // communication with the host computer
      // Start the software serial for communication with the ESP8266
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_BUILTIN, OUTPUT);
    }
    // the loop function runs over and over again forever
    void loop() {
      Serial.println("ESP -- Hello");
      delay(1000);
      // listen for user input and send it to the ESP8266
      if ( Serial.available() )  {

        int ledState = Serial.parseInt();
        if (ledState == 1) {
          digitalWrite(LED_BUILTIN, HIGH);   // turn the LED on (HIGH is the voltage level)
          Serial.println("ESP Led On\n");
        }
        if (ledState == 2) {
          digitalWrite(LED_BUILTIN, LOW);    // turn the LED off by making the voltage LOW
          Serial.println("ESP Led Off\n");
        }
      }
    }

Once I upload both sketches, then I can see it terminal " ESP -- Hello " keep printing comming from esp8266 but when I enter 1 or 2, its not sent to esp8266 due to which I never see "ESP led on/off" messages , so correct me guys what mistake I am making.

body: using SoftSerial on the hardware serial isn't working on Arduino properly as sometime data receive and sometime not with garbage added so Using digital pins  other  2, & 3  other than hardware serial resolved the issue.


message:
How to burn arduino bootloader on SAMD21 chips using J-Link mini

I am planning on making my own custom PCB of a SAMD21 board. I would like to ask if anyone has experience uploading arduino bootloader on a [J-link Mini][1] although adafruit has a [guide][2] on this device, its not uploading a arduino bootloader.

On a related note which pins should I connect it to my SAMD21 chip ?

  [1]: https://www.mouser.com/ProductDetail/Segger-Microcontroller/80891?qs=sGAEpiMZZMve4/bfQkoj%2BGJy0Rcfgzx64YhEx8e9g/U=
  [2]: https://learn.adafruit.com/assets/69849

<!-- Trick -->

body: The Atmel EDBG would work for Arduino Zero since that has the EDBG chip. With Jlink, you can use Atmel Studio. Once the Jlink is connected to the chip via the 10 pin SWD header, goto the programmer option in Atmel Studio, select the chip and programmer and burn your firmware with the selected programmer. You can follow a tutorial [here](https://learn.adafruit.com/how-to-program-samd-bootloaders/programming-the-bootloader-with-atmel-studio) which walks through it.


message:
L298N motor driver issue

I am facing the same issue with my motor driver. Initially I ran the code and connected the L298N with Arduino and it worked fine. At that time motors were running absolutely fine. But when I ran it sometimes later then the motors are not running. However the motors are getting power but I think thy are getting very less power from the Motor Driver.

I directly ran motors from Arduino +5V pin and the motors were running fine. Is there something wrong with my L298N motor driver?

One more thing I checked the power for all the pins for L298N motor Driver and all pins are working fine.

Here is my complete program:
<!-- language-all: lang-cpp -->

    const int MOTOR_RIGHT = 1;
    const int MOTOR_LEFT =  2;
    const int MR_CONTROL_PIN_A = 8;
    const int MR_CONTROL_PIN_B = 9;
    const int ML_CONTROL_PIN_A = 10;
    const int ML_CONTROL_PIN_B = 11;

    void setup() {
      // These two pins will act as output pin

      pinMode(MR_CONTROL_PIN_A,OUTPUT);
      pinMode(MR_CONTROL_PIN_B,OUTPUT);
      pinMode(ML_CONTROL_PIN_A,OUTPUT);
      pinMode(ML_CONTROL_PIN_B,OUTPUT);
      Serial.begin(4800);

    }

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

      forward(MOTOR_RIGHT);
      forward(MOTOR_LEFT);
      delay(5000);
      stopMotor(MOTOR_RIGHT);
      stopMotor(MOTOR_LEFT);
      delay(1000);
      backward(MOTOR_RIGHT);
      backward(MOTOR_LEFT);
      delay(5000);
      stopMotor(MOTOR_RIGHT);
      stopMotor(MOTOR_LEFT);
      delay(1000);

    }
    /////////////////////////////////////////////////////////////////////
    //Forward

      void forward(int motorNo)
      {

      Serial.print("\r\n Forward : ");
      Serial.print(motorNo);

      switch(motorNo)
      {
        case MOTOR_RIGHT:
        digitalWrite(MR_CONTROL_PIN_A,HIGH);
        digitalWrite(MR_CONTROL_PIN_B,LOW);
        break;

        case MOTOR_LEFT:
        digitalWrite(ML_CONTROL_PIN_A,HIGH);
        digitalWrite(ML_CONTROL_PIN_B,LOW);
        break;

      default:
        Serial.print("\r\n Error :Invalid Motor No ");
        Serial.print(motorNo);
       }
      }

    //////////////////////////////////////////////////////////////////////
      void backward(int motorNo)
      {
       Serial.print("\r\n Backward : ");
       Serial.print(motorNo);
      switch(motorNo)
      {
        case MOTOR_RIGHT:
        digitalWrite(MR_CONTROL_PIN_A,LOW);
        digitalWrite(MR_CONTROL_PIN_B,HIGH);
        break;

        case MOTOR_LEFT:
        digitalWrite(ML_CONTROL_PIN_A,LOW);
        digitalWrite(ML_CONTROL_PIN_B,HIGH);
        break;

      default:
        Serial.print("\r\n Error :Invalid Motor No : ");
        Serial.print(motorNo);
       }

      }

    ///////////////////////////////////////////////////////////////////////
      void stopMotor(int motorNo)
      {
       Serial.print("\r\n STOP : ");
       Serial.print(motorNo);
      switch(motorNo)
      {
        case MOTOR_RIGHT:
        digitalWrite(MR_CONTROL_PIN_A,HIGH);
        digitalWrite(MR_CONTROL_PIN_B,HIGH);
        break;

        case MOTOR_LEFT:
        digitalWrite(ML_CONTROL_PIN_A,LOW);
        digitalWrite(ML_CONTROL_PIN_B,LOW);
        break;

      default:
        Serial.print("\r\n Error :Invalid Motor No : ");
        Serial.print(motorNo);
       }

      }

Is there something wrong with my L298N ? How can I test it?

body:
The specified minimum voltage for the motors is **2.5 volts higher than the logic supply**.

You need to use a separate supply for the motor that is higher than the logic power.


body: 9 volt batteries have very low capacity. That could be the cause of your problem. Replace the battery with a power supply with higher capacity. Or other bigger batteries that add up to around 9 volts.


message:
Blink Adafruit_NeoPixel

I wish to blink all the strip. In the code below it just blink the first LED, how can I fix it?

Code:

    #include <Adafruit_NeoPixel.h>

    #define PIN 6
    #define NUM_LEDS 24

    Adafruit_NeoPixel strip = Adafruit_NeoPixel(NUM_LEDS, PIN, NEO_GRB + NEO_KHZ800);

    void setup() {
      strip.begin();
      strip.show();
    }

    void loop() {
      strip.setPixelColor(0, 255, 255, 255);
      strip.show();
      delay(1000);
      strip.setPixelColor(0, 0, 0, 0);
      strip.show();
      delay(1000);
    }

body:
The first argument of `setPixelColor` is is the number of the led. In your case 0, so the first led.

Instead use a `for` loop to set all the leds from 0 until (excluding) 24 (which is stored in `NUM_LEDS`).

    void loop()
    {
      for (int led = 0; led < NUM_LEDS ; led++)
      {
        strip.setPixelColor(led, 255, 255, 255);
      }
      strip.show();
      delay(1000);

      for (int led = 0; led < NUM_LEDS ; led++)
      {
        strip.setPixelColor(led, 255, 255, 255);
      }
      strip.show();
      delay(1000);

To make the code better (shorter, but more important more maintainable, and reducing code duplication), create a separate function:

    void loop()
    {
      setLeds(255);
      setLeds(0);
    }

    void setLeds(int intensity)
    {
      for (int led = 0; led < NUM_LEDS ; led++)
      {
        strip.setPixelColor(led, intensity, intensity, intensity);
      }

      strip.show();
      delay(1000);
    }


message:
Turn on/off low current device (LED) with Arduino

I am just starting with Arduino and my first project consists in switching a LED light with Arduino.

I know a relay must be use to control AC high voltage device (i.e. 240V), however, as my LED seems to be powered by DC 7V voltage (7V - 0.43A written on the power supply which is integrated within the outlet, so I can only access the low voltage wire), I am wondering how to control such a device.

Do I still need a relay or the Arduino can handle this on its own?

body:
Use a power MOSFET transistor. This one from Sparkfun is an example: https://www.sparkfun.com/products/10213

If you use a relay you will probably need transistor and a separate power supply to drive the relay coils anyway, and will also need a [**flyback diode**][1] to protect the control circuit of the relay from the "back EMF" of the relay coils.

**DO NOT** try to drive relay coils directly from an Arduino digital pin. It will almost certainly fry the Arduino pin, and might destroy the entire Arduino.

A MOSFET transistor like the one I linked can be controlled directly from an Arduino GPIO line, and can switch DC loads of up to 60V and 30A.

  [1]: https://en.wikipedia.org/wiki/Flyback_diode


message:
Using an Arduino Nano to program (as ISP) a standalone 328p

I uploaded the ArduinoISP sketch to an Arduino Nano to use it as a programmer for other chips.

It worked successfully to program an ATtiny45, I did the usual wiring between them, and added a 10uF between RST and GND of the Nano. Everything worked.

Now I'd like to program a standalone ATmega328p with the Nano, I did the usual wiring as well (see this [tutorial](http://www.martyncurrey.com/arduino-nano-as-an-isp-programmer/)), as well as this 10uF cap.

But it does't work:

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

The reason might be because this 328p comes from an Arduino Uno, probably configured to be ext-clocked by a crystal. Whereas I don't have any crystal here and wanted to clock the 328p with the internal clock.

**Question: how can I restore the 328p to factory default / internal clock, if I don't have a crystal?**

Or what other reason can this error be?

Edit: a solution is found here: https://arduino.stackexchange.com/questions/68779/change-the-fuses-of-an-arduino-uno-can-an-arduino-uno-change-its-own-fuses

body:
You can temporarily put it in an UNO. Don't connect this UNO via USB, but use jumper wires to connect the ISP pins plus the power pins to the other Arduino that you are using as an ISP programmer. (You could also use the (2x3) ISP header on the UNO if that's more convenient.)

Or, you could use a high voltage programmer.

Or get/desolder a crystal from some junk electronics. Exact frequency doesn't matter that much. I think somewhere between 1 Mhz and 16 Mhz would work.

You can then reset the fuses, so it doesn't need a crystal.


body:
That error basically says the bootloader you are trying to burn does not *appear* to be for that device.  This could be due to corruption or (more likely in your case) harvesting and reconfiguring the hardware.

If the error does not appear when you try to load the bootloader for the Uno (original device you harvested it from for those harvesting from other configurations), you will know it is the latter.

Either way, you can try to -f it by running avrdude to burn the bootloader via command line (as it says).  I've successfully saved  stuff with a corrupt bootloader this way although i've never found it worth the hassle to harvest and reconfigure- if you pulled it off the uno, surely you can stitch it to a clock.

If your clock is off by a bit, you may just need to get lucky over several attempts :)


message:
exit status 1 error compiling for board arduino/Genuino Uno when tone code is used

I am just trying to use an ultrasonic sensor with a buzzer but the buzzer doesn't respond to my code. I mean it doesn't make any sound. I tested it to check if by sending 5 volts to it, it will make a sound.. and it did... but using this code below... for some reason, it doesn't make any sound....

    #include <NewPing.h>
    #define TRIGGER_PIN 11
    #define  ECHO_PIN 12
    #define buzzer 13

    NewPing sonar1 (TRIGGER_PIN, ECHO_PIN);

    long inches1;
    int sound = 250;

    void setup (){

      Serial.begin (9600);

      pinMode (TRIGGER_PIN, OUTPUT);
      pinMode (ECHO_PIN, INPUT);
      pinMode (buzzer, OUTPUT);

    }

    void loop () {

      inches1 = sonar1.ping_in();
       if (inches1 <= 5 ){
     //   sound = 250;
        tone(buzzer, 1000); // Send 1KHz sound signal...
        delay(1000);        // ...for 1 sec
        noTone(buzzer);     // Stop sound...
        delay(1000);
        Serial.print (inches1);
        Serial.print ('\n');
       }
      delay (200);
    }

body:
If you have a look at the complete error message you will see that there is a collision between the libraries **NewPing** and **Tone**.

    Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Arduino/Genuino Uno"

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

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

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

    collect2.exe: error: ld returned 1 exit status

    exit status 1
    Error compiling for board Arduino/Genuino Uno.


message:
How can I make my arduino start when a magnet is sensed, and stay running until the application determines it was to shut down

My thought was to use a magnetic reed switch to turn on the arduino.  But how do I keep it running if the magnet is moved?  The idea is that the application will determine when it is ok to shut off the power to the arduino.

I don't want any power usage when the system is dormant since it could be weeks between magnetic triggers.

Doug

body: Put your Arduino into deep sleep and attach an interrupt to a pin that is monitoring your reed switch. Once triggered it can run your code before deep sleeping again


body:
The [LowPower][1] library will help you to minimize the amount of power used by putting the Arduino to sleep. The Arduino will awaken once the magnetic reed switch triggers it, then you can execute some code before it goes back to sleep again.

There is an [example sketch][2] that may work for you:
<!-- language-all: lang-cpp -->

    // **** INCLUDES *****
    #include "LowPower.h"

    // Use pin 2 as wake up pin
    const int wakeUpPin = 2;

    void wakeUp()
    {
        // Just a handler for the pin interrupt.
    }

    void setup()
    {
        // Configure wake up pin as input.
        // This will consumes few uA of current.
        pinMode(wakeUpPin, INPUT);
    }

    void loop()
    {
        // Allow wake up pin to trigger interrupt on low.
        attachInterrupt(0, wakeUp, LOW);

        // Enter power down state with ADC and BOD module disabled.
        // Wake up when wake up pin is low.
        LowPower.powerDown(SLEEP_FOREVER, ADC_OFF, BOD_OFF);

        // Disable external pin interrupt on wake up pin.
        detachInterrupt(0);

        // Do something here
        // Example: Read sensor, data logging, data transmission.
    }

  [1]: https://github.com/rocketscream/Low-Power
  [2]: https://github.com/rocketscream/Low-Power/blob/master/Examples/powerDownWakeExternalInterrupt/powerDownWakeExternalInterrupt.ino


body:
You can connect a power MOSFET in parallel to the reed switch, that is controlled by the Arduino:

<!-- Begin schematic: In order to preserve an editable schematic, please
     don't edit this section directly.
     Click the "edit" link below the image in the preview instead. -->

![schematic](https://i.stack.imgur.com/SN0Ee.png)

<!-- End schematic -->

The Arduino powers up, when the reed switch is activated. Then you can activate (drive HIGH) the pin connected to the MOSFET, so that the Arduino is still provided with the needed power through the MOSFET, if the reed switch turns off. If the correct time comes to turn the Arduino off, you can release the digital pin (drive LOW or high impedance/input), so that it get's pulled to low. That will deactivate the MOSFET, which cuts the power off the Arduino.


message:
Change the fuses of an Arduino Uno (can an Arduino Uno change its own fuses?)

For now, I'm using an Arduino Uno alone including its 328p (no other external chip to program).

I would like to **change its fuses to internal 8 Mhz clock** (because then I'll move the 328p out of the Arduino Uno), and for simplicity I'd like to do it from Arduino IDE.

Here is what I tried:

* I created a new entry in boards.txt copy-pasted from Uno, [fuses modified](http://www.engbedded.com/fusecalc), like this:

        atmega328p.name=Atmega328p
        atmega328p.upload.tool=avrdude
        atmega328p.upload.protocol=arduino
        atmega328p.upload.maximum_size=32256
        atmega328p.upload.maximum_data_size=2048
        atmega328p.upload.speed=115200

        atmega328p.bootloader.tool=avrdude
        atmega328p.bootloader.low_fuses=0x62
        atmega328p.bootloader.high_fuses=0xD9
        atmega328p.bootloader.extended_fuses=0xFF
        atmega328p.bootloader.unlock_bits=0x3F
        atmega328p.bootloader.lock_bits=0x0F
        atmega328p.bootloader.file=optiboot/optiboot_atmega328.hex

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

* I selected this board in *Tools > Board: Atmega328p*

* I tried to *Upload* any sketch (and not *Upload with programmer* since I have no other chip connected to the Arduino Uno), hoping it would modify the fuses during the (successful) *Upload* process.

**I think it didn't work (when I move the 328p outside of the Uno it doesn't work).**

**How can I change the fuses for an Arduino Uno directly from Arduino IDE, to enable internal 8 Mhz clock?**

____

PS: "Tools > Burn Bootloader" does not succeed, but I think this is normal, since there is just the Arduino Uno, and no other chip / nothing to use as a "Programmer":

> avrdude: stk500_recv(): programmer is not responding
> avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x03

body: You need a programmer to burn fuses.  If you have another arduino then you can use the Arduino as ISP example sketch in the IDE.  You can't burn fuses just using the USB cable like you upload code with.  The only reason that can talk to the chip at all is because there is another chip to convert it to serial and a bootloader on the 328P to allow it to upload code via serial.


body:
As mentioned in the other answer, it seems that it's not possible for an Arduino Uno to change *its own fuses*.

So here is how I did:

* I used a Nano (loaded with "Arduino as ISP") as programmer for the Uno with this classical wiring (except that in my case, the left board, the programmer, is a Nano):

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

* I added this to `boards.txt` (source [here](https://forum.arduino.cc/index.php?topic=308347.msg2149945#msg2149945)):

        ##############################################################
        atmega328bb.name=ATmega328 on a breadboard (8 MHz internal clock)
        atmega328bb.upload.protocol=arduino
        atmega328bb.upload.maximum_size=30720
        atmega328bb.upload.maximum_data_size=2048
        atmega328bb.upload.speed=57600
        atmega328bb.upload.tool=avrdude
        atmega328bb.bootloader.tool=arduino:avrdude
        atmega328bb.bootloader.low_fuses=0xE2
        atmega328bb.bootloader.high_fuses=0xDA
        atmega328bb.bootloader.extended_fuses=0x05
        atmega328bb.bootloader.file=atmega/ATmegaBOOT_168_atmega328_pro_8MHz.hex
        atmega328bb.bootloader.unlock_bits=0x3F
        atmega328bb.bootloader.lock_bits=0x0F
        atmega328bb.build.mcu=atmega328p
        atmega328bb.build.f_cpu=8000000L
        atmega328bb.build.core=arduino
        atmega328bb.build.variant=standard
        atmega328bb.build.board=AVR_BARE

* I used *"Programmer: Arduino as ISP"*, then *"Burn bootloader"* then *"Upload with programmer"* with any sketch.

* Then the fuses are programmed to Internal 8 Mhz, and we can take the ATmega328p out of the Uno and move it on a breadboard! Working now :)

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


body:
This is technically possible, but tricky.

First you'd have to wire up the Arduino with some jumpers in such a way that the 328P can use its ICSP header to reprogram the 16U2/8U2 via that chips own header. With the right custom firmware in place you could then re-wire the board so that the 16U2 changes the fuses of the 328P upon boot and reuploads the firmware before switching into its usual function. Then it's just a matter of having the 328P reprogram the 16U2 with the original DFU firmware, and presto! An Arduino that changed its own fuses!

If you just need to change the fuses without a ICSP programmer then that can be done by just [programming the 16U2 chip directly through its USB port](https://welldoneblog.fedevel.com/2015/04/13/how-to-flash-arduino-bootloader-without-a-programmer/) (although technically that doesn't qualify as the Uno "programming itself").


message:
can't power up arduino from dc jack

Yesterday I was working on Arduino based bluetooth car. I was using adafruit motor shield v1. Arduino and shield were on same power supply(11v li-ion cell battery). Every thing was fine. I decided to add some leds to my car. I connected two leds with 5v on shield pins(leds were in series and were multi-colored so 5v was okay). It worked for sometime but later it stopped working. Green led on arduino was on while other were off. I disconnected shield and supplied arduino from dc jack, same result. Then I connected arduino with usb cable then everything was fine. Now it works because I supply arduino from usb and shield is working too either from usb supply or external supply. What could possibly go wrong?

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

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

body:
It would appear that the output of the power regulator pin has been vaporized.

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

From the Arduino R3 schematic we see this part as U1 which is an NCP1117ST50T3G power regulator.  [Here][2] is that data sheet for that part. From that data sheet we see the physical image of the part.

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

It appears that pin 2 has been vaporized.  If we look at the schematic of the Arduino R3 we see where pin 2 supplies the regulated power to the rest of the Arduino board and likely any connected electronics.  Note the red "X" indicating the vaporized pin 2.

[![enter image description here][4]][4]

The schematic and the data sheet both indicate the regulator's TAB is also an output.  If true it is difficult to explain why pin 2 vaporized.  Perhaps this particular version of the regulator does not use the TAB as an output.  Or perhaps the Arduino R3 PCB and schematic do not agree.

Added later...

There has been a comment that U1 (the NCP1117ST50T3G power regulator) may sometimes be manufactured with out the center pin.  Still, if you can power the Arduino R3 using the USB port and unable to power the Arduino R3 using power through the barrel jack, the likely suspects are U1 and D1.  However, to be sure, you would have to check the voltage before D1 and after U1.

  [1]: https://i.stack.imgur.com/GaiuA.png
  [2]: https://www.onsemi.com/pub/Collateral/NCP1117-D.PDF
  [3]: https://i.stack.imgur.com/KB8Nf.png
  [4]: https://i.stack.imgur.com/GmMl8.png


message:
Why can't I control speed of the motor? (M1 and E1)

When `myservo_1,myservo_2,myservo_3,myservo_4` is commented, I can't control the speed of my M1 motor. But only when I uncomment `myservo_1` and so on, I can control the motor speed again.

Can someone help me? My codes are listed down below:

    #include <Servo.h>
    Servo myservo_1;
    Servo myservo_2;
    Servo myservo_3;
    Servo myservo_4;

    int SensorL = 0;
    int SensorR = 0;
    int SensorM = 0;

    #define E1 10
    #define M1 12
    #define E2 11
    #define M2 13
    int pos = 0;
    int incomingByte = 0;

    void setup()
    {
      Serial.begin(9600);
      myservo_1.attach(9);
      myservo_2.attach(8);
      myservo_3.attach(7);
      myservo_4.attach(6);
      pinMode(SensorL, INPUT);
      pinMode(SensorR, INPUT);
      pinMode(SensorM, INPUT);
      pinMode(M1, OUTPUT);
      pinMode(M2, OUTPUT);
    //  pinMode(E1, OUTPUT);
    //  pinMode(E2, OUTPUT);
    }

    void loop()
    {
      SensorR = digitalRead(2);
      SensorL = digitalRead(3);
      SensorM = digitalRead(5);

      if (SensorL == LOW && SensorR == LOW && SensorM == HIGH)
      {
        digitalWrite(M1, HIGH);
        digitalWrite(M2, HIGH);
        analogWrite(E1, 255);
        analogWrite(E2, 255);
        Serial.println(" FORWARD ");
        //delay(1);
      }
      if (SensorL == HIGH && SensorR == LOW && SensorM == HIGH)
      {
        digitalWrite(M1, HIGH);
        digitalWrite(M2, LOW);
        analogWrite(E1, 255);
        analogWrite(E2, 255);
        Serial.println(" LEFT ");
        //delay(1);
      }
      if (SensorL == LOW && SensorR == HIGH && SensorM == HIGH) //move right
      {
        digitalWrite(M1, LOW);
        digitalWrite(M2, HIGH);
        analogWrite(E1, 255);
        analogWrite(E2, 255);
        Serial.println(" RIGHT ");
        //delay(1);
      }

      if (SensorL == HIGH && SensorR == HIGH && SensorM == HIGH) //stop
      {
        digitalWrite(M1, HIGH);
        digitalWrite(M2, HIGH);
        analogWrite(E1, 0);
        analogWrite(E2, 0);
        Serial.println(" STOP ");
        //delay(1);
      }

      if (SensorL == HIGH && SensorR == LOW && SensorM == LOW) //move left
      {
        digitalWrite(M1, HIGH);
        digitalWrite(M2, LOW);
        analogWrite(E1, 125);
        analogWrite(E2, 125);
        Serial.println(" LEFT ");
        //delay(1);
      }

      if (SensorL == LOW && SensorR == HIGH && SensorM == LOW) //move right
      {
        digitalWrite(M1, LOW);
        digitalWrite(M2, HIGH);
        analogWrite(E1, 125);
        analogWrite(E2, 125);
        Serial.println(" MoVE Right ");
        //delay(1);
      }

      if (Serial.available() > 0)
      {
        incomingByte = Serial.read();
        {
          {
            if (incomingByte == 'J')//ARM OPEN
            {
              myservo_1.write(0);
              Serial.println(" ARM OPEN ");
            }
            if (incomingByte == 'L')//ARM CLOSE
            {
              myservo_1.write(180);
              Serial.println(" ARM CLOSE ");
            }
            if (incomingByte == 'I')//ARM UP
            {
              myservo_2.write(0);
              myservo_3.write(180);
              Serial.println(" ARM UP ");
            }
            if (incomingByte == 'K')//ARM DOWN
            {
              myservo_2.write(180);
              myservo_3.write(0);
              Serial.println(" ARM DOWN ");
            }
            if (incomingByte == 'U')//ROTATE LEFT
            {
              myservo_4.write(0);
              Serial.println(" ROTATE LEFT ");
            }
            if (incomingByte == 'O')//ROTATE RIGHT
            {
              myservo_4.write(180);
              Serial.println(" ROATE RIGHT ");
            }
            if (incomingByte == 'M')
            {
              myservo_1.write(90);
              myservo_2.write(90);
              myservo_3.write(90);
              myservo_4.write(90);
              Serial.println(" ALL STOP ");
            }
            if (incomingByte == 'N')//ARM STOP
            {
              myservo_1.write(90);
              Serial.println(" ARM STOP ");
            }
            if (incomingByte == 'B')//UP DOWN STOP
            {
              myservo_2.write(90);
              myservo_3.write(90);
              Serial.println(" UP DOWN STOP ");
            }
            if (incomingByte == 'V')//ROTATION STOP
            {
              myservo_4.write(90);
              Serial.println(" ROTATION STOP ");
            }
            if (incomingByte == 'W')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 200);
              analogWrite(E2, 0);
              Serial.println(" FORWARD ");
            }
            if (incomingByte == 'Z')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 255);
              analogWrite(E2, 255);
              Serial.println(" FORWARD ");
              delay(100);
            }
            if (incomingByte == 'S')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, LOW);
              analogWrite(E1, 255);
              analogWrite(E2, 255);
              Serial.println(" REVERSE ");
            }
            if (incomingByte == 'A')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, LOW);
              analogWrite(E1, 255);
              analogWrite(E2, 255);
              Serial.println(" LEFT ");
            }
            if (incomingByte == 'D')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 255);
              analogWrite(E2, 255);
              Serial.println(" TURNING RIGHT ");
            }
            if (incomingByte == 'X')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 0);
              analogWrite(E2, 0);
              Serial.println(" STOP MANAUAL ");
            }
            if (incomingByte == 'w')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 125);
              analogWrite(E2, 125);
              Serial.println(" SLOW FORWARD ");
            }
            if (incomingByte == 's')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, LOW);
              analogWrite(E1, 125);
              analogWrite(E2, 125);
              Serial.println(" SLOW REVERSE ");
            }
            if (incomingByte == 'a')
            {
              digitalWrite(M1, HIGH);
              digitalWrite(M2, LOW);
              analogWrite(E1, 125);
              analogWrite(E2, 125);
              Serial.println(" SLOW LEFT ");
            }
            if (incomingByte == 'd')
            {
              digitalWrite(M1, LOW);
              digitalWrite(M2, HIGH);
              analogWrite(E1, 125);
              analogWrite(E2, 125);
              Serial.println(" SLOW RIGHT ");
            }
          }
        }
      }
    }

body:
The Servo library uses `timer 1` to send the signals to the servos. But `timer 1` is also used to run PWM on pins 9 and 10. It can't however do both.

So since Motor E1 uses pin 10, and `timer 1` is already used by the Servo library, PWM, and by extension, `analogWrite` doesn't work.

E2 uses pin 11, which uses `timer 2` for it's PWM, so is therefor no affected.

So move E1 to one of the PWM pins, other than 9 and 10, and thing should start working again.

I however don't know why M1 doesn't work.


body:
 - Please correct your code there are several mistakes, such as
   1. the lines at beginning of loop SensorR = digitalRead(2); SensorL = digitalRead(3); SensorM = digitalRead(5); doesn't make any sense.. as
   you not defined 2,3,5 pin as input. And for taking analog input
   please change pins 2,3,5 and analog pins..
   2. Motor Pin M1 and M2 are connected 12,13 which are not pwm pins so you can't use to change the speed of your Motor.. Please make this
   code sensible....


message:
how to switch more 230v with arduino?

i am working on a project automatic street lighting with arduino.i am done with the code and the circuit.i am able to switch the AC voltage in my house which is 230v,50hz with a 230v relay but when its comes to implementation there are 30 to 40 street lights are connected and the voltage is very high I think around 415 volts.what should I use to control that? need help

body:
You have to use a relay that can handle minimum 415 volts (and keep some reserve).

Also take the current/amperage into account (possibly use multiple relays).


message:
When I verify the sketch I get several errors

I am extremely new to Arduino coding and have downloaded a sketch for the PCA9685 to use with model railroading and turnout control.  When I verify the sketch I get several errors ... I don't even know how to resolve and could use some assistance.  There are two sketches:

#1:

        /***************************************************
      This sketch can be used to operate any number of turnouts on a
      Model Railroad. Code blocks can be added to accomodate any number
      of servos. This sketch uses only two servos for this demonstration.

      The pushbutton can be replaced with a SPST switch
      commonly used on a control panel. Three pin Bicolor LED can be used
      in place of two seperate LEDs in each circuit.

      10K Ohm pulldown resistor used on switch
      330 Ohm resistor used on LEDs. One per pair of LEDs

      Created 03/02/2019 by Tom Kvichak
      https://tomstrainsandthings.com/
      Additional Arduino Projects can be found at the above web address

     ****************************************************/

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>
    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

    int buttonPin0 = 2;   // Can add as many buttons as needed
    int ledPin0C = 3;     // C designates Closed position of turnout
    int ledPin0T = 4;     // T designates Thrown position of turnout
    int buttonState0 = 0;

    int buttonPin1 = 5;
    int ledPin1C = 6;
    int ledPin1T = 7;
    int buttonState1 = 0;

    void setup() {
      Serial.begin(9600);
      Serial.println("pca9685_TurnoutFinal!");
      pwm.begin();
      pwm.setPWMFreq(60);
      delay(30);

      pinMode(ledPin0C, OUTPUT);
      pinMode(ledPin0T, OUTPUT);
      pinMode(buttonPin0, INPUT);
      pinMode(ledPin1C, OUTPUT);
      pinMode(ledPin1T, OUTPUT);
      pinMode(buttonPin1, INPUT);
    }

    void loop() {
      ///////////
      buttonState0 = digitalRead(buttonPin0);
      if (buttonState0 == HIGH) {
        pwm.setPWM(0, 0, 370);
        digitalWrite(ledPin0T, LOW);
        digitalWrite(ledPin0C, HIGH);
      }
      else  {
        pwm.setPWM(0, 0, 285);
        digitalWrite(ledPin0C, LOW);
        digitalWrite(ledPin0T, HIGH);
      }
      //////////
      buttonState1 = digitalRead(buttonPin1);
      if (buttonState1 == HIGH) {
        pwm.setPWM(1, 0, 370);
        digitalWrite(ledPin1T, LOW);
        digitalWrite(ledPin1C, HIGH);
      }
      else  {
        pwm.setPWM(1, 0, 285);
        digitalWrite(ledPin1C, LOW);
        digitalWrite(ledPin1T, HIGH);
      }
      //////////
    }

#2:

        /***************************************************
      This is an example for our Adafruit 16-channel PWM & Servo driver
      Servo test - this will drive 8 servos, one after the other on the
      first 8 pins of the PCA9685

      Pick one up today in the adafruit shop!
      ------> http://www.adafruit.com/products/815

      These drivers use I2C to communicate, 2 pins are required to
      interface.

      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!

      Written by Limor Fried/Ladyada for Adafruit Industries.
      BSD license, all text above must be included in any redistribution
     ****************************************************/

    #include <Wire.h>
    #include <Adafruit_PWMServoDriver.h>

    Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
    //Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x41);

    #define SERVOMIN  110 // this is the 'minimum' pulse length count (out of 4096)
    #define SERVOMAX  510 // this is the 'maximum' pulse length count (out of 4096)

    // May have to adjust values to match your servos
    // Test your servo with the procedures below

    // our servo # counter
    uint8_t servonum = 0;

    void setup() {
      Serial.begin(9600);
      Serial.println("pca9685_TurnoutTest!");
      pwm.begin();
      pwm.setPWMFreq(60);  // Analog servos run at ~60 Hz updates
      delay(50);
    }
    ///////////////////Functions//////////////////////

    void driveMin() {
      pwm.setPWM(servonum, 0, SERVOMIN);    //Use to test low range
    }
    void driveMax() {
      pwm.setPWM(servonum, 0, SERVOMAX);    //Use to test high range
    }
    ///////////////End Of Functions//////////////////

    void loop() {

      for( int angle =0; angle<181; angle +=15){  // testing only right now
        delay(500);
        pwm.setPWM(1, 0, convert2angle(angle) );   // May only need this for sweeping the servo
      }

    }
    int convert2angle(int myang){
       int pulse = map(myang,0, 180, SERVOMIN,SERVOMAX);// map angle of 0 to 180 to Servo min and Servo max
       Serial.print("Angle/Pulse: ");Serial.print(myang);
       Serial.print(" / "); Serial.println(pulse);
       return pulse;
    }

**ERROR MESSAGES:**

    pca9685_TurnoutTest:23:25: error: redefinition of 'Adafruit_PWMServoDriver pwm'

     Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                             ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:21:25: note: 'Adafruit_PWMServoDriver pwm' previously declared here

     Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

                             ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void setup()':

    pca9685_TurnoutTest:35:6: error: redefinition of 'void setup()'

     void setup() {

          ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:33:6: note: 'void setup()' previously defined here

     void setup() {

          ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutTest.ino: In function 'void loop()':

    pca9685_TurnoutTest:52:6: error: redefinition of 'void loop()'

     void loop() {

          ^

    C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master\examples\pca9685_TurnoutFinal\pca9685_TurnoutFinal.ino:48:6: note: 'void loop()' previously defined here

     void loop() {

          ^

    Using library Wire at version 1.0 in folder: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\hardware\arduino\avr\libraries\Wire
    Using library Adafruit-PWM-Servo-Driver-Library-master at version 2.0.0 in folder: C:\Users\wdhen\Documents\Arduino\libraries\Adafruit-PWM-Servo-Driver-Library-master
    exit status 1
    redefinition of 'Adafruit_PWMServoDriver pwm'

body:
You seem to compile a sketch from a folder, where more than 1 .ino file is placed. I guess this from the paths, that are mentioned in the error messages.

The Arduino IDE supports you to organize your code into multiple .ino files, so that big code can be read way easier. For this it put's together all .ino files in the folder of the main sketch, so that they get compiled together.

Since you have at least 2 full sketches in the same folder, this leads to a redefinition error, since these resources (the variable `pwm` and the functions `setup()` and `loop()`) are already defined by the first sketch, when the compiler gets the second sketch.

You have to put all your individual sketches into own folders. Then the error will not appear. I tried to compile your two sketches individually and that worked fine.


message:
Why Arduino pins don't output 0 volt?

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

    void loop() {
      analogWrite(5, 0);
      // or
      //digitalWrite(5, LOW);
    }

Output is 0.003V and the tiny voltage causes the circuit to draw 20uA.

Is there anyway to get absolute 0V from Arduino PWM pin?

body:
It doesn't output 0v because it's near impossible. 0.003v is in fact very low. The LOW output, according to the datasheet, can be as high as 0.8v (when powered by 5v) and still be considered valid.

LOW does not mean 0v. It means "below the voltage threshold that is considered a LOW".


message:
Interface a mobile phone's finger print scanner with arduino

Is it possible to salvage a fingerprint scanner from an old and dead smartphone and use it with Arduino? I am not talking about writing an android program and send data to Arduino over Bluetooth or WiFi, I am talking about wiring up fingerprint scanner of a mobile phone to Arduino.

body:
Possible but not directly as the arduino compatible fingerprint sensor contains image formation and saving mechanism which means that those sensors scan a fingerprint form image and send the scan status not the finger print image....

As in case of fingerprint sensor of phones, the sensor directly send the whole image...

so you have to use FPGA (Field Programming Gate Arrays) to make communication between that...

But this is a very expensive way... As FPGA are very expensive but have huge functionality means you can design any circuit any sensor any controller you want using FPGA


body:
In general: It depends. We can only talk about the general situation, not about details, because we don't know the exact sensor type. You are facing some serious problems when doing this.

- Without a part number or something like this, we cannot say, how the sensor communicates with the phones mainboard. It might or might not be a communication interface, that the Arduino has or can be made capable of.
- The sensor and it's interface might be proprietary, which would mean, that there is no public documentation about the interface and how it works. Reverse Engineering something like this need mostly a big amount of time and experience with various electronical systems.
- As Shyam Singla already pointed out in his/her answer, most (if not all) Arduino compatible fingerprint sensors don't send the actual fingerprint image, but do the difficult image handling and recognition by themselves. The Arduino only get's status information (for example if a previously saved fingerprint was detected). On a phone, this is most likely not the case. The main processor of the phone has way enough power to do the calculation by itself. It doesn't need to offload them to an external chip like the Arduino needs to. (Also this gives the vendor the opportunity to update the recognition software later on with a simple OS update.) That means, that the sensor will most likely only send images and you would need to do the image handling and recognition on the Arduino. AVR based Arduinos (like the Uno or Nano) are totally undersized for this.
- The connection pins of the sensor will be very small and difficult to connect, especially if you are a beginner.
- You would have to use level shifters and voltage regulators to interface between the 5V devices Uno/Nano and the sensor, which will most likely work with a significantly lower voltage (at max 3.3V, most likely less).

Using FPGAs to tackle some of these problems is possible, but also very challening. If you need to ask this question, this is most likely out of scope. (A friend of mine did program a FPGA for his physics master on university. It can be very difficult.)

All in all I would say, it is not worth the effort to even try this. Instead buy an Arduino compatible fingerprint sensor.


body:
Long-shot, but if the phone is still functional enough to unlock with a fingerprint, try sensing the overall screen brightness when locked and when unlocked, and use that as the "Fingerprint matched" signal. Obviously this won't work with a truly dead phone.

A *lot* of processing goes into reading and storing or matching a finger-print. The magic is in the software, not (only in) the sensor. An Arduino (Uno class or similar) is way under-powered for the task. Perhaps one of the Arm- or other high-end Arduinos would have the capability if you had or could write the necessary software.

Short answer: No.


message:
Requesting help with CNC Project using Arduino

I have made a setup with Arduino Uno, Nema 17, T8 lead screw, IR Sensor and a DC motor.
I am trying to establish a code which:

1. Resets Home position of the Machining Head on the lead screw
2. Has an action button, which operates only when the position of the Head is on the lead screw, goes down the specified depth
3. Takes input from user to run the DC Motor (to rotate the tool on the machine head)
4. Takes second input to stop rotating and return to the reset position.

I am facing one major problem and two minor problems:

Major Problem:
To remove an error which was later resolved, I added the line: action_permit=0
Now due to some reason (I have pulled a lot of hairs trying to understand this), when I remove this action_permit line, the DC Motor rotation is stopped. I  have to include this line to rotate my DC Motor.

Minor Problem:
To get input from the user as to control when the DC motor starts and stops, I included the code which accepts 'y' for yes (start rotating the DC motor) and 'n' as no (stop rotation and return to home position)

Minor Problem:
I am not sure how to control the PWM, I have copied the code from a video, but do not know how to reach maximum and minimum rpm; also I understand the variation between PWM value and RPM is not linear. Any feedback on how to precisely control the rpm of the motor would be great
<!-- language-all: lang-cpp -->
```
int IR_signal=2;
int DC_ENB=11;
int DC_IN3=4;
int DC_IN4=5;
int STE_dir=6;
int STE_step=7;
int STE_ena=10;
int button_reset=8;
int button_action=9;
//define arduino pin
int action_permit;//0-action part is not allowed to run. 1-action part is allowed to run
int IRon;
int COUNT;//the amount of steps that the machine head should go
int HEIGHT;//total height that the machine head should go
int i;
int reset_on;
int action_on;
String Switch_DC;

//parameter
void setup() {
  // put your setup code here, to run once:
  pinMode(IR_signal,INPUT);
  pinMode(button_reset,INPUT);
  pinMode(button_action,INPUT);
  //input part
  pinMode(DC_ENB,OUTPUT);
  pinMode(DC_IN3,OUTPUT);
  pinMode(DC_IN4,OUTPUT);
  pinMode(STE_dir,OUTPUT);
  pinMode(STE_step,OUTPUT);
  pinMode(STE_ena,OUTPUT);
  //output part
  action_permit=0;// ban the action part at the beginning
  COUNT=0;
  HEIGHT=0;

  //original value of parameters
  //digitalWrite(DC_ENB,HIGH);
  analogWrite(DC_ENB,200);
  digitalWrite(STE_ena,LOW);
  digitalWrite(DC_IN3,HIGH);
  digitalWrite(DC_IN4,HIGH);
  //original pin output
  Serial.begin(9600);
  // start the monitor
}

void loop() {
  // put your main code here, to run repeatedly:
  reset_on=digitalRead(button_reset);
  action_on=digitalRead(button_action);
  //read the signal from the button
  if(reset_on==0)//reset button is pressed
  {
    delay(10);
    // preventing manual error
    if(reset_on==0)
    {
      RES();
    }
  }
  if(action_on==0)//action button is pressed
  {
    delay(10);
    // preventing manual error
    if(action_on==0)
    {
      ACT();
    }
  }
}
void RES()//reset part
{
  while(action_permit==0)//when 0, this "while" loop will keep running
  {
    IRon=digitalRead(IR_signal);// read the signal from IR sensor
    if(IRon==1)// machine head is not in original position
    {
      delay(1);
      //ensure the signal is not happened by a BUG
      IRon=digitalRead(IR_signal);
      if(IRon==1)
      {
        digitalWrite(STE_dir,LOW);
        digitalWrite(STE_step,HIGH);
        delay(1);
        digitalWrite(STE_step,LOW);
        delay(1);
        //if machine head is not in original position, it will go up for one step
      }
    }//if HIGH, go up
    else if(IRon==0)
    {
      action_permit=1;
      COUNT=0;

    }//once machine head reaches the original position, controller will get out this loop and allow action part to run
  }
}
void ACT()//action part
{
  if(action_permit==1)
  {

   for(i=0;i<3523;i+=1)
   {
     digitalWrite(STE_dir,HIGH);
     digitalWrite(STE_step,HIGH);
     delay(1);
     digitalWrite(STE_step,LOW);
     delay(1);
   }
   delay(100);
   for(i=0;i<100;i+=1)
   {
     digitalWrite(STE_step,HIGH);
     delay(10);
     digitalWrite(STE_step,LOW);
     delay(10);
   }
   action_permit=0;

   Serial.println("Please press y to start tool rotation");
   while((Serial.available()==0))
   {
    //waiting for input
   }
   Switch_DC=Serial.readString();
   if (Switch_DC == "y")
   action_permit=0;
   {
    analogWrite(DC_ENB,200);
    digitalWrite(DC_IN3,HIGH);
    digitalWrite(DC_IN4,LOW);
    delay(2000);
   }

   Serial.println("Please press n to stop tool rotation");
   while((Serial.available()==0))
   {
    //waiting for input
   }
   Switch_DC=Serial.readString();
   if(Switch_DC == "n")
   action_permit=0;
   {
    analogWrite(DC_ENB,200);
    digitalWrite(DC_IN3,LOW);
    digitalWrite(DC_IN4,LOW);
   }
   digitalWrite(STE_dir,LOW);
   for(i=0;i<4523;i+=1)
   {
     digitalWrite(STE_step,HIGH);
     delay(1);
     digitalWrite(STE_step,LOW);
     delay(1);
   }
   action_permit=0;
  }
}
```

body:
You have some obvious problems in your code, though I don't know, if the logic will be correct (doing what you want it to do) if you fix them. But either way it is a good start.

- You check for `action_on` and `reset_on` to be LOW, so I guess the button will pull the pin to LOW, if you press it. You didn't activate the internal pullup resistors, so I guess you already have them externally (if not: You definitely need them). So `action_on==0` actually is the case for action is permitted to run, not forbidden. You seem to think, that it is the other way round.
- Then you are doing this (and the same with `reset_on`):

        if(action_on==0)//action button is pressed
          {
          delay(10);
          // preventing manual error
          if(action_on==0)

    You check, if `action_on` is zero. If yes, you wait a bit and check the same again. The value of `action_on` cannot change during the delay, so this will always be true and thus is superfluous. If you meant to read the button again, to check if the button was really pressed (for debouncing), you have to actually read the button state again with `digitalRead()` and save it to `action_on`, like you have done before. This is not done automatically for you.
- `for(i=0;i<3523;i+=1)`  Using a global variable to count in a for loop is not a good idea. Instead you should always use a local variable to do this: `for(int i=0;i<3523;i+=1)`
- `Switch_DC=Serial.readString();`  Using `readString()` is not good coding, because this function just reads all data, that comes until the timeout hits (default 1s). This is not a reliable way to read data from Serial. Instead you should read each character individually from the Serial interface, put it into a buffer, and only stop and process the output, if a delimiting character was send. Often a newline character `\n` is used for this. So one message/command, that should be processed as a whole should be ended with a newline character. That will prevent, that the input from serial is processed incorrectly, only because the timing was different. If you only have commands, that consist of only 1 character, you can instead use a single `Serial.read()`, which reads exactly one character from the Serial interface (or returns -1 if there is no character to read).
- Then you wrote this:

        if (Switch_DC == "y")
        action_permit=0;
        {

   I guess, here you have inserted the `action_permit=0`. This cannot be, want you meant. As you wrote it, the `action_permit=0` line will only be executed, if `Switch_DC` is equal to "y", since this statement is inside the if statement. The `;` at the end of the statement also closes the if statement. So the code inside the following brackets will always be executed and the brackets are superflous. I don't know, where you intended to insert the `action_permit=0`, but since it is never used in the rest of the function, it is sufficient to just use it at the end of the function, like you already did. Remove all other of these lines from that function.

---

If you want to control the RPM of the motor, not just some relative PWM value, you first need to measure the RPM. PWM just controls the electrical energy going into the motor in a relative way (relative to fully powered on). To set a RPM value for the motor, you need to measure the current RPM (for example with a light barrier or a rotary encoder) and use that as input for a PID controller (Proportional Integral Differential). The output of the PID controller then must be fed into the `analogWrite()` function. The PID controller will raise or lower the PWM value, until the RPM setpoint is reached. There is a [PID library][1] for Arduino, that will help you with the calculation.

  [1]: https://github.com/br3ttb/Arduino-PID-Library/


message:
a code to implement a simple traffic signal and also display on LCD which color is ON?

I have tried code given below for simple traffic signal and also display on LCD which color is ON, but it didn't work. Please me to make it work.
<!-- language-all: lang-cpp -->

    int red = 10;
    int yellow = 9;
    int green = 8;
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    void setup(){
        pinMode(red, OUTPUT);
        pinMode(yellow, OUTPUT);
        pinMode(green, OUTPUT);
    }

    void loop(){
        changeLights();
        delay(1500);
    }

    void changeLights(){
        lcd.print("red");
        digitalWrite(yellow,LOW );
        digitalWrite(red, HIGH);
        digitalWrite(green,LOW );
        delay(3000);
        lcd.print("yellow");
        digitalWrite(yellow,HIGH );
        digitalWrite(red,LOW );
        digitalWrite(green,LOW );
        delay(3000);
        lcd.print("green");
        digitalWrite(yellow,LOW );
        digitalWrite(red,LOW );
        digitalWrite(green,HIGH );
        delay(3000);
        //if(
    }

body:
Write a sketch to test your LCD.

    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 4, 2);
    void setup(){
        lcd.begin();
        lcd.print("Hello World!");
    }
    void loop() {
        lcd.setCursor(0, 1);
        lcd.print(millis() / 1000);
    }

Make sure the R/W pin is connected to GND on your breadboard. You may need to connect the contrast pin to 5V. Ideally it should be connected to the wiper of a 10KOhm trimpot with either end connected to GND & 5V (so you can vary the contrast).

Once that set-up works change your code

     void setup(){
         lcd.begin();
         lcd.print("Traffic signals");
         delay(500);
         pinMode(red, OUTPUT);
         pinMode(yellow, OUTPUT);
         pinMode(green, OUTPUT);
     }

     void loop(){
         changeLights();
         lcd.setCursor(0,0);
     }


body:
A small update to your code

 1. Added `lcd.begin();` function
 2. added `lcd.clear();` function so that old characters will be removed before adding new display

Here is the complete code

    int red = 10;
    int yellow = 9;
    int green = 8;
    #include <LiquidCrystal.h>

    LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
    void setup() {
      lcd.begin(16, 2);
      pinMode(red, OUTPUT);
      pinMode(yellow, OUTPUT);
      pinMode(green, OUTPUT);
    }

    void loop() {
      changeLights();
      delay(1500);
    }

    void changeLights() {
      lcd.clear();
      lcd.print("red");
      digitalWrite(yellow, LOW );
      digitalWrite(red, HIGH);
      digitalWrite(green, LOW );
      delay(3000);
      lcd.clear();
      lcd.print("yellow");
      digitalWrite(yellow, HIGH );
      digitalWrite(red, LOW );
      digitalWrite(green, LOW );
      delay(3000);
      lcd.clear();
      lcd.print("green");
      digitalWrite(yellow, LOW );
      digitalWrite(red, LOW );
      digitalWrite(green, HIGH );
      delay(3000);
      //if(
    }
The output would look like this:

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

[Here][2] is the link to the Arduino simulator example

  [1]: https://i.stack.imgur.com/HP3Io.gif
  [2]: https://wokwi.com/arduino/projects/304640214914040386


message:
Expected unqualified-id before 'public'

I'm making an arduino program for a buzzer that you can record notes and song for and then play them back. I have 2 arrays that hold both pitch and if a note is being played. I continue to get errors that say `expected unqualified-id before 'public'`.

Does anybody know how to fix this?

```
void setup()
{
 Serial.begin(9600);
 pinMode(5, INPUT_PULLUP);
 pinMode(14, INPUT_PULLUP);
 pinMode(12, INPUT_PULLUP);
}

void freePlayMode()
{
    int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }
}

void recordMode()
{
 int readS2 = digitalRead(12);
 if (readS2 == LOW)
 {
  rec();
 }
 else
 {
  if (readS2 == HIGH)
  {
    playBack();
  }
 }
}

void rec()
{

static public int recordings[99999999] = {NULL};
static public int notes[99999999] = {NULL};
int state;
static unsigned long i = 0;
int readP = analogRead(0);
  int readB = digitalRead(5);
  readP = map(readP, 0, 1023, 300, 2000);
  Serial.println(readP);
  if (readB == LOW)
  {
  tone(4, readP);
  }
  else
  {
    noTone(4);
  }

  if (i < 99999999)
 {
  if (readB == HIGH)
  {
    state == 0;
  }
  else
  {
    state == 1;
  }
  recordings[i] = state;
  notes[i] = readP;
  i++;

 }
}

void playBack()
{

}

void loop()
{
int readS1 = digitalRead(14);
if (readS1 == LOW)
{
  freePlayMode();
}
else
{
  if (readS1 == HIGH)
  {
    recordMode();
  }
}

}
```

<!-- Remove this -->

body:
    static public int recordings[99999999] = {NULL}

This is not valid C code. Remove the word `public`.
Also you cannot create such a big array. The Arduino has only 2 KB (SRAM) memory and also since it is static you have to fill it with values directly, like:

    static int recordings[5] = { 0, 1, 2, 3, 4 };

How many values you want to store?

In case you need quite a lot (like hundreds), I would use a different solution for the `state` array as it only stores values 0 or 1. For example, you can use arrays of uint8_t which cost only 1 byte per element, but even better would be to store 8 0 or 1 (boolean) values in one byte each, but that means you have to get/set the values in the correct indices yourself.


message:
NodeMCU MQTT getting topic but not calling IF loop

I am very new to Arduino/ESP and I am writing a code to activate 2 relays using MQTT. My connection is successful and I am able to receive message/topic printed out on serial console. Here is my code:

```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <DNSServer.h>
#include <WiFiManager.h>
#include <PubSubClient.h>
#include <Wire.h>
#include "SSD1306Wire.h"
#define wifi_ssid "SSID"
#define wifi_password "PASSWORD"
#define mqtt_server "192.168.1.1"
#define mqtt_user "mqtt_username"
#define mqtt_password "mqtt_password"

SSD1306Wire  display(0x3c, D2, D1);
const int relay1 = 5;
const int relay2 = 4;
String header;
String output5State = "off";
String output4State = "off";
const int output5 = 5;
const int output4 = 4;
WiFiClient wificlient;
WiFiClient espClient;
PubSubClient client(espClient);
ESP8266WebServer server(80);

//------------------- MAIN WEB PAGE ------------------------
const char MAIN_page[] PROGMEM = R"=====(
<head><meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<title>HOME IOT</title>
<style>html { font-family: Helvetica; display: inline-block; margin: 0px auto; text-align: center;}
.button { background-color: #195B6A; border: none; color: white; padding: 16px 40px
text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer
body{margin-top: 50px;} h1 {color: #444444;margin: 50px auto 30px;
.button2 {background-color: #77878A;
p {font-size: 24px;color: #444444;margin-bottom: 10px;}
</style>
</head>
<body>
<div id="webpage">
<h1>Security Door</h1>
<p><a href="/show/SecurityDoor/Open"><button class="button">Open</button></a></p>
<p><a href="/show/SecurityDoor/Close"><button class="button">Close</button></a></p>
</div>
</body>
</html>
)=====";
//------------------- MAIN WEB PAGE ------------------------

void setup() {
  Serial.begin(9600);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
  //-----------------------------------------
  WiFiManager wifiManager;
  //wifiManager.resetSettings();
  wifiManager.autoConnect("IOT-LivinRoom");
  //-----------------------------------------
  server.on("/", handle_OnConnect);
  server.onNotFound(handle_NotFound);
  server.begin();
  Serial.println("Initializing OLED Display");
  display.init();

  display.flipScreenVertically();
  display.setFont(ArialMT_Plain_10);
  Serial.println("HTTP server started");
}

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(wifi_ssid);
  WiFi.begin(wifi_ssid, wifi_password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());

}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String messageTemp;
  for (int i = 0; i < length; i++) {
    Serial.print((char)payload[i]);
    messageTemp += (char)payload[i];
  }
  Serial.println();
  Serial.print(messageTemp);

 if(topic=="livingroom/securitydoor"){
     Serial.print("Changing esp01 relay1 to ");
     if(messageTemp == "on"){
       digitalWrite(relay1, LOW);
       Serial.print("On");
       Serial.print("On from opening");

     }
     else if(messageTemp == "off"){
       digitalWrite(relay1, HIGH);
       Serial.print("Off");
       Serial.print("On from Closing");
     }
 }
 Serial.println();

 if(topic=="livingroom/ac"){
     Serial.print("Changing esp01 relay2 to ");
     if(messageTemp == "on"){
       digitalWrite(relay2, LOW);
       Serial.print("On");
       Serial.print("On from opening");

     }
     else if(messageTemp == "off"){
       digitalWrite(relay2, HIGH);
       doorClosing();
       Serial.print("Off");
       Serial.print("On from Closing");
     }
 }
 Serial.println();
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP8266Client", mqtt_user, mqtt_password)) {
      Serial.println("connected");
      client.subscribe("livingroom/securitydoor");
      client.subscribe("livingroom/ac");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

//--------------------------- void loop-----------------------
void loop() {

  server.handleClient();
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

}

//----------------------------- Web Calls Function -----------
void handle_OnConnect() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s);
}

void handle_NotFound(){
  server.send(404, "text/plain", "Not found");
}

```

Issue is: message from below is not printing in serial

```
       Serial.print("On");
       Serial.print("On from opening");
```

In fact code is displaying topic and message in serial console.

My actual user case is to display status on OLED display as well as control relay.

body:
thanks for suggestions,

When i am doing it in below way, it got worked

```
if (strcmp(topic, "livingroom/securitydoor") == 0)
  {
    Serial.print(topic);
  }
```