message:
Arduino voltage connection pins

On the Arduino power connector jack, which is the positive terminal pin and the negative pin?

body: Arduino's power connector jack's tip is positive while the sleeve is negative but the more important thing to know is what will you be using in powering Arduino? Please provide more information about your setup and possibly a schematic. This will help us understand more what you're trying to accomplish.


sender: user

message:
Finding address of OLED using I2C communication and Arduino

It is known that address of OLED SSD1306 is 3C. The frame format is as follows:
[![enter image description here][1]][1]

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

The figure implies that the binary pattern should be 01111000 for the first frame (considering write mode and the second last bit is a dont care).
So I was trying to send the first frame using Wire.h library. The following is a code
``` Wire.beginTransmission(0b01111001); ```
But i receive a nack (return value of 2)

However, If I send 00111100, i receive a ack(return value of 0). What is wrong in my interpretation?

sender: assistant

body:
I2C has a 7-bit address space. The device's actual address is `0b0111100` (=0x3c). The sequences `0b01111001` and `0b01111000` address the same slave while the first one (least significant bit is `1`) starts a read transmission, the second one starts a write transmission.

Those least significant bits are nothing you need to care about when using `Wire.h`: the mode of operation is automatically set when using `Wire.startTransmission(addr)` (returns `0` when slave ACK'ed write command) and `Wire.requestFrom(addr)` (returns `0` when slave ACK'ed read command).


body:
You misinterpret how the `Wire` library is used. Though the first byte in the transmission is called the address byte, the actual address consists only of the 7 higher bits in that byte. The direction bit is not in the address.

So the `Wire.beginTransmission()` method wants the address as parameter, without the direction bit. That bit is set corresponding to the used function (0 for `Wire.beginTransmission()` and 1 for `Wire.requestFrom()`).

`0b0111100` is the real address (when connnecting the address pin to ground)(note, that there are only 7 bits, since the address only has 7 bits). The write operation address byte will then be `0b01111000`, though the library is hiding that way from you. You need to provide the 7 bit address to the function.

> the second last bit is a dont care

As mentioned above, that is not correct. This bit (the least significant bit of the address) is set by the address pin SA0. It seems, that you have it tied to ground, which sets the corresponding bit in the address to zero. If you would tie it to Vcc, it would be 1.


message:
Arduino program using i2c stops working after printing to OLED a few times

**A NOTE ON THE PROJECT AND PROGRAM STRUCTURE**

I am developing an open source Smart Watch project using Arduino.
The code can be found here: https://github.com/shivangsgangadia/SmartWatch
The code is too large and divided into multiple files, hence I cannot paste it here within the question, hence I request you to look into the github repo.

So far I have interfaced an OLED (128 X 64 SSD1306) and RTC (DS3231 in ZS-042).
I have written libraries for both, which have been included in Github repo.

The program structure allows to add multiple "Modules" which are basically like apps. There is a static State class that holds the program state such as modules to be serviced, and time from RTC.
Each "Module" can be a "App" or "Overlay". Overlays are always visibles, there can be mutiple overlays active, but only 1 app can exist at a time.

**WHAT I AM TRYING TO DO ?**

 1. Read RTC into State class's static variables
 2. Display once
 3. Attach interrupt to set boolean flag when the RTC gives interrupt (alarm
    set to 1 minute) Service interrupt in loop by:

 - Read RTC into State class's static variables
 - Reset alarm for RTC
 - Update display

**WHAT IS THE PROBLEM ?**

The program works fine 2-3 times, i.e. does what's expected after servicing 2-3 interrupts (hence 2-3 minutes), but after that the print on the OLED becomes mangled and the program stops altogether.

**WHAT HAVE I TRIED TO SOLVE IT ?**

With `Serial.println()` in many areas such as before and after `OLED::writeString` is called in respective classes, I concluded that the RTC is not the issue, but the OLED somehow causes the program to stop.

Removing `OLED::writeString` statements does allow the rest of the printing to continue for more than 2-3 times, but the program eventually does stop. I have tried replacing the wires and the breadboard, but nothing seems to have any effect.

body:
This is wrong in many ways:

    String input = Serial.readString();
    serialInputBuffer = new char[input.length()];
    input.toCharArray(serialInputBuffer, input.length());

**What's fatal is that you later don't free the memory allocated with `new`.** Don't use String and `new`. Both use heap memory and will fragment it with these small allocations until there is no space for the next allocation. I see you have dynamic allocation in other parts of the sketch and there it looks like you have a `delete`, but they still cause the fragmentation problem.

Use a global buffer like `char serialInputBuffer[64];` and use:

    int l = Serial.readBytes(serialInputBuffer, sizeof(serialInputBuffer));
    serialInputBuffer[l] = 0;

In the scale function, there is a dynamically allocated array. Replace it with a class variable, which acts as a buffer which can hold the maximum number of bytes you expect the use to scale their byte to.

Again, dynamic allocations will cause fragmentation even if the memory is released properly.


message:
Button debounce using millis() in this example

I have been trying to find a way to use millis() instead of delay(), in order to press 2 buttons to turn on and off a blue led.

EDITED:

    const int right_button = 8, left_button = 9, yellow_led = 7, blue_led = 6, green_led = 5, red_led = 4;
    int previous_left_button_status = LOW, previous_right_button_status = LOW, blue_status = LOW, green_status = LOW;
    unsigned long time_setup = millis();
    const int delay_task = 250;

    void setup()
    {
      pinMode(right_button, INPUT_PULLUP);
      pinMode(left_button, INPUT_PULLUP);
      pinMode(blue_led, OUTPUT);
      pinMode(green_led, OUTPUT);
      pinMode(red_led, OUTPUT);
      pinMode(yellow_led, OUTPUT);
      Display.clear();
    }

    void loop()
    {
      int right_button_status = digitalRead(right_button);
      int left_button_status = digitalRead(left_button);
      unsigned long time_passes = millis();
      if (time_passes - time_setup >= delay_task)
      {
        time_setup = time_passes;
        if (right_button_status == previous_right_button_status)
        {
          green_status = !green_status;
          digitalWrite(green_led, green_status);
        }
      }
    }

body:
You've declared the variable for the millis function inside your loop correct and you've declared the delay duration you want to use. Two things you've missed are you've declared 2 variables with the millis function and to use it to control the program flow based on some condition to execute some code, in your case, to press 2 buttons to turn on and off an LED.

The way to to this is to use an if-else statement inside the loop function with one variable declared with the millis function, delay_duration as your reference, and 1 variable declared with a zero value.

    unsigned long storeMillis = 0;
    const int delay_duration = 500;

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

    void loop() {
    unsigned long currentMillis = millis();
    if (currentMillis - storeMillis > 500) {
    storeMillis = currentMillis; //update and store the value of storeMillis for the next iteration
    //code you want to do
    }


message:
MPU6050 Accelerometer freezes/glitches after acceleration

I am trying to do rotational vector calculation using a MPU6050 chip which actually work really well with not too much drift **when I rotate the MPU slowly**. However, when I accelerate too much, e.g. change direction in my slow rotations or just slightly tap the breadboard with my finger, the values completely go nuts.

I am using an ESP8266 chip to control the chip and I have tried multiple libraries for reading the Gyro/Accelerometer values which all have more or less the same behaviour.

My accelerometer readings from the Serial plotter, before and after the light tap to the breadboard:

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

Gyroscope does the same thing. The MPU is new (just arrived in the mail few hours ago), I power it using 3.3V and use 3.3V GPIO logic from the ESP chip.

Does anyone know what could be causing this?

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

body:
Your problems are (most likely) related to loose connections in the breadboard. Sudden movements can cause power to be interrupted briefly, or data signals to become corrupted.

Breadboards aren't great for prototyping anything that moves, even slightly.


message:
Serial Moniror, '\r' and Realterm

I'm wanting the results from each of the 6 ultrasound modules to print on their respected line after new results have been generated instead of spitting out a continuous flow (see attached image). I've downloaded Realterm and got the results to show on there as I've read that the serial monitor can't do that but I don't know where to put the '\r' syntax within my script as I have multiple serial.prints to display the data I need.

Here is a section for 1 of the ultrasound modules, they are just repeated for the differing modules.

Thanks in advance for any help!

[![serial monitor][1]][1]

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

``` void loop() {

  //Object Ahead Distance.
  long duration1, distance1;
  digitalWrite(trigPin1, HIGH);
  digitalWrite(trigPin1, LOW);
  duration1 = pulseIn(echoPin1, HIGH);
  distance1 = (duration1/2) / 29.1;

   delay(500);
   if (distance1 >= 40){
    Serial.print("Nothing Ahead, Okay");
    Serial.print(distance1);
    Serial.println("cm");}
   else if (distance1 <= 39 || distance1 >= 29){
    Serial.print("Vehicle Ahead, Slow ");
    Serial.print(distance1);
    Serial.println("cm");}```

body:
`\r` returns the cursor to the start of the current line. You can't use it to go back up to previous lines.

Instead you need to learn ANSI escape sequences to move the cursor around.

For example `Serial.print("\e[2J");` will clear the entire screen. `Serial.print("\e[1;1H");` will move the cursor to the top left corner of the screen (the coordinates are `\e[{Y};{X}H` by the way).

You can also add colour and all sorts of other nice things, none of which the Arduino IDE's "Serial Monitor" can do.

You can find a good reference of ANSI escape codes [here](https://gist.github.com/fnky/458719343aabd01cfb17a3a4f7296797).


message:
Wireless Bluetooth USB HUB using Arduino nano

I have the following problem/idea:

I have a electronics workbench and a separate PC desk. Now I have a USB HUB on the workbench, but it doesn't properly work, because the USB-cable to the pc is too long. My setup doesnt really allow me to put the PC somewhere else and the USB-hub is already mounted in the closest usable location.

A few days ago I remembered that I have a arduino nano with a hc-05 bluetooth module attached to its hardware serial port. And as both bluetooth and USB are serial connections I was wondering if I couldn't use the arduino sort of as a middle man and connect the arduino via bluetooth to the pc. Then have a software on the pc that registers the arduino as a USB hub with one port and run some code on the arduino that basically makes the arduino act as a USB host (I know that this is possible with the arduino nano) and have it just move data between the USB connection and the bluetooth module.

Im quite sure that all this should be possible. The atmega should even be capable of doing so at or close to maximum USB 2.0 data rates as that is only 12 Mbit/s and it can run at 16 MHz when powered with 5V. Im not quite sure about the maximum data rate for the bluetooth module though, but I can work with a little lower speeds...

The software for the pc could also be relatively straight forward. Something like a virtual USB-port and the software just shifting data from the com-port that is the bluetooth to this virtual USB-port.

So thats the idea. I have some experience in both programming microcontrollers and software for pc.

So what I need is a bit of help with this, as I am not quite sure how to accomplish this.

The parts that I will need the most help with are going to be the programming of the USB host on the arduino and the virtual USB-port on the pc.

The rest should be relatively easy as its basically just shifting data from one register into another.

body:
You can't. As simple as that. The mere act of thinking about it belies a desperate lack of understanding about how USB works.

Yes, it's "serial" in that it sends one bit after another, as opposed to multiple bits all together ("parallel"), but it is completely unrelated in any way to the "serial" that the bluetooth module or the Arduino speak ("UART").


body:
I agree with Majenko. The best way for you is to buy an active USB extension cable, so that you can handle the distance easily (the signal gets refreshed in the cable by active electronics, so that you can use USB over longer distances).

You consider this to be easy, because you haven't dug into the depth of these topics yet. Here are some important information on that:

- Bluetooth and USB are fundamentally different. The term "serial" outside of the Arduino world is just a term for one bit after another. It doesn't describe any protocol or working principle. Interfaces as SPI and I2C are also serial interfaces, but that doesn't mean, that they work similarly, not even in their topology and also not in their protocol behavior. A bridge between these different interfaces is better described as a translator. And translation is always difficult.

- Serial in the Arduino world means the UART interface. No similarity to USB or bluetooth.

- The Bluetooth spec is rather big. There are many types of connection interfaces, that can be build with it. Examples are the UART (Arduino Serial), HID (like a mouse or keyboard on a PC) or audio (like headphones) interfaces. Each connection has it's specific function. The USB spec is even bigger, way bigger to be precise. You would need to understand how bluetooth and USB work at their core for implementing something like that.

- The HC-05 is a chip for getting an UART interface over bluetooth. To change that, you would need to reprogram it with a new firmware. I doubt, that any firmware, that you can find in the web, would be sufficient for your case. Not generic enough. Also the chips hardware is limited, so you can only get limited resources out of it. Most likely you have the HC-05 on an adaptor board, which has a voltage regulator on it (since the HC-05 is a 3.3V device). You would need to ditch that board and solder the chip itself.

- The Nano is a bad choice for everything involving USB. The Atmega328p on it, that you program when programming the Arduino, does not have an USB interface. For that the Nano has a second chip, the Atmega32u4, which acts as USB to UART adaptor. You would need to hack it to do anything different than that. Doing it is possible, but you would need to ask yourself, why you are trying to do something so complex with such an incapable board. Also the Nano cannot be an USB host, nor a hub. There is an USB Host shield for the Uno, but that also is limited.

- Getting anything even remotely near to 12Mbit/s is illusionary. You won't be able to process nearly one bit every clock edge. You already need several clock edges to do very primitive processing (going into an ISR and then moving the data into a different register, as you put it). And the translation between the protocols will not be that easy. You will need much processing power and also quite some RAM and flash (you will certainly need to buffer some data and the program itself will also be very big to implement something like USB). "A little lower speeds" don't cut it there. Even if possible, that would be painstakingly slow in comparison to a real USB hub.

- Most of the software, that you would need for such a project, is non-existent. Doing something that complex with such crappy hardware is an edge case. So you would need to write your own USB stack software. As mentioned, the USB interface is very complex and if you need to ask this question, you are currently not capable of doing this (and neither am I).

I don't say it is absolutely impossible to implement a bit USB functionality with the Nano. But you won't get a satisfying result, that you really can use, even if you were an absolute expert on microcontrollers and the USB and bluetooth stacks (which you really would need to be for it). That is at maximum a project, that an expert would do just for the grind, not for real results.

You have a real life problem, that you want to solve. Choose the easiest way and buy an active USB extension cable.


message:
esp8266 OTA issue

I have uploaded the BasicOTA sketch in Esp8266-12e.
I am written one program, when i try to upload it first time in Esp using the OTA port it gets uploaded successfully, but when i try to upload any sketch after that it does not work.
The console responds with `No Answer`.

After searching on internet many people have asked to check the sketch size. To check if size matters or not i tried with blinking sketch, and same issue happens there too.

The sketch only gets uploaded in first time.

Can anyone guide me resolving this issue.

body:
Things to check:

1. Partition arrangement selected. You have to make sure to keep the same partition arrangement between uploads.
2. Partition arrangement selected. You have to make sure that the partition arrangement you have chose supports OTA uploads.
3. You have to reset the ESP8266 manually after your USB upload. You can only do an OTA update to a sketch that has booted in "run" mode, not "boot" mode.
4. You have the right IP address / hostname selected? (I don't know how that is handled in the Arduino IDE...)
5. You must upload an OTA-enabled sketch for OTA to continue working.


message:
Toggling a blinking led ON & OFF

I am trying to implement a toggle switch to turn blinking ON & OFF. However, the code only turns the led ON or OFF and that too unreliably. Can you help me understand why it isn't working?

       const int redLed = 10;
    const int buttonPin = 2;
    unsigned long newTime;
    unsigned long oldTime = 0;
    byte newButtonState;
    byte oldButtonState = 0;
    boolean ledState = false;
    boolean blinkState = false;
    boolean state = LOW;

    void setup() {
      pinMode(redLed, OUTPUT);
      Serial.begin(9600);
      pinMode(buttonPin, INPUT);
    }

    void loop() {

      newButtonState = digitalRead(buttonPin);
      delay(100);

      // check if button state has changed
      if (newButtonState != oldButtonState) {
        // if button was pushed
        if (newButtonState == HIGH) {
          // check led state
          if (ledState == false) {
            ledState = true;
            blinkState = true;
          } else {
            ledState = false;
            blinkState = false;
          }
          if (ledState == true && blinkState == true) {
            newTime = millis();
            if (newTime - oldTime >= 250) {
              state = !state;
              oldTime = newTime;
            }
            digitalWrite(redLed, state);
          }
        }
      }
      oldButtonState = newButtonState;
    }

body:
You never set the `pinMode` of `buttonPin`.

Normally it defaults to `INPUT` if you don't manually specify anything, and I assume from your results that you don't have an external pullup or pulldown resistor.  Therefore you need to specify `pinMode(buttonPin, INPUT_PULLUP);` and make sure that your switch or button connects the input pin to ground when activated (which means that "active" will be LOW).

Or, if you do have an external pullup or pulldown resistor then it sounds like it may not be wired corrcetly.


body:
Note, this is not an answer, but I want to show some code examples based on the comment:

You can use as said in the comment:

- Remove '== true' in a boolean condition
- Replace '== false' by '!' in a boolean condition

You will get this:

      // check if button state has changed
      if (newButtonState != oldButtonState) {
        // if button was pushed
        if (newButtonState == HIGH) {
          // check led state
          if (!ledState) {
            ledState = true;
            blinkState = true;
          } else {
            ledState = false;
            blinkState = false;
          }
          if (ledState && blinkState) {
            newTime = millis();
            if (newTime - oldTime >= 250) {
              state = !state;
              oldTime = newTime;
            }
            digitalWrite(redLed, state);
          }
        }
      }
      oldButtonState = newButtonState;
    }

About the following fragment:

      if (!ledState) {
        ledState = true;
        blinkState = true;
      } else {
        ledState = false;
        blinkState = false;
      }

Since you write `ledState` and `blinkState` in both clauses, and the condition is simple (so you don't need to put it in a temporary variable, you can replace this fragment by:

    blinkState = !ledState;
    ledState = !ledState;

Note you have to reverse the order as `blinkState` depends on `ledState`.


body:
Your blink code is only active

    if (newButtonState != oldButtonState)

so it won't blink (by itself)

To toggle blinking, just change it e.g. like this

    void loop() {
      bool newButtonState = digitalRead(buttonPin);
      if (newButtonState != oldButtonState) {
        // button state has changed
        delay(5);  // debounce
        oldButtonState = newButtonState; // run only once per button push
        if (newButtonState == HIGH) {
          // toggle blink state
          blinkState = ! blinkState;
        }
      }

      if (blinkState) {
         // BlinkWithoutDelay
         unsigned long newTime = millis();
         if (newTime - oldTime >= 250) {
            state = !state;
            oldTime = newTime;
            digitalWrite(redLed, state);
         }
      } else {
         // no Blinking : just leave redLed as is
      }
    }

Now please clean up the global variables: some are not required globally, some are not required at all.


body:
I don't see why you would set `blinkState` together with `ledState`. I assume, that you want the button to toggle the blinking. 1 press --> LED is blinking, another press --> LED stops blinking, ...

I suggest to restructure your code. First separate input and output, meaning button check code and LED blink code. For blinking you already have a state variable named `blinkState`. So in your `loop()` function you first write

    newTime = millis();
    if(blinkState && newTime - oldTime >= 250){
        ledState = !ledState;
        oldTime = newTime;
    }

That will toggle `ledState`, whenever `blinkState` is set, in intervals. Now we simply `digitalWrite()` that value out directly after that:

    digitalWrite(redLed, ledState);

Now we need to handle the button. Your button if statements seem to be good, so we only need to change, whats inside the statements. There we simply negate the `blinkState` variable:

    if (newButtonState != oldButtonState) {
        // if button was pushed
        if (newButtonState == HIGH) {
            blinkState = !blinkState;
        }
    }
    oldButtonState = newButtonState;
    delay(100);

With this code the LED will stop changing and keep the state, that it had, when you pressed the button. If you want the LED to turn off at that point, you shoud add `ledState = false;` after negating `blinkState`.

Note, that this code doesn't need your `state` variable. 2 variables are enough for this. 1 for the current led state, 1 for the blinking state.

Also note, that using `delay()` is not the best way to debounce a button. It is an easy way, but it might not behave exactly, like you want to. If you want better debouncing, you can use the [Bounce2 library][1] from github. If you don't want to use a library for it, you can still learn about their ways to debounce in the Readme file.

  [1]: https://github.com/thomasfredericks/Bounce2


message:
Mouse.move values

I understand that `Mouse.move` move the mouse from its current position, example:

`Mouse.move(100, 100);`

Will move the mouse to 100 pixels right and 100 pixels down.

But in reality it will move to somehting like 150 pixels right and/or 150 pixels down..

I already tested without cursor precision/acceleration and it doesn't change a thing.

What unit does the function use ?

I know about the 127 -127 limit, and i respect it, but still... when i ask to move 100,100 it doesn't move 100,100.

body:
The mouse coordinates are not pixels. They are a proportion of the physical minimum/maximum parameters of the report descriptor. Since those aren't specified in the report descriptor they are taken to be the same as the logical: -127 to 127.

So moving 100 "units" is moving 100/(127-(-127)) of 100%, which is about 40%.

But 40% of what?

Well, 40% of an inch. Or what your OS believes that an inch is on your current screen.

In the HID specification:

> While Logical Minimum and Logical Maximum (extents) bound the values
returned by a device, Physical Minimum and Physical Maximum give
meaning to those bounds by allowing the report value to be offset and scaled.
For example, a thermometer might have logical extents of 0 and 999 but
physical extents of 32 and 212 degrees.The resolution can be determined
with the following algorithm:
> ```
> if ((Physical Maximum == UNDEFINED) || (Physical Minimum == UNDEFINED) || ((Physical Maximum == 0) && (Physical Minimum == 0))) {
>     Physical Maximum = Logical Maximum;
>     Physical Minimum = Logical Minimum;
> }
>
> If (Unit Exponent == UNDEFINED)
>     Unit Exponent = 0;
>
> Resolution = (Logical Maximum – Logical Minimum) / ((Physical Maximum – Physical Minimum) * (10^Unit Exponent))
```


message:
Can I run 3 devices on Arduino Uno with different power sources?

I'm pretty new to these types of projects I'd like to work on a greenhouse project with an Arduino Uno. The goal is to be able to sense temperature and control a heating lamp, detect humidity and control a humidifier, and connect a soil hydration sensor and connect a small water pump for irrigation.
Could the Uno support all of this power that could theoretically run at the same time? How would controlling the 3 isolated functions look in the Sketch?

body:
Your question is 2 fold:

- **Power requirements:** The actual power requirement depends on the devices, but the Arduino will certainly not be able to provide power for a heating lamp. It just cannot provide that much current (you would fry the Arduino). But the Arduino is also only powered from outside. I guess you have a power source, that can provide enough power for all the devices. Then you can connect these devices in parallel to the power source (meaning + and - of the heating lamp power goes directly to the power supply). That way the current for the devices doesn't flow through the Arduino. The Arduino will only use control signals, which don't have high current. Sensors are normally either analog sensors (which connect to the analog pins with only neglectable currents) or use communication interfaces, which are also ok. The current hungry output devices (humidifier and heat lamp) either have a digital control pin, a communication interface, or they must be controlled via a relay (depends on the actual devices).

- **Controlling all the devices:** The Arduino can only do 1 thing at a time. But that is no problem, since you can do things sequentially very fast. For example write one function for every device, that you want to control. In that function you communicate with/control the device according to some variables (like the measured temperature). The `loop()` function can then look as simple as:

        void loop(){
            measure_temperature();
            measure_humidity();
            measure_soil_hydration();
            control_humidifier();
            control_headlamp();
        }

    If you want to only do this periodically (not all the time), you can either add a `delay()` or - better - use `millis()` like in the `BlinkWithoutDelay` example (there are also many tutorials about `millis()` on the web). Make sure, that the individual functions are not blocking. They should do, what they need to do, and exit quickly. No long staying in loops or waiting for an event there.


body:
Yes, you can run all of those from an UNO, but you'd probably be better off using an ESP32 so that you can add a web portal to your project for relatively the same cost.

You would be able to run the HDT or similar sensor and temperature sensor as well as the hydration sensor directly from an MCU. The other components would require something else, like NPN MOSFET low side power switch (like an FDS3890) that could be controlled by the MCU. You will need to look at the datasheets for each component you buy, find the power ratings, and make sure you have components rated to support the voltage and current of your devices (A good rule of thumb is twice the expected use, so if you have a 12V pump that can sink 3A of current, you should get a MOSFET that can handle 24+ volts and 6+ Amps.

Each sensor will likely have a library you will use and has samples. Googling each one and working on one individual function at a time is a great way to learn and progress your project.

Some MCU only have one core and everything is placed into a loop. Others (like that ESP32) have multiple cores, and can use a RTOS for task scheduling.


message:
Can a video game potentially detect arduino leonardo?

If I automated an action in a video game through arduino leonardo, can it be detected? Things like autohotkey can be easily detected, however i would expect an arduino would be far more difficult. How easy/difficult would it be detect?

body: Nigh on impossible. True the game could look to see if there is a specific VID/PID combination visible to the computer, but that is probably not going to happen (and anyway you can change it).  As far as the game is concerned, input from a keyboard is input from a keyboard, whether that keyboard has buttons or a piece of code it really can't tell.


body:
Yes.

First you'll need to define how you plan to inject the new input signal, into the data "packets" as a spoof of controller signals, or just jumping the switches?

In the context of any modern gaming console, it could be detected. Easily. Consoles and controllers use any number of proprietary protocols which sync.commands to improve response and reduce controller lag. If you're just jumping the switches, then no, you could simulate hadouken and probably get away with it just fine.

If you're referencing PC gaming, then that would be hard if not impossible with the variance of input control available.  The best deterrent would be the security of the game software itself and the genre of the gaming. Some games actively encourage Hotkeys.


message:
Clearing string buffer with memset after a serial read

In using the SerialTransfer.h / pySerialTransfer libraries to send commands between my laptop and an Arduino Mega, I am sending multiple sequential strings between the devices. However, I'm having trouble "clearing" the receiving buffer on the Arduino side - it never shrinks, despite a few different attempts to clear the string (memset; a for loop).

I'm sending a string to the Arduino of the format <rand_len_str=**>, where there are anywhere from 1 to 5 asterisks.  Then the Arduino is simply sending the exact same string back, without any processing (as of yet).  And in the python terminal, I'm printing it all out; this is what I get:
```
SENT (17 bytes): <rand_len_str=**>
RECD (17 bytes): <rand_len_str=**>

SENT (18 bytes): <rand_len_str=***>
RECD (18 bytes): <rand_len_str=***>

SENT (19 bytes): <rand_len_str=****>
RECD (19 bytes): <rand_len_str=****>

SENT (17 bytes): <rand_len_str=**>
RECD (19 bytes): <rand_len_str=**>*>

SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>

SENT (18 bytes): <rand_len_str=***>
RECD (19 bytes): <rand_len_str=***>>
```
As long as the string is growing, all is well - but see the error in the 4th pair, with the extra *> characters, etc.

The following is my Arduino code; I've tried to reset the receiving string using memset, but this seems not to be working.
```
#include "SerialTransfer.h"

SerialTransfer myTransfer;

const int CMD_LEN = 200;
char buff[CMD_LEN];
char received_str[CMD_LEN];

void setup()
{
  Serial.begin(115200);
  myTransfer.begin(Serial);
}

void loop()
{
  if(myTransfer.available())
  {
    //////////////////////////////////////////////
    // handle call from Python

    memset(received_str, '\0', CMD_LEN*sizeof(char));
    myTransfer.rxObj(received_str, CMD_LEN);

    sprintf(buff, "%s", received_str);
    //////////////////////////////////////////////

    //////////////////////////////////////////////
    // send response
    myTransfer.txObj(buff, strlen(buff));
    myTransfer.sendData(strlen(buff));
    //////////////////////////////////////////////
  }
  else if(myTransfer.status < 0)
  {
    Serial.print("ERROR: ");

    if(myTransfer.status == -1)
      Serial.println(F("CRC_ERROR"));
    else if(myTransfer.status == -2)
      Serial.println(F("PAYLOAD_ERROR"));
    else if(myTransfer.status == -3)
      Serial.println(F("STOP_BYTE_ERROR"));
  }
}
```
I didn't see anything in SerialTransfer.h about clearing the rxObj; I can always just use the first terminating > character to parse the command - but I imagine there is a cleaner / better solution in clearing the buffer, or at least, I'd like to understand what's going on! Thanks in advance.

body:
Instead of clearing your buffers, make use of the bytesRead property.  Have a look at how they print the received string in the example code from the library using a for loop.  I don't know that it is null terminated or anything.

Example from the library's github page:

    #include "SerialTransfer.h"

    SerialTransfer myTransfer;

    void setup()
    {
      Serial.begin(115200);
      Serial1.begin(115200);
      myTransfer.begin(Serial1);
    }

    void loop()
    {
      if(myTransfer.available())
      {
        Serial.println("New Data");
        for(byte i = 0; i < myTransfer.bytesRead; i++)
          Serial.write(myTransfer.rxBuff[i]);
        Serial.println();
      }
      else if(myTransfer.status < 0)
      {
        Serial.print("ERROR: ");

        if(myTransfer.status == -1)
          Serial.println(F("CRC_ERROR"));
        else if(myTransfer.status == -2)
          Serial.println(F("PAYLOAD_ERROR"));
        else if(myTransfer.status == -3)
          Serial.println(F("STOP_BYTE_ERROR"));
      }


body:
Thanks for the pointer - that did the trick.  Applying it to my original code, if I update the few lines around `handle call from Python` to the following, it works as intended.
```
    //////////////////////////////////////////////
    // handle call from Python

    myTransfer.rxObj(received_str, CMD_LEN);
    strncpy(buff, received_str, myTransfer.bytesRead);
    buff[myTransfer.bytesRead] = '\0';

    //////////////////////////////////////////////
```
Thanks again!


message:
Controllino Mega and Fatek HMI

I have a setup that controls the rotation of two stepper motor using Arduino UNO, HBS860H stepper drivers, 4X4 keypad and LCD screen. I have replaced the Arduino Uno by a Controllino Mega and it works good. Now I am trying to replace the Keypad and LCD screen by a FATEK HMI PN2043NK.
I have the sketch for the Controllino,
I can use RS485 to communicate both devices.
I use FV Designer to program the HMI, but I don't understand how to run the sketch from the HMI.
I need some help with a simple example Please, any help I could use to start learning to communicate the HMI with the Controllino and run the steppers will be welcome.

body:
The usual "sketch" is "always" running on your arduino (Controllino) unless it is put into a non-run mode (like when loading a program) or doesn't have power.  What you need in your sketch is to do something IF a command is received on the serial (RS485).  Rather than simply running the command you want, the sketch needs to check the serial and only execute the command if the HMI sent the correct signal.

For motor control, you could use G-code where your HMI sends G-code move commands over RS485 and your Controllino executes them.  A handy RS232 example is grbl.


message:
Can a MEMS accelerometer sensor be used as a shock sensor?

I am trying to make an IOT project- SMART DOOR where I have used a serve motor and NodeMcu and for adding further functionality I have been thinking of adding a theft detection feature where whenever a large force is applied on the lock an alarm starts beeping and for that I don't have a shock sensor but I do have MEMS accelerometer sensor(MPU6050 Accelerometer and Gyroscope).
So can I use it to add this functionality?
If yes, can I get a little guide on what configuration and sensitivity I should use?

THANK YOU!

body:
Sure you can. A "shock" is merely a large amount of acceleration over a short period of time.

You would probably want to set the MPU6050 to its least sensitive setting (±16g), and you might even be able to make use of the "tap" function whereby the MPU6050 itself looks for a sudden short sharp shock to trigger an interrupt (though that may be a little too sensitive for your needs, I don't know).


message:
Can I emulate Arduino in a headless CI/CD setup?

6 years ago, there has been a question "[How to emulate Arduino on PC][1]".

Since then, probably many more Arduino emulators have been introduces.

With this question, I would like to narrow the search scope down to the following criteria:

- Linux compatible
- headless operation mode without UI/IDE possible to run in a [CI/CD][2] (continuous integration/delivery) system in collaborative environment where many code versions need to be merged and tested.

Do such setups exist already?

  [1]: https://arduino.stackexchange.com/questions/61/can-i-program-for-arduino-without-having-a-real-board
  [2]: https://en.wikipedia.org/wiki/Continuous_integration

body:
The problems with this kind of software is:

  - always behind the recent releases of cores/ hw variations.
  - reliable only for simple programs/tasks
  - Imho all the products I tested (mainly on Win) are actually a (somewhat crippled ) teaching and visualization help.
  - if you look into the emulators you mostly see only support for different chips and not the whole micro computer, which is far more complex to create

Due to the low cost of the hardware it is easier to run real HW setups with HW diagnostics (and get also feedback for thermal/electric issues) <br>So this kind of SW is for the low cost avr/esp HW and its hundreds of variants (even between production batches from one manufacturer) hard to develop and mantain. So you'll only find nice "play around" emulators which won't fulfill any professional requirement (even if some claim it)


message:
Uno - error during uploading with library

I'm writing the code in *VS Code* on *IO Platform*. Yesterday i finished my code and uploaded it to the Arduino Uno. It works fine. Next day i launched the VS Code and i changed the code a bit, then i uploaded it and i got the error.

Error:

    Tone.cpp.o (symbol from plugin): In function `timer0_pin_port':
    (.text+0x0): multiple definition of `__vector_7'
    NewPing.cpp.o (symbol from plugin):(.text+0x0): first defined here
    collect2.exe: error: ld returned 1 exit status
    *** [.pio\build\uno\firmware.elf] Error 1

I am using the libary `NewPing.h`. The code should does this: If is distance more than 20cm, the the buzz makes the sound and turns on the red led. If distance is less than 20cm, the blue led turns on

The code:

    #include <Arduino.h>  //It has to be there, because the arduino ide in VS Code will not work.

    #include <NewPing.h>

    #define echo_pin 3
    #define trig_pin 4
    #define max_range 450

    #define red_led_pin 7
    #define blue_led_pin 9
    #define buzz_pin 10

    int distance = 0;

    NewPing sonar(trig_pin, echo_pin, max_range);

    void setup(){
      Serial.begin(9600);
      pinMode(red_led_pin, OUTPUT);
      pinMode(blue_led_pin, OUTPUT);

      pinMode(buzz_pin, OUTPUT);
    }

    void loop() {

      distance = sonar.ping_cm();
      delay(50);

      if (distance > 0) {
              distance = 0;

        for (int i=0; i<5; i++) {
          distance += sonar.ping_cm();
          delay(50);
        }
        distance /= 4;

        Serial.print("Distance: ");
        Serial.print(distance);
        Serial.println("cm");

        if (distance > 20) {

          digitalWrite(blue_led_pin, LOW);
          digitalWrite(red_led_pin, HIGH);
          tone(buzz_pin, 1500);
          tone(buzz_pin, 800);
        }

        else {

          digitalWrite(red_led_pin, LOW);
          digitalWrite(blue_led_pin, HIGH);
        }
      }
    }

I don't undersand, what has changed. I tried to import again the libary <https://www.arduino.cc/en/guide/libraries> by importing the *.zip file, also installing in IDE.

body:
You have a conflict of interrupts. Both the internal `tone()` command and the `NewPing.h` use Timer 2 by default, which makes them mutually exclusive.

However you can change `NewPing` to not use a timer by editing the `src/NewPing.h` file and setting `TIMER_ENABLED` to be `false`:

        #define TIMER_ENABLED true      // Set to "false" to disable the timer ISR (if getting "__vector_7" compile errors set this to false). Default=true


message:
Can I integrate Arduino in a CI/CD setup?

While it seems [less valuable][1] to emulate Arduino in a CI/CD setup, are there any experiences/best practices for collaborative teams to automate their acceptance tests where a real Arduino is integrated into a CI/CD toolchain (or, what are comparable practices)?

Minimal example of acceptance testing:

* compilation is successful for a given compiler version.

  [1]: https://arduino.stackexchange.com/questions/74772/can-i-emulate-arduino-in-a-headless-ci-cd-setup?noredirect=1#comment162856_74772

body:
There are different approaches around. I can only point you to some of them:

  - [GitLab CI approach A](https://codeblog.dotsandbrackets.com/gitlab-ci-esp32-arduino/)
  - [GitLab CI approach B](https://dzone.com/articles/hands-on-iot-devops-day-3-gitlab-cicd)
  - Your specific solution: To build [pipelines for Arduino](https://devblogs.microsoft.com/premier-developer/azure-devops-build-pipelines-for-arduino-microcontrollers/) (although its Azure) but you can use this technique on [Linux with Jenkins](https://opensource.com/article/19/9/intro-building-cicd-pipelines-jenkins)

As a valuable commenter mentioned on your previous question - this does not cover the attached hardware testing (sensors/ motors) - this has to be "integrated" via a test lab station, which you have to control manually (or semi-automated via lab equipment) on defined release/version changes


message:
Can stack size be determined by free heap?

i have NodeMCU with es8266 onboard on it. I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen. So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

one tiny question here: can `Serial.println("asd asd")` cause memory fragmentation?

body:
> I read heap and stack memory are facing each other and if heap or stack gets full and reachs another strange things happen.

Indeed they do. And such things can be a pain to track down.

> So i am wondering if can we use ESP.getFreeHeap() to get free heap and conclude usage of stack.

No, you can't.  The "free" amount of heap does not equate to the top address of heap. Heap can (and generally does) have holes in it. The "free" space is the sum of all those holes plus any extra "heap reserved" space above the highest heap entry.

To get the current stack usage you need to know two things:

1. The staring address of the stack, and
2. The current extent of the stack

Item 1 will be a fixed value, though what that value is I have no clue, but some reading will surely give you that value.

Item 2 can be obtained by allocating a local variable in a function and getting the address of that variable.

If all you care about is the change in stack imposed by your code you can record the "starting" stack point and use that in point 1.  For example:

```
char *stack_start;

void setup() {
    char stack;
    stack_start = &stack;
}
```

Then you can use that to get the current stack size compared to the start of your program:

```
uint32_t stack_size() {
    char stack;
    return (uint32_t)stack_start - (uint32_t)&stack;
}
```

> one tiny question here: can Serial.println("asd asd") cause memory fragmentation?

No.  Use of `String` and other dynamic allocation is what causes memory fragmentation.


message:
How to install a dependency library to an Arduino compilation environment?

Following *[approach A][1]* from this Arduino SE answer, I managed to kick off an Arduino CLI compilation in a Docker environment.

However, the project I am trying to compile has a [dependency][2] on a LCD control library.

Error output:

    ...../OpenSourceVentilator/OpenSourceVentilator.ino:494:116:
    fatal error: LiquidCrystal_PCF8574.h:
    No such file or directory
    compilation terminated.

What is the proper way to link dependencies to the compilation environment of an Arduino project?

While the source suggests a direct compiler call, maybe I need a Makefile instead of the following?

    arduino-cli compile --fqbn esp32:esp32:esp32 -o ignored.bin OpenSourceVentilator.ino

  [1]: https://arduino.stackexchange.com/questions/74781/can-i-integrate-arduino-in-a-ci-cd-setup
  [2]: https://github.com/mathertel/LiquidCrystal_PCF8574/tree/master/src

body: If the library is installed the Arduino IDE (or CLI I assume too) just finds it and compiles/links it for you.


message:
How to control one Mosfet with another mosfet

I've got 4x 12V 6a peltiers and some [3d printer mosfet controllers][1] to drive them using PWM with my arduino. But I've found the mosfets need ~7V to switch on, so I'm now wanting to control them with some logic level ones I had around. I could just use the logic ones directly to the peltiers, but am finding it difficult to make my stripboard capable of handling 24A ([this page][2] seems to say I need tracks/wire of 2.3+mm diameter which I don't have). Hence I'm trying to make a circuit for the arduino to use the logic mosfets to control the 3d printer mosfets but can't quite get my head around how to do it. I think I'm missing a power source for the first mosfet - do I need to have a whole separate DC power supply for this to the peltiers? Very grateful for a bit of help please!

[![mosfet 3d printer controllers][3]][3]
[![Proposed circuit - sorry the M represents my peltier!][4]][4]

  [1]: https://www.amazon.co.uk/Aibecy-Expansion-Current-Ramps1-4-Printers/dp/B07BS6TQCG
  [2]: https://www.powerstream.com/Wire_Size.htm
  [3]: https://i.stack.imgur.com/cIEPv.png
  [4]: https://i.stack.imgur.com/uYlGw.jpg

body:
There's one thing you missed with your arrangement, and that is getting the 12V to turn the MOSFET on.  In your current arrangement it's possible to turn it off, but never on.  Adding a pullup resistor can help:

<!-- 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/8tNKg.png)

<!-- End schematic -->

R1 pulls the gate of M1 up above the switching threshold to turn it on. M2, when on, pulls the gate down below the switching threshold, turning it off.

However: you may have noticed that the switching is now backwards: send a HIGH from the Arduino to turn it off. Which of course has the effect that *the output is normally on and you have to actively turn it off*.

Again a pullup resistor can help:

<!-- 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/HlQoD.png)

<!-- End schematic -->

Now R2 keeps the gate of M2 pulled up (switched on) which keeps M1 turned of. That is, until you actively pull the gate down to ground by sending a LOW from the Arduino.

To ensure that the peltier never turns on when you don't want it to you should also take steps to ensure that the 12V power is never provided without the 5V also being provided - so you could maybe power the Arduino through the barrel jack from the 12V supply.  It doesn't matter if the 5V is provided but not the 12V, but the other way around could mean the peltier comes on with no active control over it.


message:
Regarding Strings and assignments

I have this code which works :

    String ErrorMsg;
    .......
    if(!UploadPacketError)
    {
        ErrorMsg="OK";
    }
    else
    {
       ErrorMsg="NOK";
    }

String creates a dynamically allocated array which I want to avoid. I would prefer something like :
```
unsigned char ErrorMsg[5];
......
if(!UploadPacketError)
    {
        strcpy(ErroMsg,"OK",3); // +1 for the Null Termination ?
    }
    else
    {
       strcpy(ErroMsg,"NOK",4); // +1 for the Null Termination ?
    }
```
i.e. is there a way to dynamically assign a value to a fixed size character array ?

Cheers
Thomas

body:
Almost.

First it's `char` not `unsigned char`:

```
char ErrorMsg[5];`
```

Second you don't specify a size with `strcpy`:

```
strcpy(ErrorMsg, "OK");
```

There is a variant of `strcpy` called `strncpy` which copies *at most* `n` characters:

```
strncpy(ErrorMsg, "OK", 5);
```

That is used to prevent buffer overruns. But when working with string literals like that it's pretty pointless.


body:
Also recomending the fixed char approach but for completeness there is a possibility to "get away with String class" IF you **ONLY** use fixed AND predefined Strings to build dynamicly variable messages:

    bool first = true;

    String A = F("My first ");
    String B = F("My second ");
    String C = F("answer");
    if (first) serial.println(A+C);
    else serial.println(B+C);

Read more on the [F-macro here](https://www.baldengineer.com/arduino-f-macro.html).
Conclusion:

  - Large blocks of text to a file system (like SPIFFS, LittleFS, SD)
  - dynamic texts to large enough fixed char arrays and
  - short messages (consisting of fixed parts) can be created with the F-Macro


message:
Error compiling for board Arduino Nano

I have multiple Arduino Nano boards.
I am able to compile or upload code only once. If I try to compile/upload again I get an error: "Error compiling for board Arduino Nano". However there is a workaround: to be able to upload again I change something in tools menu for example board or processor.
I tried all of the nanos and all of the ports.

The error message is below (verbose is enabled).

The problem appeared from nowhere.
Thank you in advance!

    C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
    C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\Nauris\Documents\Arduino\libraries -fqbn=arduino:avr:nano:cpu=atmega328old -vid-pid=1A86_7523 -ide-version=10812 -build-path C:\Users\Nauris\AppData\Local\Temp\arduino_build_956544 -warnings=none -build-cache C:\Users\Nauris\AppData\Local\Temp\arduino_cache_309115 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino5.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\Nauris\Documents\Arduino\RC\wifi_arduino\wifi_arduino.ino
    Using board 'nano' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr
    Detecting libraries used...
    Error compiling for board Arduino Nano.

body: I resolved this issue by installing older arduino ide version.


body:
ive been having this same issue for the last 9 or so month it is driving me insane i have uninstalled and reinstalled arduino in every way i possibly can... using revouninstaller and cccleaner and even tried starting a new user account on my computer and installing it and i still have this issue.. i can only click verify or upload one time and the very next time as soon as i click it i get the exact same error message.. and not just for the nano for every board i have on the list,, it is so irritating!!!! the only work around i have found. well the simplest is to change back and forth from nano old bootloader to atmega328.. or switch back and forth from nano and uno in the boards menu..

so when im trying to put multiple codes together and get it to compile every time i click verify i have to change the board info.. or it instantly says

Using core 'arduino' from platform in folder: C:\Program Files\Arduino\hardware\arduino\avr
Detecting libraries used...
Error compiling for board Arduino Nano.

about to just throw it all in the trash


message:
Possibly fried a new atmega328p?

I have a new atmega328p IC that I wanted to program. To do so I placed it into the socket of an arduino uno. I accidentally placed it the wrong way around (180° rotated), and powered it via USB and tried to upload the blink sketch, which obviously did not succeed. After I noticed it I turned it around and placed it into the socket the right way. I tried again uploading the blink sketch again without success.

1. Have I fried the atmega328p by placing it in the socket the wrong way?
2. Is there something else you need to do to new atmeag328p before you can program them the usual way?

----

**Update:** It seems that just rotating the IC did not damage it in the state where there was no bootloader programmed. And and the bootloader needed to be programmed first before the IC could be used.

body:
Whether your chip is fried or not, we can't say, but they're reasonably tough and will stand a bit of abuse before they fail. Did anything smoke or get hot?

You can buy atmega328p chips pre-programmed with a bootloader from a few vendors, but they don't come from the factory that way so most are not. Preprogrammed chips typically cost a couple of $ US more than blank chips for the time spent by the vendor to buy blank ones, program, and repackage them for sale in small quantities, and are almost always advertised as such. If you don't know whether yours is programmed with a bootloader, it probably isn't. It's worth trying to do it yourself, on a breadboard, using a known-working Uno as a bootloader- programmer. There are lots of how-to articles on the internet.


body: After a reset it should blink pin13 led as all Arduinos do. If not, I'd first try uploading  a bootloader cause I have gotten ones that don't have bootloaders. The 328p if a pretty resistant chip. One time i put 12v into a digital pin and it got so hot the smd desoldered itself but worked fine apart from that pin being blown.


message:
No Websockets Server for Arduino mkr1010?

I've seen some interesting explanations on using websocket comms on mkr 1010 but it's always handling the mkr 1010 as the client and the server being always a computer or some other "non-arduino" server . I'm working on a system with several mkr 1010's in a master/slave setup and bidi comms i.e. i want to use one of the mkr's as a server (does the calculations etc.) and the other as clients (get result from calculations ans send back sensor info). I did not found any library or example of websocket server for mkr1010. I found it for ESP systems. Please help as i tried my bidi comms with webclient and webserver using http but not good enough for my applicaton (not realy bidi).
thanks a lot !

body:
Most websocket libraries work over a Client. Client is base class for all EthernetClient and WiFiClient classes.

But why do you want to use a Websocket for communication of two MCU in the same LAN? Websockets are intended for communication over HTTP infrastructure (firewalls, proxies) to a web server in Internet or from browser to a web server.

Use a basic TCP socket over Arduino Client.

WiFiClient object wraps a TCP socket. A normal TCP socket is connected to IP address and port. WiFiServer starts a listening socket on a port. If server on listening socket is contacted by a remote client socket, it creates a local socket connected with the remote client socket on a free port and returns a WiFiClient object wrapping the socket. Everything you write or print to a WiFiClient is send to that one remote socket.

If one of your client boards creates a WiFiClient and connects it to IP address and port of the WiFiServer on your 'server' board, then you get there a WiFiClient from server.available() and this two WiFiClient objects are connected. What you write/print on one side you read only from the WiFiClient object on the other side.

client socket

    if (client.connect(serverIP, PORT)) {
      client.print("request\n");
      String response = client.readStringUntil('\n');
      Serial.println(response);
      client.stop();
    }

server side

    WiFiClient client = server.available();
    if (client && client.connected()) {
      String request = client.readStringUntil('\n');
      Serial.println(request);
      client.print("response\n");
      client.stop();
    }


message:
Runtime compilation

I want to compile a sketch on Arduino Uno, while Arduino is running and not connected to anything else, and then run the compiled sketch automatically.

Is this feasible?

How?

body:
No. It's not feasible.

The Uno cannot compile.  The Uno cannot run code from RAM.  The Uno is *not* a computer.

You *might* be able to find some small scripting language that could run on an Uno, but TBH the Uno is so underpowered you'd be able to do little more than blink an LED...


body:
No, not feasable, not possible.

The Arduino runs machine code and it does not have enough space or computation power for a compiler (also there is simply no version of the avr C++ compiler for the AVR platform, for obvious reasons). Also it is internally hardwired to run code from the flash memory. You cannot execute code from RAM. The Arduino is a microcontroller, not a computer. (Here I mean computer as something like: Has a microprocessor to execute code from RAM; has an OS; has huge amount of resources in relation to the average microcontroller)

Also: "not connected to anything else" --> Then how would you interact with the Arduino, writing the code, triggering compilation?

If this is about the cable connection, you can implement programming over bluetooth through the HC-05 module (google for it, there should be plenty of tutorials out there). Or go away from the Arduino and change to an ESP, so that you can do Over The Air (OTA) updates over wifi.

Or you could change to a minicomputer like the Raspberry Pi Zero, which is just a little bigger than the Arduino Nano and smaller than the Uno. (Though that hardly depends on the goal, what you are trying to achieve. Microcontrollers are sometimes better used for specific tasks in contrast to minicomputers)


message:
read state from button to check if clicked

I"m kinda new here and new to the arduino framework.

I want to build a "menu" using LCD 20*4, so I want to detect "button clicked" event.

I've connected button to pin 8 and to ground, like this(please ignore the other wiring):
[![enter image description here][1]][1]

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

    int leftButton = 8;

    void setup() {
      pinMode(leftButton, INPUT);
      digitalWrite(leftButton, HIGH);
      Serial.begin(9600);

    }
    bool leftButtonClicked(){
      return digitalRead(leftButton);
    }
    void loop(){
      delay(20);
      Serial.println(digitalRead(leftButton));
    }

I am receiveing on the serial `1` while the button is not clicked, and when its clicked I receive `0`.

What is the problem? Thank you guys.

body:
As you are a beginner, you seem to have some misconceptions:

- **Reading button state with `digitalRead()`:** You thought something is wrong, because you thought that `digitalRead()` returns, if the button was pressed (thus 1 would mean pressed). But that is not directly the case. `digitalRead()` returns the electrical state of the corresponding pin (if the pin voltage is at ground level (0) or Vcc (supply voltage) level) (1)). This corresponds with the button depending on your wiring. I guess you copied the wiring somewhere in the internet. It shows the most common way of connecting a button. The button consists only of two contacts, which get pressed together, when you press the button. So the button can connect the pin to either ground or Vcc, but not to both. When the button is not pressed, the pin is connected to nothing, thus it is floating and the value changes erratically. This is solved with a pullup or pulldown resistor (a rather big resistor from the pin to either Vcc or ground), which sets the value of the pin, when the button is not pressed. That means, that you need 1 resistor for each button, that you want to use. The good news is: The Arduino already has internal pullup resistors, that you can activate via `pinMode(pin, INPUT_PULLUP)`. That way you can save 1 extra component. Since it is a pullup resistor, which connects the pin with Vcc, you need to connect the button with ground.

    That also gives you the inverted logic. In the end it is determined by you, what the `digitalRead()` value means. Think electrically about it.

- **Events:** In Arduino programming there are not events. You are programming very much directly the hardware. There is no OS or GUI system, that would handle events for you. The program, that you write, runs command after command with a specific speed (determined by the Arduinos clock frequency; 16MHz for the Uno), pretty much linearly. Though there is one exception for that: interrupts. Microcontrollers have some peripherals build into them (ADC, communication interfaces, Timers, ...) and many of them work parallel to the main program (since their function does not need code, but is implemented in hardware). These peripherals can generate interrupts (for example to service the peripheral), which pauses the normal run of the program, runs an ISR (Interrupt Service Routine) and then returns to the main program. That is somewhat like an event, but very hardware specific and not nearly as generically usable as events on a PC.

- **Reading a button click:** In your code you don't read the "button click", but only the state of the button. Thus you get multiple times 0 for one long enough button press. For the real click action you need to look for the transition from 1 to 0, which ideally only happens one time per button press. I write "ideally", because real life buttons bounce. In the moment of contact the value changes rapidly multiple times, until the button contacts have settled. So you need to debounce the button. You have already done basic debouncing by using `delay(20)` (because the button may need about that time to stabilize). You can see more sophisticated debouncing in the [Bounce2][1] library, which is also easy to use for reading button clicks and presses.

  [1]: https://github.com/thomasfredericks/Bounce2


message:
How do I set up a multi-file project in the Arduino IDE?

Suppose I have a project with several modules and a main program.  This works well by adding the modules to main_program.

    module1.cpp
    module1.h
    module2.cpp
    module2.h
    ...
    main_program.ino

I'm having problems when I have test programs for each of the modules.  These allow the various devices to be tested in isolation.

    module1.cpp
    module1.h
    module1.ino # test program
    module2.cpp
    module2.h
    module2.ino # test program
    ...
    main_program.ino

I'm required to have each ino file in a directory of the same name.  I can add the files to main_program by adding (e.g.) ../module1/module1.{cpp,h}.  But, I discover that it has actually copied module1.{cpp,h} to main_program/.

How do I set this up?  Is there any option other than making each module a library?  If possible I would like to keep these files more local than the library directory, since they're specific to this project and not general-purpose libraries.

body:
You have two options with ArduinoIDE.

**First** Each module in a module directory

So the structure looks like

      main_routine
         main_routine.ino
      --module1
          module1.ino  #test routine
          module1.cpp
          module1.h
     --module2
      .....
included in `main_routine.ino`

       #include "module1/module1.h"
       #include "module2/module2.h"

So you have everything in your master dir and in module specific subdirs below - Nothing is or will be copied by the ArduinoIDE (v1.8.12)

The **second** (more hacky way) is to have everything in one dir and for development testing working with include guards in the `main_routine.ino`

     // for production comment all MODULEX_TEST and uncomment PRODUCTION
     //#define PRODUCTION
     #define MODULE1_TEST
     //#define MODULE2_TEST
    .....
    #if defined (PRODUCTION) || defined (MODULE1_TEST )
       #include "module1/module1.h"
    #endif

    #if defined (PRODUCTION) || defined (MODULE1_TEST )
       uint8_t myModule1Var = 0;
    #endif

    setup(){
    .....
    #if defined (PRODUCTION) || defined (MODULE1_TEST )
       myModule1setup someInit(1,2,3);
    #endif
    .....
     }

    loop(){
    .....
    #if defined (PRODUCTION) || defined (MODULE1_TEST )
       void mymodule1Func(){....};
    #endif
    #ifdef MODULE1_TEST
       void mymodule1Test(){....};
    #endif

Pros and cons

  - +This approach gives you the possibility to test two modules together.
  - -Its harder to read, but
  - +easier to document with tools like doxygen
  - ~Only the active includes are compiled and so no overhead in the compiled code

Be aware that with some tool chains there are at the moment problems when using special templates (works if everything is in one module file - I use an "extended header" file as momentary work around) or arrays as initializer (open issue in esp8266)


message:
acelermetor count goes down after 1 peak

I am using a Wemos D1 Mini and an mpu 6050 accelerametor. I managed to get the acceleratmetor to work and have 1 value come out of movements. So when a peak it hit (aka, the threshold of 1.00 is hit) n gets incremetented with 1. So it work a bit like a pedometer. This value is pushed to my firebase DB.

However mY problem is that after pushing it once, so the value of n is 1. The program blocks for a second and either slows down bad or the accelerametor value drops to 0. this only happens when i my piece of firebase code in. Im not sure if this causes any delays..

here is my part of my code:

    #include <Wire.h>

    #include "ESP8266WiFi.h"
    #include "FirebaseArduino.h"

    #define FIREBASE_HOST "xxxxxxxxxx.firebaseio.com" //Without http:// or https:// schemes
    #define FIREBASE_AUTH "XXXXXXXXXXXXXXXXXXXXX"
    #define WIFI_SSID "Bankai"
    #define WIFI_PASSWORD "xxxxxxxxxxxx"

    const float HI_THRESHOLD = 1.00;
    const float LO_THRESHOLD = 0.70;
    bool count_flag = false;

    int n= 0; //will be used to store the count
    int oldValue = n;
    String myString;

    const uint8_t MPU_addr = 0x68; // I2C address of the MPU-6050

    const float MPU_GYRO_250_SCALE = 131.0;
    const float MPU_GYRO_500_SCALE = 65.5;
    const float MPU_GYRO_1000_SCALE = 32.8;
    const float MPU_GYRO_2000_SCALE = 16.4;
    const float MPU_ACCL_2_SCALE = 16384.0;
    const float MPU_ACCL_4_SCALE = 8192.0;
    const float MPU_ACCL_8_SCALE = 4096.0;
    const float MPU_ACCL_16_SCALE = 2048.0;

    struct rawdata {
      int16_t AcX; //Acceleration
      int16_t AcY; //Acceleration
      int16_t AcZ; //Acceleration
      int16_t Tmp;
      int16_t GyX; //Gyroscope
      int16_t GyY; //Gyroscope
      int16_t GyZ; //Gyroscope
    };

    // Using int variables to convert later on to degrees and decimals
    struct scaleddata {
      float AcX; //Acceleration
      float AcY; //Acceleration
      float AcZ; //Acceleration
      float Tmp;
      float GyX; //Gyroscope
      float GyY; //Gyroscope
      float GyZ; //Gyroscope
    };

    bool checkI2c(byte addr);
    void mpu6050Begin(byte addr);
    rawdata mpu6050Read(byte addr, bool Debug);
    void setMPU6050scales(byte addr, uint8_t Gyro, uint8_t Accl);
    void getMPU6050scales(byte addr, uint8_t &Gyro, uint8_t &Accl);
    scaleddata convertRawToScaled(byte addr, rawdata data_in, bool Debug);

    //start connection, serial, and connection to db
    void setup() {
      Wire.begin();
      Serial.begin(115200);

      mpu6050Begin(MPU_addr);

        WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
      Serial.print("Connecting to Wi-Fi");
      while (WiFi.status() != WL_CONNECTED)
      {
        Serial.print(".");
        delay(100);
      }
      Serial.println();
      Serial.print("Connected with IP: ");
      Serial.println(WiFi.localIP());
      Serial.println();
        Firebase.begin(FIREBASE_HOST, FIREBASE_AUTH);

    }

    //if the value now is different from the current value it gets pushed to the DB, otherwise a flood of numbers apperars.
    void loop() {
      rawdata next_sample;
      setMPU6050scales(MPU_addr, 0b00000000, 0b00010000);
      next_sample = mpu6050Read(MPU_addr, false);
      convertRawToScaled(MPU_addr, next_sample, false);

I feel likeit is thei part which creates the bottleneck.

      //myString = String(n);
      if(oldValue != n){
       Firebase.setInt("Reps/Value", n);
      }
      delay(100); // Wait 5 seconds and scan again

    }

     float filterConstant = 0.05;
      values.AcX = (float) data_in.AcX / scale_value;
      values.AcY = (float) data_in.AcY / scale_value;
      values.AcZ = (float) data_in.AcZ / scale_value;
      filteredAx = filteredAx * (1.0 - filterConstant) + values.AcX * filterConstant;
      filteredAy = filteredAy * (1.0 - filterConstant) + values.AcY * filterConstant;
      filteredAz = filteredAz * (1.0 - filterConstant) + values.AcZ * filterConstant;
      float result = sqrt((filteredAx * filteredAx) + (filteredAy * filteredAy ) + (filteredAz * filteredAx ));

    //  Serial.print(values.AcX); Serial.print("\t");
    //  Serial.print(filteredAx); Serial.print("\t");

      Serial.println(result);

      //    Serial.print(values.AcY); Serial.print("\t");
      //    Serial.print(values.AcZ);
    //  Serial.println();

     if( result > HI_THRESHOLD && !count_flag) //if analog_in > Hi_THRESHOLD and count_flag == false
         {
               n++;
               count_flag = true;
         }

         if(result <= HI_THRESHOLD) //set count_flag to false only when below the threshold
               count_flag = false;

      Serial.println(n);

      return values;
    }

Can you help me find the problem? Thank you!

body:
Logging the data is indeed what slows your program down.  You can't avoid that.  There are several ways to deal with it depending on what you need.

Instead of logging data all the time, you could try to accumulate a bunch of data and then write it.  This approach of buffering data will still fail to read while you log, but you will be able to get bursts of good data in between.


message:
store multiple of float type on EEPROM

I have 7 float variables.

`float temperature, differential, calibration,hta,lta,hha,lha;`

I want to store them all on the EEPROM memory, how do I calculate the addresses given that there type is float.

Thanks!

body:
With the `sizeof` function:

    int nrOfBytesOfTemperature = sizeof(temperature);

You can also use directly a type:

    int nrOfBytesOfFloat = sizeof(float);


body:
create a struct and store the struct

    #include <EEPROM.h>

    const int DATA_ADDR = 0;

    struct MyData {
      float temperature, differential, calibration,hta,lta,hha,lha;
    };

    MyData data;

    void setup() {
      data.temperature = 1.2;

      EEPROM.put(DATA_ADDR, data);

      EEPROM.get(DATA_ADDR, data);
    }

    void loop() {

    }


message:
Making a Bluetooth Mouse with Arduino

I'm trying to make a bluetooth mouse using Arduino. I will be using an analog 2 axis thumbstick as the sensor. I understand that it's possible to do this with the Arduino connected directly to the computer (https://www.arduino.cc/reference/en/language/functions/usb/mouse/). Would it be possible for the arduino to instead communicate wirelessly using bluetooth? The controller I'm interested in is here: https://www.dfrobot.com/product-1259.html

Thank you!

body:
With that specific board, yes you can.  According to [this review](http://www.lucadentella.it/en/2018/01/25/ble-con-bluno-beetle/):

> Bluno also supports the HID (Human Interface Device) mode. When running in this mode, Bluno simulates an input peripheral (keyboard, mouse…) connected via BLE.


message:
Stepper Motor is not working with A4988 board

So, I have been following this tutorial on how to run a stepper motor with Arduino using an A4988 Stepper Driver. This is the tutorial: [How To Control a Stepper Motor with A4988 Driver and Arduino][1]. I have connected the wires according to this schematic:

[![Schematic][2]][2]

I have connected the wires exactly like this and triple-checked it! The problem is the stepper motor is not turning. This is the code(it's simple):

    // defines pins numbers
    const int stepPin = 3;
    const int dirPin = 4;

    void setup() {
      // Sets the two pins as Outputs
      pinMode(stepPin,OUTPUT);
      pinMode(dirPin,OUTPUT);
    }

    void loop() {
      digitalWrithe(dirPin,HIGH); // Enables the motor to move in a particular direction
      // Makes 200 pulses for making one full cycle rotation
      for(int x = 0; x < 200; x++) {
        digitalWrite(stepPin,HIGH);
        delayMicroseconds(500);
        digitalWrite(stepPin,LOW);
        delayMicroseconds(500);
      }
      delay(500); // One second delay
    }

One weird thing:
> **When I connect the sleep and reset pin on the A4988 board the stepper motor starts turning. Like why?**

**NOTE:** I replaced the MEGA with a UNO because at the moment I'm just testing.

  [1]: https://www.youtube.com/watch?v=5CmjB4WF5XA
  [2]: https://i.stack.imgur.com/VyPmX.png

body:
You have to connect the sleep and reset pin together. I assume that you took this schema on how to mechatronics. In his video you see that the sleep and reset pins are connected. I don't know why but it has to be like that.

Then, if the motor vibrates or click, it may be one of these problems:
- You didn't connect the motor properly
- The current is set too low on the board (screw on the motor driver)
- The battery (Vmot) isn't powerful enough

If it's not one of those problems, the A4988 chip might have an issue. I have a similar problem where it turn in one direction and only when the pwm signal goes throught the direction pin  instead of the step pin.


message:
random soft wdt reset while request

i am making post requests with esp8266 on nodeMCU. i have a messy code so i dont want to annoy you with showing it here. the problem is i get soft wdt reset time to time while making request. for example i change piece of code(removing or adding some `serial.println` lines) and i see i get soft wdt reset right there in `http.post`.

i tried my best to avoid Strings. I only used a few times, without in the loop. I am only using WiFiClientSecureBearSSL with FirebaseESP8266.

do you have any idea what cause this problem?

body:
Show examples of the error - and install ESPexeption decoder to analyse the stack trace this will at least show why the wdt was caused

So the only thing as of now I can recommend

There is an issue with bearssl:

It's a WDT error caused by an extended SSL negotiation.

  - Change the core frequency to 160MHz (if not already done) and try again.
  - Use instead of LWIP1.4 (memory hog) low-mem LWIP2.0 with your program.
  - Since SSL negotiation can take 5 seconds even at 160MHz for some websites be sure by adding a yield() not to trigger a wdt reset

So without code/ trace and error messages its hard to guess


message:
Arduino "Phantom Powering"

I am using an Arduino Uno in my project. I recently found that if I disconnect the power from my Arduino (I am powering it by USB port, from a 5V regulator - 7805), then it remains under power from the input pins. I also found that if I disconnect the 3 digit 7 segment common anode display (which is also powered from same 7805) and if I remove the LM358 (which is again powered from the same 7805) from the socket, then my Arduino is not powered anymore.
My questions are:

1. Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?
2. My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Please find attached 2 schematics, one is the main PCB (the one with Arduino) and the other schematic is the one with the display, which is placed on the front panel. The J2 connector from first schematic is connected pin to pin to the J2 from second schematic.

https://ibb.co/QnLHsM0

https://ibb.co/KxLFKsQ

body:
When you disconnect the arduino from 5V you must also remove either

 - disconnect any other device that is connected to the arduino and has its own power supply
 - or disconnect every device that is connected to the arduino from its power supply

When you disconnect 5V from the arduino while devices connected to a gpio are still powered, this gpio might see a voltage larger than zero. But the voltage at any pin must not exceed the arduino's actual supply voltage by more than 0.3V. Otherwise the atmega's supply rail will be pulled high through esd protection diodes and the atmega will try to operate. It will then probably draw more current than what the esd diodes are rated for and they will eventually fail (destroying that gpio).


body:
> Is my setup correct - if I am powering it from the 5V regulator (7805) through the USB port ?

Yes.

> My Arduino and the other components from the schematic - the display, the LM358, the mosfet - will be powered on at the same time, when the 230V switch that is placed on the mains input of the 24V SMPS is closed. Could this be a problem in terms of "phantom powering" ? Is there any better way to power the Arduino when I have 5V regulated supply on the schematic ? I will always keep connected the Arduino to the 5V output of the 7805 to the USB port.

Not really.

Your problem only occurs when you "break" the system by separating the 5V from the Arduino - at which point current flows from the output of the op-amp and through the LED displays, through the IO pins, up through the clamping diodes inside the IO pins, and to the Arduino's 5V.

Since it only happens if you disconnect the 5V and you don't intend to disconnect the 5V then it's not a problem. However if you wanted to improve it then you could take the output of the 5V reguator and feed that direct into the Arduino's USB port. You could then power all the other devices that run at 5V from the Arduino's 5V pin.  That way if you remove the 5V from the Arduino then you also remove it from all the other 5V devices that potentially feed power back in.


message:
Why is delay(1000) breaking my serial communication?

I have the following sketch...

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(115200);
    }

    void loop() {
      if(Serial.available() > 0){
        Serial.println("Hello world from Ardunio!");
      }
    }

This works great with my client code...

    import SerialPort from 'serialport';
    const port = new SerialPort('/dev/ttyACM0', {
      baudRate: 115200,
      autoOpen: false
    })

    port.open(function (err) {
      if (err) {
        return console.log('Error opening port: ', err.message)
      }

      // Because there's no callback to write, write errors will be emitted on the port:
      console.log("port opened");
      port.on('readable', function () {
        console.log('Data:', port.read())
      })
    })

Now I want to slow it down so I change the sketch to...

    void loop() {
      if(Serial.available() > 0){
        Serial.println("Hello world from Ardunio!");
      }
      delay(10000);
    }

I would expect this to delay each message by 10 seconds, however, it seems to never rerun so I do not get any messages. What am I missing? Why would delay break the loop?

body:
NEVER use delay() in a loop - its a bad habit you get used to and then you return later on with complex code asking why nothing is happening or your webserver is dead for 10 seconds every time you receive a request.

 So instead of

    void loop() {
      if(Serial.available() > 0){
        Serial.println("Hello world from Ardunio!");
      }
      delay(10000);
     }

you would do

    unsigned long timerStart = 0;
    unsigned long myTimer = 10000;

    setup(){....}

     void loop() {
      if(Serial.available() > 0 ){
         if(millis() - timerStart > myTimer){      // non blocking
           Serial.println("Hello world from Ardunio!");
           timerStart = millis(); // reset timer
         }
       }
     }

What your code does at the moment is enter the IF clause if exactly in this millis the buffer is filled, then wait for ten seconds ignoring whatever you do. Next chance tohit and so on. Delay() is blocking processing => not a good thing todo in communication scenarios,


body:
Get rid of `if(Serial.available() > 0)`. You only need that if statement if you're expecting information from `Serial`, but it doesn't seem to be the case for your project.

Also, only use `delay()` if you have a really good reason to.


message:
Car PA system enhancement

Hello i have one of [these](http://gg.gg/hwrmi)

My goal for this project is to have a higher quality mic and be able to play music through it

My question is how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line. I have prior knowlege on liking a aux as i have setup my Christmas lights as a vu meter using relays and a aux but the confusing part is the rj9 line

Are the speaker pins only to trigger a relay and allow power to flow from the car battery or am i completely wrong if im right i assume i could just solder the audio jacks positive negative to the rj9 mic positive negative and then find a method to triger the speaker relay

body:
"how would i link a 3.5mm aux cable to the arduino as input and output to the rj9 line" - the arduino uno doesn't have a digital to analog converter, so without external hardware it's not possible to make him generate the audio signal. Also its ADCs are not fast enough to sample an audio signal coming from a microphone at a sufficient sample rate (I think the maximum are 1-2kHz). As you explicitly want to improve sound quality this is an issue.

When using an arduino uno you might be better off using an external audio circuit which only gets switched on and off by the arduino.
Controlling the siren's buttons will not be a big difficulty. You have to do some reverse engineering to find out the siren's logic level and how the buttons are used in the device. You can probably simply replace them with mosfets, but that is an electronic issue.


message:
Restart sequence of NeoPixel stick with a push button at any time

I am really happy with my new Arduino stuff and playing around with all those pixels :).

I am new to programming and it's difficult to understand it, but with every success, I grow in knowledge.

My latest problem now is to restart my loop of incrementing the strip at any time with the push of a button.

I know that `delay();` will stop the code completely and wait till the time passes, but I wrote some code without the use of `delay();` and used `millis();` instead.

So far my LEDs are incrementing through my strip, but I am not able to restart it until it passes though completely. I read that the `while();` part in my code works kinda like a `delay();` and that would prevent it from restarting until a full cycle. I used some `millis();` code from a different sample so it's not like the ones from Blink Without Delay.

I searched so many sites and cannot write another code to increment without a delay, so hopefully you can help me with it.

```
#include <FastLED.h>

#define NUM_LEDS_PER_STRIP 16
CRGB ledStrip[NUM_LEDS_PER_STRIP];

const int signalButtonPin = 4;
const int ledStripPin = 8;

int buttonState = 0;
int lastButtonState = 0;

int delaySignalAnimation = 100;

unsigned long currentMillis = 0;
unsigned long previousMillis = 0;

void setup() {
  pinMode(signalButtonPin, INPUT_PULLUP);
  pinMode(ledStripPin, OUTPUT);
  FastLED.addLeds<NEOPIXEL, 8>(ledStrip, NUM_LEDS_PER_STRIP);
}

void loop() {
  buttonState = digitalRead(signalButtonPin);
  if (buttonState != lastButtonState) {
    if (buttonState == LOW) {
      fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
      for (int i = 0; i < 16; i++) {
        ledStrip[i] = CRGB::Blue;
        FastLED.setBrightness(100);
        FastLED.show();
        currentMillis = previousMillis = millis();
        while (previousMillis + delaySignalAnimation >= currentMillis) {
          currentMillis = millis();
        }
      }
    } else {
      lastButtonState = buttonState;
    }
    fill_solid(ledStrip, NUM_LEDS_PER_STRIP, CRGB::Black);
    FastLED.setBrightness(0);
  }
  FastLED.show();
}
```

Thanks in advance for you help.

body:
Firstly, good for you trying to avoid `delay()`.

However your `while` loop pretty much does exactly what `delay()` does anyway.

Instead you need to change your way of thinking. Instead of "I want to light LEDs 0 to 15 in sequence" you need to instead think "I have 6 LEDs lit. Now I need to light the 7th".

Each time through the loop, if enough time has passed (check the BlinkWithoutDelay example) then light *just one more LED*.  Once you have lit all 16 you can then restart your sequence.

And when you know how to restart your sequence at the end you should also know how to restart the sequence when you press a button.

For example `loop()` might look something like this (untested):

```
void loop() {
    static uint8_t lednum = 0;
    static uint32_t animTicker = millis();

    if (millis() - animTicker >= 1000) { // Once per second
        animTicker = millis();

        lednum++;
        if (lednum > NUM_LEDS_PER_STRIP) lednum = 0; // This resets the sequence

        // Turn on up to lednum LEDs and turn off the others
        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
            if (i < lednum) {
                ledStrip[i] = CRGB::Blue;
            } else {
                ledStrip[i] = CRGB::Black;
            }
        }

        FastLED.show();
    }

    buttonState = digitalRead(signalButtonPin);

    if (buttonState != lastButtonState) {
        lastButtonState = buttonState;
        if (buttonState == LOW) {
            lednum = 0;
        }
    }
}
```

The key there is that the variable `lednum` contains the number of LEDs that you want to display. Once per second, controlled by `millis()`, the LEDs are updated to display that number of LEDs.


body:
This is not an answer, but an expansion on Majenko's code.

It adds another layer between the button press and the led display functions to make the program more flexible

    void loop() {

        static bool     tick          = false;                 // periodic trigger signal
        static bool     zap           = false;                 // enable signal to run sequence
        static bool     buttonClicked = false;                 // button moved from "released" to "pressed"

        static uint8_t  mode          = 0;                     // chooses the light sequence to run
        static uint8_t  lednum        = 0;

        static uint32_t animTicker    = millis();

        if (millis() - animTicker >= 1000) {                   // Once per second
            animTicker = millis();
            tick = true;                                       // set the tick flag
        }

        if (buttonClicked) {                                   // you could check for a double-click here
            buttonClicked = false;
            zap = !zap;                                        // start/stop with button  ... zap is used for the separation of the button click function and the display function
            if (zap) {
                lednum = 0;                                    // start animation sequence at beginning
                mode += 1; if (mode > 2) mode = 0;             // select the next mode .... this could be done with a double-click
            }
        }

        if (tick && zap) {
            tick = false;                                                   // clear the tick flag .... zap stays set for the duration of the animation sequence
            lednum++;

            if (lednum > NUM_LEDS_PER_STRIP) {
                zap = false;                                                // This stops the sequence (runs only once) ... use a counter if multiples are needed
            }

            else {
                switch (mode) {                                             // pick one of the sequences ....  only colors change in this example

                    case 0:
                        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {  // Turn on up to lednum LEDs and turn off the others
                            if (i < lednum) {
                                ledStrip[i] = CRGB::Blue;
                            } else {
                                ledStrip[i] = CRGB::Black;
                            }
                        }
                        break;

                    case 1:
                        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                            if (i < lednum) {
                                ledStrip[i] = CRGB::Red;
                            } else {
                                ledStrip[i] = CRGB::Black;
                            }
                        }
                        break;

                    case 2:
                        for (uint8_t i = 0; i < NUM_LEDS_PER_STRIP; i++) {
                            if (i < lednum) {
                                ledStrip[i] = CRGB::Green;
                            } else {
                                ledStrip[i] = CRGB::Yellow;
                            }
                        }
                        break;
                }

                FastLED.show();
            }
        }

        buttonState = digitalRead(signalButtonPin);

        if (buttonState != lastButtonState) {        // button state transition
            lastButtonState = buttonState;           // new "last state"
            if (buttonState == LOW) {                // transition from "released" to "pressed"
                buttonClicked = true;
            }
        }
    }


message:
Error messages while verifying code with Visual Studio Code

I move recently to use Visual Studio Code to develop for arduino. But I'm receiving some error messages while I'm trying to verify my code that confuse me. The messages are:

```
2020-04-12T13:53:40.409Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=20892E5EE7E84976
2020-04-12T13:53:40.926Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=20892E5EE7E84976, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:40.926Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404
2020-04-12T13:53:40.937Z INFO c.a.u.n.HttpConnectionManager:148 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Connect to https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA, method=GET, request id=D8C082A90BB14CDF
2020-04-12T13:53:41.044Z INFO c.a.u.n.HttpConnectionManager:152 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Request complete URL="https://builder.arduino.cc/builder/v1/boards/0x8087/0x0ACA", method=GET, response code=404, request id=D8C082A90BB14CDF, headers={null=[HTTP/1.1 404 Not Found], Cache-Control=[no-cache, no-store, must-revalidate], Server=[nginx], Connection=[keep-alive], Vary=[Origin], Pragma=[no-cache], Expires=[0], Content-Length=[0], Date=[Sun, 12 Apr 2020 13:53:41 GMT]}
2020-04-12T13:53:41.044Z WARN p.a.h.BoardCloudResolver:64 [cc.arduino.packages.discoverers.serial.SerialDiscovery] Fail to get the Vid Pid information from the builder response code=404
```

Based on this output it seems something is happening with these URLs but when I try to do the same in the same computer with Arduino IDE there is no such error messages.

Does anybody know how to get rid of these messages?

Thank you very much.

body:
It works with Arduino IDE either 1.8.9 OR 1.8.12 BUT the VS code extension is broken. So

  - You have to downgrade to January release 1.42 **AND**
  - Then turn off automatic updates for the moment.

How to get the release: [Click here](https://code.visualstudio.com/updates/v1_42)

Before installing /downgrade<br>
The excessive debug logging is caused by running Java with -DDEBUG=true. Adding -DDEBUG=false to the C:\Program Files (x86)\Arduino\arduino_debug.l4j.ini fixes it for now.