text:
SD card reader and lcd display
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?

This is talked about in multiple Arduino threads.  This thread, this thread & this thread 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() 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 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 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() 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.


text:
Does MFRC522 supports native SPI of Arduino Due?
Does MFRC522 library support native SPI interface of Arduino Due?
By native SPI I mean this one:

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?

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.

I tested it, it actually works.

You have a typo, should be MFRC522::UNUSED_PIN.

@kelin Indeed it should. Well spotted.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
What does (byte*)variable_name mean in C++?
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

external EEPROM?

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.

Thanks Mr.Majenko Can you please refer me some material or website for me to learn more about this topic, It would be helpful . Thanks for the reply

https://www.tutorialspoint.com/cprogramming/c_type_casting.htm

Thanks Mr.Majenko

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Arduino RGB IR Controller -> led always close to white
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

Your code is for a single RGB LED or a simple dump RGB LED strip.  The linked code is for a NeoPixel (WS2812B) strip. Which are you using?

The controller is for an a-rgb strip and I want to control also a single rgb led on a fan, so i have added the function void fanON() which has the above code that works separatly

Does the IR code get correctly received? Honestly I don't want to analyse over 700 lines of code. You should deactivate parts of your code, until you found the problematic code

in the setup i call the function rgb(0, 0, 0); and it supposed to turn off the led when i start the arduino without any input, but the led is showing white. And yes the IR get correctly received. When i press on my ir remote the strip changes color but the led on the fan no->still white


text:
Soft wdt reset error on NodeMCU (ESP8266)
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 AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_wiring.c line 180
0x401003b9: __digitalWrite at 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 Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 172
0x402027a4: sim808_send_byte(unsigned char) at 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 Documents\Arduino\libraries\DFRobot_SIM808-master/sim808.cpp line 191
0x402025dc: DFRobot_SIM808::init() at 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 AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.5.0\cores\esp8266/core_esp8266_main.cpp line 122
0x40100e8d: cont_wrapper at 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() {

}

The culpret is the SIM808 library. It's not written to work well with the ESP8266.
The problem lies in this function:
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.

Thank you very much. It worked. Really appreciated. But I am facing I more issue after 10-12 "Sim808 init error" I receive success why is it so why it does not get initialised in first attempt.

Probably waiting to connect to the network. That can take up to a minute sometimes.

Thanks for the reply. Nothing to bother. There was some contact issue between Gnd Pins of both modules.


text:
LCD displays bad character while counting rotation
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:

When I start my drill, LCD changes to this:

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.

Msquare thanks for replay i found out the problem that as you have seen i put the screen on galvanized metal whenever drill starts the screen gets noise i don't know why there is no touching part of lcd and galvanized material. thanks


text:
Everything is ready for project . I have one doubt! I am using transmitter + Arduino *Uno*..and receiver + arduino *nano* will it work?
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!)

only you know what the project is, so only you can determine if it will work

Uno and Nano have the same MCU and the same Arduino pin mapping. Nano is only a small Uno.

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.

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.


text:
Nodemcu Server with multiple sensors
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

#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

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

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

Using a web server for communication between two NodeMCUs is insanely over-engineering it. Far simpler to use a basic TCP connection and treat it much like a serial communication channel.

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 without HTTP protocol overhead.

kindly can you tell me what should be my 'serversend' command?

now all values are showing as zero :-(

sorry, I edited the Answer

@MuhammadJahanzaib, does it work now?

Yes it worked any how, now I have different situation, I want to connect 2 clients to the same server, one client is working perfectly but confused how to connect server with other client


text:
Playing Audio from SD - Get VU, or audio waveform
I am using the library SimpleSDAudio 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, 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);

}

My expected output of sampling the output from A0:

what does this mean? some unexpected readings

I would expect to see something similar to a wave form. Like I would see in Audacity. As the audio plays, I would see different values based upon the level of the output. Sorry if it's confusing.

it is not confusing ... it is just pointless to say that something is unexpected, without an explanation, because nobody else knows what you are expecting

@jsotola I have added an "expected" image. Thanks.

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.

The delay was a leftover from me troubleshooting the code. When I leave the delay out, I get similar results. I have code to take the sample, and produce a VU, I didn't include as I didn't think I was getting something that I could use from the raw audio pin.

Still the raw audio pin will only have a PWM signal. You should try the low pass filter and sample that filtered signal.

If you didn't think, that you would get something useful from the audio pin, why did you sample it?

Sorry I was replying from mobile and was trying to be brief. I have edited my question to include a graph more like I was expecting. If I received a waveform from the audio pin like pictured above, I would have then ran the code through my "VU" function. This "expected" graph was produced with a condenser microphone connected with the same code, sampling at 20Hz. This condenser circuit has a op-amp that drives the output. Perhaps the output of the PWM audio signal isn't enough to drive the ADC and produce the waveform I thought I would see? Thanks @chrisl for your help!

You didn't show a VU function, so I cannot know, if this function would help. So you get a more expected output, if you take the sound with a microphone and sample that? As I tried to explain, there is already a (mechanical) low pass filter incorporated, since the speakers membrane cannot move fast enough to follow the PWM signal. Instead it will take the mean. That is the whole point in doing sound via PWM. If you don't want to use a mecrophone to sample the real sound, but want to use the direct electrical signal, you need an electrical low pass filter, to filter out the PWM frequency

And surely, you mecrophone samples are closer to the real world, but also not a good representation of the real soundwave


text:
Impossible to connect ESP32 with Mosquitto on Raspberry using certificates
I installed Mosquitto broker 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;
    }
  }
}

See https://github.com/espressif/arduino-esp32/issues/2875 and https://github.com/TwilioDevEd/sync-for-iot-examples/blob/master/Espressif_ESP32/Quickstart/certificates.hpp. Does it work when adding R in front of the string constant for the ca_cert?

Hi Maximilian,
I tried as recommended but I get the same error even with the R     -
MQTT connecting ...[E][ssl_client.cpp:33] handle_error(): X509 - Certificate verification failed, e.g. CRL, CA or signature check failed
[E][ssl_client.cpp:35] handle_error(): MbedTLS message code: -9984
[E][WiFiClientSecure.cpp:132] connect(): start_ssl_client: -9984     -
do you have any suggestions for me?

Do you have a full mbedtls log for the whole session? You might need to set debug level to the most verbose in the Arduin IDE then.

I found the solution, the problem was related to the generation of certificates.
The OU must be different for each file generated. SUBJECT_CA="/C=SE/ST=Stockholm/L=Stockholm/O=himinds/OU=CA/CN=192.168.0.11"
SUBJECT_SERVER="/C=SE/ST=Stockholm/L=Stockholm/O=himinds/OU=Server/CN=192.168.0.11"
SUBJECT_CLIENT="/C=SE/ST=Stockholm/L=Stockholm/O=himinds/OU=Client/CN=192.168.0.11"

Good morning, first I would like to say that I am Brazilian, so I'm using the translator, if something goes wrong please do not care. Come on, I have the same problem, I believe it is problem in the certificate rsrs, could you tell me please, how did you solve your problem? thanks.

@Michele You can post that as an answer

Thanks for your help, but can you please tell me which folder I create this script in? I still have the same problem.
thanks

Hi, it is not important which script you create, however
from home of raspberry,
mkdir test,
cd test,
sudo nano test.sh and paste the script and save.
chmod +x test.sh
then run the script with ./test.sh

@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


text:
Arduino random LED on
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);
  }
}

LEDs?  Or relays?  You seem to use both terms.  They’re not the same thing.

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.

Does that help?


text:
How to transmit data from a sensor using SIM800L?
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.

which part of the project are you able to do now?

I read about basic interfacing like send and read SMS and calling methods.I am able to read the data from sensor but I am unable to find a code/ function to upload it.

try this... https://exploreembedded.com/wiki/GSM_SIM800L_Sheild_with_Arduino


text:
How i convert to Arduino Mega?
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

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

hello,
you said that
"..which on the Uno is digital 3, but on the Mega is digital 18."
how do you know on the Mega is Digital Pin 18?
and i still don't understand about use pins A8 through A15 and read the word as PINK

@IbnumRichaflor: Re “how do you know [...]”: Google “Arduino Uno pinout” and “Arduino Mega pinout”. Re “use pins A8 through A15 and read the word as PINK”: Pins A8 – A15 (Arduino labeling) are PK0 – PK7 (manufacturer's labeling), collectively known as “port K”.


text:
when submit data to ESP8266, ets Jan 8 2013,rst cause:4, boot mode:(1,6) wdt occurs
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:

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.

you have io 0 LOW (the 1 in mode should be 3 for normal boot). on reset esp8266 starts in flashing mode

wdt rest is watchdog reset. it happens when the code doesn't get out of the loop 10 or more seconds and yield() or delay() is not called to let the SDK handle the WiFi

thank you for answering.


text:
Communication between three NodeMCUs such that one in in AP mode, second one in AP+STA mode and the third NodeMCU in STA mode
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.

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.

does it mean that the IP should be same for first and second nodemcu  is same?Also, the IP should be same for second and third nodemcu? Do I need two different IPs for the second nodemcu?

you have no clue about IP addresses? the STA must have the IP in the range of the AP it connects to. no matter if the AP is a box or a esp8266


text:
Can't Compile .ino using ArduinoJson Library
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.

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():
*pin = doc["Pin"];
*pinmode = doc['Mode"];
*timeInMilliseconds = doc["TimeInMilliseconds"];

It works. Thank you for the explanation!!! You really saved my day! :)


text:
Serial Module Echoing a `0x00`
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, one for each arduino,
AWG24 Cable, shorter than 7 in each.

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

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

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.

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.

You do have the grounds of the Arduinos connected together don't you?

All are plugged from a same USB splitter, but even connecting them in the breadboard, the effect persists.

Ok, looking in more detail - what code is at the other end? You have two megas, but only show one code.  Second - your terminal program is set to a different baud rate than your program.

Same code for both. The effect is the same for all speeds.

With that code for both, why do you expect anything to echo back? The 00 is the error, not the no response.

Yes, the 0x00 is an error. No echo or response should be received. If I disconnect the AB bus, the echo is still there... If I remove the RE'DE signal, the echo dissapears (but no reception, since it is disabled).

Does your fritzing diagram precisely describe reality, or is your right-hand chip actually wired differently to how you are showing it?

It is almost exactly as the diagram. In a same breadboard, wiring the cables as named into the proper arduino. The named and the AB cables are about 7 in length.

So, you actually have your right-hand chip wired wrong? Inspect the wires going between the Arduino and the right hand chip...

Oh right, it is a drawing error (unfortunately?)... Already corrected.

Looks like you have wired it for the MAX3291 instead of the MAX3292.  Remove the PEE wire , since it's not PEE, it's PSET.  Connect a resistor and capacitor to VCC. Read page 11 of the datasheet.

I had them previously and i have just added them now, but unfortunately still the same echo, one per character in a string, after sending strings or sending individual characters...

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

Well, the code and the configuration was ok but... a resistor divider at the RO output not shown in the diagram was causing the problem. After removing it, everything worked fine. Thanks for the effort anycase...


text:
Changing preferences.txt to 4-space tabs, how to AutoFormat existing code?
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.

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.

Good grief. I'll test it here shortly @Majenko. Thanks

Wow. What a meticulously ridiculous way to do things. Answer accepted as it worked. I'll have to make notes for this and update my automation routines, as I can see this going downhill in the future on new setups.

The auto formatter (astyle) uses a separate configuration to the editor - with what possible justification?

@NickGammon I wish I knew. When I implemented astyle in UECIDE it just read the same formatting settings (plus extras that don't apply) for the editor...


text:
How to produce a .o file from code using Arduino IDE (primarily for LGPL3 compliance)
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.

Owen DeLong, as in the Internet Engineering arena? Just curious... it's been a long time.

Just FYI, the Arduino core lib is also LGPL. https://github.com/arduino/ArduinoCore-avr/blob/master/cores/arduino/Arduino.h

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

Go to the Arduino->Preferences menu item. This will open a preferences window.
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).
Click "OK" to close the preferences window.
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.

Note that the Arduino IDE defaults to compile with link-time optimization enabled, which will make it harder for another user to do the final link, as “bytecode files generated in one version of GCC do not work with an older or newer version of GCC.” I suggest you compile with -flto -ffat-lto-objects in order to alleviate this problem.


text:
Serial.availableForWrite versus Serial.flush
Is there a difference between the following two line codes?

while (Serial.availableForWrite <= 0) {}

versus

Serial.flush()

Thanks!

The line
while (Serial.availableForWrite() <= 0) {}

waits until the serial output buffer is not full. Whereas
Serial.flush();

waits until the serial output buffer is empty.

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.


text:
CNY70 from 3.3v instead of 5v?
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 and here). 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) ?

That 200R is current limiting resistor. For 5V power supply and 1.3V forward voltage drop on LED that means about 19mA through resistor: If = (5V-1.3V)/200R = 18.5 mA. With 3.3V power supply you'll get about 10mA with the same resistor.

and what about 10k on the transistor ?

That's just a pull-up resistor. It's basically "pick one between 1K and 100K". So even internall pull up resistor on the input should be sufficient. It depends on wire length, its capacitance and so on. Longer lines means stronger pull ups. Well, technically it should match line impedance, so there will be no signal reflections, but it's valid on much higher frequencies.

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.

I'm total noob, but with 200 resistor, the LED might not get enough current to power up from 3.3 so I should lower it? Or not?

The lower the resistor the brighter the LED will be and the more sensitive the sensor. The higher the resistor the dimmer the LED will be and the less sensitive the sensor. Most people erroneously size the resistor to the maximum current of the LED thinking that is good - however brightness is non-linear, and halving the current doesn't halve the brightness.  You will get about 2/3 the current, but that's still more than enough to "power up" the LED.

Thanks! Must be something else wrong then, I'll double check my wiring


text:
How to calculate illuminance from the output of a TCS34725 color sensor?
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?

The corresponding Adafruit tutorial states it is in Lux, but you are not using their library. Have you read the datasheet?

Are you using a laser or spectral lamp to shine monochromatic light (i.e. light with a well defined wavelength) onto your sensor? If not, what do you mean by “calculate wavelength”?

Hello Chirsl I am not going to use the sensor on arduino for my final application.This if for the initial test weather the sensor is working or not.But i need to know the calculation of lux or intensity from counts.

Hi Edger,Need to calculate lux or intensity form the counts

@user59381: Then talking about wavelength is a nonsense. And it's “illuminance”, not “intensity”. And it's “Edgar”, not “Edger”. I edited your question to fix all that.

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(), from the
Adafruit TCS34725 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. 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 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. 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.

float cData = (data[1] * 256.0) + data[0];I am having confussion on the above line. Is the line is for storing the data's in one variable or for coverting the data into RGB value.

float cData = (data[1] * 256.0) + data[0];I am having confussion on the above line. Is the line is for storing the data's in one variable or for coverting the data into RGB value

@user59381: It's for combining two bytes (data[0] and data[1]) into a single number.

OK.Thank you so much

In the chip's datasheet 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 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.

my end application is different.I need to know the calculation of lux or intensity of light from the counts

float cData = (data[1] * 256.0) + data[0];I am having confussion  on the above line. Is the line is for storing the data's in one variable or for coverting the data into RGB value.


text:
Convert String to IPAddress
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"

There are two possibilities in the link, which one did you use? If it didnt work, you did something wrong, but I can't guess what you did do. Post your code, perferably the shortest possible bit - it does not have to be functional, just the the bit where you get your string (is it a String or a char[] ?) how you implemneted the convert code, and where you call the ip() function.

please do not say didn't work ... instead say this is what happened .... .... "didn't work" is almost meanigless

ip.fromString(s.c_str());

@Msquare  have added an example tried both codes but they gave me a result of 1

@jsotola your right sorry, i added code and my result

@Juraj this just gave me a result of 1

because you print the return value of fromString and not the IP address. Serial.println(apip);

The IPAddress class has a member function bool fromString(const char *address).
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");
}

You could do this:
String myip="192.168.1.2"
IPAddress local_IP;
bool x= local_IP.fromString(myip);

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

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.


text:
Alternative to delay() when using Ticker in ESP8622
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 says that you can use a Ticker as delay, but in the ESP8266 implementation 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 has no documentation nor comments on the functions.)

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

Yes. That seems to work, but I do need to put ESP.wdtFeed(); inside the while loop in the delay function. Otherwise the watchdog timer is triggered.


text:
Arduino UNO Low-Power Consumption (Multiple Ultra-Sonic Sensors)
I've read post that it's possible to connect multiple Ultra-Sonic Sensors to one Arduino.
But I have a few questions:

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

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)

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

How to secure jumpers/cables to work on extreme temperatures (e.g. -20 / +50 Celsius degrees)
Thanks in advance :D

A "bare minimum" standalone Arduino will use less power. useful link

Don't use jumper cables. Use cables rates for the specified temperature range and solder them to the board

@newbie thanks, man. This link is very helpful

@chrisl Roger that. For the testing purpose, I wanted to use jumpers. :D

@rmir you're welcome. most electronic components have wide range of temperature tolerance but the real problem is humidity in outdoor environment.

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.
In general, Arduino Uno is not designed for low-power applications. If you want more specific answer, you should ask more specific question...
Working temperature of Arduino Uno is -40 to 85 °C.
One of the options is using a terminal shield with screw terminals, e.g something like this.

Sorry for not being too specific, you know, when you are working on something, you think that everyone has the same process, same tools... And I'm a newbie to Arduino... :D

Yeah, you are right, I was referring to HC-SR04.
Again I wasn't too specific. Didn't want you to bother with too many details, but I need a measurement device that will measure distance every 15 seconds, my plan is to turn on/off Arduino every 15 seconds to measure the distance. Since I need this device to be used in the woods, I need a battery-powered device.
Thanks.
Awesome.

Look at sleep_mode() and set_sleep_mode(mode) function. You will also need to switch off the power supply for the ultrasonic sensors. Then you'll need to measure power consumption of the whole set to be able to decide what kind of battery you should use...


text:
Translating WS2812-LED-Strip-IDs when cutting up a strip to multiple parallel ones
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?

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


text:
"expected primary-expression before '.' token" in debug code
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

Macros cannot contain a .. Thus you cannot define a macro Serial.println(x). You probably wanted to define it the other way around anyway.
#define DEBUG_PRINT(x) Serial.println(x)

I switched them around, per Kwasmich's comment. Now the error message is "expected ';' before 'Serial'"

Somewhere in your code (not shown above) you have a DEBUG_PRINT statement where in the line before that you have skipped the ;

Didn't know it would give me an error message on that line if a line further down had a problem. Thank you!

@Kwasmich You posted an answer as a comment. Please make a proper answer. Then you will get rep for it, and Stack Exchange will consider the question answered. Win win!

@NickGammon, I see this as typographic error (and I will downvote an answer to this question). I voted to close

@Juraj Typographical errors are errors too.  Besides, this isn't a typographical error. A typographical error would be Serial.print1n(). This is a lack of understanding of how macros work and should be formed on the part of the OP and deserves aiding the OP in improving their understanding.

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:

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 for reference.
It is always a good idea to do that when using features you haven't used before. Sometimes it can be enlighting.


text:
I2C communication problem with two slaves (atlas scientific) and one Nano (official)
I'm working on a project using an arduino Nano (official) and two peripherals from Atlas Scientific (pH and DO) communicating via i2c. Everthing works fine when i use a usb alimentation connected to the PC or to a 5V adaptater (typically a phone charger).
I want to use a 12V battery and a 12V DC 1.5A adaptater to power up my system, the problem is that it works fine for a moment (30 to 40 seconds) and then the pH start having problem with the communication and the led becomes red and the TX/RX leds from the arduino (which are connected to nothing start going crazy. I use 4.7k pull up resistors and an L7805ACV voltage regulator to go from 12 to 5V.
Attach, a part of the system schematics.
If you have any clue, starting to be new idealess
EDIT : Here is the part of the program concerning the i2c communication :
#include "Wire.h"

/*********************************************************************************************************
 *                                               Address
 *********************************************************************************************************
 */
int pH_address = 99;
int DO_address = 97;

/*********************************************************************************************************
 *                                         i2C CONFIGURATION
 *********************************************************************************************************
 */

byte received_from_computer = 0;
char sensor_data[20];
byte in_char_sensor = 0;
byte j = 0;
byte code = 0;
int time_ = 850;

void setup()
{
  Wire.begin();
}
void loop()
{
  pH = Get_i2C(pH_address);
  delay(200);
  DO = Get_i2C(DO_address);
  delay(200);
}

/**********************************************************************************************************
 *                                                  i2C
 * ********************************************************************************************************
 */

float Get_i2C(int address)
{
  char computerdata = 'R';
  Wire.beginTransmission(address);
  Wire.write(computerdata);
  Wire.endTransmission();

  delay(time_);

  Wire.requestFrom(address, 16, 1);
  code = Wire.read();
  while (Wire.available())
  {
    in_char_sensor = Wire.read();
    sensor_data[j] = in_char_sensor;
    j += 1;
    if (in_char_sensor == 0)
    {
      j = 0;
      break;
    }
  }
  return atof(sensor_data);
}

Two ideas.
1: Count your grounds. If you count more than 1 you have a problem. Your system should have a single ground, so ANY connection on every component labeled GND should be connected to ground.
The reason multiple grounds are a problem is that your signals (other than differential signals) are measured relative to ground, so if two components have different ideas of what "ground" is they start to disagree about what constitutes a 1 and a 0.
2: Scope your power supply. Check that your 5V supply is still providing 5V. It's possible (although unlikely) that the L7805ACV can't supply enough current and your system is browning out. If possible have a look with an oscilloscope to check for noise on the 5V supply.
Your boards should already have decoupling capacators, but adding another won't hurt, so also try adding a 0.1uf cap between 5V and GND to eliminate any noise.

Thank you for your answer. For the first idea : every ground are connected together. For the second one, i thought about that too, so i now power my nano with the 12V for the adaptater and the two i2C are power supply with the 5V of the nano. The rest CO2 + HC05 with the 5V of the L7805ACV.

And still get the problem ... i can try adding some decoupling capacitor. Something really weird is that the TX/RX leds start to blink but nothing is connected to it, when the problem is happening.

@HugoVernier-Lambert That's really weird. All I can suggest is removing parts until you see the problem resolve. That may at least give you an idea what part may be the issue. Failing that, probe every signal. You could also provide us with a copy of your code. It doesn't sound probable, but there could be something there.

I edited the question with the i2c program.

I tried to add some decoupling capacitor, or to change from the 5V of the arduino to the 3.3V which has more decoupling capacitor already than the 5V but nothing, still the same problem.

The problem comes from the pH module (red one), but i commented the DO i2C peripheral and the pH module was working fine on any power supply. And same if i comment the pH i2C peripheral, the DO works fine. The problem is when i use it "simultanously", actually one after the other, but both wired and used by the program.

Discussing the problem with another electronic engineer, he told me that the L7805ACV was over heating making some voltage drop which were rebooting over and over the arduino. And because the TX/RX leds blink one time when rebooted at start, we see it blinking faster and faster. I'll try to get some heat sink in order to cool that voltage regulator.


text:
Number of digits setting for serial printing the sensor output value
I am getting fan motor rpm as 3200. But if I get the data as 50, I should get the value like 0050. How can I do this?
I can do it like checking the value for single digit(0-9), double digit (10-99), and triple digit (100-999) and four digit(1000-9999). I need to fix digit size and send it through serial. Is there any other way for this?

You can use the C function sprintf:
char text[5];
sprintf(text, "%04d", number);
Serial.println(text);

The leading 0 in 04d will add zero's for the length (4) is met, so 1 will become 0001, 10 will become 0010, 100 will become 0100 and 1000 will stay 1000.

this is what i expected... thank you very much for your comment..

Why char text[5]; ? Why 5 is entered?? Why not 4 or 3?

Three if statements look a bit simplistic, but are much better in code size than sprintf, if that's the only usage for sprintf.
 if (number < 1000) Serial.write('0');
 if (number < 100) Serial.write('0');
 if (number < 10) Serial.write('0');
 Serial.println(number);

Saves about 1.5kB Flash, compiled with Arduino 1.8.9 for an Uno

if      (number <   10) { Serial.print("000"); }
else if (number <  100) { Serial.print("00"); }
else if (number < 1000) { Serial.print('0'); }
This saves another 200 bytes.


text:
In Nrf24lO1 pa+Lna,is there any indication led light?
How do I know that my **Nrf24lO1 pa+Lna **  is working or not? For that any separate led is there for on ?

There is no led.
But you can use the isChipConnected function in the RF24 library