message:
WiFiManager - Combine NonBlocking portal AND addParameter

I wish to config `WiFiManager` and `addParameter` of MQTT topic and local server on its ConfigPortal.

Additionally in a case of a power outage or any, in case of losing WiFi, to continue in a `NonBlocking` way.

The problem is when combining both features in one sketch, I get some errors.

Entire code is ( please notice comments marked `Marker[i]` ):

    #include <WiFiManager.h>
    #define MQTT_SERVER "192.168.3.200"
    WiFiManager wm;

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

      WiFiManagerParameter custom_mqtt_server("mqtt_server", "mqtt server", MQTT_SERVER, 40);
      WiFiManagerParameter custom_mqtt_user("mqtt_user", "mqtt user", "", 10);
      WiFiManagerParameter custom_mqtt_pwd("mqtt_pwd", "mqtt password", "", 10);
      WiFiManagerParameter custom_mqtt_topic("mqtt_topic", "mqtt topic", "", 10);
      WiFiManagerParameter custom_mqtt_group("mqtt_group", "mqtt group", "", 10);
      WiFiManagerParameter custom_mqtt_root("mqtt_root", "mqtt rootTopic", "", 10);
      wm.addParameter(&custom_mqtt_server);
      wm.addParameter(&custom_mqtt_user);
      wm.addParameter(&custom_mqtt_pwd);
      wm.addParameter(&custom_mqtt_topic);
      wm.addParameter(&custom_mqtt_group);
      wm.addParameter(&custom_mqtt_root);

      WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
      //  wm.resetSettings();

      //  wm.setConfigPortalTimeout(180);
      // wm.setConfigPortalBlocking(false);  // <--- Marker [#1]

      //  if (!wm.autoConnect("AutoConnectAP")) {
      //    Serial.println("failed to connect and hit timeout");
      //    delay(3000);
      //    //reset and try again, or maybe put it to deep sleep
      //    ESP.restart();
      //    delay(5000);
      //  }

      bool res;
      res = wm.autoConnect("test123", "password"); // password protected ap
    }

    void loop() {
      // put your main code here, to run repeatedly:
      //  wm.process(); //<--- Marker [2]
      Serial.println("hi");
      delay(100);

    }

1) When `Marker[1]` & `Marker[2]` are commented out ConfigPortal works as expected, and in `Blocked` state - meaning there is no `hi`'s on Serial monitor.

2) When only `Marker[2]` is commented out, ConfigPortal is reached, lacking all `addParameter` fields.

3) When `Marker[1]` & `Marker[2]` are not commented out, ConfigPortal is now reachable, but not having Non-Blocking feature...

4) What is the purpose of `wm.process()` ?

Guy

body:
The WiFiManger's `autoConnect` function starts the configuration web server (and AP) only if connection to configured WiFi network is not established.

If you want to run the WiFiManger's web server to reconfigure WiFi or to set other parameters, you can start the WM web server with the `startConfigPortal` function.

`autoConnect` and `startConfigPortal` are blocking by default. The library has a loop inside this functions which runs until the web server is stopped calling [Exit] action on the configuration web page or the timeout set with `setConfigPortalTimeout` is reached after last contact from browser.

To run the WM web server 'parallel' to your sketch you can configure it as not blocking with `setConfigPortalBlocking(false)`. Then to allow WM handling of the web server the sketch must periodically call `wm.process()`.

In not blocking mode the [Exit] action on the configuration wen page doesn't stop the web server. The server must be stopped in code.

The parameter definitions must by global in sketch, if you want to run WiFiManager with parameters outside of setup(). Parameters local in setup() don't exist after setup() finishes. WiFiManager detects this and doesn't use the parameters.

The `OnDemandWebPortal` example and `OnDemandNonBlocking` example demonstrate `startConfigPortal` in blocking and not blocking use.


sender: user

message:
Convert from hexadecimal to binary

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

I need to simulate a pulse train. Everything is in order with this code, it solves its problem.
The question is: I need to change the keys, but it is too difficult to manually type in so many zeros and ones each time.
On the other hand, I know that my hexadecimal key looks much shorter: "B8C4F9".
  Is it possible to create a string in such a way that the system itself translates to the binary system?

And the second question: How can you automatically measure the length of an array so as not to manually calculate KEY_LEN?

    const int KEY_LEN = 24;
    const char key[KEY_LEN] = {"101110001100010011111001"};

    int T = 200; // Pulse repetition period in microseconds
    int Zero = 80; //0.4*T; // Duration of zero in microseconds
    int One = 120; //0.6*T;// Duration of a unit in microseconds

    const int LED_PIN = 13; // Used digital pin 13 of the arduino to connect the transmitter

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

    void loop()
    {
      for (int n = 0; n < KEY_LEN; n++)
      {
        if (key1[n] == '1') //If the bit read == 1
        {
          sendSignal(One);
        }

        else if (key1[n] == '0')//If the bit being read == 0
        {
          sendSignal(Zero);
        }
      }
    }

    void sendSignal(int duration)
    {
      digitalWrite(LED_PIN, LOW);
      delayMicroseconds(duration);
      digitalWrite(LED_PIN, HIGH);
      delayMicroseconds(T - duration);
    }

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

sender: assistant

body:
There is really no reason to save the key as a string, as you are doing. You can just save it as a normal number. Then you can also use the hexadecimal representation on your code:

    unsigned long key = 0xB8C4F9;

Then you need to send out each bit of that number:

    for (int n = 0; n < KEY_LEN; n++)
    {
        if (key & (1 << n)) { //If the bit read == 1
            sendSignal(One);
        } else {//If the bit being read == 0
            sendSignal(Zero);
        }
    }

The following is happening in the if statement: `(1 << n)` will take the value 1 (binary `0b00000001`) and will shift the bits to the left by n digits. For example: If n is 2, we get `(0b00000001 << 2) = 0b00000100`. With this we can select a bit in our number. Then we take that and do a bitwise AND `&` with the key. That will set all bits to zero, which are not currently selected. The resulting number is zero, if the corresponding bit in `key` is zero. If the corresponding bit is 1, this will return a number different from zero (which is interpreted as `true`. Thus we check, if the n-th bit of `key` is one or zero.

> How can you automatically measure the length of an array so as not to manually calculate KEY_LEN?

Generally you can calculate the size of an array with the `sizeof()` function:

    unsigned int size_of_array = sizeof(array)/sizeof(array[0]);

`sizeof()` returns the number of bytes. So to get the number of elements, we need to divide by the number of bytes in each element;

For the way shown above this is not that easy. Normally it is not really needed, since such keys normally don't change length very often. If you find a variable type, which exactly fits your key size, you could use `sizeof(key)*8` to get the number of bits in it. But your current value `0xB8C4F9` only needs 3 bytes. I don't know a type with 3 bytes, but maybe somewhere you can get something like `uint24_t`. Honestly here I would just use a hardcoded size, just like you are using a hardcoded key value.


message:
ATTiny85 won't boot if PIN2 is not pulled high

I had some problem setting up a working ATTiny85 outside of its development board.
Connection on my breadboard:

    pulled high (10K R)  -- 1  PIN 8  -- VCC (+5V)
         trouble here!!  -- 2  PIN 7  --
                         -- 3  PIN 6  -- LED
                   GND   -- 4  PIN 5  --

as you can guess pins are referred to actual chip's pins enumeration.
My simple test code:

```c++
void setup() {
  pinMode(1, OUTPUT);
}
void loop() {
  if (analogRead(A1) > 512) {
    digitalWrite(1, HIGH);
    delay(250);
    digitalWrite(1, LOW);
    delay(250);
  } else {
    digitalWrite(1, HIGH);
    delay(1000);
    digitalWrite(1, LOW);
    delay(1000);
  }
}
```

I'm using Arduino IDE v1.8.13 with digistump avrboards v1.6.7.

I flashed t85_default [micronucleus][1] v2.5 bootloader in my chip with fuses set to lfuse:0xe1, hfuse:0xdd, efuse:0xfe.
The problem is that if I power the chip with PIN2 not pulled high it won't start execution of the code, it won't blink.  If it’s started from pulled high, it will start code about 5s after power on. If it’s started pulled low code won’t execute until is pulled high. As I pull high, even just for a second, PIN2 it will start blinking and executing code.

Is it normal? I think I have missed something.

  [1]: https://github.com/micronucleus/micronucleus

body:
Well, I've made *some* headway.  I hope to update this with something more helpful though.

I don't have a digispark or even the correct Zener diodes to replicate the necessary parts of it.  However, I did install t85_default.hex on an ATTiny85 with some alterations to the hex file to place break instructions in a few strategic places.  And then I ran avarice/debugwire against it.

The basic problem is that it's trying to tune the internal oscillator against the USB frames by looking at the D- pin.  Basically, [it's stuck in `tuneOsccal`][1].

```None
988  00001d06 <tuneOsccal>:
   1     1d06:       b3 9b           sbis    0x16, 3 ; 22
   2     1d08:       fe cf           rjmp    .-4             ; 0x1d06 <tuneOsccal>
   3     1d0a:       07 d0           rcall   .+14            ; 0x1d1a <countFrame>
...
```

So if you want to [avoid this][2], you need to compile with that feature off, and [there is a feature to do that][3].

I have not yet run one with this feature disabled.  But I did compile t85_default once, using `make CONFIG=t85_default` and found it necessary to remove the `START_WITHOUT_PULLUP` from the [first line of the t85_default/bootloaderconfig.h file][4].

The code [mentions the existence][5] of `OSCCAL_SAVE_CALIB`, which lets you specify your own OSCCAL value, assuming the factory one for the chip isn't good enough for whatever reason.  But there doesn't seem to be any guidance on how you're supposed store it or where.  Looking at the code though, if enabled, you can see it [loads the OSCCAL value][6] from [just before][7] where the [bootloader starts][8].

A simple way to put it there without messing with command-lines and linker scripts would be to just edit the the t85_default.hex that results from building with `OSCCAL_SAVE_CALIB` enabled, and add an extra record for setting the osccal value at the correct address, which I guess would be 0x19FA, so:

:0119FA00**XX***SS*

Where **XX** is whatever you've determined your OSCCAL value is and *SS* is [the checksum value][9], or `0x100 - ((0x14 + XX) & 0xFF)` in this case.  Or, if you want to be lazy, put whatever you want for *SS* and let AVRDude complain tell you what it's supposed to be when it tries to load the .hex file.  It will report the expected value in decimal, which you can convert to hex and patch into the file, and run AVRDude again.

  [1]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/osccal.S#L47
  [2]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/main.c#L439
  [3]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/configuration/t85_default/bootloaderconfig.h#L246
  [4]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/configuration/t85_default/bootloaderconfig.h#L1
  [5]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/configuration/t85_default/bootloaderconfig.h#L239
  [6]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/main.c#L218
  [7]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/main.c#L50
  [8]: https://github.com/micronucleus/micronucleus/blob/v2.5/firmware/configuration/t85_default/Makefile.inc#L20
  [9]: https://en.wikipedia.org/wiki/Intel_HEX#Checksum_calculation


body: I had the same problem, I changed to firmware micronucleus-1.11-upgrade.hex (from 2.3 to 1.11) and it was solved, you can find ir here https://github.com/micronucleus/micronucleus/tree/v1.11/upgrade/releases


message:
Is there a working combination of Arduino IDE + Ardublock?

I'm trying to set up [Ardublock](https://sourceforge.net/projects/ardublock/), but the last release they have is from 2014 and in a recent Arduino IDE it fails when I try to upload the program to the Arduino board:

```
Exception in thread "AWT-EventQueue-0" java.lang.NoSuchMethodError: processing.app.Editor.setText(Ljava/lang/String;)V
 at com.ardublock.ArduBlockTool.didGenerate(ArduBlockTool.java:72)
   ....
```

I assume there is a different API in the recent Arduio IDE for copying the generated code into the editor. This is the block diagram I'm trying to upload. As you can see there are no libraries involved:

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

Is there a known combination of Arduino IDE and Ardublock which works? Or perhaps an addon similar to Ardublock which is maintained?

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

body: I found that Ardublock project was forked on [Github](https://github.com/taweili/ardublock/releases), and the latest release indeed works with up-to-date Arduino IDE.


message:
TimedAction.h: No such file or directory

I am new to Arduino and I am trying one of the library TimedAction.h for sudo multithreading on Arduino. However the library is not present in the Arduino. How do I install external library(if it is)?

body:
You can use three ways to install libraries in the Arduino IDE:

The probably easiest way is to go to **Sketch > Include Library > Manage Libraries**, (you can use *Ctrl+Shift+I* too) search for the library you want to install and click the install button. After that you need to include the library in your sketch with a `#include <LibraryName.h>`, or if you don't know the name, head again to **Sketch > Include Library** and click on the library you want to include.

If a library is not in the Library Manager from step one, you have to download the `.zip` file, go to **Sketch > Include Library > Add .ZIP Library** and search for the file. You just have to do that once, and it will be moved to your library folder. Again, make sure to include the library into the sketch.

If you just have a single file, you can move it to the sketch folder and include it by using `#include "LibraryName.h"`, but you have to do it all over again for a new sketch, so I would recommend the other solutions if you can and want to use it permanently.


message:
ESP32 Arduino Bluetooth Serial does not reconnect after disconnecting

The basic ESP32 Arduino Bluetooth Serial example pairs and connects as expected, BUT once I disconnect the Bluetooth terminal it stops responding to new events at all,

once I reset the esp32, it starts working again with the same problem. (it doesn't matter if it keeps being paired or not)

I have tested it with the windows Bluetooth terminal and with the Bluetooth Any terminal. (from the windows store)

I have downloaded the latest esp32-Arduino library from GitHub and I still get the same problem.

I have tested it with several esp32 modules, and they all respond with the same problem.

So it looks like a bug in the library code.

See the simple Arduino example code below:

```
#include "BluetoothSerial.h"

#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED) #error Bluetooth is not enabled! Please run make menuconfig to and enable it #endif

BluetoothSerial SerialBT;

void setup() { Serial.begin(115200); SerialBT.begin("ESP32test"); //Bluetooth device name Serial.println("The device started, now you can pair it with bluetooth!"); }

void loop() { if (Serial.available()) { SerialBT.write(Serial.read()); } if (SerialBT.available()) { Serial.write(SerialBT.read()); } delay(20); }

```

Does anyone know of another Bluetooth serial library that does work?

Thank You!

body:
Nothing wrong with your code, I've the exact same issue as you have. It bothers me whole week long and fortunately, we (along with my colleague) accidentally figured that was caused by Windows 10, weird right? We don't believe it at very beginning either, but after several back-N-forth testing, it just like that. When we upload exact same code from another older computer with Windows 7 OS, it just works no matter how many time we connect/disconnect or even "QUIT" the APP without make it disconnect properly, its been able to be reconnect no problem. But once we use new computer with Windows 10 OS to upload the code, it can only be connected for first time, then stop broadcasting (or advertising).
The arduino official website in IDE download page also has a notice message "IMPORTANT: This app performs with core functionality on Windows 10 S but some limited plugins do not work. We are working with Microsoft on a fix.", hope this information helps.


message:
Thermistor returns correct value on Arduino Nano, completely fails on Arduino Uno Wifi Rev 2?

I am completely baffled. When I wire the thermistor into my [Nano][1], everything reads completely fine. Then when I switch to the [Uno Wifi Rev 2][2], I get negative numbers -40 to -80 when I was reading 24 on the Nano.

Wiring Diagram is:

               Thermistor
               |       |
    Gnd---Resistor     Vcc
               |
           A6/A0 (6 for nano, 0 for Uno)

Code is:

    #include <thermistor.h>
    #define pin A6 //I change this to A0 on the WIfi. This is the only change
    float temp;
    uint32_t timeout = millis();
    THERMISTOR thermistor(pin, //Analog pin
                      9800,    //Nominal res at 25 ºC
                      3559,    //Thermistor's B value
                      10000);  //Value of the resistor
    void setup() {
      Serial.begin(9600);
    }

    void loop() {
      delay(1000);
      temp = thermistor.read();
      Serial.println(temp);
    }

  [1]: https://www.arduino.cc/en/pmwiki.php?n=Main/ArduinoBoardNano
  [2]: https://store.arduino.cc/usa/arduino-uno-wifi-rev2

body:
The Arduino UNO WiFi Rev2 defaults to an internal analog reference of 0.55V where the classic (non-"Every") Nano defaults to the external VCC voltage as a reference, which is usually around 5V, often a little lower because of the diode it uses between USB and "5V".

Either you need to be using the same voltage reference by selecting a common one with [analogReference][1], or you need to use different references and calculate differently (or provide different values to the thermistor library) according to each reference.

If you've been using the VCC on the normal Nano board, you could try `analogReference(VDD);` on the UNO Wifi Rev 2.  This isn't necessary a great way to do it (probably using internal references would be better), but it is a simple way to get similar results on a UNO Wifi Rev2 without changing more than a single line to set the reference.

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


message:
Using PWM pins on the UNO to generate Stereo Sound

I am trying to generate stereo sound using an Arduino UNO. Instead of using a separate DAC chip (as shown [here][1]), can I use the PWM pins on the UNO along with a low-pass filter?

Also, would I need any additional circuitry if I go this path?

  [1]: https://www.instructables.com/Stereo-Audio-with-Arduino/

body:
You can generate "stereo sound", but I don't think you'll like it.  The PWM frequency is only 490 or 980 Hz, which is going to be plainly audible unless you filter the output very severely.  So you'll only be able to produce low frequency sounds, about like what comes out of the woofer speakers in your home stereo.  In other words, nothing like music.  Might be OK for certain experiments, but nothing you'd want to listen to for pleasure.

As far as additional circuitry, you'll need to convert the DC outputs of your two low-pass filters to AC before you try to drive headphones.  This requires a big decoupling capacitor for each channel. If you are going to drive a separate amp, you might be able to skip the capacitors since most amps have them built into the inputs.


message:
Arduino H-bridge for rc car

I've got an old rc car laying around, of which i would like to swap the insides, but re-use some of the parts that are already in there. The car runs 2 dc motors: one for steering, one for throttle. The dc motors are both connected to H-bridges in the original setup to make their direction switchable. This is done via 8 transistors. 4 for the throttle and 4 for the steering.

The transistors for steering are 2x S8050 (NPN) and 2x S8550 (PNP).
For throttle it uses 2x 2SD882 (NPN) and 2x 2SB772 (PNP).

I found a schematic in an online post of a arduino H-Bridge setup. It look promising, but it uses 2n4403 and 2n4401 transistors. I was wondering if I could copy the schematic, replace the Arduino 5v power source (as depicted in de schematic) with the battery voltage source of the car, and replace the transistors in the schematic with one pair of the transistors I described above (so 2x 2SD882 and 2x 2SB772 or 2x S8050 and 2x S8550) Would the arduino be able to switch the described transistors? Would the 1K ohm resistors in between the arduino and the transistors suffice?

I am planning on making this schematic twice, once for throttle and once for steering. The throttle output is max 11.5v and the steering uses around 5v. Therefore the throttle circuit would be powered from the battery voltage and the steering circuit would be powered of a 5v regulator.

Can this be done this way?

[![The schematic I am talking about][1]][1]

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

body: Just a comment about your diagram. The two transistors should not share an Arduino pin in that way. If the pin is pulled high the transistors saturate and your current 'shoots through' from supply straight to ground. Instead assign one Arduino pin to each transistor (using the base resistor in your diagram).


message:
How do I add Gyroscope, Accelerometer, Euler, and Temperature data to one Arduino board?

I have to use a BNO055 to get temperature/accelerometer/Euler/Gyroscope data into one Arduino board for a school project. I am very new to coding so I am not familiar with the commands. I have gotten my BNO055 to give me all the data individually but I am having problems getting them all compiled into one code file to upload. I have googled it but I keep getting links to upload them individually. Posted below is my latest attempt.

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>

Adafruit_BNO055 bno = Adafruit_BNO055(55);

void setup(void)
{
  Serial.begin(9600);
  Serial.println("Orientation Sensor Test"); Serial.println("");

  /* Initialise the sensor */
  if (!bno.begin())
  {
    /* There was a problem detecting the BNO055 ... check your connections */
    Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
    while (1);
  }

  delay(1000);

  bno.setExtCrystalUse(true);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  /* Display the current temperature */
  int8_t temp = bno.getTemp();

  Serial.print("Current Temperature: ");
  Serial.print(temp);
  Serial.println(" Celsius");
  Serial.print("");
}

void loop(void)
{
  /* Get a new Sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(gyroscope.x());
  Serial.print(" Y: ");
  Serial.print(gyroscope.y());
  Serial.print(" Z: ");
  Serial.print(gyroscope.z());
  Serial.println("");
  delay(100);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> accelerometer = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(accelerometer.x());
  Serial.print(" Y: ");
  Serial.print(accelerometer.y());
  Serial.print(" Z: ");
  Serial.print(accelerometer.z());
  Serial.println("");
  delay(100);
}

void loop(void)
{
  /* Get a new sensor event */
  sensors_event_t event;
  bno.getEvent(&event);

  imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);

  /* Display the floating point data */
  Serial.print("X: ");
  Serial.print(euler.x());
  Serial.print(" Y: ");
  Serial.print(euler.y());
  Serial.print(" Z: ");
  Serial.print(euler.z());
  Serial.println("");
  delay(100);
}

body:
Does the code below work? I have no compiler at hand, so I can not test it.

If you have to explain what you have done, you'll get into trouble. I don't know your teacher, but ... ;-). Seriously, that was very basic stuff. Try to find some documentation, how to program with the Arduino IDE and learn the basics. A good startpoint is https://www.arduino.cc/en/Tutorial/HomePage .

Then go on with SENSORs and Vector Maths.

    #include <Wire.h>
    #include <Adafruit_Sensor.h>
    #include <Adafruit_BNO055.h>
    #include <utility/imumaths.h>

    Adafruit_BNO055 bno = Adafruit_BNO055(55);

    void setup(void)
    {
      Serial.begin(9600);
      Serial.println("Orientation Sensor Test"); Serial.println("");

      /* Initialise the sensor */
      if (!bno.begin())
      {
        /* There was a problem detecting the BNO055 ... check your connections */
        Serial.print("Ooops, no BNO055 detected ... Check your wiring or I2C ADDR!");
        while (1);
      }

      delay(1000);

      bno.setExtCrystalUse(true);
    }

    void loop(void)
    {
      /* Get a new sensor event */
      sensors_event_t event;
      bno.getEvent(&event);

      /* Display the current temperature */
      int8_t temp = bno.getTemp();

      Serial.print("Current Temperature: ");
      Serial.print(temp);
      Serial.println(" Celsius");
      Serial.print("");

      imu::Vector<3> gyroscope = bno.getVector(Adafruit_BNO055::VECTOR_GYROSCOPE);

      /* Display the floating point data */
      Serial.print("X: ");
      Serial.print(gyroscope.x());
      Serial.print(" Y: ");
      Serial.print(gyroscope.y());
      Serial.print(" Z: ");
      Serial.print(gyroscope.z());
      Serial.println("");
      delay(100);

      imu::Vector<3> accelerometer = bno.getVector(Adafruit_BNO055::VECTOR_ACCELEROMETER);

      /* Display the floating point data */
      Serial.print("X: ");
      Serial.print(accelerometer.x());
      Serial.print(" Y: ");
      Serial.print(accelerometer.y());
      Serial.print(" Z: ");
      Serial.print(accelerometer.z());
      Serial.println("");
      delay(100);

      imu::Vector<3> euler = bno.getVector(Adafruit_BNO055::VECTOR_EULER);

      /* Display the floating point data */
      Serial.print("X: ");
      Serial.print(euler.x());
      Serial.print(" Y: ");
      Serial.print(euler.y());
      Serial.print(" Z: ");
      Serial.print(euler.z());
      Serial.println("");
      delay(100);
    }


message:
What terminologies and concepts describe the codes that follow a format of Text1.Text2()?

I'm just really curious because some codes really follow a format like this. Examples include serial.begin(), serial.println() and when I used servomotors the left part was the name of the servomotor, which I declared. I want to know what concept does the code with a format of Text1.Text2() refer to? What do you call Text1 and Text2? Are there official or commonly used terminologies for the concepts and parts such as "variable", "statement", "code"?

To add to my understanding, it appears that Text1 refers to an object and that Text2 has the concept of "function" where it performs something related to the object. Though I would think that another terminology would be possessed by Text2 other than function to distinguish it from a function since it is required to be written in the format I mentioned, which next to the object with a period separating them and no spaces at all.

body:
The over-arching concept is *Object Oriented Programming* ([OOP](https://en.wikipedia.org/wiki/Object-oriented_programming)).

The terms I was taught at University - taking `Serial.println()` as an example:

* `Serial` is an *instance* of a *class* (in this case `HardwareSerial`), sometimes called an *object*.
* `println()` (a function in a class) is a *method* of a class.
* A "variable" in a class is called a *property* of a class.

A commented code example:

```c++

class Foo { // This is the *class*

    public: // These symbols are accessible from outside the class

        int bar; // This is a public property

        void baz() { // This is a public method
        }

    private: // These symbols are only available from inside the class

       int meep; // This is a private property

       void moop() { // this is a private method
       }
};

Foo bar; // Instantiate an instance of the Foo class and call it bar.
```


message:
Fast PWM with Arduino, the inputs outputs don't work

Hello to the community!

I am using ATTINY85 and I am programming it through the AVRISP using an Arduino UNO.

This is the code I am using :

```c++
#include <avr/io.h>
#include <avr/interrupt.h>

void setup() {
    PORTB = 0;        //Reset values on port B

    // After setting up the timer counter,
    // set the direction of the ports to output
    DDRB |= (1<<PB1) | (1<<PB0) | (1<<PB3); // PB0, PB1 and PB3

    // PLLCSR - PLL control and status register:
    // PLL is a clock multiplier
    //      - multiplies system 8 MHz by 8 to 64 MHz
    // PLL is enabled when:PLLE bit is enabled,
    // CKSEL fuse is programmed to 0001.  This clock is
    //   switched off in sleep modes!
    PLLCSR |= (1<<PLLE);    // PLL enable

    // Wait until the PLOCK bit is enabled
    // before allowing the PCK to be enabled
    //WaitForPLOCK();
    //unsigned int i = 0;

    while ((PLLCSR & (1<<PLOCK)) == 0x00)
    {
        // Do nothing until plock bit is set
    }

    // Enable asynchronous mode, sets PWM clock source
    PLLCSR |= (1<<PCKE);

    TCCR1 = (1<<CTC1)    | // Enable PWM
            (1<<PWM1A)   | // Set source to pck
            (0<<(CS13))  |
            (0<<(CS12))  |
            (1<<(CS11))  |
            (1<<(CS10))  | // Clear the pin when match with ocr1x
            (1<<COM1A1);
    GTCCR = (1<<PWM1B) | (1<<COM1B1);

    // Set PWM TOP value - counter will count and reset
    //  after reaching this value
    //           OCR1C
    // 100 kHz   159
    // 80 kHz    199
    OCR1C = 199;

    // Enable Timer1 OVF interrupt
    TIMSK = (1<<OCIE1A) | (1<<TOIE1);

    sei();

    OCR1A = 190;  //chaning th FR
}

void loop() {
    PORTB |= (1 << PB3);
    delay(500);
    PORTB &= ~(1 << PB3);
    delay(500);
}
```

the problem is that when I use the PWM my rest of the outputs do not work . Any idea why is this happening?

I am using the ATTINY CORE library from Spence Konde.

body:
This line:

```c++
TIMSK = (1<<OCIE1A) | (1<<TOIE1);
```

enables a couple of interrupts generated by Timer 1. Whenever you
enable an interrupt source, you should make sure that the matching ISR
has been defined. Otherwise, the interrupt request is routed to
`__bad_interrupt()`, which by default jumps to the reset vector, thus
resetting your program.


message:
How should I decide the cut-off frequency for my low-pass filter?

I'm trying to generate some basic thumping stereo sound using Arduino's PWM pins along with low-pass filters.

This is the frequency spectrum for the sound I want to play using Arduino UNO's PWM pins:

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

Based on this, I think (from what I understand) the cut-off frequency for the low-pass filter should be around 8900Hz. But, wouldn't the PWM function operate at a much higher frequency to generate the same wave? If that's how it'll be, how should I decide the cut-off frequency for my low-pass filter?

I understand that the fastest frequency one can get for 8-bit PWM on an UNO is 62.5 kHz. So, I might not be able to generate this wave using the UNO itself. Unfortunately, I won’t be able to use another microcontroller for this project. However, what I can do to solve this issue is - generate a different sound wave of lower frequency. If someone can help me with finding out by how much will the frequency of the wave increase if I use PWM to generate it, I’ll be able to generate an appropriate wave.

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

body: That looks like the spectrum of an 8-bit sound that is playing low bass notes only.  Most everything above that looks like noise floor.  (You can only get about 6 dB range per bit of resolution, so 8 bits gives about 48 dB max.)  If this is the case, you definitely don't want to reproduce the upper frequencies.  If you want to stick to your original PWM scheme, use pins 5 or 6 because they use 980 Hz PWM instead of 490.  I suggest you determine the filter by trial and error, since it comes down to how much PWM carrier you can tolerate.  You can make a simple RC filter using the formula F = 1 / (2 * pi * R * C) where F is the cutoff frequency in Hz, R is ohms, and C is farads (that's 10^6 microfarads per farad).  This type of simple filter will have a very soft cutoff frequency, about 6 dB per octave, so if you set it for 123 Hz (3 octaves below 980 Hz) the 980 Hz PWM will be reduced by 18 dB.  The R connects to the PWM pin, and the C goes from the other end of R to ground, as does the signal output.  The formula assumes that there is no output load, so you should connect an amplifier there.  If you are like most folks, you probably have fewer capacitor values on hand than resistor values, so pick the C value first.  Let's say it's 1 uFd.  Then if you use R=1K the cutoff will be 159 Hz.  Change R while listening to the output


message:
Using millis() instead of delay() when playing a melody

I want to make my Arduino to play several simple melodies, and also be able to skip a melody by pressing a button and go on with the next song. therefore I cannot use delay() because the code should constantly check if a button is pressed. So I wanted to use millis(), but dont't know how to implement it.

this is how song code looks like with delay():
```
#define NOTE_B0  31
#define NOTE_C1  33
#define NOTE_CS1 35
//etc...

int tempo=144;

// change this to whichever pin you want to use
int buzzer = 11;

int melody[] = {

  //Based on the arrangement at https://www.flutetunes.com/tunes.php?id=192

  NOTE_E5, 4,  NOTE_B4,8,  NOTE_C5,8,  NOTE_D5,4,  NOTE_C5,8,  NOTE_B4,8,
  // etc...

};

// sizeof gives the number of bytes, each int value is composed of two bytes (16 bits)
// there are two values per note (pitch and duration), so for each note there are four bytes
int notes=sizeof(melody)/sizeof(melody[0])/2;

// this calculates the duration of a whole note in ms (60s/tempo)*4 beats
int wholenote = (60000 * 4) / tempo;

int divider = 0, noteDuration = 0;

void setup() {
  // iterate over the notes of the melody.
  // Remember, the array is twice the number of notes (notes + durations)
  for (int thisNote = 0; thisNote < notes * 2; thisNote = thisNote + 2) {

    // calculates the duration of each note
    divider = melody[thisNote + 1];
    if (divider > 0) {
      // regular note, just proceed
      noteDuration = (wholenote) / divider;
    } else if (divider < 0) {
      // dotted notes are represented with negative durations!!
      noteDuration = (wholenote) / abs(divider);
      noteDuration *= 1.5; // increases the duration in half for dotted notes
    }

    // we only play the note for 90% of the duration, leaving 10% as a pause
    tone(buzzer, melody[thisNote], noteDuration*0.9);

    // Wait for the specief duration before playing the next note.
    delay(noteDuration);

    // stop the waveform generation before the next note.
    noTone(buzzer);
  }
}
```
I found this code on internet but I don't know how to implement this in above code. when I try to, I get some kind of cursed sound.
```
unsigned long previousMillis = 0;
boolean outputTone = false;

if (millis() - previousMillis >= noteDuration) {
    previousMillis = millis();
    if (outputTone) {
        noTone(buzzer);
  outputTone==false;
    } else {
        tone(buzzer, melody[thisNote], noteDuration*0.9);
        outputTone==true;
    }
}
```
edit1: I tried this:
```
    unsigned long previousMillis = millis();
    int thisNote = 0;

    while (thisNote < notes * 2) {

     // calculates the duration of each note
     divider = lied1[thisNote + 1];
     if (divider > 0) {
       // regular note, just proceed
       noteDuration = (wholenote) / divider;
      } else if (divider < 0) {
        // dotted notes are represented with negative durations!!
        noteDuration = (wholenote) / abs(divider);
       noteDuration *= 1.5; // increases the duration in half for dotted notes
     }

     // play the note
        tone(buzzer, melody[thisNote]);

        check();//check if button is pressed, and if so, changes number to 2
        if (number ==2){
         thisNote=notes*2;
        }
        if ((millis() - previousMillis) >= noteDuration){
           thisNote = thisNote + 2;
        // stop the waveform generation before the next note.
        noTone(buzzer);
        }

    }
```
but it doesn't work, and I don't really understand why

edit2: I changed something, this is probably the closest I have been to a working melody without "delay()". But it is extremely slow.
```
    boolean outputTone = false;
    unsigned long previousMillis = millis();
    int thisNote = 0;

    while (thisNote < notes * 2) {

     // calculates the duration of each note
     divider = lied1[thisNote + 1];
     if (divider > 0) {
       // regular note, just proceed
       noteDuration = (wholenote) / divider;
      } else if (divider < 0) {
        // dotted notes are represented with negative durations!!
        noteDuration = (wholenote) / abs(divider);
       noteDuration *= 1.5; // increases the duration in half for dotted notes
     }

       if (millis() - previousMillis >= noteDuration) {
       previousMillis = millis();
      if (outputTone) {
          noTone(buzzer);
          outputTone==false;
      } else {
          tone(buzzer, melody[thisNote], noteDuration*0.9);
          outputTone==true;
               thisNote = thisNote + 2;
      }
  }

        check(); //checks if button is pressed, and if so, changes number to 2.
        if (number ==2){
         thisNote=notes*2;
        }
    }
```

body:
In essence you will need to break your for loop open and use a global variable for thisNote, incrementing it each loop (with the millis example so that proper timing is still adhered to).

This isn't the only approach to this problem. Your existing code could check for the button press within the for loop and escape the for loop when pressed.


body:
I don't quite understand the code snippets, that you added to your question afterwards (they are partly incomplete). But I will propose my own solution to the problem.

A melody is a list of notes and pauses. Each note has a pitch and a duration. A pause has only a duration. We can now define a struct for holding a note:

    struct Note {
        unsigned int pitch;
        unsigned int duration;
    };

Since a pause does not have a pitch, we can use our struct for a note by setting the pitch to an invalid value (for example zero). For building a melody we are now  defining an array of `Note`s. But since we want multiple melodies, so that we can switch between them, we are using a 2 dimensional array for defining all melodies in one array:

    #define NR_MELODIES  2
    #define MELODY_LENGTH 8
    Note melody[NR_MELODIES][MELODY_LENGTH] = {
        { // melody 0
            {0      , 4}, //pause
            {NOTE_E5, 4},
            {NOTE_B4, 8},
            {NOTE_C5, 8},
            {NOTE_D5, 4},
            {NOTE_C5, 8},
            {0      , 8}, // pause
            {NOTE_B4, 8}
        },
        { // melody 1
            {0      , 4}, //pause
            {NOTE_B4, 8},
            {NOTE_C5, 8},
            {NOTE_D5, 8},
            {NOTE_C5, 4},
            {NOTE_B4, 8},
            {0      , 8}, // pause
            {NOTE_E5, 4}
        }
    };

Here I used the divider (part of the whole note), just like you did in your code. A `4` means a quarter note, `8` an eight note. For preventing loosing the first note, I inserted a quarter pause at the start.

We also need a variable to hold the current position in our melody, one for the current melody and a timestamp variable for the timestamp of the last played note:

    unsigned int current_note = 0;
    unsigned int current_melody = 0;
    unsigned long last_note_timestamp = 0;

Now in `void loop()` we check for our timestamp and the duration of the current note. If the current note should end, we end it, increment to the next note and start playing it:

    if(millis() - last_note_timestamp > wholenote/melody[current_melody][current_note].duration){
        last_note_timestamp += wholenote/melody[current_melody][current_note].duration; // increment timestamp to start of next note
        noTone(buzzer); // stop current note
        current_note++; // increment to next note
        if(melody[current_melody][current_note].pitch){ // next note is not a pause
            tone(buzzer, melody[current_melody][current_note].pitch, wholenote/melody[current_melody][current_note].duration); // start note
        }
    }

And after the if statement we can add an if statement for checking the melody change button. You didn't include the button check code in your question, so I will just use a placeholder function here.

    if(change_melody_pressed()){
        // incrementing current melody and wrap around, if we reached last melody
        current_melody = (current_melody + 1) % NR_MELODIES;
        // reset current note to play melody from start
        current_note = 0;
    }

Now we still need to think about, what happens, when a melody finishes. 3 possibilities:

- **We could restart the current melody:** We need to check for the last note in a melody, and then reset `current_note`:

        if(current_melody >= MELODY_LENGTH ){
            current_note = 0;
        }

- **We can increment to the next melody:** Like above, but we add the melody incrementing line in the if statement:

        current_melody = (current_melody + 1) % NR_MELODIES;

- **We can stop playing:** Here I would use the above if statement and set `current_note` to `-1`. Then we need to check in our first if statement, if `current_note` is not `-1`:

        if(current_note != -1 && millis() - last_note_timestamp > wholenote/melody[current_melody][current_note].duration)

Note: I have not tested the above code, but I compiled it to try finding syntax errors.


message:
What is the difference when an arduino has been unplugged vs when a serial port connection was closed?

Using python code for a serial port connection to an arduino, it sends a value to the arduino, which then starts printing values to serial. The python code will print the value on the first or second run (if run soon enough after), but after that it won't read what's from ```Serial.println``` again. To get it to read again (whether I wait some time or not, like for the while loop to finish), the arduino has to be unplugged and plugged in again, why is that different than the serial port connection being closed by python? Here is the arduino code used,

```
int measured;
int counter = 0;
int maxnum = 10;

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

void loop()
{
  if(Serial.available() > 0)
  {
    while(counter < maxnum)
    {

        Serial.println("V");
        counter++;
        delay(100);

    }
  }
}
```

I know the value sent from python can be read because I added in code that reads from serial after checking if it's available and changed an output pin value, which works, even if the serial println is not read.

Edit: Since the answer is there shouldn't be a significant difference and the arduino script should be reset if the serial port was closed, the issue should be with the python code.

body:
We cannot know, if your python code also has a problem. But your Arduino code will send the series of "V" only once.

You are using this while loop:

    while(counter < maxnum)

in there you are incrementing the variable `counter`. But after you left the while loop, you are never resetting `counter` to zero. So the next time, `counter` is still equal to `maxnum`. Thus the while loop will not run again. To solve that, insert

    counter = 0;

directly after your while loop. Though, for such loops its normally easier to just use a for loop.

---

Also you might have a second problem. Currently the code waits for Serial data to be received. When something is received, the code will enter the

    if(Serial.available() > 0)

statement. But this will stay true, unless you are actually reading the data. Currently the code inside the if statement will be executed on every `loop()` interation forever. So if you are applying the above fix to the first problem, the code will send "V" forever after you send the first byte to the Arduino. To actually only react to data being received, you need to read the data from the buffer - even if you are throwing the data away:

    Serial.read();

---

> What is the difference when an arduino has been unplugged vs when a serial port connection was closed?

For the Arduino itself? Nearly none. Reopening the serial connection will cause the Arduino to reset. The code then starts again from its beginning. Thats also what happens, when you power cycle (replugging) the Arduino. I think there are some little details, where both differ, but that certainly is not the problem here.

For the computer, replugging means, that the USB device (the USB-to-Serial chip on the Arduino to be precise) gets disconnected and again connected. That can lead to the OS allocating a different com-port/device-file for it, than before. Though that doesn't directly do something with the Arduino code (apart from the mentioned power cycle with reset).

For resetting (preserved from comment of OP):

> I found that by setting DTR to 0 then 1, then 0 again, right before closing the port, the arduino resets.


message:
Increase or decrease const byte value inside the code with a push button

I'm kind of new in the Arduino world. I decided to make a self learning project with an Arduino where it controls a conveyor that simply moves from right to left and back again. There is a start and stop button. On each end of the conveyor are inductive sensors to stop the motor when it reaches the end position. After a delay, the conveyer starts again the opposite direction. Inside the code I have a cycle counter that stops the conveyer after a certain number of cycles.
Now my question is, how could I change the value of the cycle counter using two push buttons. One to increase the other to decrease.

If there is somebody who could help I would appreciate.
Thanks already
```
const byte sensorLinksEnd  =  2;
const byte sensorRechtsEnd =  3;
const byte startPin        =  4;
const byte stopPin         =  5;
const byte relaisLinks     =  6;
const byte relaisRechts    =  7;

enum {relaisAn, relaisAus};
enum {warten, on, rechts, haltrechts, links, haltlinks, off};
byte schritt = warten;
byte zyklus = 20; //cycles
const byte maxzyklus = 20; //max cycles

void setup() {
  Serial.begin(115200);
  Serial.println(F("Start...."));
  pinMode(sensorLinksEnd, INPUT);
  pinMode(sensorRechtsEnd, INPUT);
  pinMode(startPin, INPUT);
  pinMode(stopPin,  INPUT);
  pinMode(relaisLinks, OUTPUT);
  digitalWrite(relaisLinks, relaisAus);
  pinMode(relaisRechts, OUTPUT);
  digitalWrite(relaisRechts, relaisAus);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);
}

void loop() {
  schrittkette();
}

void schrittkette()
{
  static unsigned long lastmillis;
  const unsigned long pauseZeit = 5000; // in ms
  if (digitalRead(stopPin))
  {
    schritt = off;
  }
  switch (schritt)
  {
    case warten:
      if (digitalRead(startPin))
      {
        zyklus = 0;
        schritt = on;
      }
      digitalWrite(relaisRechts, relaisAus);
      digitalWrite(relaisLinks, relaisAus);
      break;
    case on:
      digitalWrite(LED_BUILTIN, HIGH);
      schritt = rechts;
      break;
    case rechts:
      digitalWrite(relaisRechts, relaisAn);
      if (digitalRead(sensorRechtsEnd))
      {
        digitalWrite(relaisRechts, relaisAus);
        schritt = haltrechts;
        lastmillis = millis();
      }
      break;
    case haltrechts:
      digitalWrite(relaisRechts, relaisAus);
      digitalWrite(relaisLinks, relaisAus);
      if (millis() - lastmillis > pauseZeit)
      {
        schritt = links;
      }
      break;
    case links:
      digitalWrite(relaisRechts, relaisAus);
      digitalWrite(relaisLinks, relaisAn);
      if (digitalRead(sensorLinksEnd))
      {
        digitalWrite(relaisLinks, relaisAus);
        schritt = haltlinks;
        lastmillis = millis();
      }
      break;
    case haltlinks:
      digitalWrite(relaisRechts, relaisAus);
      digitalWrite(relaisLinks, relaisAus);
      if (millis() - lastmillis > pauseZeit)
      {
        if (zyklus == maxzyklus)
        {
          schritt = off;
        }
        else
        {
          zyklus++;
          schritt = rechts;
        }
      }
      break;
    case off:
      digitalWrite(LED_BUILTIN, LOW);
      schritt = warten;
      break;
  }
}
```

body:
The `const` keyword tells the C/C++ compiler that the variable is a constant and cannot be changed in your code anymore.

Simply remove `const` and you can modify `maxzyklus` by using 2 digital inputs.

    byte maxzyklus = 20; //max cycles


message:
Passing a method pointer

I created a small library, which takes a callback function:

    MyClass::add_callback(bool (*callback_function)(), byte behaviour) {
      // ...
      bool result = callback_function();
      // ...
    }

So far, I'm using it for periodic polling (for which I don't want to use ISR interrupts). However, I like to use it for other periodic calls that require a state. A simple example is a blinking light, which has an on-off state, as well as knowledge when the next state change needs to occur.

I like to change this method or add another method that takes a method, instead of a function. How should I do this? I'm struggling with the C basics, but answers on StackOverflow seem foccused to more modern C variants. For example, this [great answer on Stackoverflow](https://stackoverflow.com/a/402385/428542) recommends to use boost::bind, but I rather not include such a large dependency.

What I'm looking for is something akin to:

    MyClass::add_callback(void *obj, bool (*callback_method)(), byte behaviour) {
      // ...
      bool result = Object::callback_method(&obj);
      // ...
    }

where `Object::callback_method(&obj);` should be equivalent to `Object obj; bool result = obj.callback_method();`.

For bonus points, is it possible to make this independent on the Object class?

I'm happy for pointers to other sites (like StackOverflow), provided it is applicable to a bare Arduino program.

body:
The easiest method I know to do this would be to use a "C"-style wrapper for the member function call. This is in fact done to interface C callbacks with C++ objects.

You could do it like this:

    struct Blinky {
      //state etc.
      bool isOn() { return /* something useful */ true; }
    };

    // The "C" wrapper for the callback
    bool Blinky_callback(void *vblinky)
    {
      return static_cast<Blinky*>(vblinky)->isOn();
    }

    struct MyClass {
      void add_callback(void *obj, bool (*callback_method)(void *), byte behaviour) {
        // ...
        bool result = callback_method(obj);
        // ...
      }
    };

    // Globals
    MyClass c;
    Blinky b;

    void setup() {
      c.add_callback(&b, Blinky_callback, 0);
    }

A slightly tidier way with a static member (functionally identical):

    struct Blinky {
      //state etc.
      bool isOn() { return /* something useful */ true; }

      static bool callback(void *vblinky) {
        return static_cast<Blinky*>(vblinky)->isOn();
      }
    };

    // ...
    c.add_callback(&b, Blinky::callback, 0);

Other variants would be using inheritance and virtual functions.

    // Abstract base class
    struct Sensor {
      virtual bool do_check() = 0;
    };

    struct Blinky : public Sensor {
      bool do_check() override { return true; }
    }

Then you can have your `add_callback` look like:

    void MyClass::add_sensor(Sensor *sensor) {
      // ...
      bool result = sensor->do_check();
      // ...
    }

This is relatively nice to code with, and the compiler has a fighting chance at keeping your code typesafe, if all the "things" you want to control can conform to the same interface. The virtual dispatch won't cost much more (if anything) than the static wrapper in the previous example. You "pay" a few bytes per class and one pointer per instance for the virtual table though.

More modern techniques would involve templates and/or lambdas, or perhaps `std::function`, but all that seems overkill if your need is as described (and might generate a lot more code than you're expecting, or do dynamic allocations for `std::function` which is best avoided in context).

---

Remark: if you want to do it with (non-static) member function pointers, it is possible but the syntax is hairy:

    void add_callback(Blinky *obj, bool (Blinky::*callback_method)(), byte behaviour) {
      // ...
      bool result = (obj->*callback_method)();
      // ...
    }

And you're tied to that class. Unless you make `add_callback` a template, but beware extra codegen.


message:
How to convert kitchen timer code into a countdown

I found this code for a kitchen timer, it was the closest thing to a countdown. The code is here:

```

#include <LiquidCrystal.h>

const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);

signed short minutes, secondes;
char timeline[16];

void setup() {

  lcd.begin(16, 2);
  lcd.print("Chronometre :");

}

void loop() {

  lcd.setCursor(0, 1);
  sprintf(timeline,"%0.2d mins %0.2d secs", minutes, secondes);
  lcd.print(timeline);

  delay(1000);
  secondes++;

  if (secondes == 60)
  {
    secondes = 0;
    minutes ++;
  }

}

```

How do I convert it properly for it to countdown from 1 minute and 30 seconds?

body:
As a start, you need to initalise the `secondes` and `minutes` variables to 30 and 1 respectively.

replace `signed short minutes, secondes;` with:

    signed short minutes = 1;
    signed short secondes = 30;

Next thing I notice is that the code you have provided counts up and you have requested that it count down.

Change `secondes++;` and `minutes++;` with:

    secondes--;
    minutes--;

Lastly you need to change the logic for when the `secondes` and `minutes` variables reach zero.

If the `secondes` variable reaches zero but the `minutes` variable is greater than zero, then you decrement the minutes (using the line of code provided above) and top-up the `secondes` with 59.

    secondes = 59;

You will need to check the value of the `secondes` and `minutes` variables using a couple of [if][1]...[else][2] statements.

    if (secondes == 0 && minutes == 0) {
        // insert your timer finished code here
    }
    else if ( secondes == 0 && minutes > 0) {
        minutes--;
        secondes = 59;
    }
    else {
        // Error - your code should not reach here.
        // Display an error message on the LCD
    }

This if..else statement will need to go at the top of your loop instead of the end.

  [1]: https://www.arduino.cc/reference/en/language/structure/control-structure/if/
  [2]: https://www.arduino.cc/reference/en/language/structure/control-structure/else/


body:
The first thing I recommend is that you don't use sprintf(). Your sketch "program storage space" drops from 3502 bytes down to 1928 bytes by NOT using that function call, and dynamic memory used drops from 101 to 79 bytes.

I would recommend an OOP design that would make it easy to add functionality, like the ability to start, stop and reset the timer.

```
// Arduino Uno, IDE version 1.8.9
// 2330 bytes (7%) of program storage space.
// Global variables use 201 bytes (9%) of dynamic memory.
class CountdownTimer{

  private:

    byte m_hour;
    byte m_minute;
    byte m_second;
    byte m_timerActive;
    byte m_timerComplete;
    unsigned long m_previousMillis;

  public:

    CountdownTimer():
      m_hour(0),
      m_minute(0),
      m_second(0),
      m_timerActive(0),
      m_timerComplete(0),
      m_previousMillis(0){}

    bool Update(){

      if(m_hour == 0 && m_minute == 0 && m_second == 0){
        m_timerComplete = 1;
        return 0;
      }

      if(m_timerActive && (millis() - m_previousMillis >= 1000)){
        m_previousMillis += 1000;
        m_second--;
        if(m_second == 255){
          m_second = 59;
          m_minute--;
          if(m_minute == 255){
            m_minute = 59;
            m_hour--;
            if(m_hour == 255){
              m_hour = 0;
            }
          }
        }
        return 1;
      }
      else{
        return 0;
      }
    }

    byte GetIsTimerComplete(){
      return m_timerComplete;
    }

    void SetHour(byte hour){
      m_hour = constrain(hour, 0, 23);
    }

    void SetMinute(byte minute){
      m_minute = constrain(minute, 0, 59);
    }

    void SetSecond(byte second){
      m_second = constrain(second, 0, 59);
    }

    void Start(){
      m_timerActive = 1;
    }

    void Stop(){
      m_timerActive = 0;
    }

    void ReStart(){
      m_timerActive = 1;
      m_timerComplete = 0;
      m_previousMillis = millis();
    }

    void PrintTimeRemaining(){
      if(m_hour < 10){Serial.print("0");}
      Serial.print(m_hour);
      Serial.print(":");
      if(m_minute < 10){Serial.print("0");}
      Serial.print(m_minute);
      Serial.print(":");
      if(m_second < 10){Serial.print("0");}
      Serial.println(m_second);
    }

};

// Make a copy of the object to work with.
CountdownTimer myCountdownTimer;

void setup(){

  // Built in pin 13 LED timer completed indicator.
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, LOW);

  // Test output to the serial monitor.
  Serial.begin(9600);

  // Set the countdown timer values,
  // start the countdown timer and
  // print the initial timer setting.
  myCountdownTimer.SetHour(0);
  myCountdownTimer.SetMinute(1);
  myCountdownTimer.SetSecond(30);
  myCountdownTimer.Start();
  myCountdownTimer.PrintTimeRemaining();
}

void loop(){

  // Call the Update function as fast as possible.
  if(myCountdownTimer.Update()){
    myCountdownTimer.PrintTimeRemaining();
  }

  // Turn on the Uno's Pin 13 LED once timer is complete.
  if(myCountdownTimer.GetIsTimerComplete()){
    digitalWrite(LED_BUILTIN, HIGH);
  }

}
```


message:
Current difference between pinMode(pin, INPUT_PULLUP) and digitalWrite(pin, HIGH)?

Does pin 5 or pin 6 use more power if they're just being used as a signal to an external device?

    pinMode(5, INPUT_PULLUP);

    pinMode(6, OUTPUT);
    digitalWrite(6, HIGH);

.

EDIT:  Thanks to some links below, I hopped thru a series of threads until I found the website [www.gammon.com.au/power][1] which did tests with a 328 and found the following results with the pins disconnected (which is different than my question but seems relevant nonetheless):

In SLEEP_MODE_PWR_DOWN:
- All pins as outputs, and LOW: 0.35 µA.
- All pins as outputs, and HIGH: 1.86 µA.
- All pins as inputs, and LOW (in other words, internal pull-ups disabled): 0.35 µA (same as before).
- All pins as inputs, and HIGH (in other words, internal pull-ups enabled): 1.25 µA.

  [1]: http://www.gammon.com.au/power

body:
It all depends on the external device. If it has high-impedance inputs,
then it makes no difference. The Arduino itself has high-impedance on
its pins configured as `INPUT`. If the device draws current from this
signal, then chances are it will draw more current from an `OUTOUT`
`HIGH` than from an `INPUT_PULLUP`. How much more? We cannot say without
knowing the specifics of that device.

If you model the device as a simple resistor to ground (which is almost
certainly _overly_ naive), then the current draw is

I = VCC / (R + Ro)

where R is the value of the resistor and Ro the output
resistance of the Arduino: about 25 Ω for an `OUTPUT` and
32 kΩ for an `INPUT_PULLUP`.


message:
What is happening when digitalWrite(pinname, LOW) is invoked after pinMode(pinname, INPUT_PULLUP)?

I read the Arduino official docs on digitalWrite and am confused about what is happening from an electrical perspective when digitalWrite is invoked on INPUT_PULLUP pins.

Say my code says this:

    pinMode(4, INPUT_PULLUP);
    digitalWrite(4, LOW);

The docs say:

> If the pin is configured as an INPUT, digitalWrite() will enable
> (HIGH) or disable (LOW) the internal pullup on the input pin. It is
> recommended to set the pinMode() to INPUT_PULLUP to enable the
> internal pull-up resistor. See the Digital Pins tutorial for more
> information.

Does this mean pin 4 is floating or is it at ground?  Are those two lines of code equivalent to `pinMode(4, OUTPUT); digitalWrite(LOW);`  ?

body:
It's pretty explicitly stated there in your quote: if you write a LOW when in INPUT mode it disables the pullup resistor. That's all it does.

```c++
pinMode(4, INPUT);
digitalWrite(4, HIGH);
```

is exactly the same as:

```c++
pinMode(4, INPUT_PULLUP);
```

And

```c++
pinMode(4, INPUT_PULLUP);
digitalWrite(4, LOW);
```

is exactly the same as

```
pinMode(4, INPUT);
```

Of course this exploits a peculiarity of the AVR's IO block, but any decent core will emulate that functionality for compatibility with older code.


message:
Set interrupts that are not GPIO or Timer in ESP32

I am making a project on ESP32. It reads certain sensor values, stores them in RTC memory and sends them by MQTT after a certain time. I wish that it transmits data immediately if there is a difference of, say 10 units, via an interrupt. I suppose this is not possible by GPIO interrupts and obviously not by a timer as I wish it to happen only if a condition is true and not periodically.
I searched on the internet but couldn't find anything except GPIO and Timer interrupts.

**I am working on Arduino IDE.**

Is what I want possible and if yes, how. Please also give a certain example that is in Arduino language for me to study. Also, if it is possible using GPIO interrupts, please tell me how.

Thank you in advance

body:
There is no such thing as an "interrupt on a value changing" since that is something that only exists in software, and interrupts are things triggered by hardware.

All you can do is check the value in `loop()` and send the data if the value is above your threshold. If you want to wake from sleep then you will have to do that periodically through other means.


message:
Buzzer+Push button+arduino

I want to stop the sound of a buzzer after I push the push button. I tried a code, but when the button is not pushed, the buzzer continue to make sound. How can I fixed it?

```c++
const int pin_contact= 6;
const int buzzer = 9; //buzzer to arduino pin 9

void setup(){
  pinMode(buzzer, OUTPUT); // Set buzzer - pin 9 as an output
  pinMode(pin_contact, INPUT);
  Serial.begin(9600);
}

void loop() {
  tone(buzzer, 200);

  int stare_contact = digitalRead(pin_contact);
  if (stare_contact == HIGH) {
    noTone(buzzer);
  }
}
```

body:
Try this

    int LEDState = 1;
    int SwitchPin = 6;
    int LEDPIN = 9;

    void setup()
    {
      pinMode(LEDPIN,OUTPUT);
      pinMode(SwitchPin,INPUT);
      digitalWrite(LEDPIN,LEDState);
    }

    void loop()
    {

      int SwitchState = digitalRead(SwitchPin);

      if(LEDState==1 && SwitchState==HIGH){
       LEDState = 0;
      }

      digitalWrite(LEDPIN,LEDState);
        delay(10);
    }


body:
Is your buzzer active low? try this code below.
it will toggle buzzer pin output.

    const int buzzerPin = 9;
    const int buttonPin = 6;
    int buzzerState = 1;
    int buttonState;
    int buttonTemp = 0;

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

    void loop() {
      buttonState = digitalRead(buttonPin);
      digitalWrite(buzzerPin,buzzerState);
      if (buttonState == HIGH && buttonTemp == 0){
        Serial.print("Buzzer toggle to : ");
        if (buzzerState) {
            Serial.println("LOW");
            buzzerState = 0;
        } else {
            Serial.println("HIGH");
            buzzerState = 1;
        }
        buttonTemp = 1;
      } else if (buttonState == LOW) {
        buttonTemp = 0;
      }
    }


message:
[SOLVED]SIM7600 Module Power up by Arduino Uno doesn't work

Am using SIM7600X 4G HAT with Arduino Uno

I follow to manual to Power up the module and it works well, The NET light flashing.
[![enter image description here][1]][1]

But when I connect to Arduino Uno and use DigitalPin 2 write (High -> Delay500ms -> Low) for "power on pulse" it doesn't work, The NET light still not flashing.
[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/LfO3O.png
  [2]: https://i.stack.imgur.com/GmI5L.jpg
My code:

    #include <Waveshare_SIM7600.h>
    // Pin definition
    int POWERKEY = 2;

    char phone_number[] = "XXX";      //Store the phone number you want to call

    void setup() {
      Serial.begin(9600);
      sim7600.PowerOn(POWERKEY);
      sim7600.PhoneCall(phone_number);
    }

    void loop() {

    }

code from Waveshare (Waveshare_SIM7600.h):

 /**************************Power on Sim7x00**************************/
 void Sim7x00::PowerOn(int PowerKey = powerkey){
    uint8_t answer = 0;

   Serial.begin(9600);

   // checks if the module is started
   answer = sendATcommand("AT", "OK", 2000);
   if (answer == 0)
   {
     Serial.print("Starting up...\n");

     pinMode(PowerKey, OUTPUT);
     // power on pulse
     digitalWrite(PowerKey, HIGH);
     delay(500);
     digitalWrite(PowerKey, LOW);

        // Stuck in below loop because Send AT command and no response ///////
        // Becuase NET light not flashing (not connect) //////////////////////

     // waits for an answer from the module
     while (answer == 0) {     // Send AT every two seconds and wait for the answer
       answer = sendATcommand("AT", "OK", 2000);
    delay(1000);
     }

   }

   delay(5000);

   while ((sendATcommand("AT+CREG?", "+CREG: 0,1", 500) || sendATcommand("AT+CREG?", "+CREG: 0,5", 500)) == 0)
     delay(500);
 }

body: The GSM module requires a 5V 2A source and my Arduino Uno cant draw for it, my solution is to use a power bank that can draw 5V 2A for powering the GSM module and jump PWR pin to GND (manual said) the NET led start flashing and module can working but TX, RX pin still there for comm.


message:
Atmega 328p at 3.3v : Internal vs external oscillator

I am currently working on a pcb that uses smd atmega 328p (au).
I will be powering it through a lipo battery and a ldo regulator for 3.3v input. I am using the multiwii flight controller code.
I know that atmega runs at 8mhz at 3.3v and 16mhz at 5v without overclocking the chip.
The question is that should I use the internal 8mhz oscillator or external 8mhz?
I will definitely make the chip more accurate as given in some forums but still does this effects anything or not?

body:
If the 8 MHz oscillator is off by a handful of percentage points, it will affect timing measurements you make using millis() and micros(). It could affect the baud-rates of Serial or SoftwareSerial. If these are not of any concern, the only remaining difference would be how fast your code can be executed. It's unlikely that the code pushes the chip runs so close to its maximum capability that it would matter, even at ~8 MHz.

Update:

> ... I just want to know if clock frequency effects the code and if I need
> to change code a bit like for example blink sketch runs at different
> time intervals on 8mhz and 16mhz(I tested it).

If you do nothing else, then yes, millis() will appear to run at half speed. You need to add a board definition to the IDE for an Arduino Uno running at 8 MHz. Then millis() and micros will be adjusted for the slower processor clock. How you do this depends on whether you choose the internal and less accurate 8 Mhz oscillator, or an external 16 MHz crystal.

For the internal oscillator, there is a [board-definition on Github][1] with instructions to load it into your IDE.

For an external oscillator, this article describes how to select the board type as "Arduino Pro or Pro Mini" and then be able to select the board frequency, using the Tools menu twice.

  [1]: https://github.com/joranvg/arduino-atmega328p-a


message:
Any way a GSM sim 900 can still work (USA)?

so I’m pretty new to arduino and have been working for weeks on a GPS tracker using a sim 900 and a knock off neo 6M. All my code seemed to be working but for some reason I could not get the sim900 to establish a connection. Took me long enough to find out 2G carriers have been pretty much shut down. This is for a project and I don’t have time to start over with a 4G shield. Are there any cell carriers that still support 2G? What are my options? I don’t know what to do

Edit: more detail, I’m using the sim 900 to send an sms with a gps location

body: Somehow I got a connection! I live in PA but when I went to Boston for school I got 2G service. Maybe carriers haven’t fully shut it down.


message:
How to receive commands to a running arduino program from a raspberry pi?

I have looked all over for a solution to this. I'm a noob in the arduino space and am really just getting my feet wet. It's possible that I am interpreting what I am reading wrongly. If so I apologize. Here is my problem/question. I want to create an autonomous driving small land drone. It would connect to some drive sensors, dc motors and do some stuff all by itself. In addition to this I want a raspberry pi with a camera surveying the scenery. Because it is unknown if/when the raspberry PI will see something that is interesting i want this default behavior to occur. The reason I want to do it like this is that I read it is better performance to drive from the Arduino because a linux based computer has so much stuff running on it there could be more lag in the response. In addition the python program will be making HTTP requests, doing image processing, and potentially doing even more. If the image processing software on the PI picks up something interesting then I want this functionality to override the Arduino default program. I was thinking to create a program in Arduino for the basic drive functionality but then be listening to a python process that is running on the PI. If it hears a command to go do something, then of course it will drop the default program, go complete the python generated task and once it is done then it will continue with the arduino default program.

How do I in effect listen to a python process from the Arduino? Or would the proper solution be to not even use the Arduino but drive it all from python on the PI? Any suggestions for how to solve this would be great to hear. I feel like there is an obvious best practice way to do this that I am not aware of. Thanks in advance!

body:
What you are asking for is not completely trivial, and may be ill-suited
for a beginner's project. You will have to create a protocol for the
communication between the Raspberry Pi and the Arduino (your own
“command language” of sorts), and then implement on the Arduino a
command interpreter that understands this protocol and acts accordingly.
I highly recommend you use a text-based protocol, as this will be way
easier to debug than a binary protocol.

For the Arduino side of the project, you first have to learn how to
[read the serial port from the Arduino][serial]. Then, you can take a
look at this very basic [command line interpreter][interpreter] for
inspiration. Or you can search for Arduino libraries that provide
similar interpreters.

On the Python side, you have to open the serial port (`/dev/ttyACM0`)
and send your commands through it. The details on how to do that
would be a Python question, which is are out of scope here.

[serial]: https://majenko.co.uk/blog/reading-serial-arduino
[interpreter]: https://gist.github.com/edgar-bonet/607b387260388be77e96


message:
How to print something when a character touches a character

I am making a stickman rush game, where it goes up and down and then there is a object that scrolls to the left. Whenever that stickman touches the object, it prints game over. However when the object is below the stickman, it prints game over even though its not touching. Can someone explain why this is happening?

Code:

```
#include <LiquidCrystal.h>

LiquidCrystal lcd(2, 3, 4, 5, 6, 7);

byte customChar[] = {
  B01110,
  B01110,
  B01110,
  B00100,
  B01110,
  B10101,
  B00100,
  B01010
};

byte gameObstical[] = {
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111,
  B11111
};

int vX = A0;
int vY = A1;
int sw = 8;

int xPosition = 0;
int yPosition = 0;
int SW_state = 0;
int mapX = 0;
int mapY = 0;

int screenWidth = 16;
int screenHeight = 2;

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

  pinMode(vX, INPUT);
  pinMode(vY, INPUT);
  pinMode(sw, INPUT);

   lcd.begin(16, 2);
  lcd.createChar(0, customChar);
  lcd.home();
  lcd.write(byte(0));

  lcd.createChar(1, gameObstical);
  lcd.write(byte(1));

}

void loop() {

  int stickManPosition = 0;
  int obsticalPosition = 0;
  int stickManPosition2 = 0;
  int obsticalPosition2 = 0;

  for (obsticalPosition = 15; obsticalPosition >= 0; obsticalPosition--) {
  lcd.setCursor(obsticalPosition, 1);
  lcd.write(byte(1));
  lcd.print(" ");
  delay(150);

  xPosition = analogRead(vX);
  yPosition = analogRead(vY);
  SW_state = digitalRead(sw);
  mapX = map(xPosition, 20, 1003, -500, 500);

    Serial.println("-----------");
  Serial.println(mapX);
  Serial.println("-----------");

    if (mapX > 200) {

    lcd.clear();
    lcd.setCursor(stickManPosition, 0);
    lcd.write(byte(0));

  } else if (mapX < -200) {

    lcd.clear();
    lcd.setCursor(stickManPosition, 1);
    lcd.write(byte(0));
    }

  if (stickManPosition == obsticalPosition) {
    lcd.clear();
    lcd.print("Game Over.");
      } else if (
    }
  }
```

Any help would be great.

body:
You check StickMan and Object only X position not check Y position
incase you can check StickMan Y or check StickMan action like this code below.
or try this sim https://www.tinkercad.com/things/1LiyoY5n1mS-copy-of-stickman-rush/editel?sharecode=X6rMj1GjrKoAH95qWKY21z98ttyAs5aOTAKYy6hVJ3c

    // Defind it on top
    bool stickManIsJump = false;

    // Added some code to check StickMan isJump or not
 if (mapX > 200) {
      lcd.clear();
      lcd.setCursor(stickManPosition, 0);
      stickManIsJump = true;  /////////////// ADDED
      lcd.write(byte(0));
    } else if (mapX < -200) {
      lcd.clear();
      lcd.setCursor(stickManPosition, 1);
      stickManIsJump = false;  /////////////// ADDED
      lcd.write(byte(0));
    }

    if (stickManPosition == obsticalPosition && !stickManIsJump) {   /////////////// ADDED
      lcd.clear();
      lcd.print("Game Over.");
    }

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

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


message:
[SOLVED]how to send command to Gsm module from Arduino via serial port

Am using SIM7600X 4G HAT module (GSM) and Arduino Uno
after I start the module and Arduino, I receive data from Gsm module but I can't send any command to it.
On my Arduino board when I get data RX led flashing, and when I send command TX led flashing.

    #include <SoftwareSerial.h>
    SoftwareSerial myserial(3, 4); // gsm_TX, gsm_RX

    void setup(){
      myserial.begin(9600); //Initialize GSM serial port
      Serial.begin(9600); //Initialize Arduino default serial port
    }

    void loop(){
      while(1){
        while (myserial.available()) {
          //Serial received data, output via mySerial.
          Serial.write(myserial.read());
        }
        while(Serial.available()) {
          //myserial received data, output it via Serial.
          myserial.write(Serial.read());
        }
      }
    }

As the picture I send "AT" command or any command it no response.
it show only module start up command.
[![enter image description here][1]][1]

My circuit

[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/o1F8y.png
  [2]: https://i.stack.imgur.com/PDMC6.jpg

body: I solved my problem, On my circuit GSM module use an external source and my Arduino Uno use serial port source, So it cant communicate via pin because both ground of them did not connect to each other then the answer is connected GSM module GND to Arduino Uno GND.


message:
How to improve the sampling rate of Arduino due ADC?

I am now working on a project, which needs a cheap analog acquisition device with a sampling rate of no less than 5MHz. Before, I only used Arduino, and rarely operated the registers on Arduino. I hope to use Arduino due to complete it. I spent a lot of time researching and querying solutions, but it didn't succeed. I hope someone can help me.

body:
I haven't used the Due, but I understand its ADC is rated for 1 MHz sampling.  If that's its absolute limit then you can't expect 5 MHz.  However, judging by the Unos which I have used, you may be able to push things by limiting the number of bits.  This gives a speed boost two ways, by shortening the time the ADC uses to acquire the data, and if you limit to 8 bits you have half as many bytes to move into memory.

Do *not* try to use more than one channel, since then you have multiplexer delays as well.

Also, you may want to skip interrupts and just sample in a tight loop. Using this loop trick doubles the useful ADC rate of the Uno, from 50 kHz to over 100 kHz. (You'll need to figure out the actual sample rate by reading the timer before and after the loop, then divide by the loop size and take the reciprocal.)


message:
AVRdude does not read the FUSE byte values correctly

I am exploring the ATmega328p MCU via a standard Arduino UNO, with the help of avr-gcc toolchain and AVRdude (All in the WINAVR package). I have successfully programmed the board a few times with it. However, when I try to read the fuse values via AVRdude, I get `0x0` for `lfuse`, `hfuse` and `efuse`.

I am using the following command (or its variants) to read:

```avrdude -c arduino -p ATMEGA328p -P com3 -b 115200 -v -F -U hfuse:r:hi_fuse_val.hex:h```

Following is the output I get:
```
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0
avrdude.exe: safemode: lfuse reads as 0
avrdude.exe: safemode: hfuse reads as 0
avrdude.exe: safemode: efuse reads as 0
```
The file `hi_fuse_val.hex` also has `0` written to it.
What am I doing wrong?

body:
A couple of things.  That you can't change fuses from the bootloader and that optiboot can't report fuse values correctly, even if you change them.

No self-programming of fuses
----------------------------

A bootloader can't write fuses, at all.  The chip just doesn't allow self-programming of fuses.  If you want to change fuses, you'd need to resort to external programming (usually using the ISP protocol) with an AVR programmer (or another Arduino [set up to behave as one][1]).

Optiboot and reading fuses
--------------------------

Optiboot doesn't report fuses, at least not as compiled for UNO.

The "arduino" bootloader protocol used by the avrdude `-c arduino` option is a modified version of the [STK500(v1) protocol][2].  The are two commands there that would need to be implemented to read fuses, `Cmnd_STK_READ_FUSE` and `Cmnd_STK_READ_FUSE_EXT`.  They have [corresponding][3] [definitions][4] in the AVR Arduino core's copy of optiboot source.  But the places where they would be implemented in the series of `if`-`else`s [are absent][5].  Unlike writing fuses, reading fuses *is* possible from AVR code.  So it's not a limitation of the chip, the code to do it just isn't there.

Sidenote: You may notice that there are also definitions for commands that write FUSES.  These exist for STK500v1 programmers rather than bootloaders, which can implement these to support writing fuses.

For what it's worth optiboot doesn't actually read the signature of the chip either.  It just reports whatever values have been baked in [at compile time][6].  Both this and the not-reading-fuses above are probably done to keep optiboot as small as possible, which is its goal.

In any case, if you *do* change your fuses using a programmer, expect optiboot to continue reporting them as zero.

Current fuse values
-------------------

If you're curious about your actual fuses values, you run sketch that [reads them][7] and prints them over serial by using `#include <avr/boot.h>` and

```c++
Serial.print('E');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_EXTENDED_FUSE_BITS), HEX);

Serial.print('H');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_HIGH_FUSE_BITS), HEX);

Serial.print('L');
Serial.print(':');
Serial.println(boot_lock_fuse_bits_get(GET_LOW_FUSE_BITS), HEX);
```

  [1]: https://www.arduino.cc/en/Tutorial/BuiltInExamples/ArduinoISP
  [2]: http://ww1.microchip.com/downloads/en/Appnotes/doc2525.pdf
  [3]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/bootloaders/optiboot/stk500.h#L33
  [4]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/bootloaders/optiboot/stk500.h#L38
  [5]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/bootloaders/optiboot/optiboot.c#L331
  [6]: https://github.com/arduino/ArduinoCore-avr/blob/1.8.3/bootloaders/optiboot/optiboot.c#L486
  [7]: https://www.nongnu.org/avr-libc/user-manual/group__avr__boot.html#ga37ce7078335dd85f04d150a52a01d6ad


message:
How can I share one power supply between an arduino and servos?

I'm trying to power an arduino and a few modules (RF receiver, two servos, and a laser diode) through one power supply.

I get jittery/unresponsive servos when hooked up in the following configuration:
* power supply goes to usb breakout, joins with top + and - rails, powers everything (tried
* all grounds go to top - rail
* black/grey/white wires going off right side are power/ground for the servos
* red, green, yellow wires going off left/top side are signals to the servos/laser
* purple wire going off left/top is ground for the laser

[![circuit photo][1]][1]

If I remove the orange wire (usb breakout to + rail) and plug another power supply into the Arduino, the poor performance disappears and everything works nicely.

Since my power supply is 2.5A, I doubt that I don't have enough power for this setup. This leads me to believe that the Arduino/receiver side of the circuit is making the voltage unstable so the servos misbehave. Is there a way I can isolate these two parts of the circuit (diode, capacitor?) so that I can power the whole setup with one cable?

Components:
* Arduino pro micro (5v)
* RF Link Receiver (WRL-10532, 434 MHz)
* Servo (ROB-09065, sub-micro)
* Laser diode (5V, 20mA)
* Micro USB breakout (1A)
* USB Micro power supply (5.1V, 2.5A)

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

body:
You need to figure out your total current requirements. Don't guess, figure it out. What is the peak current draw of the servos? of the other components? Add everything up. If the total is within 20% of your power supply current, that may be the problem.

Also, servos tend to draw spikes of current. You might need to add a filter capacitor to the +5V rail on the Arduino to even out dips as the servos cause sags in current before the voltage regulator in your power supply can compensate. (Put the cap between +5V and ground right at the Arduino.)


body:
I too have found the servo driving of the Arduino ie UNO to be jittery. The problem is that the Arduino uses a timer, interrupts and software to terminate the pulse so if the processor is busy servicing another interrupt then the pulse gets extended by up to 10us. Modern servos, even the cheap ones, respond to this delay as if it were noise.

The servo library was dependent on clock frequency, and limited to pins 9 & 10, at one point in time, although that might have been fixed in updated versions. out of curiosity, what pins are you attaching your servos to? (9 or 10?)

you might try updating your version of the ardunio IDE/Libraries.

another thought, is that many servos are rated at 6V (not 5v), and while they will work, they may also be jittery. you might find it best to use a separate power supply. Be sure to connect the grounds of the Arduino and external power supply together.

From Servo.h:

    ...
        //attach(pin )  - Attaches a servo motor to an i/o pin.
        //attach(pin, min, max  ) - Attaches to a pin setting min and max values in microseconds
        //default min is 544, max is 2400
    ...

    #define MIN_PULSE_WIDTH       544     // the shortest pulse sent to a servo
    #define MAX_PULSE_WIDTH      2400     // the longest pulse sent to a servo
    #define DEFAULT_PULSE_WIDTH  1500     // default pulse width when servo is attached
    #define REFRESH_INTERVAL    20000     // minumim time to refresh servos in microseconds
    ...

you might try tweaking the min, max, and default settings, or check your code against the settings provided by Servo.h.


message:
int array passed through function has wrong values only after multiple passes

I have this code:
```
for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
}
```
which calls the function "multiLamp" and passes 3 int arrays with 2 values each. Here is the function:
```
void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],2);
    }
  }
}
```
This function is supposed to call some function "lamp" with a few integers from the arrays. In the beginning this works fine but after more than 50 calls of the "multiLamp" function the values in the arrays become {0,128,128} and {3,3,3} or something similar even though the values passed into it from my main code are equally valid as before (they are somehow changed after being passed to the "multiLamp" function).

I can't seem to find the issue here. Any help is appreciated!

**UPDATE:**

Here is the full code, although I don't know if it will be of any use because I wrote it to control some LEDs and if you don't have the setup it's difficult to see if the code is working or not.

```
int e[] = {12,13,11,10};
int xy[] = {2,3,4,9,6,7,8,5,1,A0,A1,0,A3,A4,A5,A2};

void setup() {
  for(int a=0;a < 4;a++){
         pinMode(e[a], OUTPUT);
         digitalWrite(e[a], LOW);
  }
  for(int b=0;b < 16;b++){
         pinMode(xy[b], OUTPUT);
         digitalWrite(xy[b], HIGH);
  }
}

void loop() {
  bigCubes(100);
  rain(20, 30);
  miniCubes(15);
  every(80);
}

void lamp(int epos, int xpos, int ypos, int del) {
  int xypos = 4*xpos+ypos;
  digitalWrite(e[epos], HIGH);
  digitalWrite(xy[xypos], LOW);
  delay(del);
  digitalWrite(e[epos], LOW);
  digitalWrite(xy[xypos], HIGH);
}

void multiLamp(int epos[], int xpos[], int ypos[], int del, int len) {
  for(int it = 0; it < del; it++) {
    for(int i = 0; i < len; i++) {
      lamp(epos[i],xpos[i],ypos[i],1);
    }
  }
}

void every(int wait) {
  for(int i = 0; i < 4; i++) {
    for(int j = 0; j < 4; j++) {
      for(int k = 0; k < 4; k++) {
        lamp(i,j,k,wait);
      }
    }
  }
}

void miniCubes(int wait) {
  int cube[8][3] = {{0,0,0},{0,0,1},{0,1,1},{0,1,0},{1,1,0},{1,1,1},{1,0,1},{1,0,0}};
  for(int c = 0; c < 8; c++) {
    for(int it = 0; it < wait; it++) {
      for(int i = 0; i < 8; i++) {
        lamp(cube[i][0]+2*cube[c][0],cube[i][1]+2*cube[c][1],cube[i][2]+2*cube[c][2],2);
      }
    }
  }
}

void bigCubes(int wait) {
  multiLamp(new int[32] {0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,3,3,3,3,3,3,3,3}, new int[32] {0,0,0,0,1,1,2,2,3,3,3,3,0,0,3,3,0,0,3,3,0,0,0,0,1,1,2,2,3,3,3,3}, new int[32] {0,1,2,3,0,3,0,3,0,1,2,3,0,3,0,3,0,3,0,3,0,1,2,3,0,3,0,3,0,1,2,3}, wait, 32);
}

void rain(int its, int wait) {
  int x2 = random(0,4);
  int y2 = random(0,4);
  int x1;
  int y1;
  for(int i = 0; i < its; i++) {
    x1 = random(0,4);
    y1 = random(0,4);
    multiLamp(new int[2] {3,1}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {2,0}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    x2 = random(0,4);
    y2 = random(0,4);
    multiLamp(new int[2] {1,3}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
    multiLamp(new int[2] {0,2}, new int[2] {x1,x2}, new int[2] {y1,y2}, wait, 2);
  }
}
```

body:
You are wrongly using the `new` operator for your arrays. That will dynamically allocate these arrays. They are put on the heap (not the stack like local variables) and thus don't get freed automatically, when the function exits. That has to be done by your code with the `delete` keyword. Your code just eats up all the available memory. Thats called a memory leak.

That you need to free your dynamically created variables is not an Arduino thing; this is correct for all C/C++ code. But the limited memory on AVR based Arduinos like the Uno makes it worse.

If you do the math, one iteration of `void loop()` will block 432 bytes of memory (216 array elements, each of type `int` thus 2 byte). The 2KB of memory (which is also needed for local and global variables) is eaten up rather fast.

I don't see, why you even would use dynamically created arrays. Why not just using locally defined arrays, like in the `miniCubes()` function?

---

That said, it is also a generally bad idea to use dynamic memory allocation microcontrollers, especially those with small memory. When creating and deleting objects of different sizes (which is the main advantage of dynamic allocation), you will leave small holes in your RAM, which are too small for one of your objects to fit. At some point your RAM is completely filled with these holes, so that no more memory can be allocated for your objects to save. Thats called memory fragmentation.

On your PC that isn't a problem because of 2 reasons:

- The PC has loads of RAM available, and
- the OS manages the RAM, defragmenting it, if necessary.

Since microcontrollers don't have an OS managing the RAM and often very limited RAM, you need to make sure, that your RAM doesn't get fragmented too much in the runtime of your code.


message:
DS3218MG Servo - Not working with power supply

I'm trying to run my **DS3218MG Servo Motor** with an external power supply and my arduino nano.

I'm using the following code:

    #include<Servo.h>
    Servo Myservo;
    int pos;
    void setup()
    {
    Myservo.attach(3);
    }

    void loop()
    {

    for(pos=0;pos<=180;pos++){
    Myservo.write(pos);
    delay(15);
    }
      delay(1000);

      for(pos=180;pos>=0;pos--){
    Myservo.write(pos);
    delay(15);
    }
      delay(1000);
}

According to the datasheet the servo needs a **DC 4.8-6.8** voltage. My first attempt was to only use the arduino and no external power supply. So did the following connections:

 - servo's **ground** to arduino's **ground**
 - servo's **+** to arduino's **5V**
 - servo's **data** to arduino's GPIO **pin** 3

Using this connection works fine and the servo rotatates to the desired positions. However, because the arduino does not supply enough current, i bought a power supply with the following specs:

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

With that, i did the following connections:

 - connect the **ground** of the power supply to arduino's **ground** (and servo)
 - keep the **data** pin
 - connect **+** of power supply to servo's **+**

[![enter image description here][2]][2]

Unfortunately, the servo does not move with the external power supply. IMO, it should have the right voltage and also supply enough current (at least as much as the Arduino).

Do you see the problem?

  [1]: https://i.stack.imgur.com/4l18Dm.jpg
  [2]: https://i.stack.imgur.com/fGJgLm.png

body: @starcat,  regular  usb cable for  powering  arduino


message:
Arduino IDE 1.8.13 won't launch properly

Recently I have been trying to install Arduino IDE 1.8.13, and I have ran into according problem.
When trying to launch Arduino IDE with ./arduino command it shows according error:

    ./arduino: line 35: /home/wiktor/Downloads/arduino-1.8.13/java/bin/java: No such file or directory

I have checked and java file does indeed exist.
I am using 32 bit version of Arduino IDE and 32 bit version of Linux Alpine 3.13.3.

Thanks for all answers

body:
Note: Below, [technician 274][1] (the original poster) commented:

> It ended up working, after following alpinelinux wiki and installing
> the IDE using flatpak.

---

Part of the problem is how confusing the message is.
`No such file or directory` is not actually referring to the java file.  It's referring to the ld-linux.so interpreter specified in the elf file.

If you run the `file` command on the java executable, you'll see output that looks like:
```None
./java/bin/java: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.9, not stripped
```

If you look for `/lib/ld-linux.so.2`, you're going to find that you don't have one, and that's the file it's complaining about.

Alpine Linux apparently uses [Musl][2] and the java binaries were compiled for [glibc][3], which is normal for desktop Linux.  On a typical desktop Linux system, that the java that ships with the Arduino IDE was compiled for, all kinds of executables make use of ld-linux.so.2.  On your Alpine system, you'll find they're referring to /lib/ld-musl-i386.so.1 instead.  From this vantage point, it's more of a Linux problem than an Arduino one, but I thought it might as well have something of an answer to point people toward relevant looking resources:

* https://wiki.alpinelinux.org/wiki/Running_glibc_programs
* https://github.com/sgerrand/alpine-pkg-glibc

You may find it's easier to replace the java interpreter, but that won't be enough, because the Avrdude and GCC binaries will also expect ld-linux.so.2.

In the end, it may be easier to just not use Alpine Linux.

  [1]: https://arduino.stackexchange.com/users/75308/the-technician-274
  [2]: https://www.musl.com/
  [3]: https://www.gnu.org/software/libc/


message:
How to build and run AUnit tests

I found this example on how to create a project with AUnit tests: https://www.thecoderscorner.com/electronics/microcontrollers/embedded-testing/getting-started-unittesting-arduino/

According to it and projects I have found on github my project structure should look like this:

    Application
        src
            SomeComponent.cpp
            SomeComponent.h
        tests
            TestSomeComponent
                TestSomeComponent.ino
        Application.ino

But when I try to run TestSomeComponent.ino with Arduino IDE or VSC with Arduino plugin it does not see contents of src folder. I am assuming that it is treated as a separate sketch. What is a proper way to build and run tests?

[edit]
Some context (not sure what matters):

- Our target board is ESP32 DevKit v1
- Optimally if our developers could run tests on Windows and Linux machines
- I have not gotten yet to continuous integration. I will start automating once I have any test building and running

[edit 2]
I have tried command line tools. Got AUniter running and tried like this (hoping for some automagic done by tools):

    me@mypc:~/workspace/Application/Application/tests$ auniter.sh test esp32:/dev/ttyUSB0 TestSomeComponent/

I have tried any sane path combination in include path directive, for example:

    #include "SomeComponent.h"
    #include "app/SomeComponent.h"
    #include "../../src/app/SomeComponent.h"
    #include <SomeComponent.h>
    #include <app/SomeComponent.h>
    #include <../../src/app/SomeComponent.h>

But I keep getting this:

    TestSomeComponent:4:42: fatal error: ../../src/app/SomeComponent.h: No such file or directory

body:
I eventually switched to PlatformIO. It took me less than half an hour to rearrange sources, fix some compiler issues, build and flash my device.
Tests work really well. You just need to keep tested sources in lib folder. I even got GoogleTest package so I can use gmock in my tests.