text:
Is it possible to use the same power source for the arduino and a high current
I've need to control some leds which draw 300mA with an arduino (actually an atmega) and after some searching I think the following is the circuit I need, but I'm not really sure if the power source for the LEDs can be the same as for the arduino.
R1 = 1k

Yes, it can, as long as it can provide the needed current. And be sure to not let the LED current through the Arduino. Connect the led circuit directly to your power supply

If the power supply has sufficient power and voltage stability, you can use it to power the LED and Arduino. However, the circuit is not entirely correct on the LED side, a current limiting resistor should be used in series with the LED. I would also recommend using a more powerful bipolar transistor or field effect transistor.

Thank you, yes, the leds have a resistor connected I just didn't draw it, didn't realize it could be confusing for someone seeing it.
Thanks for the tip on the transtor, what would be the problem with this one?

This transistor will dissipate about 0.2 W of power and may be slightly warm.

can you use a npn transistor high side like that from the MCU? IT would seem to be a voltage follower, 0.6v below Vcc. Much better to switch on the low side...


text:
What is the difference between serial begin() and wire.setClock() for I2C communication?
I am a new Arduino IDE user and have a simple question below
For I2C transmission speed setting, there are serial begin() and wire.setClock(). Some sample codes just use Serial.begin() without Wire.seClock(), some use both as shown below. What is the real differences between them? When to use just serial and when to use both of them? Thanks.
void setup() {
  Serial.begin(9600);          // start serial communication at 9600bps

  Wire.begin();                // join i2c bus (address optional for master)

  Wire.setClock(400000); //Increase  I2C clock rate to 400 kHz
}

Serial has nothing to do with Wire/I2C communication. The examples only have this, because mostly they use Serial out- and input for interaction in the example codes (like showing the data of an I2C sensor on the Serial Monitor).
If you don't want to use the Serial Montior/Serial communication, then you can leave all the calls to Serial out.

Serial.begin starts the communication on USB or RX/TX pins. It has nothing to do with Wire library and I2C communication.
I2C clock speed determines the speed of communication on the I2C bus. Wire.begin() among other settings, sets the I2C clock speed to some default value.
Wire.setClock() allows to set a different clock speed. This should be supported by all devices on the I2C bus or clock speed can be changed before communicating with a specific device on the bus.
Wire.setClock should be called after Wire.begin because Wire.begin sets the clock speed to some default.

source: Stack Exchange

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

sort: votes


text:
Is there a way to go to the start of the void loop() function kind of like a "continue" keyword in c in loops?

I am new to Arduino programming and am trying to make an obstacle avoiding car with an ultrasonic sensor and a differential driver model. While learning how to code it, I learned that you can exit the void loop() function with an exit(0) to terminate the program analogous to break keyword in C language.
Is there anything similar that I can use to mimic the "continue" keyword, say if I don't want to run the code after a particular line in the void loop() function.

If you return from the loop() function, you immediately end the execution of the current iteration. The loop() function will then start again, as its always looping (therefor the naming). loop() is just a function like any other. It just gets called over and over in an infinite loop.

Using "return;" as if it were a normal function seemed to work. I thought at first that return would do the same thing as exit(0). Thank you so much @chrisl.

I think anexit(0) will just lead into an infinite loop,which is doing nothing. On a microcontroller there must run a code at anytime. It cannot give the control back to an OS.

yes, I have heard using exit(0) is a bad Arduino programming practice.

In the loop() function, return will perform that function. By exiting the function, the for() loop in main() (which we don't see) will iterate again, calling loop() again.
Another way to accomplish the same thing is to write everything in your setup() function, including whatever kind of loop construct you want, and use break; and continue; statements as you're used to:
void setup(){
   // pinMode() & digitalWrite() calls
   // Initialize the Serial port if you need to
   // Any other one-time setup
   //
   // Everything happens here:
   for( .... ){
      // loop contents here
      if( whatever ){
         continue;
      }
      else if( something_else ){
         break;
      }
   }
}

// This just stalls forever when setup() ends:
void loop(){
   ;
}

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


text:
ESP32S v1.1 NodeMcu vs ESP32 DevKitV1
I have two different ESP32 development boards labelled "ESP32S v1.1 NODEMCU" (A) and "ESP32 DEVKITV1" (B).  From what I can tell they have the same major components, but their pins and general layout are quite different. I assume they are both knock-offs.

When uploading from the Arduino IDE, both read the same revision number and features:
Chip is ESP32-D0WDQ6 (revision 1)
Features: WiFi, BT, Dual Core, 240MHz, VRef calibration in efuse, Coding Scheme None
Crystal is 40MHz

From what I can tell NodeMcu has something to do with the firmware for the ESP8266 (wiki)?  Also, it seems my ESP32S NodeMcu board doesn't have the standard pin layout for ESP32 boards.
What exactly is this NodeMcu board and what are the differences between the two?

there's lots of wroom modules, all vary slightly in pinout, serial chip, component selection, etc; but they all do the same basic thing as far as arduino is concerned. I try to find ones with 36+ pins and pin labels on both sides of the board, and that are cheap.

The DevKit is a development board by ESP32 manufacturer Espressif to demonstrate ESP32 usage and to support prototyping.
The NodeMcu is a board by NodeMcu intended for the NodeMcu Lua language firmware.
There is no standard pinout. The labels on the DevKit are io pin numbers of the MCU.
You can use both development boards with the ESP32 "Arduino boards support package".

I wrote to Espressif asking about the ESP32 DEVKITV1 and they said they don't manufacture it. It appears to be made by this company: https://www.doit.am/#/mozu


text:
Init a calss inside a class
I'm building a monitoring IP class, IPmonitoring, that using an SPIFFS class that I wrote, flashLOG. Inside IPmonitoring I have 2 instances of flashLOG (code below).
My sketch have several instances of IPmonitoring for several servicesI wish to monitor. I Wish that connectionLOG and disconnectionLOG have unique and automated names.
For example if I'm monitoring a service called MQTT its connect and disconnect log will be MQTT_discolog.txt and MQTT_conlog.txt. In my code below, filename1 and  filename2 are consts.
class IPmonitoring
{
private:
        char *_IP;
        char *_nick;

        flashLOG connectionLOG;
        flashLOG disconnectionLOG;

public:
        IPmonitoring(char *IP, char *nick, char *filename1 = "/conlog.txt", char *filename2 = "/disconlog.txt")
            : connectionLOG(filename1), disconnectionLOG(filename2)
        {
                _IP = IP;
                _nick = nick;
        }

EDIT1 - example how to use class
my goal is that filename1 for example will be MQTTbroker_connlog.txt meaning a combination of _nick and a suffix,
IPmonitoring MQTT_service("192.168.3.200","MQTTbroker");

void setup()
{
MQTT_service.start();
}

void loop()
{
MQTT_service.loop();
}

Do you mean the variable names in the source code? Any reason why you want this and not use a member in the class flashLOG, initialized by its constructor, to retain its name?

@Sacha yes,  filename1 + filename2. I don't understand what is your suggestion, since this is the way flashLOG inits ( with a filename )

Forget about my first comment. In your example, how would the code creating the IPmonitoring instance know the name of the service it will monitor?

@Sacha - In a case I have more than one instance, using filename1 and filename2 in shown manner will over run each other - it is a not valid way to do so, unless I write each ones name in specific

you have the filenames as parameters. so construct it with different filenames

Please show us some example how you like to use the class IPmonitoring.

@thebusybee see edit 1

@Juraj see edit1

If you let the caller provide the complete filenames, the task would be quite simpler. I see this as a reasonable decision. -- Oh, and since you are programming in C++, the usage of std::string instead of C strings (char[]) can make things easier.

Judging from your example usage, you want the filenames to be built by
the IPmonitoring constructor. However, since that class cannot know in
advance how much space is needed for the file names, you are left with
two choices:

Let those file names be data members: arrays of char of some fixed
size. This will impose a limit on the maximum file name length.

Allocate the arrays dynamically at construction time.

Here is a tentative implementation of the second approach:
class IPmonitoring
{
private:
    const char *_IP;
    const char *_nick;
    const char *connectionLOG_filename;
    const char *disconnectionLOG_filename;
    flashLOG connectionLOG;
    flashLOG disconnectionLOG;

    // Return a dynamically allocated string with the concatenation
    // of `a' and `b'.
    const char *str_concat(const char *a, const char *b)
    {
        char *s = new char[strlen(a) + strlen(b) + 1];
        strcpy(s, a);
        strcat(s, b);
        return s;
    }

public:
    IPmonitoring(const char *IP, const char *nick)
        : _IP(IP), _nick(nick),
        connectionLOG_filename(str_concat(nick, "_connlog.txt")),
        disconnectionLOG_filename(str_concat(nick, "_disconnlog.txt")),
        connectionLOG(connectionLOG_filename),
        disconnectionLOG(disconnectionLOG_filename)
    {}

    ~IPmonitoring(){
        delete[] connectionLOG_filename;
        delete[] disconnectionLOG_filename;
    }
};

Note the destructor, which is needed to avoid memory leaks, unless all
the instances of the class are statically allocated (which would be good
to avoid memory fragmentation). You may want to implement a copy
constructor and a copy assignment operator, as per the rule of
three.

Can you please explain : _IP(IP), _nick(nick) I never used such syntax

@Guy.D: It means “Initialize _IP with the value of IP”. It is functionally equivalent to the assignment you used in the constructor, but it is syntactically an initialization rather than an assignment. It is here intended to make clear that the constructor does nothing more than initialize the data members.

great! Didn’t know it

Can you please explain/ give an example for static allocate of class ?

@Guy.D: See your own usage example: the object is a global variable, and global variables are statically allocated. In this case the constructor is called at program startup, before main(), and the destructor is normally never called.

OK, just wanted to be sure your mean.

Would it make sense to use C++ strings (std::string) that can be dynamically concatenated? -- 2. Beginning with C++14 the rule to obey is the Rule of Five.

You have three options for the file names and generally.

constant string a.k.a. string literal
string buffer global or on stack with scope valid while the string is used
dynamically allocated string on heap

with 2) and 3) you can then build a string with C str or sprintf functions
option 3) is alright on MCU if you create these file names only at startup, not if you create them repeatedly as the sketch is running
If you choose option 3) you can build the strings in the constructor of IPmonitoring class, but you can't build the string in the member initialization part of the constructor. You have to add setters to flashLOG class and after building the strings for file names set them to the flashLOG instance with the setters.

@Guy.D I enhanced the answer


text:
LED does not blink - Arduino UNO+WiFi R3 ATmega328P+ESP8266 board
As I am learning the Arduino coding, I want to see if my program can turn on the LED light. I have tried all the things, but the code does not start the LED light I have installed on the board.
The code compiles successfully and upload on the board, but nothings happens after that. See the output logs as below:
See all the configuration of board as below:
The board I have:
UNO+WiFi R3 ATmega328P+ESP8266 CH340G Board compatible with Arduino
https://robocraze.com/uno-wifi-r3-atmega328p-esp8266-ch340g-board-compatible-with-arduino
Board switch settings:
5,6,7 => ON (to upload the code from Arduino IDE)
Yellow LED installed:
13 => Positive, GND => Negative
Board setup:

Arduino IDE Setup:

Program:
void setup()
{
  pinMode(13, OUTPUT);
}

void loop()
{
  digitalWrite(13, HIGH);
  delay(2000);
  digitalWrite(13, LOW);
  delay(2000);
}

Output logs after uploading the code:
esptool.py v2.8
Serial port COM8
Connecting....
Chip is ESP8266EX
Features: WiFi
Crystal is 26MHz
MAC: ec:fa:bc:3e:2e:6f
Uploading stub...
Running stub...
Stub running...
Configuring flash size...
Auto-detected Flash size: 4MB
Flash params set to 0x0340
Compressed 261472 bytes to 193134...
Wrote 261472 bytes (193134 compressed) at 0x00000000 in 17.1 seconds (effective 122.1 kbit/s)...
Hash of data verified.

Leaving...
Hard resetting via RTS pin...

As you can see, the last message is Hard resetting via RTS pin....
Would anyone please tell me what is happening here? Why the program does not start the LED light even after everything looks fine?
Any help would be greatly appreciated.
Thanks.

switch the DIP switches to ATmega328p, set Uno in Tools menu and upload the Blink sketch. the esp8266 is there as a network adapter, not as a main MCU of the board

Thank you @Juraj. It is working now. Please put this comment as a answer and I will mark a an accepted answer. Thank again.. You made it.

that is all? this was the problem?

Yes @Juraj. That was the only issue. Thanks very much.

Related, if not about the same thing: https://arduino.stackexchange.com/questions/83377/arduino-uno-with-integrated-esp2866-wifi-not-working-correctly

The Uno+WiFi board is an Uno. With DIP switches 3 and 4 in ON position it is a normal Arduino Uno clone with CH340 chip for USB. All the pin headers at board sides and the ICSP pins are as on an Arduino Uno. Every sketch for Uno will work.
The esp8266 is added for WiFi functionality. The DIP switches allow to program the esp8266 over the CH340 or to connect the esp8226 to Serial of the Uno part (ATmega328p).
To have Serial free for USB, it is usual to wire the esp8266 to a common Uno on some other pair of pins then RX/TX and use SoftwareSerial. There is no such connection on this Uno+WiFi, but the esp8266 header has the Rx/RX pins of the esp8266 so it is possible to wire SoftwareSerial pins with jumper wires (power and ground are connected on board of course).

Don't switch the DIP switches too frequently. They are not made for it and fall apart. Upload some permanent firmware to esp8266 or use OTA upload for esp8266.

Thanks for the answers. What would be the DIP switch settings if I want to run Arduino UNO clone with CH340 + Wifi functionality. (Wifi is already on board). What would be the switch settings for both to work together? so that I can create a program to read the data from internet and display on LED panel. Please suggest.

you should not use switches 1+2 and 3+4 at same time so you can set 3+4 for 'Uno' and put two wires between the RX/TX of esp8266 and a pair of Uno pins and use SoftwareSerial on that pins

Thanks, but not getting it right as I am beginner and not sure how to do that. Any information on how to do that would be greatly appreciated.

the Internet has many tutorials how to connect an esp8266 module to Uno. now you know how to apply them to Uno+WiFi


text:
How to change Windows 10 Device Manager so Arduino NANO COM3 can operate on COM4
The Arduino ATmega328 NANO uses COM3 on my WINDOWS 10 computer,
but COM3 is NOT available.
QUESTION:
Please explain in detail how I can change this Arduino NANO
to operate on COM4

What do you mean com3 is not available...?

if COM3 is not available, then the Nano is not using COM3 or it is not plugged in or it has failed in some way

In device manager, right click on the device and select "Properties". Then go to the tab "Connection properties" and click on "Advanced". There you can change the COM port number assignment for a particular device.

In general, Windows assigns COM ports to USB devices when they are plugged in the first time.  If you have multiple USB sockets, the same physical device will be assigned a different COM port when plugged into different sockets.  Is it possible that you have changed your setup and are now using a different USB socket?  Try the others to see if that works.


text:
Changing the order of GUI-elements inside Arduino ESP-Dash-library
I'm trying to add a new item "index" to GUI-elements that are created by using ArduinoJSON and the Vue.js-framework inside the ESP-Dash-library.
The library creates GUI-elements like buttons, sliders etc. and provides easy to program call-back-procdures to make the microcontroller interact with the user-input from the website.
The code as it is iterates through all defined GUI-elements and creates the HTML-code. First all temperture-showing elements then all humidity elements, then all sliders etc...
This means the sequence and the position of the GUI-elements can't be defined by the programmer.
The new functionality I want to achieve is that the programmer can define the sequence and position of all GUI-elements on the website.
This means a new item like "index" must be added and the HTML-creation-code must be changed to another kind of iteration through the GUI-elements.
Now I'm very lost on where to look into all the Arduino- or the javascript-code  to find that place where the iteration must be changed.
Here is the link to the GiPo https://github.com/ayushsharma82/ESP-DASH
and especially to the app.vue javascript https://github.com/ayushsharma82/ESP-DASH/blob/master/vue-frontend/src/App.vue
If this kind of question is inapropriate please drop a few words what is wrong.
And then add a link to "how to post good questions"
best regards Stefan


text:
Why does the LED state behave differently?
I wanted the sensor to be high when I press the button, but when DigitalRead does low, the LED turns on, when it does high, the LED goes off.
Whereas when the digitalRead is high, isn't it supposed to turn on the led?
int pirPin = 8;
int ledPin = 13;
int state;
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 1000;

void setup() {
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {

  unsigned long currentMillis = millis();
  state = digitalRead(pirPin);
  Serial.println(durum);

  if (state == HIGH) {
    previousMillis = currentMillis;
     }
    if (currentMillis - previousMillis >= interval) {
      digitalWrite(ledPin, LOW);
    }
    else
      digitalWrite(ledPin, HIGH);
  }

What about the button? Have you connected a button to pirPin or a PIR sensor?

"isn't it supposed to turn on the led?" - how should we know that? It's your code. You tell us what it's supposed to do. If you want the LED to go on, the code is wrong.

This way the led lights up.But I don't understand why the led turns on when I make low

@ chrisl. yes i connected.code already works this way.I'm wondering why the led lights up when it's low

Probably because it’s wired so that it lights up when the output is low, for example by putting the LED between the positive supply and the output pin (with a resistor in between).

Check out this link. The LED could be a common anode LED

Please provide a schemtic or wiring diagram of your circuit. And please better describe your problem. What behavior did you expect? What did actually happen? I currently don't understand you. "I make it low" is not really a helpful description of what you are doing

Your code is a bit of a mess. You log the value of something called durum, but never define it. You have an if statement, if (state == HIGH) that only affects the value of previousMillis, despite misleading indentation.  It looks like pulling pirPin HIGH would cause your LED pin to be pulled high for 1 second.

I suggest you check your {} in the if(state==HIGH) section, they sre probably wrong. You'd better use those braces consistently: though you wouldn't need them on any of those three lines, you use them on the first two, but you don't use them on the last.

Atm, you refresh the timestamp if the button is pressed. Then, if the timestamp has expired you turn the led off, otherwise on. This should behave as follows: when the button is pressed, the led should go on, one second after the button is released, the led turns off. As pointed out, this all depends pn how your button is wired.

Thank you all, I took care of the problem


text:
Receiving "ERROR: Timeout waiting for client." when connecting to a single table in database - mysql connector on Arduino Uno Wifi Rev2
I have a MariaDb database on a local server and I am using it to store data from various Arduino's around my shop. The database currently has 12 tables. I also have another Arduino Uno Wifi Rev2 that is able to connect to its two respective tables; it collects setpoint information from one table and inserts data perfectly into the other.
The Arduino I'm having a problem with can insert data perfectly fine into its data table (veg2_data) but fails when trying to select data from it's sp table (veg2_sp). It can also connect to any of the other tables in my database, including the one for the first arduino. Only veg2_sp is malfunctioning
Here is my code:
#include <SPI.h>
#include <WiFiNINA.h>
#include <MySQL_Connection.h>
#include <MySQL_Cursor.h>
#include "config.h"
//Node Libraries
#include <DHT.h>

#define O_UPPER 9
#define O_LOWER 10

//Wifi
byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED }; //Do I need this?
char ssid[] = CONFIG_SSID;
char pass[] = CONFIG_PASS;
int status = WL_IDLE_STATUS;
int keyIndex = 0;
WiFiClient client;

//MySQL
IPAddress server_addr(192, 168, 1, 133);
char user[] = CONFIG_MYSQL_USER;
char password[] = CONFIG_MYSQL_PASS;
char db[] = CONFIG_MYSQL_DB;
char query[128];
char DATA_QUERY[] = "INSERT INTO veg2_data VALUES (now(), %d, %d, %s, %s, %s, %s, %s, %s, %d);";
char SP_QUERY[] = "SELECT * FROM veg2_sp ORDER BY timestamp DESC LIMIT 1;";
char rawTime[30];
byte refreshRate = 1;
uint32_t dbContactTimer;
MySQL_Connection conn((Client *)&client);
MySQL_Cursor cur = MySQL_Cursor(&conn);

//Node Specific
bool o_UpperState, o_LowerState, daytime = 0;
byte dayTempSP = 25, dayHumiditySP = 30, nightTempSP = 10, nightHumiditySP = 20,
     o_UpperLock = 0, o_LowerLock = 0, sunrise = 7, sunset = 19;
int soilMoisture;
float intakeTemp, intakeHum, roomTemp, roomHum, exhaustTemp, exhaustHum ;
char intakeTempArray[7], intakeHumArray[7], roomTempArray[7], roomHumArray[7],
     exhaustTempArray[7], exhaustHumArray[7];

DHT exhaust(6, DHT11);
DHT intake(7, DHT11);
DHT room(8, DHT11);

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

  exhaust.begin();
  intake.begin();
  room.begin();

  pinMode(O_UPPER, OUTPUT);
  pinMode(O_LOWER, OUTPUT);
  digitalWrite(O_UPPER, LOW);
  digitalWrite(O_LOWER, LOW);

  //spCheck();
  dbContactTimer = millis();
}

void loop() {

  //Default refesh rate is 5 seconds. Some nodes need to increase refesh rate at specific times
  if (millis() - dbContactTimer >= (refreshRate * 1000)) {
    dbUpdate();
    spCheck();

    //If set to auto (2), my lights will turn on and off depending on day/night. Currently unfinished
    if (o_UpperLock == 2) {
      if (daytime) {
        digitalWrite(O_UPPER, HIGH);
        o_UpperState = 1;
      }
      else {
        digitalWrite(O_UPPER, LOW);
        o_UpperState = 0;
      }
    }
    dbContactTimer = millis();
  }

}

//------------------------------------MySql Functions-------------------------
void spCheck() { //Updates setpoints
  if (!conn.connected()) {
    conn.close();
    if (!conn.connect(server_addr, port, user, password, db)) {
      return 0;
    }
  }
  row_values *row = NULL;
  cur.execute(SP_QUERY);
  column_names *columns = cur.get_columns();
  do {
    row = cur.get_next_row();
    if (row != NULL) {
      //Serial.println(row->values[0]);
      o_UpperLock = atol(row->values[1]);
      //o_LowerLock = atol(row->values[2]);
      //dayTempSP = atol(row->values[3]);
      //dayHumiditySP = atol(row->values[4]);
      //nightTempSP = atol(row->values[5]);
      //nightHumiditySP = atol(row->values[6]);
      //sunrise = atol(row->values[7]);
      //sunset = atol(row->values[8]);
    }
  } while (row != NULL);

  if (o_UpperLock < 2) {
    if (o_UpperLock) {
      digitalWrite(O_UPPER, HIGH);
      o_UpperState = 1;
    }
    else {
      digitalWrite(O_UPPER, LOW);
      o_UpperState = 0;
    }
  }
  return 1;
}

void dbUpdate() { //Updates data
  if (!conn.connected()) {
    conn.close();
    if (!conn.connect(server_addr, port, user, password, db)) {
      return 0;
    }
  }

  intakeTemp = intake.readTemperature();
  dtostrf(intakeTemp, 4, 2, intakeTempArray);

  intakeHum  = intake.readHumidity();
  dtostrf(intakeHum, 4, 2, intakeHumArray);

  roomTemp = room.readTemperature();
  dtostrf(roomTemp, 4, 2, roomTempArray);

  roomHum = room.readHumidity();
  dtostrf(roomHum, 4, 2, roomHumArray);

  exhaustTemp = exhaust.readTemperature();
  dtostrf(exhaustTemp, 4, 2, exhaustTempArray);

  exhaustHum = exhaust.readHumidity();
  dtostrf(exhaustHum, 4, 2, exhaustHumArray);

  soilMoisture = analogRead(A0);

  sprintf(query, DATA_QUERY, o_UpperState, o_LowerState, intakeTempArray,
          intakeHumArray, roomTempArray, roomHumArray, exhaustTempArray, exhaustHumArray, soilMoisture);
  cur.execute(query);

  return 1;
}

void wifiInit() {

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("No wifi Module - Abort");
    while (true);
  }
  while (status != WL_CONNECTED) {
    Serial.println("Connecting to wifi");
    for (byte i = 0; i < 2; i++) {
      digitalWrite(LED_BUILTIN, HIGH);
      delay(2000);
      digitalWrite(LED_BUILTIN, LOW);
      delay(1000);
    }
    status = WiFi.begin(ssid, pass);
  }

  IPAddress ip = WiFi.localIP();
  long rssi = WiFi.RSSI();
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());
  Serial.print("IP Address: ");
  Serial.println(ip);
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

The problem is with the SP_QUERY. I can change the table to any other in my database, and the code functions fine. If I read from veg2_sp, I get the error.
Tables: The first one is the one im having problems with, the second is the one that is currently functioning.

I'm utterly baffled.

firewall on PC?

I thought so too, but I can still connect to the other table in the database. If I couldn't connect to anything, I'd agree, but what is stopping me from accessing a single table??


text:
When it comes to UART to RS485 communication, what is the difference between the 'MAX485' and the 'HW-0519' module?
I recently found this model with the ID 'HW-0519' on it. It can be found online (HW-0519 in Aliexpress) and is sold for the purpose of converting UART to RS485 communication using Arduino devices. The MAX485 module (MAX485 in Banggood) is the more commonly used module for this purpose and has been used in many projects. The MAX485 has the following pins DI (data in), RO (receiver out), DE (Data Enable), RE (Receiver Enable), VCC, GND and the 'A' and 'B' pins for the RS485 device (Shown below).

The HW-0519 module, has a slightly different pin configuration, and I can't seem to wrap my head around it. It has Tx and Rx pins, which I am guessing match up with RO and DI respectively, but don't have enable pins. They have the VCC and GND pins along with the 'A' and 'B' pins, but also come with this pin marked in Chinese. I translated it using Google translate and it translates to something similar to 'Ground'. Which is not connected to the GND pin though (Shown below).

Does anyone know whether I can use the HW-0519 module in the same manner as the MAX485? If so, are there any libraries written for this module? I want to use the module for communication with a pH sensor like the one in this link.

Looks like the HW-0519 module implements automatic TX/RX mode switching for you.

@Majenko does that mean I need not concern myself with controlling the direction of the data when writing the code with this HW-0519?

@Majenko because, from what I understand, the DE and RE in the MAX485 module are usually connected together to one pin in the microcontroller and set to HIGH when transmitting and LOW when receiving.

Theoretically, though there may be baud rate considerations to take into account and pre/post send delays or something. I don't know how the module works, so YMMV with it.

I did a bit of research and found others who use this particular component for their RS485 communication purposes. It is difficult to get clear info because the device goes by different names and the most commonly used name is MAX485 (name of the IC), which is used interchangeably for both the components shown in the question.
It seems the more I search for the 'HW-0519', the more names I find for it. So far, it goes by the name 'MAX485', 'XY-017', and 'XY-K485'. A clear advantage for this 'HW-0519' is that it does not require D or R enabling, just straightforward Tx and Rx. It also has LEDs to show the data transfers. I found a project that used this module here. I am unsure about their pin connections from the ESP-32 though. It looks like they've connected the ESP-32's TX2 to the HW-0519's Tx, and the RX2 to the Rx. I thought it should be the other way around.

I confirm the module has to be connected like: Module TX--TX MCU and Module RX--RX MCU

I have the HW-0519 (bought as https://www.amazon.co.uk/gp/product/B0BCFLTLGJ/ at £9.98 for 8x in 2023-09) and it matches the picture above quite closely enough. It is a variant, and the first difference I see is the (?) polyfuses JK075 above are T010 on mine.
I picked this because it has protection components on the board which others don't have - including the MAX485 board from Banggood linked above.
Both boards lack mounting holes but the MAX485 board has pins which (if they align?) might assist breadboard usage. For me, the prototyping phase will start with epoxying HW-0519 to a Lego brick.
I found a circuit diagram at https://easyeda.com/modules/HW-0519-TTL-to-RS485-converter_c4836920e8ec45b3924add8ac2acbe57 for something similar which helped me work out what's what. I'm not going to steal a copy and upload here but it looks like https://web.archive.org/web/*/https://image.easyeda.com/components/c4836920e8ec45b3924add8ac2acbe57.png .

Starting at the A+ / B- lines,
fuses F1 and F2 of type "108L" (presumably polyfuse type),
120Ω bus termination R14 across,
then an SM712 asymmetric TVS protection chip https://www.semtech.com/products/circuit-protection/rs485/sm712 ,
finally the pull-up resistors 4k6 and MAX348 chip named U6.

My board is a cousin of the circuit diagram I found.

chips are named U2 (unmarked SOIC14, maybe 74HC04) and anon unmarked SOIC8,
its TVS protection is done as three chunky 2-pin diodes marked WK as in the HW-0519 above,
bus termination resistor is R9 and you have to short R0 to terminate the bus, so one at each end but not in the middle, in the usual way.
TVS protection comes to that third bus pin 球大(??) which I think is "earth big (something)"

Note that the bus ground is not connected to the logic ground GND on the 4-pin connector. You need to provide bus ground separately and maybe from a different source after considering fault currents.


text:
Arduino freezes , how can I convert Arduino String to C string type?
this is my first post, im not an expert but I managed to build an Arduino Mega with an ESP8266 to water my plants inside a tent, unfortunately its freezes/crashes randomly and I have to go and reset it manually all the time. I read that this is because im using string and I should use C string type.
Could you please help me out to find a way to stop reseting manually all the time?
Thanks!
Here is the code:
#include <DHT.h>
#include <DS3231.h>
#define DHTPIN 51 // before it was 53
#define DHTTYPE DHT11
#include <ESP8266_Lib.h>
#define EspSerial Serial1

#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);

const int AirValue = 820;   // 778
const int WaterValue = 437;  //
int soilmoisturepercentA0=0;
int soilmoisturepercentA1=0;
int soilmoisturepercentA2=0;
int soilmoisturepercentA3=0;

String agAdi = "XXXXXX";
String agSifresi = "XXXXX";
String ip = "184.106.153.149";
float sicaklik, nem;

int led = 38;
int UV_Light = 27;
int Tent_Humid = 29;
int Heater = 26;
//int Free_IN3 = 28;
const int button1 = 53;
int buttonState1 = 0;

DHT dht = DHT(DHTPIN, DHTTYPE);
DS3231  rtc(SDA, SCL);
Time t; // Main time to display

//Schedule R2 UV_Light
const int OnHour_R2 = 6;
const int OnMin_R2 = 00;
const int OffHour_R2 = 1;
const int OffMin_R2 = 00;

int IN1 = 22;
int IN2 = 23;
int IN3 = 24;
int IN4 = 25;

int Pin1 = A0;
int Pin2 = A1;
int Pin3 = A2;
int Pin4 = A3;

float value1 = 0;
float value2 = 0;
float value3 = 0;
float value4 = 0;

void setup() {
  Serial.begin(9600);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
  pinMode(IN3, OUTPUT);
  pinMode(IN4, OUTPUT);

  pinMode(Pin1, INPUT);
  pinMode(Pin2, INPUT);
  pinMode(Pin3, INPUT);
  pinMode(Pin4, INPUT);

  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, HIGH);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, HIGH);

  pinMode(led, OUTPUT);
  pinMode(UV_Light, OUTPUT);
  pinMode(Tent_Humid, OUTPUT);
  pinMode(Heater, OUTPUT);
  pinMode(button1, INPUT_PULLUP);

  digitalWrite(UV_Light, HIGH);
  digitalWrite(Tent_Humid, HIGH);
  digitalWrite(Heater, HIGH);

  dht.begin();
  rtc.begin();

  delay(500);

  Serial.println("Started");
  EspSerial.begin(9600);                                          // We are starting serial communication with ESP8266.
  EspSerial.println("AT");                                         // We do the module control with the AT command.
  Serial.println("AT  sent ");
  while(!EspSerial.find("OK")){                                     // We wait until the module is ready.
    EspSerial.println("AT");
    Serial.println("ESP8266 Not Found.");
  }
  Serial.println("OK Command Received");
  EspSerial.println("AT+CWMODE=1");                                 // We set the ESP8266 module as a client.
  while(!EspSerial.find("OK")){                                     // We wait until the setting is done.
    EspSerial.println("AT+CWMODE=1");
    Serial.println("Setting is ....");
  }
  Serial.println("Set as client");
  Serial.println("Connecting to the Network ...");
  EspSerial.println("AT+CWJAP=\""+agAdi+"\",\""+agSifresi+"\"");    // We are connecting to our network.
  while(!EspSerial.find("OK"));                                     // We wait until it is connected to the network.
  Serial.println("CONNECTED to the Network ");
  delay(500);
//OLED
  display.begin(SSD1306_SWITCHCAPVCC, 0x3C);  // initialize with the I2C addr 0x3D (for the 128x64)
  display.display(); // show splashscreen
  delay(500);
  display.clearDisplay();   // clears the screen and buffer

}
void loop() {

//  DHT11.read(dht11Pin);
  dht.read(DHTPIN);
  sicaklik = (float)dht.readTemperature();
  nem = (float)dht.readHumidity();
//  value1 = analogRead(Pin1);
  soilmoisturepercentA0 = map(value1, AirValue, WaterValue, 0, 100);
  soilmoisturepercentA1 = map(value2, AirValue, WaterValue, 0, 100);
  soilmoisturepercentA2 = map(value3, AirValue, WaterValue, 0, 100);
  soilmoisturepercentA3 = map(value4, AirValue, WaterValue, 0, 100);
  String veri = "GET https://api.thingspeak.com/update?api_key=123456";   // Thingspeak command. We write our own api key in the key part.
  veri += "&field1=";
  veri += String(sicaklik);// The temperature variable we will send
  veri += "&field2=";
  veri += String(nem);// The moisture variable we will send
  veri += "&field3=";
  veri += String(soilmoisturepercentA0);// Soil A0
  veri += "&field4=";
  veri += String(soilmoisturepercentA1);// Soil A1
  veri += "&field5=";
  veri += String(soilmoisturepercentA2);// Soil A2
  veri += "&field6=";
  veri += String(soilmoisturepercentA3);// Soil A3
  veri += "\r\n\r\n";
  EspSerial.print("AT+CIPSEND=");                                   // We give the length of data that we will send to ESP.
  EspSerial.println(veri.length()+3);
//  delay(500);

  if(EspSerial.find(">")){                                          // The commands in it are running when ESP8266 is ready..
    EspSerial.print(veri);                                          // We send the data.
    Serial.println(veri);
    Serial.println("Data sent.");
    delay(500);
  }
  Serial.println("Connection Closed.");
  EspSerial.println("AT+CIPCLOSE");                                // we close the link
  delay(500);

  Serial. print('\n');
  Serial.print("MOISTURE LEVEL A0:");
  value1 = analogRead(Pin1);
  Serial.println(value1);
  Serial.println(soilmoisturepercentA0);
    if(value1>750)
  //if(soilmoisturepercentA0>35)

  {
      digitalWrite(IN1, LOW);
  }
  else
  {
    digitalWrite(IN1, HIGH);
    }

  Serial.print("MOISTURE LEVEL A1:");
  value2 = analogRead(Pin2);
  Serial.println(value2);
  Serial.println(soilmoisturepercentA1);
  if(value2>750)
 //  if(soilmoisturepercentA1>35)
  {
      digitalWrite(IN2, LOW);
  }
  else
  {
    digitalWrite(IN2, HIGH);
    }

  Serial.print("MOISTURE LEVEL A2:");
  value3 = analogRead(Pin3);
  Serial.println(value3);
  Serial.println(soilmoisturepercentA2);
  if(value3>750)
  //  if(soilmoisturepercentA2>35)
  {
      digitalWrite(IN3, LOW);
  }
  else
  {
    digitalWrite(IN3, HIGH);
    }

  Serial.print("MOISTURE LEVEL A3:");
  value4 = analogRead(Pin4);
  Serial.println(value4);
  Serial.println(soilmoisturepercentA3);
  if(value4>750)
   // if(soilmoisturepercentA3>35)
  {
      digitalWrite(IN4, LOW);
  }
  else
  {
    digitalWrite(IN4, HIGH);
    }
    Serial.println();
  delay(500);

{
    t = rtc.getTime();
  Serial.print(t.hour);
  Serial.print(" hour(s), ");
  Serial.print(t.min);
  Serial.print(" minute(s)");
  Serial.println(" ");
  delay (500);

  digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(500);
  }
    // Relay UV_Light
  if (t.hour == OnHour_R2 && t.min == OnMin_R2) {
    digitalWrite(UV_Light, LOW);
  }
  else if (t.hour == OffHour_R2 && t.min == OffMin_R2) {
    digitalWrite(UV_Light, HIGH);
  }
   buttonState1 = digitalRead(button1);
   if (buttonState1 == LOW) {
    digitalWrite(UV_Light, LOW);
    delay (100);
  }
  // Read the Humidity in %:
  float h = dht.readHumidity();
  // Read the Temperature as Celsius:
  float t = dht.readTemperature();
  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
  }
   // Display Humidizador
if (h <40)
  {
  digitalWrite(Tent_Humid, LOW);
  Serial.print("Humid ON");
  Serial. print('\n');
  } else{
    digitalWrite(Tent_Humid, HIGH);

    Serial.print("Humid OFF");
    Serial. print('\n');
}

// Display Heater
if (t <18)
  {
  digitalWrite(Heater, LOW);
  Serial.print("Heater ON");
  Serial. print('\n');
  } else{
    digitalWrite(Heater, HIGH);

    Serial.print("Heater OFF");
    Serial. print('\n');
}
    delay (100);
    float hic = dht.computeHeatIndex(t, h, false);
  Serial.print("Humidity: ");
  Serial.print(h);
  Serial.print(" % ");
  Serial.print("Temperature: ");
  Serial.print(t);
  Serial.print(" \xC2\xB0");
  Serial.print("C ");
//  Serial.print("Heat index: ");

   EspSerial.println("AT+CIPSTART=\"TCP\",\""+ip+"\",80");           // We connect to Thingspeak.
  if(EspSerial.find("Error")){                                      // We check the connection error.
    Serial.println("AT+CIPSTART Error");
  }

// OLED
{
  float h = dht.readHumidity();
  // Read temperature as Celsius (the default)
  float t = dht.readTemperature();
  // Read temperature as Fahrenheit (isFahrenheit = true)
  float f = dht.readTemperature(true);

  // Check if any reads failed.
  if (isnan(h) || isnan(t) || isnan(f)) {
    delay(500);
  } else{
    // routine for converting temp/hum floats to char arrays
    char temp_buff[5]; char hum_buff[5];
    char temp_disp_buff[11] = "Tmp:";
    char hum_disp_buff[11] = "Hum:";

    // appending temp/hum to buffers
    dtostrf(t,2,1,temp_buff);
    strcat(temp_disp_buff,temp_buff);
    dtostrf(h,2,1,hum_buff);
    strcat(hum_disp_buff,hum_buff);

    // routine for displaying text for temp/hum readout
    display.clearDisplay();
    display.setTextSize(2);
    display.setTextColor(WHITE);
    display.setCursor(0,0);
    display.println(temp_disp_buff);
    display.println(hum_disp_buff);
    display.display();
    delay(500);
{
   digitalWrite(led, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(500);               // wait for a second
  digitalWrite(led, LOW);    // turn the LED off by making the voltage LOW
  delay(500);

  }
  }
}
}

What means "crashes constantly"? After a few seconds, a few minutes or a few hours? The code above is supposed to run on an Arduino Mega or an ESP8266?

Sometimes after 8 hours, sometimes after 2 hours, its never the same frequency, Im using an Arduino Mega 2560 with an ESP8266 Wifi module.

why don"t you use a proper WiFi library ?

I tried using ESP8266WiFi.h but was not working with the Arduino Mega

Regardless of what the actual answer is, you may want to look into using the watchdog timer.

there is WiFiEsp or my WiFiEspAT for newer AT firmware version

here Majenko writes about C strings in second part: https://majenko.co.uk/blog/evils-arduino-strings


text:
Why my arduino board does not blink properly?
I have two files
blink1.cpp
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

blink2.cpp
typedef unsigned char int8_t;
typedef volatile int8_t * volatile port_type;

port_type portB = (port_type) 0x25;
port_type ddrB = (port_type) 0x24;
port_type portC = (port_type) 0x28;
port_type ddrC = (port_type) 0x27;
port_type portD = (port_type) 0x2B;
port_type ddrD = (port_type) 0x2A;

void delay_500ms()
{
    asm (
    // 8000000 cycles
    "ldi  r19, 150 \n\t"
    "ldi  r20, 128 \n\t"
    "ldi  r23, 41 \n\t"
    "L1: \n\t"
    "dec  r20 \n\t"
    "brne L1 \n\t"
    "dec  r19 \n\t"
    "brne L1 \n\t"
    "dec  r23 \n\t"
    "brne L1 \n\t"
    );
}

int main()
{
    ddrB = (port_type) 0x20;

    while(true)
    {
        *portB = (int8_t) 0x20;
        delay_500ms();
        *portB = (int8_t) 0x00;
        delay_500ms();
    }
}

The difference between these two files are the definition of only a few unused ports in blink2.
I compile and upload them to the board by
avr-g++ blink1.cpp -o blink1
avr-objcopy -O ihex -R .eeprom blink1 blink1.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink1.hex

avr-g++ blink2.cpp -o blink2
avr-objcopy -O ihex -R .eeprom blink2 blink2.hex
avrdude -F -V -c arduino -p ATMEGA328P -P /dev/ttyUSB0 -b 115200 -U flash:w:blink2.hex

The first one does not blink properly but the second one does. What is the problem of the first code?

Do both files behave the same when using avr-g++ -Os blink1/2.cpp -o blink1/2 for compilation?

@MaximilianGerhardt, using -Os both act as before.

I think ddrB = (port_type) 0x20; should be *ddrB = (int8_t) 0x20; no?

@MaximilianGerhardt, You are correct. However, this fix does not change anything. The board behavior highly depends on the variable you define after ddrB and its value.

@MaximilianGerhardt, it is interesting that when I use *ddrB = (int8_t) 0x20;  with -Os, the LED turns on but does not blink. If I do not use -Os it will blink fine.

Maybe you're killing the contents of registers that are being used. Check the disassembly to see if the registers you are using in assembly are being pushed to the stack before use and popped off afterwards - if they aren't then you should be doing that manually.

https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#Clobbers-and-Scratch-Registers

You may want to exchange the assembly code for C code for a test and see if that's the problem, e.g. with the code https://pastebin.com/Z5m2fvWt

@MaximilianGerhardt: Your delay_500ms() is more than an order of magnitude slower than the original.

There are a couple of issues here.
One of them has already been raised in a comment:

 int main()
 {
-    ddrB = (port_type) 0x20;
+    *ddrB = (int8_t) 0x20;

     while(true)
     {

The more serious issue is in the command line you used to compile the
program. When compiling for an Uno, you should add the option
-mmcu=atmega328p. This way the compiler knows which version of the C
runtime it should add to your program. Otherwise the compiler will
include no runtime at all.
The C runtime does some important initializations. For example, it
clears the register r1, which is required by the ABI, and assumed
to be the case by the compiler. For example, when you write *portB = (int8_t) 0x00;, the compiler copies r1 to the port, without first
clearing it. Another important role of the C runtime is to call
main(). Without it, the program will start by executing whichever
function happens to be at the start of the flash. Unless you program in
assembly, you have no control over that. If the first function happens
to be main(), the program may work as expected. If it is another
function, that function may then return to the bootloader. Any seemingly
innocuous change in the program can then change the behavior.
Then a few minor issues, that should not prevent the program from
working:

int8_t is meant to be a signed type. If you want the unsigned
version, use uint8_t instead. Sure, these are your own type
definitions, but creating a type that conflicts with a standard type
can only create confusion. Best option is to drop the definition and
include <stdint.h> instead.

Whereas port_type should certainly be a “pointer to volatile” data,
there is no point in making the pointer itself volatile. That can only
hinder valid optimizations.

portB and ddrB should be const, and that may allow the compiler
to better optimize them. But why not use PORTB and DDRB from
<avr/io.h>?

I confirm using avr-g++ -mmcu=atmega328p instead of avr-g++ has fixed the problem. Thank you so much.


text:
Why SSD1306 OLED display get scrambled text when printing messages from separate tasks in RTOS? (revised)
ESP32 with RTOS, test app with 2 independent tasks. Each prints a message to OLED display.
Why text gets frequently scrambled? Mutex have been used to share display resource.

#define DEBUG_ESP              //comment out to deactivate debug console verbose
#ifdef DEBUG_ESP
  #define pDBGln(x) Serial.println(x)
  #define pDBG(x)   Serial.print(x)
#else
  #define pDBG(...)
  #define pDBGln(...)
#endif

//create handle for the mutex. It will be used to reference mutex
SemaphoreHandle_t  xMutex;

//*********************************SSD1306 OLED Display
#define I2C_SDA              14
#define I2C_SCL              15
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
//*****************************************************

void setup() {

  // create mutex and assign it a already create handler
  xMutex = xSemaphoreCreateMutex();

  Wire.begin(I2C_SDA,I2C_SCL);
  Serial.begin(115200);

   // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    pDBGln("SSD1306 allocation failed - Halt");
    for(;;); // Don't proceed, loop forever
  }else{
    // Show initial display buffer contents on the screen --
    // the library initializes this with an Adafruit splash screen.
    display.setTextSize(1);
    display.setTextColor(SSD1306_WHITE);
    display.setCursor(0, 0);
    display.clearDisplay();
  }

    xTaskCreatePinnedToCore(
        task01,             /* Function to implement the task */
        "task01",           /* Name of the task */
        10000,              /* Stack size in words */
        NULL,               /* Task input parameter */
        1,                  /* Priority of the task */
        NULL,               /* Task handle. */
        0);                 /* Core where the task should run */

    xTaskCreatePinnedToCore(
        task02,             /* Function to implement the task */
        "task02",           /* Name of the task */
        10000,              /* Stack size in words */
        NULL,               /* Task input parameter */
        1,                  /* Priority of the task */
        NULL,               /* Task handle. */
        1);                 /* Core where the task should run */
}

void loop() {}

void task01( void * parameter ){
  while(1){
    printToDisplay("Task01..............");
    vTaskDelay(1500);
  }
}

void task02( void * parameter ){
  while(1){
    printToDisplay("Task02..............");
    vTaskDelay(2500);
  }
}

void printToDisplay(String text){
  bool myMutex;
  while(1){
    // take mutex
    myMutex = xSemaphoreTake(xMutex, portMAX_DELAY);
    if(myMutex){
      static byte   lineCounter = 0;
      static String displayText[8];
      if(lineCounter>7){
        for(int i=0;i<7;i++){
          displayText[i] = displayText[i+1];
        }
        displayText[7] = text;
        display.clearDisplay();
        display.setCursor(0, 0);
        for(int i=0;i<8;i++){
          display.println(displayText[i]);
        }
      }else{
        displayText[lineCounter] = text;
        display.println(displayText[lineCounter]);
        if(lineCounter<8){lineCounter++;}
      }
      display.display();

      // release mutex
      xSemaphoreGive(xMutex);
      break;
    }
  }
}

The code below uses no RTOS and works perfectly: (my project requires RTOS)
#define DEBUG_ESP              //comment out to deactivate debug console verbose
#ifdef DEBUG_ESP
  #define pDBGln(x) Serial.println(x)
  #define pDBG(x)   Serial.print(x)
#else
  #define pDBG(...)
  #define pDBGln(...)
#endif

byte lineCounter = 0;

//*********************************SSD1306 OLED Display
#define I2C_SDA              14
#define I2C_SCL              15
#include <Wire.h>
#include <Adafruit_SSD1306.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
#define OLED_RESET     4 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, -1);
//*****************************************************

void setup() {

  Wire.begin(I2C_SDA,I2C_SCL);
  Serial.begin(115200);

   // SSD1306_SWITCHCAPVCC = generate display voltage from 3.3V internally
  if(!display.begin(SSD1306_SWITCHCAPVCC, 0x3C)) {
    pDBGln("SSD1306 allocation failed - Halt");
    for(;;); // Don't proceed, loop forever
  }else{
    // Show initial display buffer contents on the screen --
    // the library initializes this with an Adafruit splash screen.
    display.setTextSize(1);
    display.setTextColor(SSD1306_WHITE);
    display.setCursor(0, 0);
    display.clearDisplay();
  }
}

void loop() {
  pDBGln("Start Display Test...");
  task01();
  task02();
}

void task01(){
  printToDisplay("Task01..............");
  delay(500);
}

void task02(){
  printToDisplay("Task02..............");
  delay(500);
}

void printToDisplay(String text){
  static byte   lineCounter = 0;
  static String displayText[8];
  if(lineCounter>7){
    for(int i=0;i<7;i++){
      displayText[i] = displayText[i+1];
    }
    displayText[7] = text;
    display.clearDisplay();
    display.setCursor(0, 0);
    for(int i=0;i<8;i++){
      display.println(displayText[i]);
    }
  }else{
    displayText[lineCounter] = text;
    display.println(displayText[lineCounter]);
    if(lineCounter<8){lineCounter++;}
  }
  display.display();
}

At first glance that all looks fine. Maybe there's something behind the scenes that's messing it up. Maybe you should have all the display code in one dedicated thread and pass data to that thread from the others.

You mean create a third task printToDisplay(String text)?

A third task that takes instruction through some other route (maybe a pipe or something similar) from the other tasks and displays the information.

Just found that if I put Task01 to run on the same core as Task02 (core 1) it works perfectly. And if I put both to run on core 0 the mess becomes a lot worse. The problem has clearly something to do when the task running on core 0 tries to write to the display even protected by Mutex.

Core 0 is used for the Wifi and IP stack. There's probably some timing issue then.

Yes, possibly. Still trying to find a way around it or will have to live with it...

Can you show us a picture of the display corruption? We may be able to see a pattern that would explain it.

Please check pictures I added at the top.Yes, there is a pattern that repeats but I believe it to be a result of the timing between task execution.

Ok, so there is one of two things happening here, and it's impossible at the moment to know which. The way the library works is it has an internal framebuffer which is what you modify with the drawing/printing functions. That framebuffer is then output in its entirety to the display in one go with .display(). Either that internal framebuffer is being corrupted while drawing, or the communication with the display is being broken when sending. I suggest having the .display() only ever happen in a thread on core 1. The rest can be wherever.

This is a formal answer to the question based on the comments between Paulo Borges and Majenko.

The ESP32 is dual core, meaning that it comes with 2 Xtensa LX6 32-bit microprocessors: core 0 and core 1.
The issue is not a bug in your code but rather that you are running your threads on Core 0 instead of Core 1.
In the ESP, the Core 0 is used for the RF communications. Even with the mutex protection, it is highly likely that your tasks are having timing issues.
Move Task01 and Task02 into Core 1 and your program will run without any display issues.


text:
How can I get an integer from an RFID tag from Arduino Mega to NodeMCU 1.0 over serial communication?
I want the number from an RFID tag read by a reader connected to an Arduino Mega to end up as a string on a NodeMCU connected to the Mega. I am trying to confirm that the string is on the NodeMCU using the serial monitor. With the code below, the serial monitor for the NodeMCU prints "receivedChars:" only and not the number from the tag. What am I missing?
Code for Arduino Mega

#include <SPI.h>
#include <MFRC522.h>

#define SS_PIN 53
#define RST_PIN 5
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.

String sent = "n";
String UID_string = "";

void setup() {

    SPI.begin();            // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
    Serial.begin(115200); // Initialize serial communications with the PC
    Serial.println("Running Version Jan5a");
    Serial.println("Mega:Serial Monitor initialized at 115200 baud...");
    Serial3.begin(9600); // Initialize serial communication with ESP
    Serial.println("Mega:Serial Port 3 for NodeMCU initialized at 9600 baud...");
    Serial.println("Mega: Scan PICC to see UID and type...");
}

////////

void SendUIDtoESP() {

if (sent == "n") {
  Serial.print("sent= ");
  Serial.print(sent);
  //if (UID_string.length() > 0)  {
  UID_string = "Hello World"; //test line
  Serial3.print("<");
  Serial3.print(String(UID_string));
  Serial3.print(">");
  Serial.println("Mega:Sending UID string to ESP");
  sent = "y";
  Serial.print("after sending, sent= ");
  Serial.print(sent);
//  } else {
 //   Serial.println("Mega: Error: UID-string not set yet!");
  //}

}
} // end Send UID to ESP

void loop {
SendUIDtoESP() ;
}

Code for NodeMCU

int numChars = 0;
String receivedChars = "";
boolean newData = false;
String tag = "";
unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

SoftwareSerial s(D1,D2);// assign pins to send data to and receive data from NodeMCU to Arduino Mega rx, tx

void setup() {
Serial.begin(9600);
    s.begin(9600);
    Serial.println("NodeMCU: Waiting for serial connection with Mega to be available over s");
  while (! s.available() >0){
    Serial.print("."); // waiting
    return;
  }
  Serial.println("NodeMCU: Looks like Mega is available.");
} // end void setup

 void recvWithStartEndMarkers() { //listen to Mega
    static boolean recvInProgress = false;
    static byte ndx = 0;
    char startMarker = '<';
    char endMarker = '>';
    char rc;

    while (s.available() > 0 && newData == false) {
        rc = s.read();

        if (recvInProgress == true) {
            if (rc != endMarker) {
                Serial.println(rc);
                receivedChars[ndx] = rc;
                ndx++;
                if (ndx >= numChars) {
                    ndx = numChars - 1;
                }
            }
            else {
                receivedChars[ndx] = '\0'; // terminate the string
                recvInProgress = false;
                ndx = 0;
                newData = true;
            }
        }
        else if (rc == startMarker) {
          Serial.println("startMarker received");
            recvInProgress = true;
        }
    }
} // end recvWithStartEndMarkers()

void loop() {
recvWithStartEndMarkers();
}

why the Mega? NodeMcu has SPI too

what is this?: String UID_string =  (String)UID_unsigned;

I think I took the block containing that line from here: https://github.com/miguelbalboa/rfid/issues/63#issuecomment-66874814

I'm using the NodeMCU for Wifi for the Mega (not reflected here to cut down on code length); I'm using the Mega because I plan on adding an unknown number of components down the road and think I need the ports.

determine if the serial comm actually works as expected ... start with simple hello world sketch

@jsotola are you suggesting testing the Mega sending 'hello world' to the NodeMCU?

yes, that would make certain that the two devices are able to communicate ... one other thing, when printing receivedChars, print the length of receivedChars also ... some characters are nonprinting

@jsotola Thanks for pointing me back to this level of basics. It does not seem to be working with hardcoded Uid_string = "Hello World" in the Mega code (nothing seems to be coming through, and no value for length is prining). I'll work on that. I read somewhere that using the SerialMonitor on the NodeMCU's USB micro-B port could interfere with the serial communications (ESP D1, D2 / Mega 15,14) with the Mega. Might that be an issue here?

Your nodemcu code would print "receivedChars" also, if nothing was received. You might wanna move that code into the if statement of the end marker (so only printing, when a full message was received). How did you connect the mega and the nodemcu?

@jsotola Update: I have focused on getting just 'Hello World!' to transmit and displayed on Serial Monitor for the ESP, and that is now working. I have removed the RFID section because I think the real challenge is converting a character array to string on the ESP, not the RFID reading on the Mega. The serial monitor for the ESP, however, prints "startMarker received" on one line, and then each character of "Hello World!" on a different line. If someone can help me to get 'Hello World!' on the ESP as a string I can append to a URL as a parameter, I should be set (I think).


text:
Resuming Serial Connection after sleep on Arduino M0
For debugging purposes I want my serial connection to resume after sleep.  After running LowPower.sleep() from the <ArduinoLowPower.h> library, I don't get any new serial messages in the serial monitor.
Several factors seem to be at play (which I've listed at the bottom) and I've developed a partial solution but it's not great because it requires some long artificial delays of about 1 second after each sleep to resume the serial.  So to recap, my question is how I can get serial to work after sleeping the microcontroller without having to insert long delays.
For background, I am using an Adafruit Feather M0, which I think actually uses SerialUSB and automatically converts serial commands to that according to the guide, but I am not sure what any of that means.
Here's some stuff I looked into:

COM Port: One factor is that the Arduino disconnects from the my Windows 10 computer at sleep and reconnects when it wakes up sometimes on a different COM port.  Using the program Tera Term instead of the Arduino IDE Serial Monitor seems to keep it on the same COM port.

Serial Flush and End: As notes in my code example, both of these commands seem necessary before sleeping or else I won't receive new messages after sleep.

Delay: Seems that the arduino can send messages right after waking up that Tera Term wont see.  I have to put a delay of 1 full second after waking up or else I won't see the messages.

Here's some code I have tried.
#include <ArduinoLowPower.h>

void setup() {
  Serial.begin(115200);
  while(!Serial){delay(10);}
  Serial.println("start");
}

void loop() {

  Serial.println("");
  Serial.println("sleep");
  Serial.flush();  //if this line is commented out, only one cycle of "sleep" will show
  Serial.end();   //if this line is commented out, only one cycle of "sleep" will show
  //delay(2000);  //doesn't seem to fix anything so commented out
  LowPower.sleep(2000);
  delay(1000);  //at 750 misses some "awake" messages
  //Serial.begin(115200);  //this line doesn't appear to fix anything so commented out
  Serial.println("awake");

Output:
start

sleep
awake

sleep
awake

sleep
awake

while (!Serial);?

so i have a chance to open the serial on my computer before it goes nuts


text:
Hello, help with CODE servo mechanism and DS1307
I am trying to make a auto feeder for birds!,
I can't setup my code, the aim is to move servo when the certain time comes,
My commend if doesnt work, what else commend can I use?
#include <Wire.h>
#include "RTClib.h"
#include <Servo.h>

RTC_DS1307 RTC;
Servo myservo;

void setup () {
    Serial.begin(9600);
    Wire.begin();
    RTC.begin();
    myservo.attach(9);
    myservo.write(45);

  if (! RTC.isrunning()) {
   Serial.println("RTC is NOT running!");

  RTC.adjust(DateTime(2017,05,18,11,10,0));
  }
}

void loop () {
    DateTime now = RTC.now();
Serial.print(now.year(), DEC);
 Serial.print('/');
 Serial.print(now.month(), DEC);
 Serial.print('/');
 Serial.print(now.day(), DEC);
 Serial.print(" (");
 Serial.print(") ");
 Serial.print(now.hour(), DEC);
 Serial.print(':');
 Serial.print(now.minute(), DEC);
 Serial.print(':');
 Serial.print(now.second(), DEC);
 Serial.println();
 Serial.print(" since midnight 1/1/1970 = ");
 Serial.print(now.unixtime());
 Serial.print("s = ");
 Serial.print(now.unixtime() / 86400L);
 Serial.println("d");

    if ( now.hour()== 10 && now.minute() == 18){
      Serial.print('a');

    }

}

my code doesnt work is meaningless ... something like my code does xyz, and i would like it to do abc123 has a meaning

also, please indent your code properly ... it shows the fliw of the code, like paragraphs in a book ... it is indented properly in first half of setup(), and then it gets messy ... the first line of loop() is indented properly and then all the serial.print statements are badly indented ... my guess is that you added the badly formatted code


text:
Get production count for current minute
I am trying to make a production counter for a machine. I want to display production count of the last minute for each seconds. So, display should update every second and should display real value of last 60 seconds.  I have a system for detect real-time product output and get it to the Arduino using digital input pin.
I wrote below codes and for that.
what I have done is count output and get output per second. Then store it on an array as separated value for each seconds. Every second the array updated and added new value for current second. At last add all count value of last 60 seconds and output as production rate of current minute.
My question is, Is there any easy and efficient way for do this without using few variables ?
    #define countSensor 8  //count sensor input

    uint8_t records[60];
    uint8_t countSensorState = 0;
    uint8_t totalCount = 0;
    uint8_t countOfLastSec = 0;
    uint8_t lastCount = 0;
    uint8_t lastMinCount;
    uint32_t preMills = 0;

    void setup() {
      Serial.begin(9600);
      //init sensor input pin
      pinMode(countSensor, INPUT_PULLUP); //change according to sensor type

      //clear random value of memory locations
      for (int i = 0; i < 60; i++) {
        records[i] = 0;
      }

    }

    void loop() {
      //get count at falling edge
      if (digitalRead(countSensor)^ countSensorState) {
        if (!digitalRead(countSensor)) {
          totalCount++;

        }
        countSensorState = digitalRead(countSensor);
      }
      //get count of last second
      if (millis() - preMills > 1000) {
        preMills = millis();
        countOfLastSec = totalCount - lastCount;
        lastCount = totalCount;
        //record last 60s counts
        //--shift back a second in the array
        for (int i = 0; i < 59; i++) {
          records[i] = records[i + 1];
        }
        //--record current second in array at 59th index
        records[59] = countOfLastSec;
        //get last 60s count
        for (int i = 0; i < 60; i++) {
          lastMinCount += records[i];
        }
        Serial.println(lastMinCount);
      }

    }

If you really need the total of the last 60 seconds, then yes, you have to store that array. If you can live with something like an exponentially weighted moving average, then only the previous value of the average has to be stored.

you don't need to shift the values .... index the array in circular manner

@jsotola I couldn't get it correctly. How can I apply circular array to my code? Could you give me a modified code...

right now you use for loop to iterate the array using a pointer i ....  remove the for statement ... use i++ every second instead ... count 0 1 2.. 59 0 1 2 ....

As I said in a comment, if you really need to compute that moving sum,
you absolutely need to store the last 60 one-second counts in memory.
That being said, there are a few small issues with this code for which I
would have some suggestions:

There is no point in storing totalCount. You do not really use it,
and it will eventually overflow.

You do not need to explicitly initialize all globals to zero, as that
is implicitly done by the runtime: it is a requirement of the
language.

Your are calling digitalRead(countSensor) three times in a row. The
logic for counting edges is sound as long as the three calls yield the
same result, but that is not guaranteed. It is safer to only read the
pin once per loop iteration.

Similarly, the two calls to millis() can yield different results,
and that will make your timings slightly off.

The condition millis() - preMills > 1000 will only fire when
1001 milliseconds have elapsed. Because of the way millis() works,
sometimes you will miss the 1001th millisecond, and process on the
1002nd millisecond. In order to avoid accumulating these small timing
errors, it is best to update preMills by always adding exactly 1000.

As pointed out by jsotola, you do not need to shift the array: you can
instead reuse the array cell that holds the data you do not need
anymore.

You do not need to perform the whole sum every time. You can instead
update the previously computed sum by removing the count of the second
that falls off the current one-minute window, and adding the count of
the current second.

Here is my attempt at applying all the above suggestions. Warning: it
has not been tested.
const uint8_t countSensor = 8;

uint8_t record[60];       // last 60 one-second counts
uint8_t currentIndex;     // current index in record[]
uint8_t oldSensorState;   // previous state of countSensor input
uint32_t previousSecond;  // last time we printed minuteCount
uint8_t thisSecondCount;  // count of items in the current second
uint16_t minuteCount;     // count of items in the last minute

void setup() {
    Serial.begin(9600);
    pinMode(countSensor, INPUT_PULLUP);
}

void loop() {
    // Count falling edges.
    uint8_t sensorState = digitalRead(countSensor);
    if (oldSensorState == HIGH && sensorState == LOW) {
        thisSecondCount++;
    }
    oldSensorState = sensorState;

    // Update stats every full second.
    if (millis() - previousSecond >= 1000) {
        previousSecond += 1000;

        // Update minuteCount by removing the second that falls off
        // the window and adding the one that enters the window.
        minuteCount += thisSecondCount - record[currentIndex];

        // Replace the count that is not needed anymore by
        // the current one.
        record[currentIndex] = thisSecondCount;

        // Start counting a new second.
        thisSecondCount = 0;

        // Update current index, wrapping at 60.
        if (++currentIndex >= 60) {
            currentIndex = 0;
        }

        Serial.println(minuteCount);
    }
}


text:
Reading ground signal from circuit
I am trying to detect whether a signal is high or low from an ESU LokSound 5 decoder for HO locomotives. My idea was to use one of the auxiliary pins used to drive an LED (AUX 3 in my case).

The problem is that these decoders are common positive rather than common negative, which means I can't directly connect AUX 3 to a digital pin on the Arduino and expect it to work flawlessly since it outputs a negative voltage rather than positive.
I'm trying my best to not use an op amp, as the locomotive I'm making this accessory for is already cramped. It sort of works if I directly connect it, but it is not smooth at all. I've tried using the built-in pull-up resistor, I've tried using an external pull-down resistor, I've tried using a resistor in line and I can't seem to figure out how to solve this without resorting to using an op-amp.

i think that you are misunderstanding how the circuit is wired ... one side of a lamp is connected to the +V ... the other side of the lamp is connected to an open collector AUX output ... the output gets pulled low to light a lamp .... connect arduino ground to decoder ground ... connect the AUX3 to arduino data pin ... do not connect lamp to AUX3 ... enable arduino internal pullup resistor .... AUX output acts like a switch that connects AUX to ground


text:
Is it safe to connect VCC to a data pin on Attiny chips?
I'm trying to make a compact prototype with Attiny2313A, and want to connect VCC to pin 18 with a push button as in the picture. Is it safe? Or do I need a resistor there?

As long as the pin is configured as input, its save. Though you need a pulldown resistor in that case, or your pin will be floating, when the button is not pressed

As mentioned by @chrisl, here you would need a pull-down resistor to make sure that pin was not high when the button was not pushed.
It is more typical to connect the button between the IO pin and ground since then you can use the built-in pull-up resistors to make sure the pin is high when the button is not pushed. (This chip only has built-in pull-ups, although some chips have pull-downs).

In some cases I'll series something like 150 Ohms with the I/O pin.  It's not enough resistance to negatively affect the function of the circuit (it is small fraction of the pullup resistance value), but it's enough to limit current to a reasonably safe level in case something goes wrong in software and the pin becomes configured to output high.

@timemage In practice, this is almost never necessary in ATTINY chips. If you were to somehow accidentally set the button pin to an OUTPUT pin and drive it high, and then press the button so that pin was shorted to ground, then the chip would quickly undervoltage reset, which would set the pin back to an input.


text:
Automate capturing photograph on ESP32-CAM
I want to capture photographs from the ESP32 camera, but not doing it manually. Specifically, when a signal is sent from a sensor, I want ESP32 to understand that, and start taking photographs automatically for some seconds. The main problem, is the automation. I have searched on the web a lot, but can't find any answers. I am not expecting answers with code -since this is difficult- rather than some sites that provide solution to my problem. Thank you.

What sensor are you using?

@PythonSchlange ultrasonic.

ping it with an esp8266 monitoring the sensor.

So what about using if(distance <= distance_when_triggered) capture_photo();. I'm not sure if you want to make multiple photos at once, but then you'd have to put capture_photo(); into a for-loop. If this is what you were looking for, I'd suggest learning the basics of C/C++, which will make programming Arduino a lot easier.

Please have a look https://github.com/Yurik72/ESPHap/tree/master/examples/ESPHAPCamera
The project has different things, but definetelly doing what you asked, captures photo by external event, command...

I'll take a look at it. Thanks!


text:
Is it advisable to use Serial.write in an ISR when loop() routinely uses Serial.read?
I do not know much electronics.
I have Nano v3 as I2C master, it reads 5-byte packets (of delimtted data) from PC's USB port, processes it and forwards it.
I now need to implement a way to signal PC if something went wrong down the line. I don't want to clutter I2C channel and its just a flag so I think interrupt is best for my purpose.
While writing the ISR function I am not sure if its advisable to write data using Serial, because loop might have read 2-3 bytes of the 5-byte message packet. And I don't know if it will overwrite data coming from PC or what...
What will happen if I Serial.write(0x1) (suddenly, in an ISR function) while loop() was reading data from same Serial?
I don't know how to test this myself.

Reading and writing of serial data are separate functions. When you .write() you just append the data to the TX buffer. When you .read() you just take the next character from the RX buffer.
All actual sending and receiving, and filling/emptying of the buffers is done inside the ISRs for the UART module.
That said, you really shouldn't use Serial inside an ISR. This is because the sending and receiving is done by an ISR, and if you are in your ISR then the sending can never happen until you leave your ISR.  For the odd occasional byte it's not really a problem, but if the TX buffer fills up Serial.write() will block until the TX ISR has sent some data - which won't happen since your ISR is blocking the TX ISR.
So it's best to avoid any Serial operations inside an ISR. Instead you would normally set flags and values in an ISR then check for those flags in loop() to report anything.

Roger that. Yeah I am writing just 1 byte and then error handling will take over. I'll mark as answer soon, thanks.


text:
Problem displaying data sent from Arduino Mega to Arduino Mrk1000 using serial communications
I've been doing a personal project.
The idea of the bigger project is to feed my fish using a robot.
My specific problem is that I would like to see some data from the various sensors that I will be adding. But at the moment I am wanting to be able to use serial communication between my 2 boards to transfer an integer from  my Mega board to my MKR1000 board, and then for my MKR1000 to connect to the WIFI where I can see the information on my phone from the IP address.
Below is the 2 pieces of code, first being for the Mega board, where intergers are turned into strings and then sent the Mrk1000.
The sencond piece of code is for the MKR1000. Main goal is to recieve the data from the Mega board and then diaplayed on the client (over WIFI).
FOR MEGA BAORD ------------------------------------------------------------------------------------------
            char str[4];
            char str1[4];
            char str2[4];
            char str3[4];
            char str4[4];

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

            void loop() {
              int value= 500; //this would be much more exciting if it was a sensor value
              int value1= 400;
              int value2= 300;
              int value3= 200;
              int value4= 100;

              itoa(value, str, 10); //Turn value into a character array
              itoa(value1, str1, 10);
              itoa(value2, str2, 10);
              itoa(value3, str3, 10);
              itoa(value4, str4, 10);
              Serial.write(str, 4);
              delay(10);
                Serial.write(str1, 4);
                delay(10);
                  Serial.write(str2, 4);
                  delay(10);
                    Serial.write(str3, 4);
                    delay(10);
                      Serial.write(str4, 4);
                      delay(10);

            }

FOR MRK1000 -----------------------------------------------------------------------------------------
            #include <SPI.h>
            #include <WiFi101.h>
            #include <stdio.h>
            #include <math.h>

            //#include "arduino_secrets.h"
            ///////please enter your sensitive data in the Secret tab/arduino_secrets.h
            char ssid[] = "";//SECRET_SSID;        // your network SSID (name)
            char pass[] ="";// SECRET_PASS;    // your network password (use for WPA,
            or use as key for WEP)
            int keyIndex = 0;                 // your network key Index number (needed only for WEP)

            char str[4];
            char str1[4];

            int status = WL_IDLE_STATUS;
            WiFiServer server(80);

            void setup() {
              Serial.begin(9600);      // initialize serial communication
              pinMode(6, OUTPUT);      // set the LED pin mode
              Serial1.begin(9600);

              // check for the presence of the shield:
              if (WiFi.status() == WL_NO_SHIELD) {
                Serial.println("WiFi shield not present");
                while (true);       // don't continue
              }

              // attempt to connect to WiFi network:
              while ( status != WL_CONNECTED) {
                Serial.print("Attempting to connect to Network named: ");
                Serial.println(ssid);                   // print the network name (SSID);

                // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
                status = WiFi.begin(ssid, pass);
                // wait 10 seconds for connection:
                delay(10000);
              }
              server.begin();                           // start the web server on port 80
            printWiFiStatus();                        // you're connected now, so print out the status
            }

            int x = 0;       int i = 0;
            void loop() {
              WiFiClient client = server.available();   // listen for incoming clients

              if (client) {                             // if you get a client,
                Serial.println("new client");           // print a message out the serial port
                String currentLine = "";                // make a String to hold incoming data from the client
                while (client.connected()) {            // loop while the client's connected
                  if (client.available()) {             // if there's bytes to read from the client,
                    char c = client.read();             // read a byte, then
                    Serial.write(c);                    // print it out the serial monitor
                    if (c == '\n') {                    // if the byte is a newline character

                        if (Serial1.available()) {
                            delay(100); //allows all serial sent to be received together
                            while(Serial1.available() && i<4) {
                              str[i++] = Serial1.read();
                            }
                          str[i++]='\0';
                        }

                      // if the current line is blank, you got two newline characters in a row.
                      // that's the end of the client HTTP request, so send a response:
                      if (currentLine.length() == 0) {
                        // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
                        // and a content-type so the client knows what's coming, then a blank line:
                        client.println("HTTP/1.1 200 OK");
                        client.println("Content-type:text/html");

                              //strcpy(str, "98993489");
                          int val = atoi(str);
                            //Serial.println(str,4);
                            client.print("str = ");
                            client.print(x);

                        client.println();
                        client.print(x);
                         client.println("
");

                        // the content of the HTTP response follows the header:
                        client.print("Click here turn the LED on pin 9 on
");
                        client.print("Click here turn the LED on pin 9 off
");

                        // The HTTP response ends with another blank line:
                        client.println();
                        // break out of the while loop:
                        break;
                      }
                      else {      // if you got a newline, then clear currentLine:
                        currentLine = "";
                      }
                    }
                    else if (c != '\r') {    // if you got anything else but a carriage return character,
                      currentLine += c;      // add it to the end of the currentLine
                    }

                    // Check to see if the client request was "GET /H" or "GET /L":
                    if (currentLine.endsWith("GET /H")) {
                      Serial.println("high");
                      digitalWrite(9, HIGH);               // GET /H turns the LED on

                      }
                    if (currentLine.endsWith("GET /L")) {
                      Serial.println("low");
                      digitalWrite(9, LOW);                // GET /L turns the LED off

                    }
                  }
                }
                // close the connection:
                client.stop();
                Serial.println("client disonnected");
                x++;
              }
            }

            void printWiFiStatus() {
              // print the SSID of the network you're attached to:
              Serial.print("SSID: ");
              Serial.println(WiFi.SSID());

              // print your WiFi shield's IP address:
              IPAddress ip = WiFi.localIP();
              Serial.print("IP Address: ");
              Serial.println(ip);

              // print the received signal strength:
              long rssi = WiFi.RSSI();
              Serial.print("signal strength (RSSI):");
              Serial.print(rssi);
              Serial.println(" dBm");
              // print where to go in a browser:
              Serial.print("To see this page in action, open a browser to http://");
              Serial.println(ip);
            }

And where exactly is your problem? With displaying over Wifi (on a Website hosted on the MRK?)? Or with the Serial communication?

with trying to display over wifi.

You're going about your sending all wrong. You don't need to convert anything. Just use Serial.println(val1); etc,  then read your serial up until the terminating \n.

3 MCU for this? ATmega2560, SAMD21 and ESP32?


text:
Can I use an accelerometer to measure the velocity of a car in a curve?
I am making an application that is used to measure the velocity, it has an accelerometer that measures the component acceleration in the XYZ-axis. When the car is moving just straight the measurement is ok, as only linear components are involved.
My doubt came when the car is on a curve, I am not sure if the accelerometer can measure correctly in such situation or if it is necessary to apply a gyroscope to measure any missing component.
The code snippet for measure the total acceleration is shown below, I measure the acceleration in each axis and I remove the gravitational to finally calculate the velocity and the speed
    float AccTotal_X = ((AcX - grav_X)*9.81);
    float AccTotal_Y = ((AcY - grav_Y)*9.81);
    float AccTotal_Z = ((AcZ - grav_Z)*9.81);

    float Vx = vx_0 + AccTotal_X*dt;
    vx_0 = Vx;
    float Vy = vy_0 + AccTotal_Y*dt;
    vy_0 = Vy;
    float Vz = vz_0 + AccTotal_Z*dt;
    vz_0 = Vz;

    speed_dt = sqrt(pow(Vx,2)+pow(Vy,2)+pow(Vz,2))*3.6;

What hardware are you using? Most accelerometers also include turn sensors. But there's a great range in quality of these things, from very inaccurate for $5 to highly accurate for $60000.

Note that the gravity only acts in one direction. You don't need to multiply with the gravity in all axes.

@PMF, I am using the MPU5060, it has both accelerometer and gyroscope, however, I am justing using the accelerometer to measure the acceleration linear to get the velocity.

@PMF about the gravity being multiplied in all axis is because depending on the inclination of the sensor on the plane, the gravity will be present in one or more axis

@GustavoDaSilvaGhedim Are you getting accurate results? Accelerometers usually have bias and noise which usually make them unsuitable to compute velocity by integrating their readings.

@Sacha for straight moviments the results have good accuracy, however, the problem comes when the vehicle is turning left or right, during such a situation the difference between reading and the true velocity is considerable

That's sure right. But you have to know which direction is down. Typically, that is obtained when the device is in a standstill.

You're probably better off on the physics (or maybe maths) stack, since you're getting into the realms of integrating angular acceleration and other complex topics that are far outside the realms of this stack.

I think the last line of the Wikipedia page on angular acceleration sums it up nicely: "In conclusion, the general relation between torque and angular acceleration is necessarily more complicated than that for force and linear acceleration"

Yes, you need the gyroscope. You can't determine the radius of the curve with the accelerometer only, but that is critical.

@SimSon, thank you for the answer, but do you know how could I represent it in the equation or which source could I find it, most sources that I read the just represent the linear case, there was none explaining about the the linear and circular in the same case

As long as the car does not slip or drift, the rotation angle of the car (gyroscope) equals the angel it passes around the curve's center. The same applies to angular velocity and acceleration. The equation is centripetal vs momentum: ma=mv^2/r or a=w^2*r

I found out the answer to the question in the following article SenSpeed: Sensing Driving Conditions to Estimate Vehicle Speed in Urban Environments
According to the article

When a vehicle makes a turn, it experiences a centripetal force, which
is related to its speed, angular speed and turning radius. Thus, by
utilizing the accelerometer and the gyroscope, we can derive the
tangential speed of a vehicle.

Therefore, just with the accelerometer is not possible to measure the velocity when an object is making a turn, it is necessary a gyroscope also.
The equation to measure the tangential velocity is:
v = Rω (1),
Where v is the tangential speed, R the radius of the curve and ω the angular speed.
As the centripetal acceleration is given by a = ω²R (2), reformulating (2) and substituting in (1), it is obtained:
v = a/ω (3).
Both a and ω are given by the accelerometer and the gyroscope respectively.


text:
connect USB keyboard to Arduino using clk and data wires
Edit:
What I'm looking for is some kind of library which could be used with an arduino to read the HID protocol output from the Data+ and Data- cables of the USB.
==========
If I cut the cable of a usb keyboard, plug in power and ground can I use the clk and data wires to read keystrokes into the Arduino? If so any pointers to libraries and schematics?
Simple I instructions? The "for dummies" version?
EDIT
Following some of the suggestions below I found this:
https://github.com/julianschuler/USBKeyboard
Which looks like what I want to do, basically hook up the lines into the arduinio and read from the keyboard using the HID protocol in this library.
EDIT 2
That doesn't do what I want. Does anyone know how this could be accomplished?

From what device do you want to read keystrokes? from an USB keyboard?

yes from the keyboard.

I think you can do this using an USB Host shield.

Which looks like what I want to do ... no it isn't ... read it again

If it is possible to make an AVR bit-bang the USB protocol as a device, it may also be possible as a host. Have you tried to find such a library or project?

@thebusybee I have not found one. That is what I'm asking for.

OK. It might be because everyone is using a USB host shield. And since the USB protocol is quite complicated, no-one wrote such a low-level library, most probably. -- Is it really not an option to use a non-USB keyboard? Is this a project for many users, or is it just for you in one "incarnation"?

USB doesn't have data and clock lines. It has a pair of data lines with inverted polarity (D+ and D-). The USB protocol is considerably more complex than you seem to imagine.
However there is a caveat: some keyboards have the ability to work in IBM PS/2 mode. For this you will need a USB to PS/2 adaptor (pictured below) and then use the PS2Keyboard.h library. Your mileage may vary, though, as not all keyboards will work.

Any place I can get information on this protocol? I don't want the adapter, I want to plug in the cables directly and manipulate the data.

I think you don't actually need the adapter. It should just connect the pins of the USB jack to the pins of the PS/2 plug. So you could just directly connect the lines to the Arduino. A very short google search gave some promising results

These adapters only work if the USB keyboard has a dual controller which understands the PS2 protocol as well as the HID USB protocol. (Most modern keyboards don't) I don't have one of those, and I am looking for a library or method for directly interfacing the HID protocol with an Arduino.

Then you will need to invest in a usb host shield.


text:
Calling class member from .h file
In .ino file I have a class defined (called IPmonitoring).Also, inside the same .ino file, I call a .h file ( which is located "above" class IPmonotoring).
When I try to call members of IPmonitoring inside .h file - I get an error, which usually I solve using extern, but seemingly it is not the same for classes.
What should be done ?
Guy

the class definition is then not included in the .h file. So normally you would define that class in another .h file and then let the first .h file include the second .h file with the class definition.

I don't know what you mean by "call a .h file."  You mean #include it?

You should not have code in a .h file unless it's inline or a template class.

@timemage - yes

You need to re-think your layout, and your usage of the .h file.

You should never have code in a .h file unless it is either inline or part of a template class.

A .h file should only contain hints about where other things are. Those things should then be in .cpp or .ino files.
For example your IPmonitoring class would be declared in a .h file, and defined (or implemented) in a .cpp file (or .ino file if you prefer). Any place you want to use that class you #include the .h file. In one place you may choose to create an instance of that class. It is that instance that you then reference with extern.
In the Arduino world it is common to create a single instance of the class in the class's .cpp file and extern it in the .h file so everywhere that you include the .h file instantly has access to that single instance of the object.
This is how most libraries are written.
For example:
// IPMonitoring.h

class IPMonitoring {
    public:
        void doStuff();
};

extern IPMonitoring ipMon;

And:
// IPMonitoring.cpp

#include <IPMonitoring.h>

IPMonitoring ipMon;

void IPMonitoring::doStuff() {
    // Do something
}

And finally:
// mySketch.ino

#include <IPMonitoring.h>

void setup() {
    ipMon.doSomething();
}

void loop() {
}

class templates are instantiated to create classes; likewise for function templates and functions.  The involvement of a template doesn't affect things beyond being an incentive to inline, since the export keyword never really took off and then was later removed from the standard.

Majenko  -Thank you. It all started as .ino file with functions. During writing the code I gathered all function into class, since I wanted 3 instances of it. And the .h file  gathers all the function I used for my wifi and MQTT of other class I'm constantly using... well thing started to get messy :)


text:
read first line from sd card and save the position for again reading from sd card
I am reading sd card .txt file, I want to read the first line then how to save the position of the pointer for the next line read?

You mean like using a variable to save the number of the current line? What have you tried so far? Please show the code, that you already have

You should not need to save the position, the file knows where you last read from. You'd only need to manually save such information if you close the file and re-open it again, which unless you have a good reason is actually a very wasteful operation.
If you really do need to you can use the .position() and .seek() functions:
Save the location:
uint32_t pos = myFile.position();

Recall the location:
myFile.seek(pos);

Documentation:

https://www.arduino.cc/en/Reference/FilePosition
https://www.arduino.cc/en/Reference/FileSeek

File myFile = SD.open("test.txt", O_RDWR);
if (myFile) {

  while (myFile.available()) {
    int i = 0;
    while (i < myFile.size()) {
      inputString =  myFile.readStringUntil('\n');
      //Serial.print(inputString);
      if (myFile.readStringUntil('\n')) {

I have set a size for the loop, every time it returns "I want it to read a new line" but it skips, what could be the reason?
To help with this question, I wanted to show the process I did on the same question. Thank you, I will ask the question elsewhere.
I am sending from the serial port when the end of the line is not read twice, during each reading. I'm sending line by line

Please ask questions as new questions rather than in an answer on another different question. After deleting this, when you create your new question, please be as specific and clear as possible (and maybe explain why you're doing two readStringUntils in a row).

evet dediğinizi anladım ve kaldırdım. Çok teşekkür ederim. işe yarıyor. cevabımı bir yere yazmak gerekirse bana bildiriniz ben oraya cevap olarak eklemek isterim.

Answering your own questions is perfectly fine :)