text:
I have a problem combining two different sketches into one sketch
Below are two attached the two codes, the second code is for using a microphone to detect for cough and sneezes where the first code is used for humidity and temp.
// For Scanning Insitu Exhale Parameters via nRFConnect or any BLE Service App
// Carbon-dioxide & Volatile OCs have been pseudo-mapped under Pressure & Rainfall respectively(ppm & ppb);)
#include <ArduinoBLE.h>
#include <Wire.h>
#include <SparkFunBME280.h>
#include <SparkFunCCS811.h>
#define CCS811_ADDR 0x5B
#define PIN_NOT_WAKE 5
CCS811 myCCS811(CCS811_ADDR);
BME280 myBME280;

BLEService sensorService("181A");  // Environmental_Sensor-Service
// 180D HeartRate
// 181B BodyComposi.
BLEShortCharacteristic sensorLevelChar1("2A6E", BLERead | BLENotify);   // Temperature-Characteristic
BLEShortCharacteristic sensorLevelChar2("2A6F", BLERead | BLENotify);   // Humidity-Characteristic
BLELongCharacteristic sensorLevelChar3("2A6D", BLERead | BLENotify);    // PCo2-Characteristic
BLELongCharacteristic sensorLevelChar4("2A78", BLERead | BLENotify);    // PTVoC-Characteristic
// 2A37 HRmeasurement
// 2A2C Magdeclination
// 2A98 weight
// 2A6D Pressure
// 2A9D Recom.HRMax.
// 2A8E Height
// 2A8D Max.HR
// 2A8C Gender
// 2A00 DeviceName
// 2A38 bodysensorlocation
int oldSensorLevel1 = 0;
int oldSensorLevel2 = 0;
int oldSensorLevel3 = 0;
int oldSensorLevel4 = 0;
long previousMillis = 0;

void setup() {
  Serial.begin(9600);
  while (!Serial);
  pinMode(23, OUTPUT);

  if (!BLE.begin()) {
    Serial.println("Bluetooth init. failed!");
    while (1);
  }
  Wire.begin();
  CCS811Core::status returnCode = myCCS811.begin();
  Serial.print("CCS811 begin exited with: ");
  printDriverError( returnCode );
  Serial.println();
  myBME280.settings.commInterface = I2C_MODE;
  myBME280.settings.I2CAddress = 0x77;
  myBME280.settings.commInterface = I2C_MODE;
  myBME280.settings.I2CAddress = 0x77;
  myBME280.settings.runMode = 3; //Normal mode
  myBME280.settings.tStandby = 0;
  myBME280.settings.filter = 4;
  myBME280.settings.tempOverSample = 5;
  myBME280.settings.pressOverSample = 5;
  myBME280.settings.humidOverSample = 5;
  delay(10);
  myBME280.begin();

  BLE.setLocalName("Mask.xME");
  BLE.setAdvertisedService(sensorService);
  sensorService.addCharacteristic(sensorLevelChar1);
  BLE.addService(sensorService);
  sensorLevelChar1.writeValue(oldSensorLevel1);

  sensorService.addCharacteristic(sensorLevelChar2);
  BLE.addService(sensorService);
  sensorLevelChar2.writeValue(oldSensorLevel2);

  sensorService.addCharacteristic(sensorLevelChar3);
  BLE.addService(sensorService);
  sensorLevelChar3.writeValue(oldSensorLevel3);

  sensorService.addCharacteristic(sensorLevelChar4);
  BLE.addService(sensorService);
  sensorLevelChar4.writeValue(oldSensorLevel4);

  // start advertising
  BLE.advertise();
  Serial.println("Bluetooth active, waiting to be connected.....");
}

void loop() {
  // waiting for a BLE central device.
  BLEDevice central = BLE.central();
  if (central) {
    Serial.print("Connected to central: ");
    Serial.println(central.address());
    digitalWrite(23, HIGH);  // indicate connection
    while (central.connected()) {
  if (myCCS811.dataAvailable())
  {
    myCCS811.readAlgorithmResults();
    printInfoSerial();
    float BMEtempC = myBME280.readTempC();
    float BMEhumid = myBME280.readFloatHumidity();
    myCCS811.setEnvironmentalData(BMEhumid, BMEtempC);
  }
  else if (myCCS811.checkForStatusError())
  {
    printSensorError();
  }
      long currentMillis = millis();
      if (currentMillis - previousMillis >= 200) {
        previousMillis = currentMillis;
        updateSensorLevel1();
        updateSensorLevel2();
        updateSensorLevel3();
        updateSensorLevel4();
      }
    }
    digitalWrite(23, LOW);
    Serial.print("Disconnected from central: ");
    Serial.println(central.address());
  }
}

void updateSensorLevel1() {
  float temperature = myBME280.readTempC();
  Serial.print("Temperature = ");
  Serial.print(temperature, 0);
  //float T = myBME280.readTempC();
  Serial.println(" °C");
  float sensorLevel1 = map(temperature, 0, 100, 0, 10000);
  sensorLevelChar1.writeValue(sensorLevel1);
  oldSensorLevel1 = sensorLevel1;
}

void updateSensorLevel2() {
  float humidity = myBME280.readFloatHumidity();
  Serial.print("Humidity = ");
  Serial.print(humidity, 0);
  Serial.println(" %");
  float sensorLevel2 = map(humidity, 0, 100, 0, 10000);
  sensorLevelChar2.writeValue(sensorLevel2);
  oldSensorLevel2 = sensorLevel2;
}

void updateSensorLevel3() {
  float CO2 = myCCS811.getCO2();
  Serial.print("Co2 = ");
  Serial.print(CO2);
  Serial.println(" ppm");
  float sensorLevel3 = map(CO2, 0, 100, 0, 1000);
  sensorLevelChar3.writeValue(sensorLevel3);
  oldSensorLevel3 = sensorLevel3;
}

void updateSensorLevel4() {
  float VoC = myCCS811.getTVOC();
  Serial.print("TVoC = ");
  Serial.print(VoC);
  Serial.println(" ppb");
  float sensorLevel4 = map(VoC, 0, 100, 0, 100);
  sensorLevelChar4.writeValue(sensorLevel4);
  oldSensorLevel4 = sensorLevel4;
}

void printInfoSerial()
{
  Serial.println("CCS811 data:");
  Serial.print(" CO2 concentration : ");
  Serial.print(myCCS811.getCO2());
  Serial.println(" ppm");
  Serial.print(" TVOC concentration : ");
  Serial.print(myCCS811.getTVOC());
  Serial.println(" ppb");

  Serial.println("BME280 data:");
  Serial.print(" Temperature: ");
  Serial.print(myBME280.readTempC(), 2);
  Serial.println(" degrees C");
  Serial.print(" %RH: ");
  Serial.print(myBME280.readFloatHumidity(), 2);
  Serial.println(" %");
  Serial.println();
}

void printDriverError( CCS811Core::status errorCode )
{
  switch ( errorCode )
  {
    case CCS811Core::SENSOR_SUCCESS:
      Serial.print("SUCCESS");
      break;
    case CCS811Core::SENSOR_ID_ERROR:
      Serial.print("ID_ERROR");
      break;
    case CCS811Core::SENSOR_I2C_ERROR:
      Serial.print("I2C_ERROR");
      break;
    case CCS811Core::SENSOR_INTERNAL_ERROR:
      Serial.print("INTERNAL_ERROR");
      break;
    case CCS811Core::SENSOR_GENERIC_ERROR:
      Serial.print("GENERIC_ERROR");
      break;
    default:
      Serial.print("Unspecified error.");
  }
}
void printSensorError()
{
  uint8_t error = myCCS811.getErrorRegister();
  if ( error == 0xFF ) //comm error
  {
    Serial.println("Failed to get ERROR_ID register.");
  }
  else
  {
    Serial.print("Error: ");
    if (error & 1 << 5) Serial.print("HeaterSupply");
    if (error & 1 << 4) Serial.print("HeaterFault");
    if (error & 1 << 3) Serial.print("MaxResistance");
    if (error & 1 << 2) Serial.print("MeasModeInvalid");
    if (error & 1 << 1) Serial.print("ReadRegInvalid");
    if (error & 1 << 0) Serial.print("MsgInvalid");
    Serial.println();
  }
}

Code 2
// Cough & Sneeze Classifier built through Edge Impulse Studio.
// If your target is limited in memory remove this macro to save 10K RAM
#define EIDSP_QUANTIZE_FILTERBANK   0
#include <PDM.h>
#include <cscan2_inference.h>

typedef struct {
    int16_t *buffer;
    uint8_t buf_ready;
    uint32_t buf_count;
    uint32_t n_samples;
} inference_t;

static inference_t inference;
static bool record_ready = false;
static signed short sampleBuffer[2048];
static bool debug_nn = false; // Set this to true to see e.g. features generated from the raw signal

/**
 * @brief      Arduino setup function
 */
void setup()
{
    // put your setup code here, to run once:
    Serial.begin(115200);
    Serial.println("SpecVital Inference...");
    // summary of inferencing settings (from model_metadata.h)
    ei_printf("Inferencing settings:\n");
    ei_printf("\tInterval: %.2f ms.\n", (float)EI_CLASSIFIER_INTERVAL_MS);
    ei_printf("\tFrame size: %d\n", EI_CLASSIFIER_DSP_INPUT_FRAME_SIZE);
    ei_printf("\tSample length: %d ms.\n", EI_CLASSIFIER_RAW_SAMPLE_COUNT / 16);
    ei_printf("\tNo. of classes: %d\n", sizeof(ei_classifier_inferencing_categories) / sizeof(ei_classifier_inferencing_categories[0]));
    if (microphone_inference_start(EI_CLASSIFIER_RAW_SAMPLE_COUNT) == false) {
        ei_printf("ERR: Failed to setup audio sampling\r\n");
        return;
    }
}

/**
 * @brief      Arduino main function. Runs the inferencing loop.
 */
void loop()
{
    ei_printf("Starting inferencing in 2 seconds...\n");
    delay(5000);
    ei_printf("Recording...\n");
    bool m = microphone_inference_record();
    if (!m) {
        ei_printf("ERR: Failed to record audio...\n");
        return;
    }
    ei_printf("Recording done\n");

    signal_t signal;
    signal.total_length = EI_CLASSIFIER_RAW_SAMPLE_COUNT;
    signal.get_data = &microphone_audio_signal_get_data;
    ei_impulse_result_t result = { 0 };

    EI_IMPULSE_ERROR r = run_classifier(&signal, &result, debug_nn);
    if (r != EI_IMPULSE_OK) {
        ei_printf("ERR: Failed to run classifier (%d)\n", r);
        return;
    }

    // print the predictions
    ei_printf("Predictions (DSP: %d ms., Classification: %d ms., Anomaly: %d ms.): \n",
        result.timing.dsp, result.timing.classification, result.timing.anomaly);
    for (size_t ix = 0; ix < EI_CLASSIFIER_LABEL_COUNT; ix++) {
        ei_printf("    %s: %.5f\n", result.classification[ix].label, result.classification[ix].value);
    }
#if EI_CLASSIFIER_HAS_ANOMALY == 1
    ei_printf("    anomaly score: %.3f\n", result.anomaly);
#endif
}
/**
 * @brief      Printf function uses vsnprintf and output using Arduino Serial
 *
 * @param[in]  format     Variable argument list
 */
void ei_printf(const char *format, ...) {
    static char print_buf[1024] = { 0 };
    va_list args;
    va_start(args, format);
    int r = vsnprintf(print_buf, sizeof(print_buf), format, args);
    va_end(args);
    if (r > 0) {
        Serial.write(print_buf);
    }
}
/**
 * @brief      PDM buffer full callback
 *             Get data and call audio thread callback
 */
static void pdm_data_ready_inference_callback(void)
{
    int bytesAvailable = PDM.available();
    // read into the sample buffer
    int bytesRead = PDM.read((char *)&sampleBuffer[0], bytesAvailable);
    if (record_ready == true || inference.buf_ready == 1) {
        for(int i = 0; i < bytesRead>>1; i++) {
            inference.buffer[inference.buf_count++] = sampleBuffer[i];
            if(inference.buf_count >= inference.n_samples) {
                inference.buf_count = 0;
                inference.buf_ready = 1;
            }
        }
    }
}
/**
 * @brief      Init inferencing struct and setup/start PDM
 *
 * @param[in]  n_samples  The n samples
 *
 * @return     { description_of_the_return_value }
 */
static bool microphone_inference_start(uint32_t n_samples)
{
    inference.buffer = (int16_t *)malloc(n_samples * sizeof(int16_t));
    if(inference.buffer == NULL) {
        return false;
    }
    inference.buf_count  = 0;
    inference.n_samples  = n_samples;
    inference.buf_ready  = 0;
    // configure the data receive callback
    PDM.onReceive(&pdm_data_ready_inference_callback);
    // optionally set the gain, defaults to 20
    PDM.setGain(80);
    //ei_printf("Sector size: %d nblocks: %d\r\n", ei_nano_fs_get_block_size(), n_sample_blocks);
    PDM.setBufferSize(4096);
    // initialize PDM with:
    // - one channel (mono mode)
    // - a 16 kHz sample rate
    if (!PDM.begin(1, EI_CLASSIFIER_FREQUENCY)) {
        ei_printf("Failed to start PDM!");
    }
    record_ready = true;
    return true;
}
/**
 * @brief      Wait on new data
 *
 * @return     True when finished
 */
static bool microphone_inference_record(void)
{
    inference.buf_ready = 0;
    inference.buf_count = 0;
    while(inference.buf_ready == 0) {
        delay(10);
    }
    return true;
}
/**
 * Get raw audio signal data
 */
static int microphone_audio_signal_get_data(size_t offset, size_t length, float *out_ptr)
{
    arm_q15_to_float(&inference.buffer[offset], out_ptr, length);
    return 0;
}

/**
 * @brief      Stop PDM and release buffers
 */
static void microphone_inference_end(void)
{
    PDM.end();
    free(inference.buffer);
}

#if !defined(EI_CLASSIFIER_SENSOR) || EI_CLASSIFIER_SENSOR != EI_CLASSIFIER_SENSOR_MICROPHONE
#error "Invalid model for current sensor."
#endif

And... what is the "problem" you have with it?

You have 2 different problems you need to solve before you can merge these sketches.
The first sketch has a loop within a loop. in psuedocode it is:
void loop(){
   Connection con = connect();
   while(con.connected()){
       doStuff();
   }
   notify_disconnected();
}

This is a problem because the loop never exits in normal operation.
you can rewrite this into
Connection con;
void loop(){
    if(con.connected()){
        was_connected = true;
        doStuff();
    } else{
        if(was_connected){
            notify_disconnected();
            was_connected = false;
        }
        con = connect();
    }
}

The other sketch has the classic delay problem which the first sketch gives an example of handling.
void loop(){
    delay(5000);
    doStuff();
}

this can be changed into
void loop(){
    long currentMillis = millis();
    if (currentMillis - previousMillis >= 5000) {
        previousMillis = currentMillis;
        doStuff();
    }
}

After you do these fixes and make sure the names of the globals and functions don't collide and no unneeded wires cross you can put both in the same sketch:
void setup(){
    setup_sketch1();
    setup_sketch2();
}

void loop(){
    loop_sketch1();
    loop_sketch2();
}


text:
JSON Parser fails because number of bytes is being sent
Sorry I am new with this.
I am trying to read a JSON response from my website using an ESP8266, but it keeps failing.  I am using the following code:
WiFiClientSecure httpsClient;    //Declare object of class WiFiClient
httpsClient.setInsecure();
httpsClient.setTimeout(15000); // 15 Seconds

if (httpsClient.connect(host, httpsPort)) {

  String Data ="/IOT/Device_Setup.php?MAC="+deviceMAC;

  httpsClient.print(String("POST ") + Data + " HTTP/1.1\r\n" +
   "Host: " + host + "\r\n" +
   "Connection: close\r\n\r\n");

  while (httpsClient.connected()) {
    String line = httpsClient.readStringUntil('\n');
    Serial.println(line);
    if (line == "\r") {
      Serial.println("headers received");
      break;
    }
  }
  String payload = "";
  while (httpsClient.available()) {
    char c = httpsClient.read();
    payload=payload+c;
  }

  Serial.println(payload);

  // Allocate JsonBuffer
  // Use arduinojson.org/assistant to compute the capacity.
  const size_t capacity = JSON_OBJECT_SIZE(3) + JSON_ARRAY_SIZE(2) + 60;
  StaticJsonDocument<200> jsonBuffer;
  // Parse JSON object
  DeserializationError error = deserializeJson(jsonBuffer, payload);
  if (!error) {

    const char* Switch = jsonBuffer["Switch"];
    const char* LED = jsonBuffer["LED"];
    const char* DHT = jsonBuffer["DHT"];

    // Decode JSON/Extract values
    Serial.print("Switch = ");
    Serial.println(Switch);
    Serial.print("LED = ");
    Serial.println(LED);
    Serial.print("DHT = ");
    Serial.println(DHT);
  }
}

When I print out the payload after the header I receive the following output:

22
{"Switch":"0","LED":"0","DHT":"1"}
0

I know the 22 is the hex value for the number of bytes being sent.  Is there a way of ignoring the numbers and just using the JSON code?

how is it failing?

it is then chunked transfer encoding. set content length on server to avoid it.

Agree, this is Chunked Transfer Encoding, use HTTP/1.0 to avoid it. See also JsonHttpClient.ino on arduinojson.org.

Thanks everyone. Adding the size in the header worked.

source: Stack Exchange

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

sort: votes


text:
16 by 2 lcd display is not showing any character
I am trying to interface 16by2 lcd with msp432p401m controller but my 16 by 2 lcd is not showing any character. I have attached schematic and code for reference. By using same schematic and code 20 by 4 lcd is working properly.
please help me...

why do you believe that the same code would work for both displays? ... what is your question? ... you did not ask any

Do you realize that the MSP432P401M is not a 5V device and might not be able to interface reliably with a 5V device like your LCD? Do you get anything on the screen (for example: dark rectangles)? Your schematic does not show E, RS, 5V and GND connected to the display. Are they connected? Have you tried to adjust the contrast?

Your use of (P4OUT & 0x00) | seems pointless but harmless.  Otherwise nothing really jumps out that's worth mentioning.

@StarCat, EN and RS are labeled nodes at both the MCU and display. They're logically connected despite not having a graphic line running from one to the other.  Similar thing going on with DGND and 5VD; somewhere else in the schematic they're more than likely labeled at a regulator. They've hardwired RW at LCD pin 5 into write mode.  Voting up with regard to other parts of your comment though.  All that said, hopefully the backlight has some current limiting on the module; I don't know that they all do.

@timemage, I mentioned EN and RS because they were not explicitly connected in the schematic and the question is clearly by someone inexperienced with this kind of material. There was a lot of information missing about the physical setup and I addressed some of that.

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


text:
How to bring WiFi back up if woken from deepSleep(WAKE_RF_DISABLED)
I'm trying to build a sensor that should update an MQTT broker only if something changes. So every few seconds it's supposed to wake up just enough to check a few inputs, compare them with the last time it woke up, and only if there has been a change should it connect to the broker and write the updates. I don't expect many updates per day, but if I sleep more than 10 seconds, I might miss them.
I'm using WiFi.forceSleepBegin() and WiFi.forceSleepWake(), mainly based on these articles. But there is this tempting option of ESP.deepSleep(n, WAKE_RF_DISABLED)
The API that I found only mentions this:

If you implement deep sleep with WAKE_RF_DISABLED and require WiFi functionality on wake up, you will need to implement an additional WAKE_RF_DEFAULT before WiFi functionality is available.

Do I read this correct if I understand that I would need to make another deepSleep just to wake up again with WiFi back active? Or is there an easier way to boot up the WiFi after such a sleep?
Thank you

WiFi.forceSleepBegin();
delay(1);
WiFi.forceSleepWake();
delay(1);

Source: GitHub
That also works, I tested it December 2020.  Thanks to Erik Bakke for finding it.  It's a bit more clean than another Deep Sleep boot with the modem enabled.  Igrr and I both struggled to find a way to wake the modem, and Erik mixed the magic sauce.  Hopefully it still works today with the changes to the core WiFi files.

This is not really an answer...

Yes, you understood correctly; after using ESP.deepSleep(n, WAKE_RF_DISABLED) to disable WiFi, the most reliable method to re-enable it is to call ESP.deepSleep(1, WAKE_RF_DEFAULT). Then connect to WiFi on the next wake (which should be in 1 second). Apparently, WAKE_RFCAL and WAKE_NO_RFCAL also result in WiFi working.
A cheap way to approach this, is to normally sleep with WAKE_RF_DISABLED but when your WiFi connection fails, sleep with WAKE_RF_DEFAULT to make the next connection more likely to be successful.
If you want a more elegant, but slightly more complex solution, you can use the RTC memory to store the known WiFi state when you sleep; so when you sleep with WAKE_RF_DISABLED, you'll know that you'll have to reset with WAKE_RF_DEFAULT before trying to connect. And, when you wake again, you'll know the WiFi has been enabled.
As mentioned in another answer, after using WAKE_RF_DISABLED, you could call WiFi.forceSleepBegin() and then immediately call WiFi.forceSleepWake() to try to bring the WiFi back up without resetting. While I have actually found this to work, sadly it seems to be unreliable. Seems like it might work while on USB power, but when changing to another power source, it stops working. I'm not sure why. When using that approach, sometimes the MCU will consume only 40 mA when it's supposed to consume 70 mA with WiFi on, so this suggests to me that the WiFi doesn't properly initialize.
All that being said, I would suggest that using WAKE_RF_DISABLED is quite extreme. Like in your original solution, I have found that you can avoid using WAKE_RF_DISABLED altogether if you call WiFi.forceSleepBegin() immediately when the device starts (i.e. at the top of your setup() function), and then WiFi.forceSleepWake() when you want to use WiFi. When the device starts, there is only perhaps 50-100ms when the device is using 70mA before WiFi is turned off. This is probably acceptable for most low power designs.


text:
Any advice on how to repeat the song 6 times instead of infinitely?
//Here is my code so far
int speakerPin = 9;

int length = 28;

char notes[] = "GGAGcB GGAGdc GGxecBA yyecdc";

int beats[] = { 2, 2, 8, 8, 8, 16, 1, 2, 2, 8, 8,8, 16, 1, 2,2,8,8,8,8,16, 1,2,2,8,8,8,16 };

int tempo = 150;

void playTone(int tone, int duration) {

for (long i = 0; i < duration * 1000L; i += tone * 2) {

   digitalWrite(speakerPin, HIGH);

   delayMicroseconds(tone);

   digitalWrite(speakerPin, LOW);

   delayMicroseconds(tone);

}

}

void playNote(char note, int duration) {

char names[] = {'C', 'D', 'E', 'F', 'G', 'A', 'B',

                 'c', 'd', 'e', 'f', 'g', 'a', 'b',

                 'x', 'y' };

int tones[] = { 1915, 1700, 1519, 1432, 1275, 1136, 1014,

                 956,  834,  765,  593,  468,  346,  224,

                 655 , 715 };

int SPEE = 5;

for (int i = 0; i < 17; i++) {

   if (names[i] == note) {
    int newduration = duration/SPEE;
     playTone(tones[i], newduration);

   }

}

}

void setup() {

pinMode(speakerPin, OUTPUT);

}

void loop() {

for (int i = 0; i < length; i++) {

   if (notes[i] == ' ') {

     delay(beats[i] * tempo);

   } else {

     playNote(notes[i], beats[i] * tempo);

   }

   delay(tempo);

}

}

Assuming, the program can stop after playing 6 times, put another for loop in the loop function:
void loop()
{
   for (int nTimes = 0; nTimes < 6; nTimes++)
   {
      // Existing loop code
   }

   while(true) {};
}

A less crude way is to create a global variable:
int _timesPlayed = 0;

And change the for loop:
void loop()
{
   if (_timesPlayed < 6)
   {
      // Existing loop code

     _timesPlayed++;
   }
}

In most programming contexts, creating a global variable to represent a loop-counter would be considered very crude (rather than less crude), as it's unnecessarily hoisting the scope of the loop-counter from the for-block to not even just the method-scope, but the global-scope.  Is there a special reason that this might be a good thing in Arduino?

@Nat: The benefit of making items global is that it will show up in the summary of compiling so that it shows the amount of used SRAM. Also, some libraries use global defined variables (including those libraries is enough). And if a variable is global, you can access it anywhere (which is not so maintainable, but easy), but by passing parameters the stack is filled which also counts toward the amount of SRAM, although this should be ignorable (passing structs or buffers, not by pointer/reference is not a good idea anyway).


text:
How to extract code on one DT-06 board to another board?
I have two DT-06 boards DT06 datasheet.

The board stock firmware provides Web UI for wifi/network/serial setup. I've replaced the firmware on one board with other sketch; but now I want to revert it to the stock firmware. I cannot find the stock firmware source code anywhere. The DT-06 manufacturer also won't give it out.
Is it possible to extract the stock firmware from another DT-06 board and put it back into the other DT-06 board?
Thank you.

why are you looking for the firmware source?

Have you tried finding the firmware in binary? That would be enough. Mostly firmware isn't opensource, but can be downloaded as hex file.

It could be either binary or source. I can't find both. Can I extract its binary from one of my  DT-06?

Did you copy from one DT-06 to another DT-06 with the above program? I would also like you to show me the connections. Thanks.

Just save the stock firmware from one DT-06 on your pc/laptop and flash the saved firmware to another DT-06 which stock firmware was replaced earlier See my commands in my answer below.

Okay. I found a way to extract the binary file (stock firmware) from one DT-06 and flash it to another modified DT-06, by using esptool command
/*To extract firmware */:
esptool.py -p COM4 -b 460800 read_flash 0 0x400000 dt06_backup.bin
/*To flash the backup binary file to another DT-06 */
esptool.py -p com4 write_flash -fm dout 0x00000 dt06_backup.bin

I also have some DT-06 modules that did not come with the original firmware. I appreciate your knowledge. I'm just getting started with the arduino. It would be good for many if you could make the original firmware of the DT-06 Wifi module with the .ino extension as an arduino program.
, or you could send it. thank you: ferbela@freemail.hu

You may download its stock firmware (as a .bin file) from my google drive here:
https://drive.google.com/file/d/1oJyDso02NVfE8YmhDvKFJmyJGmnOsdw2/view?usp=sharing
or as a zip file here:
https://drive.google.com/file/d/1Z19SgD2dpa5PM9bHKWDcOLvxZjFnL2d3/view?usp=sharing
I did not use Arduino software to extract its stock firmware. I use python commands as posted here. Sorry I'm not sure how to make it as xxx.ino as you suggested.


text:
How to program an Arduino Uno to collect data using a timer interrupt and analyze that data in matlab?
I working on a project where I want to collect sensor data (from a sensor) and I want to analyze the first 20 data sample (e.g., find the range, trendline e.t.c.). I know how to compile a timer interrupt in Arduino IDE (using an ISR timer), but how would I be able to do this something similar (ISR timer) in MATLAB. The reason being, I want to collect my sensor data at exactly 20 Hz and using a delay function can prove to be inaccurate. Also, when I run a sample program that collects data in MATLAB, my sample frequencies change from 15Hz to even 24Hz (as shown below) . Does anyone have any suggestion on how I can do this? If the question is not clear enough I can elaborate more in the comments.
This is my MATLAB code:
clear all;
a = arduino('com4', 'uno');
i = 0;
v1 = zeros(1e4,1);
v2 = zeros(1e4,1);
x = zeros(1e4,1);
t = timer('TimerFcn', 'stat=false; disp(''Timer!'')',...
                 'StartDelay',5,'Period', 1);
start(t)

stat=true;
tic
while(stat==true)
   %while i<60
    i = i + 1;
    v1(i) = readVoltage(a, 'A0');
    v2(i) = readVoltage(a, 'A1');
    x(i) = i;
    disp(x(i));
    pause(.00001);

  % end
end
toc

% %Plot voltage versus time
v1 = v1(1:i);
v2 = v2(1:i);
x = x(1:i);

p = v1;
n = v2;
%Plot voltage versus time
figure(1);
plot(x,p,'-',x,n,'-')
xlabel('Elapsed time (sec)')
ylabel('v')
title('Ten Seconds of voltage Data')
%set(gca,'xlim',[t(1) t(i)])
legend('v1', 'v2');

%
delete(t) % Always delete timer objects after using them.

Output is
>> Timer
     1

     2

     3

     4

     5

     6

     7

     8

     9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    25

    26

    27

    28

    29

    30

    31

    32

    33

    34

    35

    36

    37

    38

    39

    40

    41

    42

    43

    44

    45

    46

    47

    48

    49

    50

    51

    52

    53

    54

    55

    56

    57

    58

    59

    60

    61

    62

    63

    64

    65

    66

    67

    68

    69

    70

    71

    72

    73

    74

    75

Timer!
    76

Elapsed time is 5.032553 seconds.
>>

I apologize for the long output. But as you can see, I specified a pause time of .00001, which should give me well over a 20Hz sampling frequency. But I only get 76 samples/5 seconds = 15.2Hz. Also, sometime when I run this the program may collect 79sample/5secons, or even  121sample/5seconds. It just is not consistent. I was hoping to solve this with a timer interrupt that will be hard coded in MATLAB to collect data at exactly 20Hz. Please let me know what y'all think. Thank you.

This is Arduino SE, so we can tell you how to use a timer interrupt in Arduino. But we are no Matlab experts, so your question is off topic here. Currently the sample frequency is directly dependent on the execution time of all the involved function calls, including readVoltage() you didn't account for that I guess. I don't know, what exactly that function does and what firmware you have on the Arduino. Depending on that you might need to write your own firmware, that can be better fitted to your goal. The readVoltage() function might be too slow.

I agree with chrisl: this looks more like a Matlab question than an Arduino question. 2. I don't think Matlab is the right choice for real-time sampling. You could instead let the Arduino handle the timings and send the data through the serial port, then process the data on Matlab.

The latency for matlab with arduino is a known issue. A good start would be to change the default communication speed of 9600 baud

Your title says you want to collect the data with an Uno and analyze it with MATLAB, but your description suggests you are also trying to collect some data with MATLAB. Which one is correct? If it's as the title says, MATLAB doesn't need to sample at all; it only needs to read the collected data from the Uno, after the fact.

You have an Arduino in your project, which runs ISR loops at very precise intervals. There's no point in adding timing on the receiver side. Just timestamp the data and collect it as it comes in.

I've configured the timer differently making use of its UserData property. The timer will update the data every fixed period for a specified number of samples.
close all;
clear all;

% Some useful constants.
NUM_SAMPLES = 20;
PERIOD = 0.05;

global a;
a = arduino('com4', 'uno');

% Initialise data. It will be updated by the timer.
data.i = 0;
data.v1 = zeros(NUM_SAMPLES, 1);
data.v2 = zeros(NUM_SAMPLES, 1);
data.x = (1:NUM_SAMPLES) * PERIOD;

% Initialise timer for a fixed period for a specific number of samples.
t = timer;
t.ExecutionMode = 'fixedRate';
t.Period = PERIOD;
t.TasksToExecute = NUM_SAMPLES;
t.TimerFcn = @TimerCallback;
t.UserData = data;

% Run the timer and wait for it to complete.
start(t);
wait(t);
stop(t);
data = t.UserData;  % Retrieve the updated data.
delete(t);

% Plot voltage versus time.
figure(1);
plot(data.x, data.v1, '-', data.x, data.v2, '-');
xlabel('Elapsed time (s)');
ylabel('Voltage (V)');
title('Voltage Data');
st = sprintf("%0.3f seconds", NUM_SAMPLES * PERIOD);
subtitle(st);
legend('v1', 'v2');

function TimerCallback(obj, event)
    global a;
    obj.UserData.i = obj.UserData.i + 1;
    obj.UserData.v1(obj.UserData.i) = readVoltage(a, 'A0');
    obj.UserData.v2(obj.UserData.i) = readVoltage(a, 'A1');
end

Each communication with Arduino takes 20ms, you have two in the loop so in the ideal conditions you could get 25 readings/second. See here the source
This also depends on the size of the data you request.
I think this is what you are looking for but I cant give you any advice since I don't have Matlab and Octave is not having this feature.


text:
How to run multiple DC motors in different patterns?
I am a complete novice in programming and I hope someone could guide me here. I am doing a haptic research project, where 8 DC coin vibrating motors would be fitted on the fingers of subjects (excluding thumbs), and the subject has to respond the number of fingers they feel the vibrations on.
Every trial has to have a different pattern of outputs, say: in first trial, 4 motors are activated-motor 1, motor5, motor8 and motor 3. In a single trial, the motors have to have a common delay of 150 ms and 4 seconds break after next one starts.
My question is, that in 8 motors, there are 255 different activation patterns possible. How do I define all these 255 patterns and randomise their sequence?
I am using the mega board and connecting each motor to a PWM pin and all having a common ground.
Here is a sample code with 3 such combinations (only seven motors are connected here):
#define viboutpin 2
#define viboutpin1 3
#define viboutpin2 4
#define viboutpin3 5
#define viboutpin4 6
#define viboutpin5 7
#define viboutpin6 8

void setup() {
     pinMode(viboutpin,OUTPUT);// define a pin as output
     pinMode(viboutpin1,OUTPUT);
     pinMode(viboutpin2,OUTPUT);
     pinMode(viboutpin3,OUTPUT);
     pinMode(viboutpin4,OUTPUT);// define a pin as output
     pinMode(viboutpin5,OUTPUT);
     pinMode(viboutpin6,OUTPUT);
}

void loop() {
    digitalWrite(viboutpin,HIGH);
    digitalWrite(viboutpin1,HIGH);
    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin3,HIGH);
    digitalWrite(viboutpin4,HIGH);
    digitalWrite(viboutpin5,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin, LOW);
    digitalWrite(viboutpin1,LOW);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin3,LOW);
    digitalWrite(viboutpin4,LOW);
    digitalWrite(viboutpin5,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin2,HIGH);
    digitalWrite(viboutpin6,HIGH);
    delay(150);
    digitalWrite(viboutpin2,LOW);
    digitalWrite(viboutpin6,LOW);
    delay(2000);

    digitalWrite(viboutpin4,HIGH);
    delay(150);
    digitalWrite(viboutpin4,LOW);
    delay(2000);
}

Why not generate a psuedo random number from 0 to 255 and use it as a code for which motors are to be activated - bit 0 == viboutputpin0, etc.? Then one function can look at each bit in turn and activate that motor if the bit is set, delay, and stop the motors.
You'll probably want to test your code with a few pre-defined test patterns instead of the random ones, and once you're satisfied that it works, randomly seed the random number generator so your project will generate a different pattern each time. One way to do that is to ask via terminal for the operator to click the 'Send' button (or tap the space bar if you're using a separate terminal emulator that sends key by key). Measure the time from the request to the response in microseconds, discard the 2 or 3 least significant bits of the result and keep the next 8. The micros() function's resolution is 4 usec at 16 MHz, is the reason for discarding those 2 lower bits.


text:
Debouncing interrupt using capacitor
I'm currently working on nodeMCU and need to use interrupt pin. I find out there are bouncing problem when using interrupt thus i use capacitor 100uF to solve this problem. The question is by using multiple interrupt pin, do i need multiple capacitor (one for each pin) or only one for all pin? The question arise because if I parallel the capacitor it would increase the capacitance and perhaps would create a problem(?)
I using interrupt pin for LM 393 speed encoder like this one
(for simplicity, i use switch to describe the encoder pin on schematic)
Basically work like switch but no floating pin since it is a comparator, always between high or low.
Schematic :

You are talking about an interrupt being used for some kind of switch closure, correct?

@timemage input of lm393 encoder

4 encoder using 4 different pin as input

The LM393 is as common comparator.  You're saying "encoder".  So this is confusing. Perhaps you should edit the question to link to the thing you're talking about.  And a diagram of what you're doing maybe of what you're proposing as a possible solution that you're asking about.

sorry for confussions i make, i attach the schematic and some additional info above @timemage

Yeah, that's definitely clearer.  I had about four different interpretations of it before.  It still doesn't quite make sense as drawn.  Being open collector, the LM393 that is part of your encoder boards acts to pull the signal to GND, rather than to VCC as you have modeled.  And It's not clear how the capacitors are supposed to work under the way you've drawn the model.  Just a warning, I'm not sure to what degree others will find this on topic.  So although we may refine the question it may get closed anyway.  We'll see.

Does the output of the encoder board really show bouncing? Thats normally only with mechanical switches. A ready to use module like you showed shouldn't do that. Or did you just assume, that is bounces?

the caps go in parallel to the "switches".

I suggest using a low pass filter where the capacitor is on the micro pin.  You can then add a series resistance to control your debounce time. I do not know the part but are you sure it has internal pull down resistors.


text:
No "Huge APP partition scheme" (ESP32)
I recently downloaded the expressif ESP32 library and I'm trying to run the CameraWebServer example. Attempting to compile it results in the following error:
Sketch uses 2529577 bytes (192%) of program storage space. Maximum is 1310720 bytes.
Sketch too big; see http://www.arduino.cc/en/Guide/Troubleshooting#size for tips on reducing it.

I can reduce this number (192%) to 120% by changing partition scheme from "Default" to "No OTA (Large APP)". Online I've seen people using a partition scheme called "Huge APP", which I believe would solve my problem, but I don't see that option in Tools. Only "Default", "Large App" and "Minimal SPIFFS" (which doesn't work either).
How can I get the "Huge APP" partition scheme option in Arduino IDE?

Did the people online tell what core they are using for their ESP32? Also the used board is important. I use the esp32 core by Espressif Systems and I cannot see such a partition scheme for the Wemos Lolin32, but the ESP32 Dev Module shows more partition options up to 3MB for the app.

I do see the option if I switch the board the ESP32 Dev Module and it compiles successfully! My teacher told me to use the Wemos Lolin32 board, so will it work fine if I change the board to Dev Module?

It's possible to manually edit the board definition (boards.txt) to add a "Huge" partition scheme, if there'e enough storage space available. You can look up the syntax of the board definitions and add huge_app.upload.maximum_size=3145728 (or more, if there's space available) and its associated entries as a new partition scheme under the board entry for your ESP32Cam.

Thank you so much, I found the file and added the partition scheme and it looks like it's working.

I was able to fix the issue by editing the boards.txt file and adding the following lines:
lolin32.menu.PartitionScheme.huge_app=Huge APP (3MB No OTA/1MB SPIFFS)
lolin32.menu.PartitionScheme.huge_app.build.partitions=huge_app
lolin32.menu.PartitionScheme.huge_app.upload.maximum_size=3145728

This will add a "Huge APP" partition scheme to WEMOS Lolin32.

Exactly, this is what I described in my comment. Make sure you have a copy or backup of the altered boards.txt files as it will be overwritten when you update the ESP32 Board Manager.


text:
Why do I need to use latin-1 instead of utf-8 when using python with arduino?
When reading and writing with a python serial port connection to arduino, if I don't use latin-1 ('ISO-8859-1'), the results are not as expected. Like if I have
int outP = 5;
//...
int outV = Serial.read();
analogWrite(outP, outV);

While with python I have
serial_port.write(chr(255).encode())

I read 3.78 V from the pin, whereas if I use
serial_port.write(chr(255).encode(encoding = 'latin-1'))

I get 5.04 V. I have read latin-1 and utf-8 don't always match, but is there something about arduino that requires using latin-1? Of course, these return different values when testing each encoding, using 255 gives b'\xc3\xbf' (from 'Ã¿') with utf-8 or b'\xff' from ('ÿ') with latin-1, but why does arduino work with latin-1?
FYI other options that work are
v = 255

serial_port.write(v.to_bytes(1, byteorder = 'big'))

serial_port.write(bytes[v])

but is there something about arduino that requires using latin-1?

No, not really.
What it comes down to is that Serial.read() reads bytes, irrespective of whatever encoding they may be being used with.  ISO-8859 only encodes character code points in the 0-255 range, so when you choose a 0-255 code point and send it as ISO-8859, it gets sent as 1 byte, which is how you're code has been written to receive it.
A 255 code point as utf-8 would require multiple bytes to encode and so would result in multiple Serial.read() calls for a given value.
If you open a python3 REPL and put chr(255).encode() or more explicitly chr(255).encode('utf-8') you will see it results in b'\xc3\xbf'.  So on the Arduino side you will see this as two separate Serial.read() results, 0xC3 and 0xBF.
When you're just taking in strings and UTF-8 and splatting them out via Serial.println(), the Arduino is blissfully unaware of that they're UTF-8 and not ISO-8859.  Really you could use any encoding you wanted, the the caveat being that if you're using c-strings to store them, the encoding would need to be one that doens't allow for a single null byte to be in the middle of the string.

You may want to look into using struct.pack rather than cobbling together python bytestrings with sequences of chr() and .encode(whatever). struct.pack will also result in a bytestring, but it's more purpose built for doing this.
You can import struct and then struct.pack('B', 255) will result in b'\xff same as chr(255).encode('iso8859-1'), but at least expresses intent.  'B' here signifies an unsigned char range, you'll find the format specifiers in the documentation. You'll get a greater benefit when you begin using multiple fields where struct.pack will be a lot less unwieldy than the chr and encode and string concatenation.

Yes, len(chr(255).encode(encoding = 'latin-1')) returns 1, while len(chr(255).encode()) returns 2

ok thanks, what format should be used with struct.pack?

I have migrated my previous comment into the answer and addressed your question there.


text:
how to control switch (proteus) using bluetooth card (HC-05) and arduino?
This is the first time I use the Internet with the Arduino in the proteus ,
What are the stages that I must follow in order to be able to control the switch via Bluetooth?
If it was possible to clarify more, because I really do not know anything about the other applications, taht my first project in iot.

A switch is a mechanical device. It can only be controlled via bluetooth, if you add a motor, which presses the switch mechanically. Though that cannot be simulated in Proteus. Though I don't think this is, what you are really asking. The switch is connected to pin 2 of the Arduino. So you are reading the switch with your code. I guess you don't want to control the switch, but you want to control, what the switch is controlling via the code. So please include your code and explain, what exactly should happen on what serial data and what problems you have with doing that.

That sounds more like an essay question. I don't know Proteus really, but depending on how accurately it models reality, the HC-05 board needs VCC and GND wired.  Possibly others.


text:
Control DC motor in both directions with two relays
I am using an Arduino and two relays to control 12V DC motor.
I need to rotate the motor in both directions.
For the first trials it worked fine. Finally one next switching fried my Arduino.
I think there is something wrong in the schematic.
I believe that Arduino was killed by reverse voltage spike produced by motor.
I already know that I need a diode across the motor. However, I have two directions here.
So, what is the proper schematic for my task?

Isn't this relay used to control AC devices? http://www.techydiy.org/keyes-sr1y-relay-module/

@Adamelli your link does not help here. That guy does not power an Arduino and a motor with the same power source.

It wasn't to help you. You didn't specify what relay.

@Adamelli, yes, it is a relay module to control AC devices.

Some potential issues to consider: https://electronics.stackexchange.com/a/130253/266181

@Adamelli, I don't power motor from the arduino! look at my schematic. I power motor from an external power supply.

I didn't say you powered the motors from the Arduino. Start reading at, "Yes, you can use a relay as that switch"...

Let us continue this discussion in chat.

please don't crosspost
...  https://electronics.stackexchange.com/questions/552144/control-12v-dc-motor-with-arduino-and-two-relays-in-both-directions

In short, you're probably overloading your regulator.
It's difficult to say for sure, but I have a suspicion and can give a framework for thinking about it with some very crude numbers.
If you're powering the Nano from a 12 V source, you are dropping 7 V across the regulator.  If you do the math on this 7 V drop, it means every 14 mA drawn through the regulator induces nearly a tenth Watt of heat in the regulator.  7 V * 0.014 A = 0.098 W.  I'm guessing you have a budget of perhaps 300mW based on the way the Nano's regulator is set up.
The ATmega328P says it uses 5.2 mA (typical) or 9 mA (maximum) at 5 V and active at 8 MHz.  But really it will use more at the 16 MHz frequency.  For sake of argument, I'm just going to say it's using 14 mA, because it makes the math easy and because power usage scales somewhat linearly with frequency.
Just the power led will use about 3 mA, if it's an official Nano, but for simplicity sake, I'll call it 7 mA, being half of 14 mA and we'll ignore the fact that there are other loads on the board like the serial transceiver.
Your relay coils will use at least 30 mA, but likely more, perhaps a lot more.  But for ease of calculation lets go optimistic and say they only use 28 mA (cause 2 * 14 mA).
So we have the ATMega328P inducing 100 mW in the regulator, the power led and some extras adding 50 mW. at at least one relay coil energized for another 200 mW.  So right there you're already at 350 mW.  If you screwed up and managed to energize both relays, 550 mW.  Hopefully the regulator will enter thermal shutdown when this happens, in which case all you need to do is let it cool down and, you know, stop doing that.  But it may also just die,which is more likely if you have a clone that happens to use a crappier regulator.
But, I think these numbers are conservative.  For example, a datasheet for a Songle SRD-05VDC-SL-C relay that a lot of these modules use seems to say it will use closer 70 mA each, rather than 28 mA.  This means operating just one of these coils by itself, nevermind the rest of the Arduino, will cause nearly half a Watt to be dissipated in the regulator if you're powering from 12 V.  If you managed to turn on both coils well... nothing good.
If this is not the problem you're having, it is a problem.  You can save yourself a fair bit of trouble by powering your Nano from USB with a powered hub or reasonable quality USB-output wall adapter.  Doing so bypasses your regulator altogether.
If you're going to continue staging down 12 V to 5 V for the relay coils, then you may need an external regulator to operate the relay modules, just to unload the the Nano's regulator.  Exactly how you'd go about that depends somewhat on the construction of the relay module.  Some of them make it a bit easier on you and are design to accept voltage from a second source for the coils.


text:
Unable to compile c++11 libraries despite having added -std=c++11 in platform.txt
I want to use c++ data structures such as vectors, arrays, map... in my Arduino sketch. I made sure to add -std=c++11 and -std=gnu++11 in platform.txt, I am still getting the following error message:

fatal error: unordered_map: No such file or directory
#include <unordered_map> compilation terminated. exit status 1 unordered_map: No such file or directory

Here's a snapshot from ~/arduino-nightly/hardware/arduino/avr/platform.txt:

Versions:

Arduino ide: 1.8.14
g++: 5.4.0
avr-g++: 4.9.2

What else should I set up?

The AVR-based Arduinos don't come with anything close to a full C++ standard library implementation.  They have avr-libc which is fairly complete to at least the C99 standard, that is the C standard from 1999, not C++.  What you're doing with -std=c++11 is influencing the standard used by the compiler to interpret the C++ language itself.  This does work fine on AVR based Arduinos, but is not going to give you the sort of C++ containers you may be used to on a desktop or larger embedded system, like an ESP8266.
Much of the C++ standard library would be completely out of place on an AVR based Arduino, particularly those parts that make use of dynamic allocation like unordered_map in your error message.
There are some parts of the C++ library implemented via Arduino STL.  Whether or not you should be using containers from it is another question.
If you do try to use Arduino STL, I'd encourage you to use more conservative parts of it.  Something like an unordered_map, but with less (or no) dynamic allocation could be implemented by using Arduino STL's std::array and functions from its <algorithm> header, like their std::find or std::lower_bound, etc.  Trying to use a C++ map or vector container or something of that sort is kind of asking for trouble, more so on the more common AVR-based Arduinos with only roughly 2 Kbyte of RAM.

Thanks for the answer. Could you show me a way to use std::array in arduino (I am having trouble #including)


text:
Arduino Core for the Raspberry Pi Pico
I recently bought a Raspberry Pi Pico to play with, and am attempting to upload my first program to it the Arduino way, as my own operating system rather than a c++ program over an existing operating system (meaning to replace the built-in Raspberry Pi Pico operating system which runs MicroPython, not in the sense of running Linux, Windows, Mac, or any derivative or fork). I have not found any record of people hacking it like that - is it possible? If so, how would I go about it? Sorry if this is in the wrong Stack Exchange.

operating system? on a pico? maybe an RTOS, but i doubt an OS.

@dandavis What I mean is that an Arduino program is an operating system, albeit extremely minimal and simplistic. Will edit for clarity.

Technically an OS is just a program which has a lot of functionality including advanced memory management. I have edited for clarity.

@nerdguy, don't have a good answer for you, but maybe phrasing that would help.  What you're looking for is "Arduino Core for the Raspberry Pi Pico." in the sense that the UNO uses the Arduino Core for the AVR.  I see one thing on github, but it's an initial commit, and probably with no substance.

@timemage I wasn't entirely certain how to phrase it - thank you!

I recently saw an announcement that Arduino is going to officially include the Raspberry Pico as target board in their Arduino IDE. But I have not found a repo proofing that.

Official support.
Apparently there's official support for it, now anyway.
I was digging around in the Arduino-mbed core, trying to help someone else, specifically in the boards.txt and spied the line:

pico.name=Raspberry Pi Pico

Unfortunately, I don't have any way to give it a proper test as I don't have one of these.  But I did go so far as to install the core and compile a simple hello world program.
In boards manager
Search for "mbed rp2040"; these names sometimes change, but those terms work well now.  You can see in the lower item, I have version 2.0.0 installed.

Board menu selection
Tools/Board/Arduino Mbed OS RP2040/Raspberry Pi Pico

Seems to work.
As you see it at least builds without error.  As I said, I'm unable to give it a real test.  But that at least looks promising.

Here is the library for the Arduino IDE and a Raspberry Pi pico.
https://github.com/lrusak/Arduino-Core-Pico
Just install normally as a .zip.

Thank you! Sorry your original post didn't work out

Yeah, this does look to be more along the lines of what's being asked for.  I dug around that repo a bit and I'm a little skeptical that it actually works though.  Seems to be very early work in progress.

This doesn't seem to be a complete Arduino Core, may files and definition are missing.

It is worth mentioning this excellent alternative to the Arduino one from Earle F. Philhower. It seems well-maintained and doesn't depend on Mbed OS, so it leaves more space (ram and flash) for your application.
Here an informal comparative list.

This alternative doesn't require the Pico to have a serial port (which it won't have when new), but rather can upload to a Pico in bootloader mode. See https://arduino.stackexchange.com/questions/84372/


text:
nodemcu POST request over https return error code -1
I have a nodejs application deployed and have been trying to send data to the api using the following sketch on my nodemcu:

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

void setup() {

Serial.begin(115200);
WiFi.begin("mySSID", "myPassword");

while (WiFi.status() != WL_CONNECTED)

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

}

void loop() {

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

  HTTPClient http;
  http.begin("https://www.livesessions.host/api/v1/readings" , "cc2707645d0222700161a174671cb8b0258eaa91");
  http.addHeader("Content-Type", "application/json");
  String postMessage = "{'deviceMAC':'ddd eee fff', 'humidity':'99', 'soilTemp':'88'}";
  int httpCode = http.POST(postMessage);
  Serial.print("http result:");
  Serial.println(httpCode);
  http.writeToStream(&Serial);
  String payload = http.getString();
  http.end();

  }else{

    Serial.print("Error in Wifi connection");

}

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

}

Although I am able to make data entries using the api and postman, the below code returns -1 (which I think is connection refused), the website is an https site.
Please advise on what I am doing wrong.
Thanks.

supply a WiFiSSLClient object to the HttpClient

@Juraj...Thanks, but can you elaborate with a bit of example code? Would really appreciate it.

see the BasicHttpsClient example


text:
4x4 matrix keypad not working
I'm working on a research project that allows me to press a button on a matrix that then outputs a parameter like temperature, humidity etc. But I cannot find out what is wrong with the buttons, when I press them nothing is happening. Thank you very much! I've attached what the connection between the Arduino and the keypad looks like.
#include <EEPROM.h>
#include <GravityTDS.h>
#include "DHT.h"
#include <LiquidCrystal_I2C.h>
#include <Wire.h>
#include <Servo.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Keypad.h>
LiquidCrystal_I2C lcd(0x27, 16, 2);
#define DHTPIN 7
#define DHTTYPE DHT11   // DHT 11
#define SensorPin A0            //pH meter Analog output to Arduino Analog Input 0
#define Offset 0.00            //deviation compensate
#define LED 13
#define samplingInterval 20
#define printInterval 800
#define ArrayLenth  40    //times of collection
#define PUMPPIN 9
#define ONE_WIRE_BUS 4
int pHArray[ArrayLenth];   //Store the average value of the sensor feedback
int pHArrayIndex = 0;
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
Servo myservo;
GravityTDS gravityTds;
DHT dht(DHTPIN, DHTTYPE);

char incomingByte;
String inputString;
int pump = 9; // Output for pump Control
double avg;
int h;
float t;
float tdsValue;
float temperature = t;
static unsigned long samplingTime = millis();
static unsigned long printTime = millis();
static float pHValue, voltage;

const byte ROWS = 4;
const byte COLS = 4;

char hexaKeys[ROWS][COLS] = {
  {'A', 'B', 'C', 'D'},
  {'E', 'F', 'G', 'H'},
  {'I', 'J', 'K', 'L'},
  {'M', 'N', 'O', 'P'}
};

byte rowPins[ROWS] = {44, 42, 40, 38};
byte colPins[COLS] = {36, 34, 32, 30};

Keypad customKeypad = Keypad(makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

void setup() {

  lcd.begin();
  pinMode(pump, OUTPUT); //sets the digital pin as output
  digitalWrite(pump, LOW); // Initial state of the pump
  Serial.begin(9600);
  gravityTds.setPin(A1);
  gravityTds.setAref(5.0);
  gravityTds.setAdcRange(1024);
  gravityTds.begin();
  dht.begin();
  sensors.begin();
}

double averagearray(int* arr, int number) {
  int i;
  int max, min;
  long amount = 0;
  if (number <= 0) {
    Serial.println("Error number for the array to avraging!/n");
    return 0;
  }
  else if (number < 5) { //less than 5, calculated directly statistics
    for (i = 0; i < number; i++) {
      amount += arr[i];
    }
    avg = amount / number;
    return avg;
  } else {
    if (arr[0] < arr[1]) {
      min = arr[0]; max = arr[1];
    }
    else {
      min = arr[1]; max = arr[0];
    }
    for (i = 2; i < number; i++) {
      if (arr[i] < min) {
        amount += min;      //arr<min
        min = arr[i];
      } else {
        if (arr[i] > max) {
          amount += max;  //arr>max
          max = arr[i];
        } else {
          amount += arr[i]; //min<=arr<=max
        }
      }//if
    }//for
    avg = (double)amount / (number - 2);
  }//if
  return avg;
}

void loop() {
  lcd.print("working so far. test1");
  delay(5000);
  char customKey = customKeypad.getKey();
  int pumptime = 1000;
  switch (customKey) {
    case 'A':
      // pump
      digitalWrite(pump, HIGH); // on pump
      delay(pumptime);
      digitalWrite(pump, LOW);//off pump
      break;
    case 'B':
      // add pump time
      pumptime += 500;
      break;
    case 'C':
      // less pump time
      pumptime -= 500;
      break;
    case 'D':
      // reset pump time
      pumptime = 1000;
      break;
    case 'E':
      //temp
      sensors.requestTemperatures();
      lcd.setCursor(0, 0);
      lcd.print("Celsius temperature: ");
      lcd.print(sensors.getTempCByIndex(0));
      lcd.print((char)223);
      lcd.print("C");
      delay(5000);
      lcd.clear();
      break;
    case 'F':
      // Temperature & humidity
      h = dht.readHumidity();
      t = dht.readTemperature();
      lcd.setCursor(0, 0);
      lcd.print("Humidity:");
      lcd.print(h);
      lcd.print("%");
      lcd.setCursor(0, 1);
      lcd.print("Temperature:");
      lcd.print(t);
      lcd.print((char)223);
      lcd.print("C");
      delay(5000);
      lcd.clear();
      break;
    case 'G':
      // TDS
      h = dht.readHumidity();
      t = dht.readTemperature();
      temperature = t;
      gravityTds.setTemperature(temperature);
      gravityTds.update();
      tdsValue = gravityTds.getTdsValue();
      lcd.setCursor(0, 0);
      lcd.print("TDS: ");
      lcd.print(tdsValue);
      lcd.print("ppm");
      delay(5000);
      lcd.clear();
      delay(5000);
      lcd.clear();
      break;
    case 'H':
      // pH
      lcd.clear();
      lcd.setCursor(0, 0);
      if (millis() - samplingTime > samplingInterval)
      {
        pHArray[pHArrayIndex++] = analogRead(SensorPin);
        if (pHArrayIndex == ArrayLenth)pHArrayIndex = 0;
        voltage = averagearray(pHArray, ArrayLenth) * 5.0 / 1024;
        pHValue = 3.5 * voltage + Offset;
        samplingTime = millis();
      }
      if (millis() - printTime > printInterval)  //Every 800 milliseconds, print a numerical, convert the state of the LED indicator
      {
        lcd.print("Voltage:");
        lcd.print(voltage, 2);
        lcd.print("    pH value: ");
        lcd.println(pHValue, 2);
        digitalWrite(LED, digitalRead(LED) ^ 1);
        printTime = millis();
      }
      delay(5000);
      lcd.clear();
      break;
    case 'I':
      // test buttons
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'J':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'K':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'L':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'M':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'N':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'O':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
    case 'P':
      //
      lcd.print("buttons are working");
      delay(5000);
      lcd.clear();
      break;
  }//switch
  lcd.print("working so far. test2");
  myservo.write(0);
  delay(10000);
  myservo.write(90);

  delay(1800000);

}

start by reducing your code ... read a keypress and print the result ... nothing else

i suspect that you are not pressing the button in the millisecond window after the 30 minute delay ... are you actually waiting 30 minutes for the window when keypress is accepted?

Imho, your delay function in loop() is a root cause.
First, you should remove the below code
  myservo.write(0);
  delay(10000);
  myservo.write(90);

  delay(1800000);

Then,please reduce delay(5000) -> delay(200).
Build and execute your code.
Press and hold a single button and take a look what happen in LCD. At least, you able to confirm the keypad hardware works well or not.


text:
In CLion, how can I set up multiple cpp files for arduino
I'm using the Arduino plugin in CLion. I can't seem to figure out how to have multiple cpp files for my classes. I have been putting the code in my .h up until now, but that's going to bite me soon.


text:
Bluetooth HID for mouse project
I’m working on a project, to create an air mouse for people with repetitive strain injury (since I have it as well). I’m flexible with the hardware required. The plan is to use data from an IMU for movement. I’m currently learning how to work with the sensor.
I have also been researching how to eventually convert the sensor data to mouse movements. I understand that you can do this over Bluetooth (Bluetooth HID, or HID over GATT). However, this is where I reach my limits.
I was hoping to find a library, which can do this for me (similar to the mouse.h library) as it feels like it would take me months learning about the Bluetooth standards to try to implement it myself.
The options I found in my research:

Adafruit boards only library so ties you to their ecosystem
mbedOS library, code seems different then the arduino sketches I’ve
seen so far and is difficult to understand
esp32 based library,    would need to learn how to use that
processor and not sure if    supported properly in arduino IDE)
Arduinoble.h library, would    you need to create the mouse HID
profile from the ground up)

Since many of you are much more experienced than me, I would be grateful for any guidance on how to proceed. Would you show a preference for any of the options above? Or should I be attempting to do things differently, e.g. without a mouse library (but where would I start)?
PS. In case it’s useful, I have basic familiarity with C++ (e.g. I understand classes, pointers, etc.), but I don’t have a programming background. I have done a few simple arduino projects and most of the examples on the official website.

100% ESP32. Yes, it's fully supported by the Arduino IDE (and us).

Hi Majenko, thanks for responding. I saw from a previous reply you'd made a on a different topic that you have significant experience in USB protocols. In the other topic that you responded to, you advise the person not to try to build their own library because it's very difficult. Is the same true for Bluetooth?

I don't know much about bluetooth. I do know that the ESP32 has good libraries and support / documentation through the ESP-IDF though. What you'd have to do to write your own library depends 100% on the hardware. I'd say ESP32 would be the easiest to write for since all the work is done for you in the ESP-IDF and there will be plenty of Arduino-library-like abstraction layers around.

Thank you for the comment, I appreciate the information.

just bumping this in hope for some additional insights from the community.

As a question, it's just overbroad for me to try to tackle with what parts I do know something about.  I didn't mark it that way because I suspect this is not the case for someone else.  I can tell you that HID used in bluetooth and over I2C is related to the HID as it's supported by USB, and that much of the pain of implementing a mouse (or airmouse) will port between them, and different radios/controllers.  This also means that is maybe not as big a problem as you might think if you have to switch between different Bluetooth or USB hardware.  Not compared to the rest of the project anyway.

Thanks for the comment

The Adafruit library does not tie you to Adafruit boards. Mostly it ties you to the bluetooth chip, that is used there (and if special hardware of the MCU is used, to that MCU family). But that will be the case for nearly every library. I'm not qualified enough to give a proper answer about bluetooth, but I would go for the esp32. It is properly supported in the Arduino IDE (you need to install the esp32 core) and gives you lots of possibilities. Also the programming is not that different from normal Arduinos. Did that transition myself a while ago

Thanks for the comment, I appreciate you helping out. Useful advice.

Hopefully we could get some more contributions? I've seen this questions asked a few times on various websites without a good answer. But I appreciate the help nonetheless, don't mean to sound entitled.


text:
My car only moves when it is plugged directly into both my pc and battery pack?
i built a car that works with four motors,one motor driver(specifically the l293d),the arduino and the battery pack with four AA-Batteries. The motors work fine though, but they only work when it is connected to the laptop and the battery pack.I've also removed the METAL insulation from the copper wire and now it is copper.Sadly i have also connected the two poles together and there was some lightning but no fire thankfully(by accident of course).if anyone else had the same issues and fixed them please contact me.
Thank you very much stranger.

If we imagine how you have all this wired together we will be solving imaginary problems.  I'm not sure what you mean by metal insulation.  Shielding? Metal armored cable?

the battery pack came with two copper wires one red and black and then there was some metal at the tip so i removed it to make it longer and now it doesn't work

look the problem is that it only works when it is plugged in both the laptop through the usb and the battery pack with four aa batteries

how do you make something longer by removing part of it?

look the copper wire had a metal tip and then i removed it and removed some insulation and now there is only copper out .

please have one of your friends read your post ... then ask them if they understand what you are describing

so, you have a piece of wire with a stripped end ... how is that a problem?

there is battery holder with two wires out positive and negative. And then i removed the metal tip that was transferring electricity onto the motor driver and along it some insulation to make the wire bigger.And now it only runs when it is connected to both the laptop and the battery holder.by it i mean the car

i don't know if this is the problem. i thought this was the problem.I have also disconnected the power while it was working

maybe you did not reconnect the wire properly or you broke something ... you did not describe anything clearly ... it is difficult to understand what you did if you use terms that make no sense, like make the wire bigger

Given that at least two of us don't understand your descriptions, it makes even more sense than usual that you include in-focus pictures of what you're talking about.

the orange arduino led is flashing and making a weird sound

ok i will try to put a picture

The best thing you can do is post a schematic, not a frizzy thing along with a picture of the parts that you modified and links to all of the other parts. You state: "orange arduino led is flashing and making a weird sound" How does a LED make a sound, they are not designed to. The best thing you can do for yourself is read the Arduino cookbook and do some online tutorials on basic electronics and the arduino.


text:
Power LED Matrix With LiPo Battery & ESP32
I want to power an ESP32 with a 3.7V LiPo battery. There's a LED matrix of 64 WS2812 LEDs attached to the ESP32. I learned that I need a buck boost converter to power the microcontroller as it needs a 5V power input. The boost converter delivers that when there is no matrix attached. However if the matrix is attached it only receives about 2.7V. Turning the potentiometer on the boost converter changes nothing in this case. What is the reason for this? I am sorry if this question seems basic to you. I am an beginner with electronics.
Here is a rather hideous scetch of the connections. I hope this is okay:

This is the buck converter I used: https://www.amazon.de/gp/product/B079H3YD8V/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1

the converter is probably not able to supply required current to power the LEDs

Obviously @jsotola is right, 20x3 = 60mA each led group X 64 means almost 4 amps. way above 2 amps advertised by the seller which are never true. Even with a good boost converter, is your battery capable of supplying 5.5 amps required at the boost converter input?

The way you have it set up is fine if you aren't going to light up all the LEDs at full brightness. And if you do, you're not going to break your ESP32 Dev Board the way you have it set up in your diagram (since you are not running the power THROUGH the board). The LiPo battery probably has its own little regulator on it to prevent it from being damaged.
Check your dev board specifications on how much power you actually need to supply to the Vin pin. The ESP32 chip operates between 2.3 and 3.6 volts (3.3 recommended). Your dev board regulates the 5v to provide that amount to the chip.
Most likely, your dev board will run fine on the 3.7V provided by your LiPo without the buck-boost. I use a similar setup (without a buck-boost) to demo little projects to friends. I use a ESP32U-01 dev board from EZSBC, a 64 LED Matrix from Adafruit, and a 3.7v LiPo battery.
Depending on how many LEDs are lit (and what color), you shouldn't expect the battery to last very long. And the overall brightness of your led matrix will be limited.
If you are using the FastLED Animation Library, I would recommend setting a power limit using set_max_power_in_milliwatts function and limiting it to 1500mW for starters. Again, if you are not drawing power THROUGH the ESP32 board, you're fine.

By the way, if you really want 5v power, which will power your your LEDs better, I would suggest using a standard mobile phone battery pack, like an Anker PowerCore 10000. But DO NOT plug the USB directly into your dev board! Take an old USB cable, cut the end off and create a pigtail with the power wires to plug into the same Vin and LED cables you are using in your diagram.


text:
ESP32 Post Request Not Working
This sample code for the esp32 doesn't work. When contacting the website I get a 301 error and the website acts as if nothing was ever recieved. Note: Been using arduino for 2 years.
/*
  Rui Santos
  Complete project details at Complete project details at https://RandomNerdTutorials.com/esp32-http-get-post-arduino/

  Permission is hereby granted, free of charge, to any person obtaining a copy
  of this software and associated documentation files.

  The above copyright notice and this permission notice shall be included in all
  copies or substantial portions of the Software.
*/

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "lol";
const char* password = "u tried";

//Your Domain name with URL path or IP address with path
String serverName = "http://requestbin.net/r/63agtdpl";

// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;

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

  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());

  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void loop() {
  //Send an HTTP POST request every 10 minutes
  if ((millis() - lastTime) > timerDelay) {
    //Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED){
      HTTPClient http;

      String serverPath = serverName + "?temperature=24.37";

      // Your Domain name with URL path or IP address with path
      http.begin(serverPath.c_str());

      // Send HTTP GET request
      int httpResponseCode = http.GET();

      if (httpResponseCode>0) {
        Serial.print("HTTP Response code: ");
        Serial.println(httpResponseCode);
        String payload = http.getString();
        Serial.println(payload);
      }
      else {
        Serial.print("Error code: ");
        Serial.println(httpResponseCode);
      }
      // Free resources
      http.end();
    }
    else {
      Serial.println("WiFi Disconnected");
    }
    lastTime = millis();
  }
}

doesn't't the site require a secure connection https?


text:
Code for mapping voltage on a sensor and outputting a value in liters
I got a Resistive sender fuel gauge sketch off the internet that I have adapted.  The Resistive sender is a floating magnet that activates read switches to vary the resistance.  Using a stable 5v power source and 100-ohm resistor I have a voltage bridge that is connected to the sender and pin A1.  The original sketch uses this to get the voltage into liters:
TankValue0 = map(sensorTankValue0, 352, 824, 0, 100);
if (TankValue0 < 0) {
  TankValue0 = 0;
}
if (TankValue0 > 100) {
  TankValue0 = 100;

The lower range is not too far off but as you get to the top it is out to lunch.
I have mapped the segments of MY float sensor's intervals, and have found there to be 17 distinct points-- I measured the voltage at each point and made a table (I mean like on paper) to relate the measured voltage at a given point to a distance in mm, and then converted that to the relevant metric of liters in a tank when the float switch is reading a given voltage.

V
L

4.04
94

3.981
88

3.902
84

3.81
81

3.703
77

3.637
72

3.564
69

3.483
65

3.393
61

3.293
57

3.18
53

3.053
50

2.908
46

2.546
42

2.192
38

1.726
35

How do I get that information into the sketch to give me a read-out of L in my tank?
I have no programming knowledge really. I work with Arduino IDE a lot, but only using sketches other people have written.  So, I have a huge basic knowledge gap.  So, please bare that in mind.
This is the whole sketch:
#include <LiquidCrystal_I2C.h>

int TankValue0;
int TankValue1;

LiquidCrystal_I2C lcd(0x27, 16, 2);   // set the LCD address to 0x27 for a 16 chars and 2 line display

void setup() {
  lcd.init();                          // initialize the lcd
  lcd.init();
  lcd.backlight();
  lcd.setCursor(1, 0);
  lcd.clear();
  lcd.print("WORD");
  lcd.setCursor(0, 1);
  lcd.print("TO");
  delay(1500);
  lcd.clear();
  lcd.print("YO ");
  lcd.setCursor(0, 1);
  lcd.print("MOMMA");
  delay(2000);
  lcd.clear();
  pinMode(A0, INPUT);
  Serial.begin(9600);               // starting the Serial Monitor

}
void loop() {
  int sensorTankValue0 = analogRead(A0);
  int sensorTankValue1 = analogRead(A1);
  TankValue0 = map(sensorTankValue0, 352, 824, 34, 94);
  TankValue1 = map(sensorTankValue1, 785, 310, 0, 100);
  if (TankValue0 < 0) {
    TankValue0 = 0;
  }
  if (TankValue1 < 0) {
    TankValue1 = 0;
  }
  if (TankValue0 > 100) {
    TankValue0 = 100;
  }
  if (TankValue1 > 100) {
    TankValue1 = 100;
  }
  lcd.print("S.V. SAVANNAH");
  lcd.setCursor(0, 1);
  delay(100);
  lcd.print("DAY TANK   ");
  lcd.print(TankValue0);
  lcd.print("%");
  lcd.setCursor(0, 0);

  delay(1000);
  lcd.clear();
}

BTW this tank is square, and hold 100L, the float is not long enough to reach the bottom. Later i want to uses this same Arduino for 2 other tanks that are oddly shaped and hold different amounts.

start by drawing a graph

please post the data table as text, not as a picture

V L
4.04 94
3.981 88
3.902 84
3.81 81
3.703 77
3.637 72
3.564 69
3.483 65
3.393 61
3.293 57
3.18 53
3.053 50
2.908 46
2.546 42
2.192 38
1.726 35

I'd use a lookup table for such tasks. It's probably not worth the effort of modelling.

Curve fitting
Well, a lazy way to do it is just to fit a curve to it, using Excel, or Libreoffice, Google Docs or whatever.  Here's gnuplot being used that way to fit a cubic polynomial to it:
"points.txt" containing your data, tab-delimited:
4.04    94
3.981   88
3.902   84
3.81    81
3.703   77
3.637   72
3.564   69
3.483   65
3.393   61
3.293   57
3.18    53
3.053   50
2.908   46
2.546   42
2.192   38
1.726   35

Gnuplot session:
gnuplot> f(x) = A*(x**3) + B*(x**2) + C*x + D
gnuplot> fit f(x) "points.txt" via A, B, C, D
iter      chisq       delta/lim  lambda   A             B             C             D
   0 1.8323200047e+01   0.00e+00  9.28e+01    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
   1 1.8323200047e+01  -4.65e-10  9.28e+00    2.818423e+00  -1.100151e+01   1.447650e+01   2.873579e+01
iter      chisq       delta/lim  lambda   A             B             C             D

After 1 iterations the fit converged.
final sum of squares of residuals : 18.3232
rel. change during last iteration : -4.6534e-15

degrees of freedom    (FIT_NDF)                        : 12
rms of residuals      (FIT_STDFIT) = sqrt(WSSR/ndf)    : 1.23569
variance of residuals (reduced chisquare) = WSSR/ndf   : 1.52693

Final set of parameters            Asymptotic Standard Error
=======================            ==========================
A               = 2.81842          +/- 1.156        (41.02%)
B               = -11.0015         +/- 10.22        (92.86%)
C               = 14.4765          +/- 29.11        (201.1%)
D               = 28.7358          +/- 26.52        (92.27%)

correlation matrix of the fit parameters:
                A      B      C      D
A               1.000
B              -0.998  1.000
C               0.990 -0.997  1.000
D              -0.974  0.987 -0.996  1.000

And here's what looks like against the actual data with plot "points.txt" with linespoints, f(x):

So you have a function:
float f(float x) {
  static const float A =   2.81842;
  static const float B = -11.0015 ;
  static const float C =  14.4765 ;
  static const float D =  28.7358 ;
  const float x_squared = x * x;
  const float x_cubed   = x * x_squared;

  return A * x_cubed + B * x_squared + C * x + D;
}

If you don't care about the code size and the slowness of float arithmetic, then that might be okay.
Otherwise you may want to convert that function to something like fixed point arithmetic.
A cubic polynomial may be overkill, but then whole technique may be also.
Peicewise Linear
You can make a table of you points and just do what graphing programs typically do, linear interpolation between the points.
float f(float x) {
  static const struct pt {
    float v;
    int l;
  } points[] = {
    {0.0  ,  0},  // I put this here for testing, but put a better value here.
    {1.726, 35},
    {2.192, 38},
    {2.546, 42},
    {2.908, 46},
    {3.053, 50},
    {3.18 , 53},
    {3.293, 57},
    {3.393, 61},
    {3.483, 65},
    {3.564, 69},
    {3.637, 72},
    {3.703, 77},
    {3.81 , 81},
    {3.902, 84},
    {3.981, 88},
    {4.04 , 94}
    // you should probably have another entry here so that readings up to 5V work.
  };
  static const size_t table_len = sizeof points / sizeof points[0];

  for (size_t i = 0; i < table_len - 1; ++i) {
    if (x >= points[i].v && x < points[i + 1].v) {
      return
            (x - points[i].v)
          / (points[i + 1].v - points[i].v)
          * (points[i + 1].l - points[i].l)
          + points[i].l;
    }
  }

  return -1;
}

Sitting in the center of this in the return statement is basically a crude implementation of Arduino's map(), but for floating point, which again, you don't really need floating point, even if you want to use this piecewise approach.
In short, you find which two entries of the table you're sitting between, and apply what amounts to map() on the line segment formed by the two table entries.
PROGMEM
Either of the curve fitting or piecewise approach could be used to generate a much larger lookup table out of which you could just chose the nearest point.
If you're doing this on an AVR-based Arduino, the table for the piecewise linear approach or a pure lookup table approach could use PROGMEM for the array.
Regarding float and fixed point
Any of these techniques could be adapted to fixed-point math.
Which ever you use, if you're on AVR based Arduino, keep in mind that there's no hardware floating point support at all, and although double exists as a type it is implemented in avr-gcc as a single precision float.
If you're using one of the non-AVR based Arduinos, it may have support for float (and maybe for double), in which case the generated code may not be so bad, though may still be slower than using integers.
If you can do everything with integers, resulting code should be a lot smaller and faster.  I'm guessing for what you're doing, if either of them are more important, it's probably being smaller.
For using integers, you may be able to keep your input "voltage" as an ADC count, not having an intermediate voltage calculation.  And even if you want single digit liters when you're done, the intermediate interpolation, curve fitting, or table lookup may require that you work in something like centiliters, milliliters, so that values like the A constant from the curve-fitting example can be represented as an integer, e.g.  2818 mL  rather than a cruder 3 L.  If you're not using a plain lookup table and finding the nearest entry, that is if you're using the curve or piecewise linear approach, doing everything in integer arithmetic from ADC count to mL.  Although you'll need to run another curve fitting, since the A, B, etc will representing mL-per-ADC-count not L-per-Volt.  Or scale them from the value given.
And there are other options, piecewise cubic splines, etc.

Thank you so much @timemage. This is a great resource. I must admit I don't fully understand all of it;-)  I will do my research and educate myself.  in the mean time I tried inserting the "Float" code into my sketch but I get  "'lcd' does not name a type" error.

I don't know how literal you are about the uppercase 'F' in "Float", but it's lowercase in actual use.  If you need something more interactive than stackexchange, there's a few hundred Arduino users, including me, on freenode.  There's also the official forums.  If you have specific questions about what I wrote, I can try to address them.


text:
converting int or float into bytes array in arduino
I am trying to send data from one arduino to another over ethernet using udp protocol.
In arduino writing data over udp is like this
UDP.write(buffer, size);

where buffer is an array to send as a series of bytes and size is the size of the array.
Now, i am reading a sensor value from a0 pin of the arduino it will be stored either in int or float type variable. As mentioned earlier udp only sends byte type array. so all i want to do is convert the value stored in the variable to the byte type array.
my variable will be.
pinMode(A0,INPUT);
int data;
byte data_array[Size];

and in loop
data=analogRead(A0);

now i have convert this value in data_array;
Please provide the suggestion with proper explanation.
Thank you

UDP.write((const byte*) &data, sizeof(data));


text:
Arduino stopped showing up in /dev and dmesg without response
Arduino suddenly stopped being recognized.
It is not listed in /dev and
dmesg -w shows no activity at all when un/plugged.
I'm on Fedora 33. The Arduino is MKR-Zero. The cable is ok - other devices work well. I tried it on windows machine - same result - in Arduino IDE the option for port is greyed out.
Very weird thing happened before this issue- when I was trying to flash sketch, audio connected to docking station switched to speakers in laptop and keyboard + mouse connected to the docking station powered down (back light on keyboard went off and could not be turned on) however the Num lock light was on.
I'm afraid that I burned the Arduino - how do I verify if that is the case.
The "ON" LED is lit up when plugged in

Ok, I have no idea what the hell is this, but when I double-press the reset button (while connected/powered on ofc) it works again.
This can be seemingly cycled - press once and it goes wrong, press twice and it's ok again... round and round. Seems more like some retarded "feature"

It's a good feature that lets it stay in the bootloader longer for when you've screwed up the application area (sketch) so badly that it just drop off USB before you can put something else on it.

Dumb bastards put it at the top of the frequently asked questions list on the product page were you certain to never find it. =P

It would be nice to have it in documentation, but why bother, right?


text:
Connect two 64x32 RGB P4 panels Arduino Mega
I'm using an Arduino Mega and two RGB Led Panels to plot some data. The problem is that the data plotted in the first panel is duplicated in the second as well. What I want is to plot the data on both using just one Arduino Mega. Is it possible? I've read that you can achieve it using one Mega for each panel or using a more powerful controller for both. This question was asked before here
Join two rgb ledPanel 32x64 in order to get one 64x64 (How to)
but no clear answer about commands or changes to made in the code were given. Any idea?
Thanks in advance

I'm not sure how to handle this, because you're basically describing your own question as a duplicate.  So, it seems like anyone attempting to answer it shouldn't answer on the existing question.  If you're around here long enough, not very long, to get a few reputation points you'd be able to set a bounty on the existing question.

I voted up and made some minor edits to the linked question. There's a small chance it may receive some attention being further up the list. I also looked in the RGB Matrix library they reference and about the only I have to say about it thus far is a warning, that it will allocate 32643, over 6 KByte for one matrix.  Since the Mega 2560 has 8Kbyte, it doesn't appear that trying to make two instances of it will fly.


text:
Arduino changing output based on wire voltage
I’m new to arduino and I want to build myself smart switch that can be turned of both manualy and via wifi, is there any way to change position of relay based on if another wire is live or not? Im from europe so we have 230V  outlets.
Thanks for the answer.

" change position of relay based on if another wire is live or not?" - What does that mean?

If pysical switch is on then the wire passing thru is live, and id like to make decisions in arduino based on that, for example physical switch is on, then arduino switches relay conected to itself off and vice versa

It may make more sense with a concrete example of how this thing you're building is can be used.

Well, i want to use wifi controled smart switch and also be able to use my normal physical switch even if i turned my lights off with smart switch and also to be able to turn on lights with smart switch even when its truned off by physical switch. So my idea was to split live wire into 3 - one to arduino controled relay, one to normal swich and one to smart switch, and id like to be able to check if wire after normal switch and also after smart is still live so i can base some logics and determine if light should be on or off. I hope i made it clearer.

If I turn your description into a diagram, it might be clearer.  But then, it makes more sense for you to make the diagram and include that in your question along with the description.

I never did a diagram before, but i will try my best to make it right

Well i tried my best, it looks horible and not even speaking about the technical side, but I hope it is enough to understand my problem, I need to know name of the thing that returns true or false based on if is wire live, and it has to be able to handle 230V for long periods of time. My sketch -> https://i.imgur.com/erxAwkC.png

@krystof18, it seems to have done the job just fine.

Maybe a wire coil wound around the wire could pick up the frequency. Though I won't write about this, since I don't know much about how you would measure this, and because I think, that you are looking the wrong way.
You want to switch one device with multiple switches (how these switches are operates is not important for now). You can look at how this is normally done in eletrical installations. Here the switches are all connected to your breaker box. And there is one component, that waits for trigger signals from the switches and will switch the target device (the light in this case) accordingly. So in the end there is only one place, where the light is switched: in the breaker box. The switches in the room are only triggers. The current for the light does not flow through them. Also they don't necessarily need to carry mains voltage (triggers could also be low voltage) (though it seems they are in fact just using mains voltage, for which I don't know the reason. Maybe to avoid additional voltage conversion).
So I propose the following solution: The mains wires (230V) are only connected to the light and a (suitable) relay board. The relay board is connected to the Arduino, which can act as a Smart Switch (switching via WiFi, time based or whatever). For manual switching you can connect a switch or button to the Arduino and program the Arduino to read it and control the relay accordingly.
This solution is way easier, than trying to sense the live voltage on the lines, and this will most likely make it more reliable . It comes down to controlling an relay board and reading a button/switch, both things with tons of tutorials on the web
Note: Since mains voltage is always really dangerous, you should be really really caution. Don't use mains voltage, when developing your device. A simple LED with current limiting resistir connected to the power line of the Arduino through the relay is sufficient to check the complete functionality. Only connect mains voltage, if you are really really sure, that you did everything correct


text:
Controlling a flat brushless DC motor with integrated speed controller
I have recently purchased the Brushless DC-Flat Motors Series 2610 from Faulhaber and I am honestly new to this type of motor as it’s pins are not like any other I have used before. I would appreciate any help on how to connect and code this motor to rotate on an arduino using the integrated speed controller in the motor.

Everything you need to know is in the datasheet. The built in speed controller uses the industry standard 0-10V input signal to control the speed.

What exactly is your problem with it? Have you read the datasheet? Is there something, that you don't understand?

I read the data sheet, but I’m not very good with motors and arduinos so didn’t really know where each pin should be connected to and how to command it to rotate in varying speeds. I apologize for the lack of knowledge and if my question is stupid

You need a circuit to generate 0-10V analogue voltage. You can probably find a shield to do it.


text:
Serial.available is giving data even input data is not coming
Dear friends I have written a code to identify the caller and send a reply SMS to them using sim 800L and pro mini. My program is to identifying the caller number but continuously sending the SMS in an infinite loop. I am not getting what is the reason, kindly help me, thanks in advance. Code is attached
#include <SoftwareSerial.h>
SoftwareSerial Serial1(4,3);
String a;
String CellNumtemp;
String CellNum;

void setup()
{
  Serial.begin(9600);
  Serial1.begin(9600);
  Serial1.println("AT");
  delay(1000);
  Serial1.println("AT+CSMP=17,167,0,0");
  delay(1000);
  Serial1.println("AT+CLIP=1");
  delay(1000);
   }

void loop(){
   if (Serial1.available() > 0){
   String a = Serial1.readString();
   String  CellNumtemp = a.substring(a.indexOf("+91"));
    CellNum = CellNumtemp.substring(0,13);
     Serial1.println("ATH");
     delay(500);
     Serial.println(CellNum);
     delay(500);
    if (a.indexOf("+91") >= 0){
        sendSMS();
       }
     }
  CellNum = "\0";
}

void sendSMS(){  // Function that sends SMS
     Serial1.println("AT+CMGF=1\r");
     delay(1000);
     Serial1.print("AT+CMGS=");
     Serial1.print("\"");
     Serial1.print(CellNum);
     Serial1.print("\"");
     Serial1.println("\r"); // to send SMS
     delay(1000);
     Serial1.println("Happy to see your call. I am good");
      delay(1000);
     Serial1.println((char)26);
     delay(1000);
     Serial1.println();
     delay(5000);
     Serial1.flush();
     delay(2000);
    }

what do you see in the serial monitor? ... use more Serial.println` statements to debug the code ... display the value of variables to see if the values are what you expect


text:
Servo make partial rotation and stop working automatically
I'm using this board in my robotic arm project:
Adafruit PCA9685 16-Channel Servo Driver (
https://learn.adafruit.com/16-channel-pwm-servo-driver/using-the-adafruit-library)
I've connected all of my servo and now I'm trying to calibrating each one.
This is my configuration:

Setup
pwm = Adafruit_PWMServoDriver(0x40);
pwm.begin();
pwm.setOscillatorFrequency(27000000);
pwm.setPWMFreq(50);

Movement
pwm.setPWM(pinPosition, 0, power);

The power is mapped using map and minPulse and maxPulse based on this data structure:
ServoSettings servo0 = ServoSettings{
   0,   // pinPosition
   125,  // minPulse
   400, // maxPulse
   125  // currentPWM
};

I'm using minPulse and maxPulse for calibration and currentPWM to store data for each servo.
Data is sended through iPhone via BLE.

My servo, start rotating from 125 to ~280 and returns to back and stopped working. I need to power off my board and move the servo from its 0 position just to make movements again.
I don't understand two things:

why the rotation is not 180° but about 45°?
why after 45° servo come back home and stop working?

I suppose that is due to a wrong Adafruit library configuration but of course I'm not sure.

Using a manual loop instead of BLE data, result is the same:
moveServo is a wrapper of pwm.setPWM(pinPosition, 0, power)
  delay(1500);
  servoMgr.moveServo(0, 90);
  Serial.println("0");
  delay(1500);
  servoMgr.moveServo(0, 125);
  Serial.println("A");
  delay(1500);
  servoMgr.moveServo(0, 145);
  Serial.println("B");
  delay(1500);
  servoMgr.moveServo(0, 190);
  Serial.println("C");
  delay(1500);
  servoMgr.moveServo(0, 220);
  Serial.println("D");
  delay(1500);
  servoMgr.moveServo(0, 250);
  Serial.println("E");
  delay(1500);
  servoMgr.moveServo(0, 280); // <<<--- here servo come back home and die.
  Serial.println("F");
  delay(1500);
  servoMgr.moveServo(0, 300);
  Serial.println("G");

The Adafruit board is powered with an external 9V battery.
Arduino is powered with USB cable.
Can be something related to voltage?
What's wrong with the library configuration?
The board now have only 1 servo attached, just for test.
These are the used servo: https://www.amazon.it/dp/B07KD6NVPM
thanks for your suggestions.

Just to check: You are not using the standard 9V block batteries?

Like this one: https://www.amazon.it/Duracell-Plus-Power-6LP3146-Transistor/dp/B004W7GYGQ/

These 9V block batteries are made for low power applications. They cannot provide much current. It might well be the problem. Please try a better power supply, for example a 9V wallwart (just to test this), or some AA batteries in series

Thanks @chrisl, I’ll try.