body:
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

title: Parent class callback from child class

Answers: 2

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() {
        ...
      }
    }


body:
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.

title: Not getting any output from ECG sensor AD8232

Answers: 1

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.


body:
I'm trying to connect a GPS unit (GY-GPS6MV2) and an OLED screen as in the diagram below (green connector is GPS; VCC, RX, TX, GND left to right):

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

Here's the code I've come up with:

    #include <Wire.h>
    #include <Adafruit_SH1106.h>
    #include <TinyGPS++.h>
    #include <SoftwareSerial.h>

    #define OLED_RESET 4
    Adafruit_SH1106 display(OLED_RESET);
    static const int RXPin = 5, TXPin = 3;
    static const uint32_t GPSBaud = 9600;
    float vkph;
    float vmps;

    TinyGPSPlus gps;
    SoftwareSerial ss(RXPin, TXPin);

    void setup(){
      Serial.begin(9600);
      ss.begin(GPSBaud);
      display.begin(SH1106_SWITCHCAPVCC, 0x3C);
      display.display();
      delay(2000);
      display.clearDisplay();
    }

    void loop(){
      while (ss.available() > 0){
        gps.encode(ss.read());
        vkph = gps.speed.kmph();
        vmps = gps.speed.mps();
        if (gps.location.isUpdated()){
          Serial.print("Position: ");
          Serial.print(gps.location.lat(), 6);
          Serial.print(" : ");
          Serial.println(gps.location.lng(), 6);
          Serial.print("Speed: ");
          Serial.print(vmps);
          Serial.print(" m/s");
          Serial.print(", ");
          Serial.print(vkph);
          Serial.println( " km/hr");

          display.clearDisplay();
          display.setTextSize(2);
          display.setTextColor(WHITE);
          display.setCursor(0,0);
          display.println("Hello"); // Changing this to display.println(vmps);
          display.setTextSize(2);
          display.setTextColor(WHITE);
          display.println("World"); // Changing this to display.println(vkph);
          display.display();
          delay(1000);

        }
      }
    }

The GPS outputs to the serial monitor fine, and the screen displays "Hello `\n` World" as expected. But when I make the changes indicated in the comments to the display part of the code, the display just shows its splash screen, flashing when the GPS updates.

How can I get the display to show the speeds in m/s and km/hr?

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

title: OLED not updating display

Answers: 1

body:
> Maybe you need to add `delay()` in your code,I am not sure.

    display.clearDisplay();
          display.setTextSize(2);
          display.setTextColor(WHITE);
          display.setCursor(0,0);
          display.println("Hello"); // Changing this to display.println(vmps);
          display.setTextSize(2);
          display.setTextColor(WHITE);
          display.println("World"); // Changing this to display.println(vkph);
          display.display();
          delay(1000);


body:
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.

<!--- --->

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

Answers: 1

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


body:
I have written a class for generating a 25khz pwm signal for the Arduino Nano. This works great (pin 9 and 10 only) on the Nano. I want to switch to Arduino Every; this code does no longer work (the registers are unknown ‘not declared in this scope’ is the compiler error). The Every is suppose to be a drop in replacement for the Nano; how to generate a 25KHz PWM on the Arduino Every?
<!-- language-all: lang-cpp -->

    #include <Arduino.h>
    #include "HixPinPWM25KHz.h"

    HixPinPWM25KHz::HixPinPWM25KHz(int nPinNumber): HixPin(nPinNumber) {
    }

    void HixPinPWM25KHz::begin() {
      //25KHz PWM only supported on ping 9 and 10
      if ( (m_nPinNumber != 9) && (m_nPinNumber != 10) ) {
        return;
      }
      // Configure Timer 1 for PWM @ 25 kHz.
      TCCR1A = 0;           // undo the configuration done by...
      TCCR1B = 0;           // ...the Arduino core library
      TCNT1  = 0;           // reset timer
      TCCR1A = _BV(COM1A1)  // non-inverted PWM on ch. A
               | _BV(COM1B1)  // same on ch; B
               | _BV(WGM11);  // mode 10: ph. correct PWM, TOP = ICR1
      TCCR1B = _BV(WGM13)   // ditto
               | _BV(CS10);   // prescaler = 1
      ICR1   = 320;         // TOP = 320
      pinMode(m_nPinNumber, OUTPUT);
      analogWrite(50);
    }

    void HixPinPWM25KHz::analogWrite(float percent) {
      int value = (int) ( (percent * (float)320) / (float)100 );
      switch (m_nPinNumber) {
        case 9:
          OCR1A = value;
          break;
        case 10:
          OCR1B = value;
          break;
        default:
          // no other pin will work
          break;
      }
    }

title: Arduino Every 25k PWM signal

Answers: 0


body:
I have a blood glucose meter which supports downloading data to computer using a serial cable and its own software. I made a serial cable for this with a usb to ttl pl2303 and its working. I can download the data from the device to my pc using that software but now I want get the data to my arduino using serial communication. I have a serial monitor software which detects the communication between the device and the software usin com port.
Can any one please tell me how to get the data to my arduino?
I have attached the dump file from that serial monitor.

    [31/08/2019 21:32:16] - Open port COM12 (C:\Program Files\Eltima Software\Serial Port Monitor\SerialMonitorx64.exe)

    [31/08/2019 21:35:10] - Open port COM12 (C:\Users\User\AppData\Local\Diabetes_Management\Diabetes_Management_APP.exe)

    [31/08/2019 21:35:10] Written data (COM12)
        55                                                U
    [31/08/2019 21:35:11] - Close port COM12

    [31/08/2019 21:35:11] - Open port COM12 (C:\Users\User\AppData\Local\Diabetes_Management\Diabetes_Management_APP.exe)

    [31/08/2019 21:35:11] Written data (COM12)
        05                                                .
    [31/08/2019 21:35:12] - Close port COM12

    [31/08/2019 21:35:12] - Open port COM12 (C:\Users\User\AppData\Local\Diabetes_Management\Diabetes_Management_APP.exe)

    [31/08/2019 21:35:13] Written data (COM12)
        05                                                .
    [31/08/2019 21:35:13] Read data (COM12)
        01 47 6c 75 63 6f 73 65 0d 0a 02 31 2c 32 30 31   .Glucose...1,201
        38 2c 30 37 2c 32 30 2c 30 31 2c 30 30 2c 31 2e   8,07,20,01,00,1.
        31 2c 6d 6d 6f 6c 5f 4c 0d 0a 32 2c 32 30 31 38   1,mmol_L..2,2018
        2c 30 37 2c 32 30 2c 30 31 2c 30 30 2c 31 2e 31   ,07,20,01,00,1.1
        2c 6d 6d 6f 6c 5f 4c 0d 0a 33 2c 32 30 31 38 2c   ,mmol_L..3,2018,
        30 37 2c 32 30 2c 30 31 2c 33 37 2c 32 2e 34 2c   07,20,01,37,2.4,
        6d 6d 6f 6c 5f 4c 0d 0a 34 2c 32 30 31 38 2c 30   mmol_L..4,2018,0
        37 2c 32 30 2c 30 31 2c 33 36 2c 31 2e 31 2c 6d   7,20,01,36,1.1,m
        6d 6f 6c 5f 4c 0d 0a 35 2c 32 30 31 38 2c 30 37   mol_L..5,2018,07
        2c 32 30 2c 30 31 2c 33 35 2c 33 32 2e 37 2c 6d   ,20,01,35,32.7,m
        6d 6f 6c 5f 4c 0d 0a 03 04                        mol_L....
    [31/08/2019 21:35:14] - Close port COM12

.
```
--------------------------------------
#   Time                Function                                                Dir   Status           Data                                                        Data (chars)       Data length   Req. length  Port        Comments
0   31/08/2019 21:32:16 IRP_MJ_CREATE                                           DOWN                   C:\Program Files\Eltima Software\Serial Port Monitor\SerialMonitorx64.exe                                 COM12
1   31/08/2019 21:32:16 IRP_MJ_CREATE                                           UP    STATUS_SUCCESS   C:\Program Files\Eltima Software\Serial Port Monitor\SerialMonitorx64.exe                                 COM12
2   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK)      DOWN                   19 01 00 00                                                 ....                  4                       COM12
3   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK)      UP    STATUS_SUCCESS                                                                                COM12
4   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      DOWN                                                                                COM12
5   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      UP    STATUS_SUCCESS   80 25 00 00                                                 €%..                  4                       COM12
6   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_LINE_CONTROL)   DOWN                                                                                COM12
7   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_LINE_CONTROL)   UP    STATUS_SUCCESS   00 00 08                                                    ...                   3                       COM12
8   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_CHARS)          DOWN                                                                                COM12
9   31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_CHARS)          UP    STATUS_SUCCESS   1a 00 00 1a 11 13                                           ......                6                       COM12
10  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_HANDFLOW)       DOWN                                                                                COM12
11  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_HANDFLOW)       UP    STATUS_SUCCESS   00 00 00 00 00 00 00 00 00 08 00 00 00 02 00 00             ................      16                      COM12
12  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK)       DOWN                                                                                COM12
13  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      DOWN                                                                                COM12
14  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      UP    STATUS_SUCCESS   80 25 00 00                                                 €%..                  4                       COM12
15  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_LINE_CONTROL)   DOWN                                                                                COM12
16  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_LINE_CONTROL)   UP    STATUS_SUCCESS   00 00 08                                                                          3                       COM12
17  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_CHARS)          DOWN                                                                                COM12
18  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_CHARS)          UP    STATUS_SUCCESS   1a 00 00 1a 11 13                                           ......                6                       COM12
19  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_HANDFLOW)       DOWN                                                                                COM12
20  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_HANDFLOW)       UP    STATUS_SUCCESS   00 00 00 00 00 00 00 00 00 08 00 00 00 02 00 00             ................      16                      COM12
21  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE)      DOWN                   00 4b 00 00                                                 .K..                  4                       COM12
22  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE)      UP    STATUS_SUCCESS                                                                                COM12
23  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_RTS)            DOWN                                                                                COM12
24  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_RTS)            UP    STATUS_SUCCESS                                                                                COM12
25  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_DTR)            DOWN                                                                                COM12
26  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_DTR)            UP    STATUS_SUCCESS                                                                                COM12
27  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL)   DOWN                   00 00 08                                                    ...                   3                       COM12
28  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_LINE_CONTROL)   UP    STATUS_SUCCESS                                                                                COM12
29  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_CHARS)          DOWN                   1a 00 00 1a 11 13                                           ......                6                       COM12
30  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_CHARS)          UP    STATUS_SUCCESS                                                                                COM12
31  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_HANDFLOW)       DOWN                   01 00 00 00 40 00 00 00 00 08 00 00 00 02 00 00             ....@...........      16                      COM12
32  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_HANDFLOW)       UP    STATUS_SUCCESS                                                                                COM12
33  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_MODEMSTATUS)    DOWN                                                                                COM12
34  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_MODEMSTATUS)    UP    STATUS_SUCCESS   f0 00 00 00                                                 ð...                  4                       COM12
35  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_TIMEOUTS)       DOWN                   00 00 00 00 00 00 00 00 2c 01 00 00 00 00 00 00 2c 01 00 00 ........,.......,...  20                      COM12
36  31/08/2019 21:32:16 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_TIMEOUTS)       UP    STATUS_SUCCESS                                                                                COM12
37  31/08/2019 21:32:26 IRP_MJ_WRITE                                            DOWN                   55                                                          U                     1           1           COM12
38  31/08/2019 21:32:26 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   55                                                          U                     1                       COM12
39  31/08/2019 21:32:31 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
40  31/08/2019 21:32:31 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
41  31/08/2019 21:32:35 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
42  31/08/2019 21:32:35 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
43  31/08/2019 21:32:38 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
44  31/08/2019 21:32:38 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
45  31/08/2019 21:32:44 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
46  31/08/2019 21:32:44 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
47  31/08/2019 21:33:42 IRP_MJ_WRITE                                            DOWN                   55                                                          U                     1           1           COM12
48  31/08/2019 21:33:42 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   55                                                          U                     1                       COM12
49  31/08/2019 21:33:45 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
50  31/08/2019 21:33:45 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
51  31/08/2019 21:33:47 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
52  31/08/2019 21:33:47 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
53  31/08/2019 21:33:48 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
54  31/08/2019 21:33:48 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
55  31/08/2019 21:33:57 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE)      DOWN                   6e 00 00 00                                                 n...                  4                       COM12
56  31/08/2019 21:33:57 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_BAUD_RATE)      UP    STATUS_SUCCESS                                                                                COM12
57  31/08/2019 21:33:57 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      DOWN                                                                                COM12
58  31/08/2019 21:33:57 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      UP    STATUS_SUCCESS   4b 00 00 00                                                 K...                  4                       COM12
59  31/08/2019 21:34:01 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      DOWN                                                                                COM12
60  31/08/2019 21:34:01 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_GET_BAUD_RATE)      UP    STATUS_SUCCESS   4b 00 00 00                                                 K...                  4                       COM12
61  31/08/2019 21:34:04 IRP_MJ_WRITE                                            DOWN                   55                                                          U                     1           1           COM12
62  31/08/2019 21:34:04 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   55                                                          U                     1                       COM12
63  31/08/2019 21:34:09 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
64  31/08/2019 21:34:09 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
65  31/08/2019 21:34:11 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
66  31/08/2019 21:34:11 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
67  31/08/2019 21:34:15 IRP_MJ_WRITE                                            DOWN                   2e                                                          .                     1           1           COM12
68  31/08/2019 21:34:15 IRP_MJ_WRITE                                            UP    STATUS_SUCCESS   2e                                                          .                     1                       COM12
69  31/08/2019 21:34:21 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK)      DOWN                   00 00 00 00                                                 ....                  4                       COM12
70  31/08/2019 21:34:21 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_WAIT_ON_MASK)       UP    STATUS_SUCCESS   00 00 00 00                                                 ....                  4                       COM12
71  31/08/2019 21:34:21 IRP_MJ_DEVICE_CONTROL (IOCTL_SERIAL_SET_WAIT_MASK)      UP    STATUS_SUCCESS                                                                                COM12
```

[Dump file 1][1]

[New Dump file][2]

  [1]: https://drive.google.com/file/d/1g22-CNliOI4sFqon6EfdgDC7INWcTrzy/view?usp=sharing
  [2]: https://drive.google.com/open?id=1F80u5075dv3v1FT9lBTRvktpozyAukhc

title: Serial Communication with a Serial device

Answers: 0


body:
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();
  }
}
~~~

Answers: 3

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:
proper way would be to add `WebSocketsServer.h` to list of locations that gcc looks for. see: https://gcc.gnu.org/onlinedocs/gcc-2.95.3/cpp_1.html#SEC6

another way would be to download `WebSocketsServer.zip` from  https://www.arduinolibraries.info/libraries/web-sockets
to your workdir and unzip it

replace
```
#include <WebSocketsServer.h>
```
 with explicit location
```
#include "./WebSockets-2.3.5/src/WebSocketsServer.h"
```
(note unziped version in this case is WebSockets-2.3.5)

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


body:
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?

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

Answers: 2

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.


body:
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?

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

Answers: 1

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


body:
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?

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

Answers: 1

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


body:
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!

title: Run light sequence function continuously in if statement

Answers: 1

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;}
    }


body:
I am following [this tutorial][1] and have an MPU-6050 connected to an Arduino Micro with the following connections

>VCC - 5V/3.3V
GND - GND
SDA - A2
SCL - A3

I'm trying to run the short example sketch:

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

    // MPU-6050 Short Example Sketch
    // By Arduino User JohnChi
    // August 17, 2014
    // Public Domain
    #include <Wire.h>
    const int MPU_addr=0x68;  // I2C address of the MPU-6050
    int16_t AcX,AcY,AcZ,Tmp,GyX,GyY,GyZ;

    void setup(){
      Wire.begin();
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x6B);  // PWR_MGMT_1 register
      Wire.write(0);     // set to zero (wakes up the MPU-6050)
      Wire.endTransmission(true);
      Serial.begin(9600);
    }

    void loop(){
      Wire.beginTransmission(MPU_addr);
      Wire.write(0x3B);  // starting with register 0x3B (ACCEL_XOUT_H)
      Wire.endTransmission(false);
      Wire.requestFrom(MPU_addr,14,true);  // request a total of 14 registers
      AcX=Wire.read()<<8|Wire.read();  // 0x3B (ACCEL_XOUT_H) & 0x3C (ACCEL_XOUT_L)
      AcY=Wire.read()<<8|Wire.read();  // 0x3D (ACCEL_YOUT_H) & 0x3E (ACCEL_YOUT_L)
      AcZ=Wire.read()<<8|Wire.read();  // 0x3F (ACCEL_ZOUT_H) & 0x40 (ACCEL_ZOUT_L)
      Tmp=Wire.read()<<8|Wire.read();  // 0x41 (TEMP_OUT_H) & 0x42 (TEMP_OUT_L)
      GyX=Wire.read()<<8|Wire.read();  // 0x43 (GYRO_XOUT_H) & 0x44 (GYRO_XOUT_L)
      GyY=Wire.read()<<8|Wire.read();  // 0x45 (GYRO_YOUT_H) & 0x46 (GYRO_YOUT_L)
      GyZ=Wire.read()<<8|Wire.read();  // 0x47 (GYRO_ZOUT_H) & 0x48 (GYRO_ZOUT_L)
      Serial.print("AcX = "); Serial.print(AcX);
      Serial.print(" | AcY = "); Serial.print(AcY);
      Serial.print(" | AcZ = "); Serial.print(AcZ);
      Serial.print(" | Tmp = "); Serial.print(Tmp/340.00+36.53);  //equation for temperature in degrees C from datasheet
      Serial.print(" | GyX = "); Serial.print(GyX);
      Serial.print(" | GyY = "); Serial.print(GyY);
      Serial.print(" | GyZ = "); Serial.println(GyZ);
      delay(333);
    }

But the output keeps showing -1 for all the fields.

Are these values actually correct or am I doing something wrong?

  [1]: https://playground.arduino.cc/Main/MPU-6050/

title: MPU-6050 showing all -1s

Answers: 0


body:
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();
    }

title: Wiring ESP8266 and PN532

Answers: 1

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)


body:
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

title: pulseIn only returning 0

Answers: 1

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


body: arduino uno, esp8266, rfid module rc522, sd card module, real time clock module, buzzer, led light and battery holder. I was planning to build a sensor that monitors attendance with the use of and RFID card, and I was planning to make it run on its own with the help of a battery instead of being connected to a computer. If not, is there another way that would be possible?

title: Can the following materials be used to power up an attendance based sensor?

Answers: 0


body:
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

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

Answers: 2

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.


body: 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?

title: Communicate between 3 nodeMCU

Answers: 1

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/


body:
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?

title: Sim808 module HTTP Bad request

Answers: 1

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";


body:
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 !

title: How to manage two alarms with one interrupt?

Answers: 4

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).


body: I need to read alot of buttons and analog inputs for my project (60 buttons 15 faders) and there fore need to use multiplexers. But most mux libraries seems to only support one mux, am i wrong?

title: How to read from multiple multiplexers (CD74HC4067) with a library

Answers: 0


body:
I am trying to use my Arduino Leonardo (or Uno!) as a remote with the [IRRemote library][1]. **The current setup picks up and decodes a signal perfectly, but fails to retransmit it.**

I have tested the infrared LED and it works.

I have tested the setup against a television IR receiver at very close range.

My board consists of:

[![board schematic][2]][2]

I am using the example IRRecord code (included below) with one change -- I made STATUS_PIN P3 (instead of P13), as I read that [P13 is used to transmit IR signal on the Leonardo][3]. I made this change after testing all PWM pins (including P3) for transmitting the IR signal. I'd appreciate any help to get this working.

I have also tried this on an Arduino Uno to no effect. This is driving me a little crazy!

Code below.

    /*
     * IRrecord: record and play back IR signals as a minimal
     * An IR detector/demodulator must be connected to the input RECV_PIN.
     * An IR LED must be connected to the output PWM pin 3.
     * A button must be connected to the input BUTTON_PIN; this is the
     * send button.
     * A visible LED can be connected to STATUS_PIN to provide status.
     *
     * The logic is:
     * If the button is pressed, send the IR code.
     * If an IR code is received, record it.
     *
     * Version 0.11 September, 2009
     * Copyright 2009 Ken Shirriff
     * http://arcfn.com
     */

    #include <IRremote.h>

    int RECV_PIN = 11;
    int BUTTON_PIN = 12;
    int STATUS_PIN = 3;

    IRrecv irrecv(RECV_PIN);
    IRsend irsend;

    decode_results results;

    void setup()
    {
      Serial.begin(9600);
      irrecv.enableIRIn(); // Start the receiver
      pinMode(BUTTON_PIN, INPUT);
      pinMode(STATUS_PIN, OUTPUT);
    }

    // Storage for the recorded code
    int codeType = -1; // The type of code
    unsigned long codeValue; // The code value if not raw
    unsigned int rawCodes[RAWBUF]; // The durations if raw
    int codeLen; // The length of the code
    int toggle = 0; // The RC5/6 toggle state

    // Stores the code for later playback
    // Most of this code is just logging
    void storeCode(decode_results *results) {
      codeType = results->decode_type;
      int count = results->rawlen;
      if (codeType == UNKNOWN) {
        Serial.println("Received unknown code, saving as raw");
        codeLen = results->rawlen - 1;
        // To store raw codes:
        // Drop first value (gap)
        // Convert from ticks to microseconds
        // Tweak marks shorter, and spaces longer to cancel out IR receiver distortion
        for (int i = 1; i <= codeLen; i++) {
          if (i % 2) {
            // Mark
            rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK - MARK_EXCESS;
            Serial.print(" m");
          }
          else {
            // Space
            rawCodes[i - 1] = results->rawbuf[i]*USECPERTICK + MARK_EXCESS;
            Serial.print(" s");
          }
          Serial.print(rawCodes[i - 1], DEC);
        }
        Serial.println("");
      }
      else {
        if (codeType == NEC) {
          Serial.print("Received NEC: ");
          if (results->value == REPEAT) {
            // Don't record a NEC repeat value as that's useless.
            Serial.println("repeat; ignoring.");
            return;
          }
        }
        else if (codeType == SONY) {
          Serial.print("Received SONY: ");
        }
        else if (codeType == PANASONIC) {
          Serial.print("Received PANASONIC: ");
        }
        else if (codeType == JVC) {
          Serial.print("Received JVC: ");
        }
        else if (codeType == RC5) {
          Serial.print("Received RC5: ");
        }
        else if (codeType == RC6) {
          Serial.print("Received RC6: ");
        }
        else {
          Serial.print("Unexpected codeType ");
          Serial.print(codeType, DEC);
          Serial.println("");
        }
        Serial.println(results->value, HEX);
        codeValue = results->value;
        codeLen = results->bits;
      }
    }

    void sendCode(int repeat) {
      if (codeType == NEC) {
        if (repeat) {
          irsend.sendNEC(REPEAT, codeLen);
          Serial.println("Sent NEC repeat");
        }
        else {
          irsend.sendNEC(codeValue, codeLen);
          Serial.print("Sent NEC ");
          Serial.println(codeValue, HEX);
        }
      }
      else if (codeType == SONY) {
        irsend.sendSony(codeValue, codeLen);
        Serial.print("Sent Sony ");
        Serial.println(codeValue, HEX);
      }
      else if (codeType == PANASONIC) {
        irsend.sendPanasonic(codeValue, codeLen);
        Serial.print("Sent Panasonic");
        Serial.println(codeValue, HEX);
      }
      else if (codeType == JVC) {
        irsend.sendPanasonic(codeValue, codeLen);
        Serial.print("Sent JVC");
        Serial.println(codeValue, HEX);
      }
      else if (codeType == RC5 || codeType == RC6) {
        if (!repeat) {
          // Flip the toggle bit for a new button press
          toggle = 1 - toggle;
        }
        // Put the toggle bit into the code to send
        codeValue = codeValue & ~(1 << (codeLen - 1));
        codeValue = codeValue | (toggle << (codeLen - 1));
        if (codeType == RC5) {
          Serial.print("Sent RC5 ");
          Serial.println(codeValue, HEX);
          irsend.sendRC5(codeValue, codeLen);
        }
        else {
          irsend.sendRC6(codeValue, codeLen);
          Serial.print("Sent RC6 ");
          Serial.println(codeValue, HEX);
        }
      }
      else if (codeType == UNKNOWN /* i.e. raw */) {
        // Assume 38 KHz
        irsend.sendRaw(rawCodes, codeLen, 38);
        delay(100);
        Serial.println("Sent raw");
      }
    }

    int lastButtonState;

    void loop() {
      // If button pressed, send the code.
      int buttonState = digitalRead(BUTTON_PIN);
      if (lastButtonState == HIGH && buttonState == LOW) {
        Serial.println("Released");
        irrecv.enableIRIn(); // Re-enable receiver
      }

      if (buttonState) {
        Serial.println("Pressed, sending");
        digitalWrite(STATUS_PIN, HIGH);
        sendCode(lastButtonState == buttonState);
        digitalWrite(STATUS_PIN, LOW);
        delay(50); // Wait a bit between retransmissions
      }
      else if (irrecv.decode(&results)) {
        digitalWrite(STATUS_PIN, HIGH);
        storeCode(&results);
        irrecv.resume(); // resume receiver
        digitalWrite(STATUS_PIN, LOW);
      }
      lastButtonState = buttonState;
    }

  [1]: https://github.com/z3t0/Arduino-IRremote
  [2]: https://i.stack.imgur.com/mPf3q.jpg
  [3]: https://irforum.analysir.com/viewtopic.php?t=5

title: Problem sending IR signal on Arduino Leonardo/Uno (IRRemote library)

Answers: 0


body:
**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?

title: Nodemcu POST Response "-1"

Answers: 1

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.


body:
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.

title: 2 buttons pressed at the same time elevator logic

Answers: 1

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


body:
When my system is confronting at logical & hardwaretical problem,
I want to make system know It has some problem and reset automatically
because my esp8266(nodeMCU) is on the place where people usually cannot touch.

so I apply this 'ticker' code, but I think they are not working when it is on  problem status.

please see my code and give me some advice that how to make system know the problem status and do reset automatically.

```
//these are global values
Ticker ticker;
volatile unsigned int ISRcounter = 0;

void setup(){

ticker.attach(2,ISRdog);
//ticker always give Interrupt every 2 second.
//and when it get Interrupt, ISRdog function is called.
}

void ISRdog() {
  ISRcounter += 1;
//when ISR is called, ISRcounter is ++.

  if (ISRcounter == 10) {
    ESP.deepSleep(5e5); //reset
//and when it is 10, deepSleep for 5second and automatically wakeup.
//so it means, 'system reset'

  }

}

void loop(){

ISRcounter=0;
//when program running properly, system's flow always go to loop in final.
//so at the loop, make ISRcounter =0, for not making the system reset(ISRcounter==10)

.....
}

...and other functions ....

```

In short, this code is making reset until the system is not entering the  _loop()_ over 20second.

so I expect when system get problem somehow, then system do not enter to the _loop()_ and It means ISRcounter is getting 10, without =0. so system should be resetted.
but It did not worked. did not automatically resetted.

title: How to make watchdog and automatically reset on esp8266

Answers: 0


body:
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 ...

title: Reset arduino nano after disabling tx/rx

Answers: 2

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.


body:
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)

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

Answers: 2

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


body:
[![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

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

Answers: 1

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.