message:
Issue with Arduino car bot, the servo motor moves randomly also it turns hot pretty quickly

I trying to create an Arduino avoiding obstacle car. Using Arduino Uno +shield (sensor sheild v5.0). The problem is that when I upload the code, the servo moves randomly (it doesn't rotate to the right) and becomes hot quickly, it is an SG90 with 5v. I have already checked several times and the hardware seems all right.

I have tried to change the angle of the servo, checked the pins several times - uploaded the code many times I have also used serial.prints. researched on the internet.
<!-- language-all: lang-cpp -->

    #include <NewPing.h>        //Ultrasonic sensor function library. You must install this library

    //our L298N control pins
    const int LeftMotorForward = 5;
    const int LeftMotorBackward = 4;
    const int RightMotorForward = 1;
    const int RightMotorBackward = 0;

    //sensor pins
    #define trig_pin A1 //analog input 1
    #define echo_pin A2 //analog input 2

    #define maximum_distance 200
    boolean goesForward = false;
    int distance = 100;

    NewPing sonar(trig_pin, echo_pin, maximum_distance); //sensor function
    Servo servo_motor; //our servo name

    void setup(){

      pinMode(RightMotorForward, OUTPUT);
      pinMode(LeftMotorForward, OUTPUT);
      pinMode(LeftMotorBackward, OUTPUT);
      pinMode(RightMotorBackward, OUTPUT);

      servo_motor.attach(11); //our servo pin

      servo_motor.write(90);
      delay(2000);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
      distance = readPing();
      delay(100);
    }

    void loop(){

      int distanceRight = 0;
      int distanceLeft = 0;
      delay(50);

      if (distance <= 20){
        moveStop();
        delay(300);
        moveBackward();
        delay(400);
        moveStop();
        delay(300);
        distanceRight = lookRight();
        delay(300);
        distanceLeft = lookLeft();
        delay(300);

        if (distance >= distanceLeft){
          turnRight();
          moveStop();
        }
        else{
          turnLeft();
          moveStop();
        }
      }
      else{
        moveForward();
      }
        distance = readPing();
    }

    int lookRight(){
      servo_motor.write(10);
      delay(500);
      int distance = readPing();
      delay(100);
      servo_motor.write(90);
      return distance;
    }

    int lookLeft(){
      servo_motor.write(170);
      delay(500);
      int distance = readPing();
      delay(100);
      servo_motor.write(90);
      return distance;
      delay(100);
    }

    int readPing(){
      delay(70);
      int cm = sonar.ping_cm();
      if (cm==0){
        cm=250;
      }
      return cm;
    }

    void moveStop(){

      digitalWrite(RightMotorForward, LOW);
      digitalWrite(LeftMotorForward, LOW);
      digitalWrite(RightMotorBackward, LOW);
      digitalWrite(LeftMotorBackward, LOW);
    }

    void moveForward(){

      if(!goesForward){

        goesForward=true;

        digitalWrite(LeftMotorForward, HIGH);
        digitalWrite(RightMotorForward, HIGH);

        digitalWrite(LeftMotorBackward, LOW);
        digitalWrite(RightMotorBackward, LOW);
      }
    }

    void moveBackward(){

      goesForward=false;

      digitalWrite(LeftMotorBackward, HIGH);
      digitalWrite(RightMotorBackward, HIGH);

      digitalWrite(LeftMotorForward, LOW);
      digitalWrite(RightMotorForward, LOW);

    }

    void turnRight(){

      digitalWrite(LeftMotorForward, HIGH);
      digitalWrite(RightMotorBackward, HIGH);

      digitalWrite(LeftMotorBackward, LOW);
      digitalWrite(RightMotorForward, LOW);

      delay(500);

      digitalWrite(LeftMotorForward, HIGH);
      digitalWrite(RightMotorForward, HIGH);

      digitalWrite(LeftMotorBackward, LOW);
      digitalWrite(RightMotorBackward, LOW);

    }

    void turnLeft(){

      digitalWrite(LeftMotorBackward, HIGH);
      digitalWrite(RightMotorForward, HIGH);

      digitalWrite(LeftMotorForward, LOW);
      digitalWrite(RightMotorBackward, LOW);

      delay(500);

      digitalWrite(LeftMotorForward, HIGH);
      digitalWrite(RightMotorForward, HIGH);

      digitalWrite(LeftMotorBackward, LOW);
      digitalWrite(RightMotorBackward, LOW);
    }

Expected to the servo to rotate 90 degrees, but right now the servo is moving randomly.

body:
I think you need to do some rigorous testing of the individual functions of your bot.

Step 1: rename your loop function to "loop_temp" which means it won't run, but it will be retained for later.

Step 2: write a new "loop" function, which sets the LeftMotorForward for 1 second, then stop for 1 second.  And observe the results.

Step 3: repeat Step 2 with LeftMotorBackward, RightMotorForward, etc

Step 4: using serial print, experiment with the output from the sonar to make sure it's delivering the expected results.

Step 5: one at a time introduce your functions and ensure they are each working properly.

Step 6: hopefully you've discovered a bug/fault somewhere, and you can re-introduce your original "loop" function.  Otherwise that function may be the issue.

I've had a look at your code, but don't see anything obviously amiss.  So I'm afraid it may be a process of elimination.


sender: user

message:
What hardware do I use to detect an electric current going to a lightbulb and tell if it is turning on and off

I’m doing a project where you have to detect a lightbulb coming on through the electrical current and was wondering what Hardware and what the program is? Can y’all help? Very much appreciated if y’all do.

sender: assistant

body:
A suitable piece of hardware would be a ACS712 Current Sensor which can be used with any Arduino which runs on 5 volts -for instance an Arduino Uno.

You may find [this guide][1] useful in writing the program.

  [1]: https://www.electronicshub.org/interfacing-acs712-current-sensor-with-arduino/#A_Brief_Note_on_ACS712_Current_Sensor


message:
Flow meter using Wemos Mini - ISR not in IRAM!

I'm trying to use a flow meter with Wemos Mini.
Most tutorials are using Arduino boards ( which code and HW work OK ), but since I want this device to send alerts over the internet when abnormal usage/leakage is detected, I want to use Wemos Mini using [How to Use Water Flow Sensor - Arduino Tutorial][1]. On top of if will add my code for notifications using Telegram.

BUT - after uploading the original code (before adding Telegram changes ), an error occurs during code run : `ISR not in IRAM!`

I tried to change Pin - but still getting this error,

  [1]: https://www.instructables.com/id/How-to-Use-Water-Flow-Sensor-Arduino-Tutorial/

body:
This happens because of conflicts between Serial and external interrupts
Put ICACHE_RAM_ATTR before your interrupt function, like this ``` ICACHE_RAM_ATTR void ISR()```


message:
How to wake up Arduino with an rtc?

I am doing a data logger with an Arduino Mega2560 and I want to use a code to make it sleep when no measure is needed and wake it up with an RTC when time comes. The reason I want this is because I intend to run the code on a Pro Mini later so I need to save as much energy as I can. I am able to put the arduino to sleep using the alarm interrupt when a minute is passed but it doesn't wake up from sleep afterwards.

Here is the code I am using:
<!-- language-all: lang-cpp -->

    #include <Wire.h>
    #include <RtcDS3231.h>
    #include <avr/sleep.h>

    const byte interruptPin = 2;
    volatile bool alarm = 0;
    volatile byte counter = 0;

    RtcDS3231<TwoWire> rtcObject(Wire);

    void setup() {

      Serial.begin(9600);
      Serial.println("Initialisation");
      pinMode(interruptPin, INPUT_PULLUP);
      attachInterrupt(digitalPinToInterrupt(interruptPin), handleInterrupt, FALLING);

      rtcObject.Begin();

      RtcDateTime timestamp = RtcDateTime(__DATE__, __TIME__);
      rtcObject.SetDateTime(timestamp);

      rtcObject.Enable32kHzPin(false);
      rtcObject.SetSquareWavePin(DS3231SquareWavePin_ModeAlarmOne);

      DS3231AlarmTwo alarm2(
        0,
        0,
        0,
        DS3231AlarmTwoControl_OncePerMinute);

      rtcObject.SetAlarmTwo(alarm2);
      rtcObject.LatchAlarmsTriggeredFlags();

    }

    void loop() {
      if (alarm == true){
        handleAlarm();
        if (counter == 1){
          mesure();
          counter = 0;
          delay(100);
          sleepNow();
        }
      }
    }

    void handleInterrupt() {
      alarm = true;
      counter ++;
      Serial.println(counter);
    }

    void handleAlarm() {
      alarm = false;
      rtcObject.LatchAlarmsTriggeredFlags();
    }

    void mesure(){
      RtcDateTime timestamp = rtcObject.GetDateTime();

      Serial.print("time interrupt at: ");
      char time[10];

      sprintf(time, "%d:%d:%d",
              timestamp.Hour(),
              timestamp.Minute(),
              timestamp.Second()
             );
    Serial.println(time);
    }

    void sleepNow() {
      Serial.println("Entering sleeping");
      delay(100);
      set_sleep_mode(SLEEP_MODE_PWR_DOWN);    // sleep mode is set here
      sleep_enable();                         // enables the sleep bit in the mcucr register
      attachInterrupt(digitalPinToInterrupt(interruptPin),wakeUpNow, FALLING);  // use interrupt 0 (pin 2) and run function
      sleep_mode();                           // here the device is actually put to sleep!!
      // THE PROGRAM CONTINUES FROM HERE AFTER WAKING UP

      sleep_disable();         // first thing after waking from sleep: disable sleep...
      detachInterrupt(digitalPinToInterrupt(interruptPin));      // disables interrupt 0 on pin 2 so the wakeUpNow code will not be executed during normal running time.
    }

    void wakeUpNow() {
      // execute code here after wake-up before returning to the loop() function
      // timers and code using timers (serial.print and more...) will not work here.
      // we don't really need to execute any special functions here, since we
      // just want the thing to wake up
    Serial.println("Woke up");
    delay(100);
    }

I want to understand how to wake it up properly so I can later make it sleep first in the loop and wake it up only if an interrupt is detected from the rtc.

Thank you for your help !

body:
If you use the [DS3232RTC library][1] then you can setup an alarm which is like an alarm. I have put a good tutorial on how to do that below.

https://thekurks.net/blog/2018/2/5/wakeup-rtc-datalogger

There is also other threads on arduino.cc you should check out. They might have additional work-arounds.

https://forum.arduino.cc/index.php?topic=333654.0

https://forum.arduino.cc/index.php?topic=99588.0

  [1]: https://github.com/JChristensen/DS3232RTC


body:
You may not need to use an RTC to wake up. Jeelabs has done extensive work on low-power consumption maybe you just need to use the jeelib library from Github. They even sold (not anymore) ultra low power optimized UNO compatible devices (https://jeelabs.org/202x/jnc/). You find jeelib on github on the linked page.

Look at the Sleepy class. It does some low level power saving magic directly with the hardware. It would be interesting to extract that class from Ports.h and Ports.cpp and try if it works standalone.

You simply use it with: Sleepy::loseSomeTime(32); and it will power down the whole MCU for some time. https://github.com/jeelabs/jeelib/blob/635113edea74b1290713360649679c3a13016304/Ports.h#L346

It uses the watchdog timer of the MCUs:

    ISR(WDT_vect) { Sleepy::watchdogEvent(); }


message:
Sending Integer > 1 Byte from Android to Arduino over Serial

I´m using

    public abstract void write(int b) throws IOException;

from class OutputStream on Android Studio to sent Integer (degrees from 0 to 360) to the Serial Port of my Arduino over HC06 Bluetooth module.

Degrees from 0 to 256 are read well by using

     int angle = Serial.read();

Values over 256 (1 Byte) are received as 0 are something weird.

I tried using

     Serial.parseInt();
as it should return an long int but all I get is one digit mostly 0.

I also tried using

    Serial.readBytes(threeDigitsInt, 3);
    angle = (threeDigitsInt[0] * 100) + (threeDigitsInt[1] * 10) + threeDigitsInt[2];

but I cannot tell what ends up in the array. Definitly not the correct single digit. I tried char[] and byte[] but I´m not able to reconstruct my send Integer value.

Summary: I want to send 360 as Integer from Android and have it as Integer on Arduino.

Appreciate your help!

body:
First off, you are only sending one byte from Android:

> `public abstract void write (int b)`
>
> Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. **The 24 high-order bits of b are ignored.**

OutputStream.write(byte) can *never* write more than one byte.

Also it's clear you have no clue about what format the data is sent in if you are trying to then read 3 bytes and use Binary Coded Decimal to reconstruct it.

Instead I suggest you work in a purely ASCII format. Forget bytes. Bytes are not what you want, unless you feel like spending some extra time defining, and then implementing, your own protocol.

Start by formatting your data into an ASCII printable string.  If Android Java is anything like normal Java I'd start by turning your integer into a string with proper line endings.  Something like:

    String val = String.format("%d\n", angle);

Then get the bytes that represent that formatted string:

    byte[] valBytes = val.getBytes();

Now you have a valid byte array containing your textual representation of the data that you can send with `OutputStream.write(byte[])`.

Now your task is to read that data on the Arduino.  That means reading each byte that arrives in turn storing it away in some form until you receive the `\n` line ending.  At that point you can take each byte as a string and convert them into an integer again.

It's possible to do that on the fly:

    static int angle = 0;

    if (Serial.available()) {
        char c = Serial.read();
        if (c == '\n') {
            Serial.print("I got: ");
            Serial.println(angle);
            angle = 0;
        } else if ((c >= '0') && (c <= '9')) {
            angle *= 10;
            angle += (c - '0');
        }
    }

Basically, have a variable that stores the incoming angle. For each character that arrives on the serial port - if it's a line ending `\n` then do whatever with the angle value. If it's a character between 0 and 9 then multiply your angle by 10 (decimal shift left), convert your character to the equivalent integer by subtracting character '0', and add it to your angle.


message:
How to include Vref in thermistor temperature calculation?

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

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

<!-- End schematic -->

This is the code that I'm using to get the temperature:

    #define COEFF_A 0.8662984364E-03
    #define COEFF_B 2.780704551E-04
    #define COEFF_C -0.9395108479E-07

    float VRT, Temp;
    float Vref = 2.52;

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

    void loop() {
      long Resistance;
      VRT = analogRead(A3);
      Resistance = 10000 / ((1023.0 / VRT) - 1);
      Temp = log(Resistance);
      Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp, 3)));
      Temp += -273.15;
      Serial.println(Temp);
      delay(500);
    }
I know that the calculation should be: `V = Vref × VRT ÷ 1023` but i don't know how to implant it in this code, any help appreciated.
___________
# Update

After Edgar Bonet [answer][1], the edited code is:

    #define COEFF_A 0.8662984364E-03
    #define COEFF_B 2.780704551E-04
    #define COEFF_C -0.9395108479E-07

    float VRT, Temp, VR;

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

    void loop() {
      long Resistance;
      VRT = analogRead(A3);
      VR = 2.52 * VRT / 1024;
      Resistance = 10000 * VR / (2.52 - VR);
      Temp = log(Resistance);
      Temp = 1 / (COEFF_A + (COEFF_B * Temp) + (COEFF_C * pow(Temp, 3)));
      Temp += -273.15;
      Serial.println(Temp);
      delay(500);
    }

But the temperature reading is 2 centigrade less than what it should be, when i remove the `analogReference(EXTERNAL);` it shows the normal/correct temperature readings.

  [1]: https://arduino.stackexchange.com/a/68288/57281

body:
Note: I formulated this answer on your previous, deleted question.

Whether the voltage increases or decreases with rising temperature depends on your circuit: if you use the ntc with R1 as a pull-down, the voltage will increase on rising temperature. If R1 is a pullup the voltage will fall respectively.

Concerning your calculation: I highly recommend using a look-up table instead. Those are some hard calculations, and at the arduinos resolution you'll be fine with a LUT with about 64 entries. There're tools out there which generate LUTs for a given NTC setup (I personally like [this tool][1]).

  [1]: http://www.sebulli.com/ntc/index.php?lang=en


body:
The formula to get the analog voltage from the ADC reading is:

    V = Vref × reading ÷ 1024

(yes, it's 1024, not 1023). The formula to get the thermistor resistance
from the measured voltage is:

    R = Rref × V ÷ (Vref − V)

where Rref is your 10 kΩ pull-up. You can combine these
two formulas in order to get the resistance directly from the ADC
reading:

    R = Rref × reading ÷ (1024 − reading)

You may notice that, while doing this simplification, Vref
cancels out. It's not an error. The readings you get with this setup are
indeed independent of your reference voltage.

------------------------------------------------------------------------

**Update 1**: After the OP's edit, we now have a _completely different_
question. The question is now: how come the readings do depend on the
reference voltage that is used, whereas in theory they should not.

The answer lies most likely in the ADC calibration. If high accuracy is
a requirement, the correct formula for the measured voltage is

    V = Vref ×
(reading + Eoff) ÷ (1024 + Egain)

where Eoff and Egain are the offset error and the
gain error respectively. These errors are not knows _a priori_, and they
are usually neglected when the accuracy requirement is low. The
datasheet only gives constraints on how big these errors can be. The
actual values depend on the specific microcontroller and can somewhat
depend on the reference voltage. The only solution to get rid of these
errors is to calibrate your own ADC. See [Response of the Arduino
ADC][adc] for an example on how this could be done.

[adc]: https://wiki.logre.eu/index.php/Réponse_de_l'ADC_d'un_Arduino/en

------------------------------------------------------------------------

**Update 2**: If I had to program this in an Arduino, I would rather
simplify the calculations as much as possible before coding:

* do _not_ compute the measured analog voltage, nor the resistance, as
  they are not needed
* compute instead the ratio R/Rref directly from the analog
  reading
* rewrite the calibration polynomial as a function of
  log(R/Rref) instead of log(R) (which actually means
  log(R/(1 Ω)))
* optimize the evaluation of the polynomial by using
  [Horner's method][].

With these optimizations, we get:

```c++
// Coefficients of polynomial fit of log(R/Rref) -> 1/T.
const float c0 = 3.3540165e-3;
const float c1 = 2.5416075e-4;
const float c2 = -2.5959644e-6;
const float c3 = -9.3951087e-8;

// Convert ADC reading to temperature in deg. C.
static float temperature(int reading)
{
    float R_ratio = reading / (1024.0 - reading);  // = R / Rref
    float x = log(R_ratio);
    float inverse_T = c0 + x*(c1 + x*(c2 + x*c3));
    return 1/inverse_T - 273.15;
}

void loop()
{
    int reading = analogRead(A3);
    Serial.println(temperature(reading));
    deay(500);
}
```

[Horner's method]: https://en.wikipedia.org/wiki/Horner's_method


message:
Which Arduino-compatible microcontroller for 2 continuous analog audio recording and 2 digital pin snapshots every second?

Apologies if the title is not very well worded. I'm new to electronics and trying to learn more about embedded systems too. I have a small project that requires recording an analog audio input at 8-bit at 40kHz and saving it every second in a SD card.

Although I know that I can do that with an ATmega328P chipset, I'm not sure if the processing power of ATmega328P will be good enough for further extension of the project.

Ideally I would like to be able to record two sound sources at the same time at around 40kHz -- 16 or 24-bit would be perfect, and capture two sensory data also every second.

This device should be able to run on a reasonably sized battery for at least two hours, but ideally up to eight hours.

I do like the idea of working on a AT91SAM3X8E chipset, but I'm afraid this might be an overkill for such a small project and the current draw of a Cortext-M3 series might be too much for this project too.

My question therefore is would a ATmega328P or ATmega2560 be suitable for such requirements -- in terms of processing power, or do I have to upgrade to something like the AT91SAM3X8E?

body:
> My question therefore is would a ATmega328P or ATmega2560 be suitable for such requirements

No. Not in the slightest.

Your primary requirement of sampling audio at, basically, CD quality (or better) requires the use of a proper CODEC chip - and to drive that you require a microcontroller that has I2S. None of the 8-bit AVR chips have that.

On top of that you will need a LOT of memory. Far far more than an 8 bit Arduino has.  Two channels of 16 bit audio at 44100Hz (CD quality) requires 176400 bytes *per second*.

You will need double that.

To both continuously record and save the data you will require DMA to do the recording.  The DMA reads the incoming data from I2S and stores it in one buffer. When that buffer is full you generate an interrupt and switch to a second buffer. You can then save the first buffer to SD - *assuming that it can be done in under a second*.  Note that SD cards, when controlled by SPI as they generally are on microcontrollers, are generally quite slow.

So with all that in mind:

> I do like the idea of working on a AT91SAM3X8E chipset, but I'm afraid this might be an overkill for such a small project

Overkill? No. Not suitable since it is not up to the task. Yes, it has I2S. Yes, it has DMA. But it doesn't have anywhere near enough memory.  You need for the audio alone 350 kilobytes (the SAM3X8E has up to 100 kilobytes) - not to mention memory required by the SD card's buffers.

So you're looking for a microcontroller that has full I2S support, DMA, and around half a megabyte of memory.  And those aren't small and cheap like the Arduino's 8-bit AVRs.


message:
How can I stop a loop when using a servo with a Key input?

How can I stop my following code using a key?

Basically the code should run the servo in a loop if "t" is pressed and stop the loop if "s" is pressed.

    #include <Servo.h>

    Servo myservo;  // create servo object to control a servo
    // twelve servo objects can be created on most boards

    int pos = 0;    // variable to store the servo position
    int servodata;

    void setup() {
      myservo.attach(8);  // attaches the servo on pin 9 to the servo object

      Serial.begin(9600);

    }

    void loop() {
      if (Serial.available()>0){
        servodata = Serial.read();
        while (servodata == 't'){
               for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
        // in steps of 1 degree
           myservo.write(pos);              // tell servo to go to position in variable 'pos'
           delay(3);                       // waits 15ms for the servo to reach the position
      }
        for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
           myservo.write(pos);              // tell servo to go to position in variable 'pos'
           delay(3);                       // waits 15ms for the servo to reach the position
        }
        }
      }
      while (servodata == 's'){
        break;
      }
    }

thank you for help.

body:
Here is a quick and dirty solution, where each `loop()` iteration
corresponds to one “start sweeping”/“stop sweeping” cycle:

* wait for the “start” command
* then sweep back and forth in an infinite loop
* stop at any point if you receive the “stop” command

```c++
void loop() {
    // Wait for the 'start' command.
    while (Serial.read() != 't')
        continue;

    // Repeatedly sweep back and forth.
    for (;;) {
        for (int pos = 0; pos <= 180; pos += 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
        for (pos = 180; pos >= 0; pos -= 1) {
            myservo.write(pos);
            delay(3);
            if (Serial.read() == 's') // check for 'stop' command
                return;
        }
    }
}
```

Note that this approach has a couple of drawbacks:

1. As this is blocking code, you cannot easily extend the program to do
   other things.
2. The sweeping runs always start at position 0, instead of resuming
   from the position that was current on the last “stop” command.

If you need anything more sophisticated, you should go to a non-blocking
approach based on a [Finite State Machine][fsm] (c.f. jsotola's
comment). Note that you can get away with `delay(3);`, as it is a quite
short delay, but you would have to break the sweeps into one step per
`loop()` iteration.

I suggest you give the FSM approach a try: read the tutorial I linked
to, then try to implement it. If you cannot get it to work, you can
always post another question here.

[fsm]: https://majenko.co.uk/blog/finite-state-machine


message:
Parent class callback from child class

I want the Parent class to pass a pointer to a callback function to the child class when the child class is created. I got this working when the parent was the sketch thanks to [this post][1]:
In this example, the parent was the `.ino` file, i.e. not a class but a collection of functions. This code worked fine.
However, I need to be able to make the call to the child constructor from a within a class as shown in the code below. I get I get an "invalid use of non-static member function on the line `child = new Child ( handlerDispatcher );`

Here is the complete code:

    class Child {
    public:
     typedef void ( *callback_t ) ( uint8_t, uint8_t );

     callback_t callback;

     // Constructor
     Child ( callback_t _callback ): callback ( _callback ) {}

     void doCallback ( uint8_t id, uint8_t index ) {
      callback ( id, index );
     }

     void makeCallbacks () {
      doCallback ( 1, 0 );
      doCallback ( 2, 1 );
      doCallback ( 3, 2 );
     }
    };

    class Parent {
    public:
     Child *child;

     Parent () {}

     void handlerDispatcher ( uint8_t id, uint8_t index ) {
      ( this->*callbackHandlers [ index ] ) ( id );
     }

     typedef void ( Parent:: *handlerPointer ) ( uint8_t );
     handlerPointer callbackHandlers [ 3 ] = {
      &Parent::handler1,
      &Parent::handler2,
      &Parent::handler3,
     };

     void handler1 ( uint8_t index ) { echo ( index ); }
     void handler2 ( uint8_t index ) { echo ( index ); }
     void handler3 ( uint8_t index ) { echo ( index ); }
     void echo ( uint8_t value ) {
      Serial.print ( "Got: " );
      Serial.println ( value );
     }

     void configure () {
      child = new Child ( handlerDispatcher );

     }
     void test () {
      child->makeCallbacks ();
     }
    };

    Parent parent;
    void setup () {
     Serial.begin ( 115200 );
     parent.configure ();
     parent.test ();
    }

    void loop() {}

  [1]: https://arduino.stackexchange.com/questions/25688/access-method-fromin-sketch-inside-class

body:
It is because

    void Parent::handlerDispatcher ( uint8_t id, uint8_t index )

is not

    void ( *callback_t ) ( uint8_t, uint8_t )

The closest equivalent would be:

    void ( *callback_t ) (Parent *, uint8_t, uint8_t )

Though I am not sure off hand if that is even possible.

But it seems you are trying to do something insanely convoluted and complex which would be made far simpler if you just used object inheritance and forget about callbacks.

With object inheritance a child object can implement the functions that a parent object defines. That way you end up with a single object instance which is a combination of the parent functions and the child functions, one overlaid on the other.

To build on Juraj's excellent answer and add a bit of explanation, if you take the following parent object:

    class Parent {
    public:

      virtual void fnc1() = 0;

      void fnc2 {
        fnc1();
      }
    };

What we have here are two functions in the parent.  `fnc2()` simply calls `fnc1()` as an example.  However `fnc1()` isn't a normal function - it's a *pure virtual* function. That is akin to an `interface` in Java. It's a placeholder in the parent that says "This function *will* exist, but the child will implement it, not me".  If you try and instantiate a Parent object the compiler will complain that certain functions are pure virtual and the object can't be created.

So then you create a child class which takes the parent class and extends it with the body of any pure virtual functions that are needed, and can also add more.  For example:

    class Child : public Parent {
    public:
      void fnc1() final {
        ...
      }
    };

Here we only have one function - `fnc1()`, which is marked as `final`.  The `final` keyword is kind of the opposite of the `virtual` keyword.  `virtual` means "This function will be overridden by the child". `final` means "I have overridden this, and nothing else can now override it". It's not essential, but it does help with the compiler's optimiser somewhat, since it no longer needs to worry about further inheritance of that function.

So now you can create a `Child` instance, and you will have access to all the parent functions and data, as well as all the child functions and data.  Simply calling `fnc2()` on this child instance will call that function on the parent, which then itself calls `fnc1()` which is implemented by the child.

And thanks to something called *polymorphism*, the child can be seen as a parent for all intents and purposes (though if you look at it as a parent you won't see any of the child's own functions).

To wrap it all up, here's a full example that uses two different child classes and stores pointers to them in an array of parents (so the children are seen as if they are objects of class `Parent`), iterates through them, and calls the parent's `fnc2()` function:

    class Parent {
        public:
            virtual void fnc1() = 0;
            void fnc2() {
                fnc1();
            }
    };

    class Child1 : public Parent {
        public:
            void fnc1() final {
                Serial.println("I am child 1");
            }
    };

    class Child2 : public Parent {
        public:
            void fnc1() final {
                Serial.println("I am child 2");
            }
    };

    Child1 c1;
    Child2 c2;

    Parent *objects[2] = {
        &c1, &c2
    };

    void setup() {
        Serial.begin(115200);
        for (int i = 0; i < 2; i++) {
            objects[i]->fnc2();
        }
    }

    void loop() { }

The serial output from that program is:

    I am child 1
    I am child 2

Which I think is the end effect that you are looking for.


body:
Use virtual functions. On object of type `Child`, `fnc2` defined in `Parent` will call `fnc1` of class `Child`:

    class Parent {
    public:

      virtual void fnc1() {
      }

      void fnc2 {
        ...
        fnc1();
        ...
      }
    }

    class Child : public Parent {
    public:
      virtual void fnc1() {
        ...
      }
    }


message:
Not getting any output from ECG sensor AD8232

I am trying for the beginning to run a simple Arduino code in order to test the functionality of the ECG sensor. What I am getting on the output are some random values around 600 or around 200.
I connected everything the same as in any tutorial about AD8232:
GND -> GND, 3.3V -> 3.3V, L0+ -> digital pin 10, L0- -> digital pin 11, output -> analog pin A0.
I placed the sensor pads on my body like in pictures (forming a triangle), but regardless of putting the electrodes or not, I always get the same floating signal.
Here is Arduino code:

    int ecg;

    void setup() {
      // put your setup code here, to run once:
      Serial.begin(9600);
      pinMode(10,INPUT);
      pinMode(11,INPUT);

    }

    void loop() {
      if((digitalRead(10) == 1)||(digitalRead(11) == 1)){
        Serial.println('!');
      }
        else{
        // send the value of analog input 0:
        Serial.println(analogRead(A0));
        }
        //Wait for a bit to keep serial data from saturating
        delay(1);
    }
When I run this code I get only "!" on the output, no matter where I put the electrodes on my body. When I comment "if" and "else" parts of the code and print directly only reading from the pin A0, I get those random floating values, like on the image.
[![Random values from analog pin A0][1]][1]

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

I also tried another custom built ECG sensor, but the results are the same. I haven't found the solution anywhere. It is not about the noise, because when I touch the metal box of my PC, I only reduce the values but there is still nothing on the output.

body: The problem was that I connected GND on the other half of the protoboard and there was no connection. I thought that the whole length of the protoboard is on the same potential for + and -, so GND wasn't connected. After connecting GND pin correctly, all worked perfectly.


message:
arduino mega multi integer values reading on other arduino mega

I need two Arduino communications.
The master arduino from the slave arduino needs to read 16 signals.
The sample serial port output from the slave is as follows.

    @ 125 @ 13 @ 874 @ 1023 & 950 @ 547 @ 965 @ 852 @ 654 @ 478 @ 0 @ 456 @ 996 @ 789 @ 556 @ 847 @

I need to throw this output into an integer array.

<!--- --->

body:
You can use the following C functions:

- `strtok`: to split a string (see [strtok][1]).
- `atoi`: to convert a string to an integer (see [atoi][2]).

  [1]: https://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm
  [2]: https://www.tutorialspoint.com/c_standard_library/c_function_atoi.htm


message:
WebSocketsServer.h: No such file or directory

I'm trying use the NodeMCU WebSocket.

 I downloaded the required libraries from:
<https://github.com/Links2004/arduinoWebSockets>
and pasted them in my Arduino libraries folder. I uploaded my code but got this error:

**WebSocketsServer.h: No such file or directory.**

_Can you please tell me why my Arduino IDE won't find the WebSocketsServer.h header file when it is physically present in my Arduino libraries folder?   Or if there's an alternative way to use the NodeMCU WebSocket?_

Here's the code:

~~~~~
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <WebSocketsServer.h>
#include <Hash.h>

// Replace with your network credentials
const char* ssid = "<WiFi-SSID>";
const char* password = "WiFi-PASSWORD";

WebSocketsServer webSocket = WebSocketsServer(81);
ESP8266WebServer server(80);   //instantiate server at port 80 (http port)

String page = "";
int LEDPin = D5;

void setup(void){
 //the HTML of the web page
 page = "
Simple NodeMCU Web Server

<button>ON</button> <button>OFF</button>
";
 //make the LED pin output and initially turned off
 pinMode(LEDPin, OUTPUT);
 digitalWrite(LEDPin, LOW);

 delay(1000);

 Serial.begin(115200);
 WiFi.begin(ssid, password); //begin WiFi connection
 Serial.println("");

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

 Serial.println("");
 Serial.print("Connected to ");
 Serial.println(ssid);
 Serial.print("IP address: ");
 Serial.println(WiFi.localIP());

 server.on("/", [](){
    server.send(200, "text/html", page);
 });

 server.on("/LEDOn", [](){
    server.send(200, "text/html", page);
    digitalWrite(LEDPin, HIGH);
    delay(1000);
 });

 server.on("/LEDOff", [](){
    server.send(200, "text/html", page);
    digitalWrite(LEDPin, LOW);
    delay(1000);
 });

 server.begin();
 webSocket.begin();
 webSocket.onEvent(webSocketEvent);

 Serial.println("Web server started!");
}

void loop(void){
  webSocket.loop();
  server.handleClient();
  if (Serial.available() > 0){
    char c[] = {(char)Serial.read()};
    webSocket.broadcastTXT(c, sizeof(c));
  }
}

void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length){
  if (type == WStype_TEXT){
   for(int i = 0; i < length; i++) Serial.print((char) payload[i]);
   Serial.println();
  }
}
~~~

body: after you included the zip file to library you must rename directory like this 'WebSocketsServer'. And then you copy all file in 'src' directory and then paste them to its parent directory (WebSocketsServer)


body:
The proper way is to add library into your Arduino IDE, it will **just work**.

 1. Open the Arduino IDE
 2. Go to `Sketch` > `Include Library` > `Manage Libraries`
 3. Search for "WebSockets Sattler' and install the library named "WebSockets by Markus Sattler"
 4. Restart the Arduino IDE.

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

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

PS
 * you will see two results for WebSockets library from the same author
 * the second "WebSockets_Generic" is a more lightweight library and it only provides support for WebSockets in the client mode (it is designed to be more memory efficient)

  [1]: https://i.stack.imgur.com/jLmVn.png
  [2]: https://i.stack.imgur.com/pDwy3.png


message:
How can I measure if a battery is there?

With my arduino I want to measure if one / two AAA batteries are in their single / double battery holder.

When the Arduino is running, connected to some other power supply and the batteries are in place everything is fine: I get my measurements of around 1.5V / 3V on the analog pin the battery is connected to (- of battery and Arduino GND are connected as well of course).

Problems arise when I either

a) pull the batteries out: The analog pin is left floating. Not good. Can I put the pin into INPUT_PULLUP mode? Is the internal resistor big enough? Or will the then connected 5V damage my batteries when they are back in the battery holder?

b) dissconect the Arduino from its external power supply: Because the Arduino is then "powered" by the 3V through the analog pin my blinking LED keeps blinking (at less brightness, but still...). I neither want the batteries to get drained nor damage my Arduino with it. So I would like to avoid this.

Actually I don't care about the actual battery voltage - I just want to know if the batteries are in their holder or not. And I want to leave the batteries there even though the Arduino is not powered. I would even consider something like "a button is held down when a battery is in its holder" or any other (simple) creative ideas.

Is this possible? How?

body:
You could add a pull**down** to the analog pin. If the ADC reads a value below e.f. 10, you could consider this the state when there are no batteries.

From the signal perspective a pullup would be better, because without batteries you would read 5V which is unambigous as it can not be provided by the batteries themselves. But in general I don't think that applying higher voltage to the batteries is good practice, even though you could limit the current with a reasonably high resistor.


body:
I see 1 main problem: Keeping the batteries isolated, so that no current flows between them and the Arduino (especially no parasitic current into the input pin of a turned off Arduino), while still reading a voltage level (HIGH or LOW).

I would suggest using a fitting N-Channel MOSFET. Connect the minus pin of the batteries to ground and the plus pin to the gate of the MOSFET. Then source and drain of MOSFET to ground and a digital arduino pin respectively. Enable the internal pullup resistor. Add a pulldown resistor between gate and ground.

Now, without the batteries, the gate is at ground level, so the MOSFET is not conducting. The level at the input pin will be high. If the batteries are in, their voltage will activate the MOSFET, which pulls the Arduinos input pin to ground, thus LOW level. Since the MOSFET is somewhat like a capacitor between gate and the rest, almost no current will flow here (only enough to load the small capacitance). Though I'm not sure, I think that no current will flow either in the case of the Arduino being unpowered.

The task now would be to find a fitting MOSFET, which goes in saturation for 1.5V.

Of course you can also use a microswitch, that gets pushed down by the batteries. That is electronically easier, but maybe mechanically challenging.


message:
Error while reburning bootloader to atmega328p by usbasp in Arduino IDE

I have got the Bootloaded ATMega328P-PU from China and I want to reburn new bootloader into it. For this I use UsbAsp programmer. I want to do it in Arduino IDE. But when I try to flash, for example, an empty flash it says that error:
```
 Using Port                    : usb
         Using Programmer              : usbasp
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : usbasp
         Description     : USBasp, http://www.fischl.de/usbasp/

avrdude: auto set sck period (because given equals null)
avrdude: warning: cannot set sck period. please check for usbasp firmware update.
avrdude: error: program enable: target doesn't answer. 0
avrdude: initialization failed, rc=-1
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.
```

But when I work in *Avrdudeprog*, it works without any problems.
How can I fix it?

body:
use Zadig 2.4 to change the driver for USBasp. USBasp works with 3 drivers but it seems the type of installed driver causes some problems in various software. khazama, progisp on one hand and Arduino on the other hand. despite all of them using avrdude.

libusb-win32 : khazama works, Arduino does not
WinUSB       : khazama doesn't work, Arduino works
libusbK      : both work


message:
How to set PC (Program Counter) register to another function (for scheduler)

I am trying to implement a scheduler for Arduino Mega 2560. I think I lack understanding of how to set the PC register to another instruction.
Here is my simple approach so far:

    void dummy(){
        digitalWrite(LED_BUILTIN, HIGH);
     }

in a naked ISR method:

    SP = (uint16_t)(&dummy)
    __asm volatile(
    "reti     \n\t"
    )

However it is not working. How should the PC register be set to a certain function or to where it was in a previous process for a scheduler approach?

body:
This:

```c
SP = (uint16_t)(&dummy)
```

is changing the stack pointer. Not what you want. You want to instead
`push` the destination address to the stack. However, rather than
simulating a function return, it should be simpler to perform an
[indirect jump][]:

```c
asm volatile("ijmp" :: "z"(dummy));
```

Don't forget that your naked ISR has to save _all_ the call-used
registers, as well as `SREG`, `r0` and `r1`, in its custom prologue. And
restore them in its epilogue. Check the [AVR calling
conventions][conventions].

[indirect jump]: https://www.microchip.com/webdoc/avrassembler/avrassembler.wb_IJMP.html

[conventions]: https://www.nongnu.org/avr-libc/user-manual/FAQ.html#faq_reg_usage


message:
Run light sequence function continuously in if statement

My goal - run light sequence function on momentary button press (button 2) continuously until another of the 3 momentary buttons are pressed.

        /* switch
     *
     * Each time the input pin goes from LOW to HIGH (e.g. because of a push-button
     * press), the output pin is toggled from LOW to HIGH or HIGH to LOW.  There's
     * a minimum delay between toggles to debounce the circuit (i.e. to ignore
     * noise).
     *
     * David A. Mellis
     * 21 November 2006
     */
     #include "FastLED.h"

    int inPin = 8;         // the number of the input pin
    int inPinTwo = 9;
    int inPinThree = 10;
    int outPin = 13;       // the number of the output pin

    int state = HIGH;      // the current state of the output pin
    int reading;           // the current reading from the input pin
    int readingTwo;
    int readingThree;
    int previous = LOW;    // the previous reading from the input pin

    int pixelNumber;

    // the follow variables are long's because the time, measured in miliseconds,
    // will quickly become a bigger number than can be stored in an int.
    long time = 0;         // the last time the output pin was toggled
    long debounce = 200;   // the debounce time, increase if the output flickers

    //NEOPIXEL
    #define LED_PIN     7
    #define LEDPIN 7
    #define LED_TYPE     NEOPIXEL
    #define NUM_LEDS    2
    #define BRIGHTNESS 10
    #define FRAMES_PER_SECOND 60
    CRGB leds[NUM_LEDS];
    #define COLOR_ORDER GRB
    #define CHIPSET     WS2811

    bool gReverseDirection = false;
    CRGBPalette16 gPal;

    void setup()
    {

      pinMode(inPin, INPUT);
      pinMode(inPinTwo,INPUT);
      pinMode(inPinThree,INPUT);
      pinMode(outPin, OUTPUT);

      Serial.begin(9600);

      // set up LED strip info
    FastLED.addLeds<LED_TYPE,LEDPIN>(leds,NUM_LEDS).setCorrection(TypicalLEDStrip);
    FastLED.setBrightness(BRIGHTNESS);
    }

    void loop()
    {

    //    BUTTON 1 - SOLID LIGHT
      reading = digitalRead(inPin);

      // if the input just went from LOW and HIGH and we've waited long enough
      // to ignore any noise on the circuit, toggle the output pin and remember
      // the time
      if (reading == HIGH && previous == LOW && millis() - time > debounce) {
        if (state == HIGH){
          state = LOW;
          fill_solid(leds,NUM_LEDS,CRGB::Black);
          FastLED.show();
        }
        else{
          state = HIGH;
          fill_solid(leds,NUM_LEDS,0xFAF6D1);
          FastLED.show();
          }

        time = millis();

      }
        digitalWrite(outPin, state);
        previous = reading;

    //  BUTTON 2 - GLITTER LIGHT
       readingTwo = digitalRead(inPinTwo);
      if (readingTwo == HIGH && previous == LOW && millis() - time> debounce){
        if(state == HIGH){
          state = LOW;
          fadeToBlackBy( leds, NUM_LEDS, 10);
          addGlitter(30);
          FastLED.show();
          }
        else{
          state = HIGH;
          fill_solid(leds,NUM_LEDS,CRGB::Black);
          FastLED.show();
        }

        time = millis();
        }
        digitalWrite(outPin,state);
        previous = readingTwo;

    //  BUTTON 3  - MOVEMENT SENSOR LIGHT
           readingThree = digitalRead(inPinThree);
      if (readingThree == HIGH && previous == LOW && millis() - time> debounce){
        if(state == HIGH){
          state = LOW;
           fill_solid(leds,NUM_LEDS,CRGB::Black);
            FastLED.show();
          }
        else{
          state = HIGH;

        }

        time = millis();
        }
        digitalWrite(outPin,state);
        previous = readingThree;
    }

    //glitter effect
    void addGlitter( fract8 chanceOfGlitter) {
      if( random8() < chanceOfGlitter) {
        leds[ random16(NUM_LEDS) ] += CRGB::White;}
    }

The issue - the function seems to be only ran once (see button 2), which doesn't achieve the required effect.  I realize that changing this `if` statement to a `while` statement would be beneficial, but I cannot figure out how to break out of this while loop upon button press.  I know that setting `state = LOW` will break the while loop but if I leave it in, the light sequence function never runs.

    //  BUTTON 2
       readingTwo = digitalRead(inPinTwo);
      if (readingTwo == HIGH && previousTwo == LOW && millis() - time> debounce){
        while(state == HIGH){
    //      state = LOW;
          fadeToBlackBy( leds, NUM_LEDS, 10);
          addGlitter(30);
          FastLED.show();
      }

        while(state == LOW){
          state = HIGH;

          fill_solid(leds,NUM_LEDS,CRGB::Black);
            FastLED.show();

        }

Any help would be greatly appreciated!

body:
I added `int btnPress` which gets set on each button press.  Then an if statement runs according to btnPress number.  Thanks jsotola for the point in the right direction!

    #include "FastLED.h"

    int inPin = 8;         // the number of the input pin
    int inPinTwo = 9;
    int inPinThree = 10;
    int outPin = 13;       // the number of the output pin

    int state = HIGH;      // the current state of the output pin

    int reading;           // the current reading from the input pin
    int readingTwo;
    int readingThree;
    int previous = LOW;    // the previous reading from the input pin
    int previousTwo = LOW;
    int previousThree = LOW;
    volatile int change;
    int btnPress;

    int pixelNumber;

    long time = 0;         // the last time the output pin was toggled
    long debounce = 200;   // the debounce time, increase if the output flickers

    //NEOPIXEL
    #define LED_PIN     7
    #define LEDPIN 7
    #define LED_TYPE     NEOPIXEL
    #define NUM_LEDS    2
    #define BRIGHTNESS 255
    #define FRAMES_PER_SECOND 60
    CRGB leds[NUM_LEDS];
    #define COLOR_ORDER GRB
    #define CHIPSET     WS2812B

    void setup()
    {

    //BUTTON
      pinMode(inPin, INPUT);
      pinMode(inPinTwo,INPUT);
      pinMode(inPinThree,INPUT);
      pinMode(outPin, OUTPUT);

      Serial.begin(9600);

      // set up LED strip info
    FastLED.addLeds<LED_TYPE,LEDPIN>(leds,NUM_LEDS).setCorrection(TypicalLEDStrip);
    FastLED.setBrightness(BRIGHTNESS);
    btnPress = 1;

    }

    void loop()
    {
    //    BUTTON 1 - SOLID LIGHT
      reading = digitalRead(inPin);
      if (reading == HIGH && previous == LOW && millis() - time > debounce) {
        if (state == HIGH){
          state = LOW;
          btnPress = 1;
        }
        else{
          state = HIGH;
          btnPress = 2;
          }

        time = millis();

      }
        digitalWrite(outPin, state);
        previous = reading;

    //  BUTTON 2 - GLITTER LIGHT
       readingTwo = digitalRead(inPinTwo);
      if (readingTwo == HIGH && previousTwo == LOW && millis() - time> debounce){
        if(state == HIGH){
          state = LOW;
          btnPress = 3;
          }
        else{
          state = HIGH;
          btnPress = 4;
        }
        time = millis();
        }
        digitalWrite(outPin,state);
        previousTwo = readingTwo;

    //  BUTTON 3  - MOVEMENT SENSOR LIGHT
           readingThree = digitalRead(inPinThree);
      if (readingThree == HIGH && previousThree == LOW && millis() - time> debounce){
        if(state == HIGH){
          state = LOW;
           btnPress = 5;
          }
        else{
          state = HIGH;
          btnPress = 6;
        }

        time = millis();
        }
        digitalWrite(outPin,state);
        previousThree = readingThree;

        //BUTTON 1 - SOLID LIGHT
         if (btnPress == 1){
              fill_solid(leds,NUM_LEDS,CRGB::Black);
              FastLED.show();Serial.println("pressed1");
          }

        if (btnPress == 2){
              fill_solid(leds,NUM_LEDS,0xFfffff);
              FastLED.show();Serial.println("pressed2");

          }

        //  BUTTON 2 - GLITTER LIGHT
        if (btnPress == 3){
                fill_solid(leds,NUM_LEDS,CRGB::Black);
              FastLED.show();Serial.println("pressed3");

          }
        if (btnPress == 4){
             fadeToBlackBy( leds, NUM_LEDS, 10);
              addGlitter(30);Serial.println("pressed4");
              FastLED.show();
          }

        //  BUTTON 3  - MOVEMENT SENSOR LIGHT
        if (btnPress == 5){
                fill_solid(leds,NUM_LEDS,CRGB::Black);Serial.println("pressed5");
              FastLED.show();

          }
        if (btnPress == 6){
            Serial.println("pressed6");
          }
      }

    //glitter effect
    void addGlitter( fract8 chanceOfGlitter) {
      if( random8() < chanceOfGlitter) {
        leds[ random16(NUM_LEDS) ] += CRGB::White;}
    }


message:
Wiring ESP8266 and PN532

I'm trying the Android Hce example in [this PN532 library][1]. I can't find how to set SDA and SCL address in the code, so I tried connecting them in CLK and SD0 pins. The serial monitor gives me "Didn't find PN53x board". Can someone help me?

[1]: https://github.com/elechouse/PN532

```cpp
    #if 0
      #include <SPI.h>
      #include <PN532_SPI.h>
      #include "PN532.h"

      PN532_SPI pn532spi(SPI, 10);
      PN532 nfc(pn532spi);
    #elif 1
      #include <PN532_HSU.h>
      #include <PN532.h>

      PN532_HSU pn532hsu(Serial1);
      PN532 nfc(pn532hsu);
    #else
      #include <Wire.h>
      #include <PN532_I2C.h>
      #include <PN532.h>
    #endif

    void setup()
    {
        Serial.begin(115200);
        Serial.println("-------Peer to Peer HCE--------");

        nfc.begin();

        uint32_t versiondata = nfc.getFirmwareVersion();
        if (! versiondata) {
          Serial.print("Didn't find PN53x board");
          while (1); // halt
        }

        // Got ok data, print it out!
        Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
        Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
        Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

        // Set the max number of retry attempts to read from a card
        // This prevents us from waiting forever for a card, which is
        // the default behaviour of the PN532.
        //nfc.setPassiveActivationRetries(0xFF);

        // configure board to read RFID tags
        nfc.SAMConfig();
    }

    void loop()
    {
      bool success;

      uint8_t responseLength = 32;

      Serial.println("Waiting for an ISO14443A card");

      // set shield to inListPassiveTarget
      success = nfc.inListPassiveTarget();

      if(success) {

         Serial.println("Found something!");

        uint8_t selectApdu[] = { 0x00, /* CLA */
                                  0xA4, /* INS */
                                  0x04, /* P1  */
                                  0x00, /* P2  */
                                  0x07, /* Length of AID  */
                                  0xF0, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* AID defined on Android App */
                                  0x00  /* Le  */ };

        uint8_t response[32];

        success = nfc.inDataExchange(selectApdu, sizeof(selectApdu), response, &responseLength);

        if(success) {

          Serial.print("responseLength: "); Serial.println(responseLength);

          nfc.PrintHexChar(response, responseLength);

          do {
            uint8_t apdu[] = "Hello from Arduino";
            uint8_t back[32];
            uint8_t length = 32;

            success = nfc.inDataExchange(apdu, sizeof(apdu), back, &length);

            if(success) {

              Serial.print("responseLength: "); Serial.println(length);

              nfc.PrintHexChar(back, length);
            }
            else {

              Serial.println("Broken connection?");
            }
          }
          while(success);
        }
        else {

          Serial.println("Failed sending SELECT AID");
        }
      }
      else {

        Serial.println("Didn't find anything!");
      }

      delay(1000);
    }

    void printResponse(uint8_t *response, uint8_t responseLength) {

       String respBuffer;

        for (int i = 0; i < responseLength; i++) {

          if (response[i] < 0x10)
            respBuffer = respBuffer + "0"; //Adds leading zeros if hex value is smaller than 0x10

          respBuffer = respBuffer + String(response[i], HEX) + " ";
        }

        Serial.print("response: "); Serial.println(respBuffer);
    }

    void setupNFC() {

      nfc.begin();

      uint32_t versiondata = nfc.getFirmwareVersion();
      if (! versiondata) {
        Serial.print("Didn't find PN53x board");
        while (1); // halt
      }

      // Got ok data, print it out!
      Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);
      Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);
      Serial.print('.'); Serial.println((versiondata>>8) & 0xFF, DEC);

      // configure board to read RFID tags
      nfc.SAMConfig();
    }

body:
Solved. Set #if 1 and #elif 0.
Connected:
SCK to D5
MISO to D6
MOSI to D7
SS to D0 (and set it on pn532spi)


message:
pulseIn only returning 0

I'm new to arduino and I've searched through a lot of posts but can't find anything to fix the issue.

I'm trying to send a signal through some medium (water in this example) using a pizoelectric transducer and measure the time it takes for the signal to go from transducer to the other.

Attached is an image of the setup. Below is the code.

    const int trigPin = 1;
    const int echoPin = 0;
    float duration;

    void setup() {
      pinMode (trigPin, OUTPUT);
      pinMode (echoPin, INPUT);
      Serial.begin (9600);
    }

    void loop() {
      // set transmitting pin to low
      digitalWrite (trigPin, LOW);
      delayMicroseconds (2);

      // send the signal
      digitalWrite(trigPin, HIGH);
      digitalWrite (trigPin, LOW);

      // read in the signal on receiving pin, print duration to the Monitor
      duration = pulseIn (echoPin, HIGH);
      Serial.print("duration: ");
      Serial.print(duration);
      Serial.print("\n");
    }

The issue is "duration" variable has been 0 in all of my tests. I've tried using various values for the timeout parameter in pulsIn to no avail. Any advice is appreciated.
[![enter image description here][1]][1]

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

body:
There are a few issues here.

The most obvious is that you are using the wrong pins. On the Arduino
Uno, digital 0 is the serial RX pin, and digital 1 is TX. Thus, if you
use `Serial` in your sketch, you cannot use these pins for anything
else.

At a more fundamental level, it looks from your picture that you have
connected your Arduino to a couple of bare piezo transducers. Your code,
on the other hand, assumes the Arduino is connected to a digital sonar
module, like the very common [HC-SR04][]. You have to keep in mind that
a piezo transducer is an analog device. The sonar module, on the other
hand contains quite a few electronic parts that take care of
conditioning the analog signals and providing an easy to use digital
interface, where you just have to call `pulseIn()` to get the
measurement.

If you want to use the bare piezo transducers, the first thing you have
to do is _read their datasheet_. This is really essential. Once you have
read (and understood) that document, you can figure out whether or not
you need some interface electronics between the piezos and your Arduino.
Maybe you can get away with exciting the transmitter with PWM and
reading the receiver with the on-board ADC. Or maybe not. First read the
datasheet, then design your circuit, then test using a scope to look at
your signals.

[HC-SR04]: https://create.arduino.cc/projecthub/Isaac100/getting-started-with-the-hc-sr04-ultrasonic-sensor-036380


message:
Can a pin be Neutral, not high or low?

I'm trying to figure out a way to controll a DFplayer mini mp3 player with ADkeys.
Because I only have two or three files to play at a fixed volume I find it easier to just use the ADkeys. https://wiki.dfrobot.com/DFPlayer_Mini_SKU_DFR0299#target_4

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

Lets say I want to use Segment 1 - Segment 3 (MP3 file 1 - MP3 file 3). I would then connect a resistor (or none in Segment 1) in between and to three pins on the Arduino.
But how can I make the pin neutral, so that it does not trigger everything at once?
As far as I can read the pins are grounded in Arduino if not "high".

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

body:
What you are talking about in this instance is "Open Drain".  Normally, as you rightly note, with outputs you have either HIGH or LOW, which effectively connects the output pin to +5V or GND respectively.

Instead you are asking for Open Drain.  In this arrangement a pin is either "active", in which case it connects it to GND, or "inactive", in which case it is disconnected from (almost) anything.

Most 8-bit Arduino boards don't have Open Drain capability on their IO pins (some more advanced 32-bit boards do, though), but it is easy enough to emulate it in software.

You can emulate it using "Tri-State" logic.  That is logic where, as well as HIGH and LOW you have "High Impedance", or "HI-Z".  HI-Z is pretty much the same as "inactive" Open Drain. On the Arduino HI-Z is the same as INPUT.

So you can emulate it by:

* To activate a pin set it to OUTPUT and LOW
* To deactivate a pin set it to INPUT

For example, to "press" one of your buttons for 100ms you could:

    pinMode(4, OUTPUT);
    digitalWrite(4, LOW);
    delay(100);
    pinMode(4, INPUT);


body:
Your drawing appears to be attempting to provide analog levels to the DF miniplayer.

What you can do in that case is use two PWM outputs from the Arduino, with a RC lowpass filter to smooth the PWM into a DC level. (Arduino pin to 10K resistor, 4.7uF cap to gnd after that, the cap/resistor junction going to the DF Miniplayer).

Then

    analogWrite(pin, 128); // with pin being 3,5,6,9,10,11 on a Uno for example

to output 2.5V to the DF Miniplayer.
Similarly, 64 would be about 1.25V, while 192 would be about 3.75V.
Other levels are easily obtained.


message:
Communicate between 3 nodeMCU

How should I verify the communication between three node MCUs where one behaves as server and the other two as clients such that data of each node mcu is obtained on all three?

body:
communication between 3 nodemcu can be done instead don`t assume one nodemcu as server other two as client. Mqtt is a message protocol which is used to transfer messages. Connect all the three nodemcu`s in the same network and host a mqtt server separately in the same network. Mqtt has to flexibility to send data from one nodemcu to other nodemcus which are in the same network. Publish and subscribe method can be used to get data or post data.

Go through this link

http://mqtt.org/


message:
Sim808 module HTTP Bad request

I have an Arduino UNO and sim808 EVB-V3.02.4.
I want to send a GET request to my url but I always receive 400 Http bad request error.
```c
#include <DFRobot_sim808.h>
#include <SoftwareSerial.h>

#define PIN_TX    7
#define PIN_RX    8
SoftwareSerial mySerial(PIN_TX,PIN_RX);
DFRobot_SIM808 sim808(&mySerial);//Connect RX,TX,PWR,

char http_cmd[] = "GET /index.php?lat=10&long=100 HTTP/1.0\r\n\r\n";
char buffer[512];

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

void loop() {
  //*********** Attempt DHCP *******************
  while(!sim808.join(F("cmnet"))) {
      Serial.println("Sim808 join network error");
      delay(2000);
  }

  //************ Successful DHCP ****************
  Serial.print("IP Address is ");
  Serial.println(sim808.getIPAddress());

  //*********** Establish a TCP connection ************
  while(!sim808.connect(TCP,"39c309ae.ngrok.io", 80)) {
      Serial.println("Connect error");
  }
  Serial.println("Connection success");

  //*********** Send a GET request *****************
  Serial.println("waiting to fetch...");
  sim808.send(http_cmd, sizeof(http_cmd)-1);
  while (true) {
      int ret = sim808.recv(buffer, sizeof(buffer)-1);
      if (ret <= 0){
          Serial.println("fetch over...");
          break;
      }
      buffer[ret] = '\0';
      Serial.print("Recv: ");
      Serial.print(ret);
      Serial.print(" bytes: ");
      Serial.println(buffer);
      break;
  }

  //************* Close TCP or UDP connections **********
  sim808.close();

  //*** Disconnect wireless connection, Close Moving Scene *******
  sim808.disconnect();
  delay(5000);
  }
```

My php code:
```php
<?php
file_put_contents('test.txt', $_GET['lat'] . '---' . $_GET['lon']);
print '
<html>
<head>
<title>Good</title>
</head>
<body>
Was Good
</body>
</html>
';
?>
```

I want just open http://39c309ae.ngrok.io/index.php?lat=10&long=100 with arduino and sim808.

What is wrong in my codes?

body:
You aren't sending the `Host:` header with your request.  Without that the web server has no idea which website you want to get the /index.php page from.

    char http_cmd[] = "GET /index.php?lat=10&long=100 HTTP/1.0\r\n"
                      "Host: 39c309ae.ngrok.io\r\n"
                      "\r\n";


message:
How to manage two alarms with one interrupt?

I have a datalogger using the RTC DS3231 as an interrupt generator. I am able to have the interrupts work but here is my problem. I would like to take 2 separate measures from 2 different sensors (one for humidity, temperature and the other for accelerations), one every 30 min et one every hour, the thing is that because I use the same pin (only one pin from the DS3231) for both of these alarms I cannot use a simple counter in my interrupt function otherwise one measure will not be taken when both of the alarms will trigger...

For example I just did a quick test with one alarm each min when seconds are 00 and an other alarm each minute when seconds are 20. The problem as I said is that I cannot increment counters for each since I use the same interrupt function (because of the single pin).
Here is my loop function and interrupt handling function :
<!-- language-all: lang-cpp -->

    void loop() {
      delay(1000);
      sleepNow();
      if (alarm == true){
        handleAlarm(); // reset the possibility to trigger alarm
        if (counter_dtphl == COUNT_DTPHL){
          take_measure_DTPHL();
          counter_dtphl = 0;
        }
        else if (counter_accel == COUNT_ACCEL){
          take_measure_ACCEL();
          counter_accel = 0;
        }
      }
    }

    void wakeUpNow() {
      Serial.println("In wake up now");
      delay(100);
      alarm = true;
      //Serial.println(counter);
      sleep_disable();//Disable sleep mode
      byte sec = get_date(SEC);
      Serial.println(sec);
      if (sec == 0){
      counter_dtphl +=1;
      }
      else if (sec == 30){
      counter_accel +=1;
      }
      detachInterrupt(digitalPinToInterrupt(interruptPin)); //Removes the interrupt from pin 2;
    }

    void handleAlarm() {
      alarm = false;
      rtcObject.LatchAlarmsTriggeredFlags();
    }

COUNT_ACCEL and COUNT_DTPHL are constant having the value of minutes corresponding to the trigger for the measure.

Has anybody an idea how to manage this situation ?
For the acceleration I need to save the data for a period of 30 sec. One solution I tried is to increment the counter according to the time in second that corresponds each minute but I cannot put it in the wakeUpNow function since only fast processing should be done there (it is the function executed by the interrupt).

Thank you for your time !

body: After the interrupt read the time from the RTC and then do the correct thing based on the result.


body:
Consider it is good practice to leave as little code in an interrupt as possible.  In this case, as the time in question is much greater then how often the loop() function is called, setting a single flag indicating an interrupt occurred would be sufficient.

Each time in your loop() function test for this flag.  If TRUE, immediately set it to FALSE so as not forget to do so later.  Next, while still in the scope of the IF statement, assuming the RTC DS3231 has been configured to create an interrupt every 30 minutes, take your "30 minute sample".  Next, while still in the scope of the IF statement, increment a counter.  Make sure this counter is defined as a global variable in order to persist between calls to the loop() function.  If this counter has reached the value of 2, clear this counter to zero and take your "60 minute sample".

Consider the following **pseudo code**:

    // Global variable defined outside of functions to track state & time.
    bool state_interrupts;
    int counter_interrupts;

    void setup()
    {
      // Initialize RTC to generate an interrupt once every 30 minutes.
      <RTC initialization code.>
      // Call attach interrupt to identify interrupt function name "wakeUpNow".
      attachInterrupt(...)
      // Initialize state & counter;
      interrupts_state = false;
      interrupts_counter = 0;
    }

    void loop()
    {
      // Check if interrupt occurred.
      if(interrupts_state)
      {
        interrupts_state = false;
        interrupts_counter++;
        // Sample 30 minute sensor.
        <Sample 30 minute sensor code.>
        if(interrupts_counter >= 2)
        {
          interrupts_counter = 0;
          // Sample 60 minute sensor.
          <Sample 60 minute sensor code.>
        }
      }
    }

    void wakeUpNow()
    {
        interrupts_state = true;
    }


body:
The typical solution to this type of problem is:

1. In the ISR set a flag to indicate an RTC interrupt has occurred.
2. In the loop check the flag and if the set:
a) Read the alarm flags from the RTC,
b) Check the alarms, return value from LatchAlarmsTriggeredFlags(), and do the appropriate action.

What you should not do is write a lot of code in the ISR. Especially code that is also interrupt driven or depend on interrupts such as Wire, Serial, millis(), delay(), etc.

Cheers!


body:
Try this:
bool x = true; This is before setup
bool done = false;

x = !x;  Do this in the interrupt function.
done = true;
this is in your loop!
if done == true{    // Determine if you have been here before
if X !true do both functions
else
do the 30 second one
I use the !X as it is faster.
done = false;}
This should give you an idea, I did not actually code this but i use code similar to this all the time. My goal is to do no more then 1 or two instructions in the interrupt service routine (ISR).


message:
Nodemcu POST Response "-1"

**Nodemcu** device is returning **HTTP response -1** for a **POST** request on django rest api.

I tried the below http request to **Postman**, and it works perfectly fine.

http://localhost:8000/api/datalogs/?plant=http://localhost:8000/api/plants/1/&light=23&temperature=24&humidity=75&soil=Dry&moisture=787&remarks=/

This is my arduino post request:

    if(WiFi.status() == WL_CONNECTED) {
        HTTPClient http;

        http.begin(host_url);

        http.addHeader("Content-Type", "application/x-www-form-urlencoded");
        httpCode = http.POST(postData);

        payload = http.getString();
        http.end();
    }

The expected result is **200**, but I get **-1**. Can someone please explain?

body:
So, I found the solution. It was a very simple mistake. The **NodeMCU IP** is not the same as the **Computer IP** that the server was running on.

I changed the **localhost** string with the IP of my pc, and it worked perfectly fine.


message:
2 buttons pressed at the same time elevator logic

I have currently created a working elevator code where the elevator goes up when pressed a button, and stops at a floor when the sensor senses that it has reached the floor. This is how it works:

    #define Buzzer 5

    #define pwmMot 6

    #define halPin 8

    #define butto1 9  //level 1
    #define butto2 10 //level 2
    #define butto3 11 //level 3

    #define SeEcho 12
    #define SeTrig 13

    int button1_status = 0;
    int button2_status = 0;
    int button3_status = 0;

    int current_level = 1;
    int required_level =-1;

    void setup(){
      Serial.begin(9600);
      pinMode(Buzzer, OUTPUT);
      digitalWrite(Buzzer, HIGH);
      pinMode(halPin, INPUT);
      pinMode(butto1, INPUT);
      pinMode(butto2, INPUT);
      pinMode(butto3, INPUT);
      pinMode(SeTrig, OUTPUT);
      pinMode(SeEcho, INPUT);
      pinMode(pwmMot, OUTPUT);
      Serial.println("you are in level 1");
    }

    void emergencyStop(){
      analogWrite(pwmMot, 255);
    }
    int sensor() {
      unsigned long duration;
      int distance;
      digitalWrite(SeTrig, LOW);
      delayMicroseconds(2);
      digitalWrite(SeTrig, HIGH);
      delayMicroseconds(5);
      digitalWrite(SeTrig,LOW);
      duration = pulseIn(SeEcho,HIGH);
      distance = int(duration/2/29.412);
      return distance;
    }

    bool hallSen(){
      return digitalRead(halPin);
    }

    int going_up(){
      while (sensor() > 12){
        analogWrite(pwmMot, 1600);
      }
      return 1;
    }

    int going_down(){
      while (sensor() > 12){
        analogWrite(pwmMot, 570);
      }
      return 1;
    }

    void loop() {
      button1_status = digitalRead(butto1);
      button2_status = digitalRead(butto2);
      button3_status = digitalRead(butto3);
      required_level = button1_status == HIGH ? 1 : button2_status == HIGH ? 2 : button3_status == HIGH ? 3 : -1;
      if (required_level != -1 && required_level != current_level){
        while (current_level != required_level){
          if (current_level > required_level) Serial.println("Going Down"), current_level-=going_down();
          else if (current_level< required_level) Serial.println("Going Up"), current_level+=going_up();
          Serial.print("you are in level "); Serial.println(current_level);
          delay(1000);
        }
        analogWrite(pwmMot, 1550); //stop elevator
        digitalWrite(Buzzer, LOW);
        delay(100);
        digitalWrite(Buzzer, HIGH);
        required_level = -1;
      }
    }

Now I am just curious as to how I will extend this so that for example if we are in level 1, both the levels 2 and 3 are pressed it should go to level 2 even if level 3 was pressed first. Or if we are in level 2 and both level 1 and 3 are pressed, it should go to the one that is pressed first as both levels are the same distance from level 2.

body:
> if we are in level 1, both the levels 2 and 3 are pressed it should go
> to level 2 even if level 3 was pressed first.

For this to work, the program should remember which buttons (mind the
plural!) have been pressed. Thus, instead of remembering only one
request, as in

```c++
int required_level =-1;
```

it should have a boolean variable for each of the possible levels,
telling us whether a stop was requested for that level.

For convenience, I would number the levels from zero, and hold these
variables in an array:

```c++
const int LEVEL_COUNT = 3;
bool requested_stop[LEVEL_COUNT];
```

> if we are in level 2 and both level 1 and 3 are pressed, it should go
> to the one that is pressed first _as both levels are the same distance
> from level 2_.

The part I emphasized doesn't make sense to me. The elevator should go
to the one that was pressed first, _irrespective of the distances_.
Imagine you are in an elevator at level 5, and press the button for
level 2. As the elevator just starts moving down, another rider presses
the button for level 6. Should the elevator immediately revert to going
up in order to reach level 6, which is closer? Of course not. If it is
going down, it should continue in that direction. Now, if the other
rider presses 3, it should stop by level 3 on its way down, even though
you pressed 2 first.

As stated by chrisl in a comment, a [finite state machine][FSM] is
definitely the solution for this kind of problems. I propose a state
machine with three states, `STOPPED`, `GOING_UP`, and `GOING_DOWN`:

* when `STOPPED`, it should change to `GOING_UP` or `GOING_DOWN` as soon
  as a button for another level is pressed
* when `GOING_UP`, as soon as it reaches a level that has been
  requested, it should change to `STOPPED`
* same thing when `GOING_DOWN`.

And here is my proposed implementation:

```c++
void loop() {
    // Check the buttons.
    for (int i = 0; i < LEVEL_COUNT; i++)
        if (digitalRead(button[i]) == HIGH)
            requested_stop[i] = true;

    // Finite state machine.
    static enum { STOPPED, GOING_UP, GOING_DOWN } state = STOPPED;
    switch (state) {
    case STOPPED:
        requested_stop[current_level] = false;
        for (int i = 0; i < LEVEL_COUNT; i++) {
            if (requested_stop[i]) {
                if (i < current_level) {
                    analogWrite(pwmMot, PWM_DOWN);
                    state = GOING_DOWN;
                    break;
                } else if (i > current_level) {
                    analogWrite(pwmMot, PWM_UP);
                    state = GOING_UP;
                    break;
                }
            }
        }
        break;
    case GOING_UP:
        if (elevator_height() >= LEVEL_HEIGHT[current_level + 1]) {
            current_level++;
            if (requested_stop[current_level]) {
                analogWrite(pwmMot, PWM_STOP);
                state = STOPPED;
            }
        }
        break;
    case GOING_DOWN:
        if (elevator_height() <= LEVEL_HEIGHT[current_level - 1]) {
            current_level--;
            if (requested_stop[current_level]) {
                analogWrite(pwmMot, PWM_STOP);
                state = STOPPED;
            }
        }
        break;
    }
}
```

This code assumes you have written the function `elevator_height()` that
measures the height of the elevator, and have defined an array of
constants `LEVEL_HEIGHT[]`.

Notice that this is still far from perfect. You should probably ensure
that each stop lasts at least some minimum duration. Otherwise, if the
elevator stops at level 1 while level 0 has also been requested, the
stop will only last an instant. This can be achieved by splitting the
`STOPPED` state in two distinct states, and switching from “waiting for
the riders to go in/out” to “waiting for a button to be pressed” on a
timeout. You may also want to ensure that, after a stop, the elevator
continues in the same direction if possible. Otherwise it will never
reach level 2 if some joker is repeatedly pressing 0 and 1.

[FSM]: https://majenko.co.uk/blog/finite-state-machine


message:
Reset arduino nano after disabling tx/rx

I know, i am a bit dummy sometimes and i don't know why i actually did this but here it is. I have an arduino nano and i want it to use an external power via the the Vin port using a 12V external power supply. I thought this would be as simple as replacing the usb power supply by my external 12V power supply on the Vin pin.
But nothing works so i did some digging on the problem and after many tries like soldering the pins 25 and 26 of the FTDI or connect the TX/RX pins to the GND. Concerning that last point, because the TX/RX was still flashing after beeing connected to the GND i have put in my program this two lines to force TX/RX to be disabled and this is my mistake :
```
digitalWrite(0,LOW);
digitalWrite(1,LOW);
```
And now what a surprise i can't load a program in my arduino nano anymore even using another arduino to burn the bootloader. And i get this message :

```
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0x2e
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0x30
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0x2c
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0x33
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0x38
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0x2e
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0x33
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x31
```
I would like to come back to my factory arduino nano and/or enable once again the TX/RX connections ...

body: After some more tries something actually worked reinitialising the TX/RX pins, but i don't know why really. I wired RX pin to the reset and i loaded an empty code into the arduino, after that i was able to load any program into my arduino again. Problem solved, but why it solved the problem is the question now.


body:
You could also do this: in the IDE, select File:Preferences and turn on Verbose outputs.

Press & hold reset, that puts all the IO pins into Inputs, then start a download.
When the compiler process shows "compilation complete, xxxxxx bytes of 32xxx used" or similar, release the Reset button.

That allows the bootloader code to run and talk to the PC over the serial pins - before your sketch has chance to run and write the 2 serial pins low.

It might take a couple of tries to release Reset at the correct time. Be patient try a few times with just a short sketch to clear out the offending code:

    void setup();
    void loop();

That would do it.


message:
How can I program a ATmega328 au tqfp32 ( SMD ) chip?

I have some experience with the Arduino UNO , Nano , mega etc .. But today I want to upgrade my skills and knowledge to next level . So I am about to design my own PCB for ATmega328 au ( SMD ) but this time I want to use a tqfp32 programmer to get the job done .. I have searched the internet and I have found that people use Universal programmers ( ISP ) such as Top2013 universal programmer or TL86ii but I have no idea how to use them and I don't even know what  software that the youtubers are using ... They are actually uploading some *.hex files it seems I am not sure but they aren't using Arduino IDE . According to my knowledge they are using a tqfp32 to dip28 programming module ( I have attached a pic ) . And then the Module is mounted on top of the ISP . Then they have uploaded code using some unknown software. And few people are using USBasp , can any explain me the scenario and what they have done ..  https://youtu.be/GFyr9tVEHzQ
The link is a reference video .
![enter image description here](https://i.stack.imgur.com/2e7C0.jpg)![enter image description here](https://i.stack.imgur.com/mxMyw.png)

body:
To upload compiled code (.hex) to a bare atmega which doesn't have a bootloader installed you can use [ISP][1]. As this stands for **i**n-**s**ystem-**p**rogramming you don't have to flash the chip before assembly, but you can flash it in-system, so when already soldered onto your pcb. There actually is no need for those adapters like shown in your first picture, which often are a bit expensive. Also, both pictures stand in contrast to the idea of ISP, they seem to show firmware upload via serial connection, which as far as I know only works with a bootloader already installed...
ISP is based on SPI (serial peripheral interface) and you need to break out the corresponding pins to fit [this][2] connector. This obviously has the advantage of being able to update a firmware afterwards without the need of a bootloader.

Atmel provides a tool for flashing firmware via ISP which is called `avrdude` ([tutorial][3]) or you can use the atmel studio. To compile your code, you can use avr-gcc.

  [1]: https://en.wikipedia.org/wiki/In-system_programming?wprov=sfla1
  [2]: https://images.app.goo.gl/8WQpQTKuM1tE91jS9
  [3]: https://www.ladyada.net/learn/avr/avrdude.html


body:
I use Atmel AVR ISP MKii, which is a dedicated Programmer - it connects via USB to the PC, and to the Power/Gnd/Reset/SCK/MOSI/MISO pins of the SMD device (i.e. the pins that connect to an ICSP header if one were installed).  Then in the IDE you can select Upload Using Programmer, and it will load the .hex file that is created as part of the IDE compilation process into the chip.  This blows away any bootloader that might exist.

The Arduino as ISP does the same, running a sketch on an Uno for example that then interfaces with the PC and the target device to program it via the ICSP connection.

If the pins are not brought to a header, but are accessible via edge connecters, than a Programmer adapter can be used to connect the Programmer to the desired pins.  Imagine this board had a SMD package vs a DIP - then the 6 wires are connected to the desired pins, in this case via flying wires, and programming can be done.  A FTDI module is connected to other pins (5V, Gnd, DTR, Tx, Rx) just to provide power to the board. The AVR ISP MKii only monitors the power level in use (generally 3.3V or 5V) and adjusts its output levels accordingly.

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

The TQFP socket you show would generally be used to pre-program chips in a manufacturing type environment before they are installed on boards, or by a distributor like Digikey if you were ordering a large quantity of parts.

Making the ICSP pins accessible on board somehow is often not hard, and can be beneficial for making changes.

Here is an example of the same chip in a TQFP package, and you can see the dedicated ICSP and FTDI headers to allow onboard bootloading and then Serial downloads of code being developed.

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

I find the dedicated hardware very convenient as I bootload and/or program a lot of boards and SMD chips on boards.

I also have this adapter for Atmega328P chips that are installed on a board.  There are 6 little spring-loaded pins that press down onto the chip's ICSP pins from above to allow programming when an ICSP header is not provided, or the signals are not brought out to accessible pins. Unfortunately, hobbyking.com does not stock them anymore, this has gotten me out of a jam on occasion.

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

  [1]: https://i.stack.imgur.com/vKF5W.jpg
  [2]: https://i.stack.imgur.com/qL3BE.jpg
  [3]: https://i.stack.imgur.com/tkX9M.jpg


message:
Is it support to use Infrared radiation module in ESP12E?

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

I have a IR module -->image as shown

is it possible to use the IR module in esp8266?

how to do(sent and receive)?

what is the packet format of IR module?

please explain.

Thanks

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

body:
> is it possible to use the IR module in esp8266?

Yes.

> how to do(sent and recive)?

You send by pressing a button on your remote control. You receive by measuring the timing of the changes in the pin state.

> what is the packet format of IR module?

Whatever packet format your remote control sends.

It's no different using IR on an ESP8266 compared to an Arduino. There's a library that everyone uses (IRRemote.h), and there are plenty of examples and tutorials on the web (or on YouTube if you can't be bothered to read). I suggest you ask Google for some.


message:
Why do most arduino function return a -1 instead of a 0

Many arduino functions return -1 if something 'fails'. Serial.read for example returns -1 or the infamous ÿ when this function is called while the serial buffer is empty.

As embedded C progammer, I am personally a fan of letting functions return data in the form of modifying pointers which points to passed on addresses and return states with the actual return functionality of a function. I am used to return a 0 if a function is 'not done' or 'failed'.

I see no logic in why many arduino functions return an int type which contains -1 instead of just a 0.

Would it not be better to let functions return a boolean type or an unsigned char type in which false or '0' would indicate a 'failed' process and true or '1' would indicate a 'succesful' process?

Also: if I type:
```if(Serial.read()) {/* body */ }  ```
and ``` Serial.read() ``` returns -1 because the buffer is empty. Will the If's body be executed or not?

body:
I suspect that this a legacy from Unix command programming, which was first done in C. For commands that only needed to return status and not data, a return value of zero meant success and any other return value indicated some kind of failure. Individual programmers could designate specific non-zero values for specific error types, if desired.

Remember that the return value comes back to the calling function in a register. And these days the term "Arduino" encompasses a broad range of architectures, including 32-bit ARM Cortex-M. Specifying that the return value is a char offers no advantage in this case.

The boolean datatype is a fairly recent addition to the C language, so it's not surprising that you don't see it used much in existing, portable libraries.

Returning an address from a simple function that just needs to indicate success or failure seems like overkill.

If you really want control over the datatypes, include `stdint.h` and use the types defined therein. If you want an unsigned 8-bit value use `uint8_t` and not `unsigned char`. If you want to allow the compiler to choose the best datatype that is at least 8 bits, use `uint_fast8_tf`.


body:
I cannot assert anything for sure, as I was not involved in the design
of the Arduino APIs. However, just like Elliot Alderson, I suspect this
was inspired by the traditional C APIs. The manual page for `getchar()`,
which is a very old function from the standard C library, states:

> **fgetc**(),  **getc**() and **getchar**() return the character read
> as an _unsigned char_ cast to an _int_ or **EOF** on end of file or
> error.

Given that `EOF` is usually defined as `-1`, this is consistent with the
behavior of `Serial.read()`.

Being beginner-friendly is also a _major_ goal of the API. Pointers are
known to be a _huge_ difficulty for beginners.

There may also be some efficiency considerations involved. Arduino
started on the AVR platform. This is a RISC architecture, with a large
number of generic CPU registers (namely 32). The compiler usually
manages to allocate most local variables to registers. The calling
convention ensures that in most cases function parameters and return
values also go through CPU registers. This means we can avoid many RAM
accesses, which are inherently much slower than register access. Using a
return-by-pointer convention defeats these optimizations.

Lastly, it is a good thing that simple things are easy to write. For
example, an interpreter for single-character commands can be very easily
written as:

```c++
switch (Serial.read()) {
case 'a':
    do_command_a();
    break;
case 'b':
    do_command_b();
    break;
// etc...
}
```

with no need to explicitly test for the serial buffer not being empty.
Obviously, a more complex command language will need a full-blown
interpreter, but the focus of Arduino has always been on _simple_
programs being easy to write.


body:
-1 is returned when "0" would be a perfectly valid response.

To take your example of `Serial.read()`: 0 is a valid byte or ASCII character.  -1 isn't.  If you returned 0 for "failure" then there would be no way of differentiating between that and the valid byte value 0.


body:
Arduino API is port of Processing. Processing is Java API to communicate with a MCU running Firmata. Arduino enabled sketches with the same API to run directly on the MCU.

So for example stream functions from Java stream classes were ported to Arduino API. This includes the [read() function][2], to read one byte. Of course Java and Java basic libraries have inspiration in C++.

For other read and write functions, if the return value is count of bytes written or read then 0 is a valid return value and -1 indicates error.

Processing, Wiring and Arduino were created by interactive arts teachers and students, not by embedded systems developers. So you can't wonder about not ideal data types used. Later some things were improved by software developers.

----------

as embedded C developer you should know that:

 - 0 is a valid value to read, so it can't be a value indicating error
 - 'if' executes if the evaluated value is not 0

  [1]: https://www.arduino.cc/en/Guide/HowtoReferences
  [2]: https://docs.oracle.com/javase/8/docs/api/java/io/InputStream.html#read--


message:
How to display float variables on oled display (0.96'')

I have a similar problem than the discussed here : https://arduino.stackexchange.com/questions/17766/how-to-display-variables-on-0-96-oled-with-u8glib-library/17773#17773

I'd like to know how can I show float variables in place of int variables. What should i modify in this part of my code ?

    char buf[9];
    sprintf (buf, "%d", a);
    u8g.drawStr(18, 3, buf);

    } while( u8g.nextPage() );

    delay(200);

    }

Thanks in advance =D

body:
The printf group of functions in the Arduino library don't implement float and double conversions. For those, you need the function

    char *dtostrf(double dval, int8_t width, uint8_t prec, char *buf);
      Convert the double value passed in dval into an ASCII string stored in
      buf. Conversion is done as "[-]d.ddd". The minimum field width of the output
      string (including the '.' and the possible sign for negative values) is given
      in width, and prec determines the number of digits after the decimal. width
      is signed, negative for left adjustment.
      Returns buf.

, which you'll need to call for each float you want to convert.

Note that you could convert several floats into strings, upfront, each into its own character buffer, then use sprintf to format the final buffer - remembering that in `sprintf`'s format string, those buffers contain character strings, which you'll need to specify with '%s' format-specs.


body:
The u8glib library [provides the Arduino's standard `print()`
method][print]. You can the write:

```c++
u8g.setPrintPos(18, 3);
u8g.print(a);
```

and it should work for mostly any type of `a`.

[print]: https://github.com/olikraus/u8glib/wiki/userreference#print


message:
How can I use a variable to choose which Serial port to interact with?

In my use case I have multiple devices connected to the serial ports of an arduino. Currently I write to them using `Serial1.write()`, `Serial2.write()`, etc.

How can I choose the port programmatically, for example:
```
for(int i = 0; i < numDevices; i++){
  Serial[i].write();
}
```

body:
You may use an array of pointers to the actual serial ports. For
example, on an Arduino Mega:

```c++
const size_t PORTS_COUNT = 4;
const HardwareSerial *ports[PORTS_COUNT] = {
    &Serial, &Serial1, &Serial2, &Serial3
};

void setup() {
    for (size_t i = 0; i < PORTS_COUNT; i++)
        ports[i]->begin(9600);
}
```