body:
i'm noob in coding i try to make some led blink ( with succes ) and now i would like to add http request to change delay.

i have no error compiling the code but it dont work any idea ?

Thanks

     include SPI.h
     include Ethernet.h

    unsigned long maxTime = 4000;

    EthernetServer arduinoServer(81);
    EthernetServer httpServer(80);

    // Enter a MAC address and IP address for your controller below.
    // The IP address will be dependent on your local network:
    byte mac[] = {
      0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
    };
    IPAddress ip(192, 168, 8, 60);

    // Initialize the Ethernet server library
    // with the IP address and port you want to use
    // (port 80 is default for HTTP):
    EthernetServer server(80);

    ////CODE IS 11001010
    int led1 = 6;  // = 0
    int led2 = 7;  // = 1

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

      // Setup the 3 pins as OUTPUT
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);

      // You can use Ethernet.init(pin) to configure the CS pin
      //Ethernet.init(10);  // Most Arduino shields
      //Ethernet.init(5);   // MKR ETH shield
      //Ethernet.init(0);   // Teensy 2.0
      //Ethernet.init(20);  // Teensy++ 2.0
      //Ethernet.init(15);  // ESP8266 with Adafruit Featherwing Ethernet
      //Ethernet.init(33);  // ESP32 with Adafruit Featherwing Ethernet

      // Open serial communications and wait for port to open:
      Serial.begin(9600);
      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB port only
      }
      Serial.println("Ethernet WebServer Example");

      // start the Ethernet connection and the server:
      Ethernet.begin(mac, ip);

      // Check for Ethernet hardware present
      if (Ethernet.hardwareStatus() == EthernetNoHardware) {
        Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
        while (true) {
          delay(1); // do nothing, no point running without Ethernet hardware
        }
      }
      if (Ethernet.linkStatus() == LinkOFF) {
        Serial.println("Ethernet cable is not connected.");
      }

      // start the server
      server.begin();
      Serial.print("server is at ");
      Serial.println(Ethernet.localIP());

    }

    void loop()
    {
      digitalWrite(led1, LOW);
      digitalWrite(led2, HIGH);
      delay(maxTime);
      digitalWrite(led2, LOW);
      delay(maxTime);
      digitalWrite(led1, LOW);
      digitalWrite(led2, HIGH);
      delay(maxTime);
       digitalWrite(led1, HIGH);
       digitalWrite(led2, LOW);
      delay(maxTime);
      digitalWrite(led1, LOW);
       delay(maxTime);

       digitalWrite(led1, HIGH);
       digitalWrite(led2, LOW);
      delay(maxTime);
       digitalWrite(led1, LOW);
       digitalWrite(led2, HIGH);
      delay(maxTime);
       digitalWrite(led1, HIGH);
       digitalWrite(led2, LOW);
      delay(maxTime);
       digitalWrite(led1, LOW);
       digitalWrite(led2, HIGH);
      delay(maxTime);
       digitalWrite(led1, HIGH);
       digitalWrite(led2, LOW);
      delay(maxTime);
         digitalWrite(led1, LOW);
       digitalWrite(led2, LOW);
      delay(5000);

     // listen for incoming clients
    }

    void receiveHttpRequest() {
      EthernetClient client = httpServer.available();
      String requestInputString;
      boolean resetArduino = false;
      boolean forceSolved = false;
      client.setConnectionTimeout(50);

      if (client)
      {
        Serial.println("new client");
        // an http request ends with a blank line
        boolean currentLineIsBlank = true;
        boolean firstLine = true;
        requestInputString = String("");
        while (client.connected())
        {
          if (client.available())
          {
            char c = client.read();
            if (firstLine)
            {
              requestInputString += String(c);
            }
            Serial.write(c);
            // if you've gotten to the end of the line (received a newline
            // character) and the line is blank, the http request has ended,
            // so you can send a reply
            if (c == '\n' && currentLineIsBlank)
            {

              client.println("HTTP/1.1 200 OK");
              client.println("Content-Type: text/html");
              client.println("Connection: close"); // the connection will be closed after completion of the response
              client.println();
              client.println("<!DOCTYPE HTML>");
              client.println("<html><body>");

                int newMaxTime = requestInputString.substring(20).toInt();
                if (newMaxTime < 2000) {
                  newMaxTime = 2000;
                }

                maxTime = newMaxTime;

                client.print(String("New maxTime is: "));
                client.println(maxTime);
              }
            }
          }
        }
      }

title: Http request change delay

Answers: 1

body:
Inside `delay()` no other code can run. Which also means that no clients can be serviced.

Change that delay-laden function to a state machine mirroring blinkWithoutDelay.

That is you test `if(millis() - previousTimestamp < delay)` and if true progress to the next state in your blinks and update `previousTimestamp`.

After that `if` you call `receiveHttpRequest()` to see if any clients are waiting and process the input.


body:
I am trying to store values sended by C# app in EEPROM via Arduino UNO. Here is a C# code that reads bytes from file (I'm 100% sure that there are, and always will be 256 bytes) and sends the buffer via SerialPort

            SerialPort port = new SerialPort("COM3", 9600);
            const string fileName = @"filepath";
            port.Open();
            byte[] buffer = File.ReadAllBytes(fileName);
            port.Write("W");
            port.Write(buffer, 0, buffer.Length);

Here is Arduino Code

    int flag;
    int datasize = 256;
    byte byteBuffer[256];

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

      //read_write();
    }

    void loop() {
      readEEPROM();
      writeEEPROM();
      delay(500);
    }

    void readEEPROM() {
      if (Serial.available()) {
        flag = Serial.read();
        if (flag == 'R') {
          for (int i = 0; i < datasize; i++) {
            byteBuffer[i] = ME.read(i);
          }
          flag = 'S';
          Serial.write(byteBuffer, datasize);
        }
      }
    }
    void writeEEPROM() {
      if (Serial.available()) {
        flag = Serial.read();
        if (flag = 'W') {
          int bytesRead = 0;
          digitalWrite(LED_BUILTIN, HIGH);
          delay(500);
          while (bytesRead < 256) {
            if (Serial.available() > 0) {
              byteBuffer[bytesRead] = Serial.read();
              bytesRead++;
            }
          }
      digitalWrite(LED_BUILTIN, LOW);

      for (int i = 0; i < datasize; i++) {
        digitalWrite(LED_BUILTIN, HIGH);
        delay(50);
        ME.writeEnable();
        ME.write(i, byteBuffer[i]);
        ME.writeDisable();
        digitalWrite(LED_BUILTIN, LOW);
        delay(50);
      }
      flag = 'S';
       }
      }
     }

As you can see in `writeEEPROM` function arduino turns on `BUILTIN_LED` before it starts reading serial, sadly the LED is never turning off, which makes me think like there are never 256 bytes in SerialPort, whats more, when i turn the c# program on again, the arduino successfully leaves the while loop, but the data is deformed, I mean the values are different.

title: Missing bytes sended through serial from C# app

Answers: 1

body:
There's two basic things wrong here.

First is your way of opening the serial port and immediately sending data.  The Arduino is reset when you open the serial port and the bootloader runs. This takes a second or so, and during that time any data that you send is lost.

Secondly you're not checking for a flag of "W" but instead you're assigning "W" to the flag, which always succeeds.

The line

    if (flag = 'W') {

should read

    if (flag == 'W') {

To get around the first problem you can either just put a delay (however you do that in C#) after opening the port and before sending the "W", or you could implement a "Are you there?" handshake to look for the Arduino.

One example would be to add an extra flag of (say) "?" to which the Arduino simply responds "Y".

The PC then sends "?" and, if it doesn't receive "Y" within a certain timeout it loops sending "?" again.

Once it receives "Y" then it knows the Arduino is there and ready to receive data, so you can send the "W" command and the data.


body:
I am using buzzer in my arduino and I read some articles about using array of tones(notes in music) with different frequencies to play play pleasant melodies.however, I do not find any site and archives for tones used in industrial, such as Start,Stop,warning,danger,next level,.... is there any site that collects these things and if not how can I create my own array of tones?

this is notes I have

    #define NOTE_B0  31
    #define NOTE_C1  33
    #define NOTE_CS1 35
    #define NOTE_D1  37
    #define NOTE_DS1 39
    #define NOTE_E1  41
    #define NOTE_F1  44
    #define NOTE_FS1 46
    #define NOTE_G1  49
    #define NOTE_GS1 52
    #define NOTE_A1  55
    #define NOTE_AS1 58
    #define NOTE_B1  62
    #define NOTE_C2  65
    #define NOTE_CS2 69
    #define NOTE_D2  73
    #define NOTE_DS2 78
    #define NOTE_E2  82
    #define NOTE_F2  87
    #define NOTE_FS2 93
    #define NOTE_G2  98
    #define NOTE_GS2 104
    #define NOTE_A2  110
    #define NOTE_AS2 117
    #define NOTE_B2  123
    #define NOTE_C3  131
    #define NOTE_CS3 139
    #define NOTE_D3  147
    #define NOTE_DS3 156
    #define NOTE_E3  165
    #define NOTE_F3  175
    #define NOTE_FS3 185
    #define NOTE_G3  196
    #define NOTE_GS3 208
    #define NOTE_A3  220
    #define NOTE_AS3 233
    #define NOTE_B3  247
    #define NOTE_C4  262
    #define NOTE_CS4 277
    #define NOTE_D4  294
    #define NOTE_DS4 311
    #define NOTE_E4  330
    #define NOTE_F4  349
    #define NOTE_FS4 370
    #define NOTE_G4  392
    #define NOTE_GS4 415
    #define NOTE_A4  440
    #define NOTE_AS4 466
    #define NOTE_B4  494
    #define NOTE_C5  523
    #define NOTE_CS5 554
    #define NOTE_D5  587
    #define NOTE_DS5 622
    #define NOTE_E5  659
    #define NOTE_F5  698
    #define NOTE_FS5 740
    #define NOTE_G5  784
    #define NOTE_GS5 831
    #define NOTE_A5  880
    #define NOTE_AS5 932
    #define NOTE_B5  988
    #define NOTE_C6  1047
    #define NOTE_CS6 1109
    #define NOTE_D6  1175
    #define NOTE_DS6 1245
    #define NOTE_E6  1319
    #define NOTE_F6  1397
    #define NOTE_FS6 1480
    #define NOTE_G6  1568
    #define NOTE_GS6 1661
    #define NOTE_A6  1760
    #define NOTE_AS6 1865
    #define NOTE_B6  1976
    #define NOTE_C7  2093
    #define NOTE_CS7 2217
    #define NOTE_D7  2349
    #define NOTE_DS7 2489
    #define NOTE_E7  2637
    #define NOTE_F7  2794
    #define NOTE_FS7 2960
    #define NOTE_G7  3136
    #define NOTE_GS7 3322
    #define NOTE_A7  3520
    #define NOTE_AS7 3729
    #define NOTE_B7  3951
    #define NOTE_C8  4186
    #define NOTE_CS8 4435
    #define NOTE_D8  4699
    #define NOTE_DS8 4978
    #define REST      0

    // DURATION OF THE NOTES
    #define BPM 480      //you can change this value changing all the others
    #define H 2*Q //half 2/4
    #define Q 6000U/BPM //quarter 1/4
    #define E Q/2   //eighth 1/8
    #define S Q/4 // sixteenth 1/16
    #define W 4*Q // whole 4/4

title: is there any archives of melody tones for buzzer used in arduino?

Answers: 1

body:
    #define NOTE_C4  262
    #define NOTE_CS4 277
    #define NOTE_D4  294
    #define NOTE_DS4 311
    #define NOTE_E4  330
    #define NOTE_F4  349
    #define NOTE_FS4 370
    #define NOTE_G4  392
    #define NOTE_GS4 415
    #define NOTE_A4  440
    #define NOTE_AS4 466
    #define NOTE_B4  494
    #define REST      0

    int piezoPin = 13;
    int numTones = 15;
    int tempo = 2.5;

    //Twinkle Twinkle Little Star:

    int tones[] = {NOTE_C4, NOTE_C4, NOTE_G4, NOTE_G4, NOTE_A4, NOTE_A4, NOTE_G4, NOTE_F4, NOTE_F4, NOTE_E4, NOTE_E4, NOTE_D4, NOTE_D4, NOTE_C4, REST};

    int duration[] = {500, 500, 500, 500, 500, 500, 1000, 500, 500, 500, 500, 500, 500, 1000, 4000};

    void setup()
    {
      for (int i = 0; i < numTones; i++)
      {
        tone(piezoPin, tones[i], duration[i] / tempo);
        delay(duration[i] / tempo);
      }
      noTone(piezoPin);
    }

    void loop()
    {
    } // Reset to play the song again


body:
I have a UPS Power Module Expansion Board for Raspberry Pi 3B/3B+(Plus) and removed the power button because it is in the way and would like to attach this read button instead. But it is not working, they board does not turn on?

Am i wiring the incorrectly?

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

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

  [1]: https://i.stack.imgur.com/xPwxN.jpg
  [2]: https://i.stack.imgur.com/3XRvJ.jpg

title: Wiring power new power button to UPS power module for raspberry pi

Answers: 1

body: This looks like a momentary push-button; use a latching button (push-on/push-off) instead.


body:
I'm using Wemos mini in my project. I wish to store a Boolean value in cell #0, which changes every boot.

Since writing to EEPROM is limited to roughly 100,000 cycles - I want to store in cell #1 the amount of writing cycles done so far, so when reaching 100,000 , value will be stored in cell#2 and writing cycles will be stored in cell#3 and so on.

Reading and writing using `#include <EEPROM.h>` is done as needed, but since each cell can store a byte, it can only reach 255.

My question is how to store a value of 10^6 (except of convert it to a*2^0 + b*2^1 + c*2^2 + d*2^3....).

Guy

**EDIT1**

Part or relevant code:

    void setup() {
            Serial.begin(9600);
            Serial.println("BEGIN:");
            if (HARD_REBOOT) {
                    EEPROM.begin(1024);
            }
            if (HARD_REBOOT) {
                    EEPROM.write(0,100000);
                    EEPROM.commit();
                    delay(50);
                    Serial.print("value in flash: ");
                    Serial.println(EEPROM.read(0));
            }
    }

and its output:

    Ȥl⸮⸮BGS[⸮<b8ɗ⸮BEGIN:
    22:40:58.732 -> value in flash: 160

title: ESP8266 using EEPROM to store a value of 100,000

Answers: 2

body:
The esp doesn't have an eeprom, but emulates it in its flash. Therefore 100.000 cylces will not apply, it's more like 10.000 cycles for flash.

The easiest way to prepare a datatype to be stored as bytes is to use [union][1] like follows:

    union Converter{
      uint32_t ui32;
      byte eeprom_bytes[4];
    }convert;

    void convert_for_eeprom (uint32_t your_number) {
      convert.ui32=your_number;
      // convert.eeprom_bytes contains the 4-byte represenstation of your number, write those to eeprom
    }

    uint32_t convert_from_eeprom () {
      // read four bytes from eeprom and assign those to convert.eeprom_bytes
      return convert.ui32;
    }

Note that this isn't a type conversion and the value of convert.eeprom_bytes are not meant to be processed, as they are simply interpreted as if they were a four-byte array, indeed those bytes contain "dumb" values. This way you can "convert" **any datatype** for byte-wise storage and read-back respectively.

Another option to convert a 32 bit integer to 4 bytes is by using bit-wise operations:

    uint32_t your_number=100000;
    byte b1=your_number;
    byte b2=your_number>>8;
    byte b3=your_number>>16;
    byte b4=your_number>>24;

But this only makes sense for integers and I suggest taking a look at `union`.
  [1]: https://en.cppreference.com/w/cpp/language/union

body:
to save any variable to EEPROM use [`EEPROM.put()`][1], to read it use `EEPROM.get()`. example

`EEPROM.put(EEPROM_COUNT_ADDR, count);`

`EEPROM.get(EEPROM_COUNT_ADDR, count);`

On esp8266 EEPROM is emulated in flash and there **the whole page wears out**. [The EEPROM library][2] of esp8266 does what can be done to protect the flash pages used for EEPROM emulation.

  [1]: https://www.arduino.cc/en/Reference/EEPROMPut
  [2]: https://arduino-esp8266.readthedocs.io/en/latest/libraries.html#eeprom


body:
I have sd card reader and lcd display. I want to display bitmap with u8g2 library. My bitmap looks like:

    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0x3f, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00

If i write it in arduino ide like:

    static unsigned char bytes[] = {
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0x3f, 0x00, 0x00, 0x00, 0x80, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
    0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f, 0x00, 0x00
    };
Everything works fine. So how can i read it from sd card to have same result as in second code?

title: SD card reader and lcd display

Answers: 1

body:
This is talked about in multiple Arduino threads.  [This thread][1], [this thread][2] & [this thread][3] are just 3 found.

It appears reading and SDCard using an Arduino results in a text like character string.  The task is to parse this (if necessary) and convert it to the desired individual values.

The most efficient way to do this might be to use the [toCharArray()][4] to copy the String’s characters to a character array (buffer).  However, this implies the data is stored exactly as needed in the SDCard.  Which may be difficult to do.  Simply put, the program would read in a string (of likely unprintable letters) from the SDCard.  Then use the above function to convert that string into the supplied character array (buffer).

(Some more experienced readers might say if one used a [union][5] here, that the character string and the array of type characters would occupy the same memory and hence have the same data.  So no call to a conversion function is needed.  Once you read in the data as a string, it would be available to read out as an array of characters.)

More often it is preferred to store SDCard data for Arduino's in a (printable) text format.  Further it appears most store data using the [CSV][6] format.  When reading back this format the strings have to be parsed.  That is, the commas need to be found and the printable numbers between the commas need to be individually converted from short character strings to values.  The function atoi() is used to convert a character string like "123" to the integer value 123.  Then you can cast that number from an integer to an unsigned character to store in your array.

Another and perhaps easier approach is to use the [toint()][7] function call.  It would appear reading a number followed by a carriage return from the SDCard then unsung this function will result in an integer value.  You would not have to look and remove delineation characters as the toint() function is looking for carriage returns as the delineating character for you.

Many times working with an unknown amount of data is a problem.  If your data will always be a fixed size of 36 bytes - this should not concern you.

  [1]: https://forum.arduino.cc/index.php?topic=260983.0
  [2]: https://forum.arduino.cc/index.php?topic=492359.0
  [3]: https://forum.arduino.cc/index.php?topic=216587.0
  [4]: https://www.arduino.cc/reference/en/language/variables/data-types/string/functions/tochararray/
  [5]: https://en.wikipedia.org/wiki/Union_type#C/C++
  [6]: https://en.wikipedia.org/wiki/Comma-separated_values
  [7]: https://www.arduino.cc/en/Tutorial.StringToIntExample


body:
Does [MFRC522 library][1] support native SPI interface of Arduino Due?

By native SPI I mean this one:
[![enter image description here][2]][2]

I came here with this question because the initializer asks for 2 pins: SS and Reset:

    MFRC522(byte chipSelectPin, byte resetPowerDownPin);

SS pin can be any, but what about Reset?

  [1]: https://github.com/miguelbalboa/rfid
  [2]: https://i.stack.imgur.com/exsHn.png

title: Does MFRC522 supports native SPI of Arduino Due?

Answers: 1

body:
There is no reason why it wouldn't support the Due's SPI. It just uses the default SPI.h library as the interface.

The `resetPowerDownPin` can be anything you like. It is not part of the SPI protocol but specific to that library. It is just controlled with `digitalWrite()` internally.

If you don't want to use the functionality you can set it to `MFRC522::UNUSED_PIN` and it will be disabled.


body:
Gentlemen,
  I am a novice C++ programmer, When I was trying to learn how to use EEPROM with Arduino, I came across this statement

> i2c_eeprom_write_page(0x57, 0, (byte *)somedata, sizeof(somedata));

where I need to know what does (byte*) somedata mean?, please let me know if someone know the answer

Regards,

Mr.B

title: What does (byte*)variable_name mean in C++?

Answers: 1

body:
It means "Interpret this pointer as a pointer to byte data".  It's called "Casting" and allows you to fool the compiler into thinking that one type of data is another.

For example, your function expects a `byte *` (a pointer to byte data), and if you have `char *` as your variable you can change it on the fly to `byte *` by casting it like that.


body:
I use arduino nano.

When i use this code the rgb light on the fan is showing the colors right

`int rossoPin = 11;
int verdePin = 12;
int bluPin = 10;
void setup(){
  pinMode(rossoPin, OUTPUT);
  pinMode(verdePin, OUTPUT);
  pinMode(bluPin, OUTPUT);
}
void loop(){
    for(int i = 0; i < 256; i++){
    rgb(255-i, i, 0);
    delay(10);
  }
  for(int i = 0; i < 256; i++){
    rgb(0, 255-i, i);
    delay(10);
  }
  for(int i = 0; i < 256; i++){
    rgb(i, 0, 255-i);
    delay(10);
  }
}
void rgb(int red, int green, int blue){
  analogWrite(rossoPin, red);
  analogWrite(verdePin, green);
  analogWrite(bluPin, blue);
}`

,but when i use the full controller code it wont work nothing(ex.white color when it's on off state)

FULL CODE:
[link to the code][1]

  [1]: https://pastebin.com/ajJC615g

title: Arduino RGB IR Controller -> led always close to white

Answers: 0


body:
I am getting error on Serial monitor Soft WDT reset. I decoded the error code also and found the following stacktrace.

I am using SIM808 module and DFRobot_sim808 as the library.

> 0x4010030d: millis at <Directory>AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_wiring.c line 180
>
> 0x401003b9: __digitalWrite at <Directory>AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_wiring_digital.c line 82
>
> 0x40202863: sim808_wait_for_resp(char const*, DataType, unsigned int, unsigned int) at <Directory>Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 172
>
> 0x402027a4: sim808_send_byte(unsigned char) at <Directory>Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 118
>
> 0x402028ce: sim808_check_with_cmd(char const*, char const*, DataType, unsigned int, unsigned int) at <Directory>Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 191
>
> 0x402025dc: DFRobot_SIM808::init() at <Directory>Documents\Arduino\libraries\DFRobot_SIM808-master/DFRobot_sim808.cpp line 63
>
> 0x402024c1: setup at G:\Development\ESP8266\SIM Module\sim_module/sim_module.ino line 41 (discriminator 1)
>
> 0x40203248: loop_wrapper() at <Directory>AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_main.cpp line 122
>
> 0x40100e8d: cont_wrapper at <Directory>AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/cont.S line 81

I tried to find solution for the same everywhere but none found it. But the same code I am trying on arduino it works but not for ESP8266. I dont have long waiting loop(). But still it gives me error.

Below is the code for the same

    #include <DFRobot_sim808.h>
    #include <SoftwareSerial.h>

    #define PHONE_NUMBER "********"

    #define MESSAGE  "hello,world"

    #define PIN_TX D1
    #define PIN_RX D0

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

    void setup() {
      delay(1000);
      mySerial.begin(9600);
      Serial.begin(9600);

      while (!Serial) {
        ; // wait for serial port to connect. Needed for native USB
      }
      while(!sim808.init()) {
          delay(1000);
          Serial.print("Sim808 init error\r\n");
      }
      Serial.println("Sim808 init success");
      Serial.println("Start to send message ...");

      sim808.sendSMS(PHONE_NUMBER,MESSAGE);
    }

    void loop() {

    }

title: Soft wdt reset error on NodeMCU (ESP8266)

Answers: 1

body:
The culpret is the SIM808 library. It's not written to work well with the ESP8266.

The problem lies in [this function](https://github.com/DFRobot/DFRobot_SIM808/blob/master/sim808.cpp#L158):

    boolean sim808_wait_for_resp(const char* resp, DataType type, unsigned int timeout, unsigned int chartimeout)
    {
        int len = strlen(resp);
        int sum = 0;
        unsigned long timerStart, prevChar;    //prevChar is the time when the previous Char has been read.
        timerStart = millis();
        prevChar = 0;
        while(1) {
            if(sim808_check_readable()) {
                char c = serialSIM808->read();
                prevChar = millis();
                sum = (c==resp[sum]) ? sum+1 : 0;
                if(sum == len)break;
            }
            if ((unsigned long) (millis() - timerStart) > timeout * 1000UL) {
                return false;
            }
            //If interchar Timeout => return FALSE. So we can return sooner from this function.
            if (((unsigned long) (millis() - prevChar) > chartimeout) && (prevChar != 0)) {
                return false;
            }

        }
        //If is a CMD, we will finish to read buffer.
        if(type == CMD) sim808_flush_serial();
        return true;
    }

It has a loop that can take some time to run, and it doesn't `yield()` at any point to allow the ESP8266's housekeeping routines to run and "kick the dog".

Adding a call to `yield()` inside the `while(1)` loop should cure the problem.


body:
I have been practicing RPM and rotation counter in arduino using infrared optocoupler. I try to implement number of rotation for drill machine but whenever drill starts to rotate, LCD prints bad characters instead of displaying rotation.
Here is my code:

    #include<LiquidCrystal.h>

     LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);
                 int SensorPin=      13;

                 int Counter = 0;
    void setup() {
      lcd.begin(16,2);
      pinMode(SensorPin,INPUT);
        lcd.setCursor(0,0);

    }

    void loop() {

               lcd .setCursor(0,0);

              if(digitalRead(SensorPin))
      {
        Counter = Counter+1;
        while(digitalRead(SensorPin));

      }
      lcd.setCursor(0,1);
         lcd.print(Counter);
      // put your main code here, to run repeatedly:

    }

Here is my lcd at initial step:

[![lcd on start][1]][1]

When I start my drill, LCD changes to this:

[![lcd with bad charcters][2]][2]

  [1]: https://i.stack.imgur.com/2iDuU.png
  [2]: https://i.stack.imgur.com/IJXZW.png

title: LCD displays bad character while counting rotation

Answers: 1

body:
I suspect you get electrical noise on the leads from the optocoupler. A few test to help find cause:
1) Does the counter work if you rotate it by hand?
2) Does the LCD go funnny if you just have the optocoupler approximatly in the same position, but not count anything.


body:
Everything is ready for project except hardware!

 I have one doubt!

I am planning to use transmitter of Arduino *Uno* and receiver of Arduino *Nano*.  Will it work? Both Uno and Nano obey for same program? (The transceivers used are  Nrf24lO1 pa+lna!)

title: Everything is ready for project . I have one doubt! I am using transmitter + Arduino *Uno*..and receiver + arduino *nano* will it work?

Answers: 2

body: Yes, it will work, in much the same way that you can send an email from a Mac to a Windows PC. The type of PC doesn't matter as long as they use the same protocol. As you haven't shared any details in that direction, I would say that if you have coded correctly, then it will work.

body: That cannot be determined until a much better description of your project is given. The parts you named are compatible with both processors. It could fail for a simple software mistook or a bad connection. Generally speaking the UNO and Nano are interchangeable electrically but not mechanically. The nano gives you two additional analog channels. Start by getting the RF to work, this probably will be the most problematic to get going. Use seperate power supplies for the RF devices.


body:
I am trying to connect my nodemcu client with nodemcu server, while my client is connected with two sensors (DHT11 and Soil Moisture) and it is workign perfectly, but on the server side I am unable to get all values, it is only giving me value of one parameter.
Server Side Code
<!-- language-all: lang-cpp -->
```
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
String apiWritekey = "PBD5LAJC4BSV3OKC"; // replace with your THINGSPEAK WRITEAPI key here
const char* ssid = "Dhamaal";// your wifi SSID name
const char* password = "03334204224" ;// wifi pasword
///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~///

///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~///
const char* httpserver = "api.thingspeak.com";
ESP8266WebServer server;
WiFiClient client;

// Configuration parameters for Access Point
char * ssid_ap = "ESP_AP";
char * password_ap = "123456789";
IPAddress ip(192,168,11,4); // arbitrary IP address (doesn't conflict w/ local network)
IPAddress gateway(192,168,11,1);
IPAddress subnet(255,255,255,0);
// Set up the server object

// Keep track of the sensor data that's going to be sent by the client
float t1=0.0;
float h1=0.0;
float s1=0.0;

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

  WiFi.mode(WIFI_AP);
  WiFi.softAPConfig(ip,gateway,subnet);
  WiFi.softAP(ssid_ap,password_ap);

  // Configure the server's routes
  server.on("/",handleIndex); // use the top root path to report the last sensor value
  server.on("/update",handleUpdate); // use this route to update the sensor value
  server.begin();
}
void handleIndex() {
    server.send(200,"text/plain",String(t1));
    server.send(200,"text/plain",String(h1));
    server.send(200,"text/plain",String(s1));// we'll need to refresh the page for getting the latest value
}

void handleUpdate() {

  // The value will be passed as a URL argument
 t1 = server.arg("value").toFloat();
  h1 = server.arg("value").toFloat();
  s1 = server.arg("value").toFloat();

  delay(100);
  WiFi.begin(ssid, password);

  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

  Serial.println();
  Serial.println("");
  Serial.print("NodeMcu connected to wifi...");
  Serial.println(ssid);
  Serial.println();
  Serial.println(WiFi.localIP() );

  delay(1000);
  ///~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~///
 float t2 = t1;
 float h2 = h1;
 float s2 = s1;
  if (client.connect(httpserver,80))
  {
         String tsData = apiWritekey;
           tsData+="&field1=";
           tsData+=String(t2);
           tsData+="&field2=";
           tsData+=String(h2);
           tsData +="&field3=";
           tsData += String(s2);
           tsData += "\r\n\r\n";

     client.print("POST /update HTTP/1.1\n");//command to update
     client.print("Host: api.thingspeak.com\n");//host name here thingspeak.com
     client.print("Connection: close\n");//closing connection
     client.print("X-THINGSPEAKAPIKEY: "+apiWritekey+"\n");
     client.print("Content-Type: application/x-www-form-urlencoded\n");
     client.print("Content-Length: ");
     client.print(tsData.length());
     client.print("\n\n");  // the 2 carriage returns indicate closing of Header fields & starting of data
     client.print(tsData);

     Serial.print("Temp: ");
     Serial.print(t2);//printing on serial monitor
     Serial.print("Humi: ");
     Serial.print(h2);
     Serial.print("Soil: ");
     Serial.print(s2);
     Serial.println("uploaded to Thingspeak server....");//dialogue box
  //}
  digitalWrite(D4, LOW);

  client.stop();//stopping client

  Serial.println("Waiting to upload next reading...");
  Serial.println();
  delay(5000);

} }

void loop() {
server.handleClient();

}
```
and the output of it is
[![Server side output][1]][1]

while the code of my client is
```
#include <DHT.h>
#include <ESP8266WiFi.h>

// Initialize sensor parameters
// Initialize network parameters
const char* ssid = "ESP_AP";
const char* password = "123456789";
const char* host = "192.168.11.4"; // as specified in server.ino

#define DHTPIN 0          //pin where the dht11 is connected

DHT dht(DHTPIN, DHT11);

// Set up the client objet
WiFiClient client;

// Configure deep sleep in between measurements
const int sleepTimeSeconds = 2;

void setup() {

  // Connect to the server
  WiFi.begin(ssid,password);
  Serial.begin(115200);
  dht.begin();
  while(WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(500);
  }
  Serial.println();
  Serial.print("IP Address (AP): "); Serial.println(WiFi.localIP());

void loop() {
  // put your main code here, to run repeatedly:
   while (WiFi.status() == WL_CONNECTED) {
    delay(500);
    int s = analogRead(A0);
    float h = dht.readHumidity();
    float t = dht.readTemperature();
  Serial.print("Temperature: "); Serial.println(t);
  Serial.print("Humidity: "); Serial.println(h);
  Serial.print("Soil Moisture: "); Serial.println(s);
  // Connect to the server and send the data as a URL parameter
  if(client.connect(host,80)) {
    String url = "/update?value=";
    url += String(t);
    String url1 = "/update?value=";
    url1 += String(h);
    String url2 = "/update?value=";
    url2 += String(s);
    client.print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + host +  "\r\n" +
                 "Connection: keep-alive\r\n\r\n"); // minimum set of required URL headers
     client.print(String("GET ") + url1 + " HTTP/1.1\r\n" + "Host: " + host +  "\r\n" +
                 "Connection: keep-alive\r\n\r\n"); // minimum set of required URL headers
     client.print(String("GET ") + url2 + " HTTP/1.1\r\n" + "Host: " + host +  "\r\n" +
                 "Connection: keep-alive\r\n\r\n"); // minimum set of required URL headers
    delay(5000);

  }
    // Read all the lines of the response and print them to Serial
    Serial.println("Response: ");
    while(client.available()){
      String line = client.readStringUntil('\r');
      Serial.print(line);
  }
}
}
```
and its output is
[![Client side output][2]][2]

Kindly help me to get all values at server side, Thanks

  [1]: https://i.stack.imgur.com/l7mV5.png
  [2]: https://i.stack.imgur.com/KdAr8.png

title: Nodemcu Server with multiple sensors

Answers: 1

body:
You use the same name `value` for all `/update?` parameters. And the format of url parameters is `?name1=value1&name2=value2`

Use

    String url = "/update?t=";
    url += String(t);
    String url1 = "&h=";
    url1 += String(h);
    String url2 = "&s=";
    url2 += String(s);

send it as one GET request

and read `server.arg("t")`,  `server.arg("h")` and  `server.arg("s")`.

Note 1: Sending more responses with `serverSend` to one request from browser has no effect. Only the first will work.

Note 2: this kind of use of String class will fragment the memory and cause a crash

Note 3: You don't need to use HTTP to communicate between your devices over TCP network. You can use [simple TCP socket connections][1] without HTTP protocol overhead.

  [1]: https://arduino.stackexchange.com/questions/60819/esp8266-tcp-ip-communication/60821#60821


body:
I am using the library [SimpleSDAudio][1] to play a song from my SD card to an op-amp later in the circuit. I would like to take a sample from the audio pin (possibly with a Analog read) to power some visualizations (VU, etc.), although I am getting some unexpected readings off the audio pin.

I tried to bias the audio [using this post][2], but got the same results.

I'm not sure if I am headed in the wrong direction here, any help would be amazing.

    #include <SimpleSDAudio.h>
    int ReadPin = A0;
    int AudioValue = 0;

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

      Serial.print(F("\nInitializing SD card..."));

      if (!SdPlay.init(SSDA_MODE_FULLRATE | SSDA_MODE_MONO | SSDA_MODE_AUTOWORKER)) {
        Serial.println(SdPlay.getLastError());
        while(1);
        } else {
        Serial.println(F("Wiring is correct and a card is present."));
      }

      Serial.print(F("Looking for THRILLER.WAV... "));
      if(!SdPlay.setFile("THRILLER.WAV")) {
          Serial.println(F(" not found on card! Error code: "));
          Serial.println(SdPlay.getLastError());
          while(1);
      } else {
         Serial.println(F("found."));
      }

      Serial.print(F("Playing... "));
      SdPlay.play();

    }

      void loop() {
        AudioValue = analogRead(ReadPin);
        Serial.println(AudioValue);
        delay(50);

    }

[![Output of analogRead ][3]][3]

My expected output of sampling the output from A0:
[![enter image description here][4]][4]

  [1]: https://github.com/isramos/mico-shield/tree/master/libraries/SimpleSDAudio
  [2]: https://forum.arduino.cc/index.php?topic=508537.0
  [3]: https://i.stack.imgur.com/jDmxI.png
  [4]: https://i.stack.imgur.com/TOWIU.png

title: Playing Audio from SD - Get VU, or audio waveform

Answers: 1

body:
You are sampling your audio signal with only 20Hz. That is very low frequency for an audio signal, that humans can hear. Generally you need to sample your signal with double of the highest containing frequency at minimum, or you will only get nonsense (you can google Nyquist Rate for more information). Also a Nano does not have a real DAC, so the audio is generated via a PWM signal, which turn the line on and off very fast, so you only see the waveform only, if you apply a low pass filter (like a speaker will do, because it cannot move that fast).

But directly sampling the audio signal is overly complex, only for making a VU meter visualization. These visualizations are way slower, than the actual audio signal. So you need to take the mean value over a specific time interval. Best you can reach this by building a low pass filter using a resistor and a capacitor. You can sample the output of that filter, which will only have lower frequencies. The sampling frequency then should be double of the cut of frequency of the filter at minimum.

Of course it is also possible to do all this in software, but for this you would have to change the library and I guess you don't want to do this.


body:
I installed [Mosquitto broker](https://mosquitto.org/) in Raspberry in my local network.
I generated certificates in Raspberry as follows:

    sudo openssl genrsa -out ca.key 2048
    sudo openssl req -new -x509 -days 3600 -key ca.key -out ca.crt
    sudo openssl genrsa -out server.key 2048
    sudo openssl req -new -out server.csr -key server.key
    sudo openssl x509 -req -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 3600

I modified the Mosqutto configuration file (.conf) as follows:

    allow_anonymous false
    cafile /etc/mosquitto/certs/ca.crt
    certfile /etc/mosquitto/certs/server.crt
    keyfile /etc/mosquitto/certs/server.key
    tls_version tlsv1.2

I restarted Mosquitto everything ok

I downloaded the ca.crt file from Raspberry to my PC with Filezilla
from my PC I use MQTT.fx to connect I set the certificate.
**WORKS WELL**

The problem:
with ESP32 I can't connect when I set the certificate with `espClient.setCACert(ca_cert);`
MQTT connecting ...
> [E] [ssl_client.cpp: 33] handle_error (): X509 - Certificate
> verification failed, e.g. CRL, CA or signature check failed

Someone can help me, I can't understand if something is missing in the code or there is some error in generating the certificates

Please help
many thanks Michael

this is my code:

    #include <WiFi.h>
    #include <WiFiClientSecure.h>
    #include <PubSubClient.h>
    #include <ESPmDNS.h>

    /* change it with your ssid-password */
    const char* ssid = "XXXXXX";
    const char* password = "XXXXXXX";
    /* this is the MDNS name of PC where you installed MQTT Server */
    const char* serverHostname = "home";

    const char* ca_cert = \
    "-----BEGIN CERTIFICATE-----\n" \
    "MIIDmDCCAoCgAwIBAgIJAKV4GE+4y/G4MA0GCSqGSIb3DQEBCwUAMGExCzAJBgNV\n" \
    "BAYTAlRWMRAwDgYDVQQIDAdUcmV2aXNvMRUwEwYDVQQHDAxDYXN0ZWxmcmFuY28x\n" \
    "DDAKBgNVBAoMA1BTUzEMMAoGA1UECwwDUFNTMQ0wCwYDVQQDDARob21lMB4XDTE5\n" \
    "MDkwODE3NDIzOFoXDTI5MDcxNzE3NDIzOFowYTELMAkGA1UEBhMCVFYxEDAOBgNV\n" \
    "BAgMB1RyZXZpc28xFTATBgNVBAcMDENhc3RlbGZyYW5jbzEMMAoGA1UECgwDUFNT\n" \
    "MQwwCgYDVQQLDANQU1MxDTALBgNVBAMMBGhvbWUwggEiMA0GCSqGSIb3DQEBAQUA\n" \
    "A4IBDwAwggEKAoIBAQC2rPN7VQXtzLCl1LufJkzLK9xedrbW72K2vBZ34VNOl+tG\n" \
    "ffNx2QQLQC0Jh5GzB79dZweqAjCRBbIEpx0IGvHWrHDUQMJrvg4BcmDr0eqNCup/\n" \
    "tBItlEcCdvmWFfm3IBezOVBDFiQWmC4jvAC/G3DPlftHiPI1k3cDewKNJEJykxeD\n" \
    "8H/4KTAz+wJXyGZiviZYv8OYOTRMa3nEhg1vaQTMgCwEVBavg5fsEQkZLArBNJQM\n" \
    "Gmw0qDdJEMDGOGWPogxRAKrxvNnXr4mIebzPj9/UTrJnfzVOPEHZ9Uz5BU/psGCL\n" \
    "cnMkBeNEa/JyLR14Hu8e+xa/pOCpJ9Dqhi/BTji5AgMBAAGjUzBRMB0GA1UdDgQW\n" \
    "BBRIz+15SpOBqo0O+vOtgYvPj4LqWDAfBgNVHSMEGDAWgBRIz+15SpOBqo0O+vOt\n" \
    "gYvPj4LqWDAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUAA4IBAQC08Crs\n" \
    "w7LPX+Bd80NwPuxgBmMU4U/pCw8AyzzSgckHmay0K8KuHXhSvZjdl6i0gjG/2xLa\n" \
    "ghCtfFGIXPu1Lu226bhTWigmuFLYasG1MivTDz2LeUTFPQrtEO8KdsRUarPZW3Fj\n" \
    "nOMyVDdzE4+HxvzvARDc1QbE9SX2ozQcNKQp4oRpunfT2+/OyzYgfMVA7MVKvehX\n" \
    "VH49fRF1P1Ajizqr2eHDFImcMQTzepRT7IjfOiQ/8PoqrZGvGenMj5so1I9MtgyK\n" \
    "gVUf1ZWPBgxmhVfla6vYBZiTGuZMHSDuF6/yFC1QnoXVq7K+bbIhAE8lsPNuOY7V\n" \
    "dKidKIfBJiN378CC\n" \
    "-----END CERTIFICATE-----\n";

    /* create an instance of WiFiClientSecure */
    WiFiClientSecure espClient;
    PubSubClient client(espClient);

    /*LED GPIO pin*/
    const char led = 5;

    /* topics */
    #define COUNTER_TOPIC    "smarthome/room1/counter"
    #define LED_TOPIC     "smarthome/room1/led" /* 1=on, 0=off */

    long lastMsg = 0;
    char msg[20];
    int counter = 0;

    void receivedCallback(char* topic, byte* payload, unsigned int length) {
      Serial.print("Message received: ");
      Serial.println(topic);

      Serial.print("payload: ");
      for (int i = 0; i < length; i++) {
        Serial.print((char)payload[i]);
      }
      Serial.println();
      /* we got '1' -> on */
      if ((char)payload[0] == '1') {
        digitalWrite(led, HIGH);
      } else {
        /* we got '0' -> on */
        digitalWrite(led, LOW);
      }

    }

    void mqttconnect() {
      /* Loop until reconnected */
      while (!client.connected()) {
        Serial.print("MQTT connecting ...");
        /* client ID */
        String clientId = "ESP32Client";
        /* connect now */
        if (client.connect(clientId.c_str(),"XXXXX","XXXXXX")) {
          Serial.println("connected");
          /* subscribe topic */
          client.subscribe(LED_TOPIC);
        } else {
          Serial.print("failed, status code =");
          Serial.print(client.state());
          Serial.println("try again in 5 seconds");
          /* Wait 5 seconds before retrying */
          delay(5000);
        }
      }
    }

    void setup() {
      Serial.begin(9600);
      // We start by connecting to a WiFi network
      Serial.println();
      Serial.print("Connecting to ");
      Serial.println(ssid);

      WiFi.begin(ssid, password);

      while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
      }
      /* set led as output to control led on-off */
      pinMode(led, OUTPUT);

      Serial.println("");
      Serial.println("WiFi connected");
      Serial.println("IP address: ");
      Serial.println(WiFi.localIP());
      /*setup MDNS for ESP32 */
      if (!MDNS.begin("esp32")) {
          Serial.println("Error setting up MDNS responder!");
          while(1) {
              delay(1000);
          }
      }
      /* get the IP address of server by MDNS name */
      Serial.println("mDNS responder started");
      IPAddress serverIp = MDNS.queryHost(serverHostname);
      Serial.print("IP address of server: ");
      Serial.println(serverIp.toString());
      /* set SSL/TLS certificate */
      espClient.setCACert(ca_cert);
      /* configure the MQTT server with IPaddress and port */
      client.setServer(serverIp, 26391);
      /* this receivedCallback function will be invoked
      when client received subscribed topic */
      client.setCallback(receivedCallback);

    }
    void loop() {
      /* if client was disconnected then try to reconnect again */
      if (!client.connected()) {
        mqttconnect();
      }
      /* this function will listen for incomming
      subscribed topic-process-invoke receivedCallback */
      client.loop();
      /* we increase counter every 3 secs
      we count until 3 secs reached to avoid blocking program if using delay()*/
      long now = millis();
      if (now - lastMsg > 3000) {
        lastMsg = now;
        if (counter < 100) {
          counter++;
          snprintf (msg, 20, "%d", counter);
          /* publish the message */
          client.publish(COUNTER_TOPIC, msg);
        }else {
          counter = 0;
        }
      }
    }

title: Impossible to connect ESP32 with Mosquitto on Raspberry using certificates

Answers: 1

body:
@sempaiscuba and Bruno I solved by regenerating the certificates in this way
you have to do this comfortably script in Raspiberry

    #!/bin/bash

    IP="192.168.0.11"
    SUBJECT_CA="/C=SE/ST=Italy/L=Roma/O=himinds/OU=CA/CN=$IP"
    SUBJECT_SERVER="/C=SE/ST=Italy/L=Roma/O=himinds/OU=Server/CN=$IP"
    SUBJECT_CLIENT="/C=SE/ST=Italy/L=Roma/O=himinds/OU=Client/CN=$IP"

    function generate_CA () {
       echo "$SUBJECT_CA"
       openssl req -x509 -nodes -sha256 -newkey rsa:2048 -subj "$SUBJECT_CA"  -days 365 -keyout ca.key -out ca.crt
    }

    function generate_server () {
       echo "$SUBJECT_SERVER"
       openssl req -nodes -sha256 -new -subj "$SUBJECT_SERVER" -keyout server.key -out server.csr
       openssl x509 -req -sha256 -in server.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out server.crt -days 365
    }

    function generate_client () {
       echo "$SUBJECT_CLIENT"
       openssl req -new -nodes -sha256 -subj "$SUBJECT_CLIENT" -out client.csr -keyout client.key
       openssl x509 -req -sha256 -in client.csr -CA ca.crt -CAkey ca.key -CAcreateserial -out client.crt -days 365
    }

    function copy_keys_to_broker () {
       sudo cp ca.crt /etc/mosquitto/certs/
       sudo cp server.crt /etc/mosquitto/certs/
       sudo cp server.key /etc/mosquitto/certs/
    }

    generate_CA
    generate_server
    generate_client
    copy_keys_to_broker

as you see OU changes for each file.
Remember to restart Mosquitto

    sudo systemctl stop mosquitto.service
    sudo systemctl start mosquitto.service

let me know how it goes
bye
Michele


body:
I have a project which has two options
No. 1 Randomly turn on one LED from a group of 6 LED (Relay Board)
No.2 randomly turn on one LED from a group of 2 LED (Relay Board)
The selection of the desired option happens with a switch.

I found this code online which is just perfect for 6 LED but I don't know how to add the selection of the options in it, how to do it?

 int timeShowRandom = 3000;
 int timeShowDecision = 6000;
 int timeBlink = 100;
 int buttonPin = 2;
 int buttonPress = false;
 int randomNumber;
 int previousNo = 0;
 int timePassed = 0;

 void setup() {
   // Set button pin
   pinMode(buttonPin, INPUT);
   // Set output pins
   pinMode(12, OUTPUT);
   pinMode(11, OUTPUT);
   pinMode(10, OUTPUT);
   pinMode(9, OUTPUT);
   pinMode(8, OUTPUT);
   pinMode(7, OUTPUT);
 }

 void getRandomNo() {
  int rand = random(7,13);
   if (rand == previousNo) {
    getRandomNo();
   } else {
  randomNumber = rand;
  previousNo = randomNumber;
   }
 }

 void loop() {
  if (digitalRead(buttonPin) == HIGH && buttonPress == false ) {
   buttonPress = true;
   } if (buttonPress == true && timePassed <= timeShowRandom) {
  getRandomNo(); // Get random pin number
  digitalWrite(randomNumber, LOW);
  delay(timeBlink);
  digitalWrite(randomNumber, HIGH);
  delay(timeBlink);
    timePassed = timePassed + (timeBlink * 2);
   } else if(buttonPress == true) {
  digitalWrite(random(7,13), LOW); // Set random pin on
  delay(timeShowDecision); // For x seconds
  buttonPress = false; // Set button to be enabled again
  timePassed = 0;
   }
   else {
  // Reset all output pins
  digitalWrite(10, HIGH);
  digitalWrite(11, HIGH);
  digitalWrite(12, HIGH);
  digitalWrite(9, HIGH);
  digitalWrite(8, HIGH);
  digitalWrite(7, HIGH);
   }
 }

title: Arduino random LED on

Answers: 1

body:
Various suggestions:

Create 2 different arrays of pin numbers: 1 for the first group of relay pins, and the 2nd for the second group of relay pins:

    byte firstRelayPins[] = [7, 8, 9, 10, 11, 12];
    byte secondRelayPins[] = [13, 14]; //Replace values with your relay pins

Write a function that returns a random index from one or the other of the arrays based on a bool:

    byte randomPin(bool useSecondArray) {
        int max;
        int index;
        if useSecondArray {
           return secondRelayPins[random(sizeof(secondRelayPins))]; //Fetch random pin from array
        } else {
           return firstRelayPins[random(sizeof(firstRelayPins))]; //Fetch random pin from array
        }
    }

Based on the state of your switch, set useSecondArray when you call that function to determine which relay's pin you turn on.

Use the returned value to set the desired relay pin.

In your "turn everything off" code, use the arrays of index pins rather than hard-coded indexes.

You should also refactor your code to use `millis()` rather than using `delay()`. (Search on "Arduino blink without delay" for guidance on how to do that.)

Note that this is a rough outline of what to do. The code above will likely need to be adjusted to fit your needs. Don't expect to be able to copy/paste it into your project.


body:
I am using soil sensor with Arduino UNO. I wish to transmit data coming from sensor to a server using sim800l.
I am unable to find any help on this. please guide me.

title: How to transmit data from a sensor using SIM800L?

Answers: 0


body:
i need using OV7670 camera on my arduino mega, and i found this site have tutorial using ov7670 camera, but in this tutorial they use arduino Uno. if i'm using arduino Mega2560, what i need to do? do i have to change their code and pin connection ?

here is the link

https://www.instructables.com/id/OV7670-Arduino-Camera-Sensor-Module-Framecapture-T/?amp_page=true

title: How i convert to Arduino Mega?

Answers: 1

body:
**Yes, you will have to change the code to match the Mega pinout**.

Because the program need to run quite fast, and the Arduino functions
`digitalRead()` and `digitalWrite()` are dead slow, the author of the
program used [direct port access][] for performing the raw IO.
[For example][]:

```c++
 //Wait for vsync it is on pin 3 (counting from 0) portD
 while(!(PIND&8));//wait for high
 while((PIND&8));//wait for low
```

This is testing pin PD3 (8 is 23), which on the Uno is
digital 3, but on the Mega is digital 18. The same code could
be written in a portable fashion:

```c++
 //Wait for vsync it is on pin 3 (counting from 0) portD
 while (digitalRead(3) == LOW);   //wait for high
 while (digitalRead(3) == HIGH);  //wait for low
```

but it would probably be too slow.

Note also that here:

```c++
    UDR0=(PINC&15)|(PIND&240);
```

the program takes advantage of the particular pin mapping of the Uno in
order to read 8 inputs with only two port reads (4 bits on
port C and 4 bits on port D). You could do even better on the Mega
if you use pins A8 through A15 for the data bus, and then read the whole
8-bit word as `PINK`.

There may be some other differences between the Uno and the Mega that
need to be taken into account, but the pin mapping is the only one that
is obvious to me just by quickly going through the code.

[direct port access]: https://www.arduino.cc/en/Reference/PortManipulation
[For example]: https://github.com/ComputerNerd/ov7670-no-ram-arduino-uno/blob/d64dcf0a8c9c04c5b4c5fe1da01fd2c6d9b35600/main.c#L34-L36


body:
I am trying to make my ESP8266(nodemcu) as a Web server. When my code operates, and user connects esp's wifi and enters '192.168.4.1/set_peroid' by IE or chrome, this webpage appears:

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

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

This is setting menu page. Usually, user puts sampling rate and time peroid, and duration or counter. Then presses 'submit', these data are going to be saved on my esp's EEPROM.

This is the code: (apologize about its complexity)

```
void input_handleForm() {

  int sample_int=0;
  int s_peroid_int=0;
  int m_peroid_int=0;

  int h_timer_int=0;
  int m_timer_int=0;

  int count_int=0;
  unsigned short curr_tmp=0;
  unsigned short max_tmp=0;

  //setting sampling rate
  String sample_str = server.arg("sample"); //get string data to 'sample' blank
  sample_int = sample_str.toInt(); //and convert to int data

  sample_int = (sample_int/4);
  EEPROM.write(SAMPLING_TIMES, sample_int); //devide by 4 and save it

  //setting user peroid (second or minute)
  String s_peroid_str = server.arg("peroid_s"); //get string data to peroid(sec) blank
      if(s_peroid_str !=NULL){
          s_peroid_int = s_peroid_str.toInt(); //and save it

            if(s_peroid_int<1){
              s_peroid_int=1;
            }
          EEPROM.write(SECOND_INDEX,s_peroid_int); //and save to the eeprom
          EEPROM.write(MINUTE_INDEX,0);
         }
       else{
          s_peroid_int =0;
          EEPROM.write(SECOND_INDEX,0);
        }

  String m_peroid_str = server.arg("peroid_m"); //get string data to peroid(min) blank

      if(m_peroid_str != NULL){

        m_peroid_int = m_peroid_str.toInt(); //save it by int

          if(m_peroid_int <1){
            m_peroid_int=1;
          }

        EEPROM.write(MINUTE_INDEX,m_peroid_int);//and save the integer to eeprom
        EEPROM.write(SECOND_INDEX,0);
      }
      else{
        m_peroid_int=0;
        EEPROM.write(MINUTE_INDEX,0);
       }

      //if user do not input anything ...
      if(m_peroid_int ==0 && s_peroid_int ==0){
        s_peroid_int = 1;
        EEPROM.write(SECOND_INDEX,s_peroid_int);
      }

    //setting timer
    String h_timer_str = server.arg("hour"); //get string data to hour blank
      if(h_timer_str != NULL){
        h_timer_int = h_timer_str.toInt();

          if(h_timer_int <1){
            h_timer_int=0;
          }
      }
      else{//if get null
        h_timer_int=0;
      }

    String m_timer_str = server.arg("minit"); //get string data to minute blank
      if(m_timer_str !=NULL){
        m_timer_int = m_timer_str.toInt();

          if(m_timer_int<1){
            m_timer_int=1;
          }
      }
      else{//if get null
        m_timer_int =0;
      }

      //caculate the 'repeat count' by (time/peroid)

      unsigned long until = (h_timer_int * 60) + m_timer_int;
         //until is set standard by minute. if user's peroid is second, have to *60

        if(until>0 && m_peroid_int >0){ //if peroid is setted by minute

            unsigned short index = until/ m_peroid_int;
            index+=3;
            EEPROM.put( MAXIMUM_INDEX , (unsigned short) index );

        }

        else if(until>0 && s_peroid_int>0){ //if peroid is setted by second
              until = until * 60; //make until(minute) to second
              unsigned short index = until / s_peroid_int;
              index+=3;
              EEPROM.put( MAXIMUM_INDEX, (unsigned short) index );

        }

        else if(until ==0){ //if user do not set timer, then scan the counter input.

          String count_str = server.arg("counts");//get string data to 'count' blank

            if(count_str !=NULL){
               count_int = count_str.toInt();
               unsigned short count_short = (unsigned short) count_int;
               count_short+=3;
                EEPROM.put( MAXIMUM_INDEX, (unsigned short) (count_short) );
            }

            else{//if user do not set timer and do not input count then...
              unsigned short tmp_default = 5;
               EEPROM.put(MAXIMUM_INDEX, (unsigned short) tmp_default );
            }

        }

         EEPROM.commit();

         delay(100);

    String s = "setting done.";
    s += "<a href='/'> Go Back </a>";
    server.send(200, "text/html", s); //Send web page

}
```

Even though they look complex, they are usually working. But problem is, when input the data and press 'submit', sometimes, very sometimes the program breaks down, irregularly. And when it breaks down, it says:
```
ets Jan  8 2013,rst cause:4, boot mode:(1,6)

wdt reset
```

Although there is 'wdt reset', but system does not reset. ESP just stops and does nothing.

Please give me advice about what is the problem, and help for a solution.

title: when submit data to ESP8266, ets Jan 8 2013,rst cause:4, boot mode:(1,6) wdt occurs

Answers: 0


body:
I am able to establish a connection between first and second NodeMCU, but unable to do so for the third nodeMCU. I used the IP  address to establish connection.
Should I assign a different IP to each nodeMCU so that communication can take place?
In the code that I had written, i have taken the same IP for all three NodeMCUs, so   communication was possible between 1st nodemcu(in AP mode) and 2nd nodemcu(in STA+AP mode).
For the 3rd node mcu the IP taken was different. Can any one suggest what to do next.

title: Communication between three NodeMCUs such that one in in AP mode, second one in AP+STA mode and the third NodeMCU in STA mode

Answers: 1

body: The two network interfaces (station and SoftAP) of the middle esp8266 must have different IP address range. If the top esp8266 has SoftAP with 192.168.4.x, set for the SoftAP of the middle esp8266 IP for example 192.168.5.1. Because with same IP address ranges the esp8266 doesn't know to which network do you want to connect a TCP socket or send an UDP message.


body:
I am using an ESP32 NodeMCU for which I wrote working software before. This also occurs when I just try to compile without uploading, so no hardware problem.
I am using the newest version of **ArduinoJson(6.12.0)** and it is included:

`#include <ArduinoJson.h>`

The only Function where I use the Library (I'm not good at C/C++, so maybe there is an error):

    int DeserializeJson(char *json, int *pin, int *pinmode, int *timeInMilliseconds){

      StaticJsonDocument<1024> doc;
      DeserializationError error = deserializeJson(doc,json);

      if (error) {

        Serial.println("Parsing failed");
        return -1;
      }

      memcpy(&pin, doc["Pin"], sizeof( doc["Pin"]));
      memcpy(&pinmode, doc["Mode"], sizeof( doc["Mode"]));
      memcpy(&timeInMilliseconds, doc["TimeInMilliseconds"], sizeof( doc["TimeInMilliseconds"]));

      return 0;
    }

This is the error I'm getting (at least a part of it):

    In file included from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayIterator.hpp:8:0,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayRef.hpp:8,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:17,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,

                     from C:\Users\error404\source\repos\IOT\esp32\esp32.ino:1:

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp: In instantiation of 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]':

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

    C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:240:24: error: no matching function for call to 'variantAs(ArduinoJson6120_000001::VariantData* const&)'

         return variantAs<T>(_data);

                            ^

    In file included from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantOr.hpp:9:0,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantOperators.hpp:9,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:12,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayIterator.hpp:8,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Array/ArrayRef.hpp:8,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.hpp:17,

                     from C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson.h:9,

                     from C:\Users\error404\source\repos\IOT\esp32\esp32.ino:1:

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:55:59: note: candidate: template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_integral<T>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*)

     inline typename enable_if<is_integral<T>::value, T>::type variantAs(

                                                               ^

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:55:59: note:   template argument deduction/substitution failed:

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp: In substitution of 'template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_integral<T>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*) [with T = const void*]':

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:240:24:   required from 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

    C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:55:59: error: no type named 'type' in 'struct ArduinoJson6120_000001::enable_if<false, const void*>'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp: In instantiation of 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]':

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

    C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:61:61: note: candidate: template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_same<T, bool>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*)

     inline typename enable_if<is_same<T, bool>::value, T>::type variantAs(

                                                                 ^

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:61:61: note:   template argument deduction/substitution failed:

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp: In substitution of 'template<class T> typename ArduinoJson6120_000001::enable_if<ArduinoJson6120_000001::is_same<T, bool>::value, T>::type ArduinoJson6120_000001::variantAs(const ArduinoJson6120_000001::VariantData*) [with T = const void*]':

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp:240:24:   required from 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type ArduinoJson6120_000001::VariantRef::as() const [with T = const void*; typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::VariantRef>::value)), typename ArduinoJson6120_000001::VariantAs<T>::type>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Object/MemberProxy.hpp:70:52:   required from 'typename ArduinoJson6120_000001::VariantAs<T>::type ArduinoJson6120_000001::MemberProxy<TParent, TStringRef>::as() const [with TValue = const void*; TObject = ArduinoJson6120_000001::JsonDocument&; TStringRef = const char*; typename ArduinoJson6120_000001::VariantAs<T>::type = const void*]'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Operators/VariantCasts.hpp:16:35:   required from 'ArduinoJson6120_000001::VariantCasts<TImpl>::operator T() const [with T = const void*; TImpl = ArduinoJson6120_000001::MemberProxy<ArduinoJson6120_000001::JsonDocument&, const char*>]'

    C:\Users\error404\source\repos\IOT\esp32\esp32.ino:70:47:   required from here

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantAs.hpp:61:61: error: no type named 'type' in 'struct ArduinoJson6120_000001::enable_if<false, const void*>'

    C:\Users\error404\Documents\Arduino\libraries\ArduinoJson\src/ArduinoJson/Variant/VariantRef.hpp: In instantiation of 'typename ArduinoJson6120_000001::enable_if<(((! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ArrayRef>::value) && (! ArduinoJson6120_000001::is_same<T, ArduinoJson6120_000001::ObjectRef>::value)) && (! ArduinoJson6120_000001::is_same<T,

    exit status 1
    Fehler beim Kompilieren für das Board ESP32 Dev Module.

title: Can't Compile .ino using ArduinoJson Library

Answers: 1

body:
In its own way, the compiler tries to say "I don't know how to convert `doc["Pin"]` to a `const void*`".

Indeed, ArduinoJson doesn't support conversion to `const void*`; it supports conversion to `const char*`, but that doesn't make sense here. Instead, you want to convert `doc["Pin"]` to an integer and assign it to the variable passed by the caller of `DeserializeJson()`.

The solution is to use the assignment operator instead of `memcpy()`:

```c++
*pin = doc["Pin"];
*pinmode = doc['Mode"];
*timeInMilliseconds = doc["TimeInMilliseconds"];
```


body:
I am having a problem with a MAXIM Serial module (Config A) with a simple repeating code from COM port. When sending a character (`k`:`0x6b`) I receive a (`0x00`) echo.

Without the module and just connecting the arduinos crossing the TX/RX cables, I do not have any echo.

The echo persists, disregarding of:

 - The speed (from 38400 to 2000000 bps),
 - Using or not the high speed options (2.3MOhm for 250000bps) of the MAXIM,
 - Using or not 120 ohm terminal resistors,
 - Both grounds are 0V, connecting them has no effect,
 - Removing the `A` (red) `B` (green) Serial Bus Cables (???). Message not send in this case, as expected (!).

What could be the problem?

**Devices**:

 - Two Arduino Mega 2560,
 - Two [MAX3292][1], one for each arduino,
 - AWG24 Cable, shorter than 7 in each.

**Config A**: With Module (`00` echo), Half Duplex (f.19 p.13).

[![Config A][2]][3]
[![Config A Datasheet][4]][5]

**Config B**: Without Module (No echo), only crossed cables

[![Config B][6]][7]

Code:

    long rate=38400;
    void setup() {
     Serial.begin(rate); while (!Serial);
     Serial1.begin(rate); while (!Serial1);
     pinMode(22,OUTPUT);
     pinMode(23,OUTPUT);
    }
    char s;
    void loop() {
     if (Serial.available()) {
      digitalWrite(22,1);
      digitalWrite(23,1);
      s=Serial.read();
      Serial1.write(s);
      Serial1.flush();
      digitalWrite(23,0);
      digitalWrite(22,0);
     }
     if (Serial1.available()){
       s=Serial1.read();
       Serial.write(s);
      }
    }

Execution: Four `k` sent, `0x00` echoes received. After this, four `k` send from other arduino, received successfully.

[![Exec A][8]][9]
[![enter image description here][10]][11]

**Epilogue.**

Actually, the problem was a resistor at the RO output, not shown in the diagram ("The problem is in the code you didn't post").

It was a voltage divider for a 5V3.3 conversion in the Arduino Due case, useless in the Arduino Mega, but still there.

Theorizing a reason, that resistor caused a spike at the output (?), thus forcing the module to interpret it as another byte, an empty one (?).

After removing the resistors, it worked perfectly.
Now I migrated this back into Arduino Due, but with a diode plus a pull up resistor as a 5V3.3 converter.

  [1]: https://datasheets.maximintegrated.com/en/ds/MAX3291-MAX3292.pdf
  [2]: https://i.stack.imgur.com/bJRCLm.png
  [3]: https://i.stack.imgur.com/bJRCL.png
  [4]: https://i.stack.imgur.com/Wy2a9m.png
  [5]: https://i.stack.imgur.com/Wy2a9.png
  [6]: https://i.stack.imgur.com/cwsI1m.png
  [7]: https://i.stack.imgur.com/cwsI1.png
  [8]: https://i.stack.imgur.com/02fXem.png
  [9]: https://i.stack.imgur.com/02fXe.png
  [10]: https://i.stack.imgur.com/UzgXim.png
  [11]: https://i.stack.imgur.com/UzgXi.png

title: Serial Module Echoing a `0x00`

Answers: 1

body:
Check your wiring! My guess is the twisted pair (A-B swap).

I've checked your code, it seems right. Please note that /RE and DE were designed that way so you can simply connect them and control with only one pin.

I don't have the exact same hardware, I had MAX485 and Arduino Nano at hand. Nano only has one hardware serial, so I've used the SoftwareSerial library instead.
I've connected them, adjusted your code to my setup, and it worked. Here it is in case it helps to troubleshoot your issue. I've also optimized your version a little bit (but it worked before so the bug is somewhere else).

```
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 4); // RX, TX

const int dir_pin=9;
const int dir_transmit=1;
const int dir_receive=0;
long rate=38400;

void setup() {
    Serial.begin(rate); while (!Serial);
    mySerial.begin(rate); while (!mySerial);
    pinMode(dir_pin,OUTPUT);
}
char s;
void loop() {
    if (Serial.available()) {
        digitalWrite(dir_pin,dir_transmit);
        while(Serial.available())
        {
          s=Serial.read();
          mySerial.write(s);
        }
        mySerial.flush();
        digitalWrite(dir_pin,dir_receive);
    }
    while (mySerial.available()){
        s=mySerial.read();
        Serial.write(s);
    }
}
```


body:
Title says it all really, but to elaborate, in my `preferences.txt` file, I've changed the `editor.tabs.size` variable to `4`, which works wonderfully, and now produces 4-space tabs as do my other IDEs for all the languages I write in.

However, I was told that using the `Tools->AutoFormat` feature would update all lines in my previously-written sketches that had the standard 2-space tabs with the new 4-space tab layout.

This isn't so. Whether I `CTRL-a` to select all and run the Auto Format function, or whether I leave everything de-selected, nothing happens.

Should auto-format "fix" the 'incorrect' indenting to the new style? If so, what am I missing?

I'm currently on Arduino IDE 1.8.5 on Linux Mint, if that makes a difference.

title: Changing preferences.txt to 4-space tabs, how to AutoFormat existing code?

Answers: 1

body:
The auto formatter (astyle) uses a separate configuration to the editor (crazy, I know, but that's the Arduino mentality for you...).

It uses a separate configuration, which is in the `lib` folder of your Arduino program, called `formatter.conf`.

* Copy that file to the same location as `preferences.txt` so it doesn't get overwritten when you upgrade the IDE.
* Edit the file and change `indent=spaces=2` to `indent=spaces=4`

The auto format should now be the same as the editor format.


body:
I spent a great deal of time looking for any posts regarding this and came up empty.

The reason I needed to do this is that I am working on some proprietary code that will be released in an embedded device, but makes use of an LGPL 3.0 licensed library which requires (4.d.0) that I release "corresponding application code in a form ... permit the user to recombine or relink the application with a modified version of the library."

Since the application is on an embedded device, the "corresponding application code" works out to the pre-link .o file which is normally well hidden in the Arduino process.

title: How to produce a .o file from code using Arduino IDE (primarily for LGPL3 compliance)

Answers: 1

body:
To extract the .o produced during compilation in the Arduino IDE, do the following:

 1. Go to the Arduino->Preferences menu item. This will open a preferences window.
 2. In the preferences window find the line that says "Show verbose output during" and make sure that compilation is checked. (you can leave upload on or off as you prefer).
 3. Click "OK" to close the preferences window.
 4. Compile (or compile and upload) your Sketch.

You will get lots of extra output. In the white text, you will either see messages about files being compiled or about "using previously compiled file". In either case, there will be a path provided which will indicate where your Sketch was compiled. On my Mac environment this is `/var/folders/<long random string>/T/arduino_build_<number>/sketch/<sketch_name>.ino.cpp.o`

The line where your sketch is compiled is very long, but the path is also visible in most of the library lines and you can just work down into `.../sketch/...` instead of `.../library/...` instead of scrolling so far to the right on the exactly correct line.

To find the exact line where your sketch is compiled, look for the line directly below a line which simply says "Compiling sketch..."

I know this is rather basic (now that I know how to do it), but it took quite a bit of digging to find it and I figured others might want an answer that's searchable.


body:
Is there a difference between the following two line codes?

>> while (Serial.availableForWrite <= 0) {}

versus

>> Serial.flush()

Thanks!

title: Serial.availableForWrite versus Serial.flush

Answers: 2

body:
https://www.arduino.cc/reference/en/language/functions/communication/serial/availableforwrite/

> `availableForWrite` Get the number of bytes (characters) available for writing in the serial buffer without blocking the write operation

Write operations on Arduino streams wait if they can't write the data to output. You can use the count returned by `availableForWrite` to avoid this blocking.

https://www.arduino.cc/reference/en/language/functions/communication/serial/flush/

> `flush` Waits for the transmission of outgoing serial data to complete.

One use of `flush()` is to wait until the data are sent away before putting the MCU into sleep mode.

body:
The line

```c++
while (Serial.availableForWrite() <= 0) {}
```

waits until the serial output buffer is **not full**. Whereas

```c++
Serial.flush();
```

waits until the serial output buffer is **empty**.


body:
I would like to use a CNY70 with arduino that is not 5v but 3.3v powered. On the web there most tutorials use 5v and 200 + 10k resistors (e.g. [here][1] and [here][2]). So as far as I understand for 3.3v I would have to use lower ones.

Can someone explain how those 200 or 10k were calculated? How could I use CNY70 with 3.3v (if it's possible at all) ?

  [1]: https://cdn2.bigcommerce.com/server3700/64749/products/1507/images/4789/cny70-2__95262.1543951318.1280.1280.jpg?c=2
  [2]: http://2.bp.blogspot.com/-DgKjxBA_j5s/Tk5kDuqXU5I/AAAAAAAAA5Q/U7fgmawtphQ/s1600/CNY70.jpeg

title: CNY70 from 3.3v instead of 5v?

Answers: 1

body:
The CNY70 is just an IR LED and IR Phototransistor.  You can treat the IR LED (emitter) portion of it just like any LED and size the resistor appropriately.

The receiver is just a phototransistor which can operate at anything from about 1V up to 32V with no need to adjust anything.  The resistor used there is merely a pullup resistor.  You can think of the receiver as a button. When enough IR light falls on it it turns "on".

On an Arduino you could even get away without the pullup resistor and use an input in `INPUT_PULLUP` mode.


body:
I am using Arduino UNO with the sensor with the following programm.

    #include <Wire.h>

    // TCS34725 I2C address is 0x29(41)
    #define Addr 0x29

    void setup()
    {
      // Initialise I2C communication as MASTER
      Wire.begin();
      // Initialise Serial Communication, set baud rate = 9600
      Serial.begin(9600);

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Select Wait Time register
      Wire.write(0x83);
      // Set wait time = 2.4 ms
      Wire.write(0xFF);
      // Stop I2C Transmission
      Wire.endTransmission();

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Select Atime register
      Wire.write(0x81);
      // Atime = 700 ms, max count = 65536
      Wire.write(0x00);
      // Stop I2C Transmission on the device
      Wire.endTransmission();

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Select control register
      Wire.write(0x8F);
      // AGAIN = 1x
      Wire.write(0x00);
      // Stop I2C Transmission
      Wire.endTransmission();

      // Start I2C Transmission
      Wire.beginTransmission(Addr);
      // Select enable register
      Wire.write(0x80);
      // Power ON, RGBC enable, wait time disable
      Wire.write(0x03);
      // Stop I2C Transmission
      Wire.endTransmission();
      delay(800);
    }

    void loop()
    {
      unsigned int data[8];

      // Start I2C Transmission on the device
      Wire.beginTransmission(Addr);
      // Select data register
      Wire.write(0x94);
      // Stop I2C Transmission on the device
      Wire.endTransmission();

      // Request 8 byte of data from the device
      Wire.requestFrom(Addr, 8);

      // Read 8 bytes of data
      // cData lsb, cData msb, red lsb, red msb, green lsb, green msb, blue lsb, blue msb
      if (Wire.available() == 8)
      {
        data[0] = Wire.read();
        data[1] = Wire.read();
        data[2] = Wire.read();
        data[3] = Wire.read();
        data[4] = Wire.read();
        data[5] = Wire.read();
        data[6] = Wire.read();
        data[7] = Wire.read();
      }

      // Convert the data
      float cData = (data[1] * 256.0) + data[0];
      float red = (data[3] * 256.0) + data[2];
      float green = (data[5] * 256.0) + data[4];
      float blue = (data[7] * 256.0) + data[6];

      // Calculate the final lux
      float luminance = (-0.32466 * red) + (1.57837 * green) + (-0.73191 * blue);

      // Output data to serial monitor
      Serial.print("Red color Luminance   : ");
      Serial.print(red);
      Serial.println(" lux");
      Serial.print("Green color Luminance : ");
      Serial.print(green);
      Serial.println(" lux");
      Serial.print("Blue color Luminance  : ");
      Serial.print(blue);
      Serial.println(" lux");
      Serial.print("IR Luminance          : ");
      Serial.print(cData);
      Serial.println(" lux");
      Serial.print("Ambient Light Luminance : ");
      Serial.print(luminance);
      Serial.println(" lux");
      delay(500);
    }

Is the output really in lux or is it counts? If it's counts, how can I calculate the illuminance in lux?

title: How to calculate illuminance from the output of a TCS34725 color sensor?

Answers: 2

body:
In the chip's [datasheet][1] on page 8 in the chapter "RGBC Operation" (emphasis by me):

> The RGBC engine contains RGBC gain control (AGAIN) and four
> integrating analog-to-digital converters (ADC)for the RGBC
> photodiodes. The RGBC integration time (ATIME) impacts both the
> resolution and the sensitivityof  the  RGBC  reading.  Integration  of
> all  four  channels  occurs  simultaneously  and  upon  completion  of
> theconversion cycle, the results are transferred to the color data
> registers. **This data is also referred to as channelcount.**

So, if you read the values from the data registers, you get simple count values, which were determined by the ADCs connected to the channels. To get a value in lux, you need to calculate that yourself.

[Adafruit][2] has a library for their breakout board with this chip. In their tutorial it seems, that the library outputs a value in lux. Maybe you can also use this library, or you can check, how they are converting the values from the sensor to lux values.

  [1]: https://cdn-shop.adafruit.com/datasheets/TCS34725.pdf
  [2]: https://learn.adafruit.com/adafruit-color-sensors/overview

body:
The output of this program is a very wild guess at what the illuminance
may be. I would definitely no trust it. It uses the same formula as [the
function `Adafruit_TCS34725::calculateLux()`][calc-lux], from the
[Adafruit TCS34725 driver][driver]. Googling for the numeric
coefficients, I found that the likely source of this formula is the
application note [Calculating Color Temperature and Illuminance using
the TAOS TCS3414CS Digital Color Sensor][dn25]. That application note
seems serious, but it addresses a _different model_ of sensor from the
one you have. It also gives a formula that does not depend on the gain
nor the integration time (maybe that's not adjustable on the TCS3414CS),
which makes absolutely no sense if you have a TCS34725. I found an
[issue filed against the Adafruit driver][issue] that shows the formulas
used in the library are grossly wrong when compared against a
high-quality lux- and color-meter.

I suggest you try implementing the illuminance formula given in the
application note [DN40 – Lux and CCT Calculations using ams Color
Sensors][dn40]. This documents gives a generic formula with specific
coefficient matching different color sensor models, and it does give
coefficients specific for the TCS3472 family. Adafruit did use this
document to implement a color temperature calculation (function
`Adafruit_TCS34725::calculateColorTemperature_dn40()`), but they failed
to use it for the illuminance calculation.

[calc-lux]: https://github.com/adafruit/Adafruit_TCS34725/blob/1.3.0/Adafruit_TCS34725.cpp#L541-L559

[driver]: https://github.com/adafruit/Adafruit_TCS34725
[dn25]: https://ams.com/documents/20143/80162/TCS34xx_AN000517_1-00.pdf/1efe49f7-4f92-ba88-ca7c-5121691daff7
[issue]: https://github.com/adafruit/Adafruit_TCS34725/issues/21
[dn40]: https://ams.com/documents/20143/80162/ColorSensors_AN000166_1-00.pdf/c0b4a4b4-9948-f2a7-f8a1-36a8208bd0a9


body:
How can i convert a String to IPAddress on arduino / esp ?

etc. "192.168.1.2"  -> IPAddress(192, 168, 1, 2)

Tried this

    void setup() {

      Serial.begin(115200);

      IPAddress apip;

      const char *apipch;
      apipch = "192.168.4.1";

    Serial.println(apip.fromString(apipch));

    }

    void loop() {
      // put your main code here, to run repeatedly:
    }

But i just get an output "1"

title: Convert String to IPAddress

Answers: 4

body:
The `IPAddress` class has a member function `bool fromString(const char *address)`.

```c++
const char *apipch = "192.168.4.1";
IPAddress apip;

if (apip.fromString(apipch)) { // try to parse into the IPAddress
 Serial.println(apip); // print the parsed IPAddress
} else {
 Serial.println("UnParsable IP");
}
```

body:
Please check the function into `IPAddress.cpp` file of line 70 :

    bool IPAddress::fromString(const char *address) {
    // TODO: (IPv4) add support for "a", "a.b", "a.b.c" formats
    ....
    }

I think you need to drop the parentheses from the `IPAdress ip()` in your code, The code should be like below :

    Void yourMethod (const char *addr, String ipStr){

    IPAdreess ip;
    bool i;

    i = ip.fromString(ipStr);
     if (i) {
      for (int a = 0; a < 4; a++) {
       addr[a] = ip[a];
              ....
      }
     }
    }

Hope this helps.

body:
You could do this:

    String myip="192.168.1.2"
    IPAddress local_IP;
    bool x= local_IP.fromString(myip);

body:
    IPAddress str2IP(String str) {

        IPAddress ret( getIpBlock(0,str),getIpBlock(1,str),getIpBlock(2,str),getIpBlock(3,str) );
        return ret;

    }

    int getIpBlock(int index, String str) {
        char separator = '.';
        int found = 0;
        int strIndex[] = {0, -1};
        int maxIndex = str.length()-1;

        for(int i=0; i<=maxIndex && found<=index; i++){
          if(str.charAt(i)==separator || i==maxIndex){
              found++;
              strIndex[0] = strIndex[1]+1;
              strIndex[1] = (i == maxIndex) ? i+1 : i;
          }
        }

        return found>index ? str.substring(strIndex[0], strIndex[1]).toInt() : 0;
    }


body:
When using the Ticker library on the ESP8266 you can't use the `delay()` function because Ticker functions are using the underlying timer. The [original Arduino library][1] says that you can use a Ticker as delay, but in the [ESP8266 implementation][2] things work differently. You "attach()" a callback function and specify the period.

**How can I generate a delay that doesn't require the underlying timer?**

(BTW, where is the documentation for the ESP8266 Ticker library? The [repository][2] has no documentation nor comments on the functions.)

  [1]: https://github.com/sstaub/Ticker
  [2]: https://github.com/esp8266/Arduino/tree/master/libraries/Ticker

title: Alternative to delay() when using Ticker in ESP8622

Answers: 1

body:
use the ticker callback to increment a value. this value can be used as millis() substitute. actually the "millis" is made that way.

write a simple function to give you a delay. **this code assumes the callback function is interrupt/event driven like a systick timer in ARMs.**

    uint32_t ticks;

    void callbackFunc()
    {
       ticks++;
    }

    void myDelay(uint32_t del)
    {
       uint32_t tempTime = ticks;
       while (ticks < tempTime + del);
    }


body:
I've read post that it's possible to connect multiple Ultra-Sonic Sensors to one Arduino.
But I have a few questions:

 1. If I use Arduino Uno, what is the maximum number of Ultra Sonic Sensors that I can connect one Arduino UNO?

 2. Is there any option to power Arduino UNO in some kind of low-power mode so I can achieve power autonomy for at least 90 days.(I'm referring to battey life, or solar powered solutions)

 3. Can Arduino UNO work on the low/high temperatures (e.g. -20 / +50 Celsius degrees), and what is the known work temperature range?

 4. How to secure jumpers/cables to work on extreme temperatures (e.g. -20 / +50 Celsius degrees)

    Thanks in advance :D

title: Arduino UNO Low-Power Consumption (Multiple Ultra-Sonic Sensors)

Answers: 1

body:
 1. You did not specified, what kind of ultrasonic sensor you want to use so I assume use of "standard" ultrasonic Arduino modules (like hc-sr04), which need 4 pin (VCC, GND, TRIGGER and ECHO). Since Arduino Uno has got 20 IO pins (6 analog and 14 digital), you can use 10 pins as outputs for TRIG signals and 10 as inputs for ECHO signals and thus connect up to 10 ultrasonic modules to one Arduino Uno.
 2. In general, Arduino Uno is not designed for low-power applications. If you want more specific answer, you should ask more specific question...
 3. Working temperature of Arduino Uno is -40 to 85 °C.
 4. One of the options is using a terminal shield with screw terminals, e.g something like [this][1].

  [1]: https://arduino-shop.eu/arduino-platform/1200-arduino-uno-terminal-shield.html


body:
Lets say i have 1 meter of WS2812 Strip at 60 LEDs per meter. Now i cut the strip up in to 6 single strips but keep the wiring the same and lay them out in parallel. So it would look something like this

1   |  11  |  21 ...

2   |  12  |  22 ...

3   |  13  |  23 ...

...

10   | 20   | 30 ...

Is there any library that would allow me to easily translate this? If i for example want to work with rows, turn a certain row in a certain color, treat certain sub-strips as if they were an individual one, etc etc...
I'm sure i can't be the first one who had this problem?

title: Translating WS2812-LED-Strip-IDs when cutting up a strip to multiple parallel ones

Answers: 1

body:
No, there is no library.

It's just simple maths.

If all your strips are the same, then you just multiply the strip number by the number of LEDs per strip, and add the number of the LED you want in that strip.

So, assuming 10 LEDs per strip:

    lednumber = 10 * strip + led;

You can make a little macro to do it for you if you like:

    #define STRIP2LED(S, L) (((S) * 10) + (L))

Then you can use such things as:

    // Set all LEDs on strip 3 to red
    for (uint8_t i = 0; i< 10; i++) {
        leds[STRIP2LED(3, i)] = CRGB::Red;
    }


body:
I'm making some code for school, and is adding debug code to it. When compiling, I get the error as written in the title. This is the code in question:

    #define DEBUG 1

    #ifdef DEBUG
    #define Serial.println(x) DEBUG_PRINT(x)
    #else
    #define DEBUG_PRINT(x)
    #endif

And the code in my void setup, which has Serial.begin:

    #ifdef DEBUG
    Serial.begin(9600);
    DEBUG_PRINT("Asteroid");
    #endif

What am I getting wrong? I get the feeling it's my define text, but I'm unsure.

Thank you for your time
Gaarden

title: "expected primary-expression before '.' token" in debug code

Answers: 2

body:
You defined the pre-processor macro the wrong way around.
Think it is like an assign statement. You come up with a name and assign something to it.

`#define SHORT_NAME(ARG) some_real_function_that_has_an_awkward_long_name(ARG)`

See the manual of your favourite compiler [GCC][1] for reference.
It is always a good idea to do that when using features you haven't used before. Sometimes it can be enlighting.

  [1]: https://gcc.gnu.org/onlinedocs/cpp/Macros.html

body:
In short: you have your macro backwards.

Macros are not formed as "Take this set of commands and call it X" but "Make this macro X and have it equate to this set of commands".

Where you have:

    #define Serial.println(x) DEBUG_PRINT(x)

it should instead read:

    #define DEBUG_PRINT(x) Serial.println(x)

When you call it, because the macro doesn't contain a semi-colon in it, you need to specify the semi-colon as if you were calling a function:

    DEBUG_PRINT("Aardvark");

You can omit the semi-colon only if you have a semi-colon in your macro:

    #define DEBUG_PRINT(x) Serial.println(x);

and then:

    DEBUG_PRINT("Aardvark")

By doing it that way your "empty" macro now does become truly empty when used.  Without the semi-colon in the macro you would have to use:

    DEBUG_PRINT("Aardvark");

Which for the empty variant would end up as:

    ;

Not always desirable, and can cause some problems.

So by adding the semi-colon into the macro you can omit it from the usage of the macro, and your empty variant now becomes: