body:
I have this code that I am using to play a sound effect where I used a program called wav2c to convert a .wav file to number values that I put into a header file that I use in the code to generate the sound. I currently have it programmed to play the audio upon uploading it to the Arduino with an LED being activated along with it and staying lit for just the duration of the sound effect. I am trying to program it so that the sound and LED only activate when I am pressing a button. I have the pin the button is plugged into already programmed in but I'm not sure how to have it control the audio and LED as stated above. I don't have much experience with programming or Arduino so any help is much appreciated! I am using an Arduino Mega 2560.

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

    #include <stdint.h>
    #include <avr/interrupt.h>
    #include <avr/io.h>
    #include <avr/pgmspace.h>

    #define SAMPLE_RATE 20000
    #include "Test.h"

    int ledPin = 2;
    int speakerPin = 9; // Can be either 3 or 11, two PWM outputs connected to Timer 2
    const byte pinSwitch1 = 3;
    volatile uint16_t sample;
    byte lastSample;

    void stopPlayback()
    {
        digitalWrite(ledPin, LOW);
        // Disable playback per-sample interrupt.
        TIMSK1 &= ~_BV(OCIE1A);

        // Disable the per-sample timer completely.
        TCCR1B &= ~_BV(CS10);

        // Disable the PWM timer.
        TCCR2B &= ~_BV(CS10);

        digitalWrite(speakerPin, LOW);
    }

    // This is called at 8000 Hz to load the next sample.
    ISR(TIMER1_COMPA_vect) {
        if (sample >= sounddata_length) {
            if (sample == sounddata_length + lastSample) {
                stopPlayback();
            }
            else {
                if(speakerPin==11){
                    // Ramp down to zero to reduce the click at the end of playback.
                    OCR2A = sounddata_length + lastSample - sample;
                } else {
                    OCR2B = sounddata_length + lastSample - sample;
                }
            }
        }
        else {
            if(speakerPin==11){
                OCR2A = pgm_read_byte(&sounddata_data[sample]);
            } else {
                OCR2B = pgm_read_byte(&sounddata_data[sample]);
            }
        }

        ++sample;
    }

    void startPlayback()
    {
        pinMode(speakerPin, OUTPUT);

        // Set up Timer 2 to do pulse width modulation on the speaker
        // pin.

        // Use internal clock (datasheet p.160)
        ASSR &= ~(_BV(EXCLK) | _BV(AS2));

        // Set fast PWM mode  (p.157)
        TCCR2A |= _BV(WGM21) | _BV(WGM20);
        TCCR2B &= ~_BV(WGM22);

        if(speakerPin==11){
            // Do non-inverting PWM on pin OC2A (p.155)
            // On the Arduino this is pin 11.
            TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
            TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2A = pgm_read_byte(&sounddata_data[0]);
        } else {
            // Do non-inverting PWM on pin OC2B (p.155)
            // On the Arduino this is pin 3.
            TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
            TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2B = pgm_read_byte(&sounddata_data[0]);
        }

        // Set up Timer 1 to send a sample every interrupt.

        cli();

        // Set CTC mode (Clear Timer on Compare Match) (p.133)
        // Have to set OCR1A *after*, otherwise it gets reset to 0!
        TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
        TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

        // No prescaler (p.134)
        TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set the compare register (OCR1A).
        // OCR1A is a 16-bit register, so we have to do this with
        // interrupts disabled to be safe.
        OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

        // Enable interrupt when TCNT1 == OCR1A (p.136)
        TIMSK1 |= _BV(OCIE1A);

        lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
        sample = 0;
        sei();

    }

    void setup()
    {
        pinMode( pinSwitch1, INPUT );
        pinMode(ledPin, OUTPUT);
        digitalWrite(ledPin, HIGH);
        startPlayback();
    }

    void loop()
    {
        while (true);
    }

The header file referenced in the code with the numeric values to create the audio.

    #ifndef _HEADERFILE_H    // Put these two lines at the top of your file.
    #define _HEADERFILE_H    // (Use a suitable name, usually based on the file name.)

    const int sounddata_length=32000;
    //const int sounddata_sampleRate=20000;

    const unsigned char sounddata_data[] PROGMEM = {
      15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,

    //There are many lines of more numbers in between that I cut out to save space

    };

    #endif // _HEADERFILE_H    // Put this line at the end of your file.

title: How do I have this audio and LED activate ONLY when a button is held using an Arduino?

Answers: 0


body:
I'm a hobbyist trying to up my arduino and electronics knowledge.
I can successfully control a hobby servo using an motor driver shield (https://learn.adafruit.com/adafruit-motor-shield/overview) but am running into issues when I try to control it without the shield using standard servo control circuits.

When the servo is connected to the basic, unworking circuit, it generally doesn't move and clicks occasionally, as though underpowered. It works flawlessly with the shield, when powered just through the standard 5V USB connection.

Schematic of circuit that doesn't work:
[![enter image description here][1]][1]

Schematic of circuit working with shield (shield is approximation from fritzing):

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

I've tried :

 - a 470uF or 1000uF decoupling capacitor between ground and +5V. Also tried with no capacitor.
 - powering the servo and/or arduino from an external power supply.  Grounds are connected correctly.
 - Different 5V power supplies. (batteries intended for phone charging, 5V from computer, 5V from wall).
 - Different Arduino Unos.
 - Different servos.

Code running on Arduino:

    #include <Servo.h>

    Servo servo;

    void setup() {
      servo.attach(10);
    }

    void loop() {
      servo.write(135);
      delay(500);
      servo.write(45);
      delay(500);
    }

I'd like to understand what I'm doing wrong, how to troubleshoot, and/or what the shield is doing that the basic circuit is not.

I'm using Arduino Unos, a hobbytech YM-2765 servo (rated for 4.8-6V), or a 3001HB servo.

  [1]: https://i.stack.imgur.com/3mD5I.png
  [2]: https://i.stack.imgur.com/F6LBs.jpg

title: Unable to control servo with decoupling capacitor and external power supply, but motor shield works

Answers: 0


body:
I want to use the buzzer KPEG2000 in my Arduino application. I would like to know if a GPIO can directly drive this buzzer, without destroy the uC (a GPIO can deliver 40 mA max). In the datasheet, we can find the current consumption under 12 volts (40 mA), but if I decrease the driving voltage to 5V, will this buzzer use more or less then 40 mA ?

https://docs-emea.rs-online.com/webdocs/07a8/0900766b807a8e16.pdf

I already tried to make this buzzer work on an Arduino, and it works. But I would like to know if plugging this buzzer directly to the Arduino will not destroy it.

title: Current consumption of a buzzer

Answers: 2

body:
In the datasheet I read 14 mA @ 12V, which is below the recommended current of a GPIO pin of 20 mA.

Note that 40 mA for a GPIO pin is the max current, recommended is 20 mA. But 14 mA is way less.

To see if it changes for 5V, try connect it without an MCU (directly to a 5 V adapter/USB/breadboard power) and measure the current using a multimeter.

In case it uses more than 20 mA @ 5V, than use a transistor/mosfet to drive the buzzer.

In case you want to have the buzzer at full power, connect a VCC 5V power rail pin to a boost converter, which is controlled by a transistor/mosfet controlled by a GPIO pin.

Thus

    Arduino VCC 5V -> Boos converter to 12 V -> Transistor/Mosfet -> Buzzer -> GND
                                                     ^
                                               Arduino GPIO pin

body:
If this is a piezo buzzer they typically work over a wide range of voltages and use very little current. I've seen them with specs for an input voltage ranging from 3 to 18v.

You could likely drive a piezo buzzer directly from a GPIO line without problems.


body:
I'm creating a LCD frequency generator.

When `TIMER1` reaches a set value, it's set to toggle Pin 9 (via `OC1A`).

Accidentally, I left the `TIMER1` "interrupt on compare match A" enabled, but never defined the `TIMER1_COMPA_vect` interrupt vector.

This made the Uno reset itself - but not running through the bootloader, just the program part - whenever `TIMER1_COMPA_vect` would've been called.

Once I defined the ISR, even without it having any content, it would run as expected.

**Is there a default content for ISRs, which resets the device / starts just after the bootloader? Shouldn't the compiler detect a completely missing ISR?**

title: Timer 1 COMPA ISR - default behaviour?

Answers: 1

body:
The compiler cannot detect a missing ISR since it is very difficult, in
the general case, to tell whether any particular interrupt-enable bit
has been set by the program.

The avr-libc library does indeed provide a “catch-all” ISR and, as
stated by the manual,

> the default action is to reset the device by jumping to the reset
> vector.

If you don't like this behavior, you can override this catch-all with
your own, [as explained in the manual][manual] (search for “Catch-all
interrupt vector”).

[manual]: https://www.nongnu.org/avr-libc/user-manual/group__avr__interrupts.html#details


body:
I am trying to follow [this tutorial][1] and I keep hitting a problem repeatedly. I checked in my code that every time it hits the line `Blynk.begin(auth, ssid, pass);`, the serial monitor shows me that there was a `cause:4, boot mode:(3,6) wdt reset`. I looked it up a little bit and learned that this is a "hardware watchdog reset" but I am not sure why this problem is happening. Please let me know if you guys would like anymore info. Thank you!

here is my code:

```
#include <ESP8266WiFi.h>

#define BLYNK_PRINT Serial    // Comment this out to disable prints and save space
#include <BlynkSimpleEsp8266.h>
char auth[] = "xxx";

/* WiFi credentials */
char ssid[] = "xxx";
char pass[] = "xxx";

/* HC-SR501 Motion Detector */
#define ledPin 7
#define pirPin 2 // Input for HC-S501
int pirValue; // Place to store read PIR Value

void setup()
{
  Serial.begin(115200);
  Serial.println("here 1");
  delay(10);
  Serial.println("here stop?");
  Blynk.begin(auth, ssid, pass);
  pinMode(ledPin, OUTPUT);
  pinMode(pirPin, INPUT);
  Serial.println("here 2");
  digitalWrite(ledPin, LOW);
}

void loop()
{
  getPirValue();
  Blynk.run();
  delay(10);
  Serial.println("here 3");
}

/***************************************************
 * Get PIR data
 **************************************************/
void getPirValue(void)
{
  pirValue = digitalRead(pirPin);
  if (pirValue)
  Serial.println("here 4");
  {
    Serial.println("==> Motion detected");
    Blynk.notify("===> Motion detected");
    Serial.println("here 5");
    delay(10);
  }
  digitalWrite(ledPin, pirValue);
  Serial.println("here 6");
}
```

Serial Monitor:

```
[6485] Connected to WiFi
[6486] IP: xx.x.x.xx
[6486]
    ___  __          __
   / _ )/ /_ _____  / /__
  / _  / / // / _ \/  '_/
 /____/_/\_, /_//_/_/\_\
        /___/ v0.6.1 on ESP8266

[6492] Connecting to blynk-cloud.com:80
[6584] Ready (ping: 38ms).

 ets Jan  8 2013,rst cause:4, boot mode:(3,6)

wdt reset
load 0x4010f000, len 1384, room 16
tail 8
chksum 0x2d
csum 0x2d
v8b899c12
~ld
here 1  (Serial.println in line 19 of code)
here stop? (Serial.println in line 21 of code)
```

Specs:

 - Board: Generic ESP8266 Module
 - Upload Speed: 115200
 - CPU Frequency: 80MHz
 - Flash Frequency: 40MHz
 - Flash Mode: DOUT (compatible)
 - Flash Size: 512K (no SPIFFS)
 - Crystal Frequency: 26MHz
 - Reset Method: ck
 - Debug Port: Disabled
 - Debug Level: None
 - IwIP Variant: v2 Lower Memory
 - VTables: Flash
 - Exceptions: Disabled
 - Builtin LED: 2
 - Erase Flash: Only Sketch
 - Espressif FW: nonos-sdk 2.2.1 (legacy)
 - SSL Support: All SSL ciphers (most compatible)

  [1]: https://www.instructables.com/id/IoT-Motion-Detector-With-NodeMCU-and-BLYNK/#discuss

title: Blynk.Begin(auth, ssid, pass) causing watchdog reset

Answers: 0


body:
The vehicle is an AMC eagle, they come with a diagnostic port ![diagnostic port](https://i.stack.imgur.com/RrPy8.gif)
I have made a diagnostic tool that lights led lights when signals turn on and off, but it has to be wired in and is bulky. I am wondering if it would be possible to have an arduino plugged in and running off the 12v battery supply (with step-down to 5v) and have it catch the signals and send them over Bluetooth to a computer. Does this sound like it is within the scope of an arduino or am I asking too much? Or is there a better and easier way to do this? ![diagnostic tool I made ](https://i.stack.imgur.com/MIMtm.jpg)

title: Would it be feasible to build an arduino that takes 12v on/off signals from a vehicle diagnostic port (1984 pre-OBD)?

Answers: 2

body:
You can step down 12V to 5V with resistor dividers, or drive transistor base with 12V and let the collector pulldown an input with pullup resistor to signal an active signal (like an optocoupler, but without the slow optical part).
Arduino reading the inputs and sending via bluetooth to something else is pretty straightforward, perhaps send only when a change from 0 to 1, and 1 to 0, on any input is sensed. Check Adafruit.com for bluetooth modules that are easy to use.

body:
Yes, it is possible. The 12v signals would have to be conditioned for the Arduino to receive them (0 - 12v or maybe 0 - 12-14.5v?). Then the Bluetooth side would be the same as any other Bluetooth data transmission.

So your question comes down to: Is this a fun project that's worth the effort you put into it for the learning experience? Or is this meant to answer a need, and the most practical means to that end is the best means?

Ex: I wanted to know how long / what kind of driving would it take to get my car's oil to full temp (~100C), starting from dead-cold in the winter? I had a thermo-logger I'd built for another experiment, so I taped a sensor to my oil filter (yeah, not the greatest, but quick and dirty) and lead a cable outside the hood, through the driver's window, to the experimental PC board on my dash-board. It wasn't a *miserable* failure but nothing to be proud of, either.

The solution I settled on was a USD$12.00 OBD port sender and an iPhone app. The results were much better, and while I didn't have the built-it-myself experience, I got the data and the answers I needed.


body:
I have an **ESP32**-D0WDQ6, which is part of the *ESPIRIT* [freematics](https://freematics.com/products/freematics-esprit/) development kit. The processor is a 2-core Tensilica LX6 and the module has 520 kB SRAM + 4 MB external on-module flash. It also has the SIM5360E 3G/GSM module. So with that connection, I don't need neither the Bluetooth nor the WiFi stack. However, it seem that when compiling using the Arduino IDE, all these libraries are still included in the compile, even if not used. This is bad as it seem to take up a lot of extra FW space that I need for my growing app, while running my device at high currents, and heating it up.

**How can I ensure that WiFi/Bluetooth libraries are not compiled in with the Sketch when using Arduino IDE?**

At this point I have tried to disable them, but that required to `#include Wifi.h` (or similar) which no longer fit on my sketch. (This doesn't make any sense, that I need to include Wifi.h just to be able to disable it.)

---

**UPDATE:**
It's most definitely linking all those...

```bash

#--------------------------------------
# Linking everything together...
#--------------------------------------

"C:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/xtensa-esp32-elf/bin/xtensa-esp32-elf-gcc"
-nostdlib "-LC:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/sdk/lib"

    "-LC:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/sdk/ld"
    -T esp32_out.ld -T esp32.common.ld -T esp32.rom.ld -T esp32.peripherals.ld -T esp32.rom.libgcc.ld -T esp32.rom.spiram_incompatible_fns.ld
    -u ld_include_panic_highint_hdl -u call_user_start_cpu0 -Wl,--gc-sections -Wl,-static
    -Wl,--undefined=uxTopUsedPriority -u __cxa_guard_dummy -u __cxx_fatal_exception
    -Wl,--start-group "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\BTHealthThermometer.cpp.o"

    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\ECUBluetoothTask.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\FreematicsNetwork.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\FreematicsPlus.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\KolbanTask.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\eCUesp32.ino.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\eCUlogging.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\sketch\\esp32fota.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLE2902.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLE2904.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEAddress.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEAdvertisedDevice.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEAdvertising.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEBeacon.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLECharacteristic.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLECharacteristicMap.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEClient.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEDescriptor.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEDescriptorMap.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEDevice.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEEddystoneTLM.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEEddystoneURL.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEExceptions.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEHIDDevice.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLERemoteCharacteristic.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLERemoteDescriptor.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLERemoteService.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEScan.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLESecurity.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEServer.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEService.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEServiceMap.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEUUID.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEUtils.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\BLEValue.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\FreeRTOS.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\BLE\\GeneralUtils.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\ETH.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFi.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiAP.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiClient.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiGeneric.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiMulti.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiSTA.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiScan.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiServer.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFi\\WiFiUdp.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\SPI\\SPI.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\SD\\SD.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\SD\\sd_diskio.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\SD\\sd_diskio_crc.c.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\FS\\FS.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\FS\\vfs_api.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\HTTPClient\\HTTPClient.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFiClientSecure\\WiFiClientSecure.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\WiFiClientSecure\\ssl_client.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\libraries\\Update\\Updater.cpp.o"
    "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833\\core\\core.a"

-lgcc
-lopenssl
-lbtdm_app
-lfatfs
-lwps
-lcoexist
-lwear_levelling
-lesp_http_client
-lprotobuf-c
-lhal
-lnewlib
-ldriver
-lbootloader_support
-lpp
-lfreemodbus
-lmesh
-lsmartconfig
-ljsmn
-lwpa
-lethernet
-lphy
-lapp_trace
-lconsole
-lulp
-lwpa_supplicant
-lfreertos
-lbt
-lmicro-ecc
-lesp32-camera
-lcxx
-lxtensa-debug-module
-ltcp_transport
-lmdns
-lvfs
-lesp_ringbuf
-lsoc
-lcore
-lfb_gfx
-lsdmmc
-llibsodium
-lcoap
-ltcpip_adapter
-lprotocomm
-lesp_event
-limage_util
-lc_nano
-lesp-tls
-lasio
-lrtc
-lspi_flash
-lwpa2
-lwifi_provisioning
-lesp32
-lface_recognition
-lapp_update
-lnghttp
-lspiffs
-lface_detection
-lespnow
-lnvs_flash
-lesp_adc_cal
-llog
-ldl_lib
-lsmartconfig_ack
-lexpat
-lm
-lfr
-lmqtt
-lc
-lheap
-lmbedtls
-llwip
-lnet80211
-lesp_http_server
-lpthread
-ljson
-lesp_https_ota
-lfd
-lstdc++
-Wl,--end-group
-Wl,-EL
-o "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833/eCUesp32.ino.elf"

"C:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/gen_esp32part.exe"
-q "C:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/partitions/default.csv"
"C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833/eCUesp32.ino.partitions.bin"

"C:\\Users\\XXX\\Documents\\Arduino\\hardware\\espressif\\esp32/tools/esptool/esptool.exe"
--chip esp32 elf2image --flash_mode dio --flash_freq 80m --flash_size 4MB
-o "C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833/eCUesp32.ino.bin"
"C:\\Users\\XXX\\AppData\\Local\\Temp\\arduino_build_245833/eCUesp32.ino.elf"

```

title: How can remove the WiFi/Bluetooth libraries when compiling the firmware using the Arduino IDE?

Answers: 0


body:
I have 2 sketches that control a fan using Arduino UNO, that I try to combine.
The 1st is a timer, that turns a pin ON and OFF for a determined period of time.   The pin signal drives a MOSFET that in turn switches a small fan ON and OFF.
Since I need to control the speed of the motor, I would rather use the PWM control, however I am not sure how I can apply the timer since analogWrite command refers to a pin and value.
Thanks

timer code:

```c++
const byte relayPin = 6; // relay module on pin 6
const byte monitorPin = 13; // builtin LED output
const unsigned long interval_1 = 1000UL * 15, interval_2 = 1000UL * 15; // ON timer + OFF timer in milliseconds
unsigned long currentMillis, previousMillis = 0;

void setup() {
  // put your setup code here, to run once:
  pinMode(relayPin, OUTPUT);
  digitalWrite(relayPin, HIGH); // relay OFF
  pinMode(monitorPin, OUTPUT);
  digitalWrite(monitorPin, LOW); // LED off
}

void loop() {
  // put your main code here, to run repeatedly:
  currentMillis = millis();
  if (currentMillis - previousMillis >= interval_1)
  {
    digitalWrite(relayPin, LOW); // relay ON
    digitalWrite(monitorPin, LOW); // LED on
  }
  if (currentMillis - previousMillis >= (interval_1 + interval_2))
  {
    digitalWrite(relayPin, HIGH); // relay OFF
    digitalWrite(monitorPin, HIGH); // LED off
    previousMillis = currentMillis; // reset
  }
```

PWM code:

```c++
int PWMControl= 6;
int PWM_Input = A0;

int PWM_Value = 0 ;

void setup() {
  pinMode(PWMControl, OUTPUT);
  pinMode(PWM_Input, INPUT);
}

void loop()
{
  PWM_Value = analogRead(PWM_Input);
  PWM_Value = map(PWM_Value, 0, 1023, 0, 255);
  analogWrite(PWMControl, PWM_Value);
}
```

title: how to apply a timer to an analogWrite command for Arduino

Answers: 2

body: Don't think of what you have as a "timer".  That's not what it really is.  What you have is a loop function that repeats itself thousands of times per second and an if statement that asks "is it time to do this yet".  So if you want to use analogWrite instead of digitalWrite when it is time to do that thing then use analogWrite instead.  It doesn't change your timing setup one bit.  Just replace the digitalWrite calls with analogWrite calls.  If you want to read your pot at the same time then put that in there as well.  Basically everything inside the block of code controlled by that if statement is going to happen every time that interval passes no matter what it is that you put there.  If you want something to print every interval then you could put a print statement in there.  If you want it to call some custom function every interval then call that function in there.  There's nothing special about that way of timing that only works with digitalWrite.

body:
If I understand correctly, this is what you want to do:

 1. Fan + led off for 15s
 2. Fan on (speed determined by A0) + led on for 15s
 3. Repeat

clearly defining your goal in english can help with coding, so I hope I guessed right.

here's my suggestion for your code

     const byte controlPin = 6; // MOSFET on pin 6
     const byte monitorPin = 13; // builtin LED output
     const unsigned long interval_1 = 1000UL * 15, interval_2 = 1000UL * 15; // ON timer + OFF timer in milliseconds
     unsigned long currentMillis, previousMillis = 0;
     int PWM_Input = A0;
     int PWM_Value = 0 ;

     // setting pin direction and default state
     void setup() {
       pinMode(controlPin, OUTPUT);
       digitalWrite(controlPin, HIGH); // MOSFET OFF
       pinMode(monitorPin, OUTPUT);
       digitalWrite(monitorPin, LOW); // LED off
     }

     // run fan for a while, then stop fan for a while
     void loop() {

       currentMillis = millis();

       //fan on, led on, both signals active low
       if (currentMillis - previousMillis >= interval_1){
           PWM_Value = analogRead(PWM_Input);
           PWM_Value = map(PWM_Value, 0, 1023, 0, 255);
           analogWrite(PWMControl, PWM_Value);
           digitalWrite(monitorPin, LOW);
       }

       //fan off, led off, reset timing
       if (currentMillis - previousMillis >= (interval_1 + interval_2)){
          digitalWrite(controlPin, HIGH); // MOSFET OFF
          digitalWrite(monitorPin, HIGH); // LED off
          previousMillis = currentMillis; // reset
       }
     }

There are still issues I can with this code:

 1. You did not tell us what type of MOSFET you are using, so I can't tell if it is actually active low
 2. I believe that the LED on most arduino boards (pin 13) is active high, so that's probably wrong
 3. Don't forget comments. I find comments more useful for a block of code than for a single line, but you can do both if you want ;)
 4. I find your code convoluted regarding millis logic, for me it would be more logical to have something along the lines of:

         current = millis()-previous
         if current < interval1
            fan off
         elseif current < inteval1+interval2
            fan on
         else
            previous = millis()

It would be more readable for a human, the result on the arduino would be similar.


body:
So I have a couple of XBee S2Cs, and I have configured them properly--they can in fact communicate with each other. I am using them with Arduino Unos and this shield: https://store.arduino.cc/usa/shield-xbee-without-rf. I am attempting to interface with the XBees with SoftwareSerial, but for whatever reason, they are instead using just regular Serial. Anything I put on the SoftwareSerial appears to be ignored entirely, while anything I put on Serial appears in my serial monitor and also is transmitted to the other XBee. I have this code for transmitting:

```
#include <SoftwareSerial.h>
SoftwareSerial xbee (2, 3);
void setup() {
    Serial.begin(9600);
    xbee.begin(9600);
}

void loop() {
    xbee.println("hello");
    Serial.println("world");
    delay(5000);
}
```

And this code for receiving:

```
#include <SoftwareSerial.h>

SoftwareSerial xbee(2, 3);

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

void loop() {
    if (xbee.available() > 0) {
        Serial.println("xbee: " + xbee.readString());
    }
    else {
        Serial.println("no xbee data");
    }

    if (Serial.available() > 0) {
        Serial.println("serial: " + Serial.readString());
    }
    else {
        Serial.println("no serial data");
    }
    delay(5000);
}
```

Every 5 seconds, I get this output through the serial monitor on the transmitting side:
```
world
```

and this on the receiving side:
```
no xbee data
serial: world
```
I also get the string ```world``` when I connect a third XBee to my XCTU console.

So I have a couple of questions:

First off--how is this happening? I'm no Arduino expert, but as far as I can tell from what I've read, if the XBee is capturing my serial output, then I shouldn't also be able to see it in the serial monitor.

Second off--how can I get the SoftwareSerial to work? I could theoretically just use Serial forever, but that would make debugging way more trouble, and would probably create a code-maintenance headache later. If I had to guess, I might need to use different pins for my shield, but I have no idea how to find out what pins are the right ones to use.

Update: Based on what I've seen and read, it looks like the particular combination of the Uno with this shield leaves me with no options but to use the hardware serial. A different shield or Arduino board would grant me options to separate my serial output from my xbee output, but that does not appear to be an option here.

title: XBee using Serial rather than SoftwareSerial--how to fix

Answers: 2

body:
You will need an xbee breakout board [Xbee breakout board](https://core-electronics.com.au/breakout-board-for-xbee-module.html?utm_source=google_shopping&gclid=Cj0KCQjwgezoBRDNARIsAGzEfe5rKn6w0U7HULrudkAvlGlFTfzhgk3rpAOtz9_sqn95fasWv4DuRV8aAmPaEALw_wcB) or this one from [Sparkfun](https://www.sparkfun.com/products/8276) to do that...

Make sure you check if the board comes with headers as they are **not always included**. Note also that the xbee socket is not a standard size - which is why you need the breakout board - it converts the XBee pin to a standard size. Here are the [2mm headers](https://www.sparkfun.com/products/8272) required for xbee and regular [0.1" headers](https://www.sparkfun.com/products/116) required for connection to a breadboard or jumper wires etc.

*Actually*, I used leonardo for the very reason that you asked about in your question. Leonardo has two serial ports, one is for the usb connection you are familiar with on Uno, **but** it is not connected to pins 0 and 1.

The other is a completely independent serial port that is wired to pins 0 and 1 on leonardo.

So on Leonardo, you can do `Serial.println("Debug msgs");` and `Serial1.println("xbee messages");` (note the digit 1 in Serial**1**). Of course other platforms such as Mega also can be used in the same way.

I am assuming you already have some sort of an XBee shield that allows you to plug the XBee directly into your Uno. The beauty of the Leonardo is that you can continue to use that sheild. The XBee will "automatically" be connected to Serial1.

FWIW, i had all sorts of trouble with s/w serial. I couldn't get it to work with my XBees at all. I could never work out why it did not seem to work.

As soon as i moved to leonardo, it worked like a charm.

body:
To debug the sketch with SoftwareSerial, remove the jumpers from JP2 and JP3 and wire (with jumper wires) the middle pin of JP2 and JP3 to SoftwareSerial pins of your choice.

Middle pin of JP2 is TX of the Xbee so wire it to RX of SoftwareSerial. Middle pin of JP3 is RX of XBee.

On that particular board, JP2 is the jumper closer to the middle of the board, while JP3 is closer to the edge.

[shield's schematics][1]

  [1]: https://www.arduino.cc/en/uploads/Main/XbeeShieldSchematic.pdf


body:
I've search on how to do statistic calculation in EEPROM, but non related.
The data that I stored in EEPROM is body temperature.
Currently I stored the data using float.

Below is my code for data store in eeprom.
I'm stuck at the void function named "printTemp". I know how to calculate average in array using for loop statement, but not EEPROM. From average/mean, I can find standard deviation.

Does anyone have an idea on how can we do calculation using data from EEPROM?

<!-- language-all: lang-cpp -->
```
#define LM35 A1
#define READSAMPLES 100

float bt;
int buttonPin1 = D5;     // the number of the pushbutton pin 1 MEASURE
int buttonPin2 = D6;     // the number of the pushbutton pin 2 RESET CYCLE
int buttonState = 0;         // variable for reading the pushbutton status
int ButtonState = 0;         // variable for reading the pushbutton status
int address = 0;      //EEPROM address counter
int count, counT;
int sample[READSAMPLES];

void setup() {

    int contCount = EEPROM.get(5, count) / 10;

}

void loop() {

  buttonState = digitalRead(buttonPin1);
  ButtonState = digitalRead(buttonPin2);

  // check if the pushbutton is pressed.
  // if it is, the buttonState is HIGH:
  if (buttonState == LOW) {
        Serial.println("Measuring your Body Temperature:");

        count = counting();
        counT = count / 10;
        Serial.print("Data count entering: ");
        Serial.println(counT);

        writeTemp();
  }

  if (ButtonState == LOW) {

        Serial.println("Update New Cycle of body temp...");
        printTemp();
        clearEEPROM();
        Particle.publish("DONE new Cycle");

  }

}

void printTemp()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    float cel = EEPROM.read(i);                //read EEPROM data at address i
    //How to find MEAN of all data?
  }
}

void clearEEPROM()
{
  for (int i = 0 ; i < EEPROM.length() ; i++) {
    if(EEPROM.read(i) != 0)                     //skip already "empty" addresses
    {
      EEPROM.write(i, 0);                       //write 0 to address i
    }
  }
  Serial.println("EEPROM erased");
  address = 0;                                  //reset address counter
}

void writeTemp()
{
  //getting the voltage reading from the temperature sensor
  int j;
  float average;
  for (j = 0; j < READSAMPLES; j++)
  {
    sample[j] = analogRead(LM35);        //read sensor value
    delay(50);
  }

  average = 0;
  for (j = 0; j < READSAMPLES; j++)
  {
    average += sample[j];
  }
  average /= READSAMPLES;

  //float mv = ( average / 4096.0) * 3300;
  //float cel = ( mv / 10 ) - 55.01;
  float mv = ( average / 1024.0) * 5000;
  float cel = ( mv / 10 );

  EEPROM.write(address, cel);         //write value to current address counter address

  Serial.print("Sensor value stored at address ");
  Serial.println(address);

  address++;                      //increment address counter
  if(address == EEPROM.length())  //check if address counter has reached the end of EEPROM
  {
    address = 0;              //if yes: reset address counter
  }
}

float counting()
{
  count = count + 10;   // plus 10 is because to give a space for data entering the eeprom for LATER CODE. Just live it here.
    Particle.publish("Start Count =", String(count));
  return count;
}
```

What I can share from my problem findings are, to do the calculation of statistic from EEPROM data;

1. we need to know how to read back all the data in EEPROM. As in my code I know how to read the data, but the data cannot be hold because in FOR loop the the process will running until the end of 'i'.
2. we need to know how many data are there in EEPROM that have entered. To solve this, I'm using count; in order to count the entering data.

I need suggestion links or maybe any idea on how to do statistics in EEPROM.

Thanks.

title: Calculate statistic in EEPROM

Answers: 2

body:
Doing that calculation from EEPROM is exactly the same as doing it from any other source.  You have a count so you know where the EEPROM data ends.  You know where the EEPROM data starts.  You know how to read a number out of EEPROM.  What is stopping you from creating a for loop to read the i'th address from EEPROM and add all those numbers together just like you would for an array?

    for (int i = EEPROM_START; i < EEPROM_END; i++){
       sum = sum + EEPROM.read(i);
    }
    average = sum / count;

where EEPROM_START and EEPROM_END are supplied by you by knowing what address you started and ended writing at.

body:
There are quite a few issues with your program. Averaging is just one of
them.

You wrote:
> Currently I stored the data using float.

No, you didn't. You stored 8-bit unsigned integers (aka `uint8_t`).

<!-- language-all: lang-c++ -->

    int contCount = EEPROM.get(5, count) / 10;

Assuming you are using an 8-bit Arduino, this is reading the EEPROM
cells at addresses 5 and 6, combining these two readings into a single
signed 16-bit number, and storing it in `count`. Given that these EEPROM
cells are also used to store temperature readings, this operation makes
no sense at all. BTW, the line above also stores a copy of the newly
updated `count` into a fresh local variable that gets immediately
discarded. This also makes no sense.

Later you wrote:

    for (int i = 0 ; i < EEPROM.length() ; i++) {
      if(EEPROM.read(i) != 0)  //skip already "empty" addresses
      {
        EEPROM.write(i, 0);    //write 0 to address i
      }
    }

There is an `EEPROM.update()` method meant to do this in a simpler way:

    for (int i = 0 ; i < EEPROM.length() ; i++) {
      EEPROM.update(i, 0);  //write 0 to address i unless it is already 0
    }

Later:

    for (j = 0; j < READSAMPLES; j++)
    {
      sample[j] = analogRead(LM35);        //read sensor value
      delay(50);
    }

There is no point in storing all the readings in RAM just to compute the
average. You can get rid of the `sample` array and instead:

    float average = 0;
    for (int j = 0; j < READSAMPLES; j++)
    {
      average += analogRead(LM35);  //read sensor value
      delay(50);
    }
    average /= READSAMPLES;

Later:

    float cel = ( mv / 10 );
    EEPROM.write(address, cel);
    [...]
    address++;

This is probably your biggest issue. You may believe you are storing
floats, yet `EEPROM.write()` can _only_ write bytes. Thus the value
`cel`, which is a voltage in centivolts, is implicitly casted to a
`uint8_t`. This means it is rounded down to the nearest integer below
it, then wrapped modulo 256. This is quite likely _not_ what you want.

If you really want to store floats, you should replace the last two
lines of code above by

    EEPROM.put(address, cel);
    address += sizeof cel;

but then beware that when reading the EEPROM you should also increment
the address in steps of `sizeof(float)`.


body:
I'm trying to send some data to my arduino mega 2560 using serial communication.

I'm using the exemple that I found [here] without success.

Every site I read say that I can send data to the arduino board like writing to any file on ubuntu.

But I alway get `Segmentation fault`

**Here is my code**

    #include <stdio.h>
    #include <string.h>

    char arduinoPort[] = "/dev/ttyACM0";

    int main() {

      char buffer[] = {'1'};

      FILE *usb_port;

      usb_port = fopen(arduinoPort, "rwb");

      fwrite(buffer, sizeof(char), sizeof(buffer), usb_port);

      fclose(usb_port);

      return 0;
    }

[here]: https://forum.arduino.cc/index.php?topic=178913.0

title: Serial communication between PC and Arduino using C

Answers: 1

body:
Your program works flawlessly on my Ubuntu 18.04. I would guess that you
have a problem with your setup (flaky USB port, permission problems...)
rather than the program itself. Still, I would recommend you add some
error checking: right after the `fopen()` call,

```c++
if (!usb_port) {
    perror(arduinoPort);
    return 1;
}
```

I would expect you see something like

```none
/dev/ttyACM0: No such file or directory
```

or

```none
/dev/ttyACM0: Permission denied
```

that could help you pin down the real problem.


body:
I am working of on a Wemos R1 D2 board with VL53L0X Laser Sensor. I need to stop my program after calculating an average of 50 readings but as soon as I try while(1) { } or any other method my output produces garbage.

```c++
void loop()
{
  float initial=0,inside=0,outside=0,sum=0,x;
  for (int i = 0; i < 10; i++) {
    x = sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
    sum = sum + x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
  while(1) {};
  Serial.flush();
}
```

title: If I try to pause my loop function my output screen starts printing trash

Answers: 2

body:
There is nothing immediately obviously wrong with your program, but what happens if you do it a bit more "normally"?

By normally, just do nothing after the 10th (or 50th) time through, instead of the infinite loop you are currently executing.

```C
int cntr = 0;
float initial=0,inside=0,outside=0,sum=0,x;

void loop()
{
  if (cntr < 10 /* or 50 */) {
    cntr++;
    x=sensor.readRangeSingleMillimeters();
    if (sensor.timeoutOccurred()) {
      Serial.print(" TIMEOUT");
    }
    sum=sum+x;
    Serial.print("Initial Reading: ");
    Serial.println(sum);
  }
}

```

My reason for suggesting this is that when I tried an ESP board, there was an enourmous amount of bloatware included in the generated code. There may well be other stuff that needs to happen in the background between calls to the loop method. But you are preventing that from happening with your infinite loop.

However, clearly something is happening in the background because your infinite loop is somehow generating, as you put it,  "garbage".

You did not publish the  details of sensor library or its methods. Could there be any side affects there? What pins does the sensor connect to?

body:
ESP8266 based boards do not like being tied up for too long without being able to service any WiFi based tasks.

Having a while(1){} effectively ties up the processor indefinitely. This causes a watchdog reset, and the serial port will print garbage (actually it's the chip's boot message). You don't show your Serial setup.

The ESP8266 can service its WiFi tasks at the end of loop(), during a delay() or if the yield() function is called.

I would suggest adding a delay() or yield() to your while block will fix the problem.


body:
I ran into the following error with a recent Arduino IDE version (1.8.9) when trying to upload to an "Arduino Nano" clone (ATmega328P):

    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x18
    ...
    avrdude: stk500_recv(): programmer is not responding
    avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x18
    Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

The problem could be resolved by choosing "ATmega328P (Old Bootloader)" as *Processor* in the *Tool* menu - as now suggested to me and solved in https://arduino.stackexchange.com/questions/804/.

The change was made in August 2018 with the release of Arduino IDE 1.8.6: https://github.com/arduino/Arduino/releases/tag/1.8.6

Details about the different bootloaders are described in
https://arduino.stackexchange.com/questions/51866/.

It seems the fuses have to be changed in order to make full use of the newer, smaller bootloader, so an ISP will have to be used anyway.

But is the bootloader able to update itself (via *Tools > Burn bootloader*) or is there an intermediate "bootloader update sketch" available?

title: Can the Arduino (Nano) bootloader be updated via itself and the Arduino IDE or is an ISP required?

Answers: 1

body:
On ATmega328p and similar ATmega MCUs with bootloader support, the application is not allowed to write to flash. Only code running in bootloader area of the flash memory is allowed to write to flash. Bootloader area is at the end of the flash and the beginning is set with the BOOTSZ fuses.

The write to flash page is done in two steps. First step is deleting the contents of the flash page, second step is write the new data to the flash page. In bootloader area* it is allowed to first prepare the data to temporary buffer page, then delete the flash and write the data in one step. So in theory the bootloader could overwrite itself with a function running in the last flash page. But I don't know about bootloader which would do it.

**To write a bootloader an ISP programmer is necessary. Or other Arduino with the "Arduino as ISP" sketch.**

 *note: the read-while-write area at the end of flash has the size of the largest bootloader area possible and is not determined by BOOTSZ.


body:
I have been trying to use the **HC-05 Module** with my **Arduino Uno** to control a LED, which can be turned on and off by my phone. Everything is fine when i input the values from the serial monitor. The problem **only occurs when I use my phone**. I am using a bluetooth terminal for HC-05 and it shows it connected. The **bluetooth module is conected** as its blinking slows down when I use the app.

Here's the code:

    #define ledPin 8
    int state = 0;

    void setup() {
     pinMode(ledPin, OUTPUT);
     digitalWrite(ledPin, LOW);
     Serial.begin(38400); /
    }

    void loop() {
     if(Serial.available() > 0){ // Checks whether data is comming from the serial port
     state = Serial.read();
     }
     if (state == '0') {
     digitalWrite(ledPin, LOW);
     Serial.println("LED: OFF");
     state = 0;
     }
     else if (state == '1') {
     digitalWrite(ledPin, HIGH);
     Serial.println("LED: ON");;
     state = 0;
     }
    }

Here's the serial monitor output;

[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/cB4Vf.png

Appreciate the Help!

title: My HC-05 Bluetooth Module is not working

Answers: 2

body:
Few Points that you might want to Look into.

 1. Where exactly are you connecting Bluetooth Module with Uno. Make sure you are connecting it with Rx and Tx Pin Only.
 2. First make Simple Program to send some data on Serial Say "Hello World" at every 1second and make sure your Bluetooth is connected to Hardware Serial Pins only. If you receive data on phone then you are good to receive as well If not then Try below points.
 3. Make sure your HC-05 Baudrate is correct. If you are not sure then try some others as well like 9600, 115200 etc.
 4. Make sure Rx and Tx pins are connect with correct pins of HC-05. If you know your Baudrate then try swapping Rx Tx and it should response to you.

body:
When switching from serial monitor to phone, did you change how the Arduino board was powered? If you power Arduino board via VIN port, then voltage across VIN and GND needs to be STRICTLY between 7 to 12 volts, otherwise the Arduino board is unstable (even if the board is on).

More tips and supporting information can be found on Step 3 of:
https://www.instructables.com/How-to-Connect-HC-05-to-Windows-1011-Mac-Apple-Com/


body:
I've seen that resistor dividers can be used to read negative voltages, but I'ld like if there is a way to accomplish this with less components and having a way to turn this off.

I was thinking if there would be an extreme option of changing from pinMode INPUT to INPUT_PULLUP or INPUT_PULLDOWN to power the circuit and use the 20k pullups to make part of the divider, together with another resistances on the input. Alternatively, switching from INPUT to OUTPUT would be fine.

What I want to measure is an external +3V/GND/-3V power supply (battery pack) that shares the GND with the arduino SAMD21 (3.3V), measuring both +3V and -3V, and avoiding drain when not measuring (hence the pin mode changes)

Currently I'm using this schema to measure the voltage of +5V supply battery (connected through VIN, thus using the internal regulator), by dividing with 2 1Mohm resistances, ground to digital pin and measurement by internal adc. I don't need so much precision, so this is enough here. So I'm looking for the same or better alternatives, but for the -3V I don't know how to properly calculate the 3 resistor divider.

title: measure +3V and -3V through resistor divider and switch on/off by digital pins

Answers: 2

body:
When measuring a voltage that is higher than the maximum rating, the voltage of interest is tied to ground with a voltage divider. When measuring a negative voltage, you instead have to tie the voltage of interest to the positive supply voltage (study the answers to [this question][1]).

In theory you can use the internal pullup to spare one resistor, but I would consider this a bad practice and recommend using an external pullup for the following reasons:

  - a uC's internal pullups/-downs are not accurate and sometimes not specified
  - especially when measuring negative voltage, chances are that harmful voltage is applied to the adc (consider the default state of a gpio)
  - a pullup/-down is an uncritical component concerning its value and precision. Therefore they are very cheap

  [1]: https://electronics.stackexchange.com/q/3105/197351

body:
Two 1M resistors for a voltage divider is high. You could add a capacitor (1nF or 10nF) to GND and the analog input.

Could you try to find what the leakage current or the self-discharge current of the battery itself is? Then take a percentage of that, for example 20%, then calculate what resistor value the voltage divider should be.

It does not have to be 20%, it can be any current that you are willing to give up to be able to measure the voltage.

For example, when the battery has a self-discharge current of 10µA, then 20% is 2µA, which is two resistors of 825kΩ. That happens to be close to the 1M resistors that you already use.


body:
I have an Arduino Uno and an Adafruit data logging shield and I have connected a digital pressure sensor that uses serial communication. The sensor requires a character to start transmitting data. I have managed to read the data using this code:

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(8,9);

int depth;

void setup() {

    Serial.begin(9600);
    mySerial.begin(9600);
    mySerial.print("C");

}

void loop()
{

 if (mySerial.available()) {

   depth = mySerial.read();

 }

}
```

This returns the following:

> C1000
C1000
C1000

where 1000 is the value.

I have written another code that logs data to the shield and tested with other sensors but I cannot log data from this sensor by modifying the above code and cannot find any relevant examples.
If I add something like this it does not return the same value.
```
logfile.println(depth);
```
Complete newbie in so any suggestions are welcome.

UPDATE

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

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

title: Logging data to SD card from software serial

Answers: 1

body:
use the C as the line start indicator. if received char is 'C' then do a `file.println();` example with output to Serial

    #include <SoftwareSerial.h>
    SoftwareSerial mySerial(8,9);

    void setup() {
        Serial.begin(9600);
        mySerial.begin(9600);
        mySerial.print("C");
    }

    void loop() {
     if (mySerial.available()) {
       char c = mySerial.read();
       if (c == 'C') {
         Serial.println();
       }
       Serial.write(c);
     }
    }


body:
I get several errors once I try to include these two libraries:

>
error: expected unqualified-id before '{' token
   #define DEBUG_PRINTLN(...) {}

    #include <DHT.h>
    #include <DGS.h>

    void setup() {
    }

    void loop() {
    }

Apparently `DEBUG_PRINTLN` is causing the problems, because it is defined as a private function in DGS.h and as a constant (#define) in DHT.h.

Including DGS.h before DHT.h does not throw errors. But is this a safe workaround or might I run into errors later? How can I deal with that, without modifying the libraries?

[DGS.h][1]:

    /*
      DGS_25SEP17.h - Library for reading KWJ Engineering with SPEC Sensors on Digital SDK with firmware date 25SEP17.
      Created by David E. Peaslee, Mar 29, 2018.
    */

    #ifndef _DGS_h
    #define _DGS_h

    #if defined(ARDUINO) && ARDUINO >= 100
    #include "Arduino.h"
    #elif defined(SPARK)
    //#include "application.h"
    #else
    #include "WProgram.h"
    #endif

    #include "Stream.h"

    class DGS
    {
      private:
        Stream *_mySerial;
        long dataArray[11]; //Multipurpose array
        //void unlock(void);
        void DEBUG_PRINTLN(long x);
        void DEBUG_PRINTLN(float x);
        void DEBUG_PRINTLN(String x);
        void DEBUG_PRINT(long x);
        void DEBUG_PRINT(float x);
        void DEBUG_PRINT(String x);

      public:
        DGS(Stream &mySerial); //Class that represents DULP with Stream as class for Serial
        DGS(Stream *mySerial); //Class that represents DULP with Stream as class for Serial

        bool DEBUG;

        int setToff(float offset);  //Sets a temperature offset
        int setBC(String BC);  //Initializes DGS with all information from barcode, only way to set Span
        String getFW(void); //Returns the Firmware Date

        int getLMP(void); //Loads LMP[3] with register values from LMP91000
        int LMP[3];  //LMP Registers, needs to be loaded with getLMP
        int setLMP(int R1, int R2, int R3); //Sets new LMP registers and reintializes LMP

        int zero(void); //Zeros to current reading, Zero only in a clean air environment
        int setXSpan(float); //ReCalibrates device, only should be used after zero, and using a calibrated gas

        int getData(char c); //Gets the data and loads into variables
        long getConc(char x = 'p');  //Reads concentration from current data array 'p' ppb or 'c' counts
        long getTemp(char t = 'C');  //Reads temperature from current data array 'C' for Celsius or 'F' for Fahrenheit
        long getRh(char r = 'r'); //Reads Rh from current data array 'r' for Rh and 'c' for counts

        void getEEPROM(void); //Loads variables into EEPROM E[5] and e[14] arrays, outputs EEPROM if DEBUG is true
        String eepromStr[5]; //Stores the character based EEPROM data
        long eepromInt[13];  //Stores the integer based EEPROM data
        float Sensitivity_Code;  //Stores the sensitivity coefficient in nA/PPM
    };

    #endif

DHT.h:

    /* DHT library

    MIT license
    written by Adafruit Industries
    */
    #ifndef DHT_H
    #define DHT_H

    #if ARDUINO >= 100
     #include "Arduino.h"
    #else
     #include "WProgram.h"
    #endif

    // Uncomment to enable printing out nice debug messages.
    //#define DHT_DEBUG

    // Define where debug output will be printed.
    #define DEBUG_PRINTER Serial

    // Setup debug printing macros.
    #ifdef DHT_DEBUG
      #define DEBUG_PRINT(...) { DEBUG_PRINTER.print(__VA_ARGS__); }
      #define DEBUG_PRINTLN(...) { DEBUG_PRINTER.println(__VA_ARGS__); }
    #else
      #define DEBUG_PRINT(...) {}
      #define DEBUG_PRINTLN(...) {}
    #endif

    // Define types of sensors.
    #define DHT11 11
    #define DHT12 12
    #define DHT22 22
    #define DHT21 21
    #define AM2301 21

    class DHT {
      public:
       DHT(uint8_t pin, uint8_t type, uint8_t count=6);
       void begin(uint8_t usec=55);
       float readTemperature(bool S=false, bool force=false);
       float convertCtoF(float);
       float convertFtoC(float);
       float computeHeatIndex(bool isFahrenheit=true);
       float computeHeatIndex(float temperature, float percentHumidity, bool isFahrenheit=true);
       float readHumidity(bool force=false);
       bool read(bool force=false);

     private:
      uint8_t data[5];
      uint8_t _pin, _type;
      #ifdef __AVR
        // Use direct GPIO access on an 8-bit AVR so keep track of the port and bitmask
        // for the digital pin connected to the DHT.  Other platforms will use digitalRead.
        uint8_t _bit, _port;
      #endif
      uint32_t _lastreadtime, _maxcycles;
      bool _lastresult;
      uint8_t pullTime; // Time (in usec) to pull up data line before reading

      uint32_t expectPulse(bool level);

    };

    class InterruptLock {
      public:
       InterruptLock() {
    #if !defined(ARDUINO_ARCH_NRF52)
        noInterrupts();
    #endif
       }
       ~InterruptLock() {
    #if !defined(ARDUINO_ARCH_NRF52)
        interrupts();
    #endif
       }
    };

    #endif

  [1]: https://github.com/SPEC-Sensors/DGS

title: Two libraries collide. Ambiguous functions/variables?

Answers: 1

body:
The DEBUG_ functions in the DGS class are private and used only in DGS.cpp. They will not collide with the macros from DHT.h

If DHT.h is included before DGS.h, the preprocessor replaces the DEBUG_ function names with the content of the macros from DHT.h and the result doesn't make sense for the compiler.

You could do `#undef DEBUG_PRINT` and `#undef DEBUG_PRINTLN` after DHT.h to undefine the macros for the rest of the sketch. DHT.cpp includes DHT.h and will have the macros defined.


body:
I'm integrating a wind direction- and speed sensor with an Arduino. It communicates over RS485 Modbus RTU, which I don't have any experience with.

The documentation is very short, and it just says:

9600bps, 8 bit, stop bit: 1, check bit: no
Slave address is FFH.

Host Scan Order( slave address 0xFF)
FF **03 00 00 00 02** D1D5

Slave Response
FF **03 04** 00 09 00 3A 0401

The bold parts are fixed, the last two bytes are for checksum.  So the data of the response is direction in the two first bytes (00 09), and then speed in the two after that.

So basically I gotta send that exact byte sequence to the sensor, and then decode what I get. I'm not gonna need to do anything more advanced with this, and so I'm trying to figure out what the most easy way to do this is.

There are different modes, like single, mutliple registry, discrete values, coils, I don't know which one I'm supposed to pick, would be grateful if someone could take the time to explain to me how to do it.

title: Reading a simple sensor with Modbus RTU on Arduino Uno

Answers: 0


body: I want to connect multiple sensors and see their measurements via ESP8266 Web Server. But, the problem is that ESP8266 has only one analog pin and I can't connect multiple sensors to it, so i need to connect it to the Arduino. How can i do that?

title: Connect Arduino and ESP8266 NodeMCU

Answers: 0


body:
EDIT: I think this fits better in the C++ Stack Overflow, so I'm going to re-post this there.

I am working on a menu system with ```#define``` macros (inspired by the Marlin firmware on my 3D printer) I am attempting to generalize each menu item with the macro ```#define MENU_ITEM_EDIT()```. The full code is really long, so I am leaving out chunks of code of compactness. However, you can find the full code here: https://pastebin.com/h24itG9y

``` c++
void draw_row(int row, char* value) { /* Stuff here*/ } // Draws row
char* uiToStr(int x) { /* Stuff here*/ } // Converts unsigned int to a string

#define disp_array(display, value)  display[value]
#define disp_func(display, value)   display(value)
#define disp_char(display, value)   display

#define MENU_ITEM_EDIT(min, max, rate, display, displayType, width, label, value) \
    // A bunch of stuff
    draw_row(rowNum, disp_ ## displayType(display, value)); \
    // More stuff
```

Using the code macro would look like:
``` c++
// Values
const char item1[] = "Item 1", item2[] = "Item 2", item3[] = "Item 3";
const char* const itemList[] = {item1, item2, item3};
int currentItem = 0;
uint8_t item1Val = 10;

void menu1()
{
   START_MENU();
       MENU_ITEM_EDIT(0, 3, 1, itemList, array, 6, "Item:", currentItem);
       MENU_ITEM_EDIT(0, 255, 1, uiToStr, func, 3, "Item 1 Value:", item1Val);
   END_MENU();
}
```

Which displays as:
```
Item:     Item 1
Item 1 Value: 10
```

For convenience in the declarations of my menus, I am trying to use common menu types, such as an ```uint8_t``` that ranges from 0 to 255. Then, in the menu, I would use ```__u255_t``` instead of the first 6 arguments.
``` c++
#define __u255_t 0, 255, 1, uiToStr, func, 3

void menu2()
{
    int item2Val = 10;

    START_MENU();
        MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
    END_MENU();
}
```
Previously, I had it set up such that every time I wanted a different type of menu, even if I would only use it once, I had to define a type for it and how it should evaluate in the macro. This way, I can use 1 argument instead of 6 for commonly recurring types in rows. However, I still want the ability to use the 6 argument option when I have a row that has a unique set of arguments, such as a different range or list of display strings.

However, in this example, the program won't compile because it places ```__u255_t``` into ```min``` in the ```MENU_ITEM_EDIT()``` macro, rather than expanding ```__u255_t``` into its 6 values and placing them into the first 6 arguments of ```MENU_ITEM_EDIT()```. The macro evaluates as:

``` c++
MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
// Evaluates as:
MENU_ITEM_EDIT( (0, 255, 1, uiToStr, func, 3), "Item 2 Value", item2val, , , , , );
```
Note: I put an extra set of parentheses to make it more clear to understand.

But I want:
``` c++
MENU_ITEM_EDIT(__u255_t, "Item 2 Value", item2Val);
// Evaluates as:
MENU_ITEM_EDIT(0, 255, 1, uiToStr, func, 3, "Item 2 Value", item2Val);
```

I thought about using a ```struct```, however I'm not sure that I can because depending on the row, the ```value``` string in ```draw_row()``` could be a function or an array. Does anyone have any advice on how to solve this problem?

Also, please let me know if I need to add any more code to make my problem more clear.

title: Order of Evaluation for #define Macros

Answers: 1

body:
You need to turn your macro itself into a macro. Sounds odd, I know.  But take the following example:

    #define foo bar, baz
    #define foobar(X, Y, Z) something(X, Y, Z);
    #define boofar(...) foobar(__VA_ARGS__)

    boofar(foo, 4)

`boofar` is a macro that takes a variable argument list.  That expands out into a call for your actual macro call, expanding `foo` in the process.  Then your actual macro gets expanded out with the real arguments already in here. The point here is that `foo` is expanded *before* being passed to the macro that needs the multiple arguments that are inside `foo`.

So the expansion chain is actually:

    boofar(foo, 4) ->
    foobar(bar, baz, 4) ->
    something(bar, baz, 4);

Running it through `cpp` and you get:

    # 1 "t.c"
    # 1 "<built-in>"
    # 1 "<command-line>"
    # 31 "<command-line>"
    # 1 "/usr/include/stdc-predef.h" 1 3 4
    # 32 "<command-line>" 2
    # 1 "t.c"

    something(bar, baz, 4);


body: I've searched this and have only found solutions for **receiving data FROM Arduino TO android**, **I need the opposite**. I basically need to figure out how to press a button from my android phone that will activate the hardware attached to my arduino mega 2560 AND make it where my arduino can read sensor values from the android device. I'm not an expert with android or arduino, most of the code I already have pertaining to the USB Serial connection is from GitHub.

title: Sending sensor data from Android app to arduino via USB Serial

Answers: 0


body:
So I set up an Arduino circuit that while a button was pressed, a sound effect would play and an LED would activate until I stopped pressing the button. Since I didn't use a micro sd card module, I had to use [wav2c][1] to convert the audio to numeric values that I then used the code [here][2] to implement the audio. The numeric values for the audio were placed in a header file that was referenced in the code. The code and my circuit work but I want to see if I can use one of my new ATTiny85's to run the code and perform the same operations as the Arduino did. I have set up my Arduino Mega 2560 to program the ATTiny85. I have tested it with Blink and it works. However, after I had moved the pins of the speaker, LED, and button to those of the ATTin85 and edited the appropriate code, it will not upload to the ATTiny85. It gives error messages that certain variables have not been declared in this scope. One such is "TCCR1B" and when I comment it out, it claims another variable has not been declared in this scope. Any idea how I can overcome this and if it's even possible to use the ATTiny in this capacity?

The Code I tried uploading to the ATTiny85
<!-- language-all: lang-cpp -->

    #include <stdint.h>
    #include <avr/interrupt.h>
    #include <avr/io.h>
    #include <avr/pgmspace.h>

    #define SAMPLE_RATE 20000
    #include "Test.h"

    int ledPin = 0;
    int speakerPin = 1; // Can be either 3 or 11, two PWM outputs connected to Timer 2
    const byte pinSwitch1 = 2;
    volatile uint16_t sample;
    byte lastSample;
    int buttonState = 0;
    const byte interruptPin = 2;
    volatile byte state = LOW;

    void stopPlayback()
    {
        digitalWrite(ledPin, LOW);
        // Disable playback per-sample interrupt.
        TIMSK1 &= ~_BV(OCIE1A);

        // Disable the per-sample timer completely.
        TCCR1B &= ~_BV(CS10);

        // Disable the PWM timer.
        TCCR2B &= ~_BV(CS10);

        digitalWrite(speakerPin, LOW);
    }

    // This is called at 8000 Hz to load the next sample.
    ISR(TIMER1_COMPA_vect) {
        if (sample >= sounddata_length) {
            if (sample == sounddata_length + lastSample) {
                stopPlayback();
            }
            else {
                if(speakerPin==11){
                    // Ramp down to zero to reduce the click at the end of playback.
                    OCR2A = sounddata_length + lastSample - sample;
                } else {
                    OCR2B = sounddata_length + lastSample - sample;
                }
            }
        }
        else {
            if(speakerPin==11){
                OCR2A = pgm_read_byte(&sounddata_data[sample]);
            } else {
                OCR2B = pgm_read_byte(&sounddata_data[sample]);
            }
        }

        ++sample;
    }

    void startPlayback()
    {
        digitalWrite(ledPin, HIGH);
        pinMode(speakerPin, OUTPUT);

        // Set up Timer 2 to do pulse width modulation on the speaker
        // pin.

        // Use internal clock (datasheet p.160)
        ASSR &= ~(_BV(EXCLK) | _BV(AS2));

        // Set fast PWM mode  (p.157)
        TCCR2A |= _BV(WGM21) | _BV(WGM20);
        TCCR2B &= ~_BV(WGM22);

        if(speakerPin==11){
            // Do non-inverting PWM on pin OC2A (p.155)
            // On the Arduino this is pin 11.
            TCCR2A = (TCCR2A | _BV(COM2A1)) & ~_BV(COM2A0);
            TCCR2A &= ~(_BV(COM2B1) | _BV(COM2B0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2A = pgm_read_byte(&sounddata_data[0]);
        } else {
            // Do non-inverting PWM on pin OC2B (p.155)
            // On the Arduino this is pin 3.
            TCCR2A = (TCCR2A | _BV(COM2B1)) & ~_BV(COM2B0);
            TCCR2A &= ~(_BV(COM2A1) | _BV(COM2A0));
            // No prescaler (p.158)
            TCCR2B = (TCCR2B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

            // Set initial pulse width to the first sample.
            OCR2B = pgm_read_byte(&sounddata_data[0]);
        }

        // Set up Timer 1 to send a sample every interrupt.

        cli();

        // Set CTC mode (Clear Timer on Compare Match) (p.133)
        // Have to set OCR1A *after*, otherwise it gets reset to 0!
        TCCR1B = (TCCR1B & ~_BV(WGM13)) | _BV(WGM12);
        TCCR1A = TCCR1A & ~(_BV(WGM11) | _BV(WGM10));

        // No prescaler (p.134)
        TCCR1B = (TCCR1B & ~(_BV(CS12) | _BV(CS11))) | _BV(CS10);

        // Set the compare register (OCR1A).
        // OCR1A is a 16-bit register, so we have to do this with
        // interrupts disabled to be safe.
        OCR1A = F_CPU / SAMPLE_RATE;    // 16e6 / 8000 = 2000

        // Enable interrupt when TCNT1 == OCR1A (p.136)
        TIMSK1 |= _BV(OCIE1A);

        lastSample = pgm_read_byte(&sounddata_data[sounddata_length-1]);
        sample = 0;
        sei();
            //digitalWrite(ledPin, HIGH);
            //delay(1000);
            //digitalWrite(ledPin, LOW);
    }

    void setup()
    {
        pinMode( pinSwitch1, INPUT );
        pinMode(ledPin, OUTPUT);
        pinMode(interruptPin, INPUT_PULLUP);
        attachInterrupt(digitalPinToInterrupt(interruptPin), stopPlayback, CHANGE);

    }

    void loop()
    {
    //startPlayback();
    //delay(5000);
    //stopPlayback();
    buttonState = digitalRead(pinSwitch1);

    stopPlayback();

    if (buttonState == LOW) {
        startPlayback();
        delay(1150);

    }

    }

The header file with the audio

    #ifndef _HEADERFILE_H    // Put these two lines at the top of your file.
    #define _HEADERFILE_H    // (Use a suitable name, usually based on the file name.)

    const int sounddata_length=32000;
    //const int sounddata_sampleRate=20000;

    const unsigned char sounddata_data[] PROGMEM = {
      15,1,49,0,150,0,138,0,219,255,133,0,176,0,15,1,210,

    //There are a lot more numbers in here to generate the audio but I cut most out to save space

    };

    #endif // _HEADERFILE_H    // Put this line at the end of your file.

  [1]: https://github.com/olleolleolle/wav2c
  [2]: https://playground.arduino.cc/Code/PCMAudio/

title: How can I adapt this code for the ATTiny85?

Answers: 1

body:
As @delta_G pointed out, this code is written specifically to access the timer hardware on the chip, and the ATTINY85 has different timer hardware.

It would not be hard to change this code to work with your just need to output the next step in the list of audio values 8000 timer per second.

There are two ways you could do this...

1. You could figure out the corresponding settings for the ATTINY85 timer hardware and use those instead. The timer registers are documented in the ATTINY85 datasheets and you can google lots of info on how to set those registers, but it is complicated.

2. You can bit-bang the audio data out though a digital pin. Bing banging means you write code that manually sets the pin high or low at the appropriate times.

Since it does not look like you need to do anything else while the sound is playing, I think bit banging is the simpler approach here.

Do do bit banging, you get rid of the start and end playback functions and instal have a playSound() function that looks something like this...

```
void playSound() {
    pinMode(speakerPin, OUTPUT);  // This really belongs in setup()
    for(unsigned sample=0; sample<sounddata_length; sample++) {      // step though the audio samples
        sample_value=pgm_read_byte(&sounddata_data[sample])/2;    // grab next value from array in flash

        // Note that we divide the value by 2. This is because our target rate is
        // 8000 samples per second, which is 125us per sample. Each sample value is 0-255, so /2 gives us
        // a value 0-127. If we spend about 127us on each sample then we are in the right ballpark
        // for playback speed (ok, a bit slow).

        digitalWrite( speakerPin , 1);     // poor man's single cycle bitbang PWM
        _delay_us( sample_value );
        digitalWrite( speakerPin , 0);
        _delay_us( 127-sample_value );

     }

    }
}
```

This is just pseudo code and I have not checked to see if this even compiles, but you should get the idea.

This is also a hack, so it does not take into account how long the digitalWrite() takes
or the overhead of the loop. It also explicitly stretches the sample time from 125us to 127us for math simplicity and speed (dividing the 0-255 by 2 is very fast). All these will likely make the playback sound slow and low, but i'm not sure how much.

I also do not take into account that the playback can get interrupted which would cause audio glitches. You can fix this by putting cli()/sei() around the playSound() code.

Finally, each sample only gets a single PWM cycle so I don't expect audio to be CD quality, but maybe good enough. If you need more PWM cycles then there are ways to do this, but then probably better to use the hardware timer.

LMK if you can get this working (post a video!) or have any questions!


body: I connected 5V to GND accidentally (connect directly, no LED, no motor). Now the LED on the board doesn't light up and power LED lights up but it is not bright. The 5V output pin is only around 1.98V. I'm using clone version from Alibaba. I ordered two, one is still working but the shorted one doesn't work. May I know how to fix them?

title: How to fix when i shorted 5v to gnd accidentally (Arduino Nano)

Answers: 1

body: I would say that to repair an Arduino Nano clone yourself, if ICs/SMD parts are damaged, is not worth the effort, if you could do it at all (first having to find out which parts need to be replaced, carefully de-soldering the delicate SMD parts, then putting new parts in place, etc.).


body:
I am only replacing a portion of my code where I want to use the first method but as you can see it is making my sketch size little bigger

<!-- language: c -->

    //if(iBPM >= 40 || iBPM <= 170 )
          {
          char iBPMwav[50];
          String thisString = String(iBPM);
          String stringThree =  "n" + thisString;
          stringThree =  stringThree + ".wav";
          stringThree.toCharArray(iBPMwav, 50);
          tmrpcm.play(iBPMwav);
          }

**`Sketch uses 29678 bytes (100%)`**

This is simple but at the end, I want to go from the number 40 up to 170, and this is why I want to use the first method.

<!-- language: c -->

    //if(iBPM >= 40 || iBPM <= 170 )
      {
          if(iBPM == 71)
    tmrpcm.play("n71.wav");
      else if(iBPM == 72)
    tmrpcm.play("n72.wav");
      else if(iBPM == 73)
    tmrpcm.play("n73.wav");
      else if(iBPM == 74)
    tmrpcm.play("n74.wav");
      else if(iBPM == 75)
    tmrpcm.play("n75.wav");
      else if(iBPM == 76)
    tmrpcm.play("n76.wav");
      else if(iBPM == 77)
    tmrpcm.play("n77.wav");
      else if(iBPM == 78)
    tmrpcm.play("n78.wav");
      else if(iBPM == 79)
    tmrpcm.play("n79.wav");
      else if(iBPM == 80)
    tmrpcm.play("n80.wav");
      else if(iBPM == 81)
    tmrpcm.play("n81.wav");
      else if(iBPM == 82)
    tmrpcm.play("n82.wav");
      else if(iBPM == 83)
    tmrpcm.play("n83.wav");
      else if(iBPM == 84)
    tmrpcm.play("n84.wav");
      else if(iBPM == 85)
    tmrpcm.play("n85.wav");
      else if(iBPM == 86)
    tmrpcm.play("n86.wav");
      else if(iBPM == 87)
    tmrpcm.play("n87.wav");
      else if(iBPM == 89)
    tmrpcm.play("n89.wav");
      else if(iBPM == 90)
    tmrpcm.play("n90.wav");
      else if(iBPM == 91)
    tmrpcm.play("n91.wav");
      else if(iBPM == 92)
    tmrpcm.play("n92.wav");
      else if(iBPM == 93)
    tmrpcm.play("n93.wav");
      else if(iBPM == 94)
    tmrpcm.play("n94.wav");
      else if(iBPM == 95)
    tmrpcm.play("n95.wav");
      else if(iBPM == 96)
    tmrpcm.play("n96.wav");
      else if(iBPM == 97)
    tmrpcm.play("n97.wav");
      else if(iBPM == 98)
    tmrpcm.play("n98.wav");
      else if(iBPM == 99)
    tmrpcm.play("n99.wav");
      else if(iBPM == 100)
    tmrpcm.play("n100.wav");
      else if(iBPM == 101)
    tmrpcm.play("n101.wav");
      else if(iBPM == 102)
    tmrpcm.play("n102.wav");
    else
     tmrpcm.play("n170.wav");
    }

**`Sketch uses 29024 bytes (101%)`**

title: Why does this take more byte?

Answers: 2

body:
I suggest having simpler file names (same size, always 3 digit numbers)

    /// Return a text "n000.wav" ... "n255.wav"
    /// depending on the parameter
    char* makeFileName(byte i) {
      static char name[9] = "nxxx.wav";
      byte digit = i/100;
      name[1] = '0' + digit;
      i -= digit*100;
      digit = i/10;
      name[2] = '0' + digit;
      i -= digit*10;
      name[3] = '0' + i;

      return name;
    }

body:
While the Strings class makes a C/C++ program easy to understand and maintain, as stated in the comments, using the Strings class is a memory intensive option which should be should be avoided when memory is in short supply.  Such as on the embedded processors used in most Arduino platforms.

Here are 2 examples where Stings is used and not used.  Note the reduction from 2326 bytes to 734 bytes of program memory necessary to store the sketch in the embedded processor.

    void setup()
    {
    }

    void loop()
    {
      uint8_t iBPM;
      uint8_t pointer;
      for(iBPM = 40; iBPM <= 170; iBPM++)
      {
        char iBPMwav[50];
        String thisString = String(iBPM);
        String stringThree =  "n" + thisString;
        stringThree =  stringThree + ".wav";
        stringThree.toCharArray(iBPMwav, 50);
    //  tmrpcm.play(iBPMwav);
      }
    }

Sketch uses 2326 bytes (7%) of program storage space. Maximum is 32256 bytes. Global variables use 27 bytes (1%) of dynamic memory...

    void setup()
    {
    }

    void loop()
    {
      uint8_t iBPM;
      uint8_t pointer;
      for(iBPM = 40; iBPM <= 170; iBPM++)
      {
        char iBPMwav[50];
        pointer = 0;
        char temp_str[10];
    //  String thisString = String(iBPM);
    //  String stringThree =  "n" + thisString;
    //  stringThree =  stringThree + ".wav";
    //  stringThree.toCharArray(iBPMwav, 50);
        itoa(iBPM, temp_str, 10);
        if(iBPM < 100)
        {
          strncpy(&iBPMwav[pointer],"n0",2);
          pointer += 2;
          strncpy(&iBPMwav[pointer],temp_str,2);
          pointer += 2;
        }
        else
        {
          strncpy(&iBPMwav[pointer],"n",1);
          pointer += 1;
          strncpy(&iBPMwav[pointer],temp_str,3);
          pointer += 3;
        }
        strncpy(&iBPMwav[pointer],".wav",4);
    //  tmrpcm.play(iBPMwav);
      }
    }

Sketch uses 734 bytes (2%) of program storage space. Maximum is 32256 bytes. Global variables use 15 bytes (0%) of dynamic memory...


body:
[![enter image description here][1]][1]Hello friends

I'm working on a light detection system for the higher secondary summer term project, for which I'm using a simple Arduino board, Adafruit 16-Bit ADC, an LDR with some resisters, a 5V USB power source either the computer USB 2.0 port or a mobile power bank 5V-500mA/1A/2.1A, a USB mobile charging cable (not the data cable) and a Bluetooth module to communicate with Arduino system, an android or a computer (different from Arduino power source) to record the data.

The difference in maximum and minimum response is very poor when replacing the power source from the computer USB to power bank USB. With the same environmental and experimental conditions, the response goes from 50000 to 45000 counts (the changes in response are 5000 counts) with the power bank. For the same situations, the response goes from 50000 to 5000 counts (the changes are 45000) with the computer power source which is more suitable but it's better to use a small power supply.

How can I get the better and stable response? Kindly help me to solve out this issue. Thank you.

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

title: light detection system: Response different from power bank and computer system

Answers: 1

body:
Based on limited knowledge of the design and limited knowledge of the requirements here are 3 possible reasons.  More may exist.

1. The [USB 2.0 definition][1] stats such a port provide 0.5A of current.  Some devices limit the current as a precaution.  Therefor the battery may provide more current then the USB source.  The type of USB source was not specified and no voltage measurement data was provided.

2. How fast does the device need to react to a change in light level?  A [light-dependent resistor or LDR][2] can have a latency of as much as a second with respect to light level changes.

3. With regards to the 16 bit ADC.  What precautions have been made with regards to precisely controlling the ADC's voltage reference?  Any fluctuation can cause large errors.  What precautions have been made with regards to filtering out the ADC's random noise?  For example, [many ADCs only have a fraction of their resolution if averaging is not used][3].

  [1]: https://en.wikipedia.org/wiki/USB
  [2]: https://en.wikipedia.org/wiki/Photoresistor
  [3]: https://www.cypress.com/file/236481/download


body:
The board does reconnect from time to time, but there are times where it just disconnects and never reconnects again and I can't replicate the error because while I run it with Serial open and turn ON and OFF my WiFis it always reconnects as it should.

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

    #include <ArduinoHttpClient.h>
    #include <WiFiNINA.h>
    #include <EmonLib.h>

    EnergyMonitor emon1;
    EnergyMonitor emon2;
    EnergyMonitor emon3;
    int INTERVAL = 60;
    int last_code = 0;

    char ssid[] = "MySSID";
    char pass[] = "MyPW";

    String ID = "Garden_Pump_Sensor";

    int sequence = 0;
    double kWh = 0.0;

    char serverAddress[] = "192.168.1.108";  // server address
    int port = 5005;

    WiFiClient wifi;
    HttpClient client = HttpClient(wifi, serverAddress, port);

    int status = WL_IDLE_STATUS;

    void setup() {
      Serial.begin(9600);
      analogReadResolution(9);
      emon1.current(0, 100);
      emon2.current(5, 100);
      emon3.current(6, 100);
      Connecting();
    }

    void Connecting() {
      int tries = 4;
      while ( (WiFi.status() != WL_CONNECTED && tries > 0) || last_code != 200) {
        Serial.print("Status #1: ");
        Serial.println(WiFi.status());
        WiFi.begin(ssid, pass);
        Serial.print("Status #2: ");
        Serial.println(WiFi.status());
        tries--;
        last_code = 200;
      }

      Serial.print("SSID: ");
      Serial.println(WiFi.SSID());
      IPAddress ip = WiFi.localIP();
      Serial.print("IP Address: ");
      Serial.println(ip);
    }

    void reconnecting() {
      if (WiFi.status() != 3  || (WiFi.RSSI() <= -90) || (WiFi.RSSI() == 0) || last_code != 200) {
        WiFi.end();
        Connecting();
      }
    }

    void loop() {
      unsigned long delayTime = INTERVAL * 1000;
      unsigned long time_start = millis();

      DataMonitorAndSend();

      unsigned long time_final = millis() - time_start;
      unsigned long delay_value = delayTime - time_final;
      Serial.println(delay_value);
      if (delay_value < 1  || delay_value > delayTime) {
        return;
      } else {
        delay(delay_value);
      }

    }

    void DataMonitorAndSend() {
      reconnecting();

      Serial.println("making POST request");
      String contentType = "application/json";
      kWh = kWh + getKWH();
      String postData = "{\"ID\": \""+ID+"\",\"seq\": " + String(sequence) + ",\"kWh\": " + String(kWh, 6) + "}";
      Serial.print("data: ");
      Serial.println(postData);

      client.setHttpResponseTimeout(5 * 1000);
      client.post("/receivedata/", contentType, postData);

      // read the status code and body of the response
      int statusCode = client.responseStatusCode();
      String response = client.responseBody();

      Serial.print("Status code: ");
      Serial.println(statusCode);
      if (statusCode == 200) {
        kWh = 0;
        sequence++;
      }
      last_code = statusCode;
      Serial.print("Response: ");
      Serial.println(response);

    }

    double getKWH() {
      int LOOPS = 15;
      double kWh_Total = 0.0;
      unsigned long delayTime_kwh = 2 * 1000;
      for (int i = 0; i < LOOPS; i++) {
        unsigned long time_start_kwh = millis();

        double Irms1 = emon1.calcIrms(600);
        if (Irms1 < 0.3) Irms1 = 0;
        double Watt1 = (Irms1 * 230) / 1000;

        double Irms2 = emon2.calcIrms(600);
        if (Irms2 < 0.3) Irms2 = 0;
        double Watt2 = (Irms2 * 230) / 1000;

        double Irms3 = emon3.calcIrms(600);
        if (Irms3 < 0.3) Irms3 = 0;
        double Watt3 = (Irms3 * 230) / 1000;

        kWh_Total = kWh_Total + ((Watt1 + Watt2 + Watt3) / 60);

        unsigned long time_final_kwh = millis() - time_start_kwh;
        unsigned long delay_value_kwh = delayTime_kwh - time_final_kwh;
        if (delay_value_kwh < 0  || delay_value_kwh > delayTime_kwh) {
          delay(0);
        } else {
          delay(delay_value_kwh);
        }

      }

      return kWh_Total / LOOPS;
    }

Feel free to ignore the `getkWH()`, it's code related to power consumption. Also the firmware is up to date and the server is using a static IP.

title: MKR1010 disconnects and reconnects normally until it reaches a point where it never reconnects again

Answers: 2

body:
I found that before using WiFi.begin() to re-connect, one needs to use WiFi.disconnect() first. At least that keeps my set-up reliably re-connecting, when its battery is empty or my router is out for a moment. Also, testing for WL_CONNECTED or 3 only means that one's set-up is connected to the router, but the router not necessarily yet to the internet; in case of a restart of the router after a power outage. On one of my routers, one has to wait 10 seconds, on another 18 seconds.

```
void connectToWLAN()
{
  // Check if the AirLift FeatherWing's WLAN module works
  if (WiFi.status() == WL_NO_MODULE)
  {
    Serial.println("Connection to AirLift FeatherWing WLAN module failed");

    // If not, indicate there is a WLAN module malfunction
    WiFi.setLEDs(0, 255, 0); // Red

    // And stop forever
    while (true);
  }

  // Return to loop() if already connected to the WLAN router
  if (WiFi.status() == WL_CONNECTED)
  {
    return;
  }

  Serial.println("Trying to connect to WLAN router");

  // Indicate there is no WLAN router connection just yet
  WiFi.setLEDs(192, 255, 0); // Yellow

  do
  {
    // Start connection to WLAN router and print a status value
    WiFi.disconnect();
    delay(1000);

    status = WiFi.begin(WLAN_SSID, WLAN_PASS);
    // WL_IDLE_STATUS     = 0
    // WL_NO_SSID_AVAIL   = 1
    // WL_SCAN_COMPLETED  = 2
    // WL_CONNECTED       = 3
    // WL_CONNECT_FAILED  = 4
    // WL_CONNECTION_LOST = 5
    // WL_DISCONNECTED    = 6
    Serial.println(WiFi.status());
    delay(10000);
  }
  while (status != WL_CONNECTED);

  Serial.println("Connection to WLAN router successful");

  // Indicate that the WLAN router connection was established
  WiFi.setLEDs(255, 0, 0); // Green

  // To better see the status indicating RGB LED's state
  delay(2000);
}

body:
Since you only send a data every 60s, it is better to only establish a WiFi when you need it, AND only create an instance of HttpClient after that. That's means that it only creating the `wifi` and `client` instances when you need it instead of using a global instances. Here is a way I usually do for such an application that I modified based on your sketch, you could give it a try. Please noted that only the  changes that I made are highlighted in my code snippet, please fill-in the rest of your code:

```
unsigned long INTERVAL = 60000;  // in milliseconds
unsigned long time_start = millis() + INTERVAL;    // noted that I changed this to a global variable and to unsigned long

// WiFiClient wifi;
// HttpClient client = HttpClient(wifi, serverAddress, port);

void Connecting() {
  WiFi.disconnect();
  WiFi.begin(ssid, pass);
  Serial.print("Connecting to ");
  Serial.print(ssid);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(1000);
  }
  Serial.println(" Connected");

  // your code for printing localIP
}

void loop() {

  if (WiFi.status() != WL_CONNECTED)
    connecting();

  // send data when INTERVAL is reached
  if (millis() - time_start > INTERVAL) {
    DataMonitorAndSend();
    time_start = millis();
  }

  yield();

}

void DataMonitorAndSend() {
  // reconnecting();

  WiFiClient wifi;
  HttpClient client = HttpClient(wifi, serverAddress, port);

  // rest of your DataMinitorAndSend() code

  client.end();

}
```


body:
I am part of a product group that is developing a low cost wireless intrusion detection system, for home usage.

We have already produced and delivered to market ESP8266 based product however for the new thing, we need the chipset to be able to enter promiscuous mode and receive/inject 802.11 packets on the fly without any limits.

ESP8266 is limited to 112bytes max, which is not enough to even parse the Beacon frame properly.

What are the alternatives for ESP8266 currently - that allow:

- to capture the 802.11 frames
- have no packet length limits
- allow packet injection

Ps. doesn't have to be ARDUINO - but needs to be C/C++ programmable.

Thanks in advance.

title: Which of the ESP8266 alternatives allows for full packet capture/injection in promiscuous mode?

Answers: 0


body:
I'm trying to build a battery operated hand lantern. It has the Arduino, an MPU6050 accelerometer, and 4 APA106 (WS2812B-like) LEDs.

If everything's powered through the Arduino's 5V pins, that's 80mA for the [Arduino](https://forum.arduino.cc/index.php?topic=135872.msg1021818#msg1021818), 240mA for the [4 LEDs](https://docs.audectra.com/guides/hardware/led-power-consumption/), and let's round up to 5 mA for the [MPU6050](https://store.invensense.com/datasheets/invensense/MPU-6050_DataSheet_V3 4.pdf).

If I'm using 5x AA batteries for 7.5V (at full charge) that should be 2.5V * 325mA of power wasted or just under a watt that'll be heating up the regulator? I'm not sure if that's huge or tiny or in between or what.
What's the most sane way to power this device for an absolute newbie?

title: How to keep the regulator cool while battery powering the arduino and accessories?

Answers: 3

body: Use en external voltage regulator (go switch-mode if you care about battery life) that is adequately cooled.

body:
1W is near the limit of what a small LDO can handle. It will get considerably hot.

I would use 4 batteries instead of 5, and a 3.3V Arduino clone instead of the UNO, and power the LEDs directly from the batteries. You could also use your original UNO, feeding it with 6V on a 5V pin through a simple diode, which would drop it to something like 5.4..5.3V.

body:
I suggest using a DC-DC buck/boost voltage regulator. Those can take a wide range of input voltages and put out an adjustable output voltage

[This one on Amazon][1], for example, can take an input of 3-40V and provide an output of 1.5-35V(Adjustable). It is a switching power supply, so it should not produce much waste heat. That one is rated at 2A, or 3A if you add a heat-sink.

You could feed the regulated 5V into the USB connector on your Arduino, and to your other components as well. (Just take a USB cable, cut it, and tie the red and black wires to ground and +5V, respectively.

You might need a filtering capacitor to protect the Arduino from voltage variations as the load on the power supply changes.

  [1]: https://www.amazon.com/Ultra-small-adjustable-Compatible-Atomic-Market/dp/B00TMFKJ9Q/ref=asc_df_B00TMFKJ9Q/?tag=hyprod-20&linkCode=df0&hvadid=198062682203&hvpos=1o3&hvnetw=g&hvrand=14377977594083820282&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9008140&hvtargid=pla-319814629648&psc=1


body:
I'm using a [ItsyBitsy 32u4](https://www.adafruit.com/product/3677), Adafruit says it can act as a USB HID keyboard. The mc is based on the 32u4 which the [Keyboard](https://www.arduino.cc/reference/en/language/functions/usb/keyboard/) docs say are supported.

I have a simple sketch that prints "A" every second and should press "A". When I upload the sketch and connect to the serial port I see the print output but I don't get any key presses.

Any ideas? I'm on linux, I suspect that the controller doesn't register as a HID device, maybe I need UDEV rules or drivers?

EDIT: the keyboard works on a different computer.

<!-- language-all: lang-cpp -->
```
#include <Keyboard.h>
void setup() {
  Serial.begin(9600);
  Keyboard.begin();
  Serial.println("Start");
}

void loop() {
  Serial.println("a");
  Keyboard.write('a');
  delay(1000);
}
```

title: Arduino HID keyboard does not work

Answers: 2

body:
Keyboard.press() expects a character, but you are passing a character array. Also Keyboard.press() only presses but does not release the key. Keyboard.releaseAll() can be used to release all keys.

I would try:

    Keyboard.press('A') ;  //note the ' instead of "
    Keyboard.releaseAll();

or preferably:

    Keyboard.write('A');   //handles press and release of basic keys

body:
There was some issue with my laptop, not controller or the sketch.

I tried the my board with another computer and it worked. I tried a commercial keyboard on my first computer it also didn't work.

Both keyboards work after a reboot.


body:
I wrote a code to generate 1kHz Phase and frequency correct PWM signal from Arduino mega 2560 using timer 4. When I try the code with fast PWM mode it works perfectly. But phase correct mode didn't provide the expected outcome. What is wrong with my code?
<!-- language-all: lang-cpp -->

    unsigned int b=7999;
    void setup() {
    pinMode(6,OUTPUT);
    pinMode(7,OUTPUT);

    TCCR4A=0;
    TCCR4B=0;
    //Timer 1 1kHz mode 8: phase and frequency correct pwm oc1a non inverting

    TCCR4A=(1<<COM4A1)|(0<<COM4A0)|(0<<WGM41) ;//| (0<<WGM40)
    TCCR4B=(1<<WGM43)|(0<<WGM42);//
    ICR4=b;
    OCR4A=int(b*1/5);
    TCCR4B|=(1<<CS10);
    TIMSK4 |=(1<<OCIE4A);
    }

    void loop() {
      }

    ISR(TIMER_COMPA_vect){

      }
The output of the code for different duty cycles are as below
**Duty cycle:0.2 (OCR4A=b/5)**
[![enter image description here][1]][1]

**Duty cycle:0.2 (OCR4A=b/2)**[![enter image description here][2]][2]

  [1]: https://i.stack.imgur.com/VHwhd.png
  [2]: https://i.stack.imgur.com/dRlOd.png

title: Phase and frequency correct PWM mode Arduino Mega 2560

Answers: 1

body:
You wrote:

> `TIMSK4 |= (1<<OCIE4A);`

and then never defined `ISR(TIMER4_COMPA_vect)`. As soon as you get a
compare match, you get a bad interrupt, which defaults to resetting your
program and restarting again from reset vector.


body: To calculate an operation execution time, I was saving the `millis()` result before and after the operation to calculate the interval time. Is there an alternative on the Arduino Uno like the RDTSC found on x86 architectures?

title: RDTSC alternative for Arduino

Answers: 1

body:
There are several alternatives. The best choice for you depends on the
time resolution you need and the maximum duration you may want to
measure:

1. `millis()` is good for slow things. It has a resolution of 2 ms
   (it increments by steps of 1 ms most of the time, but 2 ms
   occasionally) and can measure durations as long as 49.7 days.

2. `micros()` is the easy choice for when you want more resolution for
   faster things. It increments in steps of 4 µs and is limited to
   about 71.6 minutes.

3. For very fast things, you can get single-cycle resolution if you
   configure Timer 1 to count at the full CPU speed, assuming you
   don't need the timer for something else. But beware the timer will
   roll over roughly every 4.1 milliseconds.

4. You could also use Timer 1 with the prescaler set at ÷8 in order
   to expand the measurable range to 32.8 ms, at the cost of a
   degraded resolution.

Here is a table summing up the available methods, sorted by resolution:

    method        data type  resolution  max. duration
    --------------------------------------------------
    millis()       uint32_t        2 ms     49.7 days
    micros()       uint32_t        4 µs     71.6 min
    Timer 1 (÷8)   uint16_t      0.5 µs     32.8 ms
    Timer 1 (÷1)   uint16_t     62.5 ns      4.1 ms


body:
I am working on a project in making a timer socket using Arduino and a current sensor. For the code I decided to modify a code that was meant to be a [kitchen timer][1].

In that code I found a statement

`currentMode = currentMode == MODE_IDLE ? MODE_RUNNING : MODE_IDLE;`

I assumed this works in a way that it chose whether the timer is in the current mode or the idle mode but I don’t understand the mechanism behind it.
What does this statement mean?

  [1]: https://create.arduino.cc/projecthub/i-and-myself/arduino-kitchen-timer-db8ba6

title: A confusing condition statements

Answers: 1

body:
Assuming you understand how the ternary operator works, the statement is simply toggling the currentmode between its two possible settings.

if you do not understand ternary operators, it can be re-written as:

```C
if (currentMode == MODE_IDLE) {
  currentMode = MODE_RUNNING;
} else {
  currentMode = MODE_IDLE;
}
```

You should read up on the `ternary` operator.  It appears in several languages in various formats and can come in handy in a variety of situations.

In general terms the ternary operator is of the following form (as used in an assignment):

```C
result = (booleanExpression) ? (value if true) : (value if false);
```
but you can use it in other contexts for example in a function call:
```C
someFn(booleanExpression ? trueValue : falseValue);
```