message:
0 temperature & hummidity DH11

Alright so I'm having problems with my code. Its my first time using DH11

I keep on getting that temperature is 0 degrees so as the humidity

    #include "dht.h"
    #define dht_apin A0

    dht DHT;

    void setup(){

      Serial.begin(9600);
      delay(500);
      Serial.println("DHT11 Humidity & temperature Sensor\n\n");
      delay(1000);

    }

    void loop()
    {

        DHT.read11(dht_apin);

        Serial.print("Current humidity = ");
        Serial.print(DHT.humidity);
        Serial.print("%  ");
        Serial.print("temperature = ");
        Serial.print(DHT.temperature);
        Serial.println("C  ");

        delay(5000)

    }

What Im getting is basically

> Current humidity = 0.00%  temperature = 0.00C

body:
I have run into problems when using some `DHT` library versions.  May I suggest that you try using a different version of `dht.h`?

This version works for me (there is a [newer version][1] I have NOT tested):

dht.h (606B 6/12/2012)

 //
 //    FILE: dht.h
 // VERSION: 0.1.00
 // PURPOSE: DHT Temperature & Humidity Sensor library for Arduino
 //
 //     URL: http://arduino.cc/playground/Main/DHTLib
 //
 // HISTORY:
 // see dht.cpp file
 //

 #ifndef dht_h
 #define dht_h

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

 #define DHT_LIB_VERSION "0.1.00"

 class dht
 {
 public:
  int read11(uint8_t pin);
     int read22(uint8_t pin);
  double humidity;
  double temperature;

 private:
  uint8_t bits[5];  // buffer to receive data
  int read(uint8_t pin);
 };
 #endif
 //
 // END OF FILE
 //

  [1]: http://arduino.cc/playground/Main/DHTLib


sender: user

message:
Interrupts arduino interrupting serial comunication

I have problem with communicating VB.Net-Arduino.

It seems the interrupt pause my serial communication line in `void loop() { ... }`. I don't know what to do, and I can't erase interrupts line since I got this code from another site and he said that the interrupt play important role in this code.

So, is there another method to keep interrupts like make a new void in the code? Could you help me, please?

here is the code:

```c++
//For MEGA 2560

int i = 0;
int j = 0;
int k = 0;

int x = 0;
int y = 0;
int z = 0;

int OK = 0;
int OK1 = 0;
int OK2 = 0;
int OK3 = 0;
int OK4 = 0;

int sinPWM[] = {
    0, 1, 2, 3, 4, 6, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 21, 22,
    23, 24, 26, 27, 28, 29, 31, 32, 33, 34, 36, 37, 38, 39, 40, 42, 43,
    44, 45, 47, 48, 49, 50, 52, 53, 54, 55, 56, 58, 59, 60, 61, 62, 64,
    65, 66, 67, 68, 70, 71, 72, 73, 74, 76, 77, 78, 79, 80, 82, 83, 84,
    85, 86, 87, 89, 90, 91, 92, 93, 94, 96, 97, 98, 99, 100, 101, 102,
    104, 105, 106, 107, 108, 109, 110, 111, 112, 114, 115, 116, 117,
    118, 119, 120, 121, 122, 123, 125, 126, 127, 128, 129, 130, 131,
    132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144,
    145, 147, 148, 149, 150, 151, 152, 152, 153, 154, 155, 156, 157,
    158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
    171, 171, 172, 173, 174, 175, 176, 177, 178, 179, 179, 180, 181,
    182, 183, 184, 185, 185, 186, 187, 188, 189, 189, 190, 191, 192,
    193, 193, 194, 195, 196, 197, 197, 198, 199, 200, 200, 201, 202,
    203, 203, 204, 205, 205, 206, 207, 208, 208, 209, 210, 210, 211,
    212, 212, 213, 214, 214, 215, 215, 216, 217, 217, 218, 219, 219,
    220, 220, 221, 221, 222, 223, 223, 224, 224, 225, 225, 226, 226,
    227, 227, 228, 228, 229, 229, 230, 230, 231, 231, 232, 232, 233,
    233, 234, 234, 234, 235, 235, 236, 236, 237, 237, 237, 238, 238,
    238, 239, 239, 240, 240, 240, 241, 241, 241, 241, 242, 242, 242,
    243, 243, 243, 244, 244, 244, 244, 245, 245, 245, 245, 246, 246,
    246, 246, 246, 247, 247, 247, 247, 247, 247, 248, 248, 248, 248,
    248, 248, 248, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249,
    249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249,
    249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249, 249,
    248, 248, 248, 248, 248, 248, 248, 247, 247, 247, 247, 247, 247,
    246, 246, 246, 246, 246, 245, 245, 245, 245, 244, 244, 244, 244,
    243, 243, 243, 242, 242, 242, 241, 241, 241, 241, 240, 240, 240,
    239, 239, 238, 238, 238, 237, 237, 237, 236, 236, 235, 235, 234,
    234, 234, 233, 233, 232, 232, 231, 231, 230, 230, 229, 229, 228,
    228, 227, 227, 226, 226, 225, 225, 224, 224, 223, 223, 222, 221,
    221, 220, 220, 219, 219, 218, 217, 217, 216, 215, 215, 214, 214,
    213, 212, 212, 211, 210, 210, 209, 208, 208, 207, 206, 205, 205,
    204, 203, 203, 202, 201, 200, 200, 199, 198, 197, 197, 196, 195,
    194, 193, 193, 192, 191, 190, 189, 189, 188, 187, 186, 185, 185,
    184, 183, 182, 181, 180, 179, 179, 178, 177, 176, 175, 174, 173,
    172, 171, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161,
    160, 159, 158, 157, 156, 155, 154, 153, 152, 152, 151, 150, 149,
    148, 147, 145, 144, 143, 142, 141, 140, 139, 138, 137, 136, 135,
    134, 133, 132, 131, 130, 129, 128, 127, 126, 125, 123, 122, 121,
    120, 119, 118, 117, 116, 115, 114, 112, 111, 110, 109, 108, 107,
    106, 105, 104, 102, 101, 100, 99, 98, 97, 96, 94, 93, 92, 91, 90,
    89, 87, 86, 85, 84, 83, 82, 80, 79, 78, 77, 76, 74, 73, 72, 71, 70,
    68, 67, 66, 65, 64, 62, 61, 60, 59, 58, 56, 55, 54, 53, 52, 50, 49,
    48, 47, 45, 44, 43, 42, 40, 39, 38, 37, 36, 34, 33, 32, 31, 29, 28,
    27, 26, 24, 23, 22, 21, 19, 18, 17, 16, 14, 13, 12, 11, 9, 8, 7, 6,
    4, 3, 2, 1, 0
};

#define toggle 7

int sw;
int nilaiVB;
int potvolt = A1;                //Pengatur Tegangan
int potfreq = A2;                //Pengatur Frequency

float potvoltval;
float potfreqval;
float DataVolt;
float DataFreq;
float A;
float F;

String inputString = "";         // a String to hold incoming data
boolean stringComplete = false;  // whether the string is complete
String In_1;
String In_2;

int Val1 = 0;
int Val2 = 0;

void setup() {
    Serial.begin(9600);
    inputString.reserve(200);

    pinMode(4, OUTPUT);
    pinMode(13, OUTPUT);
    pinMode(9, OUTPUT);
    pinMode(10, OUTPUT);
    pinMode(2, OUTPUT);
    pinMode(5, OUTPUT);

    cli();                            // stop interrupts
    TCCR0A = 0;                       //reset nilai
    TCCR0B = 0;                       //reset nilai
    TCNT0 = 0;                        //reset nilai
    //0b : menulis bits dalam binary
    TCCR0A = 0b10100001;              //phase correct pwm mode
    TCCR0B = 0b00000001;              //tidak ada prescaler

    TCCR2A = 0;                       //reset nilai
    TCCR2B = 0;                       //reset nilai
    TCNT2 = 0;                        //reset nilai
    //0b : menulis bits dalam binary
    TCCR2A = 0b10100001;              //phase correct pwm mode
    TCCR2B = 0b00000001;              //tidak ada prescaler

    TCCR3A = 0;                       //reset nilai
    TCCR3B = 0;                       //reset nilai
    TCNT3 = 0;                        //reset nilai
    //0b  : menulis bits dalam binary
    TCCR3A = 0b10100001;              //phase correct pwm mode
    TCCR3B = 0b00000001;              //tidak ada prescaler

    TCCR1A = 0;                       //reset nilai
    TCCR1B = 0;                       //reset nilai
    TCNT1 = 0;                        //reset nilai
    OCR1A = 509;                      // compare match value
    TCCR1B = 0b00001001;  //WGM12 bit is 1 for CTC mode and no prescaler

    TIMSK1 |= (1 << OCIE1A);          // memulai interrupts

    sei();                            // enable interrupts
}

// interrupt mulai ketika timer 1 cocok dengan OCR1A
ISR(TIMER1_COMPA_vect) {

    //=========================Phase A================================//

    if (i > 629 && OK == 0) {   // nilai akhir dari sample untuk pin 13
        i = 0;                  // mulai dari nilai awal sample
        OK = 1;                 // mengaktifkan pin 4
    }

    if (i > 629 && OK == 1) {   // nilai akhir dari sample untuk pin 4
        i = 0;                  // mulai dari nilai awal sample
        OK = 0;                 // mengaktifkan pin 13
    }

    x = round(A*sinPWM[i]); // nilai x berasal dari sample dan i berindex 0
    i = i+F;                    // ke posisi selanjutnya dari sample
    if (OK == 0) {
        OCR0B = 0;                      //pin 4 0
        OCR0A = x; //pin 13 memulai pembacaan sample
    }

    if (OK == 1) {
        OCR0A = 0;                      //pin 13 0
        OCR0B = x; //pin 4 memulai pembacaan sample
    }

    // jika nilai i mencapai 209, maka phase kedua akan dimulai
    if ((i >= 418) || OK1 == 1) {
        OK1 = 1;                  //mempertahankan if function

        //=========================Phase B============================//

        if (j > 629 && OK2 == 0) {  // nilai akhir dari sample untuk pin 10
            j = 0;                  // mulai dari nilai awal sample
            OK2 = 1;                // mengaktifkan pin 9
        }

        if (j > 629 && OK2 == 1) {  // nilai akhir dari sample untuk pin 9
            j = 0;                  //mulai dari nilai awal sample
            OK2 = 0;                // mengaktifkan pin 10
        }

        y = round(A*sinPWM[j]); // nilai y berasal dari sample dan i berindex 0
        j = j+F;                    // ke posisi selanjutnya dari sample
        if (OK2 == 0) {
            OCR2B = 0;              // pin 9 0
            OCR2A = y;              // pin 10 memulai pembacaan sample
        }

        if (OK2 == 1) {
            OCR2A = 0;              // pin 10 0
            OCR2B = y;              // pin 9 memulai pembacaan sample
        }
    }

    // jika nilai j mencapai 209, maka phase ketiga akan dimulai
    if ((j>= 418) || OK3 == 1) {
        OK3 = 1;                    // mempertahankan if function

        //=========================Phase C============================//

        if (k > 629 && OK4 == 0) {  // nilai akhir dari sample untuk pin 5
            k = 0;                  // mulai dari nilai awal sample
            OK4 = 1;                // mengaktifkan pin 2
        }

        if (k > 629 && OK4 == 1) {  // nilai akhir dari sample untuk pin 2
            k = 0;                  // mulai dari nilai awal sample
            OK4 = 0;                // mengaktifkan pin 5
        }

        z = round(A*sinPWM[k]); // nilai z berasal dari sample dan i berindex 0
        k = k+F;                    // ke posisi selanjutnya dari sample
        if (OK4 == 0) {
            OCR3B = 0;              // pin 2 0
            OCR3A = z;              // pin 5 memulai pembacaan sample
        }

        if (OK4 == 1) {
            OCR3A = 0;              // pin 5 0
            OCR3B = z;              // pin 2 memulai pembacaan sample
        }
    }
}

void loop() {
    sw = digitalRead(toggle);

    if (sw == 0) { //    VB
        if (stringComplete) {
            if (inputString.substring(0, 4) == "VOLT") {
                In_1 = inputString.substring(4);
                Val1 = In_1.toInt();
                A = Val1/1023; // Formula Pengontrolan Tegangan
                Serial.println(Val1);
            }
            if (inputString.substring(0, 4) == "FREQ") {
                In_2 = inputString.substring(4);
                Val2 = In_2.toInt();
                F = map(Val2, 1023, 0, 0, 50);// Formula Pengontrolan Frequensi
            }

            inputString = "";
            stringComplete = false;
        }
    }
    else if (sw == 1) { // Potensiometer
        potvoltval = analogRead(potvolt);
        A = potvoltval/1023; // Formula Pengontrolan Tegangan

        potfreqval = analogRead(potfreq);
        F = map(potfreqval, 1023, 0, 0, 50);// Formula Pengontrolan Frequensi
    }
}

void serialEvent() {
    while (Serial.available()) {
        // get the new byte:
        char inChar = (char) Serial.read();
        // add it to the inputString:
        inputString += inChar;
        // if the incoming character is a newline, set a flag so the
        // main loop can do something about it:
        if (inChar == '\n') {
            stringComplete = true;
        }
    }
}
```

And here are the interrupts position:
[![Interrupts][1]][1]

And i got the code from this [site][2]

And Here is my VB code

    Public Class Form1

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Try
            Me.CenterToParent()
            SerialPort1.PortName = "COM4"
            SerialPort1.BaudRate = 9600
            SerialPort1.Open()
            Timer1.Start()
            SerialPort1.Write("VOLT" & TrackBar1.Value & Chr(10))
            SerialPort1.Write("FREQ" & TrackBar2.Value & Chr(10))
        Catch ex As Exception
            MsgBox(ex.Message, MessageBoxIcon.Error, "Error Message")
            Me.Close()
        End Try
    End Sub

    Private Sub Form1_Closed(sender As Object, e As EventArgs) Handles Me.Closed
        SerialPort1.Close()
    End Sub

    Private Sub TrackBar1_Scroll(sender As Object, e As EventArgs) Handles TrackBar1.Scroll
        Try
            SerialPort1.Write("VOLT" & TrackBar1.Value & Chr(10))
        Catch ex As Exception
            MsgBox(ex.Message, MessageBoxIcon.Error, "Error Message")
        End Try
    End Sub

    Private Sub TrackBar2_Scroll(sender As Object, e As EventArgs) Handles TrackBar2.Scroll
        Try
            SerialPort1.Write("FREQ" & TrackBar2.Value & Chr(10))
        Catch ex As Exception
            MsgBox(ex.Message, MessageBoxIcon.Error, "Error Message")
        End Try
    End Sub
    End Class
And the design as well[![Design][3]][3]

  [1]: https://i.stack.imgur.com/QBKY4.png
  [2]: http://www.eprojectszone.com/how-to-generate-a-sine-wave-from-arduino-or-atmega-328/
  [3]: https://i.stack.imgur.com/9qkuz.png

sender: assistant

body:
Since the ISR being too long seems to be your main problem, I will address the possibility to set a flag in the ISR. See this code example (which is not a complete compilable example, only code to show the principle):

    volatile byte flag = 0;

    ISR(TIMER1_COMPA_vect) {
        flag = 1;
    }

    void loop(){
        if(flag){
            flag = 0; // resetting the flag for the next execution
            //execute the code here, that was previously in the ISR
        }
    }

First a flag variable is declared as volatile. This tells the compiler, that the value of this variable can change at any time and that the compiler cannot optimize it by using a cached value or other optimizations. This is always required, when you access a variable both in ISR's and the normal code.

In the actual ISR this flag is simply set to `1`. This takes very short time, so that no other interrupt (for example for Serial) will be blocked by it.

Then in our `void loop()` we are checking if the flag has a value, that isn't zero (every value other than zero will evaluate as `true`, so we don't need a comparison operator here). If yes, we first reset the flag to zero, so that another interrupt can set it again to 1. Then we are executing the other code, that was previously in your ISR. Since it now runs in normal code, it will not block Serial interrupts from happening.

---

"The ISR is too long" can also mean, that it is happening too often. Juraj already stated in his comment, that the interrupt happens "every 509 clock ticks". That is not very much. You can increase the time between 2 consecutive timer interrupts by using a prescaler. As doing just this would reduce the frequency of your output sinus wave, you would need to do some calculations, maybe only using every forth or so array element of the sinus wave. With this you are loosing precision in time, but you gain more computation time to do other things.

---

In general you always have to do a trade-of. The longer the code runs, that should be executed on a timer interrupt, the less precision will be possible with it. The code should always run considerable shorter, that the time between two consecutive interrupts.

Your code is not really understandable, since you didn't use speaking variable names and your comments are not written in english. From the structure I would guess, that it can be strongly optimized by you to execute shorter, but without understanding what the code really should do, that is only wild guessing.


message:
Possible to have different torque levels on MG966R servo with Rotary Potentiometer?

I want to apologise first and foremost, and say that I am very new to Arduinos!

I wanted to control the torque on a MG966R servo so that I can separate it into 4 different torque levels. I read that by adjusting the input voltage, you can run the servo at different speed, hence, i was thinking if I could incorporate a rotary potentiometer to adjust the speed of the servo.

Also wondering if changing angle stepsize of MG966R servo will affect torque in anyway?

Thanks all!

body:
Generally it is not easy to control the torque of a standard servo, since mostly they aren't meant for that. A servo has an internal controller, which will read the input PWM signal and control the geared motor, so that the desired position will be reached. And to get there, the most servos will use the maximum torque. Also the torque of a servo motor depends on more variables, for example speed and type of load ([See here for more information about this][1].

> I read that by adjusting the input voltage, you can run the servo at different speed

That's not really true. Most servos only support a rather small voltage range, where they will work. You can get more torque, if you use a higher voltage, but it is not a simple linear relationship, since the torque depends on way more variables. One way may be to always drive the servo to it's current maximum torque and change this maximum torque by changing the input voltage inside the working range. Though this might not get you 4 torque levels, that are different enough for you.

> Also wondering if changing angle stepsize of MG966R servo will affect torque in anyway?

It is unclear, what exactly you mean by "stepsize" here. If you mean to control the speed of the servo: Yes, it will affect the torque, but not in a linear way. And this greatly depends on the load, that you apply.

In the answer to [this question][2], sensing the current of the servo is suggested as a measurement of (applied) torque. If you use a feedback loop with this, you might be able to control the (applied) torque. I haven't done this kind of thing, so I'm not sure, if this can really work.

---

That said, you should again think about wether a normal servo is really the best way to go here, since it controls electronics, that you don't control yourself. For example you may use a geared DC motor, which you can directly control without any other electronics getting in your way.

  [1]: https://www.motioncontroltips.com/servo-motor-torque-curve/
  [2]: https://electronics.stackexchange.com/questions/170305/controlling-servo-torque


message:
Is it safe to power Arduino project using a power bank and wall charger?

I got an Arduino project that need a constant source of power. Rather than dealing with batteries, I want to use a power bank like this:

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

Better yet, I want to keep the power bank plugged in to the wall outlet using a wall charger like this:

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

The USB wire coming out of the power bank, I can modify it and connect it to the 5V on the Arduino (Pro Mini 5V version). Is it safe to do so? The application uses a stepper motor that draws around 200mA and only runs intermittently.

Thanks

  [1]: https://i.stack.imgur.com/cVfbv.jpg
  [2]: https://i.stack.imgur.com/eFJYV.jpg

body:
Yes you can.  A promini will run very well on 5V from a wallwart.  Connect 5V to VCC (not RAW or VIN).  You can also find wallwarts with 2.1mm/5.5mm plugs, and a mating barrel jack adapter that ends in screw terminals so you don't have to try hacking up a USB cable.

Power bank, you will have to play games to convince it that something is connected and drawing sufficient current to keep it turned on.

Wallwart example  https://www.mpja.com/5-Volt-DC-Plug-Power-Supply-4A-Regulated/productinfo/18520+PS/

Barrel jack to screw terminal adapter example  https://www.mpja.com/55_21mm-Power-Jack-Screw-Terminals/productinfo/19454+PL/


body: Yes, that is my standard setup for Arduino and Raspberry Pi.


message:
Arduino Nano LED not working

I am just starting with Arduino and was trying to make the LED example work. I changed the script as follows to keep the LED on:
<!-- language-all: lang-cpp -->

    #define LED_PIN 12
    #define LED_RX_SIG LED_BUILTIN

    void setup() {
      // initialize digital pin LED_BUILTIN as an output.
      pinMode(LED_PIN, OUTPUT);
      pinMode(LED_RX_SIG, OUTPUT);
    }

    // the loop function runs over and over again forever
    void loop() {
      digitalWrite(LED_PIN, HIGH);   // turn the LED on (HIGH is the voltage level)
      //delay(1500);                       // wait for a second
      //digitalWrite(LED_PIN, LOW);    // turn the LED off by making the voltage LOW
      //delay(1500);                       // wait for a second
      //digitalWrite(LED_RX_SIG, HIGH);
      //delay(1000);
      //digitalWrite(LED_RX_SIG, LOW);
      //delay(1000);
    }

I setup the Nano board, LED and a 220ohm resistor on a breadboard. The D12 port on Nano is connected to one end of the 220ohm resistor using a jumper cable. The other end of the resistor is connected to the positive (longer end) of the LED. The negative end of the LED is connected to the GND pin on Nano. The setup is shown in the image below:

[![Nano Board Setup Top View][1]][1]

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

What's wrong with the setup and why the LED is not lit?
Sorry in advance for such novice question and any help will be greatly appreciated. Thanks

  [1]: https://i.stack.imgur.com/Tqa5F.jpg
  [2]: https://i.stack.imgur.com/3xywB.jpg

body:
As your program is currently written, you should see your LED light. I see nothing wrong with your program or your wiring. I am also assuming that you had no errors while compiling and downloading the program.

With the rest of the lines uncommented, what you should see is your LED light up for 1.5 seconds and then off. Then after another 1.5 seconds, the on-board LED should turn on and then off (both 1 second).

If you have wired up the LED wrong (or a bad connection), you should at least still see the on-board LED flash about once every 5 seconds. If you don't see this then something else is wrong.

One thing I notice from the photos is that you have no way of powering your circuit. (I realise this may just be while you took the photo). Plug a USB cable into the Arduino and the other end into the computer. You should see the LED called "POW" light up.

To verify your LED circuit, try disconnecting the jumper at D12 and connecting it to 5V and you should see the LED light. If this works then your circuit is OK so replace the jumper back at D12.

If the LED still does not light up when the jumper is connected to 5V then we need to dive into that circuit. Possible reasons include:

- The LED is dead -> replace the LED
- The breadboard is not making good connection -> wiggle the leads (to scratch away any corrosion) or twist together the wires where possible or even solder them together.
- The jumper wires are manufactured poorly (eg. the plastic wasn't stripped before crimping) -> check the jumper crimps.
- The LED has been manufactured wrong and what should be the anode is actually the cathode (I have seen this) -> reverse the polarity of the LED.
- The resistor is burnt out -> replace the resistor.


body: If your led does not turn on after you directly connect it to the VCC and the GND (as you mentioned in a comment) , it means that your led is most likely broken. Simply try using another Led as your circuit and code look fine.


message:
How to utilize SPI Serial bus on a ATSAMD21G18?

Like the title suggests, I have a [ATSAMD21G18][1] microcontroller that I want to interface with a [LTC6803-4][2] chip, but I'm not sure how to set up the SPI bus on the microcontroller, and the datasheet proved too confusing for me to understand.

  [1]: https://www.microchip.com/wwwproducts/en/ATsamd21g18
  [2]: https://www.analog.com/en/products/ltc6803-4.html

body:
Use the SPI API provided by Arduino (https://www.arduino.cc/en/Tutorial/SPITransaction) and the command format that the chip wants you to use based on the datasheet. Here's a bit of example code for SPI transaction. Though untested, it's what I understood from reading the datasheet. Written for an Adafruit Feather M0 express (uses SAMD21G18 MCU). For pinout see https://learn.adafruit.com/adafruit-feather-m0-express-designed-for-circuit-python-circuitpython/adafruit2-pinouts#logic-pins-2-8.

Also note that Analog Devices does provide Arduino-Code for *similiar* devices like LTC6803-2 but not for the -4. Still, you can look how they implemented a driver. See [here](https://www.analog.com/en/products/ltc6803-2.html#product-documentation)

<!-- language: cpp-->

    #include <Arduino.h>
    #include <SPI.h>

    /* pin setup */
    int chip_select_pin = PIN_A2;
    /* SPI pins labeled "SCK" "MO" "MI" on the Adafruit Feather M0 express board
     * are used implicitly.
     * PIN_SPI_MISO (22),  PIN_SPI_MOSI(23), PIN_SPI_SCK(24),
     * */

    #define LTC6803_4_MAX_SCLK_FREQ 1000000
    #define LTC6803_4_USED_SCLK_FREQ (LTC6803_4_MAX_SCLK_FREQ/2)

    SPISettings settings(LTC6803_4_USED_SCLK_FREQ, BitOrder::MSBFIRST, SPI_MODE3);

    void start_voltage_adc_conversion(){
     SPI.beginTransaction(settings);
     digitalWrite(chip_select_pin, LOW);
     //STCVAD
     //Start Cell Voltage ADC Conversions and Poll Status, with Discharge Permitted
     uint8_t tranfer_buf[2] = {
       0x10, //CODE
       0xB0 //PEC
     };
     SPI.transfer(tranfer_buf, 2);
     //wait for conversion, just a static time. at least 12 milliseconds.
     delay(20);
     digitalWrite(chip_select_pin, HIGH);
     SPI.endTransaction();
    }

    void read_voltages_1_to_4(){
     //trigger voltage conversion
     start_voltage_adc_conversion();

     SPI.beginTransaction(settings);
     digitalWrite(chip_select_pin, LOW);
     //transfer buffer must have 2 bytes for command
     //and 6 bytes for response (four 12-bit ADC values encoded in 6 registers CVR00..CVR05)
        //plus 1 byte for PEC from chip
     //Read Cell Voltages 1-4, "RDCVA", page 22
     uint8_t tranfer_buf[2 + 6 + 1] = {
       0x06, //CODE
       0xD2 //PEC
     };
     SPI.transfer(tranfer_buf, 9);
     digitalWrite(chip_select_pin, HIGH);
     SPI.endTransaction();

     //recover 12-bit ADC value from C1V[0]..C1V[11] from register values CVR00 and CVR01
     //see datasheet page 24
     uint16_t adc_cell_1 = tranfer_buf[2] | ((tranfer_buf[3] & 0B1111) << 8);
     //adc value to voltage conversion according to page 15
     float voltage_cell_1_millivolt = ((int)adc_cell_1 - 512) * 1.5f ;
     Serial.print("Cell voltage 1: ");
     //print with 5 digits accuracy
     Serial.print(voltage_cell_1_millivolt, 5);
     Serial.println(" mV");
    }

    void setup() {
        Serial.begin(115200);
     pinMode(chip_select_pin, OUTPUT);
     SPI.begin();
    }

    void loop() {
     read_voltages_1_to_4();
     delay(2000);
    }


message:
Can you put Ardupilot on any flight controller?

Some FC's say that they support cleanflight and have no mention of Ardupilot. Is this just because its what's recommended or because it's all that works?

body:
There are pre-built binaries for many flight controllers.

[http://firmware.ardupilot.org/][1] lists out the different ardupilot builds (arducopter, arduplane, etc.) and by clicking on them , you can see the different versions, then the different builds per version.

[This document][2] goes into more detail on the file structure they use for pre-built binaries.

  [1]: http://firmware.ardupilot.org/
  [2]: http://ardupilot.org/dev/docs/pre-built-binaries.html


message:
analogRead() output oscillates even though the pin is grounded

I'm using Arduino Micro to read from 5 flex sensors and display the corresponding angles to the Serial monitor. I am currently having quite some problems with the oscillating values I am getting from the analogRead(). It doesn't seem to matter whether the pin is connected to a flex sensor or just grounded - the output is oscillating a lot.

Originally everything was being read and outputted just fine but I wanted to have an exact 100Hz sampling frequency and tried to play a bit with Timer Interrupts. And that's when this oscillating behaviour started. I reversed to my original code, which just uses some delay(), and simplified to only read from two pins, but cannot seem to shake off the oscillations.

I think I may have messed up something about ADC when trying to implement Interrupts, but I don't know how to check it or fix it. Please, help me figure out how to fix this!

This is the raw output of analogRead. The drop in values occurs when I bend the flex sensor:

[![This is the raw output of analogRead. The drop in values occurs when I bend the flex sensor][1]][1]

And this is the resulting calculated angle. Also oscillating:

[![And this is the resulting calculated angle. Also oscillating.][2]][2]

This is the code I've been using to read the pins:

    int fin;
    const int input[5] = {A0,A1,A2,A3,A4}; // the analog pins

    int flex[5]; // analog signal read
    float flexV;
    float flexR[5]; // resistance on the 47k resistor
    int angle[5]; // joint angles

    const float VCC = 4.98; // Measured voltage of Arduino 5V line
    // Measured resistance of the 47k resistors R1-R5
    const float R[5] = {45900.0,45900.0,45900.0,45900.0,45900.0};

    // Calibration values of resistance measured during straight phase and 90 deg bend phase
    const float R_STRAIGHT[5] = {37651.0,37651.0,37651.0,37651.0,37651.0};
    const float R_BEND[5] = {71783.0,71783.0,71783.0,71783.0,71783.0};

    void setup() {

    }

    void loop() {

      for(fin = 0; fin <= 4; fin++) {
       flex[fin] = analogRead(input[fin]);
       flexV = flex[fin]*VCC/1023.0;
       flexR[fin] = R[fin] * (VCC/flexV - 1.0);
       angle[fin] = map(flexR[fin],R_STRAIGHT[fin],R_BEND[fin],0,90.0);
       delay(1);
        }
        Serial.print(angle[0]);
        Serial.print(" ");
        Serial.print(angle[1]);
        Serial.print(" ");
        Serial.print(angle[2]);
        Serial.print(" ");
        Serial.print(angle[3]);
        Serial.print(" ");
        Serial.print(angle[4]);
        Serial.print(" ");
        Serial.println(millis());
        delay(6);
    }

  [1]: https://i.stack.imgur.com/eVNVf.png
  [2]: https://i.stack.imgur.com/Up2fp.png

body:
You have nothing in your setup loop. You need to set up all the inputs as inputs.

You setup() should look like this:

    void setup()
     {
       Serial.begin(9600);
       for (int i = 0; i < 5; i++);
        {
          pinMode(input[i], INPUT);
        }
     }

The code cycles through your array "input", setting all the pins as inputs. Try that.


message:
Velleman KA02 not working on Mega 2560 r3

I have a [Velleman KA02][1] audio shield. When I use this shield on an [Arduino UNO R3][2] with this [sample code][3], it works. And by "work" I mean when I interact with the `Serial Monitor` (by pressing `Y`, for example), I hear the playback.

However, if I place this audio shield on a [Mega 2560 R3][4], the shield no longer works (pressing `Y` does nothing). I read about the [SPI library][5], and the document seems to suggest that `MISO`, `MOSI`, `SCK` and `SS` are different for the Uno vs the Mega. For the Uno,

* MOSI: 11
* MISO: 12
* SCK: 13
* SS: 10

and the article is consistent with the constants defined in the [ISD1700.h file][6]. For the Mega,

* MOSI: 51
* MISO: 50
* SCK: 52
* SS: 53

I can modify `ISD1700.h` for use with the Mega easy enough. However, I do not think I can just sit the audio shield right on top of the Mega with the modified code and have it work. I used some (male to female) jumper wires to connect from the Mega pins 50, 51, 52, 53 to the audio shield pins 12, 11, 13, 53 (correspondingly). Additionally, I have jumper wires connecting the power and ground from the Mega to the audio shield. What works is that the audio shield has power and I am able to press the physical buttons on the audio shield to record and playback. What does not work is that when I enter `Y` in the serial monitor to force a playback, although the character is read and the `switch` case is reached, the playback never happens.

Any ideas on what I am doing wrong? On the Velleman site, they seem to suggest that this audio shield only works with the Uno, but the [Illustrated Assembly Manual][7] says that the audio shield should work with the Mega.

  [1]: https://www.velleman.eu/products/view/?id=412160
  [2]: https://www.microcenter.com/product/486544/inland-uno-r3-mainboard
  [3]: https://github.com/Velleman/KA02/blob/master/ka02_sample_code/ka02_sample_code.ino
  [4]: https://www.microcenter.com/product/486545/inland-arduino-mega-2560
  [5]: https://www.arduino.cc/en/Reference/SPI
  [6]: https://github.com/Velleman/KA02/blob/master/ISD1700/ISD1700.h#L25
  [7]: https://www.velleman.eu/downloads/0/illustrated/illustrated_assembly_manual_ka02.pdf

body: Nevermind, I solved it. There's 6 pins located on the Uno and Mega labelled ICSP, and those were the key. I simply connected the MOSI, MISO and SCK pins on the Mega to the audio shield (along with GND and 5V) and also the 10 pin (audio shield) to the 53 pin (Mega) via a male to male jumper. The header code was modified to work with the new values, and now I am able to send character signals via the serial monitor.


message:
How to prevent modify library of arduino?

For some reasons of security, I created library for everybody to use, but I don't want people change my library, cause it make device not work. I search around but still not working. Do I need to set password for library or make it unreadable or make it can not modify or another way that you can give the direction ?

P/s: Think like a hacker, I can change library and make an attack to the server from library.

body:
No, you can't do that. How could a library work if it is unreadable?

If you don't want people changing it, don't publish it.

If you publish it you could put a disclaimer on it:

> If you change my library, it may stop working.

---

**(Added to question two days later)**

> P/s: Think like a hacker, I can change library and make an attack to the server from library.

Yes, but, if you distribute the original library, then someone would have to download it, change it, and then attack themselves with it!

And if your library does something to do with servers (you haven't said *what* your library does) then someone could make a similar library, and build the attack code into that. Hacking your particular one wouldn't be required.

My other issue is: If your library is a secret, that is, I can't read its source code, then I might presume that *your* library is where the hack is. At least if people get the source code they can read it and check it.


body:
Later versions of the IDE have the ability to use pre-compiled libraries.  This means that the end user only gets the compiled version of your library (a `.a` file) rather than the source code.

Modify your `library.properties` file to include `dot_a_linkage=true`. If you don't have a `library.properties` file you need to make sure you create your library in 1.5.x format.

Then compile your library in the normal way. This will result in a `.a` file somewhere in the build  tree which gets linked with your sketch.  You need to grab that `.a` file.

Next make a new copy of your library that has just the header file (needed for compilation) and the `.a` file (needed for linking). No `.cpp` files.

Now you in the new `library.properties` file you add `precompiled=true`.

As long as you lay out the files right it should now compile using the precompiled `.a` file.

You can read more about the `library.properties` contents [here](https://github.com/arduino/Arduino/wiki/Arduino-IDE-1.5:-Library-specification).


message:
Memory usage in AnalogBinLogger of SdFat library

The AnalogBinLogger.ino file of SdFat library says the following:

>  Each 512 byte data block in the file has a four byte header followed by up to 508 bytes of data. (508 values in 8-bit mode or 254 values in 10-bit mode).
 Each block contains an integral number of samples with unused space at the end of the block.

I was wondering why only 254 values can be stored in 10-bit mode instead of (508*8 bits/ 10 bits ~ 406 values ).

 1. Is this because of the memory being byte-addressable and hence does a 10-bit value take up 2 bytes?
 2. If so, how will a file-reader differentiate between a 10-bit value taking 2 bytes and two 8-bit values?
 3. The AnalogBinLogger.ino says:

> The logger will use SdFat's buffer plus BUFFER_BLOCK_COUNT additional buffers.

  `BUFFER_BLOCK_COUNT` is 1 for the Arduino Uno since it has 2KB of SRAM. Each buffer is 512-byte long. Is **SdFat's internal buffer** also in SRAM? If I am not wrong, the libraries the program uses and the program code reside in the Flash memory, can SdFat write into a buffer in Flash memory?

body:
> how will a file-reader differentiate between a 10-bit value taking 2
> bytes and two 8-bit values?

The file [AnalogBinLogger.h][], which comes with the example sketch you
mentioned, contains the following:

```c++
// First block of file.
struct metadata_t {
  unsigned long  adcFrequency;     // ADC clock frequency
  unsigned long  cpuFrequency;     // CPU clock frequency
  unsigned long  sampleInterval;   // Sample interval in CPU cycles.
  unsigned long  recordEightBits;  // Size of ADC values, nonzero for 8-bits.
  unsigned long  pinCount;         // Number of analog pins in a sample.
  unsigned long  pinNumber[123];   // List of pin numbers in a sample.
};
```

Thus, the file reader just needs to be aware of the format of this first
block, and read the `recordEightBits` field in order to know whether
this is 8-bit data or not.

> Is SdFat's buffer also in SRAM?

Yes, that's the only sensible place you could have a data buffer. [It's
allocated on the stack][stack], only during the execution of the
`logData()` function.

[AnalogBinLogger.h]: https://github.com/greiman/SdFat/blob/master/examples/AnalogBinLogger/AnalogBinLogger.h
[stack]: https://github.com/greiman/SdFat/blob/master/examples/AnalogBinLogger/AnalogBinLogger.ino#L591


message:
Problem with passing string pointer from child to parent

I am trying to pass a pointer to a const char * from a child to its parent, but I am clearly not understanding how to do this correctly. Here is the code which contains three classes:
1) parent
2) Alpha (child)
3_ Beta (child)

    #pragma once
    class Parent {
    protected:
     char *childName;

    public:
     Parent ( char* _childName ) {
      childName = _childName;
     }

     char *getChildName () {
      return childName;
     }
    };

    class Alpha: public Parent {
    protected:
     const char* alphaName = "ALPHA";

    public:
     Alpha (): Parent ( alphaName ) {
      Serial.print ( F ( "My name is " ) );
      Serial.println ( getChildName () );
     }
    };

    class Beta: public Parent {
    protected:
     const char* betaName = "BETA";

    public:
     Beta (): Parent ( betaName ) {
      Serial.print ( F ( "My name is " ) );
      Serial.println ( getChildName () );
     }
    };

    Alpha *alpha;
    Beta *beta;
    void setup () {
     Serial.begin ( 115200 );
     while (!Serial.availableForWrite ()) {}

     alpha = new Alpha ();
     beta = new Beta ();
    }

    void loop() {}

And here is the output I get:
My name is �

My name is �˵

body:
The problem here is that `alphaName` and `betaName` are member variables. That means they are initialized during the `Alpha` and `Beta` constructors. However, the superclass constructor of `Parent` is always called first, before calling the child class constructors. Result: `Parent::Parent(char *)` is called with an uninitialized pointer.

Here is your code on the Compiler Explorer: <https://godbolt.org/z/otAuQU>
As you can see, `Alpha::Alpha()` compiles to the following:

    call Parent::Parent(char*)
    ldd r24,Y+1
    ldd r25,Y+2
    ldi r18,lo8(.LC0)
    ldi r19,hi8(.LC0)

`.LC0` is the string "ALPHA".

The solution here is to make the names static. That way, they are initialized before the parent constructor is called.

    class Parent {
      protected:
        const char *const childName;

      public:
        Parent(const char* childName) : childName(childName) {}

        const char *getChildName () const {
            return childName;
        }
    };

    class Alpha : public Parent {
      protected:
        constexpr static const char *alphaName = "ALPHA";

      public:
        Alpha() : Parent(alphaName) {
            Serial.print(F("My name is "));
            Serial.println(getChildName());
        }
    };

This compiles to:

    ldi r22,lo8(.LC0)
    ldi r23,hi8(.LC0)
    call Parent::Parent(char const*)

As others have mentioned, pointers to string literals should always be const. The only reason this doesn't give an error is because the Arduino folks decided that it was a good idea to compile everything with `-fpermissive` ...
Mutating a string literal is undefined behavior, so an error.


message:
Libraries not included correctly

I stumbled upon the following unexpected behaviour and am curious about its cause.

header.h:

    #include <Time.h>
    [...]

main.ino:

    #include "header.h"
    #include <Time.h>
    [...]

My code is working correctly with this setup. However, if I comment out the Time.h library in my main.ino, my code is working not correctly anymore:

    #include "header.h"
    //#include <Time.h>
    [...]

I can still access the functions of Time.h, but they are returning garbage time.

Why do I have to include the library in my *.ino, although I am already including it in my header file?
Is there a best practice, on where to include libraries? Shall I simply always include all libraries in my *.h and *.ino file?

body:
Firstly you should be including `TimeLib.h` not `Time.h` - the library header name has been changed to avoid conflicts on case-insensitive systems (Windows) and the internal `time.h` header in many compilers.

Secondly you should always include all your libraries in your INO file directly.  This is because the IDE parses the INO file before compiling looking for any included libraries. It then adds these found libraries to the list of libraries that need to be compiled. Without this you won't get the source code for your libraries compiled properly.


message:
Rounding float number

I want to enable user to change the duration of PWM from 0 to 255, the number should be in minute and increase/decrease with two push buttons.

    (X) x 255 / 60000 = minute

In above example each time plus button pressed value (X) will multiple by the numbers of button pressed.

    if (plusButton == HIGH) {
        PWMduration += (X);
    }

The nearest number i found is 235.29 which equals to almost 1 minute:

    235.29 x 255 / 60000 = 0.9999

How can i round that number to 1? or is there any other alternative solution to calculate this?

body:
You can cast it to an integer after adding an offset.

Casting to an int will lower the value to the lowest integer value (e.g. 0.9975 will become 0). However, if you want an accuracy of 0.5 (e.g. all values from 0.5 <= x < 1.5 should be 1.0), than add 0.5, thus:

    int roundedValue = (int)(0.9975 + 0.5);

If you use constants and want to calculate with it, either add .0 to it, or use a f(loat) or d(ouble) postfix, e.g.:

    float f = 12.0 / 3.0;

or

    float f = 12f / 3f;

Than calculate the rounded value:

    int roundedValue = (int)(f + 0.5);


message:
how does c++ understand which function must to use?

in this code:

        void AdptSendReply(const char* str)
    {
        string s(strlen(str) + 2);
        s = str;
        AdptSendReply(s);
    }

    void AdptSendReply(const string& str)
    {
        string s(str.length() + 2);
        AdptSendReply(s); // use the next one
    }

    void AdptSendReply(string& str)
    {
        if (AdapterConfig::instance()->getBoolProperty(PAR_LINEFEED)) {
            str += "\r\n";
            AdptSendString(str);
        }
        else {
            str += "\r";
            AdptSendString(str);
        }
    }

 i think c++ use of overloading ability.but how it can recognize which of the two functions "void AdptSendReply(string& str)" or "void AdptSendReply(const string& str)" must use?!

body:
The compiler decides which function to use based on the variable type information. Imagine you write

    str += "test";

If you declare `str` as a constant, the above line will throw an error. So if you write `AdptSendReply(str)` instead, the compiler will call the const function. Likewise, if you declare `str` as a mutable variable, the above line will compile fine, and, should you call `AdptSendReply(str)`, the compiler will use the non-const function.


body:
Calling overloading function triggers a process called *overload resolution*, which uses argument types to select the proper function to call

* If you supply an lvalue argument of type `string`, the compiler will call `void AdptSendReply(string& str)` version.

        string s = "hello";
        AdptSendReply(s); // calls 'string& str' version

* If you supply an lvalue argument of type `const string`, the compiler will call `void AdptSendReply(const string& str)` version.

        const string s = "hello";
        AdptSendReply(s); // calls 'const string& str' version

* If you supply an rvalue argument, the compiler will call `void AdptSendReply(const string& str)` version.

        AdptSendReply(string("hello")); // calls 'const string& str' version

And so on. The full set of rules that govern overload resolution is quite extensive, especially when the context involves implicit conversions.

---

It is not clear what you mean by "must use". Normally, overloaded functions will do the same thing (functionality-wise), meaning that you are not supposed to worry about which function to use. Just call it with the argument you have available and the compiler will select the proper function to call.

Also, what is `string`? How are we supposed to know that? Without knowing it, your question make little sense.


message:
PIR sensor and hex inverter open collector

[![enter image description here][1]][1]the M7404 Hex inverter is used to send an active low signal from a PIR sensor to a microcntroller pin

However the reset is being constantly sent some signal keeping it set to on. You can tell because the reset light is on in the picture

Thanks to ST2000 I was able to figure out I need a hex inverter open collector to change the high signal from high to low because the reset pin on the microcontroller is active low. However, Whenever I use the active low reset pin (number 3 on the esp32) it goes into a state of holding down the reset button. Or constantly being high. Here is the thread where ST2000 was able to provide me the solution I am working on: https://arduino.stackexchange.com/questions/66529/esp32-cam-and-pir-sensor

![Here is a schematic of my wiring to the esp32 reset pin from a PIR snesor using an inverter in between](https://i.stack.imgur.com/Qk4es.jpg)

**My question is: how do i get the pir sensor to send an active low signal to the microcontroller?**

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

here is a schematic of the esp32 board
https://i.redd.it/yv050peu22p21.png

body:
I wouldn't have chosen a hex inverter for this job. I'd have just used a transistor and a resistor:

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

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

<!-- End schematic -->

When OUT is HIGH, M1 is ON, which connects D3 to GND.  When OUT is LOW, M1 is OFF, which allows R1 to pull D3 up to 3.3V.

----

As to why you have a boot loop, now you have shown a slightly (though still confusing) clearer schematic I can tell you that it is because you are using pin D3.

Don't use pin D3.

D3 is the RX pin and is held HIGH at boot. That means that when the board resets D3 goes HIGH which then pulls reset LOW through your inverter, which then lets D3 float, so RESET goes HIGH, and that makes D3 then go HIGH which means the RESET is pulled LOW... ad infinitum.

You should read [this page](https://randomnerdtutorials.com/esp32-pinout-reference-gpios/) and choose a different GPIO pin that isn't going be doing things at bootup.


message:
Which sources of randomness are available?

I need a souce of randomness to generate a seed to pass to [`randomSeed`][1]. Where can I get this randomness from?

Well, I hear I can read random noise from an unconnected pin.

But I need to connect 9 LEDs and 9 buttons to the board. There seem to be enough pins for this purpose: digital pins 2-13 + analog pins 0-5 makes a total of 18 pins. But does this leave any free pin for a source of randomness?

There are digital pins 0 and 1 left free but [I'm reading these should be left free if the board's USB socket is connected][2] and I'm planning to power the whole device by connecting it to a computer through USB. Does this mean I'm supposed to just left pins 0 and 1 unconnected or is it also forbidden to read noise from them?

Or are there any other available sources of randomness? Can I use any other pins for this purpose?

I remember when I was showing this project to the instructor I specifically asked if I have enough pins, noting that I need a source of randomness in addition to 9 LEDs and 9 buttons. He said there are enough pins. Only sadly I forgot to ask how can I read random noise then...

What are my options to somehow obtain a random seed?

  [1]: https://www.arduino.cc/reference/en/language/functions/random-numbers/randomseed/
  [2]: https://www.arduino.cc/en/reference/board

body:
Whether you need a source of random noise depends on whether your project needs to *not* run repeatably. Most experiments - Monte-Carlo simulations, for example, benefit by being able to be re-run. In those cases, you need to be able to re-use the seed, and having an non-reproducible seed (and thus, experiment) is a disadvantage.

If you really need something that runs differently each time you run it, then a seed derived from user reaction time, or from some kind of electrical noise, even reading analog values from a floating input pin, should give you plenty of non-reproducibility.


message:
why arduino can not write to server?

i write a code for Arduino + SIM800 for connecting to server.
but it don't work!

    SerialGsm.println("AT+CIPSEND=63\r\n");
    delay( 1000 );
    receive_message();
    SerialGsm.print( "GET http://sasasas.ir.ir/hadi/signal.php?value=10" );
    delay( 10000 );
    receive_message();

all thing is true but "GET" can not retrun "OK".
it is arduino response:
****************************************************************
AT

OK

Call Ready

SMS Ready
AT+CSTT="mtnirancell"

OK
AT+CIICR

OK
AT+CIFSR

100.65.157.141
AT+CIPSTART="TCP","sasasas.ir",80

OK

CONNECT OK
AT+CIPSEND=63

> GET http://sasasas.ir/hadi/signal.php?value=10
****************************************************************
"get" dont have response.what is wrong in this code?

body:
Firstly you only have half of the first line of a GET request. Secondly the half you do have is badly formatted.

A GET request does *NOT* look like this:

    GET http://jalambadani.ir/hadi/signal.php?value=10

A GET request *DOES* look like this:

    GET /hadi/signal.php?value=10 HTTP/1.1
    Host: jalambadani.ir
    Connection: close
    [extra blank line]

If you don't send the correct data you can't expect to get any response back.  You should learn the basics of what you are trying to do instead of just throwing random text a a web server.

----

Here is a full transcript of a GET request to your URL:

    $ telnet jalambadani.ir 80
    Trying 185.211.56.148...
    Connected to jalambadani.ir.
    Escape character is '^]'.
    GET /hadi/signal.php?value=10 HTTP/1.1
    Host: jalambadani.ir
    Connection: close

    HTTP/1.1 200 OK
    Date: Tue, 25 Jun 2019 22:47:07 GMT
    Server: Apache/2
    X-Powered-By: PHP/5.6.35
    Upgrade: h2,h2c
    Connection: Upgrade, close
    Vary: User-Agent
    Content-Length: 31
    Content-Type: text/html; charset=UTF-8

    New record created successfullyConnection closed by foreign host.

In code that would be:

    SerialGsm.print("AT+CIPSEND=83\r\n");
    delay(1000); // I hate that. Look for a proper OK instead.
    SerialGsm.print("GET /hadi/signal.php?value=15 HTTP/1.1\r\n");
    SerialGsm.print("Host: jalambadani.ir\r\n");
    SerialGsm.print("Connection: close\r\n");
    SerialGsm.print("\r\n);


message:
AC Voltage Sensing using Arduino Uno

Is it possible to sense AC Voltage using analog input for Arduino Uno or can it only read DC?

I mean I've tried connecting an AC voltage source to analog and I'm reading some numbers. However, I don't know if these numbers are actually AC voltage values or something else.

Ultimately I’m trying to find the avg voltage value for a given time duration. I know that analogRead ( ) gives ADC values. However, in my block of code, I have the conversion ratio of 1023/5 to get a good estimate of the voltage. However, I’m not too sure if Arduino analog sensing is suited for AC voltage? I’m using it to sense voltages generated by piezoelectric PVDF film and the frequency is pretty high. All I want is to use avg. voltage value to calculate electrical energy produced by the PVDF film.

body:
The AC voltage that you are trying to measure is about 50/60Hz depending on where you live. And the maximum effective sampling rate for a regular Arduino ADC is 9615Hz. This means you're not going to experience any aliasing as the sampling rate is well above the `2 * Signal Frequency`.

The values that are coming out of `analogRead()` are raw ADC values which you need to do, further calculation on if you want to have a correct voltage reading.


message:
Update time in RTC over I2c fails

I am communicating two arduinos using the I2C protocol and sending from the slave to the master the integer value of UTC to update the time in the RTC module. When the master receives the UTC value from I2C and tries to set the time by the RTC.set () command the Arduino hangs and needs to be restarted, however, if I use RTC.set () in the loop () method it works perfectly. I do not understand why the system for when it is updated by I2c, is there any conflict?

This is the code with the `loop()` and `Wire.onReceive()`:

```
#include <Thread.h>
#include <ThreadController.h>
#include <SoftwareSerial.h>
#include <LinkedList.h>
#include <SPI.h>
#include <TimeLib.h>
#include <DS3232RTC.h>
#include <Wire.h>

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

  Wire.begin(1);
  Wire.onReceive(receiveEvent);

  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  setSyncProvider(RTC.get);
  if (timeStatus() != timeSet)
     Serial.println("Unable to sync with the RTC");
  else
     Serial.println("RTC has set the system time");

}

void loop() {

  digitalClockDisplay();
  delay(2000);

  // test only
  /*time_t t = processUTCFromI2c("1560810413");

  if (t != 0) {
    RTC.set(t);   // it's works
    setTime(t);
  }*/

}

// ================================ INIT ONRECEIVE ===========================================

void receiveEvent(int howMany) {
  char* vectorAction;
  char c;
  Serial.println(howMany);

  LinkedList<char> myLinkedList = LinkedList<char>();

  //while (1 < Wire.available()) { // loop through all but the last
  for (int i = 0; i < howMany; i++){
    c = Wire.read(); // receive byte as a character
    myLinkedList.add(c);
  }

  vectorAction = new char[myLinkedList.size()+1];

  for(int i=0; i < myLinkedList.size(); i++) {
    vectorAction[i] = myLinkedList.get(i);
  }

  vectorAction[myLinkedList.size()] = '\0';

  getParamsAndValues(vectorAction);

}

void getParamsAndValues(char* i2cValueString) {

  char* getValue;
  char* getParam;
  char* endValue;

  getValue = strchr (i2cValueString, '=');
  getParam = strchr (i2cValueString, '@');
  endValue = strchr (i2cValueString, '#');

  const size_t maxBuffLength = 15;

  char valueBuffer[maxBuffLength+1]; // allocate local buffer with space for trailing null char
  char paramBuffer[maxBuffLength+1];

  valueBuffer[0] = '\0';

  while(getValue && getParam && endValue && (getValue > getParam) && (endValue > getValue)) {
    Serial.println(i2cValueString);

    if (getValue && getParam && (getValue > getParam)) {
      size_t paramLength = getValue-getParam-1;
      valueBuffer[0] = '\0';

      if (paramLength <= maxBuffLength) {
        strncpy(paramBuffer, getParam+1, paramLength);// http://www.cplusplus.com/reference/cstring/strncpy/
        paramBuffer[paramLength] = '\0'; // properly terminate the c-string
      }
    } else {
      // handle Wrong Input
    }

    if (getValue && endValue && (endValue > getValue)) {
      size_t valueLength = endValue-getValue-1;
      valueBuffer[0] = '\0';

      if (valueLength <= maxBuffLength) {
        strncpy(valueBuffer, getValue+1, valueLength);// http://www.cplusplus.com/reference/cstring/strncpy/
        valueBuffer[valueLength] = '\0'; // properly terminate the c-string
      } else {
        // handle buffer too small
      }
    } else {
      // handle Wrong Input
    }

    getValue = strchr (getValue+1, '=');
    getParam = strchr (getParam+1, '@');
    endValue = strchr (endValue+1, '#');

    i2cActionReceived(paramBuffer, valueBuffer);
  }

}

void i2cActionReceived(char* param, char* value) {
  if(strcmp(param, "setTime") == 0) {
    time_t t = processUTCFromI2c(value);

    if (t != 0) {
      RTC.set(t);   // It's not works
      setTime(t);
    }
  }
}

// ================================ END ONRECEIVE ===========================================

// ================================ CONVERT UTC char* TO long ===============================
unsigned long processUTCFromI2c(char* utc) {
  unsigned long auxTime = 0L;

  if (strlen(utc)>0) {
    auxTime = atol(utc);
  }

  return auxTime;
}
```

The slave sends a string through I2C in the format `@setTime=1560810413#`.

In the `loop()` this commented the code that works onorata and on `i2cActionReceived (char* param, char* value)` is where the update fails by onReceive.

body:
The symptom you are describing is: The `RTC.set()` method blocks in the `onReceive` callback of the `Wire` library, but not when used in the `loop()` function.

That sounds like an interrupt issue. The `onReceive` callback function is called from an ISR (Interrupt Service Routine) of the I2C hardware. It is no good to use any code, which utilizes interrupts, inside an ISR, until you know, what you are doing.

In this case the `RTC.set()` function (which you can find [here at line 152][1]) will call the method `RTC.write()`, which will do multiple I2C transactions (both sending and receiving as master). Doing these inside an ISR may already block the code from executing further.

But there is another problem. You have 2 Arduinos connected by I2C. The master Arduino talks only to the slave Arduino, while the slave Arduino is also a master for the RTC (You initialize this Arduino as slave, but it will become a master for the time, when you try to do master transmissions). Your slave code and the RTC library both use the `Wire` library, meaning the hardware I2C port of the Uno. So you have 2 masters on the same I2C port.

While the I2C standard supports multi-master setups via bus arbitration, the `Wire` library does not. In the case, when both masters start to transmit at the same time, it will block the bus (due to some blocking loops inside the `Wire` library, that cannot handle bus arbitration). So the setup, that you use is either not going to work at all or being very risky, depending on the amount of send data (When the bus is filled with more data, it get's more probable, that a collision between the masters happens).

With I2C on Arduino you should stick to single-master setups. For example you can set the first Arduino as slave, keeping the second Arduino as single master on the bus, which handles both getting UTC from the first Arduino and communicating with the RTC. On the first Arduino you would set up an `onRequest` callback, that fills the I2C buffer with the current UTC time, which then get's transmitted to the master Arduino, so that it can update the RTC's time with it.

---

EDIT:

I2C has a fundamental master-slave principle. The master generates the clock signal and initiates/stops any transactions on the bus. A slave cannot send anything over the bus, when the master didn't request data from it, including "calling" the master. Any communication start's with the master.

The `Wire` library gives you the possibility to initialize the Arduino as slave and then do master transactions. For this the I2C hardware is configured as master for the time of the transactions. So you can initialize both Arduinos as slaves with an address and let them change to master mode for any master transaction, that you need. That is the way, that you are talking about in your comment and what you use in the code in your question.

**BUT** you get a big problem, when both Arduinos try to send at the same time. That is called data collision. The I2C specification has the bus arbitration for this (basically the master that first sends a 1 has to back down from the transaction), so that collisions can gracefully be resolved. The `Wire` library doesn't implement this, so it will block in case of a collision. Then you have to reset the Arduino to get it going again.

You should again analyse your requirements and check, if you really need I2C for communication between the Arduinos, or if you really need individual bidirectional communication. That is often also a design choice.

If you really need individual 2 way communication between the Arduinos, I see 2 possibilities:

1. You can do it the hacky way and add an extra line between both Arduinos. You would set the Arduino with the RTC as I2C master and the other Arduino as slave. The slave Arduino can pull the extra line with a digital output pin to LOW, so that the master Arduino can sense this as signal at one of it's digital input pins (configured with internal pullup resistor). When the master Arduino senses, that the extra line goes to LOW, it can request data from the slave. So you are using the extra line for signaling the master, that new data is available at the slave.

2. If you are not bound to I2C, other communication interfaces might be better suited. UART (in the Arduino framework called `Serial`) implements bidirectional bytewise communication. No master/slave relationship. That would be a lot easier.

  [1]: https://github.com/JChristensen/DS3232RTC/blob/master/src/DS3232RTC.cpp


body:
As explained by chrisl, the fact that the Arduinos communicate with I2c and the update of the RTC is by I2C, the update fails and locks the system. To resolve this I declare the global variables `boolean updateRTC = false;` and `time_t setUTC;` and in the method that processes UTC I assign the value true to `updateRTC` and the numeric value of UTC to` setUTC` and do the verification in `void loop()`.

```
// global vars
boolean updateRTC = false;
time_t setUTC;

// RTC update inside loop()
void loop() {
  digitalClockDisplay();
  delay(1000);

  if (setUTC > 0 && updateRTC == true) {
    updateRTC = false;
    RTC.set(setUTC);
    setTime(setUTC);
    setUTC = 0;
  }

}

// Method executed at the end of the onReceive() event
void i2cActionReceived(char* param, char* value) {
  if(strcmp(param, "setTime") == 0) {
    setUTC = processUTCFromI2c(value);

    updateRTC = true;
  }
}

```


message:
expected unidentified id before 'if"

#include <iostream>
    using namespace std;
    char board[3][3]={{'1','2','3'},{'4','5','6'},{'7','8','9'}};
    char turn='X';
    int draw=0;
    int row,column;
    void display_board()
    {
        system("cls");
        cout<<"\n\n TIC TAC TOE GAME:";
        cout<<"\n\n PLAYER[1]==O\t\t\t PLAYER[2]==X";
        cout<<"\t\t     |     |     \n";
        cout<<"\t\t     |     |     \n";
        cout<<"\t\t   "<<board[0][0]<<" |  "<<board[0][1]<<"  |  "<<board[0][2]<<"   \n";
        cout<<"\t\t     |     |     \n";
        cout<<"\t\t_____|_____|_____\n";
        cout<<"\t\t     |     |     \n";
        cout<<"\t\t     |     |     \n";
        cout<<"\t\t  "<<board[1][0]<<"  |  "<<board[1][1]<<"  |  "<<board[1][2]<<"    \n";
        cout<<"\t\t     |     |     \n";
        cout<<"\t\t_____|_____|_____\n";
        cout<<"\t\t     |     |     \n";
        cout<<"\t\t     |     |     \n";
        cout<<"\t\t  "<<board[2][0]<<"  |  "<<board[2][1]<<"  |   "<<board[2][2]<<"  \n";
        cout<<"\t\t     |     |     \n";
        cout<<"\t\t     |     |     \n";
    }
    void player_turn()
    {
        int choice;
        if(turn=='X')
        {
            cout<<"\n\t  PLAYER[1]==O's turn";
        }
        if(turn=='O')
        {
            cout<<"\n\t  PLAYER[2]==X's turn";
        }
        cin>>choice;
        switch(choice)
        {
            case 1:row=0; column=0; break;
            case 2:row=0; column=1; break;
            case 3:row=0; column=2; break;
            case 4:row=1; column=0; break;
            case 5:row=1; column=1; break;
            case 6:row=1; column=2; break;
            case 7:row=2; column=0; break;
            case 8:row=2; column=1; break;
            case 9:row=2; column=2; break;
            default:
            cout<<"Invalid input";
            break;
        }
       if(turn=='X' && board[row][column]!='X' && board[row][column]!='O')
       {
           board[row][column]=='X';
           turn='O';
       }
       else if(turn=='O' && board[row][column]!='X' && board[row][column]!='O')
       {
           board[row][column]=='O';
           turn='X';
       }
       else
       {
           cout<<"Box already filled!\nplease try again!!";
           player_turn();
       }
       display_board();
    }
    int gameover()
    {
        for(int i=0;i<3;i++)
        {
            if(board[i][0]==board[i][1] && board[i][0]==board[i][2] || board[0][i]==board[1][i] && board[0][i]==board[2][i])
            return 0;
            else if(board[0][0]==board[1][1] && board[0][0]==board[2][2] || board[0][0]==board[1][1] && board[0][0]==board[2][2])
            return 0;
        }
        for(int i=0;i<3;i++)
        {
            for(int j=0;j<3;j++)
            {
                if(board[i][j]!='X' && board[i][j]!='O')
                return 1;
            }
        }
        draw=1;

        return 0;
    }

    int main()
    {
        system("cls");
        while(gameover())
        {
        display_board();
        player_turn();
        gameover();
        }
     return 0;
    }

    if(turn=='X' && draw=0)
    {
        cout<<"PLAYER[2] WINS!!!";
    }
    else if(turn=='O' && draw==0)
    {
        cout<<"PLAYER[1] WINS!!!";
    }
    else
    {
        cout<<"GAMEDRAW!!!";
    }

body:
This fragment is outside of a function:

    if(turn=='X' && draw=0)
    {
        cout<<"PLAYER[2] WINS!!!";
    }
    else if(turn=='O' && draw==0)
    {
        cout<<"PLAYER[1] WINS!!!";
    }
    else
    {
        cout<<"GAMEDRAW!!!";
    }

Some other remarks:

1. Instead of multiple `return` statements, it is better to create a local variable, set it, and return that one at the end. So only use one `return` statement per function (that has a return value).

2. As chrisl mentions: Arduino does not have cin or cout. Use the Serial class for this.

3. You can replace the following code:

>

     switch(choice)
     {
        case 1:row=0; column=0; break;
        case 2:row=0; column=1; break;
        case 3:row=0; column=2; break;
        case 4:row=1; column=0; break;
        case 5:row=1; column=1; break;
        case 6:row=1; column=2; break;
        case 7:row=2; column=0; break;
        case 8:row=2; column=1; break;
        case 9:row=2; column=2; break;

by

    row    = (int) ((choice - 1) / 3);
    column =        (choice - 1) % 3;

4. Use an enum as return type for function `gameover()`
   E.g. EGameState { Running, PlayerOneWon, PlayerTwoWon, Draw };

   This removes also the global variable `draw`.

5. You call function `gamover` twice, one time within the while loop without checking the result.

6. Do not use a char for the variable `turn` but the player number, or a boolean (XPlayerHasTurn), or an enum.


message:
i2c slave write to ARM powered device master

I want to communicate to an ARM microprocessor via I2C protocol (Multitech mDot, which uses Mbed platform). I successfully receive data from it (and got it displayed on Arduino's serial monitor), but when I want to send data from the Arduino I don't receive nothing on the other end. This is my sketch:
<!-- language-all: lang-cpp -->

    #include <DHT.h>
    #include <Wire.h>

    // Sensor temperatura, humedad DHT11 (test).
    #define DHTPIN 10
    #define DHTTYPE DHT11
    DHT dht(DHTPIN, DHTTYPE);

    // Comunicacion i2c con nodo lora. 7bitaddress 010 1001 (r/w)
    #define SLAVE_ADDRESS 0x29

    // Variables globales de sensores
    float h;
    float t;

    void setup() {
      Wire.begin(SLAVE_ADDRESS);
      Wire.onReceive(receiveEvent);
      dht.begin();
      Serial.begin(9600);
    }

    void loop() {
      delay(5000);
      h = dht.readHumidity();
      t = dht.readTemperature();

      // Comprobamos si ha habido algún error en la lectura
      if (isnan(h) || isnan(t)) {
        Serial.println("Error obteniendo los datos del sensor DHT11");
        return;
      }

      Serial.print("Humedad: ");
      Serial.print(h);
      Serial.print(" %\t");
      Serial.print("Temperatura: ");
      Serial.print(t);
      Serial.println(" *C ");

      Wire.onReceive(receiveEvent);
    }

    // Total de bytes del arreglo de datos a transmitir: 28 bytes.
    void receiveEvent(int howMany) {
      Serial.print("Mensaje recibido por i2c desde MDOT LoRa Node: ");
      while (Wire.available() > 0) {
        Serial.print(char(Wire.read()));
      }
      Serial.println();
      char enviar = "Cacatua";
      Wire.write(enviar);
      return;
    }

I wanted to know if this schematic is correct and if the wire write as it is written is performed. If so, I will need to see what is wrong with the code on my ARM device.

body:
It is important to understand, that `Wire.write()` will not actually send data over the I2C bus. It will only put the data bytes into the send buffer of the library.

The normal way of the `Wire` library to send data as a slave is to implement the `onRequest` callback function. It will be called from an I2C ISR when a master on the I2C bus requests data from this slave. In the callback, you use `Wire.write()` to fill the buffer with data, which then get's send out to the master.

I'm not quite sure about the following: My guess regarding your previous code is, that the `Wire` library clears the send buffer at some time during the send or read code. That would mean, that the data written in the `onReceive` callback will simply be lost, instead of used for transmission of requested data. That might be meant that way, so that the users will stick to implementing the `onRequest` callback, which is the correct way of doing it.

---

Note: In your code, you call `Wire.onReceive(receiveEvent)` on every `void loop()` iteration. That isn't necessary. The `Wire.onReceive()` method only set's a function pointer to the callback function. It does NOT execute this callback function, which only will be called by the corresponding I2C ISR, when data is actually received. You should use this line only once in `setup()` to setup the callback function. Though using it multiple times does not break things here. It's just useless.


message:
Flashing ESP8266 ESP-12E/12F

I'm pretty new to Arduino programming and i'm trying to connect this ESP8266 module to my FTDI programmer but constantly getting this error on my ARDUINO IDE:  **esptool.FatalError: Failed to connect to ESP8266: Timed out waiting for packet header**.
My guess is that its not in flashing mode and that i have to connect GPIO0 to ground or sompthing else.

[![/][1]][1]

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

body:
On my version of this "Adatper" adapter the io pins were not connected. I patched io 0 to the esp-01 like header, to be able to put the ESP in bootloader mode. On the picture you see a paperclip jumper connecting io 0 to ground for flashing mode.

Back then I could leave the jumper connected, because the esp8266 run the sketch after upload. In new versions of esp8266 arduino boards package the esptool hard resets the esp8266 so it returns into flashing mode. [This can be changed in platform.txt.][1]

I recommend you to buy an esp8266 dev board with USB (Wemos, NodeMcu and similar)

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

  [1]: https://arduino.stackexchange.com/questions/65628/mega-esp8266-comms-sending-baffling-data/65638#65638
  [2]: https://i.stack.imgur.com/Msz1q.jpg
  [3]: https://i.stack.imgur.com/xUGEsm.jpg
  [4]: https://i.stack.imgur.com/21fK0.jpg


message:
What is "tCAN" in codes of CAN bus?

I'm new to Arduino and CAN bus. I'm studying some code examples which contain "tCAN message".
My guess it defines a class for of CAN messages. I did a lot of search but found no information on it except for sample codes. Can anyone help me out.  Thank you!

Some code from the example project:

    void activateCAN()
    {
     //***PREPARE MESSAGE***//
        tCAN message_act;
        message_act.id = 0x750;
        message_act.header.rtr = 0;
        message_act.header.length = 8;
        message_act.data[0] = 0x00;
        message_act.data[1] = 0x00;
        message_act.data[2] = 0x00;
        message_act.data[3] = 0x00;
        message_act.data[4] = 0x00;
        message_act.data[5] = 0x00;
        message_act.data[6] = 0x00;
        message_act.data[7] = 0x00;

        mcp2515_bit_modify(CANCTRL, (1 << REQOP2) | (1 << REQOP1) | (1 << REQOP0), 0);
        mcp2515_send_message(&message_act); //SEND MESSAGE
    }
    //******CAN ACTIVATION*****ENDS****//

body:
`tCAN` will be a `struct` that defines the structure of the CAN message being sent.  The name `tCAN` is not a standard and will have been chosen by the author of the library you are using.  At a guess it's using a variant of Hungarian Notation, and the `t` prefix means `type` - so it's probably been `typedef`'d from a struct to a type name.

I am not familiar with CAN, but if there are standard message formats this struct will correspond with one of them.  You can find the actual structure within the header file for your chosen library (or maybe in the example sketch code itself?).


body:
`tCAN` here is a `struct` that defines a CAN *frame* to be sent over the network.

https://en.m.wikipedia.org/wiki/CAN_bus#Frames

There are several types of frames, standard, extended, and FD (flexible data).

The tables in the linked Wikipedia article describe the physical protocol. The struct won’t have a corresponding field for every section of the protocol, because the library will take care of setting the constant or calculatable things, like the CRC and End of Frame. You just have to set the relevant details, like ID, (maybe) data length and the data itself.

If you have trouble, check your baud rates and ensure you’re sending the expected kind of frame. Most hobbyist will use standard frames, but many industrial grade pieces of equipment will use Extended or FD frames.


message:
Multiple libraries were found for "WiFiClient.h" using nodemcu

I am trying to send HTTP requests from nodemcu so I started by uploading the esp8266 library but when I run the following code

    #include <ESP8266HTTPClient.h>
    #include <ESP8266WiFi.h>

    void setup() {

      Serial.begin(115200);                                  //Serial connection
      WiFi.begin("Iphone de elaa", "27343550");   //WiFi connection

      while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

        delay(500);
        Serial.println("Waiting for connection");

      }

    }

    void loop() {

     if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status

       HTTPClient http;    //Declare object of class HTTPClient

       http.begin("http://localhost:8080/getallcadres/getnbpassage/5");      //Specify request destination
       http.addHeader("Content-Type", "text/plain");  //Specify content-type header

       int httpCode = http.POST("5");   //Send the request
       String payload = http.getString();                  //Get the response payload

       Serial.println(httpCode);   //Print HTTP return code
       Serial.println(payload);    //Print request response payload

       http.end();  //Close connection

     }else{

        Serial.println("Error in WiFi connection");

     }

      delay(30000);  //Send a request every 30 seconds

    }

i got this error

    Arduino: 1.8.9 (Windows Store 1.8.21.0) (Windows 10), Board: "Generic ESP8266 Module, 80 MHz, Flash, Disabled, All SSL ciphers (most compatible), ck, 26 MHz, 40MHz, DOUT (compatible), 512K (no SPIFFS), 2, nonos-sdk 2.2.1 (legacy), v2 Lower Memory, Disabled, None, Only Sketch, 115200"

    Build options changed, rebuilding all
    In file included from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecure.h:41:0,

                     from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiServerSecure.h:20,

                     from C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/ESP8266WiFi.h:41,

                     from C:\Users\ELA_HIDRI\Desktop\PFE_ING\nodemcu\nodemcu.ino:2:

    C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:38:5: error: 'BearSSL::WiFiClientSecure::~WiFiClientSecure()' marked override, but does not override

         ~WiFiClientSecure() override;

         ^

    C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:41:9: error: 'int BearSSL::WiFiClientSecure::connect(const String&, uint16_t)' marked override, but does not override

         int connect(const String& host, uint16_t port) override;

             ^

    C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:46:12: error: 'size_t BearSSL::WiFiClientSecure::write_P(const char*, size_t)' marked override, but does not override

         size_t write_P(PGM_P buf, size_t size) override;

                ^

    C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi\src/WiFiClientSecureBearSSL.h:58:12: error: 'size_t BearSSL::WiFiClientSecure::peekBytes(uint8_t*, size_t)' marked override, but does not override

         size_t peekBytes(uint8_t *buffer, size_t length) override;

                ^

    Multiple libraries were found for "WiFiClient.h"
     Used: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.21.0_x86__mdqgnx93n4wtt\libraries\WiFi
     Not used: C:\Users\ELA_HIDRI\Documents\ArduinoData\packages\esp8266\hardware\esp8266\2.5.2\libraries\ESP8266WiFi
    exit status 1
    Error compiling for board Generic ESP8266 Module.

so what is this error why i am getting it
**Edit**
i switched to an other version of arduino ide 1.6.5 the error is gone but it looks like it is not connection i got
[![here][1]][1]

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

body:
Simply Switch

    #include <ESP8266HTTPClient.h>
    #include <ESP8266WiFi.h>

to

    #include <ESP8266WiFi.h>
    #include <ESP8266HTTPClient.h>


body: I am new to nodemcu. When I was using ESP8266WiFi.h, I got the error "Error compiling for board NodeMCU 1.0 (ESP-12E Module)" which said that Multiple libraries were found for ESP8266WiFi.h. I solved by simply put the void loop(){} empty function at the end of my code. Now It's working...


message:
Arduino Timer with increase time button

I have an Arduino project to do, which requires a countdown timer(which I've already done). I connected a push button, and when I press that button I need it to increase my countdown timer by +10 seconds.

Can anyone help me with adding the code for this button?

Here is the code so far(I declared the button, but I don't know if it's any good):

    #include <LiquidCrystal.h>

    int buttonPin = 7;
    int buttonState = 0;
    int seconds = 30; // count seconds
    int minutes = 0; // count minutes
    int hours = 0; // count hours
    const int rs = 12, en = 11, d4 = 5, d5 = 4, d6 = 3, d7 = 2;
    //initialize the library with the numbers of the interface pins
    LiquidCrystal lcd(rs, en, d4, d5, d6, d7); // pins connected to LCD

    void setup()
    {
      lcd.begin(16, 2); //set up the LCD's number of columns and rows
      pinMode(buttonPin, INPUT);
    }
    void loop()
    {
      buttonState = digitalRead(buttonPin);
      lcd.setCursor(1, 0);
      lcd.print ("Sosire in:");
      lcd.setCursor(6, 1);
      lcd.print(":");
      lcd.setCursor(9, 1);
      lcd.print(":");

      seconds--;
      delay(1000);

     if (seconds < 0)
      {
        minutes--;
        seconds = 59;
      }
     if (minutes < 0)
      {
        hours--;
        minutes = 59;
      }
     if (hours < 0)
      {
        hours = 0;
        minutes = 0;
        seconds = 30;
      }
     if (minutes > 9)
      {
        lcd.setCursor(7, 1);
        lcd.print(minutes);
      }
     else
      {
        lcd.setCursor(7, 1);
        lcd.print("0");
        lcd.setCursor(8, 1);
        lcd.print(minutes);
        lcd.setCursor(9, 1);
        lcd.print(":");
      }

     if (seconds > 9)
      {
        lcd.setCursor(10, 1);
        lcd.print(seconds);
      }
     else
      {
        lcd.setCursor(10, 1);
        lcd.print("0");
        lcd.setCursor(11, 1);
        lcd.print(seconds);
        lcd.setCursor(12, 1);
        lcd.print(" ");
      }

     if (hours > 9)
      {
        lcd.setCursor(4, 1);
        lcd.print(hours);
      }
     else
      {
        lcd.setCursor(4, 1);
        lcd.print("0");
        lcd.setCursor(5, 1);
        lcd.print(hours);
        lcd.setCursor(6, 1);
        lcd.print(":");
      }
     if (seconds == 0)
      {
        lcd.clear();
        lcd.print("Este in statie");
        delay(5000);
        lcd.clear();
      }

    }

body:
I don't fully understand your program, but I hope to give some guidelines/tips:

- Instead of using all kind of different variables, with hour, minutes and seconds, with with only one variable that keeps the time. E.g. a long integer value that contains 24 * 60 * hours + 60 * minutes + seconds as one value. E.g. 12:34:56 will be 24 * 60 * 12 + 60 * 34 + 56 = 19,376.
- Subtracting one or 10 seconds will be as easy as subtracting a value 1 or 10.
- To calculate back to seconds, minutes and hours, use 3 formulas (assuming time is the time value):

>
    int hours   = (int) time / 60 / 24;
    int minutes = (int) (time - hours * 60 * 24) / 60;
    int seconds = time % 60;

- Keep the code to display the LCD separate, probably it's easier to update every digit every second. You probably change it every second, or when the button has been pressed, which is very slow for a MCU.
- When using a button (you already put it in a variable), just remove 10 seconds, and update the time.
- However, check also the Blink Without Delay example on the Arduino website, since when you press a button, high likely the button will bounce and one press may result in several times 10 seconds will be subtracted.
- And as said above, use good and English variable names, and English comments (except the GUI text to be displayed... O zi buna).


message:
writting to buffer from serial input

Can some one explain this behaviour please, i have the following code

      byte buffer[512];
      byte block;
      byte len;

      Serial.setTimeout(60000L) ;     // wait until 20 seconds for input from serial
      // Ask personal data: Family name
      Serial.println(F("Type text followed by #"));
      len = Serial.readBytesUntil('#', (char *) buffer, 500) ; // read from serial
      Serial.print(len);
      for (byte i = len; i < 250; i++) buffer[i] = '#';     // pad with #
      Serial.print(len);

This works but if i change the "for" line to any thing higer then 250 it stops working and there is a "buffer out of memory condition)

My question is why can't the for loop say the below as the buffer size is 512?

    for (byte i = len; i < 512; i++) buffer[i] = '#';

Am i right in thinking it has something to do with  (Char *), i did copy this code from the example ardunio code and was jsut trying to incress the lenth of input it accpeted.

body:
A byte can only contain values from 0 to 255 (including).

So my guess it works for values until 255.

You should use a different type, e.g. unsigned int or unsigned short.

    for (unsigned short i = len; i < 250; i++) buffer[i] = '#';     // pad with #

Also, I advise to use a constant or define for the buffer size, now you have 3 values (512, 500 and 250 in the loop, I assume they should be based on the same value).

About the char*: Looking at [StreamReadBytesUntil][1], it seems that the parameter wants a char* instead of a byte* (which is more or less the same), but it's better to cast to show the parameter is of type char* since that is high likely the exact type (but the official Arduino documentation does not show the parameter types sadly).

  [1]: https://www.arduino.cc/en/Reference/StreamReadBytesUntil


message:
http.POST is not sending data to local web page

I am using a nodeMCU to send data to my local web page developed using Spring boot but when I run the code I don't get an error the esp8266 connects to WiFi but I don't get anything on my spring boot app or any responses.
Here is the rest controller used from spring boot
<!-- language-all: lang-cpp -->

    @RestController
    @RequestMapping("/getallcadres")
    public class cadreController {
        @Autowired
        cadreRepository cadre;

    @PostMapping("/getnbpassage")
        public String getnbrpassage(@RequestBody String nb){
            System.out.println("nombre de passage = "+nb);
            return "received";

        }
    }

and the Arduino code

    #include <ESP8266HTTPClient.h>
    #include <ESP8266WiFi.h>

    void setup() {

      Serial.begin(9600);//Serial connection
      WiFi.disconnect();
      WiFi.begin("Iphone de elaa", "27343550");   //WiFi connection

      while (WiFi.status() != WL_CONNECTED) {  //Wait for the WiFI connection completion

        delay(500);
        Serial.println("Waiting for connection");

      }
      Serial.println("Wifi is connected");
      Serial.println(WiFi.localIP());

    }

    void loop() {

     if(WiFi.status()== WL_CONNECTED){   //Check WiFi connection status
     Serial.println("here we start");
       HTTPClient http;    //Declare object of class HTTPClient

       http.begin("http://localhost:8080/getallcadres/getnbpassage");      //Specify request destination
       http.addHeader("Content-Type", "text/plain");  //Specify content-type header

       int httpCode = http.POST("5");   //Send the request
       String payload = http.getString();//Get the response payload

       Serial.println("return code"+httpCode);   //Print HTTP return code
       Serial.println(payload);    //Print request response payload

       http.end();  //Close connection

     }else{

        Serial.println("Error in WiFi connection");

     }

      delay(30000);  //Send a request every 30 seconds

    }

I am using Arduino IDE 1.6.5 here is what I get
[![enter image description here][1]][1]

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

body: Your URL has `localhost` as the host name. That cannot work. localhost means “self”, the computer initiating the request. In this case it would mean the ESP8266, if it even understood it. You need to use the name or the IP address of the computer running your spring boot app, not localhost.


message:
Timestamping AnalogBinLogger data

I would like to timestamp the data collected from AnalogBinLogger.ino on an Arduino Uno. The sketch uses 512-byte buffers, and I have read that writing data in 512-byte chunks is 'better' in terms of write latencies.

The sketch uses this structure for the buffers:

    // Data block for 10-bit ADC mode.
    const size_t DATA_DIM16 = 254;
    struct block16_t {
      unsigned short count;    // count of data values
      unsigned short overrun;  // count of overruns since last block
      unsigned short data[DATA_DIM16];
    };

Since I want to add the timestamps which are of `unsigned long` type, I would have to modify the structure as follows:

    // Data block for 10-bit ADC mode.
    const size_t DATA_DIM16 = 254;
    struct block16_t {
      unsigned short count;    // count of data values
      unsigned short overrun;  // count of overruns since last block
      unsigned short data[DATA_DIM16];
      unsigned long  milli[DATA_DIM16]; // time in milliseconds
    };

Now, this structure exceeds 512 bytes and is **1528 bytes**. Due to unavailability of enough free stack, my program doesn't run (sketch reports FreeStack to be 1135 bytes). How can I go about this?

PS: My root problem is to achieve **time-synchronisation** among multiple data-collecting Arduinos which sample at high rates like 8kHz. Due to clock drifts, even if I sync the start times, the timestamps collected afterwards would not be relative to each other. Hence I plan to have a master Arduino send its time to the others in regular intervals.

body:
The straightforward solution:

```c++
const size_t DATA_DIM16 = 84;
struct block16_t {
  unsigned short count;    // count of data values
  unsigned short overrun;  // count of overruns since last block
  unsigned short data[DATA_DIM16];
  unsigned long  milli[DATA_DIM16]; // time in milliseconds
  unsigned long padding;   // pad to 512 bytes
};
```

Now, I suggest to think again about your requirements. Do you really
need a 32-bit timestamp for every data point? If they are closely spaced
in time, a 16-bit, or even 8-bit timestamp should be enough. You could
put a full 32-bit timestamp at the beginning of each block, then only
8-bit timestamps for every data point. This would allow you to store
168 samples per block. You could even pack a 6-bit timestamp with
the data sample into an `uint16_t`, and have 252 samples per block.


body:
Writing in 512 byte chunks is done by SD libraries, so you could rely on that layer and simply write and store single events

    struct block_t {
      uint32_t  milli; // time in milliseconds
      uint16_t data;
      uint8_t  overrun;  // overrun status since last block
    };

I do not know your `AnalogBinLogger.ino`. In other circumstances there's no such 512 byte limit, but a general and strict RAM limit. (You could decrease your DATA_DIM to make it fit safely)


message:
ESP32 cam board and waking from deep sleep

I am getting an error that the sd card cant be mounted when the ESP32 comes out of deep sleep. The board is coded to wake up on a timer from deep sleep and mount the sd card and take a picture. My question is how can I get the SD card to mount properly? I am providing 3volts to the board and I think the same error happens when 5volts is applied. Here is the code:

    /*********
      Rui Santos
      Complete project details at https://RandomNerdTutorials.com/esp32-cam-take-photo-save-microsd-card

      IMPORTANT!!!
       - Select Board "ESP32 Wrover Module"
       - Select the Partion Scheme "Huge APP (3MB No OTA)
       - GPIO 0 must be connected to GND to upload a sketch
       - After connecting GPIO 0 to GND, press the ESP32-CAM on-board RESET button to put your board in flashing mode

      Permission is hereby granted, free of charge, to any person obtaining a copy
      of this software and associated documentation files.
      The above copyright notice and this permission notice shall be included in all
      copies or substantial portions of the Software.
    *********/

    #include "esp_camera.h"
    #include "esp_timer.h"
    #include "img_converters.h"
    #include "Arduino.h"
    #include "fb_gfx.h"
    #include "fd_forward.h"
    #include "fr_forward.h"
    #include "FS.h"                // SD Card ESP32
    #include "SD_MMC.h"            // SD Card ESP32
    #include "soc/soc.h"           // Disable brownour problems
    #include "soc/rtc_cntl_reg.h"  // Disable brownour problems
    #include "dl_lib.h"
    #include "driver/rtc_io.h"
    #include <EEPROM.h>            // read and write from flash memo
    // define the number of bytes you want to access
    #define EEPROM_SIZE 1

    RTC_DATA_ATTR int bootCount = 0;
    // Pin definition for CAMERA_MODEL_AI_THINKER
    #define PWDN_GPIO_NUM     32
    #define RESET_GPIO_NUM    -1
    #define XCLK_GPIO_NUM      0
    #define SIOD_GPIO_NUM     26
    #define SIOC_GPIO_NUM     27

    #define Y9_GPIO_NUM       35
    #define Y8_GPIO_NUM       34
    #define Y7_GPIO_NUM       39
    #define Y6_GPIO_NUM       36
    #define Y5_GPIO_NUM       21
    #define Y4_GPIO_NUM       19
    #define Y3_GPIO_NUM       18
    #define Y2_GPIO_NUM        5
    #define VSYNC_GPIO_NUM    25
    #define HREF_GPIO_NUM     23
    #define PCLK_GPIO_NUM     22

    int pictureNumber = 0;

    #define uS_TO_S_FACTOR 1000000

    #define TIME_TO_SLEEP  60

    void setup() {

      WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); //disable brownout detector

      Serial.begin(115200);

      Serial.setDebugOutput(true);
      //Serial.println();

      camera_config_t config;
      config.ledc_channel = LEDC_CHANNEL_0;
      config.ledc_timer = LEDC_TIMER_0;
      config.pin_d0 = Y2_GPIO_NUM;
      config.pin_d1 = Y3_GPIO_NUM;
      config.pin_d2 = Y4_GPIO_NUM;
      config.pin_d3 = Y5_GPIO_NUM;
      config.pin_d4 = Y6_GPIO_NUM;
      config.pin_d5 = Y7_GPIO_NUM;
      config.pin_d6 = Y8_GPIO_NUM;
      config.pin_d7 = Y9_GPIO_NUM;
      config.pin_xclk = XCLK_GPIO_NUM;
      config.pin_pclk = PCLK_GPIO_NUM;
      config.pin_vsync = VSYNC_GPIO_NUM;
      config.pin_href = HREF_GPIO_NUM;
      config.pin_sscb_sda = SIOD_GPIO_NUM;
      config.pin_sscb_scl = SIOC_GPIO_NUM;
      config.pin_pwdn = PWDN_GPIO_NUM;
      config.pin_reset = RESET_GPIO_NUM;
      config.xclk_freq_hz = 20000000;
      config.pixel_format = PIXFORMAT_JPEG;
      //pinMode(4, INPUT);
      //digitalWrite(4, LOW);

      if(psramFound()){
        config.frame_size = FRAMESIZE_UXGA; // FRAMESIZE_ + QVGA|CIF|VGA|SVGA|XGA|SXGA|UXGA
        config.jpeg_quality = 10;
        config.fb_count = 2;
      } else {
        config.frame_size = FRAMESIZE_SVGA;
        config.jpeg_quality = 12;
        config.fb_count = 1;
      }

      // Init Camera
      esp_err_t err = esp_camera_init(&config);
      if (err != ESP_OK) {
        Serial.printf("Camera init failed with error 0x%x", err);
        return;
      }

      Serial.println("Starting SD Card");
      delay(2000);
      if(!SD_MMC.begin()){
        Serial.println("SD Card Mount Failed");
        //return;
      }

      uint8_t cardType = SD_MMC.cardType();
      if(cardType == CARD_NONE){
        Serial.println("No SD Card attached");
        return;
      }

      camera_fb_t * fb = NULL;

      // Take Picture with Camera
      fb = esp_camera_fb_get();
      if(!fb) {
        Serial.println("Camera capture failed");
        return;
      }
      // initialize EEPROM with predefined size
      EEPROM.begin(EEPROM_SIZE);
      pictureNumber = EEPROM.read(0) + 1;

      // Path where new picture will be saved in SD Card
      String path = "/picture" + String(pictureNumber) +".jpg";

      fs::FS &fs = SD_MMC;
      Serial.printf("Picture file name: %s\n", path.c_str());

      File file = fs.open(path.c_str(), FILE_WRITE);
      if(!file){
        Serial.println("Failed to open file in writing mode");
      }
      else {
        file.write(fb->buf, fb->len); // payload (image), payload length
        Serial.printf("Saved file to path: %s\n", path.c_str());
        EEPROM.write(0, pictureNumber);
        EEPROM.commit();
      }
      file.close();
      delay(2000);
      // Turns off the ESP32-CAM white on-board LED (flash) connected to GPIO 4
      pinMode(4, OUTPUT);
      digitalWrite(4, LOW);
      rtc_gpio_hold_en(GPIO_NUM_4);

      esp_sleep_enable_timer_wakeup(TIME_TO_SLEEP * uS_TO_S_FACTOR);

      Serial.println("Going to sleep now");

      delay(2000);
      esp_deep_sleep_start();
      Serial.println("This will never be printed");
    }

    void loop() {

    }
also [here][2] is the board I am using

Here is output of the error:

    rst:0x5 (DEEPSLEEP_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT)
    configsip: 0, SPIWP:0xee
    clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
    mode:DIO, clock div:1
    load:0x3fff0018,len:4
    load:0x3fff001c,len:1100
    load:0x40078000,len:9232
    load:0x40080400,len:6400
    entry 0x400806a8
    Starting SD Card
    E (4147) sdmmc_sd: sdmmc_check_scr: send_scr returned 0xffffffff
    SD Card Mount Failed
    No SD Card attached

  [1]: https://i.stack.imgur.com/PO12w.png
  [2]: https://randomnerdtutorials.com/esp32-pinout-reference-gpios/

Here is a diagram of the pins used by the SD card and Camera. Although I have nothing hooked up to them currently

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

body:
The code I posted forces GPIO4 to hold its value in this line:

rtc_gpio_hold_en(GPIO_NUM_4);

This pin is used for SD card interface. I needed to un-hold it after deep sleep wakeup if I wanted to use the pin again.


body:
You need to initialize SD_MMC to 1 bit mode (by default 4 bit mode) this way the microsd is slow, but you free up 3 pins, GPIO4 too. I had this problem to write on SD when used GPIO4 to switch on/off the flash led.

<code>
if (!SD_MMC.begin("/sdcard", true)) {  // 1 bit mode
    Serial.println("SD Card Mount Failed !!!");
    return;
}
YOUR CODE HERE ...
</code>

After this I can use GPIO12 as pullup input (tested on my sketch), when it goes to GND the camera will take the frame and save it to microsd (and even send it over TCP socket to Android device and my PC that save to storage memory and show it :D).

GPIO16 don't worked here, it work just one time, then remains LOW and can't be reused.

Note that I do not use sleep function, just check in the loop() the state of GPIO12 to trigger a camera shot.