text:
declaration of 'varDay' as array of references error
I am trying to write a function to store the date and time data from an RTC module. I have used char arrays to implement the function. I get "declaration of 'varDay' as array of references" error upon compilation.
I am still learning about char arrays and manipulating them so may be I am making a very obvious mistake. Could you please explain what I am doing wrong?
#include <RTClib.h>

RTC_DS3231 rtc;

void setup() {
  Serial.begin(115200);
#ifndef ESP8266
  while (!Serial); // wait for serial port to connect. Needed for native USB
#endif

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    Serial.flush();
    abort();
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, let's set the time!");
    // When time needs to be set on a new device, or after a power loss, the
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
  }

}

void loop() {
  unsigned long newTime = millis();
  static unsigned long oldTime = 0;

  char varYear [] = "1234";
  char varMonth [] = "00";
  char varDay [] = "00";
  char varHour [] = "00";
  char varMinute [] = "00";
  char varSecond [] = "00";
  unsigned int varEpoch;
  char varDate [] = "123456789";
  char varTime [] = "12345678";
  char dash [] = "-";
  char colon [] = ":";

  if (newTime - oldTime >= 60000) {
    oldTime = newTime;

    getDate(varDay, varMonth, varYear, varDate, dash, colon);
  }

}
void getDate (char &varDay[3], char &varMonth[3], char &varYear[5], char &varDate[11], char &dash[2], char &colon[2]) {

  DateTime now = rtc.now();
  strcpy (varDay, now.day());
  strcpy (varMonth, now.month());
  strcpy (varYear, now.year());

  strcat (varDate, varDay) ;
  strcat (varDate, dash);
  strcat (varDate, varMonth);
  strcat (varDate, dash);
  strcat (varDate, varYear)

  Serial.println(varDate);
}

char &varDay[3] is an array of 3 references to type char, not a reference to type char of size 3.
Instead just pass a pointer:
void getDate (char *varDay, char *varMonth, char *varYear, char *varDate, char *dash[2], char *colon[2]) {

Also:
strcpy (varDay, now.day());
strcpy (varMonth, now.month());
strcpy (varYear, now.year());

That won't work. You can't copy a number into a string. now.day() etc need converting to a string first.
It would be better to format your string with snprintf:
snprintf(varDate, 11, "%02d-%02d-%04d", now.day(), now.month(), now.year());

Thanks a lot. I read your post "Evils of Arduino Strings" so was trying to implement this without using String class. So it was my first attempt dealing with char arrays. I didn't know about snprintf function so learnt something new :) still a lot more to learn though


text:
Difference in increment & decrement loop execution speed
I was experimenting with for loops when I noticed that a simple increment loop executes faster than a decrement loop. I can't think of any reason why it should be like that. Is there something in my code that is causing the different in execution speed?
The code is as follows:
// Global Variables
const int spk = 7;
const int led = 6;
int j = 0; // counter variable

void setup() {

  pinMode(spk, OUTPUT);
  pinMode(led, OUTPUT);
  Serial.begin(9600);
} // end of setup

void loop() {

  tone(spk, 300, 500); // first note with duration

  // increment loop
  for (j=0; j <= 500; j = j + 1) {
    digitalWrite(led, HIGH);
    Serial.println(j);
  } // end 1st note loop

  tone(spk, 100, 500); // second note with duration

  // decrement loop

  for (j = 500; j >= 0; j=j-1) {
    digitalWrite(led, LOW);
    Serial.print("the value is=");
    Serial.print("\t");
    Serial.println(j);
  } // end 2nd Note loop

} // end setup

Comment out these 2 lines
Serial.print("the value is=");
Serial.print("\t");

And report back on the speed difference.
Why not add a reading of micros() before and after each loop and see how much difference there really is?  All time variables are unsigned long.
startTime = micros();
// your loop
endTime =  micros();
duration = endTime - startTime;
Serial.println (" "); // line break
Serial.print ("duration in uS = ");
Serial.println (duration);

I edited to add some missing )s and a 2nd line break.

Yes the extra serial prints in the decrement loop were adding the extra time. However, after adding the mircros before and after each loop and removing all extra print statements I still find the decrement loop takes 60  to 80 microsecond longer. Is it usual?

I don't know.  I don't think I've ever used a decrementing for:next loop.  Might also be something with setting a pin low vs high.  You could try fastdigitalWrite() instead, see if that makes a difference (in the IDE already? maybe have to pull it from guthub?).  There is a way to look at the assembly code that is created, see what is actually being run.  Nick Gammon used to post examples like that, not sure how he got the assembly out of the compile process.

Ah it's fine :) Doesn't really make that big of a difference for now. Going after the assembly code would be too complicated and don't even know how to go about it.

In the code you posted, the decrement loop has two more Serial.print() statements.
Serial.print() takes a lot of time and while it's useful for debugging, it sometimes can cause additional bugs because of the extra delay it introduces if you are running time-sensitive code.
Consider for using Serial.print("the value is=\t" + itoa(j,10));
"itoa" converts an integer to an array of characters (aka string). As Juraj said, it takes another two arguments which are the buffer to store the output string and the base to which it converts the incoming number to be represented by (eg: 10 is decimal, 16 is hexadecimal). It returns a pointer to the output string which is essentially the same as the second argument but AFAIR you can omit the second argument and use it's return value.

+ doesn't concatenate char arrays. itoa has more parameters

source: Stack Exchange

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

sort: votes


text:
State machine problem
I am trying to record the pulses from a water flow sensor using a state machine. My goal is to count the pulses until the flow stops (i.e. the rotor inside comes to rest). This will constitute a single reading. if there is no new pulse/interrupt 5 seconds after the rotor is stopped, the total pulse count is printed and pulse count is reset to zero for the subsequent readings.
However, in practice, I get a pulse count even when the sensor rotor is moving. The pulse count gets resets after 5 sec but the pulses between the new reading and until the rotor is stopped are somehow missed.
Could you please help me figure what am I doing wrong?
#include <Arduino.h>
#include <TelnetStream.h>

const byte pulsePin = 22;
byte volatile triggerCounter = 0;

byte newState = 0;

unsigned long newTime = 0;
unsigned long oldTime = 0;

unsigned long pulseCountNew = 0;

portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;

void IRAM_ATTR handleInterrupt()
{
  portENTER_CRITICAL_ISR(&mux);
  triggerCounter++;
  portEXIT_CRITICAL_ISR(&mux);
}

void stateMachine()
{

  switch (newState)
  {

  case 0 /* Reset */:
    newState = 1;

    break;

  case 1 /* Start */:

    if (triggerCounter > 0)
    {
      newState = 2;
    }
    break;

  case 2 /* Pulse count start */:

    pulseCountNew++;
    triggerCounter--;
    newTime = millis();
    newState = 3;

    break;

  case 3 /* Pulse count stop */:

    if (triggerCounter > 0)
    {
      newState = 2;
    }

    if (newTime - oldTime >= 5000)
    {
      oldTime = newTime;
      newState = 4;
    }
    break;

  case 4 /* Cycle complete */:
    newState = 0;
    TelnetStream.println("State 4");

    break;
  }
}

void setup()
{
  pinMode(pulsePin, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(pulsePin), handleInterrupt, FALLING);
  TelnetStream.begin();
}

void loop()
{

  if (newState == 4)
  {

    TelnetStream.println(pulseCountNew);
    pulseCountNew = 0;
  }

  stateMachine();
}

The pulse count gets resets after 5 sec ... don't reset the counter ... refer to how millis() is used

do you have less than 255 readings in one batch? you use byte

The code will have a mich better readability if you use makros or an enum for the state, so you can have something like case RESET:...

You should have all code that is relevant for the state machine in the switch block. The TelnetStream.println() might be ok in thw loop(), but pulseCountNew=0 should be in case 4.

triggerCounter is declared as byte, so it can't become negative. The statements triggerCounter-- and if(triggerCounter>0) are error prone and probably don't what you expect.

@SimSon I didn't know about enum but you are right. Need to learn it's  usage

@Juraj I suppose you are talking about trigger counter being declared as type byte. Since in the state 2, the trigger will be decremented so I thought the count wouldn't go as high as 255. But thinking about it now I assume that may happen

yes it is possible to always take the value, add it to total and reset. I don't know how fast the value increments in your project. using byte is good because the operations are atomic and don't require to block interrupts. but using larger type allows spending more time in loop without checking the counter and that helps if you do networking.

I do this usually without an extra state variable.
unsigned long readSensor() {
  const unsigned long READING_TIMEOUT_MILLIS = 5000;
  static unsigned long lastReadingMillis;
  static unsigned long lastCounterValue;

  noInterrupts();
  unsigned long counter = triggerCounter;
  interrupts();

  if (counter != lastCounterValue) { // if new reading
    lastReadingMillis = millis(); // reset timout timer
    lastCounterValue = counter;
  } else if (counter > 0 && (millis() - lastReadingMillis) > READING_TIMEOUT_MILLIS) { // if something was counted and is timeout
    noInterrupts();
    triggerCounter = 0;
    interrupts();
    lastCounterValue = 0;
    lastReadingMillis = 0;
    return counter;
  }
  return 0;
}

void loop() {
  unsigned long value = readSensor();
  if (value) {
    Serial.println(value);
  }
}

sorry, the code is not tested.

I thought using a simple state machine would be simpler than using  multiple conditional statements. However, your example is much more compact.

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


text:
Timeout error with Arduino Mega and ESP8266 as the wifi module
I am trying to use the ESP8266 as the wifi module based on this tutorial. My connections are as follows:
ESP8266 <-----------------> Arduino Mega
VCC     ------------------> 3.3V (converted 5V from Mega to 3.3V using LD33V)
CH_PD   ------------------> 3.3V
GND     ------------------> GND
RX      ------------------> TX1(Pin 18)
TX      ------------------> RX1(Pin 19)

I have checked the baud rate by issuing the AT commands at 115200 baudrate and the ESP is responding. Below is my code which I am trying to use:
#include "WiFiEsp.h"
#include <PubSubClient.h>

const char* ssid = "MySSID";
const char* password = "MyPassword";
int status = WL_IDLE_STATUS; //wifi radio's status
byte* messageBuff;

//MQTT
const char* mqtt_server = "192.xxx.x.xxx";
//const char* mqtt_topic = "Rpi_Master";
const char* mqtt_username = "username";
const char* mqtt_password = "password";
//client Id
const char* clientID = "A_1";

//Variables for numbers
long randNumber1;
String rn1;
char rn1_char[50];
long randNumber2;
String rn2;
char rn2_char[50];
long randNumber3;
String rn3;
char rn3_char[50];
long randNumber4;
String rn4;
char rn4_char[50];
long randNumber5;
String rn5;
char rn5_char[50];
long randNumber6;
String rn6;
char rn6_char[50];

WiFiEspClient wifiClient;
PubSubClient client(mqtt_server, 1883, wifiClient); //1883 is the listener port for the broker

void callback(char* topic, byte* payload, unsigned int length) {

    Serial.print("Message Received: [");
    Serial.print(topic);
    Serial.println("]");
    Serial.print("Message is:");
    String message = (char *)payload;
    Serial.println(message);

    Serial.println();
    if (!strncmp((char *)payload, "Start", length)) //Start code can be changed to any string value in place of 1
    {
      randomNumberGenerator();
      client.publish("Arduino_A", "OK");
    }

}

void reconnect() {
  //Loop until we are reconnected
  while (!client.connected())
  {
    Serial.print("Attempting MQTT Connection...");
    //Attempt to Connect
    if (client.connect(clientID, mqtt_username, mqtt_password))
    {
      Serial.println("connected");
      //Once connected publish an announcement
      client.publish("Arduino_A", "Please send the pass code to send the values");
      //and resubscribe
      client.subscribe("Rpi_Master"); //This name can be changed
    }
    else
    {
      Serial.print("failed, rc = ");
      Serial.print(client.state());
      Serial.println("Trying again in 5 seconds");
      //Wait for 5 seconds before retrying
      delay(5000);
    }
  }
}

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

  //initilize the ESP module
  WiFi.init(&Serial1);
  Serial.println("Attempting to connect to WPA network");
  status = WiFi.begin(ssid, password);
  //if you are not connected stop here
  if (status != WL_CONNECTED)
  {
    Serial.println("Couldn't get a wifi network");
    while (true);
  }
  //if you are connected, print out the info about the connection
  else
  {
    Serial.println("Connected to the network");
  }
  //client.setServer(server, 1883);
  client.setCallback(callback);
  //Allow the hardware to sort itself
  delay(1500);
  randomSeed(25);
}

void loop() {
  if (!client.connected())
  {
    reconnect();
  }
  //delay(1000);
  client.loop();
  delay(50);
}

void randomNumberGenerator()
{
    randNumber1 = random(10,20);
    Serial.println(randNumber1); // print a random number from 0to 299
    rn1 = String(randNumber1);
    rn1.toCharArray(rn1_char, rn1.length() + 1);
    randNumber2 = random(20, 30);// print a random number from 10 to 19
    Serial.println (randNumber2);
    rn2 = String(randNumber2);
    rn2.toCharArray(rn2_char, rn2.length() + 1);
    randNumber3 = random(30,40);
    Serial.println(randNumber3);
    rn3 = String(randNumber3);
    rn3.toCharArray(rn3_char, rn1.length() + 1);
    randNumber4 = random (40,50);
    Serial.println(randNumber4);
    rn4 = String(randNumber4);
    rn4.toCharArray(rn4_char, rn4.length() + 1);
    randNumber5 = random (50,60);
    Serial.println(randNumber5);
    rn5 = String(randNumber5);
    rn5.toCharArray(rn5_char, rn5.length() + 1);
    randNumber6 = random (60,70);
    Serial.println(randNumber6);
    rn6 = String(randNumber6);
    rn6.toCharArray(rn6_char, rn6.length() + 1);
    client.publish("LC_1", rn1_char);
    client.publish("LC_2", rn2_char);
    client.publish("LC_3", rn3_char);
    client.publish("LC_4", rn4_char);
    client.publish("LC_5", rn5_char);
    client.publish("LC_6", rn6_char);
    client.publish("Arduino_A", "End Transaction");
}

Currently am using this code to send 6 random values whenever there is a request being sent from the broker over MQTT. I intend to replace this code once the error issue is resolved. The code works fine and the ESP connects to the broker (Raspberry Pi in my case) initially. However after some time I keep getting Timeout Error and the ESP8266 keeps diconnecting from the server.
I read in other forums that ESP8266 will not be handle high baudrates such as 115200 and should be set to 9600. Could this be a reason for the timeout error? Please let me know what changes I need to rectify this issue. Thanks a lot for your time in advance. Attached the screenshot of the error.

The old WiFiEsp by Bruno Poltaruri library can't do much with larger data received. The AT firmware sends all the data at once and the serial RX buffer overflows. It works better with 9600 baud which slows down the AT firmware.
It is hard to receive more data over network with AT firmware without UART hardware flow control and Arduino AVR boards don't have flow control and simple esp8266 modules don't have the flow control pins exposed.
My new WiFiEspAT library uses the new passive receive mode implemented in AT firmware 1.7.0 (SDK 3). The new passive receive mode of the AT firmware is not supported for UDP and secure connection (SSL) yet. For this reason in the new library UDP received message size is limited to configured buffer size and secure connection (SSL, https) is not supported.
With my new library over hardware serial high baud rates can be used. For Arduino Mega 500000 baud works good. For example a WebServer serving web files from SD card requires high baud rate to be able to serve multiple files one after other fast enough.

Thanks Juraj. Will try it out.

@Prashant, did the answer help?


text:
Parsing JSON response from Stream
I want to parse JSON response from a GET Request. I do this usually by using a String variable to store the response and later parse this string using ArduinoJSON library like shown below:
#include <Arduino.h>
#include "OTA.h"
#include "Credentials.h"
#include <HTTPClient.h>
#include <ArduinoJson.h>

const char url[] = "http://date.jsontest.com/";

HTTPClient getClient;

void getRequest(String &payload)
{
  getClient.begin(url);

  int httpCode = getClient.GET();

  if (httpCode > 0)
  {
    payload = getClient.getString();
    // Serial.print("HTTP Status: ");
    // Serial.println(httpCode);
  }
  else
  {
    Serial.println("Error on HTTP request");
  }
  getClient.end();
}

void parseResponse(String &payload)
{

  StaticJsonDocument<128> doc;

  DeserializationError error = deserializeJson(doc, payload);

  if (error)
  {
    Serial.print("deserializeJson() failed: ");
    Serial.println(error.c_str());
    return;
  }

  const char *time = doc["time"]; // "03:53:25 AM"
  // unsigned long *epoch = doc["milliseconds_since_epoch"]; // 1362196405309
  const char *date = doc["date"]; // "03-02-2013"

  Serial.println(date);
}

void setup()
{
  setupOTA("ESP-N2", mySSID, myPASSWORD);

  Serial.begin(115200);
}

void loop()
{
  ArduinoOTA.handle();

  unsigned long newTime = millis();
  static unsigned long oldTime = 0;
  String payload;

  if (newTime - oldTime >= 5000)
  {
    oldTime = newTime;
    getRequest(payload);
    parseResponse(payload);
    Serial.println();
  }
}

I want to avoid using String and ArduinoJSON offician reference page mentions that it's possible to deserialize directly from input Stream e.g. wifiClient, ethernetclient or serial but I couldn't find any example showing it's usage. So I am curious to learn how to use it.
From my basic understanding of a Stream, I suppose I need define a buffer or memory location that will hold the incoming bytes and using the address of this buffer need to read data bit by bit. So  do I need to do something like this:
char buffer[]= httpClient.getStream();

and then pass this buffer as input to deserialize function? or have I gotten it completely wrong?

https://arduinojson.org/v6/how-to/use-arduinojson-with-httpclient/

httpClient.getStream() returns an instance of Stream that you can pass to deserializeJson(), like so:
deserializeJson(doc, httpClient.getStream());

However, by doing so, you bypass the code in HTTPClient that handles chunked transfer encoding, so you must call httpClient.useHTTP10(true) before calling GET to make sure the server won't return a chunked response.
See How to use ArduinoJson with HTTPClient?

Thanks a lot for the explanation. I am happy to learn the Stream usage. It works well but I also get                                                                                [D][HTTPClient.cpp:378] disconnect(): still data in buffer (1), clean up.
[D][HTTPClient.cpp:387] disconnect(): tcp stop.                                                                               Since I am reading all the stream data, which data it might be referring to? Can it cause an issue like memory leakage or fragmentation?

I added ChunkedStreamReader to my StreamLib. it wraps an input Stream and decodes the chunked input:  https://github.com/jandrassy/StreamLib/blob/b9b31e7908479efd0149940df9de610439532506/examples/Advanced/ReadChunkedJSON/ReadChunkedJSON.ino#L36

I followed the approach mentioned in the docs but it seems that my GET requests fail when I use http1.0. My server is running on aws (amplify) and uses http2. What should I do in this case?


text:
is it necessary to include libraries that are specified in the header file already?
I am using the Adafruit BME280 library in my sketch. In the example sketches, they have included the Wire, SPI and the Adafruit_Sensor library. However, I see that in the Adafruit_BME280 library header file, these libraries are already included. So I tried commenting out them in my sketch and it still works. So I wonder if there are still cases or any specific reason to include them twice?
Additionally, if a library is included/referenced twice like mentioned above, wouldn't it increase the size of the sketch unnecessarily?

Example Sketch that comes with the library
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BME280.h>

#define BME_SCK 13
#define BME_MISO 12
#define BME_MOSI 11
#define BME_CS 10

#define SEALEVELPRESSURE_HPA (1013.25)

Adafruit_BME280 bme; // I2C
//Adafruit_BME280 bme(BME_CS); // hardware SPI
//Adafruit_BME280 bme(BME_CS, BME_MOSI, BME_MISO, BME_SCK); // software SPI

unsigned long delayTime;

void setup() {
    Serial.begin(9600);
    while(!Serial);    // time to get serial running
    Serial.println(F("BME280 test"));

    unsigned status;

    // default settings
    status = bme.begin();
    // You can also pass in a Wire library object like &Wire2
    // status = bme.begin(0x76, &Wire2)
    if (!status) {
        Serial.println("Could not find a valid BME280 sensor, check wiring, address, sensor ID!");
        Serial.print("SensorID was: 0x"); Serial.println(bme.sensorID(),16);
        Serial.print("        ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n");
        Serial.print("   ID of 0x56-0x58 represents a BMP 280,\n");
        Serial.print("        ID of 0x60 represents a BME 280.\n");
        Serial.print("        ID of 0x61 represents a BME 680.\n");
        while (1) delay(10);
    }

    Serial.println("-- Default Test --");
    delayTime = 1000;

    Serial.println();
}

void loop() {
    printValues();
    delay(delayTime);
}

void printValues() {
    Serial.print("Temperature = ");
    Serial.print(bme.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");

    Serial.print(bme.readPressure() / 100.0F);
    Serial.println(" hPa");

    Serial.print("Approx. Altitude = ");
    Serial.print(bme.readAltitude(SEALEVELPRESSURE_HPA));
    Serial.println(" m");

    Serial.print("Humidity = ");
    Serial.print(bme.readHumidity());
    Serial.println(" %");

    Serial.println();
}

it is not necessary now. in the past it was necessary to include all used libraries in the main sketch file.

It doesn’t use any extra code space.  There is an include guard on any decent library that stops it actually being included twice.

Actually, the first two lines in the include file (#ifndef __BME280_H__,  #define __BME280_H__ .... and the #endif on the last line of the file prevent it from being processed twice, so it doesn't matter how many times your code tries to #include it. All or most include files from libraries work the same way.

Historically it was necessary, yes. In times past the IDE would look only in your sketch to find the list of libraries to compile and link. However much progress has been made in recursive library searching, whereby the IDE can now find libraries that are included by other libraries.
I am not sure when that change was implemented, but it was a long time coming and is only recently that it's worked.
So if you are distributing code for other people to use then it's a good idea to still add the libraries in the sketch - just in case they're using an older version of the IDE that can't find the libraries included by other libraries.

Thanks for the answer. But what about the memory usage if libraries are added twice?

I don't understand what you're asking. You mean the memory usage of your computer?

I meant size of the sketch and required memory (SRAM and/or Flash) on the MCU if the library is added once in the sketch and once called by another library. Usually when libraries are included the sketch size increases. But I suppose the compiler would be smart enough to see the duplication.

Oh, I see. The compiler doesn't need to be "smart enough" to "see" the duplication. There is no duplication. Added is added. You can't add the same apple to a bowl twice - no matter how many times you put it in the bowl it's the same apple. A library is a library. It's a single item. Referencing it multiple times in multiple places is still just the one library.

@Zaffresky, the library is not the .h file. the library is added to build because the include is detected in the source code. this is what the Arduino builder does for you. In normal C++ tools you must list the libraries in the makefile.

@Zaffresky: "But what about the memory usage if libraries are added twice?" If a global is defined (not just declared) in a .h file and the .h file lacks include-guards, then that global would be multiply-defined. But the .h file doesn't actually pull in the library code and data; the linker does that in order to satisfy references to definitions the library contains. When the library has been added, all program references to anything in it are now satisfied, so the linker never needs to pull it in a second time.

@JRobert Thanks for clarifying. Makes sense :)


text:
How to use more than 2 I2S microphones on MKR Zero?
I am trying to build a portable device that can record from at least 3 microphones. I had a look and saw I2S is good for audio so I bought an Arduino MKR Zero to read them with. I was wondering how to record from multiple microphones on the I2S bus at once. The only thing that I have been able to do is record stereo from two mics but I need the microphone readings to be mono. I am using the Adafruit I2S MEMS Microphone SPH0645LM4H.

By definition, the I2S bus only allows up to 2 channels to be transmitted at the same time.  Here is a quote from the Details section of the Wikipedia's I2S page:

The word select clock lets the device know whether channel 0 or
  channel 1 is currently being sent, because I²S allows two channels to
  be sent on the same data line.

This is further illustrated in Figure 8 / Page 6 of the Knowles SPH0645LM4H data specifications.  In this figure we see where 2 SPH0645LM4H microphones are configured (ground or Vcc to the SEL pin 2) such that they can be multiplexed onto the I2S bus by the I2S bus master.


text:
How to calibrate an inclined MPU 6050 on Arduino?
I'm trying to use the MPU 6050 sensor (gyroscope + accelerometer) with my Arduino UNO to get some data when walking, running and making some other moves while carrying it. The problem is that my welding makes the sensor stay inclined. The first photo is from the sensor and the second from the 3-D visualization using the Processing IDE:

Is there a way to calibrate the sensor to "act as if it were straight" based on its reads when inclined on the breadboard (as shown in the photo)? I am still a beginner with Arduino, so sorry if this is a silly question/problem.

Can you show us the sketch you're using?

your question is not about the Arduino ... it is about a Processing program ... just subtract the tilt before displaying the data


text:
difference between the nano and the nano every
So I wondered what the difference between the nano and the nano every is and why the nano every is so much cheaper than the nano.
I'm new to the microcontroller business and I would like to know what would be better for what situation.

The classic Nano has ATmega 328p MCU, same as Uno. The 328p is classic AVR ATmega as used in Arduinos from the start and before in many AVR MCU projects for over 20 years now. There is large knowlege base for this MCUs, many ready codes in form of libraries, snippets, tutorials.
The Nano Every and Uno WiFi Rev 2 use a modern version of the AVR based MCU a so called megaAVR_0-series, an ATmega4809. It uses the same AVR CPU architecture in core of the MCU so the compiler is the same as for 328p and co., but the MCU peripherals configuration is very different then in the classic ATmegas. So the old knowledge base about AVR MCU peripherals doesn't help here.
The lower price is not related to manufacturing costs. The possible reasons are:

better price by MCU manufacturer at introduction of the new MCU family to market
higher price of classic Nano because it is popular and together with classic Uno founds Arduino as company
getting the new chip to Arduino power users to build up the knowledge and code base for the new MCU

To mention some more differences of classic Nano and Nano Every: Nano uses a bootloader for sketch upload and an external USB chip for USB communication. Nano Every doesn't use a bootloader, it has an on board UPDI programmer in form of a small SAMD MCU which serves as USB adapter for serial communication too.


text:
Arduino Serial Communication possible with IDE 1.8.5 but not with IDE 1.8.13
I have the following problem: I am working with an Arduino Nano 33 IoT and a second serial interface via sercom0. The code is just taken from this tutorial:
http://www.getmicros.net/serial-communication-on-the-arduino-nano-iot.php
In loop, I just print the input from my serial connection to the standard serial connection. The input comes from a ozon sensor that sends data packages every single second.
Now when I program the arduino with my Laptop, my IDE version being 1.8.5, it works well, but when I use my PC with a newer version (IDE 1.8.13), it doesn't work any more. The code is the same, the cable and the arduino are the same, the only difference is the PC. But when I try to use an hyperterminal to print the data packages recieved from the sensor, both the Laptop and the PC receive the correct packages. Somehow, the Arduino or the difference in IDE versions causes the communication to fail....
Does anyone have experience with this error?

"this error" Are you getting an actual error message?  If so, what is it?

If you program on your laptop then plug into your PC does it work? How about the other way around?

Serial1 is there for pins labeled RX/TX. the boards package version is independent from IDE version so IDE version doesn't give any useful information here.

I am not getting an error message since for both cases, data is being revied by the arduino. The problem is that the data is different when I use the serial interface on my PC.
No, sadly programming it on my Laptop and then plugging it into my PC does not work...
I don't really understand what you mean, Serial1 is not being used. I use the normal Serial for sending the data to the PC or Laptop and the sercom0 interface for reading in the sensor values.


text:
snprintf doesn't display float values
I don't understand why the formatted string is displaying ?? instead of float values.
My code:
#include <Arduino.h>
#include <Wire.h>
#include "SparkFunCCS811.h"
#include <DFRobot_SHT3x.h>

DFRobot_SHT3x sht3x(&Wire, /*address=*/0x44, /*RST=*/4);

//* Get SHT31 readings

void readSHT(float &temp, float &humid)
{

    DFRobot_SHT3x::sRHAndTemp_t data = sht3x.readTemperatureAndHumidity(sht3x.eRepeatability_High);

    char shtVal[50];

    if (data.ERR == 0)
    {
        temp = data.TemperatureC;
        humid = data.Humidity;

        Serial.println(data.TemperatureC);
        Serial.println(data.Humidity);
    }

    snprintf(shtVal, 50, "Temp = %f  Humidity = %f", temp, humid);
    Serial.println(shtVal);
}

void setup()
{

    Serial.begin(115200);

    //*Initialize the chip
    while (sht3x.begin() != 0)
    {
        Serial.println("SHT31 Initialization Failed");
        delay(1000);

        Serial.print("Chip serial number");
        Serial.println(sht3x.readSerialNumber());

        if (!sht3x.softReset())
        {

            Serial.println("Failed to Initialize the chip....");
        }
    }
}

void loop()
{

    unsigned long newTime = millis();
    static unsigned long oldTime = 0;

    if (newTime - oldTime >= 5000)
    {

        float temp = 0.0;
        float humid = 0.0;

        oldTime = newTime;

        readSHT(temp, humid);
    }
}

& here is the output:
Here is what I get as output:
21.23
41.06
Temp = ?  Humidity = ?

The function readSHT()has no problem displaying the actual values but why the formatted string shows ???. Am I doing something wrong?

The standard avr-libc does not have float support enabled in the printf family of functions. This is because float support would bloat your code massively, and most people don't need it.
It is possible to enable it through some black magic (I don't know what, but someone else may), but in general you don't want to since there are better ways.
Typically you would use dtostrf() to format your float into a char array separately. Or if all you are doing is printing to serial then you wouldn't even format it into a string in the first place.
Serial.print(F("Temp = "));
Serial.print(temp);
Serial.print(F("  Humidity = "));
Serial.println(humid);

Ah Ok. I will use dtostrf () as I need to pass these values to another function as well. This way I can store the value with suitable no. of decimal places.


text:
Boolean variable with if statement
I am trying to use boolean variables with two if statements. The second if condition never evaluates to be true. May be it's a problem with how I have defined my boolean variables. Do you see the mistake?
Here is the code:
int x = 0;
boolean state1 = (x <= 10);
boolean state2 = (x > 10);

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

void loop() {

  x++;

  if (state1) {
    Serial.println("x <= 10");
  } else if (state2) {
    Serial.println(" x > 10");
  }

}

You never update your state variables. When you assign in C you assign the result of the formula, not the formula itself.

I was trying to assign the two conditions to the boolean variables so yes like you said I was assigning the formula.

This question does not concern the Arduino but is a general programming question.

I asked this question to be moved to Stackoverflow as it is not Arduino related.
However to answer your question, you assign the booleans before you start the program, so they are never re-evaluated and always keep their initial value, based on when x = 0.
What you should do is, reevaluate them within the loop:
int x = 0;
boolean state1;
boolean state2;

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

void loop() {
  x++;
  state1 = (x <= 10);
  state2 = (x > 10);
  if (state1) {
    Serial.println("x <= 10");
  } else if (state2) {
    Serial.println(" x > 10");
  }
}

Also, because if state1 is true, state2 will always be false and vice versa, so you don't need to have two booleans. This will give:
int x = 0;
boolean state;

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

void loop() {
  x++;
  state = (x <= 10);
  if (state) {
    Serial.println("x <= 10");
  } else {
    Serial.println(" x > 10");
  }
}

Beyond that, you don't need to define the boolean globally, because you only need it inside the loop and is not need to be 'stored' from one loop to another. So you get
int x = 0;

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

void loop() {
  x++;
  boolean state = (x <= 10);
  if (state) {
    Serial.println("x <= 10");
  } else {
    Serial.println(" x > 10");
  }
}

Of course you can also directly check for x <= 10 instead of storing it in a boolean, but I assume you need the boolean elsewhere further within the loop function later.

Yes I see the issue now. I saw a few sketches where boolean variables were used in if statement and thought that I could use them to store the conditions itself. I was assuming that since the condition is now stored / assigned to the boolean variable so every time the variable is used it will automatically compare the condition to the current value of x. But your code helped me see the need to update the variables and storing them locally. I understand it better now. Thanks

You are welcome ... True, there is a difference between declaring the variables (boolean b), and assigning (b = x). When x changes, b does not change, until you perform a new assignment (unless it is a pointer). I suggest to read about C/C++, it makes using the Arduino much more powerful).

Yes I do plan to learn more C/C++ but at this stage just getting familiar with basic electronics and writing simple arduino sketches. So the next step is definitely digging deeper into C.

You cannot do anything at the same time (I'm also still learning electronics)


text:
How to transfer serial data or plot wirelessly on an arduino?
I have an arduino uno and an accelerometer connected reading vibrations. I want to be able to send the serial data or serial plot wirelessly from the arduino to any program(recommendations will be considered) on the pc without using the USB port on the pc. Is it possible?
I have an arduino ethernet shield, bluetooth modules HC-05 and HC-10 all at hand if they will be helpful.
please help, any help would be greatly appreciated.

serial plot is just serial data .... google is your friend ... find a tutorial about the Arduino and HC-05

so i gave the arduino an ip address through the ethernet shield and it is reading the data when i type in the ip address in my computer, now I just need a way how to plot this data and I think I need a database for that kind of work. Any suggestions on how to do this.

you want to collect data and then draw a chart it in a spreadsheet offline? with HC-05 you could draw realtime in the IDE Serial Plotter

yes i want to collect data and then draw it in a spreadsheet offline, realtime plotting would also be a great add on.

paired HC-05 creates a COM port which you can select in Arduino IDE and use it with Serial Monittor/Plotter

actually i cant use the bluetooth modules anymore, do you know anything about wonderware?

so which part should be wireless? the communication with the sensor or the communication with PC or both?


text:
Arduino Nano 33 battery power/charging
I have a project with an Arduino Nano 33 BLE Sense. My project is working great, but I need to transition it to battery power, and I'm having a bit of confusion about exactly what's required.
I have a small 3.7V Li-ion battery I'd like to use (similar to this one {0}) if possible.
I have read what seems to be some conflicting information, so I'd like to see which of the following are true:

I can power the Arduino directly from the 3.3v pin? I'm suspicious of this advice since on the datasheet the 3.3v pin is marked output only. There's a note on the product page that says:

Note: for ultra low-power functionality, you should cut the 3V3 jumper on the back of the board, and use an external battery at 3V3.

Is this something I should do? It seems difficult to reverse, I'm worried I might break my project.

I can power the Arduino directly from the VIN pin? This again seems to contradict the datasheet, which says the VIN pin can only handle 4.5 - 21V. 3.7V is less than this.
I could use a Step-up DC-DC transformer - like this {1}? I'd rather not wait for shipping from China.

Furthermore, I'd like to be able to charge the battery, so if I use a charging board like this one {2}, would that just work?
I don't want to connect the battery anywhere it might not be welcome for the risk of frying anything. Any help would be appreciated.

Link references (in case ebay listings go away):
0: Lithium Ion Battery - 110mAh

1: Mini 3V 3.3V 3.7V 5V 9V to 12V Step Up Boost Converter Module Voltage Regulator

2: 4.2V 5V 1A Micro USB Li-ion Battery Charger TP4056 Protection Chip Lithium-ion

the pads near the 3.3 V pin where you can cut the tiny trace between them are easy to bridge with solder.

https://forum.arduino.cc/index.php?topic=665272.msg4481636#msg4481636

Thanks, that's good to know. So if I cut the bridge, enabling 3.3V mode, the USB cable will stop working, but I can power directly from that pin. It seems to suggest there's no voltage conversion going on, so I could damage the board if I supply 3.7+?

the power from USB will stop, not the data

Did you find a solution to this problem?

The VIN (and the USB) goes into a 3.3V switching regulator. This has a minimum input voltage of 4.5V.
You isolate the output of that regulator from the rest of the circuit by cutting that one link (which is easy to re-solder). You are then free to feed 3.3V from your own power source directly into the board.
Yes, if you provide more than 3.3V you are liable to damage the board (note that a Li-Poly can be around 4.2V when fully charged).
You need to take your battery power and feed it through a nice efficient switching voltage regulator that has a low enough "dropout" voltage to allow good use from the battery. Note that many devices "rated" at 3.3V will also work much lower. For example:

Nina-B3 series module will run at down to 1.7V.
The APDS-9960 will operate down to 2.4V.
The HTS221 will run at down to 1.7V.
MP34DT06J can go as low as 1.6V.
LSM9DS1 can run from 1.9V.
LPS22 is 1.7V minimum

So it could be good to reduce your power to 2.5V instead of 3.3V to give more life from the battery. You should check each of the components in the both the device schematic and the rest of your circuit (by reading the datasheets) to find the highest "minimum" voltage they will work on.


text:
Water pump control hysteresis
I'm using arduino with analog pressure sensor, temperature sensor and a relay to control water pump. The simple code I wrote works, but I want better control.
#include <OneWire.h>
#include <DallasTemperature.h>

 const int pinCidlaDS = 2;
 int pinA0 = A0;
 int teplota;
 int rele;
 float tlak = 0;  //ideal 290+-

OneWire oneWireDS(pinCidlaDS);
DallasTemperature senzoryDS(&oneWireDS);

void setup() {
 senzoryDS.begin();
 rele = 3;
 pinMode(3, OUTPUT);
 Serial.begin(9600);
}

void loop() {
 tlak = analogRead(A0);
 teplota = (senzoryDS.getTempCByIndex(0));
  if ((tlak < 285) && (teplota < 30)) {
   digitalWrite(rele, LOW);
   delay(7000);
 }
   else {
   digitalWrite(rele, HIGH);
   delay(500);
 };
 Serial.print("Tlak: ");
 Serial.println(tlak);
 Serial.print("Teplota: ");
 senzoryDS.requestTemperatures();
 Serial.print(senzoryDS.getTempCByIndex(0));
 Serial.println(" stupnu Celsia");
 teplota = (senzoryDS.getTempCByIndex(0));
 delay (200);

}

So now I'm using delay to get away from the treshold value. And I wanted to write a code that would work like:
Pressure is lower than 'x', relay ON.
Pressure rises to 'Y', relay OFF until Pressure is lower than 'x'.
What should I use? Could you please give me a example, if there is?
Thank you very much! :)

Implementing hysteresis turns out to be quite straight-forward:
float pressure = read_pressure();
if (pressure < x)
    turn_relay_on();
else if (pressure >= y)
    turn_relay_off();

In addition to this answer you can also use millis(); function instead of delay, take a look at BlinkWithoutDelay example in Arduino IDE.

@newbie, with appropriate hysteresis values you might not need any delay logic at all, using either millis() or delay(). The hysteresis range allows you to have a "dead zone" range where nothing changes. It takes time for the temperature to go from the temp/pressure "on value" to the "off value", so the pump turns on and off less frequently.

It looks like the OP's application makes its pump on /  pump off decisions based on both temperature and pressure. We need to know the values for both that should trigger the pump on, and the values that should trigger the pump to go back off again.

@DuncanC: Hysteresis on two variables is more complex. My usual approach would be to draw, in the (T, P) plane, three regions: pump on, pump off, and an hysteresis band between them. Then write a predicate on the (T, P) pair for each of pump on and pump off. Cutting out a quarter-plane (T<T1 && P<P1 and T>=T2 || P>=P2) is the simplest case, but I would not trust something with such a sharp corner to be anywhere near optimal for any application.


text:
Matching baud rate on serial monitor
I am using different codes which set different values of baud rate through the Serial.begin() function. Do I need to change the baud rate of the serial monitor to match the initialized value on the code I am running every time, or can I just leave the serial monitor baud rate set at the highest frequency of all my sketches (115200)?

If at any point rates between receiver and sender are different the receiver will not be able to decode the data correctly. You will see strange characters after Serial.read()

you can leave the serial monitor set to one baud rate ... you only need to change it if you want to be able to read the output

If your sketch has
  ...
void setup() {
  Serial.begin(115200);
  // ... other stuff here;
}
  ...

And you run the IDE serial monitor at 9600, you will get gibberish. The same happens the other way round. You need to match the monitor to the baud rate you've defined on the Serial.begin(); call.

Interestingly, I was not getting gibberish for having the line Serial.begin(9600); and having my serial monitor set to 115200. But ok, I will make sure to change the baud rate of the monitor to always match what's in the code, just in case. Thanks!

Sometimes yes, and sometimes no.
The majority of Arduino boards are connected to your computer through a USB connection (there are some rare outside cases that use other connections like bluetooth or RS485...).  That USB connection can fall into two broad categories:

A USB to UART adaptor that then connects to a UART on the Arduino's main MCU, and
A direct USB connection to the main MCU

Type 1 are such boards as the Uno, Mega and Nano. Basically any board that has both a main MCU and a secondary chip that lies between the USB connection and that MCU.
In this case the baud rate in the serial monitor is communicated to the USB interface chip and tells that chip "You are to communicate with the main MCU at this speed".  You also then have to have the main MCU communicate with the USB chip at that same speed. So it is imperative that those two speeds match.
In the second case this isn't true. USB itself has no real concept of "baud rate". Instead the baud rate you set is merely a piece of configuration information the device at the end of the USB connection can use for something if it sees fit (what that "something" is, is entirely up to the device).  Changing that baud rate has no real effect on the communication.  Boards like the Leonardo and the Mini fall into this category.  They all have a "U" chip, like the ATMega32U4, which directly talk USB.
So, in short:

If you have a "Non-U" chip based board with a USB interface chip you must match the baud rates, and
If you have a "U" chip based board (or some other make of board with a direct USB interface) then the whole concept of baud rate is meaningless1 and it really doesn't matter what the numbers are you choose to use where.

1. 1200 baud is a special case in Arduino USB boards as it is used to trigger the bootloader for uploading new code.


text:
Pin Mappings from Arduino Metro M4 Express Board to SAMD51
After looking through the internet, I coudln't find any document (not in the datasheet, no nice graphics on google image searches) that showed the mapping between the Arduino breakout board and the SAMD51. Does such a mapping exist?
I'm answering my own question below, but perhaps someone knows of a better table.

Edit: Since writing my answer, I found this Google Sheet that does a much better job.
Arduino has some schematics on their website. Here's an image I used to build the following list below.
There are in this format: Arduino Pin | SAMD51 Pin | SAMD51 Description
Analog
A0  3   PA02/EINT2/AIN0/VOUT0
A1  14  PA05/I5/AIN5/VOUT1/SERCOM0.1
A2  15  PA06/I6/VREFC/AIN6/SERCOM0.2
A3  13  PA04/I4/VREFB/AIN4/SERCOM0.0
A4  11  PB08/I8/AIN2/SERCOM4.0
A5  12  PB09/I9/AIN3/SERCOM4.1

Digital
D0  44  PA23/I2C/I7/SERCOM3.1 +5/SOF/I2SFS1
D1  43  PA22/I2C/116/SERCOM3.0+5.1/I2SDI
D2  40  PB17/SERCOM5.1/I2SMCK0
D3  39  PB16/I0/SERCOM5.0/I2SCK0
D4  26  PB13/I13/SERCOM4.1/I2SMCK1
D5  27  PB14/I14/SERCOM4.2/PCC8
D6  28  PB15/I15/SERCOM4.3/PCC9
D7  25  PB12/I12/SERCOM4.0/I2SCK1
D8  42  PA21/I5/SERCOM3+5.3/I2SDO
D9  41  PA20/I4/SERCOM3+5.2/I2SFS0
D10 37  PA18/I2/SERCOM1+3.2
D11 38  PA19/I3/SERCOM1+3.3
D12 36  PA17/I2C/I1/SERCOM1.1+3.0
D13 35  PA16/I2C/I0/SERCOM1.0+3.1
GND
AREF    4   PA03/I3/VREFA/AIN1
SDA 63  PB02/I2/AIN14/SERCOM5.0
SCL 64  PB03/I3/AIN15/SERCOM5.1

SPI
MOSI    29  PA12/I12/I2C/SERCOM2.0+4.1
SCK 30  PA13/I13/I2C/SERCOM2.1+4.0
MISO    31  PA14/I14/SERCOM2+4.2


text:
What are the sizes of each primitive datatype on a Metro M4 Express SAMD51?
What are the data sizes of all the primitive datatypes on a Metro M4 Express SAMD51 C++ implementation? In some C++ implementations, int has 16 bits and in other implementations it has 32 bits. Is

It depends on compiler's data model for target processor. But I'd rather use int16_t/int32_t instead. It's much better for portability.

And that is the only difference in fundamental type sizes. On 8-bit Arduinos int is 16 bit and on 32-bit int is 32 bit.

short is 16 bit
long is 32 bit
long long is 64 bit

https://en.cppreference.com/w/cpp/language/types

Here is a sketch to quickly find out unsigned maximum values on any architecture and deduce the bit width from them (I had to use sprintf, because Serial.println(unsigned long long) did not work on my Due):
#include <limits.h>

#define sprintfln(args...) { char _qsx6_[200]; snprintf(_qsx6_, 200, args); Serial.println(_qsx6_); } // _qsx6_ may collide with local var

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

    unsigned char  uc = 0; uc=~uc; Serial.println(uc);
    unsigned short us = 0; us=~us; Serial.println(us);
    unsigned int   ui = 0; ui=~ui; Serial.println(ui);
    unsigned long  ul = 0UL; ul=~ul; Serial.println(ul);
    unsigned long long ull = 0ULL; ull=~ull; // doesn't work: Serial.println(~ull);

    sprintfln("char:%u short:%u int:%u long:%lu long long:%llu", uc, us, ui, ul, ull);
    sprintfln("char:%u short:%u int:%u long:%lu long long:%llu", UCHAR_MAX, USHRT_MAX, UINT_MAX, ULONG_MAX, ULLONG_MAX);
    sprintfln("char:%u short:%u int:%u long:%u long long:%u", sizeof(uc), sizeof(us), sizeof(ui), sizeof(ul), sizeof(ull));
    sprintfln("pointer:%u", sizeof(&uc));
}

On Arduino Due this gives (I expect it to be the same on SAMD51):
char:255
short:65535
int:4294967295
long:4294967295
long long:18446744073709551615
char:1 short:2 int:4 long:4 long long:8
pointer:4

Usually you could include "limits.h", but it seems that unsigned long long is missing (at least on Due). Hmmm, I didn't expect int and long to be the same, good to know.

Note that unsigned int ui = -1; is a valid way to set an unsigned number to it's maximum value. 2. sizeof(int) may be more convenient. 3. int and long are both 32 bits on most 32-bit environments, and even on 64-bit Windows. 4. It would be cool to have also the size of pointers.

Oh, forgot about sizeof() which works on pointers, too. To your suggestion (1) I would comment that 'unsigned long long x = -1LL' is strange style with type conversion and its up to the compiler to do the right thing. I would not do that.


text:
facing issue with while loop
I'm trying to develop one code in which I'm facing issue with while loop. Once I enter any newString it enter in while loop it count till 10 times, when (n>10)  then it is coming out from the while loop.
Facing issues in this part
while (n < 10)
  {
    while (!ret) {
      if ((time + 15) < millis()) {
        ret = dmd.stepMarquee(-1,0);
        time = millis();
      }
    }
     ret = false;
     n++;
    }

I just want when I enter any newString when loop is running it break while loop and start display newString.
Please help me out with this. Thanks for your help, greatly appreciated.
Here is my full code:
#include <SPI.h>
#include <DMD.h>
#include <TimerOne.h>
#include "SystemFont5x7.h"
#include "Arial_black_16.h"

//Fire up the DMD library as dmd
#define DISPLAYS_ACROSS 2
#define DISPLAYS_DOWN 1
DMD dmd(DISPLAYS_ACROSS, DISPLAYS_DOWN);

String inputString = "";
boolean stringComplete = false;
String commandString = "";

void ScanDMD()
{
  dmd.scanDisplayBySPI();
}

void setup()
{
   Serial.begin(9600);
   Serial.println("Arduino Start");
   Timer1.initialize( 5000 );
   Timer1.attachInterrupt( ScanDMD );
   dmd.clearScreen( true );
}

void loop() {

if(stringComplete)
{
  stringComplete = false;
  getCommand();

  if(commandString.equals("STAR"))
  {
   dmd.clearScreen( true );
  }

  else if(commandString.equals("PRSC"))
  {
    String text = getTextToPrint();
    printText(text);
  }
  inputString = "";
}

}

void getCommand()
{
  if(inputString.length()>0)
  {
     commandString = inputString.substring(1,5);
  }
}

String getTextToPrint()
{
  String value = inputString.substring(5,(inputString.length())-2);
  return value;
}

void printText(String text)
{
  char newString[256];
  int sLength = text.length();
  text.toCharArray( newString, sLength+1 );
  dmd.selectFont(System5x7);
  dmd.drawMarquee( newString , sLength , (32*DISPLAYS_ACROSS )-1 ,1);
  unsigned long time;
  boolean ret = false;
  time = millis();
  int n;
  n= 0;
  while (n < 10)
  {
    while (!ret) {
      if ((time + 15) < millis()) {
        ret = dmd.stepMarquee(-1,0);
        time = millis();
      }
    }
     ret = false;
     n++;
    }
}

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

what is the purpose of the while loop? ... how do you want the program to behave?

I'm sending the data to Arduino UNO via serial(Keyboard) and then UNO is to turn expected to scroll the received text on P10 DMD display.  Whenever it receive new serial data it start displaying that data into display. I want this.

scroll the received text ... you have not clearly defined the desired operation... serial characters arrive one at a time ... keep that in mind when you decide how you want the character scrolling to work

Forget using serialEvent(). It is one of the more stupid things that Arduino implemented.  It is nothing more than a function that gets called (wrapped in a check to Serial.available()) once per iteration of the main loop() function.
It is not really an "event" function at all.
To have anything happen inside your while loop you have to manually implement that thing within your while loop.  Nothing outside of the while loop (with the exception of interrupts) can affect the operation of the while loop.

So is there any possibilities to change in code?? Please help me out

There are plenty of possibilities. Personally I would ditch the while loop completely.

Now my code is working like I'm sending the data to Arduino UNO via serial(Keyboard) when it receive any serial data it scroll till 10 time and when (n>10) then will loop stop. In between this whenever I'm send any new data it is not accepting.
what exactly I want whenever I send new data to Arduino UNO via serial(Keyboard) and then UNO is to turn expected to scroll the received text on P10 DMD display at the same time.  Whenever it receive new serial data it start displaying that data into display.


text:
Where is the documentation for the Emoro GLAM pro module?
My 11-year-old son recently brought out an Emoro robot he got for his birthday. We had some temporary confusion with the robot, but got it to work.
He is now trying to connect to his computer via Bluetooth from the Emoro, but cannot find any documentation on Emoro Bluetooth.
Where is the documentation for Emoro Bluetooth?

What you are searching can be found via googling, if you know, what to google for. I write a formal answer to this, because there is neither a link on the product page of the manufacturer, nor is it very easy to find for a beginner.
Have you seen this repository emoro-2560-library on github? It seems to incorporate libraries for nearly ever function of the Emoro, including the bluetooth functionality of the GLAM board. You can find examples in the GLAM examples folder.
How did I found it? I googled for "emoro github". A better search phrase would be "emoro 2560 github" (Since Emoro 2560 is somewhat the extended name of the robot). I used the term "github", since most libraries for Arduinos and their derivates/variants are hosted on github. If you are search for a library, you can first search for them on github. Most times you will find something. Often these libraries also serve as a kind of documentation (as real and good documentation can be rare to find).

Now somewhat unneeded, but from the library code and the pictures on the product page of the GLAM module, I think, that a serial bluetooth module with AT firmware like HC-05 is used. If you ever want to look past the bluetooth library for the robot, you would need to go that way. (How a Hc-05 is controlled can also be googled)

the library is in Library Manager and has some Bluetooth named files

Ah, I didn't look in the library manager. But this answered the question, so I guess it is ok.

it is a very strange library. it duplicates the files from the Arduino core

The question was about documentation. I already have the library installed.

@nerdguy If you want more documentation then what is in the library, the only ways are to google or to ask the manufacturer/reseller. And it an very well be, that the robot is just not good documented.

the Emoro core contains the Bluetooth code. the repository link to GitHub in the answer is not a valid core or library


text:
UART connected device communication only works one way
As the title implies, I have two Arduino devices (Uno and Mega) connected to each other over UART (the Mega is hardware UART, the Uno is software UART); I need the Mega to send a command to the Uno, the Uno to perform the command, then the Uno to report back to the Mega when it has finished the task. In this way, I want to implement asynchronous programming to control various light patterns as well as several motors (code not shown, it is unnecessary as the light control is in an isolated segment) without needing any firmware hacking. Sending commands from the Mega to the Uno works, but the reverse is not true, and even polling waitloops do not work. Note that if I send the "affirm" command repeatedly for infinity, but then I hang the code in the Uno and the Mega has no way to stop the barrage; it starts receiving likely random bytes.
My code for the Mega is bulky and multi-file so I can't send the entire thing, but here is the control code:
lights::showRow(Serial1, 0, 0, 1, 1, 2, 2);
lights::waitUntilFinished(Serial1);
delay(500);
lights::clear(Serial1);
lights::waitUntilFinished(Serial1);
lights::chantO(Serial1);
lights::waitUntilFinished(Serial1);
lights::showRow(Serial1, 1, 0, 1, 1, 1, 2);
lights::waitUntilFinished(Serial1);
delay(500);
lights::clear(Serial1);
lights::waitUntilFinished(Serial1);
lights::chantX(Serial1);
lights::waitUntilFinished(Serial1);

These commands are implemented by:
namespace lights{
  boll ready = false;
  boll helloSent = false;
  void chantO(HardwareSerial coms){
    coms.write(1);
  }
  void chantX(HardwareSerial coms){
    coms.write(2);
  }
  void showRow(HardwareSerial coms, uint8_t x1, uint8_t y1, uint8_t x2, uint8_t y2, uint8_t x3, uint8_t y3){
    coms.write(3);
    coms.write(x1);
    coms.write(y1);
    coms.write(x2);
    coms.write(y2);
    coms.write(x3);
    coms.write(y3);
  }
  void clear(HardwareSerial coms){
    coms.write(4);
  }
  void waitUntilFinished(HardwareSerial coms){
    while (coms.available() == 0){};
    Serial.println("Done.");
    // It can't say anything but "affirmed", so we can save some code by not checking.
  }
}

The light code:
/* To make life easy, I will include a wiring map. Change as needed.
 *  Note that each ring is 24 pixels, and is labeled with the first-position to access it. The next one is obviously going to be the final point.
 ____     ____     ____
/48  \___/72  \   /192 \
\____/   \____/   \____/
 |___     |___     |___
/24  \   /96  \   /168 \
\____/   \____/   \____/
 |___     |___     |___
/0   \   /120 \___/144 \_____[END]
\____/   \____/   \____/
 |
 |
[CONTROLLER]

*/

#include <Adafruit_NeoPixel.h>
#include <SoftwareSerial.h>

#ifdef __AVR__
  #include <avr/power.h>
#endif
#define PIN       6
#define NUMPIXELS 216
#define DELAYVAL 500

Adafruit_NeoPixel pixels(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
SoftwareSerial coms(9, 8);
int white = pixels.Color(255, 255, 255);
int red = pixels.Color(255, 0, 0);

int getPixel(uint8_t x, uint8_t y, uint8_t num){
  if (x == 0){
    return 48 - (y * 24) + num;
  }
  else if (x == 1){
    return 72 + (y * 24) + num;
  }
  else if (x == 2){
    return 192 - (y * 24) + num;
  }
}

void setRing(uint8_t x, uint8_t y, int color){
  for (int i = 0; i < 24; i ++){
    pixels.setPixelColor(getPixel(x, y, i), color);
  }
}

void setup(){
  pinMode(9, INPUT);
  pinMode(8, OUTPUT);
  coms.begin(9600);
  Serial.begin(9600);
  pixels.begin();
  pixels.setBrightness(205); // 0.8 * 256 = 204.8; thus this is 80% power. Only 6 can be lit up before you have issues.
}

void loop(){
  if (coms.available() > 0){
    uint8_t d = coms.read();
    Serial.println("He talkin' me");
    Serial.print("He say ");
    Serial.println(d);
    switch (d){
      case 1:
        for (uint8_t x = 0; x < 2; x ++){
          setRing(0, 1, white);
          setRing(1, 0, white);
          setRing(2, 1, white);
          setRing(1, 2, white);
          pixels.show();
          delay(500);
          pixels.clear();
          pixels.show();
          delay(500);
        }
        break;
      case 2:
        for (uint8_t x = 0; x < 2; x ++){
          setRing(0, 0, white);
          setRing(2, 2, white);
          setRing(2, 0, white);
          setRing(0, 2, white);
          setRing(1, 1, white);
          pixels.show();
          delay(500);
          pixels.clear();
          delay(500);
        }
        break;
      case 3:
        Serial.println("Hello, World");
        setRing(coms.read(), coms.read(), red);
        setRing(coms.read(), coms.read(), red);
        setRing(coms.read(), coms.read(), red);
        pixels.show();
        break;
      case 4:
        pixels.clear();
        pixels.show();
        break;
    }
    coms.write(1);
  }
}

upload softwareSerial example sketch into both arduinos ... use hardware serial on the mega ... test connectivity between the two arduinos

You need to pass your HardwareSerial parameters by reference to prevent object copying.

You are passing your HardwareSerial (Serial1) objects by value. That means that the object is copied, which is not good - it breaks the connection between the incoming data buffer and the interrupt that loads the RX ringbuffer.
Instead you must either pass by reference or by pointer.  Personally I prefer pointers because it's what I am used to using, but you can use either.
For example:
  void waitUntilFinished(HardwareSerial &coms){ // <--- note the &
    while (coms.available() == 0){};
    Serial.println("Done.");
    // It can't say anything but "affirmed", so we can save some code by not checking.
  }

I would also consider changing this from a namespace to a class and passing the serial object you wish to use as a parameter to the constructor and storing the pointer to it in the class - then you only need ever pass it once and then use that pointer from then on. It would just simplify your code and clean things up somewhat.


text:
Is this circuit damaging my arduino/components?
I'm building a system as follows:

There are two pumps which lower and raise the level of the water
There is an ultrasound detector which measures the level of the water
While the water is too high, water is pumped out
While it's too low, water is pumped in

There are thresholds to prevent micro-adjustments, the system doesn't flip-flop back and forth.
However after a short while the ultrasound sensor stops working, until I power the system off and on again. My electronics knowledge is extremely rudimentary, but I know motors can be nasty to other components?
I've included my circuit diagram, should I be doing anything about that? I'm using reed switches to turn them off and on, but the ground and 5v rails are all tied together, and powering the arduino too via VIN.

Motors are inductive loads (they contain coils) that generate voltage spikes when switched off. These voltage spikes can indeed be nasty to other components.
You need to add a flyback diode in parallel with the motor, with the cathode connected to Vcc.
It will normally not conduct current, but when the motor is switched off, because the voltage spike is negative, it will provide a path for the current and allow to dissipate it through the coil's internal resistance.
As pointed out in the comments, it's also a good idea to (always) add an electrolytic capacitor (> 100 µF) close to the ultrasonic detector to filter out this kind of spikes.

It might also be a good idea to put a capacitor of >100 μF between Vcc and GND, close to the utrasonic detector. Flyback diodes need to be placed between the reed relay and Vcc, in parallel with the motors, with the stripe (cathode) connected to Vcc.

Hopefully you are powering the Arduino Vin with at least 7 volts. We know the Arduino a power supply it is NOT so where does the 5V come for the motors? You need to post technical links to the hardware items you are using. Are you calling relays reed switches? D11 and D12 sound like port pins, normally they cannot drive relays unless they are designed appropriately. I would suggest you either buy another set of electronic parts or stop using it until the problems can be determined. As far as a circuit diagram does not show the information needed. A schematic, not a frizzy thing is much better.

We don't know what the OP uses, but if you use relay modules designed for use with an arduino, they include the transistor to drive the relay as well as the flyback diode, at least for the relay.


text:
Motor not switching with 2N3904
I have a small motor, it powers fine from the 3V3 and GND output of the arduino nano ble 33. However I need to be able to switch it on and off. My first attempt was to use an output pin, but that doesn't supply enough power. I'm trying to use a 2N3904 transistor (my first time attempting to use one, so sorry if I've done something stupid). I've tried wiring it as follows, but no luck:

Is this possible, or do I need something more substantial like a reed switch?

https://electronics.stackexchange.com/q/77262/6680

The motor draws 100 to 200 mA. From Figure 16 of the 2N3904 datasheet, the 100 mA curve shows an Ib of 10 mA and Vce of 0.35 V. This voltage drop is a large percentage of the supply voltage which reduces the voltage across the motor to 3.3 - 0.35 = 2.95 V which is at the limit of its specification, so consider using an N-channel MOSFET which has a much lower voltage drop across drain-source. Also, the motor requires a reverse-biased protection across its terminals.

If you use Logic Level UIS (Avalanche) rated MOSFET (check Vgs to be sure it is on) you will not need the diode. Remember the Arduino a Power Supply it is NOT! If you keep using the 3V from the arduino put more on order you will fry it in due time. I would guess you blew the gate of the 2N3904, you need a current limit resistor in series with the micro to base.

1st : you have to put an appropriate resistor between the output of your arduino and transistor Base pin

2nd : you have to connect you motor and biased transistor to >>>> a suitable power supply (which has enough current (Amps) on it's output)

you can use this circuit instead of yours :

3rd : don't forget to use the diode in the schematic; it protects transistors from you motor coil's spikes you can use 1n4147 ( it depends on the size of your motor but i think, it works for you ( i wasn't successful to take a look at your motor and it's specifications )

4th : ignore the number of transistor, you can use your transistor (2N3904) instead of it

5th :NOTICE : this circuit has a problem, you have to connect appropriate power supply and replace "arduino 5 volts" by the + of your power supply in this circuit schematic

good luck

If you are an electronic engineer, don't use an eletronics circuit that you grab from internet that has everything wrong with the design. 1) the resistor is too high, with the value, the Ibe is only (5-0.7)/10000=0.43mA, assume the DC current gain is 50, it will only capable of produce Ice of .43x50 = 21.5mA even with a correct 2N3904, this is more designed for driving a single LED, certainly not sufficient to drive a motor. 1N4007 is a retifier with very slow recovery time, not design for rapid recovery.

I mentioned that he can use appropriate resistor, and for diode, you are right, i edited the answer,i forgot this problem of 1n400X series, he can use 4147 one or others. As i said, he can use the appropriate values of resistor, i just take him an overall vision of his/her problem's solution


text:
How to adjust Partition Scheme Wemos D1 mini pro?
I bought myself a WEMOS D1 mini PRO (16MB) for creating a quite large project.
As I'm writing code, my memory is starting to grow.
When I looked at the Flash size in Arduino IDE, the only options I have are

FS 14MB, OTA: 1019KB
FS 15MB, OTA: 512KB

The only things I need in the project is OTA and EEPROM. (no need for SPIFFS)
I looked around on the internet and came on a couple of sites that manipulate the filesystem.
https://robotzero.one/arduino-ide-partitions/
Also on other forums I read that you could modify the LD scripts that Arduino uses.
But I'm not sure how to define the addresses and what to do.
Here is a visual of the config I want.
ORIGINAL

ADJUSTED

Can someone push me into the right direction ?
Thanks in advance.

the maximum size of application code on esp8266 is 1MB

I know but it is possible to adjust the 1 MB. But I don't know how to adjust the addresses.

adjust how? 1 MB is the limit of the CPU on addressing instructions. why is your code so big? put large strings or data in FS files.

@JensVanhulst What Juraj is saying is that the CPU cannot cope with any more than 1MB. Regardless of the size of the flash. That is why there are no settings where the code size is more than 1MB - it's the absolute maximum that you can have. No amount of fiddling with config files can change that, it's a physical property of the chip.


text:
Pca9685 & WS2818B, 1 Nano
Arduino n00b here. I currently have an Arduino Nano set up to run 6 servos from a PCA9685 board. I'm looking to add 6 switches and 6 LED indicators to switch servo positions. What I'm curious about is how to connect the WS2818B. I know they can be run through I2C, but the Pca9685 is using those wires. Can I run both the pca9685 and the LEDs through I2C or just run each LED through a separate pin?

I was looking at WS2818B datasheet, they do not use i2c. It just needs a single ( dedicated) pin to receive the color/brightness commands.


text:
RS232 to ttl communication of arduino
I have an rs232 to TTL converter and I want to read something in the Arduino serial monitor by using the converter instead of using Arduino serial cable. I have connected the correct wiring in my opinion such as tx, Rx, Vcc and GND of the converter to Arduino pin 0 (Rx), pin 1 (Tx), 3.3 V and GND. But when I write something in the serial monitor of Arduino, I am getting nothing. But when I use only the arduino serial cable then I receive what I am writing in the serial monitor. Kindly can anyone tell me what am i doing wrong?

did you wire RX to TX?

The Uno works on 5V. Is your TTL converter 5V tolerant? Or why did you wire 3.3V?

Have you disconnected the Arduino's built-in serial connection to the USB interface?


text:
5v relay module and bulb holder

Hello sir , so can i cut the switch from the picture and connect the wires to my relay module ? Im sorry because im still learning . Thank you !

If you are still learning I would recommend you start with something more basic like LEDs instead. And learning the basic concepts of electricity from there. Not mains power that can kill you in case of mishandling.

Thank you sir @Coder_fox i will be carefully handling this project :)

You can refer to this to cut the switch
If you are a beginner, you can get started with Relay here
NOTE: It's dangerous and can cost your life. Please be careful when using Relay with 220 VAC

Thank you sir . You r kind ! Will do , thanks again I relay appreciated it !

A relay is nothing more than a switch - but instead of your finger controlling it, it's controlled by an electromagnet.
The relay can perform the exact same function as the switch on that cable.  In the image you have posted you would use the right-hand two screw terminals (middle is "common", right is "normally open") to replace the switch.

So that means , it works right if i do like that sir @Majenko ? Thank you sir for the help ! :) Your are kind !


text:
RDTSC alternative for Arduino
To calculate an operation execution time, I was saving the millis() result before and after the operation to calculate the interval time. Is there an alternative on the Arduino Uno like the RDTSC found on x86 architectures?

yes, on Uno the alternative is millis()

There are several alternatives. The best choice for you depends on the
time resolution you need and the maximum duration you may want to
measure:

millis() is good for slow things. It has a resolution of 2 ms
(it increments by steps of 1 ms most of the time, but 2 ms
occasionally) and can measure durations as long as 49.7 days.
micros() is the easy choice for when you want more resolution for
faster things. It increments in steps of 4 µs and is limited to
about 71.6 minutes.
For very fast things, you can get single-cycle resolution if you
configure Timer 1 to count at the full CPU speed, assuming you
don't need the timer for something else. But beware the timer will
roll over roughly every 4.1 milliseconds.
You could also use Timer 1 with the prescaler set at ÷8 in order
to expand the measurable range to 32.8 ms, at the cost of a
degraded resolution.

Here is a table summing up the available methods, sorted by resolution:
method        data type  resolution  max. duration
--------------------------------------------------
millis()       uint32_t        2 ms     49.7 days
micros()       uint32_t        4 µs     71.6 min
Timer 1 (÷8)   uint16_t      0.5 µs     32.8 ms
Timer 1 (÷1)   uint16_t     62.5 ns      4.1 ms

Thank you so much! I have a sub-question: Timer 1 (÷64) and micros() seem equivalent in resolution, will reading Timer1 value be more accurate/reliable than using micros()?

@Harini: Reading TCNT1 will be faster than calling micros(), so you get less overhead, at the cost of a shorted rollover period.


text:
Arduino Stepper motor control programming problem
I want to control the speed and position of stepper motor by a 4*4 keypad and monochrome graphic lcd interfaced with arduino. some open sources gave me good hint points to start controlling the distance and the speed of the stepper motor .
 I have made some modifications on the code in order to use it in both controlling the speed of motor and distance. I expect from the code either to:
1- change the position from 1 line to another and change the value at each parameter and see it on the graphic screen.
2- To change the page of the graphic lcd and modify each parameter separately in each page.
[I tried to code the first option but I faced the problem of changing the line to the next parameter without changing the written value, and that was a bit hard to me.]
The code contains of functions that changes the pressed keypad signal to a readable number to be able to draw it in the lcd, then these functions are called by case statements.
I have modified the code to have a number string for each parameter separated from the other one.
When I modified the loop code (as cleared below), I have seen that when I press 'A' or 'B' for the first time, one of the parameters screen is shown on the screen and the loop of this parameter is activated, and I can not change the parameter by pressing the other button.
 This is because of the While loop [While(1)] which frames me in one of the buttons loops forever.
When I remove this loop, the case statements are no longer valid, I just see the change in the screen but I can not add or remove any number.
So that I tried to change it this loop with other options like: while( keypressed == 'A') or [do -- while(0)] or if statements, but no results on the screen.
this is the part of the code.
void loop()
{

char keypressed = customKeypad.getKey();  // Get value of keypad button if pressed

if (keypressed != NO_KEY)     // If keypad button pressed check which key it was
{
    if (keypressed == 'A')
    {
        Serial.println("A");
        draw3();
        while(1)
        {
            char key1 = customKeypad.getKey();
            if (key1 !=NO_KEY)
            {
                switch (key1)
                {
                    case '1':
                        checknumber(1);
                        break;
                    case '2':
                        checknumber(2);
                        break;
                    case '3':
                        checknumber(3);
                        break;
                    case '4':
                        checknumber(4);
                        break;
                    case '5':
                        checknumber(5);
                        break;
                    case '6':
                        checknumber(6);
                        break;
                    case '7':
                        checknumber(7);
                        break;
                    case '8':
                        checknumber(8);
                        break;
                    case '9':
                        checknumber(9);
                        break;
                    case '0':
                        checknumber(0);
                        break;
                    case '*':
                        deletenumber();
                        break;
                    case'#':
                        calculatedistance();
                        break;
                    }
                }
            }
        }
        if (keypressed == 'B')
        {
            draw4();
            Serial.println('B');
            while(1)
            {
                char key1 = customKeypad.getKey();
                if (key1 !=NO_KEY)
                {
                    switch (key1)
                    {
                        case '1':
                            checknumber(1);
                            break;
                        case '2':
                            checknumber2(2);
                            break;
                        case '3':
                            checknumber2(3);
                          break;
                        case '4':
                            checknumber2(4);
                            break;
                        case '5':
                            checknumber2(5);
                            break;
                        case '6':
                            checknumber2(6);
                            break;
                        case '7':
                            checknumber2(7);
                            break;
                        case '8':
                            checknumber2(8);
                            break;
                        case '9':
                            checknumber2(9);
                            break;
                        case '0':
                            checknumber2(0);
                            break;
                        case '*':
                            deletenumber2();
                            break;
                        case'#':
                           stepperspeed();
                           break;
                        }
                    }
                }
            }
        }
    }

this looks like an exact same question that has been asked very recently .... are you asking this question again? ... is this a school assignment?

note: because of their simplicity, the switch blocks would actually be more readable if you single-lined the case statements ... like so case '1':   checknumber(1);   break; ... line up the command lines into neat columns

Seems like you have three tasks: 1. reading the keypad 2. writing the lcd 3. controlling the stepper. Which of those is the problem? Asking for help in all of them is too broad to answer in my opinion.

I just changed the location of the question from robotics to arduino to be more feasible. I already discovered that I already have more than 1 issue to talk about because as you say there is more than 1 task.
If I solved the first part between the LCD and the keypad, I think that the rest of controlling the stepper will not be a problem, as designing a graphic layout is the most harsh part in the coding. anyway I have changed the method. if you are interested, check my 2nd question and I will be grateful if you helped me to answer it.


text:
Controller freezes
I am using atmega 2560 as main(master) controller and other 5 salve 2 atmega 8 and 3 atmega 328p, there is two device with analogue output connected to main controller atmega 2560 through ads1115 module ,ads1115 converts analogue signal into 16 bit digital data and give it to atmega 2560 via I2C,
also the main controller has serial communication with pc and I2C comm. with salves. and some motors are also connected with controllers.
Now, My issue is that there is one function which reads the data from ads1115 for fix instances and with fix time interval and prints it. for running code for some time lets say 4-5 hour , controller hangs in between that function. and after that no serial communication work. i have to switch of supply to restart the machine.

We cannot answer this without your code. Please provide a mininal working example,  that shows the observed behavior.

do you use String class?

It's hard to say anything for sure without seeing the code, but for a
program that freezes using I2C communication, I would seriously suspect
the Wire library. This library has a few loops here and there where it
waits for a specific condition on the bus, with no timeout. See
twi.c. If, for whatever reason, the condition never happens, then
the program is stuck in the infinite wait.
You could try finding al alternative I2C library or, if you can tolerate
the occasional crashes, enable the watchdog in order to get out of the
freezes.


text:
Arduino MKR 1010 WiFi as BLE central/client
I'm trying to use my new Arduino MKR 1010 WiFi as a Bluetooth Low Energy central/client, however I could only find information on how to use it as a peripheral/server (for example with the ArduinoBLE library, which only supports peripheral mode).
Is this possible? Maybe with a different library or firmware for the integrated NINA-W102 chip?

were you able to use it as central device?

@EinSoldiatGott Unfortunately not. I ended up using the ESP32 which worked perfectly.

In case this thread turns up in a search, the ArduinoBLE library now includes central and peripheral support.


text:
Firmware backup and restore
I need to have the firmware stored somewhere on the board in order to get back to it after flashing a new firmware.
Is there a way to store a backup of the firmware somewhere, and use a button to erase a newer firmware and get back to the old one, without re-flashing the old firmware again ?

you would need to use a device that could store multiple firmware files ... this device would reflash the firmware without the need of a computer .... possibly another arduino

possible theoretically - I noticed you tagged esp32 - they usually have 4MB flash, and the "standard" size for sketch binary is 1MB, so there's 3MB you could use. However, it's not going to be simple

Yes. You need to create a factory partition and upload your bin file to there.
You can read more about ESP32 partitions here
Note that none of the partition schemes in the ESP32 core have factory partitions, so you will need to create a custom one and link it to a menu entry (look at the boards.txt file to see how that is done).
The existing partition files are just .csv files within the ESP32 core. Copy one and modify it, then link that to a menu entry using the new file name.

Working on it. Thank you :)


text:
Stepper Motor Code. Delay or Millis
i will be designing a robot with multiple stepper motor. is it advisable to use millis instead of delay here or not?
right now im testing if Millis() would work but still having a hard time programming this.

Depends on what you need to do. delay is a blocking call, while if you use millis you can do other things between checks for time. This may not be important if you are using a multi-core arduino or it may mean the difference between responsiveness and sluggishness.

This is a poor way to control stepper that requires acceleration, velocity limits and deacceleration to target position.  Get a CNC shield and FET driver bridge and do it right with GRBL Panel,software to Uno uC interface on USB

I use 10us step pulses using Arduino + CNC Shield + GRBL PANEL s/w over Windows via USB and get excellent servo speeds, home button (auto-cal) Jog buttons with tuned g,v, max constants and optimum step rates. Bit banging is so archaic.

Arduino function delay() which pauses the program for an amount of milliseconds specified as parameter.
millis(), on the other hand, is a function that returns the amount of milliseconds that have passed since program start.
Just like delay() has a microsecond-version called delayMicroseconds(), millis() has micros(). If you need better resolution, micros() may be the way to go.
However, be aware that micros() will overflow after approximately 70 minutes, compared to millis()‘s 50 days. This means that the functions’ return values will start all over from zero.


text:
Calling functions from an array of pointers in a library causes 'undefined reference to' error
I am trying to create a library, where I have an array of pointers to functions in it. This array is used by other functions in the library. This is the code of the header file:
class Lib {
  public:
    static void call();
    static void (*caller[])();
  private:
};

This is the code of the .cpp-file:
#include "Lib.h"

void (*caller[2])();

void Lib::call() {
  caller[0]();
}

The sketch executing this is
#include <Lib.h>

void setup() {
  Lib::call();
}

void loop() {}

When I try to compile this, I get the following error:

undefined reference to `Lib::caller'
  collect2: error: ld returned 1 exit status
  Mehrere Bibliotheken wurden für "Lib.h" gefunden

Another weird thing is that the error about the multiple found libraries goes away if I take away the line
Lib::call();

However, if I put the same code directly into the sketch like so:
void (*caller[2])();

void call() {
  caller[0]();
}

void setup() {
  call();
}

void loop() {}

I get no error. What's the problem here?

void (*caller[2])();

should be:
void (*Lib::caller[2])();

Since you are defining storage space for a static member variable you have to tell the compiler what class it's a static member of.

Thanks, that solves the part about the undefined reference. How does the problem with the multiple libraries originate from this though?

Probably because you do have two libraries named Lib.h somewhere?

(incidentally, I don't speak german, so had no clue what you were on about at first about multiple libraries...)

No, there is just one Lib.h file. The funny thing is, that, as I wrote, this error goes away when not calling the function in the sketch. And it also goes away with your solution. I was just wondering where it originated from.

Probably some bug in the IDE then...


text:
Error: function was not declared in this scope when using a library without classes
I have created a library of functions that doesn't have and mustn't have a class. In order to have functions inside the library that can only be called from the library itself, you just write them into the .cpp file and leave them out of the header file completely. Here is the .cpp file of the library (the header file is empty):
#include "Lib.h"

// Definition of foo1
static void foo1(){
    foo2();
}

// Definition of foo2
static void foo2() {}

When including the library in an empty sketch and compiling it I get the following error message:

error: 'foo2' was not declared in this scope

What is the problem here?

What does this have to do with Arduino? I think it is a general C/C++ question. Did you write this question and answered it directly for documenting this?

It probably is a question that also applies more broadly, as are many other questions on this site do. Yes, I wrote and answered this question for documentation.

your Lib.h is wrong. it broke the automatic forward declarations generation

it compiles in Arduino IDE 1.8.10 with empty Lib.h

now I see my error. I thought you have the functions in .ino, but you write it is a .cpp. so in c/c++ you can't use functions defined later in code so you must use forward declarations/function prototypes, but this is how it is 50 years back, so not really an Arduino problem.

When creating a library with functions that are not mentioned in the header file, the order of appearence in the .cpp file suddenly becomes relevant. In order for a function to be used by another function, it has to be declared first.
The first possibility in this example would be to define foo2 before defining foo1 like this:
#include "Lib.h"

// Definition of foo2
static void foo2() {}

// Definition of foo1
static void foo1(){
    foo2();
}

However, this is not only bad practice, it also doesn't always work. If there is any sort of recursive procedure that makes functions call each other, you can't define both of them before the respective other at the same time.
The more elegant and foolproof way to do this is by declaring each function first like you usually would in the header file and then defining what they actually do. The .cpp file of this library would then look like this:
#include "Lib.h"

static void foo1(); // Declaration of foo1
static void foo2(); // Declaration of foo2

// Definition of foo1
void foo1(){
    foo2();
}

// Definition of foo2
void foo2() {}

Note: These declarations (static void foo1() and static void foot2() are called forward declarations.


text:
Creating an array with the length coming from a library
When creating an array like in the sketch
#include <Lib.h>

int myArray[Lib::len];

void setup() {}

void loop() {}

the variable len must be an integer constant that is known at compile time. Like shown in the sektch, I want to put the length of the array into a library and get it from there. The problem is that for this to work, you have to initialize the constant already in the .h file, which is against proper library standards. This is how you would do this (.h file of the library):
class Lib {
  public:
    static const int len = 4;
};

The .cpp file doesn't even have to contain anything in this case. The proper way to do things in a library would be like this though:
The .h file:
class Lib {
  public:
    static const int len;
};

The .cpp file:
#include "Lib.h"

const int Lib::num = 4;

But if done like this, len doen't have a value at compile time since the sketch only includes the .h file and not the .cpp file.
Is there any way to intitialize an array in a sketch with its length coming from a library while maintaining proper library design?

Header files are there to define stuff that is used by the library functions as well as by the consumer code. So if both need access to the length variable, why should it be improper library design to define the length in the header file? For example all information of MCU registers  and their name to number mapping are declared in headers.

There is absolutely nothing wrong with putting it in the header.

§9.4.2/4 If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression (5.19). In that case, the member can appear in integral constant expressions. The member shall still be defined in a name- space scope if it is used in the program and the namespace scope definition shall not contain an initializer.

Since you're just using it as a simple constant "integral" value there is nothing wrong with putting it in the header.

So the answer is "Just do it this way, even though the initialization is not in the .cpp file as with everything else"? Or is there any other way?

The answer is "Just do it this way since this is the right way to do it as you have a static const integral type"

@LukasFun You can define a constant in the header and use this to initialize the static member in the cpp File. You can also use this constant in the sketch at compile time. But that would be a worse solution (IMHO at least).


text:
Compute the size of an array that was passed as a parameter to a function
When passing an array to a function, you usually pass the length of the array along with it. You can compute the size of the array with sizeof(myArray)/sizeof(myArray[0]), which works just fine.
However, if you try to do this within the function that you pass the array to, this doesn't return the length of the array - eg. if it is an int array, it returns 1, if it is a double array, it returns 0.
Why is that so and is there any way to compute the size of an array that was passed as a parameter?

If you don't use it often (every different type/size makes new instantiation od f function), then you can use templates like: template <typename T, size_t N> void f(T(& myArray)[N])

You can't. You are passing a pointer to the array, and sizeof will give you the size of that pointer (2 on an 8-bit Arduino).
Instead the normal way is to pass the size of the array as a parameter to your function.
myFunction(myArray, sizeof(myArray) / sizeof(myArray[0]));


text:
Protecting variables and functions within a library that has no class
If you want to have functions within a library that only the library itself should be able to use or variables that shouldn't be accessed from outside, you usually make them private by writing this in the header file:
class Lib{
  public:
    // All these can be accessed from outside
    void function1();
    void function2();
    int someNumber;
  private:
    // These two can't be accessed from outside
    void secretFunction();
    int secretNumber;
};

My question is this:
I want to write this library without using classes. How do I protect things from being accessed from anywhere in this case?

If your library is implemented in a single .cpp file, you can define these
variables and functions within that file, and give them the static
qualifier:
static int my_private_variable = 42;

static void my_private_function()
{
    ...
}

Obviously, there should be no mention of them in the .h file.
Note also that we are talking about global variables. Local variables
are already hidden within the defining function.

Exactly what I was looking for. Check out this question: https://stackoverflow.com/questions/17554515/hiding-private-members-of-c-library/59093688#59093688 you basically answered that too!