text:
Maduino (Arduino Zero) at91samd21g18 - Unable to connect to the serial port
I have been using this device very little but it was use to work, and it also gave me the same issue in the past, the somewhat I was able to upload again.
I tried to use the reset button, and short GRD with RST pins, but nothing helped.
The device is recognised as Arduino MRK1000 and connected.
I also tried to specify Arduino Zero (Native USB Port).
Under Tools > Get Board Info I get:
BN: Arduino MKR1000
VID 0x2341
PID: 0X804E
SN: 414C4E1[...]

My issue:
When I try to upload the sketch (even empty) it hangs forever, or some times it shows the same message shown when you unplug the device while uploading.
No device found on COM5
Failed uploading: uploading error: exit status 1

The serial monitor is unable to connect
Sketch uses 33108 bytes (12%) of program storage space. Maximum is
262144 bytes. Global variables use 3552 bytes (10%) of dynamic memory,
leaving 29216 bytes for local variables. Maximum is 32768 bytes.
No device found on COM5 Failed uploading: uploading error: exit status 1

Attempted resolution actions:
I tried to use the reset button, and short GRD with RST pins, but nothing helped.
I tried multiple USB ports, different PC, different cable.
For information about the device:
https://github.com/Makerfabs/Maduino-Zero-4G-LTE
https://wiki.makerfabs.com/Maduino_Zero_4G_LTE.html
Requests:
If you could guide me, maybe I can try to "factory reset" the MCU, or maybe try to connect in a different way.
I read about the bootloaders but I don't know how they work and I don't want to try alone and make worse.
The manufacturer didn't reply to my messages,on GitHub I didn't receive any reply either, so this is one last attempt before I throw this into the bin.
If anyone can recommend al alternative board with GPS and LTE/4G connectivity would be a plus.

windoz computer? Try turning it off then on again, then plug in the Arduino.

use double reset to activate the bootloader. the led should pulsate when bootloader waits for upload

@Juraj how do I do the double reset? I tried in different machines, with different cables, it is definitely the sketch I uploaded that broke it.

press the reset button twice?

As suggested by Juraj (thank you), pushing the reset button twice allowed me to upload an empty sketch and "revive" an otherwise unusable device.


text:
GPS module NEO M8M not responding with Atmega 328P
I designed PCb for relay Switching using gps signal for that i am using atmaga 328P-AU and Neo 6M but after connecting gps module its not showing long, lat. i also checked power supply in module pin it shows 4.96V and RX, TX connection are also properly soldered.
i tested simple code to see the uart data in module and it should be something regardless of satelite connection but it shows nothing.
#include <SoftwareSerial.h>

SoftwareSerial mySerial(4, 5); //(RX, TX) check correct pin assignments.

void setup() {

mySerial.begin(9600);

Serial.begin(9600);

Serial.println("GPS start");

}

void loop() {

while (mySerial.available()) {

Serial.write(
mySerial.read());

}

}

in serial monitor it only shows "GPS start" when i press reset button
Schematic

my pcb layout

Actual PCB

So far i have tried this things but didnt get any result.
1.swapping RX,TX pins.
2.changing GPS module.
3.kept gps module in balcony for more than 4 hours.
4.connection checked more than 10 times.

is the GPS module oriented correctly in the plug?

also posted at https://electronics.stackexchange.com/questions/667300/gps-module-neo-m8m-not-responding-with-atmega-328p

yes it is oriented correctly

source: Stack Exchange

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

sort: votes


text:
Buzzer keeps buzzing even though the sensor doesn't detect anything
through the code that I've listed below, the idea was to have a sensor that detects objects in different ranges, if they're quite close, a light strip will turn on yellow with no buzzer. If they're very close, the light strip will turn red and buzzer will buzz rapidly. However in our case, the buzzer keeps buzzing constantly even though there's no object in the vicinity of the sensor.
Below are our code for the input:
#include <Adafruit_NeoPixel.h>

#define TRIGGER_PIN_LEFT 8
#define ECHO_PIN_LEFT 9
#define TRIGGER_PIN_RIGHT 4
#define ECHO_PIN_RIGHT 5
#define NUM_PIXELS 8
#define POTENTIOMETER_PIN A0
#define PIEZO_PIN 10
#define TILT_PIN 6

Adafruit_NeoPixel strip1(NUM_PIXELS, 3, NEO_GRB + NEO_KHZ800);
Adafruit_NeoPixel strip2(NUM_PIXELS, 2, NEO_GRB + NEO_KHZ800);

void setup() {
  pinMode(TRIGGER_PIN_LEFT, OUTPUT);
  pinMode(ECHO_PIN_LEFT, INPUT);
  pinMode(TRIGGER_PIN_RIGHT, OUTPUT);
  pinMode(ECHO_PIN_RIGHT, INPUT);
  pinMode(PIEZO_PIN, OUTPUT);
  pinMode(TILT_PIN, INPUT);
  strip1.begin();
  strip1.show();
  strip2.begin();
  strip2.show();
  Serial.begin(9600);
}

void loop() {
  long duration1, distance1, duration2, distance2;
  int speed = analogRead(POTENTIOMETER_PIN);
  int tilt = digitalRead(TILT_PIN);

  digitalWrite(TRIGGER_PIN_LEFT, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN_LEFT, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN_LEFT, LOW);
  duration1 = pulseIn(ECHO_PIN_LEFT, HIGH);
  distance1 = (duration1/2) / 29.1;

  digitalWrite(TRIGGER_PIN_RIGHT, LOW);
  delayMicroseconds(2);
  digitalWrite(TRIGGER_PIN_RIGHT, HIGH);
  delayMicroseconds(10);
  digitalWrite(TRIGGER_PIN_RIGHT, LOW);
  duration2 = pulseIn(ECHO_PIN_RIGHT, HIGH);
  distance2 = (duration2/2) / 29.1;

  if (distance1 < 200 && distance1 > 50 && tilt == LOW) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 255, 255, 0);
    }
    strip1.show();
  } else if (distance1 < 200 && distance1 > 50 && tilt == HIGH) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 255, 0, 0);
    }
    strip1.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(100);
  } else if (distance1 < 50 && speed > 100) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 255, 0, 0);
    }
    strip1.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(500);
  } else {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip1.setPixelColor(i, 0, 0, 0);
    }
    strip1.show();
  }

  if (distance2 < 200 && distance2 > 50 && tilt == LOW) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 255, 255, 0);
    }
    strip2.show();
  } else if (distance2 < 200 && distance2 > 50&& tilt == HIGH) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 255, 0, 0);
    }
    strip2.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(100);
  } else if (distance2 < 50 && speed > 100) {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 255, 0, 0);
    }
    strip2.show();
    tone(PIEZO_PIN, 500);
    delay(100);
    noTone(PIEZO_PIN);
    delay(500);
  } else {
    for(int i=0; i<NUM_PIXELS; i++) {
      strip2.setPixelColor(i, 0, 0, 0);
    }
    strip2.show();
  }
  Serial.print("Tilt=");
  Serial.println(tilt);
}

Put a Serial.print( ) debug statement after each tone() statement so you know which one is being incorrectly executed. Or maybe you already know from the colour of LED display.

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


text:
RMS Voltage Value
it has been a week that I'm struggling with the arduino to measure the RMS Voltage value. By OSC I can see that the RMS voltage value changes around 3V. But I can't see it by serial port. I think my sampling or conversion has problem and I can't find it. I really appreciate it if anyone can take a look at my codes and suggest anything.
float readRMS_new(int pin, int vref) {
  int numReadings[100];
  const unsigned long samplingInterval = 2;  // Interval between RMS calculations in milliseconds
  unsigned int readingsSum = 0;   // Sum of squared readings
  unsigned int readingsCount = 0; // Number of readings taken
  unsigned long lastSamplingTime = 0;  // Time of the last RMS calculation
  float rmsVoltage = 0;
  float finalVoltage = 0;
  float circuitGain = 4.31;  // Gain of the circuit

  unsigned long currentTime = millis();  // Current time

  // Check if it's time to perform an RMS calculation
  if (currentTime - lastSamplingTime >= samplingInterval) {
    lastSamplingTime = currentTime;  // Update the last sampling time

    // Perform RMS calculation
    for (int i = 0; i < 100; i++) {
      numReadings[i] = analogRead(pin);
      readingsSum += pow(numReadings[i] - vref, 2);
      readingsCount++;
    }

    // Calculate RMS voltage
    float rms = sqrt(readingsSum / readingsCount);
    rmsVoltage = rms * 0.0048;
    finalVoltage = rmsVoltage * circuitGain;

    if (finalVoltage > 0.0f) {
      // Print RMS voltage
      Serial.print("RMS Voltage: ");
      Serial.println(finalVoltage, 3);  // Print with 3 decimal places
    }

    // Reset variables for the next RMS calculation
    readingsSum = 0;
    readingsCount = 0;

    return finalVoltage;
  }

  return 0.0f;  // Return 0 if it's not time to perform an RMS calculation
}

Regards
Farzaneh

What calls  readRMS_new() ? An Interrupt Service Routine or from the loop() ? But, whatever, it is going to be slow with all those maths functions.

please describe the signal that is being sampled ... add the description to your question ... do not add a comment

There are multiple issues with this piece of code:

Local variables, i.e. variables defined inside functions or braced
blocks, are created each time the execution enters the function or
block, and destroyed when it leaves it. Thus, lastSamplingTime will
always be zero when it is checked. If you want the variable to
preserve its value across invocations of the function, you have to
either make it global or qualify it as static.

There is no point in storing the readings in an array, as you never
read back any element of the array other than the one you just
stored. The array is then eating memory for no good reason.

The Arduino will not be able to take more than one reading every
112 µs, or 100 readings in 11.2 ms. There is no point
in trying to ensure a 2 ms interval between RMS calculations.

There is no point in counting the readings: you know you are taking
100 of them.

You should avoid using pow() for squaring an integer: this is a
floating-point function which is prone to rounding errors.

Maybe the most serious issue: on the Mega, an unsigned int is
16-bits, and cannot store numbers larger than 65,535. readingsSum
is very likely going to overflow and give you a meaningless result.

Returning zero to mean “no data available” is probably not a very
good choice, as zero is also a perfectly valid result. You should
consider returning an impossible value, like -1 (an RMS reading
cannot be negative).

Here is how I would write the computation of the RMS value:
long readingsSum = 0;
for (int i =0; i < 100; i++) {
    long reading = analogRead(pin) - vref;
    readingsSum += reading * reading;
}
float rms = sqrt(readingsSum / 100);

Note that reading is of type long in order to avoid the squaring to
overflow.

Thank you all for your time dedication. Finally increasing the sampling and optimize the same codes I could achieve my goals. I will post the functioning code for those who might need it.
float readRMS(int pin, int vref) {

  int lecturas[200]; // declaring the matrix

  float suma = 0; // sum of the squares

  float rms = 0;  // squares mean

  float volt = 0;  //

  float Volt_Final = 0;

  for (int cont = 0; cont < 200; cont++) {

    lecturas[cont] = analogRead(pin);

    delayMicroseconds(200);
  }
  for (int j = 0; j < 200; j++) {

    //Serial.println(lecturas[j]);

    suma = suma + pow((lecturas[j] - vref), 2);

    //Serial.println(suma);
  }
  rms = sqrt((suma / 200));

  volt = (rms / 1024) * 5;

  //Serial.println(volt);

  //suma=0;

  // Reset variables for the next RMS calculation

  rms = 0;

  lecturas[200] = 0;

  //Volt_Final = (volt * 4.31); //real voltage with circuit gain

  return volt;
}

lecturas[200] = 0; is out of bounds. Array indices are 0 to 199


text:
manage some output based on some parameter and rtc
i'm trying to create a program that given a configuration (i've used multiple struct nested) i need in loop() to check for each output if they need to be on or off and set the output accordingly
let me explain the configuration (i'm not sure that this is the best way to make and store this config, suggestions are appreciated)
struct Period
{
    String name;
    String type;
    String value;
};

struct State
{
    String name;
    Period periods[2];
};

struct Output
{
    String name;
    int pin;
    int forcePin;
    State states[2];
};

Output outputs[4];

now i populate the first object (this is something that need to be editable by the user and i was thinking to store it in the EEPROM, for now in the setup() i do this
    outputs[0].name = "OUTPUT 1";
    outputs[0].pin = 27;
    outputs[0].forcePin = 25;
    outputs[0].states[1].name = "STATE 1";
    outputs[0].states[1].periods[0].name = "day";
    outputs[0].states[1].periods[0].type = "BOOL";
    outputs[0].states[1].periods[0].value = "ON";
    outputs[0].states[1].periods[1].name = "night";
    outputs[0].states[1].periods[1].type = "BOOL";
    outputs[0].states[1].periods[1].value = "OFF";
    outputs[0].states[0].name = "STATE 2";
    outputs[0].states[0].periods[0].name = "day";
    outputs[0].states[0].periods[0].type = "BOOL";
    outputs[0].states[0].periods[0].value = "ON";
    outputs[0].states[0].periods[1].name = "night";
    outputs[0].states[0].periods[1].type = "BOOL";
    outputs[0].states[0].periods[1].value = "OFF";

then in the loop i have few function that determinate the state and period and i call this function that should manage all the outputs
globalState in loop read from an input and set the variable
globalPeriod check the time and set if night or day
void manageOutputs()
{
    for (Output out : outputs)
    {
        Serial.println(out.name);
        Serial.println(out.pin);
        Serial.println(out.forcePin);
        if (digitalRead(out.forcePin) == LOW)
        {
            Serial.println("forced on set output");
            digitalWrite(out.pin, HIGH)
            continue;
        }

        Serial.println(out.states[globalState].name);
        Serial.println(out.states[globalState].periods[globalPeriod].name);
        Serial.println(out.states[globalState].periods[globalPeriod].type);
        Serial.println(out.states[globalState].periods[globalPeriod].value);
        if (out.states[globalState].periods[globalPeriod].type.equals("BOOL")) {
            if (out.states[globalState].periods[globalPeriod].value.equals("ON")) {
                digitalWrite(out.pin,HIGH);
            } else {
                digitalWrite(out.pin,LOW);
            }
        }
    }
}

i have multiple type of output in mind for example TIMER (so in the value field i would have some parameter to call another function that will alternate the output on and off for the time given) will have something like "15:10" so it will stay 15 minutes on and 10 minutes off, or a condition (for example if VAR1 > 50) so the field value would have "VAR1:>:50" so it will turn on only if the condition is met. So i will have a switch case where now i check if BOOL.
now that i hope that i have explained the situation, i would like to know if it's a good way to have 3 nested struct or if there is a better solution considering the necessity to have it stored in EEPROM, and if this is a good way to have this kind of condition like this or if there is a better way.
Considering also that in the future i would like to make a webpage or an api to update this kind of configuration from a pc (maybe using a esp-8266 for that, that is also connected to the arduino, or do everything with an esp32, but i would like first to have the basic loop working and then i will make the "UI")
thanks a lot

The 1st issue is this line: digitalWrite(out.pin, HIGH) with no semicolon. Next issue is globalState does not exist. Please read: https://stackoverflow.com/help/minimal-reproducible-example

There are many uses of the String class in these code snippets. Using
strings is quite natural in some higher-level languages. On an Arduino,
however, I would strongly advise you against this for two reasons:

String objects use dynamic memory, which is not friendly to the small
amount of RAM available on a typical Arduino.

Saving a String to EEPROM is not trivial: you do not want to save the
String object (it contains a pointer that would not make sense in
EEPROM context), and you instead have to save the character array it
refers to. This could involve handling complex memory allocation
withing the EEPROM.

Instead of a string meant to handle one of a predefined set of values
("BOOL", "TIMER", ...), use an enum. This is similar to an int,
where each possible value has been given a name (TYPE_BOOL is 0,
TYPE_TIMER is 1, ...). Instead of a string holding numbers, store the
numbers themselves. In essence, you want to create a data storage format
that is friendly to the binary nature of the CPU. If you really have to
store strings, e.g. for names (are those name fields really useful?
they do not look so in the provided example), limit their length and
store them as fixed-size character arrays.
The period::value field is interesting in that it can store different
kinds of information depending on the type field. For such a situation
the appropriate data structure is a discriminated union. A union
is like a struct except that all fields share the same memory space
and only one can be valid at a time. In a discriminated union, the
union is accompanied by  a ytpe field that tells us which is the
valid field.
Applying those principles to your problem could give this kind of data
structure:
// All the possible Period types.
enum Type {
    TYPE_BOOL,
    TYPE_TIMER,
    // etc.
};

// This is a discriminated union.
struct Period
{
    Type type;
    union {  // one union member per possible type.
        bool bool_value;  // valid when type == TYPE_BOOL
        struct {
            int on_time;
            int off_time;
        } timer_value;  // valid when type == TYPE_TIMER
        // etc.
    };
};

struct State
{
    Period periods[2];
};

struct Output
{
    int pin;
    int forcePin;
    State states[2];
};

These data structures can be trivially saved in EEPROM, as they are
self-contained: they hold no pointers to data stored in dynamic memory.
Then, in manageOutputs(), you will read a period's bool_value only
when type is TYPE_BOOL, it's timer_value only when type is
TYPE_TIMER, etc:
void manageOutputs()
{
    for (Output out : outputs)
    {
        if (digitalRead(out.forcePin) == LOW) {
            digitalWrite(out.pin, HIGH);
            continue;
        }
        Period &period = out.states[globalState].periods[globalPeriod];
        switch (period.type) {
            case TYPE_BOOL:
                if (period.bool_value) {
                    digitalWrite(out.pin, HIGH);
                } else {
                    digitalWrite(out.pin, LOW);
                }
                break;
            case TYPE_TIMER:
                digitalWrite(out.pin, HIGH);
                delay(period.timer_value.on_time);
                digitalWrite(out.pin, LOW);
                delay(period.timer_value.off_time);
        }
    }
}

Thanks a lot, the .name are useful to set a name on the output to be easy configurable and to be easier to understand what the output do (i don't think is necessary on the sub struct, but maybe on the main output, i will do some test with char array .. to see if it easy to work with that)


text:
How to connect to MQTT broker from NodeMCU with SSL?
I cannot connect to a MQTT broker from a NodeMCU, when using SSL.
This is the error message:

Attempting MQTT connection...failed, rc=-4 try again in 5 seconds.

When connecting to the same broker via other software like MQTTX or IOT MQTT panel, it does work fine, just the NodeMCU doesn't connect. What does work is using a local IP and port 1883, but as soon as I use the public mqtt broker IP and port 8883, the NodeMCU cannot connect.
I am probably overlooking something. Is it necessary to include the server certificates in the arduino code?
This is the mosquitto.conf:
persistence true
persistence_location /var/lib/mosquitto/
log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d
password_file /etc/mosquitto/passwd

listener 1883
listener 8883
certfile /etc/mosquitto/certs/server.pem
keyfile /etc/mosquitto/certs/server.key

And here is the sample Arduino Code.
#include "ESP8266WiFi.h"
#include "PubSubClient.h"
#include <SPI.h>
#include <Wire.h>

const char* ssid = "MyWiFi";
const char* password = "MyBassword";

const char* mqtt_server = "MyMqttServer";
const char* mqtt_username = "MyUser";
const char* mqtt_password = "MyBassword";
int mqtt_port = 8883;

const char* mqtt_id = __DATE__ " " __TIME__;  //compile date that is used for a mostly unique identifier

WiFiClient espClient;
PubSubClient client(espClient);

void setup()
{
    Serial.begin(115200);
    setup_wifi();
    setup_mqtt();
}

void setup_wifi()
{
    delay(10);
    WiFi.begin(ssid, password);

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

    Serial.println("WiFi connected");
    Serial.println(WiFi.localIP());
}

void setup_mqtt()
    {
        client.setServer(mqtt_server, mqtt_port);
        client.setCallback(callback);

        Serial.println("Modbus RTU Master Online");
    }

void callback(char* topic, byte* payload, unsigned int length)
    {
        Serial.print("Message arrived [");
        Serial.print(topic);
    }

void reconnect()
    {
        // Loop until we're reconnected to MQTT
        while (!client.connected())
            {
                Serial.print("Attempting MQTT connection...");
                // Attempt to connect
                if (client.connect(mqtt_id, mqtt_username, mqtt_password))
                    {
                        Serial.println("connected");
                    }
                else
                    {
                        Serial.print("failed, rc=");
                        Serial.print(client.state());
                        Serial.println(" try again in 5 seconds");
                        // Wait 5 seconds before retrying
                        delay(5000);
                    }
            }
    }

void loop()
{
    delay(1000);

    if (!client.connected())
        {
            reconnect();
        }

    client.loop();
}

use WiFiClientSecure espClient;

That changes the error from rc=-4 to rc=-2. When removing the certfile and keyfile from mosquitto.conf, the NodeMCU can connect via port 8883, but that defeats the purpose of using the cert.


text:
ESP-07s only connects to my wifi very occasionally
I've got an ESP-07s and I used an example code from the internet. When I power it and the program starts, it should just connect to my Wifi network. It has a simple webpage that should be locally accessible in my Wifi network.
I'll start by giving the code:
// Load Wi-Fi library
#include <ESP8266WiFi.h>

const char* ssid     = "MyWifiNetworkName";
const char* password = "MyWifiPassword";

// Set web server port number to 80
WiFiServer server(80);

// Variable to store the HTTP request
String header;

// Auxiliar variables to store the current output state
String output16State = "off";
String output0State = "off";

// Assign output variables to GPIO pins
const int output16 = 16;
const int output0 = 0;

unsigned long currentTime = millis();
unsigned long previousTime = 0;
// Define timeout time in milliseconds (example: 2000ms = 2s)
const long timeoutTime = 2000;

void setup() {
  Serial.begin(115200);
  // Initialize the output variables as outputs
  pinMode(output16, OUTPUT);
  pinMode(output0, OUTPUT);
  pinMode(2, OUTPUT);
  // Set outputs to LOW
  digitalWrite(output16, LOW);
  digitalWrite(output0, LOW);

  // Connect to Wi-Fi network with SSID and password
  Serial.print("Connecting to ");
  Serial.println(ssid);
  WiFi.begin(ssid, password);
  bool ledOn = true;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("~");
    digitalWrite(2, ledOn ? HIGH : LOW);
    ledOn = ! ledOn;
  }
  // Print local IP address and start web server
  Serial.println("");
  Serial.println("WiFi connected.");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  server.begin();
}

void loop(){
  WiFiClient client = server.accept();   // Listen for incoming clients

  if (client) {                             // If a new client connects,
    Serial.println("New Client.");          // print a message out in the serial port
    String currentLine = "";                // make a String to hold incoming data from the client
    currentTime = millis();
    previousTime = currentTime;
    while (client.connected() && currentTime - previousTime <= timeoutTime) { // loop while the client's connected
      currentTime = millis();
      if (client.available()) {             // if there's bytes to read from the client,
        char c = client.read();             // read a byte, then
        Serial.write(c);                    // print it out the serial monitor
        header += c;
        if (c == '\n') {                    // if the byte is a newline character
          // if the current line is blank, you got two newline characters in a row.
          // that's the end of the client HTTP request, so send a response:
          if (currentLine.length() == 0) {
            // HTTP headers always start with a response code (e.g. HTTP/1.1 200 OK)
            // and a content-type so the client knows what's coming, then a blank line:
            client.println("HTTP/1.1 200 OK");
            client.println("Content-type:text/html");
            client.println("Connection: close");
            client.println();

            // turns the GPIOs on and off
            if (header.indexOf("GET /16/on") >= 0) {
              Serial.println("GPIO 16 on");
              output16State = "on";
              digitalWrite(output16, HIGH);
            } else if (header.indexOf("GET /16/off") >= 0) {
              Serial.println("GPIO 16 off");
              output16State = "off";
              digitalWrite(output16, LOW);
            } else if (header.indexOf("GET /0/on") >= 0) {
              Serial.println("GPIO 0 on");
              output0State = "on";
              digitalWrite(output0, HIGH);
            } else if (header.indexOf("GET /0/off") >= 0) {
              Serial.println("GPIO 0 off");
              output0State = "off";
              digitalWrite(output0, LOW);
            }

            // Display the HTML web page
            client.println("<!DOCTYPE html>");
            client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">");
            client.println("<link rel=\"icon\" href=\"data:,\">");
            // CSS to style the on/off buttons
            // Feel free to change the background-color and font-size attributes to fit your preferences
            client.println("");

            // Web Page Heading
            client.println("
Example
");

            // Display current state, and ON/OFF buttons for GPIO 5
            client.println("
GPIO 16 - Status " + output16State + "
");
            // If the output5State is off, it displays the ON button
            if (output16State=="off") {
              client.println("
<button class=\"button\">ON</button>
");
            } else {
              client.println("
<button class=\"button button2\">OFF</button>
");
            }

            // Display current state, and ON/OFF buttons for GPIO 4
            client.println("
GPIO 0 - Status " + output0State + "
");
            // If the output4State is off, it displays the ON button
            if (output0State=="off") {
              client.println("
<button class=\"button\">ON</button>
");
            } else {
              client.println("
<button class=\"button button2\">OFF</button>
");
            }
            client.println("");

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

When I power it, one of the following cases happen:
Case 1
It just connects within, say 3 seconds. This is the desired case. It prints its IP address to the serial output, and when I navigate to its IP, the webpage loads and everything works. Of course, this is as how it should be.
Case 2
It keeps "trying" to connect, and after 1 ~ 2 minutes it is connected, but then the following weird thing happens. It seems to be connected, and when I look in the list of devices that are connected to my router (via router's web interface) it shows the ESP is connected, and has the IP 192.168.2.34.

As shown in my code, the ESP also prints its IP to the serial output as soon as it is connected. In the normal situation (case 1) this IP starts with 192.168.x.x, and this is expected, since all devices shown in the connected devices list have an IP that starts with the same range. But in this case, the IP shown in the serial output is something like "169.254.200.23". Also, the ESP's webpage is not accessible.
So: router shows ESP as connected, having IP 192.168.2.34, while the ESP itself prints a totally different IP (169.254.200.23). The webpage is at none of the given IP's acessible.
Case 3
It just doesn't connect. But I guess this could also be case 2 but then with an indefinitely "trying time" that I haven't waited.

Router settings have never been changed. Everything is kept default as it was when we got it from our internet provider.
I read on the internet an ESP can give problems when the WIfi channel 13 / 14 are used.
The router has set this to automatically choose a channel, and when I look in the router's web interface during a case 2, the channel was 1.
There's no MAC filtering.
The wifi signal strength at the location of the device is excellent.
The router sends both the 2.4 and 5 GHz signals.

It's a 1 / 10 chance that case 1 (desired) occurs.

I suspect insufficient powering

The ESP-07 has a tiny ceramic antenna and a socket (IPEX) for an external antenna. If you use an external antenna, there is a small capacitor on the board which has to be removed. Changing the antenna configuration may help if poor RF performance is the main issue.

Since you are joining an existing WLAN and not creating your own (soft) access point, I suppose you could try explicitly forcing the mode to station mode WiFi.mode(WIFI_STA); Also, this could be similar to your problem where it appears to attribute a 169.254.x.x address to a missing DHCP reponse. https://arduino.stackexchange.com/questions/78604/esp8266-wifi-not-connecting-to-internet-without-static-ip  so you could try giving it a static IP address in the right range.

@6v6gt The question shows an RSSI of -45dBm reported by the router, which is a good value. Poor RF performance is unlikely to be the cause of the problem.


text:
are 4AA batteries (6V) power my arduino
I'm actually new to using arduino , and trying to make a simple car, using two dc motors, a l298n and an arduino, the problem is that a 9v battery doesn't seem enough to just power the l298n and one dc motor , but in the internet some people use an 4AA battery which is 6v and power the arduino 4 dc motors and the l298n so how ?

Have you seen any of these Q+As? https://arduino.stackexchange.com/search?q=l298n

I understand you situation completely as I had also previously experienced the same problem. 9 V batteries are not enough to get the job done.
Therefore, I suggest you to use two 3.7 V Batteries. These batteries are a great alternative and had solved my problem. I hope it will do the same to you.

The name Arduino refers to dozens if not hundreds of different board and processor designs. Since a specific board / processor was not asked about we can only talk in generic terms.
Almost all Arduinos run at either 5 Volts or 3.3 Volts and contain a regulator to convert a wide range of Voltages to this value. That said, these regulators need a minimal drop between the input voltage and the desired regulated voltage in order to operate.  Some require less and are referred to as LDO or Low Drop Out regulators.
As a worse case, consider if this Arduino does not use an LDO regulator and operates at 5 Volts. The difference between the 6 Volt input and Arduino operating Voltage is only 1 Volt. Further, consider if the batteries were not fresh and were only supplying, say, 5.5 Volts. Finally, consider if one or both motors started drawing heavy current from the batteries causing a further drop in Voltage. Any of these cases could cause the Arduino to reset / behave unexpectedly.
Consider trying to use the 9 Volt battery to power the Arduino and the 6 Volt battery to power the motors.

To properly answer your question instead of taking a SWAG as I did would Be for you to post links giving technical information on each of the hardware devices and which Arduino you are using.
Nine Volt (smoke alarm) batteries do not have enough power to properly power an Arduino. Use some larger cells. There are so many places that show this improper configuration, it just will not last if it even works for a short while. Great for the battery manufacturers.
You can also purchase a SEPIC converter for a few bucks, this is a combination Buck/Boost converter. You set the output voltage you want and it will maintain it as long as you're getting the minimum voltage from the battery, even if the battery is at 3.5V and the output is at 5V. The input will range from about 3V to 30V and it will maintain its setpoint. This range is dependent on the device you pick.
The L298N is about the worce choice you can make for the motor driver. It has darlington bipolar outputs, that drop about 1.4 volts per lead or 2.8 - 3.2 volts to the motor depending on the load. That voltage drop is burnt up as heat and is doing nothing useful. Purchase an H-Bridge that is large enough to drive the motor that has MOSFET outputs, you will be much happier with that.
For batteries use whatever is convenient, the SEPIC converter solves that problem. Best to pick them to power the motor and use the SEPIC to power the Arduino Vin pin at about 7.5V. Doing it via the Vin is not as efficient as doing a 5V direct but you get the additional filtering on that input circuit. A lot depends on which Arduino we are talking about. Since you did not mention one I am assuming either a UNO or Nano.


text:
Arduino M0 pro(ATSAMD21G18A-U) to NEO-M8N-0-10 gps interface issue
i trying to interface ATSAMD21G18A-U to NEO-M8N-0-10 gps by using UART.
my problem is here, i  need to use pin 25(rx) and 26(tx) of arduino to interface. i have tried below. but getting
error:C:\Users\lenovo\AppData\Local\Temp\.arduinoIDE-unsaved2023420-9788-1he85tu.af3\sketch_may20a\sketch_may20a.ino:1:10: fatal error: SoftwareSerial.h: No such file or directory
 #include <SoftwareSerial.h>
          ^~~~~~~~~~~~~~~~~~
compilation terminated.

exit status 1

Compilation error: SoftwareSerial.h: No such file or directory

Code:
#include <SoftwareSerial.h>

SoftwareSerial gpsSerial(25, 26); // RX, TX pins for GPS module

void setup() {
  Serial.begin(9600); // Serial monitor for debugging
  gpsSerial.begin(9600); // GPS module communication
}

void loop() {
  if (gpsSerial.available()) {
    char c = gpsSerial.read();
    Serial.print(c); // Print GPS data to Serial monitor
  }
}

I tried to download library but not able find. I am newbie to arduino.

use Serial1 on RX/TX pins


text:
Problem using CH340 driver for Nano
I am at my wits end and hope somebody here can provide some much-needed guidance.
My platform is an Asus ROG AMD laptop running Windows 11.
I recently decided to try working with Arduinos and purchased a Nano Every direct from Arduino.  I installed the Arduino IDE and when I plugged in the Every it showed up in Device Manager under Ports using the FTDI driver (I suspect that the driver was installed when I installed the IDE).
I had some problems with the Every and decided to try a straight Nano. I purchased one from Micro Center and when I plug it in it also appears in Device Manager under Ports, again using the FTDI driver.  When the Arduino IDE could not communicate with the Nano (I did change board and port) I realized that the unit uses an inexpensive Chinese comm chip was told by Micro Center support that I needed to install the CH340 driver.  As recommended I downloaded the driver installation package from wch-ic.com.  When I ran that installation it reported that the driver was already installed, and I do see two ch341ser.inf_amd64_xxxx entries in Windows\System32\DriverStore\FileRepository.
My problem is that I cannot figure out how to make the Nano use the CH340 driver.  When I try to update the driver in Device Manager it tells me that the current driver is the best one.  When I try to force an update by using "Let me pick from a list", browsing to one of the ch341ser.inf_amd64_xxxx folders in DriverStore\FileRepository and selecting CH341SER.INF I am presented with a set of possible models (CH330, CH340, CH340K, CH341, CH341A).  I was unable to find any guidance on which to select, so I (probably unwisely) experimented.  When I choose CH340 or CH341 the update process begins but my laptop abruptly restarts and afterwards the Device Manager entry in Ports is still using the FTDI driver.
I don't know why the CH340 upodate fails and causes a restart.
I don't know if I should try to delete the FTDI driver (and in fact am uncertain how to go about doing that).
I would greatly appreciate whatever help anyone can provide.
IDE output:
avrdude: Version 6.3-20190619
Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
Copyright (c) 2007-2014 Joerg Wunsch
     System wide configuration file is "C:\Users\bobwi\AppData\Local\Arduino15\packages\arduino\tools\avrdude\6.3.0-arduino17/etc/avrdude.conf"

     Using Port                    : COM3
     Using Programmer              : arduino
     Overriding Baud Rate          : 57600

avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xbf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xbf
avrdude done.  Thank you.
Failed uploading: uploading error: exit status 1

may be just set the Processor option in the Tools menu

OK, tried using Processor ATMega328P (instead of ATMega328P (Old Bootloader)) and upload now works using FTDI driver.

Also had to make sure that Serial Monitor was not open when uploading.


text:
Problem when running Servo library with thread (Protothreads)
When running two threads, one for blinking led once every second, one for sweeping the servo 180 degrees. The servo just vibrates.
When I tested adding a serial printout in the run servo for loops for the pos variable it worked but a bit jerky. Any idea what could be the problem?
#include <Arduino.h>
#include <pt.h>
#include <Servo.h>

// put function declarations here:
static struct pt pt1;
static struct pt pt2;
Servo myservo;
int pos = 0;

static int protothreadBlinkLED(struct pt *pt) {
  static unsigned long lastTimeBlink = 0;
  PT_BEGIN(pt);
  while(1) {
    lastTimeBlink = millis();
    PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);
    digitalWrite(LED_BUILTIN, HIGH);
    lastTimeBlink = millis();
    PT_WAIT_UNTIL(pt, millis() - lastTimeBlink > 1000);
    digitalWrite(LED_BUILTIN, LOW);
  }
  PT_END(pt);
}

static int protoThreadRunServo(struct pt *pt) {
  static unsigned long lastServoUpdate = 0;
  PT_BEGIN(pt);
  while(1) {
    lastServoUpdate = millis();
    for(pos = 0; pos < 180; pos += 1) {
      PT_WAIT_UNTIL(pt, millis() - lastServoUpdate > 150);
      myservo.write(pos);
    }
    for(pos = 180; pos >= 1; pos -= 1) {
      PT_WAIT_UNTIL(pt, millis() - lastServoUpdate > 150);
      myservo.write(pos);
    }
  }
  PT_END(pt);
}

void setup() {
  // put your setup code here, to run once:
  pinMode(LED_BUILTIN, OUTPUT);
  myservo.attach(9);
  PT_INIT(&pt1);
  PT_INIT(&pt2);
}

void loop() {
  // put your main code here, to run repeatedly:
  protothreadBlinkLED(&pt1);
  protoThreadRunServo(&pt2);
}

use PT_SLEEP, instead of millis(), as in example code ... PT_SLEEP is non-blocking


text:
Mobile hotspot with wemos d1 mini
I recently got a wemos d1 mini and now am trying to connect it to my IPhone 13's hotspot, however it doesn't connect, I tried to run the wifiscan example - and it doesn't even detect it there.
I tried connecting it to my home router - and this worked hence I have no ideas on fixing it, so any help would be appreciated!

By default the iPhone hotspot is 5GHz only, which is why your ESP8266 can't see it. The ESP8266's WiFi radio is 2.4GHz only.
To enable 2.4GHz on the iPhone hotspot, turn on the "Maximize Compatibility" button under "Settings | Personal Hotspot". Then 2.4GHz devices should be able to connect to the phone.

Thank you!! This completely fixed the issue.


text:
slave arduino receiving commands from two serials
I have a slave arduino connected to a master arduino mega (through UART) and to a RPi (through USB). The slave arduino is set to monitor various SHT85 (through I2C) and NTC sensors. What I would like to do is to have the slave arduino respond to both commands from the master and the RPi.
The code I have works ok for the NTCs but it is sometimes problematic for the SHT sensors. From times to times (every ~10 minutes) some of the sensors do not send back all requested bytes. The functions I am using to write and read are the following:
//
// I2C write
void cmdI2Cwrite(int address, char *cmd) {
  Wire.beginTransmission(address);

  int c = 0;
  for (int i = 0; i < strlen(cmd); i += 2) {
    sscanf(&cmd[i], "%02x", &c);
    Wire.write(c);
  }

  if (Wire.endTransmission() != 0) {
    MySerial->println(F("end trasmission failed"));
  }

  if(address == 112)
  {
    if(cmd[1] == '0')
    {
      MySerial->println(F("OK - unlocked"));
      IsLocked = false;
      }
    else
    {
      MySerial->println(F("OK - locked"));
      IsLocked = true;
    }
  }
  else
  {
    MySerial->println(F("OK"));
  }
}

and for read:
// I2C read
void cmdI2Cread(int address, unsigned int nBytes) {
  delay(15);
  Wire.requestFrom(address, nBytes);

  unsigned char c;
  char cstr[4];

  // check if the same number of bytes are received that are requested.
  if (Wire.available() != nBytes) {
    MySerial->println("Requested bytes not returned");
  }

  for (unsigned int i = 0; i < nBytes; i++) {
      c = Wire.read();
      sprintf(cstr, "%02x", c);
      MySerial->print(cstr);
  }
  MySerial->println();
}

The command: Wire.available() != nBytes is sometimes satisfied and basically I receive no response from the SHT
Both the master and Rpi serials are set to a baud rate of 115200.
I have tried changing cables, shielding cables, reducing the baud rate, implementing some kind of lock mechanism
the problem doesn't seem to appear when I disconnect either the RPi or the master from the slave (so it seems there is some kind of cross talk.. not sure)
Any help would be appreciated
Thank you

the code is incomplete ... it does not compile

which arduino are you using? ... first thing to try when facing communication problems is to reduce the baud rate

Hello,
Thank you for your reply! You are right the code is incomplete! The problem is that the it's rather long and it's a bit complicated to provide a working version here. But the main loop of the slave code where the communication switch from master arduino to rpi occurs should be shared

I am using arduino mega 2560
I have tried decreasing the baud rate for both serials to 9600 and I still get the same issue

Sounds like you're using the same UART pins on your secondary arduino for communicating with the RPi and the primary arduino mega. The USB serial chip is connected to the RX/TX pins a.k.a. UART0 on an arduino. If you've got a Uno/Nano/Mini as a secondary arduino, you'll need SoftwareSerial on different pins to avoid crosstalk (two "clients" on an TX line may pull down the signal too much due to parallel pulldown resistors).


text:
Having issues understanding what "#define GET_STATUS" does
I am trying to use a Waveshare 4.2inch e-paper display with an Adafruit Feather Adalogger M0, but am having issues with two separate instances of #define GET_STATUS being defined differently in different locations. More specifically, in the Demo Library (download) for the Waveshare display, one of the files (epd4in2.h) defines GET_STATUS as 0x71. However, in a file (USBCore.h) I downloaded from the board manager in the ArduinoIDE to be able to support the Feather Adalogger, GET_STATUS is defined as 0.
I've tried messing with the values to see if making them match (both as 0x71 and both as 0) would solve the issue, but it didn't change anything. I can't find any information about what GET_STATUS in general, so I'm unsure what I can even try to fix this issue. Furthermore, I can't find any instances of GET_STATUS being used, so I'm unsure what its significance even is. So, basically, my questions are: 1) what is the significance of GET_STATUS, and 2) how can I reconcile it being used differently in two different places?
Below is the code I'm trying to run (it's the demo code from Waveshare), and the libraries other than "<SPI.h>" are in the demo library download from Waveshare.
#include <SPI.h>
#include "epd4in2.h"
#include "imagedata.h"
#include "epdpaint.h"

#define COLORED     0
#define UNCOLORED   1

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Epd epd;

  if (epd.Init() != 0) {
    Serial.print("e-Paper init failed");
    return;
  }

  /* This clears the SRAM of the e-paper display */
  epd.ClearFrame();

  /**
    * Due to RAM not enough in Arduino UNO, a frame buffer is not allowed.
    * In this case, a smaller image buffer is allocated and you have to
    * update a partial display several times.
    * 1 byte = 8 pixels, therefore you have to set 8*N pixels at a time.
    */
  unsigned char image[1500];
  Paint paint(image, 400, 28);    //width should be the multiple of 8

  paint.Clear(UNCOLORED);
  paint.DrawStringAt(0, 0, "e-Paper Demo", &Font24, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 100, 40, paint.GetWidth(), paint.GetHeight());

  paint.Clear(COLORED);
  paint.DrawStringAt(100, 2, "Hello world", &Font24, UNCOLORED);
  epd.SetPartialWindow(paint.GetImage(), 0, 64, paint.GetWidth(), paint.GetHeight());

  paint.SetWidth(64);
  paint.SetHeight(64);

  paint.Clear(UNCOLORED);
  paint.DrawRectangle(0, 0, 40, 50, COLORED);
  paint.DrawLine(0, 0, 40, 50, COLORED);
  paint.DrawLine(40, 0, 0, 50, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 72, 120, paint.GetWidth(), paint.GetHeight());

  paint.Clear(UNCOLORED);
  paint.DrawCircle(32, 32, 30, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 200, 120, paint.GetWidth(), paint.GetHeight());

  paint.Clear(UNCOLORED);
  paint.DrawFilledRectangle(0, 0, 40, 50, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 72, 200, paint.GetWidth(), paint.GetHeight());

  paint.Clear(UNCOLORED);
  paint.DrawFilledCircle(32, 32, 30, COLORED);
  epd.SetPartialWindow(paint.GetImage(), 200, 200, paint.GetWidth(), paint.GetHeight());

  /* This displays the data from the SRAM in e-Paper module */
  epd.DisplayFrame();

  /* This displays an image */
  epd.DisplayFrame(IMAGE_BUTTERFLY);

  /* Deep sleep */
  epd.Sleep();
}

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

}

When I run the code, I get the following messages
In file included from /home/beingpool/Arduino/epd4in2-demo/epd4in2-demo.ino:28:
/home/<user>/Arduino/libraries/epd4in2/epd4in2.h:64: warning: "GET_STATUS" redefined
   64 | #define GET_STATUS                                  0x71
      |
In file included from /home/beingpool/.arduino15/packages/adafruit/hardware/samd/1.7.11/cores/arduino/Arduino.h:157,
                 from /home/beingpool/.var/app/cc.arduino.IDE2/cache/arduino/sketches/96EFEDEA56FF573B678089A960FFC685/sketch/epd4in2-demo.ino.cpp:1:
/home/beingpool/.arduino15/packages/adafruit/hardware/samd/1.7.11/cores/arduino/USB/USBCore.h:23: note: this is the location of the previous definition
   23 | #define GET_STATUS     0
      |

I updated the question to include the error message I get when I compile the code. I honestly don't know too much about what the issue is that I'm trying to solve, I'm first and foremost looking to understand what the issue even is. It seems to me that these two files that define GET_STATUS need it to be two different values, and I don't know how to make them work together with a single definition.

read the second line of the message

There is no generic meaning in GET_STATUS. Apparently both libraries use the very same identifier for their own different purpose.
If you do not use GET_STATUS in your sketch, you can remove the definition before the inclusion of "epd4in2.h", like this:
#include <SPI.h>
#undef GET_STATUS
#include "epd4in2.h"

// ...

Thank you, this answers my question


text:
what is 400 bad request and how to solve this
AT+CIPSEND=65
link is not valid

ERROR

OK

OK

OK

OK
STATUS:2

OK
\x0BQ\xADUART_DEF=115200,8,1,0,0ATE0
AT+CWMODE=3
AT+CIPMUX=0
AT+CIPMODE=0
AT+CIPSTATUS
AT+CIPSTART="TCP","api.thingspeak.com",80
AT+CIPSTATUS
CONNECT

OK
STATUS:3
+CIPSTATUS:0,"TCP","52.0.107.28",80,38071,0

OK

OK
> AT+CIPSEND=65
GET api.thingspeak.com/update?api_key=M
Recv 65 bytes
E5K4JWXT2ZBSBZ8&field1=0

SEND OK

+IPD,272:HTTP/1.1 400 Bad Request
Server: awselb/2.0
Date: Tue, 23 May 2023 05:45:13 GMT
Content-Type: text/html
Content-Length: 122
Connection: close

<title>400 Bad Request</title>

400 Bad Request

CLOSED

your HTTP request does not match the HTTP protocol

The server name does not belong to the GET request line: it has to be
provided in the Host request header.
Try something this:
server.println("GET /update?api_key=ME5K4JWXT2ZBSBZ8&field1=0 HTTP/1.0");
server.println("Host: api.thingspeak.com");
server.println();  // empty line means "end of request headers"


text:
How to set OTA on ESP 32
I am currently using an evalkit Nina W106-00B board that incorporates an ESP32.
I am desperately trying to implement OTA (Over-The-Air) updates.
I started by modifying my partitions.csv file, which looks like this (without OTA) and works well:
nvs, data, nvs, 0x9000, 0x6000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 1M,
storage, data, spiffs, , 0xF0000,
The "factory" partition corresponds to my .bin file containing the code.
The "storage" partition corresponds to my .bin file containing the web pages and .js files.
I tried to modify it so that when I add a new .bin file containing the code, it goes into the "ota_0" partition, for example, and then boots without using the "factory" partition.
This is what it looks like now:
nvs, data, nvs, 0x9000, 0x6000,
otadata, data, ota, 0xf000, 0x2000,
phy_init, data, phy, 0x11000, 0x1000,
factory, app, factory, 0x20000, 1M,
storage, data, spiffs, 0x120000, 0xF0000,
ota_0, app, ota_0, 0x210000, 1M,
ota_1, app, ota_1, 0x310000, 1M,
I can compile and flash it, but when I start my board, an error message appears in the logs:
ELF file SHA256: 73241a5f6639ca7a
Rebooting...
ets Jul 29 2019 12:21:46
rst:0xc (SW_CPU_RESET),boot:0x33 (SPI_FAST_FLASH_BOOT)
configsip: 0, SPIWP:0xee
clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00
mode:DIO, clock div:2
load:0x3fff0030,len:1256
load:0x40078000,len:13276
ho 0 tail 12 room 4
load:0x40080400,len:3032
entry 0x40080598
assert failed: do_core_init startup.c:339 (flash_ret == ESP_OK)
Backtrace: 0x40081ee2:0x3ffe3a90 0x4008a4bd:0x3ffe3ab0 0x40090fdd:0x3ffe3ad0 0x400d2a13:0x3ffe3bf0 0x400d2abe:0x3ffe3c10 0x4008165e:0x3ffe3c40 0x4007927e:0x3ffe3c90 |<-CORRUPTED
This message keeps looping, and the board attempts to restart without success.
How should I modify my partitions.csv file for it to work correctly?
Thanks,
Zapsalis

the esp32 arduino platform does it for you

i've never modified such a csv file to get ota working on any of the methods Arduino offers ota; www, ide, http...


text:
Arduino-project with color sensor and rgb-led
I want to use a color sensor for my Arduino project with Arduino Uno to detect the colors red, green, blue, orange, yellow purple of leaves of paper and then light my RGB led in those colors. I have no errors in my code, but it fails for some reason :( Can someone help me?
here is the code:
#define s0 8
#define s1 9
#define s2 10
#define s3 11
#define sensorOut 12

#define LED_RED 3
#define LED_GREEN 5
#define LED_BLUE 6

// Variabelen voor de kleurwaarden
int red;
int green;
int blue;

const int RED_COLOR = (255, 0, 0);
const int GREEN_COLOR = (0, 255, 0);
const int BLUE_COLOR = (0, 0, 255);
const int ORANGE_COLOR = (255, 165, 0);
const int PINK_COLOR = (255, 105, 180);
const int PURPLE_COLOR = (128, 0, 128);
const int YELLOW_COLOR = (255, 255, 0);

int color = 0;

void setup() {
  // Zet de seriële communicatie op
  Serial.begin(9600);

  // Initialiseer de pinmodi
  pinMode(s0, OUTPUT);
  pinMode(s1, OUTPUT);
  pinMode(s2, OUTPUT);
  pinMode(s3, OUTPUT);
  pinMode(sensorOut, INPUT);

  pinMode(LED_RED, OUTPUT);
  pinMode(LED_GREEN, OUTPUT);
  pinMode(LED_BLUE, OUTPUT);

  // Zet de frequentie van de kleurensensor op 20% (rode filter)
  digitalWrite(s0, HIGH);
  digitalWrite(s1, LOW);
}

void loop() {
  // Lees de kleurwaarden
  digitalWrite(s2, LOW);
  digitalWrite(s3, LOW);
  red = pulseIn(sensorOut, digitalRead(sensorOut) == HIGH ? LOW : HIGH);
  delay(20);
  digitalWrite(s3, HIGH);
  blue = pulseIn(sensorOut, digitalRead(sensorOut) == HIGH ? LOW : HIGH);
  delay(20);
  digitalWrite(s2, HIGH);
  green = pulseIn(sensorOut, digitalRead(sensorOut) == HIGH ? LOW : HIGH);
  delay(20);

// Controleer op verschillende kleuren
if (red > green && red > blue) {
  color = RED_COLOR; // Rood
} else if (green > red && green > blue) {
  color = GREEN_COLOR; // Groen
} else if (blue > red && blue > green) {
  color = BLUE_COLOR; // Blauw
} else if (red > green && red > blue && green > blue) {
  color = YELLOW_COLOR; // Geel
} else if (red > green && red > blue && blue > green) {
  color = ORANGE_COLOR; // Oranje
} else {
  color = 0; // Geen herkende kleur
}

  // Controleer op verschillende kleuren
  if (color == RED_COLOR) {
    setColor(255, 0, 0); // Rood
  } else if (color == GREEN_COLOR) {
    setColor(0, 255, 0); // Groen
  } else if (color == BLUE_COLOR) {
    setColor(0, 0, 255); // Blauw
  } else if (color == ORANGE_COLOR) {
    setColor(255, 165, 0); // Oranje
  } else if (color == PINK_COLOR) {
    setColor(255, 105, 180); // Roze
  } else if (color == PURPLE_COLOR) {
    setColor(128, 0, 128); // Paars
  } else if (color == YELLOW_COLOR) {
    setColor(255, 255, 0); // Geel
  } else {
    // Geen herkende kleur, zet de led uit
    setColor(0, 0, 0);
  }

  delay(500); // Wacht 500 milliseconden voordat je de volgende kleur controleert
}

// Hulpmethode om de RGB-waarden in te stellen
void setColor(int red, int green, int blue) {
  analogWrite(LED_RED, red);
  analogWrite(LED_GREEN, green);
  analogWrite(LED_BLUE, blue);
}

What does “it fails for some reason” mean? What is the expected behavior of your sketch? What is the actual observed behavior? How exactly do they differ?

Reading your code, I see three points:

Your constants are not assigned the values that you think. const int RED_COLOR = (255,0,0); sets the integer constant to the value 0, i.e. the last value of a comma-separated sequence, see here. Instead, enumerate your color constants, i.e. set red=1, blue=2, etc. Or define a struct with three integer components.
The variable color will never be assigned the values ORANGE_COLOR, PURPLE_COLOR nor YELLOW_COLOR, because of the way you structured the expressions in the if-then-else block. If red > green && red > blue, the program will never even check whether red > green && red > blue && blue > green, because it already entered the first block. And PURPLE_COLOR is not listed in the upper if-else-block at all. Also, I would expect some CYAN_COLOR somewhere in there to cover the shades between green and blue.
What is the exact type of the color sensor? It seems strange to me that it transmits its data via the length of a pulse. If it doesn't, pulseIn() is the wrong method to use. If it really does, you may have a race condition here: I guess that writing to the pins s2/s3 triggers the sensor to start the "data pulse", in which case digitalRead(sensorOut) may already return the "pulse state" instead of the "pre-pulse state" and therefore waits for a different pulse than it should. You'd need to first read sensorOut into a variable, then set s2/s3, then read your data via pulseIn using the variable you set before.

But without having the datasheet of the sensor/knowing the protocol of the sensor, this is all very volatile guesswork. Please improve your question by adding the sensor type (and maybe a wiring diagram) alongside an explanation of what you mean by "it fails". How exactly does it fail? Which part works and which doesn't?
You can also glean more insight into the state of your sketch by writing measured values to the serial monitor using Serial.println.


text:
Bad readings from 12V pwm fan tachometer signal
I have the following circuit:

(The Arduino is powered via the USB)
The problem is that I the reading from the fan's tachometer signal are incorrect,
I tried to add the two resistors as voltage dividers but still the readings are wrong.
When I check the voltage of the tachometer signal with a multimeter, in the time the multimeter is connected the readings are somewhat correct (not 100%).
Here is a snippet from the fan's documentation:

(BTW: When I used a different 12v pwm fan and didn't use a voltage divider the readings were incorrect only in the time I switched the 12v power off until the fan stopped spinning (after it stopped spinning the tachometer stopped sending signals so the rpm was 0 which was correct).)
Working code (correct tacho signal value):
const byte tachpin = 2;

unsigned int tacho = 0;
long int startTime = 0;
long int elapsed = 0;

void setup() {
  Serial.begin(9600);
   // Configure Timer 1 for PWM @ 25 kHz.
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1  = 0;
    TCCR1A = _BV(COM1A1)
           | _BV(COM1B1)
           | _BV(WGM11);
    TCCR1B = _BV(WGM13)
           | _BV(CS10);
    ICR1   = 320;

    pinMode(tachpin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(tachpin), tachisr, RISING);
    startTime = millis();
}

void tachisr(){
  tacho++;
}

void loop() {
      elapsed = millis() - startTime;
      if(elapsed > 1000) {
        int tachcopy = 0;
        noInterrupts();
        tachcopy = tacho;
        tacho = 0;
        interrupts();
        rpm = (tachcopy / 2.0) * (60000 / elapsed);
        Serial.println(rpm,DEC);
      }
      startTime = millis();
}

Correct reading from working code

rpm = 0, tachcopy = 0
rpm = 1150, tachcopy = 39
rpm = 2360, tachcopy = 80
rpm = 2655, tachcopy = 90
rpm = 2773, tachcopy = 94
rpm = 2655, tachcopy = 90
rpm = 1268, tachcopy = 43

Not working code (incorrect tachometer signal):
const byte tachpin = 2;

unsigned int tacho = 0;
long int startTime = 0;
long int elapsed = 0;
long int rpm = 0;
unsigned int pwmValue = 0;
unsigned int outValue = 0;
unsigned int seconds_counter = 0;

void setup() {
  Serial.begin(9600);
   // Configure Timer 1 for PWM @ 25 kHz.
    TCCR1A = 0;
    TCCR1B = 0;
    TCNT1  = 0;
    TCCR1A = _BV(COM1A1)
           | _BV(COM1B1)
           | _BV(WGM11);
    TCCR1B = _BV(WGM13)
           | _BV(CS10);
    ICR1   = 320;

    // Set the PWM pins as output.
    pinMode( 9, OUTPUT); //!!!ADDED LINE!!!

    pinMode(tachpin, INPUT_PULLUP);
    attachInterrupt(digitalPinToInterrupt(tachpin), tachisr, RISING);
    startTime = millis();
}

void tachisr(){
  tacho++;
}

//!! ADDED FUNCTION !!!
void analogWrite25k(int value)
{

    OCR1A = value;

}

void loop() {

      elapsed = millis() - startTime;
      if(elapsed > 1000) {
        int tachcopy = 0;
        noInterrupts();
        tachcopy = tacho;
        tacho = 0;
        interrupts();
        startTime = millis();
        rpm = (tachcopy / 2.0) * (60000 / elapsed);
        Serial.print("rpm = ");
        Serial.print(rpm,DEC);
        Serial.print(", tachcopy = ");
        Serial.println(tachcopy,DEC);

        seconds_counter++;
      }

      analogWrite25k(100); //!!!ADDED LINE!!!

}

Not working code output:

rpm = 737854, tachcopy = 25012
rpm = 738591, tachcopy = 25037
rpm = 737824, tachcopy = 25011
rpm = 738591, tachcopy = 25037
rpm = 738562, tachcopy = 25036
rpm = 737854, tachcopy = 25012
rpm = 738562, tachcopy = 25036
rpm = 737854, tachcopy = 25012
rpm = 738562, tachcopy = 25036
rpm = 737824, tachcopy = 25011
rpm = 738591, tachcopy = 25037
rpm = 737854, tachcopy = 25012
rpm = 738562, tachcopy = 25036
rpm = 737854, tachcopy = 25012
rpm = 738562, tachcopy = 25036
rpm = 737854, tachcopy = 25012

Readings when using 10K ohm resistor as pull up (instead of the voltage divider (10K+4.7K))  and maxing out analogWrite25k - analogWrite25k(320);:

rpm = 6165
rpm = 6401
rpm = 6136
rpm = 6136
rpm = 6165
rpm = 6018
rpm = 6283
rpm = 5870
rpm = 6047
rpm = 6578
rpm = 6460
rpm = 6224
rpm = 5782
rpm = 6047
rpm = 6136
rpm = 6136
rpm = 6313
rpm = 5988
rpm = 6224
rpm = 6195
rpm = 6136
rpm = 5900

Which is interesting because the max speed of the fan is ~3000rpm (so rpm readings are about x2 max fan rpm when maxing out analogWrite25k)
Update:
Added debounce + 10K Ohm to Arduino 5V:
#define DEBOUNCE 10
//Interrupt handler. Stores the timestamps of the last 2 interrupts and handles debouncing
unsigned long volatile ts1=0,ts2=0;
//Calculates the RPM based on the timestamps of the last 2 interrupts. Can be called at any time.
unsigned int calcRPM(){
    unsigned long ts1_copy, ts2_copy;
    noInterrupts();
    ts1_copy = ts1;
    ts2_copy = ts2;
    interrupts();

    Serial.print(ts1_copy);
    Serial.print(" / ");
    Serial.print(ts2_copy);
    Serial.print(" / ");
    Serial.println(ts2_copy - ts1_copy);
    return (60000000.0 / (ts2_copy - ts1_copy ) / 2.0);
}

void tachisr2() {
    unsigned long m=micros();
    if((m-ts2)>DEBOUNCE){
        ts1=ts2;
        ts2=m;
    }
}

Output after adding debounce:

rpm = 2953.92
90923308 / 90923320 / 12
rpm = 2500000.00
91948328 / 91958496 / 10168
rpm = 2950.43
92994188 / 92994200 / 12
rpm = 2500000.00
94031032 / 94031040 / 8
rpm = 3750000.00
95047108 / 95057256 / 10148
rpm = 2956.25
96093308 / 96093320 / 12
rpm = 2500000.00
97119144 / 97129296 / 10152
rpm = 2955.08

When the value is ~2900 it is the correct value.
Update 2
Hope you can help me with another problem, The rpm value is scattering on a range of up to 120rpm+ even on low fan cycle of 800 rpm, of course when the elapsed time wait is bigger the scattering range is lower, the rpm reading might be not precise by about ~10%, I saw videos of live speed reading from BIOS of PC fan connected to PC motherboard and some of the fans are more precise (maybe because of BIOS code? (maybe there is a standard that specifies minimum time before reading the tacho counter?)), The question is are the tachometer sensors on 12V PC fans not supposed to be super precise by design or do I still have some problems with my circuit?, If I want a more precise rpm reading should I use an external tachometer sensor? which one is the best? optical/magnet based?
(btw my current circuit doesn't include the 4.7KOhm resistor from the schematic, only 10KOhm pull up to 5V)

Please show the code, that gave you wrong values and explain how exactly they are wrong and how you veryfied the correct values

@chrisl, added the code, I know the values are wrong because I get >10,000 as the rpm and sometimes negative numbers

@jsotola its the voltage divider, I also tried 10K pull-up connected to 3.3V without the voltage divider and also got incorrect readings

@jsotola, Check my update please, I figured that the problem occurs only when I enabled the pwm output pin.

1. Open Collector Output of a module.
The power for the open collector output should come from the MCU, not (indirectly) from the sensor's power supply. It is very similar to wiring a push button switch on the low side.
Usually, the internal pullup resistor of the Arduino pin which is connected to the module passes enough power to detect the status of this output (as you have done). This internal pullup resistor has a value of around 30k. It is also possible to add a lower value external pull up resistor, if required say because of electrical noise, between the Arduino's 5v power rail and the pin. Ensure, however, that the current is within the tolerance of the connected device.
Measuring PWM voltages with a multimeter will not be successful, as you have discovered. These tend to integrate and show an average voltage. Say 12 volts at a 50% duty cycle will be read as 6 volts. Use an oscilloscope to see the voltage across the wave form.
2. Electrical Interference.
Your figure here tachcopy = 25012 indicate that your 25KHz signal is leaking through and being detected as pulses from the sensor. Powering the open collector via the Nano's 5v power rail (as above) may eliminate this. Maybe also better decoupling on the 12 volt power supply (say adding a big capacitor).
3. Code Issues
Your code has an number of issues which should be cleaned up. Some may show up after only about 25 days. Some may show up after the next recompilation and some affect the accuracy of the results.

unsigned int tacho = 0; should be volatile.
int tachcopy = 0; should be unsigned int to match the data tape it is copying.
Variables which are derived from millis() should be unsigned long (uint32_t) as here: elapsed = millis() - startTime;.
This (60000 / elapsed) should be forced to a floating point division say (60000.0 / elapsed)
This could be in setup() instead of loop(): analogWrite25k(100); //!!!ADDED LINE!!!

4. "rpm readings is about x2 max fan rpm"
I can't explain that. It may be that the sensor output needs to be debounced.
5. Sample debounce routine (lockout principle)
// Simple debounce routine. Based on original code.
// After accepting a pulse locks out further pulses for 3 ms
// Should be OK for 100Hz (period 10ms)

void tachisr(){
  // ISR (external interrupt)
  static uint32_t lastAcceptedPulseAtMs = 0 ; // static initialised once only
  uint32_t ms = millis() ;
  if ( ms - lastAcceptedPulseAtMs >= 3 ) {  // 3 ms - tune if required
    lastAcceptedPulseAtMs = ms ;
    tacho++;
  }
}

Note: An ISR should be quick to execute and should not contain Serial.print() etc.

Yes, debouncing is a must. It sometimes also has positions that are "oscillating" even if it's not running (4-pin fans with 0% pwm)

@KIIV I did a quick search but could not discover what technology is used for the tachometer. Some are very prone to bouncing say a reed switch, however, I doubt if that would last very long in such an application. A hall effect sensor or something optical would be less of a risk. Maybe the OP can tell us what their model uses.

@6v6gt Thanks for your great answer, I will test it in a bit, However I don't understand why tacho need to be volatile? (i'm accessing it only when interrupts are off and one time in ISR). Regarding your question, I don't have access to the FAN controller but My fan is Noctua NF-F12.

@Takata tacho needs to be volatile, because the "source of truth" is in memory, not in the CPU registers. For "normal" variables, the compiler can switch the source of truth between memory and registers as it pleases. But in your case, without volatile, the register containing the tacho value while being in loop() is assigned and filled from memory at the start of loop(), which is before you call noInterrupts(). volatile basically adds machine instructions to LOAD the value from memory into a register in the moment you read the variable in your code (and STORE directly after writing)

@Takata If volatile is missing, the compiler may choose to optimize the register usage as it pleases -- and for that, it assumes a completely linear program, which is decidedly not the case with interrupts. The compiler may even decide to keep the variable completely in the registers -- which are saved on the stack when entering the ISR function and restored when leaving it.

@6v6gt Added debounce code, the rpm value is correct some of the times

DEBOUNCE value of 30 gives good tachometer values 90% of the times, that's not good enough.

@Takata I'm guessing with a signal of max 3,000 RPM (100Hz @ 2 pulses per revolution) you need a lockout of about 3ms if you do it in software. However, if the signal is very noisy, shorter wires and/or making the pull up resistor stronger are options. Probably around 2k pulled up to 5 volts is the strongest you can go to. Do you know what the tachometer sensor is based on ? Hall effect, read switch or other ?

@Takata Your debounce logic looks rather elaborate. I've added as simple version to chapter 5 of my answer. It is simply an extension of your original ISR and requires no additional global or loop() code. It works by accepting the first pulse then ignoring those which follow in the next 3ms.  If the total pullup resistance is around 10K, you could possibly achieve the same effect with 2 or 3  100nF capacitors between pin 2 and GND

@6v6gt Amazing, Thank you very much!

@Takata I've just noticed that the interrupt trigger is the RISING edge in your code. For open collector output it should really be FALLING. The falling edge is cleaner because the transistor at the output pulls down sharply when switched on. When switched off, the output floats up due to the pullup resistor and any capacitive effect of the sensor.  Whether it makes any real difference in your case I don't know.

@6v6gt Actually in my case RISING works better. I posted an update I hope you can help me figure it out, Thanks again!

@Takata Post your updated code. Some things to try (1) reduce the pullup to 5v resistor to around 2k (no lower than 1k) (2) increase the print baud rate from 9600 to 115200 (3) try a 100nf capacitor between nano pin D2 and GND (assumes a ~2k pullup resistor as suggested above). (4) check the output with a n oscilloscope. An alternative would be an optical method with an IR LED and IR photo transistor. A magnetic method could be subject to interference with the existing fan mechanism.


text:
Arduino UNO stuck at 'uploading' with base sketch, nothing wired
This question has been asked before and I have carefully read the other questions, but the solutions have not worked in my case, and the details are not the same as mine.
Description
The Arduino Uno is stuck at uploading with the error avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0x00, with the base sketch.
Details

I am trying with the base empty sketch.
Nothing is wired, nothing connected

Important Remarks

A second Arduino UNO works perfectly fine with the same setup
Loopback test worked - Loopback test instructions
Cable and drivers work fine
Correct port is selected
Rebooting, resetting, upgrading the Arduino IDE have not solved the problem

Important details

The TX LED is slightly but constantly on, and measuring the value of the TX Pin (Digital 1) outputs a value of 2.0 V. This also happens when feeding the Arduino with a 12 V supply, without USB. EDIT Got rid of this part by burning the bootloader via ISP with another Arduino - Bootloader burn instructions
Checking the COM devices via powershell mode outputs something different between the two Arduinos: a locked value of Baud: 115200 for the one not working, while for the one that works it displays Baud: None.

A second Arduino UNO works perfectly fine with the same setup

Sounds like your Uno is faulty. You could read my post here:
Have I bricked my Arduino Uno? Problems with uploading to board
Also What happens when code is uploaded using the bootloader?
The Unos should be simply replaceable. That is, if your setup works on one, then unless you have done something weird to the other one (such as changing the fuses) then that should work too.
Is it a genuine one? Or a cheap knock-off? If it's cheap, well you got what you paid for. Get another.
I have a post on my forum which lets you detect chip signatures and fuses (use your working Uno to run that). It may shed some light on what is happening.


text:
How to Send GPS Data to Firebase via SIM808 GSM Module
I have an Arduino UNO with SIM808 and I'm trying to send my GPS data to the Firebase. I have successfully get a location from SIM808 via serial. However I found that Arduino only supported HTTP communication while the Firebase accepted only HTTPS requests. How can I connect them (Arduino and Firebase) so I can send data to Firebase. Any guide and help can help me a lot thank you so much :)

don't use an Arduino UNO for the project


text:
how to avoid an Arduino pro micro waking up a pc
I have an Arduino Pro Micro only sending data via com port, connected to a PC.
I don't use the USB protocol and I think the Arduino send request with USB and it's the reason why my computer wakes up
I checked the device manager and there is no power management tab for the arduino, so I can't refuse the Arduino to wake the system up.
Also my BIOS don't have any option to wake up on a particular key combination

This "I don't use the USB protoco" is confusing. The Arduino is connected by USB, correct?  So it uses one of over a dozen USB protocols.  Probably USB/CDC.  Or are you trying to emulate a keyboard with the Arduino.  In that case USB/HID. Clearing this up may make it easier for people to answer your question.

No I use it as a standard Arduino only using the com port

The Aduino Pro Micro uses an Atmel,now Microchip, ATMEGA15U4 processor with built in USB. As it is built into the processor (other Arduinos have the USB outside the processor) your program can alter it. In normal operation I suspect the port is configured for USB/CDC and presents its self as a COM device to a Win computer. Did you check the COM device associated w/the Arduino for a power management tab? If there is no Arduino COM device, could your program have changed the USB protocol?

My Arduino appears in the com device as an Arduino Leonardo. And the program I have in is the deej project which I found on GitHub

Well, I'm confused. I just spent a lot of time looking at a github project that hasn't been touched in 2 years trying to figure out if the host Win computer needs to run a GO program or not. Then chasing down what looks like an obsolete discord account (which would likely be a better place to have this discussion). In the end, I'm no more enlightened as to what to suggest. I think the Arduino looks like a USB/CDC and I think your computer is unusual in that it turns on when seeing USB/CDC activity.  Or maybe any USB activity. IDK.

Arduinos with USB modules built in the MCU can announce themselves as compound devices consisting of a COM device, a keyboard and a mouse. At least the Leonardo does this, and I suspect yours, too. You might want to look for such devices with the same VID/PID, and then check your power preferences.

Assuming the computer is turning on due to the data received over the USB cable from the DEEJ box and not from simply plugging in the USB cable from the DEEJ box.
Consider, if this project otherwise works, re-writing the Arduino Sketch to not send out any data until after a specific digital GPIO pin goes from 1 to 0. Place a N.O. push button switch to ground on that digital GPIO pin. Remember to program that pin as a GPIO input with a pull up. If this works, not only will the DEEJ box control volumes, but might also be able to turn on the computer.

Before going to the trouble of re-writing the Sketch and adding a switch you might try to erase the Arduino and confirm that simply plugging on an Arduino does not power up your computer.

I just figured out window wakes up when the deej program is running with the Arduino connected,but when the Arduino is connected without the program running there is no problem.
So trouble is deej

Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

yes, but the questions sounded like how to not wake-up the PC with such a firmware in the Micro

No problem in answering your own question @Hadrox1.  But, it sounds like you are finding the cause and not a solution.  It is encouraged here (as in all stackexchange web sites) to make the question better by editing it instead. So: 1) Are you running a Windows program for DEEJ  on your Windows computer? 2) "without the program running" Is this the program on the Arduino or on the Windows computer? 3) What is returned whey you type "powercfg -requests" into a command prompt on your Windows computer after it has been powered up by DEEJ?


text:
Can I use regular pins (Example: D2, A3, etc...) as serial (RX, TX)?
Python/Arduino Beginner here...
I have a DFplayer I am trying to hook to my Arduino and I want to hook it up through the regular pins instead of the RX and TX pins, but I've not been able to find detailed information on if I can do that and how to set it up... Is this possible to do?

https://docs.arduino.cc/learn/built-in-libraries/software-serial


text:
is it possible for a client esp8266 to control the esp8266 that set as an access point?
Im creating a project where i need to set one of my esp as a hotspot or access point but i would like to put a function where i could control the connected esp8266 client using the esp8266 that set as access point. I wonder if could use the acces point as a remote to control the client. Thank you in advance.

on the TCP/IP level they are peers


text:
Why does a simple LED Blink not work using mbed.h PWM and Arduino Nano BLE?
I have set up a very simple test program to blink an builtin LED using PWM. Following the mbed example and setting the period to 4 seconds (0.25 Hz) and duty cycle to 0.5, the expected behaviour is for the LED to be on for 2 seconds and off for 2 seconds. However, the actual behaviour is that the LED flashes extremely quickly (almost imperceptable to the eye).
#include "mbed.h"

mbed::PwmOut ledPin = mbed::PwmOut(P0_13); //builtin led pin

void setup() {
  ledPin.period(4.0f);
  ledPin.write(0.0f);
}

void loop() {
  // put your main code here, to run repeatedly:
  ledPin.write(0.5f);
}

I have tried adding delay() and wait_ns() with different times in the main loop, tried having the main loop empty and setting the duty cycle in the setup() function as well as changing the period to larger numbers just in case it was in milliseconds all to no avail. Not quite sure what I'm missing from this extremely simple example.

According to mbed example, to create an instance of PwmOut object, it should be PwmOut ledPin(P0_13). For the setup(), set the duty cycle to 50% with ledPin.write(0.5f);, and delete the code within the loop() as itself is already a while(1) loop.

The example you linked has an infinite, but empty, loop - while(1); - following setting up the PWM.
Your loop repeatedly executes ledpin.out(0.5f);
I didn't find the .out() member function to know what it does but my first thought would be comment out the contents of your loop() function and let it also run as an empty infinite loop. Then I'd look at the .out member function and find out what its action is. Output to a pin is usually a boolean. If that is the case with .out(), then 0.5f will be converted to an integer 0 which is identical to boolean 'false', and this loop would repeatedly turn off the LED, and at around a megahertz.

The code he posted executes ledPin.write(0.5f); inside loop, not out.


text:
Barebones AVR - Connecting RESET pin to Vcc
I want to build my first barebones AVR circuit.
I plan on NOT having a RESET button. For this reason, is it valid if I connect the ATMEGA's RESET pin to Vcc directly?
What I mean by this, is that in this scenario, I will not be using a pull-down resistor as well. Just straight to Vcc.
EDIT: This is a part of the schematic:

what does the datasheet say about allowable voltages on the reset pin?

what you are proposing makes no sense ... what advantage do you gain by removing the external reset function? ... you are not using the pin for some other function ... you could bridge two solder pads with a screwdriver if you don't want a physical switch

What Atmega are you using exactly? If you really don't want to connect anything for resetting and also not using it otherwisen you can probably leave this pin unconnected, if there is an internal pullup on it. You can check in the controllers datasheet. This is true for the Attiny controllersn so probably also for the Atmegas

How do you intend to program the ATmega328P if the reset pin is tied to Vcc ?

I updated the question with a pic. I am using ATMega328. I intend to program the chip using Sparkfun's AVR Programmer.

If you are intend to build your own MCU board, you would need to read datasheet. This kind of question can be answered by reading the datasheet, see page 40 of the Reset Logic diagram.

Also read the section on "Serial Downloading", even you don't want to use RESET, there is a dude called Avrdude who help you to upload your code would issue an RESET, if you tied your RESET to VCC, by then it will short it to GND...

If you tie the RESET pin of your ICSP connector directly to Vcc like shown in your schematic, programming via this connector will not work and you might also damage the programmer by shorting one of its outputs to Vcc. Just use a pullup resistor.

Why are you running /RESET to J2? This could conflict with what might be sent by that connector. In fact, what is the purpose of J2 at all? It looks a bit like you intend to program the chip with it. If you can't pull /RESET low you won't be programming the chip (via ICSP anyway).

According to the datasheet linked to by hcheung in their comment, datasheet, on page 41 it states "Figure 10-2. MCU Start-up, RESET Tied to VCC".
I believe it would be OK to tie the pin directly to Vcc.
I also believe the graphical data presented in "Figure 10-2" could be miss-leading if the reader didn't know what Vcc meant, and also because there is no horizontal axis to specify that they are talking about elapsed time, not voltage change.
EDIT
Regarding your comment "Thanks, but now I am not sure if this setup will work with Sparkfun's Pocket AVR Programmer.".
Looking at page 40 of the datasheet, a internal pull-up resistor is built into the MCU.

You could leave the reset pin not connected and see if it still works as expected. Perhaps a high impedance DVOM would show Vcc on that pin. Some people say leave it disconnected if there are no issues from EMI. EEV Blog - Is it ok to leave atmega328p reset pin floating?
The data sheet also mentions the power on reset timeout which may allow you to program the MCU with your programmer once it first starts, (assuming you have tied the reset pin to Vcc and you leave the reset pin disconnected on your programmer).
Another option would be to program the MCU, then connect the reset pin to Vcc through a couple of solder pads you can bridge with a blob of solder.
Once the reset pin is tied to Vcc, using a programmer connected to that pin will likely result in the magic smoke being released from the MCU, your programmer, or both.

FWIW, I have an ATtiny at home with RST tied to Vcc. It has been running flawlessly 24×7 for the past six years.

Thanks, but now I am not sure if this setup will work with Sparkfun's Pocket AVR Programmer.

I updated the question with a pic. I am using ATMega328. I intend to program the chip using Sparkfun's AVR Programmer.

Then don't tie /RESET to VCC. The programming won't work. What are you doing? Trying to save one resistor? If you have J2 as a programming interface, then /RESET needs to be able to be pulled low to start the programming sequence. Either remove J2 altogether and program the chip in advance of going on the board, or use the pull-up resistor. Don't tie it to VCC.

Is it OK if I use a pull-down resistor and omit the button? Or should I include the button in the design, but never solder it?

@user1584421 What pull-down resistor? The ATmega328P reset pin already has a weak pullup resistor. However, it is usual to supplement this with a 10k pullup to Vcc. It is very unusual to tie the reset pin to Vcc because you cannot then program it, as already mentioned several times. You can simply omit the reset button if you don't need to do manual resets.

@user1584421 If you use a pull-down resistor, and it is stronger than the internal pull-up then the processor will be constantly held in Reset, which hardly seems useful.

Or should I include the button in the design, but never solder it? - an imaginary button? Include a pull-up resistor (not a pull-down) to VCC and perhaps have a couple of adjacent pads connected to Reset and Ground, so you can short them with a screwdriver if you need to reset the processor.

Also, since the design appears to have a (6 pin) ICSP header which includes the  ground pin and the (adjacent)  reset pin,  a manual reset can be forced, if required, by momentarily shorting those two pins together.

Unless they tie /RESET to VCC, then it just blows a fuse somewhere.


text:
ESP32 SocketIO Client is not connecting to Flask-SocketIO Server
I'm trying to connect a ESP32 client using SocketIO with a Flask-SocketIO server and it's not getting connected.
The server uses SSL. The local server address is https://192.168.1.137:3000.Is the https causing issue here?
The following is the output from the ESP32 in the serial monitor. Note that esp32 successfully connects to the wifi.
> ["myEvent",{"now":95506}]
> [IOc] Disconnected!
> [IOc] Disconnected!
> [IOc] Disconnected!
> ...

Esp32 code:
/*
* WebSocketClientSocketIOack.ino
*/

#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>
#include <WiFiClientSecure.h>

#include <ArduinoJson.h>

#include <WebSocketsClient.h>
#include <SocketIOclient.h>

WiFiMulti WiFiMulti;
SocketIOclient socketIO;

#define USE_SERIAL Serial

void socketIOEvent(socketIOmessageType_t type, uint8_t * payload, size_t length) {
    switch(type) {
        case sIOtype_DISCONNECT:
            USE_SERIAL.printf("[IOc] Disconnected!\n");
            break;
        case sIOtype_CONNECT:
            USE_SERIAL.printf("[IOc] Connected to url: %s\n", payload);

            // join default namespace (no auto join in Socket.IO V3)
            socketIO.send(sIOtype_CONNECT, "/");
            break;
        case sIOtype_EVENT:
        {
            char * sptr = NULL;
            int id = strtol((char *)payload, &sptr, 10);
            USE_SERIAL.printf("[IOc] get event: %s id: %d\n", payload, id);
            if(id) {
                payload = (uint8_t *)sptr;
            }
            DynamicJsonDocument doc(1024);
            DeserializationError error = deserializeJson(doc, payload, length);
            if(error) {
                USE_SERIAL.print(F("deserializeJson() failed: "));
                USE_SERIAL.println(error.c_str());
                return;
            }

            String eventName = doc[0];
            USE_SERIAL.printf("[IOc] event name: %s\n", eventName.c_str());

            // Message Includes a ID for a ACK (callback)
            if(id) {
                // creat JSON message for Socket.IO (ack)
                DynamicJsonDocument docOut(1024);
                JsonArray array = docOut.to<JsonArray>();

                // add payload (parameters) for the ack (callback function)
                JsonObject param1 = array.createNestedObject();
                param1["now"] = millis();

                // JSON to String (serializion)
                String output;
                output += id;
                serializeJson(docOut, output);

                // Send event
                socketIO.send(sIOtype_ACK, output);
            }
        }
            break;
        case sIOtype_ACK:
            USE_SERIAL.printf("[IOc] get ack: %u\n", length);
            break;
        case sIOtype_ERROR:
            USE_SERIAL.printf("[IOc] get error: %u\n", length);
            break;
        case sIOtype_BINARY_EVENT:
            USE_SERIAL.printf("[IOc] get binary: %u\n", length);
            break;
        case sIOtype_BINARY_ACK:
            USE_SERIAL.printf("[IOc] get binary ack: %u\n", length);
            break;
    }
}

void setup() {
    //USE_SERIAL.begin(921600);
    USE_SERIAL.begin(115200);

    //Serial.setDebugOutput(true);
    USE_SERIAL.setDebugOutput(true);

    // USE_SERIAL.println();
    // USE_SERIAL.println();
    // USE_SERIAL.println();

      // for(uint8_t t = 4; t > 0; t--) {
      //     USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
      //     USE_SERIAL.flush();
      //     delay(1000);
      // }

    WiFiMulti.addAP("ssid", "mypass");

    //WiFi.disconnect();
    while(WiFiMulti.run() != WL_CONNECTED) {
        delay(100);
    }

    String ip = WiFi.localIP().toString();
    USE_SERIAL.printf("[SETUP] WiFi Connected %s\n", ip.c_str());

    // server address, port and URL
    socketIO.begin("192.168.1.137", 3000, "/socket.io/?EIO=4");

    // event handler
    socketIO.onEvent(socketIOEvent);
}

unsigned long messageTimestamp = 0;
void loop() {
    socketIO.loop();

    uint64_t now = millis();

    if(now - messageTimestamp > 2000) {
        messageTimestamp = now;

        // creat JSON message for Socket.IO (event)
        DynamicJsonDocument doc(1024);
        JsonArray array = doc.to<JsonArray>();

        // add event name
        // Hint: socket.on('event_name', ....
        array.add("myEvent");

        // add payload (parameters) for the event
        JsonObject param1 = array.createNestedObject();
        param1["now"] = (uint32_t) now;

        // JSON to String (serializion)
        String output;
        serializeJson(doc, output);

        // Send event
        socketIO.sendEVENT(output);

        // Print JSON for debugging
        USE_SERIAL.println(output);
    }
}

Server code (Removed unrelated parts):
from flask import Flask, render_template, Blueprint, current_app, request, session, url_for, render_template
from flask_socketio import SocketIO, emit

from threading import Thread
from queue import Queue
import logging

loggerPath = baseUrl + "logs/appLog.log"
os.makedirs(os.path.dirname(loggerPath), exist_ok=True)
with open(loggerPath, "a") as f:
    logging.basicConfig( level=logging.INFO,
        # format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        format='%(levelname)s - %(message)s',
        filename=loggerPath
    )
bp = Blueprint('audio', __name__, static_folder='static',
            template_folder='templates')
app = Flask(__name__)

async_mode = "threading"

socketio = SocketIO(app, cors_allowed_origins="*", async_mode=async_mode)

@socketio.on('myEvent')
def test_connect(data):
    logging.info("receiving")

def runApp():
    try:
        certificatePath = os.getenv('BASE_URL')+"SSL/"
        key = certificatePath+"localhost.key"
        certificate = certificatePath+"localhost.crt"
        context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
        context.load_cert_chain(certificate, key)
        ip = socket.gethostbyname(socket.gethostname())
        socketio.run(app, host=ip, port=3000,ssl_context=context)
    except Exception as e:
        logging.error("Exception occurred in: "+__file__, exc_info=True)

q = Queue()
t = Thread(target=wrapper, args=(q, runApp), daemon=True)
t.start()

have you examined the ESP32BasicExample sketch?

Above code is from the WebSockets_Generic\examples\esp32\ESP32_WebSocketClientSocketIO\ESP32_WebSocketClientSocketIO.ino

This is version Socketio issue,I have successfully connected .
This installed version
Werkzeug 2.0.0
Flask 2.3.3
Flask-SocketIO 4.3.1
python-engineio 3.13.2
python-socketio 4.6.0


text:
Strtok operations on Arduino Zero seem to fail in runtime
I am trying to test functionality of strtok() on a new piece of hardware, as I ran out of memory to develop on my Nano. This is a basic example from the internet involving tokenizing the string and reporting the tokenized entries via SerialUSB. I'm running a Rocketscream V3 (Arduino Zero ATSAMD21G18A).
#include <string.h>

void setup() {
  char *token;
  char *mystring = "apples,pears,bananas";

  SerialUSB.begin(9600);
  while (!SerialUSB) { }

  SerialUSB.print("Serial established");

  token = strtok(mystring, ",");

  while (token != NULL) {
    SerialUSB.println(token);
    token=strtok(NULL, ",");
  }
}

The code works as expected on my Nano (with Serial instead of SerialUSB), but while it does compile for the Arduino Zero, the Zero never makes it past printing "Serial established". I have confirmed this by including code (serial print, LED flashing) past the tokenization parts, and these are never executed. The loop() function is never reached, it seems to halt at "token = strtok(mystring, ",");".
I cannot think of a simpler possible way to test strtok(), but it's just not working. Any help would be appreciated.

strtok works by modifying the source string. Your test string points to a constant string.
  char *mystring = "apples,pears,bananas";

This particular platform may put that into read-only memory. Try instead as your test string:
  char mystring [] = "apples,pears,bananas";

I don't have a Zero to test it on, but in any case using strtok on a const string is not recommended forbidden.

If you turn warnings on for the compiler (File -> Preferences) you see this:
 In function 'void setup()':
 warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
   char *mystring = "apples,pears,bananas";

If you are doing something "forbidden" then don't expect good results.

You mean char mystring[] = "apples,pears,bananas";.

Oh, and it's way worse than “not recommended”. It is “undefined behavior”.

The compiler should at least be warning, if not giving an error, for passing a const string to a pointer to char.

Ah, it does if you turn warnings on.

@EdgarBonet Yes, a little typo there. Fixed.

Thank you @Nick_Gammon, I didn't realize I had warnings turned off.  That was all I needed. So, the code as written is undefined behavior, but why does it successfully execute on Nano? Just a quirk of how it handles memory during runtime?

Undefined behaviour, by definition, will behave in unexpected (or indeed, undefined) ways. The Nano may not care that you are writing to read-only memory.