text:
Is an Arduino Uno required to send any sort of command to a NodeMCU?
I have an Amica ESP8266 NodeMCU I want to send some commands to. I have tried sending some commands like 'AT' and 'AT+CWLAP' but I do not get any sort of output for any command I send to it.
Actually I did not send commands the first time I bought it. I flashed it with a deauther program made by spacehuhn then I erased the chip using the esptool.py --port /dev/tty.SLAB_USBtoUART erase_flash command multiple times. Then I heard that you can send commands to the NodeMCU using the Serial Monitor using Arduino. So I tried it but no output. So my question is whether I need an Arduino Uno or has the command which I used to erase the factory code of the NodeMCU broken something?
PS. I am a newbie so I don't know much of this stuff.

With erase_flash you deleted the AT firmware from flash. You can load it back with esptool or with Flash Download Tool (Windows only).
AT firmware download page
Addresses for 4 megabyte flash (more in readme.md of AT firmware):
esptool.py -p /dev/tty.SLAB_USBtoUART write_flash 0x0 boot_v1.7.bin 0x01000 at/512+512/user1.1024.new.2.bin 0x3fc000 esp_init_data_default.bin 0xfe000 blank.bin 0x3fe000 blank.bin

Thanks for your help I just needed to edit your command like this esptool.py -p /dev/tty.SLAB_USBtoUART write_flash 0x0 boot_v1.7.bin 0x01000 at/512+512/user1.1024.new.2.bin 0x3fc000 esp_init_data_default_v08.bin 0xfe000 blank.bin 0x3fe000 blank.bin Now the commands work fine.

I have another question. If I flash another program on my nodemcu will the original firmware be overwritten?

you did that with deauther .. do you not learn from your actions?

@jsotola I can't understand what you're saying.

the AT firmware is nothing special in esp8266. other firmwares exist or you can create your own programs with espressif SDK or with Arduino esp8266 core package

Like 99.999% of all MCUs the ESP8266 can only hold one program in flash at a time - be that "deuther", the "AT" firmware, or your own custom program. As soon as you install one the last one is removed.


text:
Why doesn't pin 3 blink? It blinks in another program
I used toneMelody example code (sketch sample 02.Digital->toneMelody) on an Arduino UNO. Then I wanted to blink an LED with the melody.
Here's the code:
#include "pitches.h"
#define BLUE 3 // pin 3 does not blink. but, pin 9 ok.
#define GREEN 5
#define RED 6

int melody[] = {
  NOTE_C4, NOTE_G3, NOTE_G3, NOTE_A3, NOTE_G3, 0, NOTE_B3, NOTE_C4
};
int noteDurations[] = {
  4, 8, 8, 4, 4, 4, 4, 4
};

void setup() {
  for (int thisNote = 0; thisNote < 8; thisNote++) {
    analogWrite(RED, 0);
    analogWrite(GREEN, 0);
    analogWrite(BLUE, 0);
    int noteDuration = 1000 / noteDurations[thisNote];
    tone(8, melody[thisNote], noteDuration);
    int pauseBetweenNotes = noteDuration * 1.30;
    int color = melody[thisNote] % 5;
    if(color == 0) {
      analogWrite(RED, 200);
    } else if(color == 1) {
      analogWrite(GREEN, 200);
    } else {
      analogWrite(BLUE, 200);
    }
    delay(pauseBetweenNotes);
    noTone(8);
  }
  analogWrite(RED, 0);
  analogWrite(GREEN, 0);
  analogWrite(BLUE, 0);
}

void loop() {
  // no need to repeat the melody.
}

Unfortunately, pin 3 did not blink.
But it worked when I changed pin 3 to pin 9.
To check whether pin 3 or Blue LED is broken,
I checked with the following code.
#define BLUE 3

void setup() {
  analogWrite(BLUE, 0);
}

void loop() {
  for(int i = 0 ; i < 255 ; i ++) {
    analogWrite(BLUE, i);
    delay(10);
  }
  analogWrite(BLUE, 0);
}

This code worked. Blue LED blinked.
Why couldn't pin 3 blink with toneMelody?
Thanks.

In the tone function reference you can read:

Use of the tone() function will interfere with PWM output on pins 3 and 11 (on boards other than the Mega).

analogWrite() is PWM

source: Stack Exchange

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

sort: votes


text:
RC522 RFID reader doesn't read NTAG216 chip
I have an RFID-RC522 module based on the MFRC522 chip. This chip is described in the datasheet as supporting "ISO/IEC 14443 A/MIFARE and NTAG" protocols. I have wired it up to an Arduino Uno using the recommended wiring in the documentation for the MFRC522 library I'm using. I have a sketch that (among other things) polls for presence of a new card:
void setup() {
    lcd.setup ();       // initialise LCD display
    SPI.begin();        // Init SPI bus
    mfrc522.PCD_Init(); // Init MFRC522 card
}

void loop() {
    // Look for new cards
    if ( ! mfrc522.PICC_IsNewCardPresent()) {
        return;
    }
    lcd.println ("Found new card");
    ...
}

This sketch correctly detects the presence of the card that was supplied with the module (I believe this is a Mifare Classic card) but does not detect my NTAG216 implant. Does anyone have any idea why it might be failing to find the implanted chip?

please provide more of your code, from what you've provided all I can see is that your LCD will constantly print "Found new card" over and over again... plus, you've got a return in the main loop???

@Madivad that code would be enough to print "Found new card" when any compatible card is brought close to the reader - perhaps the card itself is faulty?

Hi @JaromandaX the problem is that the print statement is outside the if conditional but within the main runtime loop which will just continually print Found new card. Found new card. Found new card. ad infinitum

@Madivad you'd be correct if the conditional return was absent, however, it is not absent, and therefore you are incorrect

@JaromandaX I get your point, and I stand corrected. The return is executed if there is no new card and execution stopped, but for as long as a card is present, the println will just keep repeating. Which the OP is not getting to. I get that now. I hadn't considered a return in the main loop before, nor did I understand the implications of it. Until I just did some experiments :)

My apologies for reviving such an old post, but was this ever solved. I am having the exact issue. Any assistance will be appreciated.

I got my RFID kit (RF522) just this week, but I haven't had a chance to play with it yet - nor do I have an NTAG216 implant. But I remember when I was researching them seeing a couple of posts that had to do with "Authentication errors". The problem for you (maybe) is that they were in Python rather than C:
https://github.com/mxgxw/MFRC522-python/issues/24
and Cotix's link
https://github.com/mj3052/MFRC522-Pi
Give them a lookover and see what they can tell you.
The problem with the PICC_IsNewCardPresent() function is that it gives a Yes/No answer, not a "Yes, but there's an error". In that case it would also return false. But the other code may give you a clue - you'll have to delve into the library...

Hmm.  AIUI I should be able to read the UID of the chip without authenticating (otherwise how would you know which passcode to use to authenticate with in a system with multiple cards?), but as you suggest I'll have a look through the library and see if there's a way of finding out about errors while detecting cards. It's a shame that this seems to be the only available arduino library for this chip and AFAICT almost entirely lacks documentation :(

Having investigated this further, this doesn't sound like the right answer.  Authentication requires the chip to be in 'active' state before you can begin the authentication process, and the PICC_IsNewCardPresent method is supposed to find cards that are in the 'idle' state and put one of them into 'active', so must be able to handle locating the card without authenticating first.

authors: Алексей Канев

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

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


text:
ESP8266 + NodeMCU Motor Shield spinning motor only in one direction
I hooked my ESP8266 Wi-Fi module to an ESP-12E Motor Shield and connected it to an RC car. It works fine when connected to my laptop (Goes forward, backward, left, and right. Though the car doesn't seem to turn a lot because of low power). I connected it to a 7.4v power supply, and it works fine, except it only moves forward and only turns right. Doesn't turn the motors the other direction.
I followed this tutorial. In case, you'd want the code.
I did have a change of code though, this is the only code I changed
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

// These are the pins used to control the motor shield

#define STEER_MOTOR_POWER D2 // Motor A
#define STEER_MOTOR_DIRECTION D3

#define DRIVE_MOTOR_POWER D1 // Motor B
#define DRIVE_MOTOR_DIRECTION D4

int drivePower = 1000;

uint8_t driveDirection = LOW;

int steeringPower = 1000;

uint8_t steerDirection = LOW;

// ----------------
// Set your WiFi SSID and Password here
// ----------------
const char* ssid = "xxxxx";
const char* password = "xxxxxxxxxxx";

ESP8266WebServer server(80);

void setup(void){

  pinMode(DRIVE_MOTOR_POWER, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
  pinMode(DRIVE_MOTOR_DIRECTION, OUTPUT);
  pinMode(STEER_MOTOR_POWER, OUTPUT);
  pinMode(STEER_MOTOR_DIRECTION, OUTPUT);

  WiFi.mode(WIFI_STA);
  WiFi.disconnect();
  delay(100);

  Serial.begin(115200);
  WiFi.begin(ssid, password);
  Serial.println("");

  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.macAddress());

  if (MDNS.begin("WifiCar")) {
      Serial.println("MDNS Responder Started");
      analogWrite(DRIVE_MOTOR_POWER, 10);
      digitalWrite(DRIVE_MOTOR_DIRECTION, driveDirection);
      delay(2000);
      analogWrite(DRIVE_MOTOR_POWER, 0);
  }

    server.on("/car/controls/front", [](){
      Serial.println("front");
      analogWrite(DRIVE_MOTOR_POWER, drivePower);
      digitalWrite(DRIVE_MOTOR_DIRECTION, driveDirection);
      delay(100);
      server.send(200, "text/plain", "front");
    });

    server.on("/car/controls/back", [](){
      Serial.println("back");
      analogWrite(DRIVE_MOTOR_POWER, drivePower);
      digitalWrite(DRIVE_MOTOR_DIRECTION, !driveDirection);
      delay(100);
      server.send(200, "text/plain", "back");
    });

    server.on("/car/controls/stopDirection", [](){
      delay(100);
      Serial.println("stopDirection");
      analogWrite(DRIVE_MOTOR_POWER, 0);
      delay(100);
      server.send(200, "text/plain", "stopDirection");
    });

    server.on("/car/controls/right", [](){
      Serial.println("right");
      analogWrite(STEER_MOTOR_POWER, steeringPower);
      digitalWrite(STEER_MOTOR_DIRECTION, steerDirection);
      delay(100);
      server.send(200, "text/plain", "right");
    });

    server.on("/car/controls/left", [](){
      Serial.println("left");
      analogWrite(STEER_MOTOR_POWER, steeringPower);
      digitalWrite(STEER_MOTOR_DIRECTION, !steerDirection);
      delay(100);
      server.send(200, "text/plain", "left");
    });

    server.on("/car/controls/stopSteering", [](){
      delay(100);
      Serial.println("stopSteering");
      analogWrite(STEER_MOTOR_POWER, 0);
      delay(100);
      server.send(200, "text/plain", "stopSteering");
    });

  server.begin();
  Serial.println("HTTP Server Started");
}

void loop(void){
  server.handleClient();
}

Done! Thank you!

maybe you did not make the correct connections

The connections are good. It works okay when connected to my laptop (though its very slow and it barely moves but you know there's a reaction).
my batteries are connected exactly as the tutorial mentioned (VIN and GND) while the VIN and VM shortcut both connected together.

reduce your code to minimum ... write a sketch that moves one motor in only one direction  stops, moves motor in other direction, stops and repeats

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


text:
It is required to turn on the LED if the distance to the object is less than or equal to 200 centimeters. Find the error in the code
int trigPin = 10;

const int echoPin = 8;

int led = 7;

const int distance = 200;

void setup()
{
    pinMode(trigPin, OUTPUT);
    pinMode(echoPin, INPUT);
    pinMode(led, OUTPUT);
}
void loop()
{
    int duration, cm;
    digitalWrite(trigPin, LOW);
    delayMicroseconds(2);
    digitalWrite(trigPin, HIGH);
    delayMicroseconds(10);
    digitalWrite(trigPin, LOW);

    duration = pulseIn(echoPin, HIGH);
    cm = duration/58;
    if (cm < distance)
    {
        digitalWrite(led, HIGH);
    }
    else
    {
        digitalWrite(led, LOW);
    }
    delay(100);
}

What exactly is your problem with the code? Or is that a  school excercise?

I can't find the error in the code myself.

How do you know, that there is an error. Give us a description of your problem

Tested via https://www.tinkercad.com. Does not work correctly, did not complete the task.

In the image trigger is connected to pin 9, your code says pin 10. Does it solve your problem if you use the correct pin?

please describe the problem ... what does it do? ... Does not work correctly is a useless description of a problem

Does not work correctly - OK you've said what it doesn't do. What does it do? Does the LED light up or not?

You have trigPin as pin 10, however your wiring diagram shows it connected to pin 9, so that won't work.

pulseIn returns an unsigned long (microseconds) - see pulseIn. You are collecting the results in an int which has a maximum value of 32767. The value may be overflowing and thus not be correct.


text:
display.begin(); function breaks working code
I've been setting up a system using an Arduino Uno board that reads from both an Adafruit MPU6050 6-way gyroscope and accelerometer and an Adafruit NAU7802 connected to a load sensor. I have code for that working, but I would also like to connect an Adafruit FeatherWing OLED to display the results.
Since this is the first time I've used Arduino or any of these parts, I first wrote a sketch to output the readings from my sensors into the serial monitor and a separate sketch to experiment with the display. However, when I try to use the code from the display sketch with my sensor reading script, it completely breaks the working sensor script.
My void setup code for my sensors looks like:
#include <Adafruit_MPU6050.h>
#include <Adafruit_NAU7802.h>

Adafruit_MPU6050 mpu;
Adafruit_NAU7802 nau;

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

  Serial.println("\n\nstart test\n");
  delay(10);

  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    } else {
      Serial.println("MPU6050 Found!");
    }
  if (!nau.begin()) {
    Serial.println("Failed to find NAU7802");
    } else {
      Serial.println("NAU7802 Found!");
    }

I then tried to add a few lines to power up the display:
#include <Wire.h> //for I2C
#include <Adafruit_MPU6050.h> //for 6-way
#include <Adafruit_NAU7802.h> //for ADC
#include <Adafruit_GFX.h> //for display
#include <Adafruit_SH110X.h> //for display

Adafruit_MPU6050 mpu;
Adafruit_NAU7802 nau;
Adafruit_SH1107 display = Adafruit_SH1107(64, 128, &Wire);

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

  Serial.println("\n\nstart test\n");

  if (!mpu.begin()) {
    Serial.println("Failed to find MPU6050 chip");
    } else {
      Serial.println("MPU6050 Found!");
    }
  if (!nau.begin()) {
    Serial.println("Failed to find NAU7802");
    } else {
      Serial.println("NAU7802 Found!");
    }

  delay(200); //allows OLED to power up
  display.begin(0x3C, true); // Address 0x3C default
  display.display();
  delay(1000);

  display.clearDisplay();
  display.display();

}

Does not turn on the display, but instead causes all of the code in the setup before the display.begin() function is called to loop indefinitely (even though it's not even in the loop part of the sketch.)
I have no idea what is going on here, and any advice would be appreciated! Thank you!
EDIT: Thank you so much for all of the comments! I will try to answer the questions as best as I can here.
I was only powering the device through the USB port. Based on your suggestions, I tried the script again using 9V through the barrel jack to power the device, but it, unfortunately, didn't fix the issue.
I tried reversing the dimensions in the Adafruit_SH1107(64, 128, &Wire) function, but that also didn't change anything. Also, all of my libraries are up to date as far as I can tell.
Both the OLED and the sensors successfully run independently while both are attached to the circuit. So -- I can get the OLED to display something while the sensors are attached to the circuit, and I can get the sensors to read into the serial monitor while the display is attached to the circuit. The problem arises when I try to have all of the parts called in the same script.
Here's a picture of the circuit:
Thank you all again for your help!

setup() loops when the arduino is repeatedly resetting ... maybe the arduino has inadequate power

Please show us your circuit and explain how you are powering everything

Not sure this is related. but according to the Adafruit_SH110x library, the api for create an instance is Adafruit_SH1107(WIDTH, HEIGHT, &Wire), you seems to had it revered with width = 64, and height = 128 in Adafruit_SH1107(64, 128, &Wire).

If the OLED was working independently then resetting the Arduino due to incorrect initialization (dimensions) is unlikely. The same can be said for using an outdated version of the Adafruit GFX library. Never the less, the Adafruit SH1107 driver does come w/this warning: "This library depends on Adafruit_GFX being present on your system. Please make sure you have installed the latest version before using this library.".  Please double check these settings/configurations and update your Question if necessary.

Also, can you please clarify that you can run the sensors while the OLED hardware is installed but the OLED software is not in the Sketch?  All these devices (OLED, Accelerometer & Stress Sensor) exist on your I2C bus.  And several have independent pull up resistors. In a good hardware design there should only be 1 set up pull up resistors at the far end of the I2C bus.  Having multiple higher resistance pull up resistors will likely work but there is an upper limit.


text:
arduino connection to mysql fails
I tried to connect xampp/mysql to arduino but connection fails.
mysql is running on port 3306.
I searched a lot on the internet but could not understand where is the problem!
Would you please help me...
#include <Ethernet.h>
#include <MySQL_Connection.h>

byte mac_addr[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };

IPAddress server_addr(127,0,0,1);  // IP of the MySQL *server* here
char user[] = "root";              // MySQL user login username
char password[] = "";        // MySQL user login password

EthernetClient client;
MySQL_Connection conn((Client *)&client);

void setup() {
  Serial.begin(9600);
  while (!Serial); // wait for serial port to connect
  Ethernet.begin(mac_addr);
  Serial.println("Connecting...");
  if (conn.connect(server_addr, 3306, user, password)) {
    delay(1000);
     Serial.println("Connection stablished.");
    // You would add your code here to run a query once on startup.
  }
  else
    Serial.println("Connection failed.");
  conn.close();
}

void loop() {
}

you forgot to put in the server IP ... 127.0.0.1 is not a network IP

I also try my pc IP but didn't work . Did you mean that?

i meant only what i said, that the IP you provided is invalid .... you said nothing about the MySQL server, so no comment can be made about the server

Sorry I didn't understand it. So which IP should I set to work?

you need to use the IP of the MySQL server ... you also have to make sure that the server can be reached .... use another computer to verify that .... the setup and verification of the MySQL server is not related to the Arduino, so don't ask about it here

how can I understand what is my MYSQL IP ? Is it different from my pc IP?


text:
eps32 bad adc even with external adc (ADS1115)
Im trying to read an analog value with my esp32 and send it over wifi to another esp32. The wifi part works flawless, however when i try to read an analog value form the esp32 its not useable. It jumps around +-100 on range 0-2000. Now i tried to use an external adc, because i heard that some have problems using the internal one with wifi. However i connected it via pins 21 and 22 (SDA Scl) and i have the same problem.
Internet couldnt help me at all, i hope you guys can.
Br
Felix

Are you running the external ADC from the ESP32's power?

What kind of analog value are you trying to read?

The esp has two internal adcs, of which one does not work with wifi. But the other one is supposed to work and I haven't had any problems so far. Please say something more about your setup. Breadboards can cause problems when wifi is active.

Ok so muiltiple things caused a bad analogread. Im trying to read a voltage level from 0-3,3v. Only pin 33 Worked and there i had a bit better readings. However still unusable. After i connected the esp32 to an external power supply the value was much better and more usable. Then i implemented some code wich is calcualating an average from 500values. This helped a lot and now im on +-1 on range 0-1000. I still dont know why the external adc didnt work well. I also ran it from external power. Same problem. Best Rg Felix


text:
How many output pins do NodeMCU have?
I am trying to build a Smarthome system with NodeMCU.
NodeMCU would wire up with relays.
How many replays can one NodeMCU control?

It depends how many shift registers or IO expanders you are willing to use.

Juraj I know, but I don't know the get those GPIOs things.
Can you give me a short answer?


text:
Problem with PWM pins on Arduino uno
I am working on an Arduino Uno Project of a car with two motors. The motor driver board is an L9110 H-Bridge. Here is how everything is connected:

And here is the code I am trying to run:

//Define all the pins for the motors
#define motorPinA1 3  //A pin right motor
#define motorPinB1 5  //B pin right motor
#define motorPinA2 6 //A pin left motor
#define motorPinB2 9 //B pin left motor

//Movement functions
void stopCar();
void frwrd(int motorSpdRight, int motorSpdLeft);
void back(int motorSpdRight, int motorSpdLeft);

//Global Variables
int motorSpeedRight = 0;  //The speed of the right motor
int motorSpeedLeft = 0;   //The speed of the left motor

void setup() {
  //Movement
  pinMode(motorPinA1, OUTPUT);
  pinMode(motorPinB1, OUTPUT);
  pinMode(motorPinA2, OUTPUT);
  pinMode(motorPinB2, OUTPUT);

  //Serial Monitor for debugging
  Serial.begin(9600);

  motorSpeedLeft = 100;
  motorSpeedRight = 100;

  frwrd(100, 100);
  delay(2000);
  stopCar();
  delay(1000);

  back(100, 100);
  delay(2000);
  stopCar();
  delay(1000);
}

void loop() {

  Serial.print("Forward");
  Serial.print("\n");

  frwrd(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

  back(motorSpeedRight, motorSpeedLeft);
  delay(2000);
  stopCar();
  delay(1000);

}

// functions we need to make the code run
void stopCar(){
    Serial.print("Stoping Car\n");
    // Put motor 1 in halt
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, 0);

    // Put motor 2 in halt
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, 0);
}

// For the farward direction A pins will be high
void frwrd(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in forward motion with speed = motor_spd
    analogWrite(motorPinA1, motorSpdRight);
    analogWrite(motorPinB1, 0);

    // Put motor 2 (Left) in forward motion with speed = motor_spd
    analogWrite(motorPinA2, motorSpdLeft);
    analogWrite(motorPinB2, 0);

    /*
    // Put motor 1 (Right) in forward motion
    digitalWrite(motorPinA1, HIGH);
    digitalWrite(motorPinB1, LOW);

    // Put motor 2 (Left) in forward motion
    digitalWrite(motorPinA2, HIGH);
    analogWrite(motorPinB2, LOW);
    */
}

// For the backward direction B pins will be high
void back(int motorSpdRight, int motorSpdLeft){
    // Put motor 1 (Right) in backward motion with speed = motor_spd
    analogWrite(motorPinA1, 0);
    analogWrite(motorPinB1, motorSpdRight);

    // Put motor 2 (Left) in backward motion with speed = motor_spd
    analogWrite(motorPinA2, 0);
    analogWrite(motorPinB2, motorSpdLeft);

    /*
    // Put motor 1 (Right) in backward motion
    digitalWrite(motorPinA1, LOW);
    digitalWrite(motorPinB1, HIGH);

    // Put motor 2 (Left) in backward motion
    digitalWrite(motorPinA2, LOW);
    digitalWrite(motorPinB2, HIGH);
    */
}

Pins 3, 5, 6 and 9 are PWM so I can alalogWrite() to them and control the speed of the motors. Code uploads fine but although both motors move forward normally motor 1 (on pins 3, 5) doesn't move backward. The strange thing is that if I use digitalWrite (the commented code in the two functions) instead everything works normally but the motors move in full speed so it's not usable for my project. I have tested all the pins in other projects and everything worked fine so I know my board is not faulty.
I have also taken some measurements with a multimeter while the code was running. In the forward motion, both pairs of pins measured 1.95V. In the backward motion, the problematic pins measured 0V.
Any help would be appreciated!!

start debugging by testing the motor driver ... swap wires on the arduino output pins .... not related to the question, but the pin naming in your sketch is somewhat confusing motorPinA1 is not as clear as motor1fwd or motorLeftFwd

The l9110 has 4 input pins named IA1, IB1, IA2, IB2 so that's why I named them that way. As for the swaps, I have tried a lot of combinations but I did not get consistent results so I was a bit confused

@Juraj This is not exactly my problem. I don't have reverse movement at all on one motor.

Try different pins than 5 and 6, because those PWM generators share the timer with delay(), which I'd interpret as: You use analogWrite() to set the timer to fire every n microseconds to toggle your PWM signal  -- and then you call delay(1000), which sets that same timer to fire in one second to continue the program.
Pins 10 and 11 do use a different timer, so try these.
Reference: https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/

"The PWM outputs generated on pins 5 and 6 will have
  higher-than-expected duty cycles. This is because of interactions with
  the millis() and delay() functions, which share the same internal
  timer used to generate those PWM outputs."

I will try that and I will get back on you.

delay() doesn't interfere with PWM the way you imagine. Actually, using delay() does not interfere with PWM at all. The fact that the timer is shared does have some consequences on the timer settings. On pins 5 and 6, the PWM frequency is higher (976.6 Hz instead of 490.2), and the duty cycle slightly larger: (n+1)/256 instead of n/255, where n is the value you analogWrite().

Your solution seems to have solved the problem for now so I will accept your answer. Although when I try to run the same code as part of a more complicated project I get the previous results. I will try to debug and if I don't get results I will open another question. Thanks for your time


text:
Using NRF24L01 as transmitter and receiver (transceiver)
I am using the NRF24L01 module to communicate between multiple Arduinos. For this example I will have a master transmiter (tx) Arduino and a salve receiver (rx) Arduino to illustrative better my problem.
Master (Tx) code:
#include <nRF24L01.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9, 10); // NRF24L01 used SPI pins + Pin 9 and 10

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

    radio.begin();
    radio.openWritingPipe(27);
    radio.stopListening();
}

void loop() {
    char buf[32];
    buf[0] = 123;

    auto res = radio.write(buf, sizeof(buf));
    if (res) {
        Serial.println("worked");
    }
    else {
        Serial.println("** error **");
        delay(1000);
    }

    delay(700); // wait 700 ms

}

Slave (Rx) Code
#include <nRF24L01.h>
#include <RF24.h>
#include <SPI.h>

RF24 radio(9, 10); // NRF24L01 used SPI pins + Pin 9 and 10

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

    radio.begin();
    radio.openReadingPipe(1, 27);
    radio.startListening();
}

void codeThatMakesMasterAckStopWorking()
{
    // Code that will be changed
}

void loop() {

    if (radio.available()) {
       char buf[32];
       radio.read(buf, 32);
       Serial.println("received data");
       codeThatMakesMasterAckStopWorking();

    }

}

If I execute this code it works great just as it is. The master (tx) always gets an acknowledgment every time it sends data. Also the range of the NRF24L01 works great. The problem occurs when the slave sends data becoming a transmitter instead of a receiver. In other words if I replace the method codeThatMakesMasterAckStopWorking with:
void codeThatMakesMasterAckStopWorking()
{
    radio.stopListening();
    radio.openWritingPipe(1234); // send to some other node that is not master
    char buf[32];
    radio.write(buf, 32);
    radio.startListening();
}

The master (Tx) is able to send the data because the slave prints the message "received data" but without acknowledgment. The master keeps printing ** error ** even though the slave is receiving the data. I been doing a lot of tests and this are my findings:
// does not work (master stops receiving acknowledgment and prints '** error **')
void codeThatMakesMasterAckStopWorking()
{
    radio.stopListening();
    delay(200);
    radio.startListening();
}

// works (master receives acknowledgment and prints 'worked')
void codeThatMakesMasterAckStopWorking()
{
    radio.stopListening();
    delay(10);
    radio.startListening();
}

There are times when I want my slave arduino to stop listening and transmit a message to another arduino. When it sends a message to a different arduino the master does not receive an acknowledgment anymore even though the slave is listening again. Why could this be?

google arduino rf24mesh

Does increasing the delay from 700 to, say, 2000 have any effect? PS what does sleep do. I don't think that's part the standard Arduino functions.

Sorry I meant to write delay @garben

Try using the nRFLite library.


text:
Send only one packet from one ESP32 to another ESP32 without acknowledgment
I have a network consisting 10 slaves and one master. I am using ESP-NOW to send the messages between the nodes. All of the nodes are within close proximity. I do NOT need a mesh network to reach all the nodes.
ESP-NOW works amazing. It is simple to use and the library is easy to understand. But in this project esp-now is not working for me and here is why:

If the 10 slaves want to send data at the same time it does not work. With 10 nodes they can send data every 200ms. If I lower the time some nodes even crash and restart.

Because all nodes cannot send data at the same time I am having the master ping each node to synchronize who can send a message. The moment a slave receives a message it can reply back.

If one slave node sends data to the wrong peer for some reason the web server of the master node stops working. It freezes until that node is done sending data.

If I send a broadcast message all the nodes reply. How can I configure esp-now so that no acknowledgment is sent back?

With esp-now when you send a packet the destination node always replies with a confirmation. I want to send that confirmation once the job that the slave had to perform worked. Because I am planing to work with a lot of nodes with close proximity I want to reduce network traffic. Moreover, on esp-now if a packet is not delivered it attempts again increasing the network traffic. I only want to resend packets that are important in order to reduce network traffic.

esp-now limits the number of nodes you can have specially if you encrypt the messages.

So my question is: is there a way to instruct esp-now to NOT send an acknowledgment? Can I instruct esp-now to only send one packet regardless if it failed or not? On the NRF24L01 you can set this value with the method setRetries. I just want something like UDP where it is a fire and forget. I cannot use UDP because I do not want to be connected to a WiFi network.
It will be great if I could have 2 methods. One for sending a simple raw packet and another for reading those packets on another esp32. I know I will be having to do a lot of filtering on the receiving side.

Edit

Here is a solution that works but needs improvement
It is possible to send raw packets with the function esp_wifi_80211_tx. But still esp32 sends 5 packets when using that function! Moreover, in order to use that function you must send a wifi beacon with whatever data you want. The minimum size of a beacon packet I believe is 128 bytes. So this is a solution but not a good one.
Anyways I bellow is the code for the transmitter esp32 and the receiver esp32. The transmitter code has to be compiled with the ESP-IDF framework and NOT arduino. If I use arduino framework it compiles fine (replace main function with setup) but it does not work once I upload it to the esp32. The receiver code I compiled it using the arduino IDE.
transmitter code (tx)
#include <stdio.h>

#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"

#include "esp_event_loop.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_wifi.h"

#include "nvs_flash.h"
#include "string.h"

// pin used to flash led
#define PIN GPIO_NUM_2

/*
 * This is the (currently unofficial) 802.11 raw frame TX API,
 * defined in esp32-wifi-lib's libnet80211.a/ieee80211_output.o
 *
 * This declaration is all you need for using esp_wifi_80211_tx in your own application.
 */
esp_err_t esp_wifi_80211_tx(wifi_interface_t ifx, const void *buffer, int len, bool en_sys_seq);

esp_err_t event_handler(void *ctx, system_event_t *event)
{
    return ESP_OK;
}

void send_raw_packet_task(void *pvParameter)
{

    for (;;)
    {
        uint8_t dataToSend[] = { 0 } ;

        esp_wifi_80211_tx(WIFI_IF_AP, dataToSend, sizeof(dataToSend) , false);

        // turn on and off led AND wait 10 seconds
        gpio_pad_select_gpio(PIN);
        gpio_set_direction(PIN, GPIO_MODE_OUTPUT);
        gpio_set_level(PIN, 1);
        vTaskDelay(9500 / portTICK_PERIOD_MS);
        gpio_set_level(PIN, 0);
        vTaskDelay(500 / portTICK_PERIOD_MS);
    }
}

extern "C" void app_main(void)
{
    nvs_flash_init();
    tcpip_adapter_init();

    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();

    ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));

    // Init dummy AP to specify a channel and get WiFi hardware into
    // a mode where we can send the actual fake beacon frames.
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_AP));
    wifi_config_t ap_config;

    // SSID = TTTT (4 times the letter t in uppercase)
    wifi_ap_config_t x;
    x.ssid[0] = 84; x.ssid[1] = 84; x.ssid[2] = 84; x.ssid[3] = 84;
    x.ssid[4] = 0;
    x.ssid_len = 4;

    //x.password = "dummypassword"; // for some reason this does not compile
    x.password[0] = 84; x.password[1] = 84; x.password[2] = 84; x.password[3] = 84; x.password[4] = 84; x.password[5] = 84; x.password[6] = 84; x.password[7] = 84;
    x.password[8] = 0;

    x.channel = 1;
    x.authmode = WIFI_AUTH_OPEN;
    x.ssid_hidden = 0;
    x.max_connection = 4;
    x.beacon_interval = 60000;
    ap_config.ap = x;

    //ESP_ERROR_CHECK(esp_wifi_set_config(WIFI_IF_AP, &ap_config));
    auto res = esp_wifi_set_config(WIFI_IF_AP, &ap_config);
    if (res == ESP_OK)
    {
        printf("set esp_wifi_set_config. It worked!\n");
    }
    else
    {
        printf("It did NOT worked :/\n");
        return;
    }

    // ESP_ERROR_CHECK(esp_wifi_start());
    res = esp_wifi_start();
    if (res == ESP_OK)
    {
        printf("wifi started! It worked!\n");
    }
    else
    {
        printf("It did NOT worked :/\n");
        return;
    }

    // ESP_ERROR_CHECK(esp_wifi_set_ps(WIFI_PS_NONE));
    wifi_ps_type_t t = WIFI_PS_NONE;
    res = esp_wifi_set_ps(t);
    if (res == ESP_OK)
    {
        printf("wifi set to WIFI_PS_NONE! It worked!\n");
    }
    else
    {
        printf("It did NOT worked :/\n");
        return;
    }

    res = esp_wifi_set_channel(1, WIFI_SECOND_CHAN_NONE);
    if (res == ESP_OK)
    {
        printf("wifi set channel to 1! It worked!\n");
    }
    else
    {
        printf("It did NOT worked :/\n");
        return;
    }

    // output size of bytes that we will be sending
    printf("*** Size of configuration is %i bytes. Starting task send_raw_packet_task...", (int)sizeof(ap_config));
    xTaskCreate(&send_raw_packet_task, "send_raw_packet_task", 2048, NULL, 5, NULL);
}

receiver code (rx)
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "esp_wifi_types.h"
#include "esp_system.h"
#include "esp_event.h"
#include "esp_event_loop.h"
#include "nvs_flash.h"

uint8_t channel = 1;

static void wifi_sniffer_packet_handler(void* buff, wifi_promiscuous_pkt_type_t type);
void wifi_sniffer_packet_handler(void* buff, wifi_promiscuous_pkt_type_t type) {

    // in here esp32 will capture all wifi traffic

    auto t = (unsigned char*)buff;

    // create flag to see if packet contains "TTT"
    bool containsX = false;

    // index where the first T is located on the buffer in case it is found
    int indexWhereNameOfSsidWasFound = 0;

    // look to see if its a packet of interest
    for (int i = 45; i < 100; i++)
    {
        if (t[i] == 84 && t[i + 1] == 84 && t[i + 2] == 84)
        {
            containsX = true;

            indexWhereNameOfSsidWasFound = i;
            Serial.println(i);

            break;
        }
    }

    if (containsX == false)
        return;

    // print SSID if found
    for (int i = indexWhereNameOfSsidWasFound; i < indexWhereNameOfSsidWasFound + 20; i++)
    {
        Serial.print((int)t[i]);
        Serial.print(" ");
    }
    Serial.println();

}

esp_err_t event_handler(void* ctx, system_event_t* event)
{
    return ESP_OK;
}

// the setup function runs once when you press reset or power the board
void setup() {

    Serial.begin(115200);

    // delay 2 seconds so that esp32 initializes
    Serial.println("Starting...");
    vTaskDelay(2000 / portTICK_PERIOD_MS);

    // init wifi sniffer
    {
        // order of initializations matter!

        wifi_country_t wifi_country = { .cc = "IT", .schan = 1, .nchan = 13 }; // Most recent esp32 library struct

        nvs_flash_init();
        tcpip_adapter_init();

        ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));

        wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
        ESP_ERROR_CHECK(esp_wifi_init(&cfg));
        ESP_ERROR_CHECK(esp_wifi_set_country(&wifi_country)); /* set country for channel range [1, 13] */
        ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
        ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_NULL));
        ESP_ERROR_CHECK(esp_wifi_start());

        // turn on promiscuous to capture everything
        esp_wifi_set_promiscuous(true);
        esp_wifi_set_promiscuous_rx_cb(&wifi_sniffer_packet_handler);

        // listen on channel 1
        esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE);
    }
}

void loop() {
    // empty
}

So basically the receiver code is listening for all network trafic in promiscuous mode. Kind of like wireshark. If it sees a packet that contains the string "TTTT" it will output it.
Because there is so much wifi traffic this is way slower than esp-now. I could not figure out how to send smaller packets. Lastly when sending a packet it takes about 2 second to capture the packet. I belive esp32 stores all those packets on a queue and then latter calls the call back function.
I guess I will go back on using esp-now. Can I modify the source code of esp-now? I just want want to remove the part where it send the packet multiple times and also the part where it replies with an acknowledgment.

I don't know ESP-NOW but for one way messages in TCP/IP network UDP protocol is used. That is WiFIUdp with the WiFi library

Can I send UDP messages without being connected to a network? I guess I will have to create a network between the nodes correct?

yes it would require a standard WiFi network. one of the esp32 can create it as SoftAP

I surmise that the esp32 'raw' tx isn't really that, based on the restrictions on what can be sent (data, but not QoS data, for example.)
I think that among the 5 packets you report seeing are 1.RTS, 2. CTS, 3. DATA, 4. ACK. These (at least 1,2) are necessary to avoid collision.
ESPNow sends a vendor-specific packet which doesn't (I surmise) require or follow the CTS/RTS or ACK 802.11 conventions.
Point to Point ESPNow, however, is written to expect a packet acknowledgement from the receiver, and will resend for a certain number of times until it receives one.
Broadcast ESPNow does not expect, and in fact cannot automatically receive, one of these ESPNow-specific acknowledgements.
If you need the fastest, least reliable 802.11 packet transmission, I would advise to use Broadcast ESPNow.
Having said that, you must be aware that you will not get the full collision-avoidance protections of more usual 802.11 protocol usage. You may need to provide your own ... such as listen-before-send, random exponential backoff, and who knows what else.
Seems to me that you are embarking on a wilderness adventure :)


text:
ESP32 send data to another ESP32 without establishing a wifi connection
Originally I was creating a project consisting of the Atmega328P and NRF24L01 to create multiple arduinos that could talk to each other.  Basically I was creating something like this:

As the network grows I am starting to run out of memory when using the atmega328P. I have to be careful about allocating memory and more. So I will like to replace the NRF24L01 with the ESP32.  The price of the ESP-WROOM-32 by itself is also cheaper than buying an NRF24L01 + the atmega328.

Question
How can I send data from one ESP32 to another ESP32 without establishing a WiFi connection? Just like the NRF24L01 where you specify a writting pipe where you want to send the data and the other NRF24L01 is listening on that pipe.

I know I can do that with ESP-NOW. This video explains how. The problem with ESP NOW is that I have to know in advance the mac address of the ESP32 where I intend to send a message. I plan to be able to keep adding smart home devices without having to know the mac address.
My algorithm with NRF24 that I already created is as follows:

There is a master node listening on address 2
If I add a new  node A to the network it listens on address 1.
Master discovers all devices that have address 1 every few seconds.
So eventually node A receives a discovery packet message that comes from master. Node A listens now on a random address and replies to master with that random anddress.
So node A is now connected to the network.

The cool thing about this algorithm is that I can keep adding new nodes to the network without knowing in advance its address. I will like to do the same thing with the ESP32. How can I send a simple message betweenn 2 ESP32 modules?

You should check out mesh mode...

if they have constant power, you could connect to wifi on boot, fetch a "phone book" from a server, then disconnect wifi and start esp-now. If they only talk one-way like my light switches(buttons), you don't need to ever change config to add more units.

Finally I found a way how to do it. If you use the mac address FF:FF:FF:FF:FF:FF that works as a broadcast address. This is the working code on how to send a message from the master to another esp32 without knowing its mac address. Later the slave can reply with its real mac address:
Code for master (tx)
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

uint8_t broadcastAddress[] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

void OnDataSent(const uint8_t *mac_addr, esp_now_send_status_t status) {
  Serial.println(status == ESP_NOW_SEND_SUCCESS ? "Delivery Success 1" : "Delivery Fail 1");
  if (status ==0){
    Serial.println("Delivery Success 2");
  }
  else{
    Serial.println("Delivery fail 2");
  }

  Serial.println();
}

void setup()
{

  Serial.begin(115200);

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Once ESPNow is successfully Init, we will register for Send CB to
  // get the status of Trasnmitted packet
  esp_now_register_send_cb(OnDataSent);

   // Register peer
  esp_now_peer_info_t peerInfo;
  memcpy(peerInfo.peer_addr, broadcastAddress, 6);
  peerInfo.channel = 0;
  peerInfo.encrypt = false;

   // Add peer
  if (esp_now_add_peer(&peerInfo) != ESP_OK){
    Serial.println("Failed to add peer");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }
}

int dataToSend = 1;
void loop()
{
    dataToSend++;

    // Send message via ESP-NOW (size of an int is 4 bytes on ESP32)
    esp_err_t result = esp_now_send(broadcastAddress, (uint8_t *) &dataToSend, 4);

    if (result == ESP_OK) {
      Serial.println("Sent with success");
    }
    else {
      Serial.println("Error sending the data");
    }

    //Serial.println(WiFi.macAddress());
    delay(1000);
}

Code for slave (Rx)
#include <Arduino.h>
#include <esp_now.h>
#include "WiFi.h"

// Callback when data is received
void OnDataRecv(const uint8_t * mac, const uint8_t *incomingData, int len)
{
  int dataReceived;
  memcpy(&dataReceived, incomingData, sizeof(dataReceived));

  Serial.print("Data Received: ");
  Serial.println(dataReceived);

  Serial.println();
}

void setup()
{

  Serial.begin(115200);
  delay(100);

  Serial.println("Starting...\n");

  // Set device as a Wi-Fi Station
  WiFi.mode(WIFI_STA);

  // print our mac address
  Serial.println(WiFi.macAddress());

  // Init ESP-NOW
  if (esp_now_init() != ESP_OK) {
    Serial.println("Error initializing ESP-NOW");
    for(;;) {      delay(1);  } // do not initialize wait forever
  }

  Serial.println("initialized ESP-NOW");

  // Register for a callback function that will be called when data is received
  esp_now_register_recv_cb(OnDataRecv);

}

void loop()
{
}

You can also reply back on the receiver code if you want. It will be the same code.

google OSI model data link layer for additional info about the osi model layer 2 ... there are multiple communication protocols available ... i do not know which are implemented by the esp32 module

You don't even need to set the macAddress to FF:FF:FF:FF:FF:FF, the esp_now_send() function allows you to pass in a NULL as the macAddress for broadcasting esp_now_send(NULL, *data, len). See documentation.

For peers, you also don't need to use the physical macAddress, you can simply assign a local-administrated peer address to each peers. The advantages of doing so is not only save the trouble from finding each peer's macAddress,  when you swap out a peer and replace another one in future, you don't even need to change the peer list of macAddresses in your master code.


text:
Retrieve value from ThingSpeak using ESP8266 with Arduino setup
I just started learning ESP8266 and in my first project I am successfully able to send data to ThingSpeak.com using ESP8266 with following code:
uploadData() {
  String apiKey = "ESDS8678890SDDS";
  String myData = "45.5"; // example of data to send
  if (espClient.connect(server,80)) {
    String postStr = apiKey;
    postStr +="&field1=";
    postStr += String(myData);
    postStr += "\r\n\r\n";
    espClient.print("POST /update HTTP/1.1\n");
    espClient.print("Host: api.thingspeak.com\n");
    espClient.print("Connection: close\n");
    espClient.print("X-THINGSPEAKAPIKEY: "+apiKey+"\n");
    espClient.print("Content-Type: application/x-www-form-urlencoded\n");
    espClient.print("Content-Length: ");
    espClient.print(postStr.length());
    espClient.print("\n\n");
    espClient.print(postStr);
    Serial.print(postStr);
    Serial.print("My Data: ");
    Serial.print(myData);
    Serial.print("\n");
  }
  espClient.stop();
}

But I have no idea how to retrieve data from ThingSpeak using ESP8266.
// Using XXXXX here as my channel is private
GET https://api.thingspeak.com/channels/XXXXXX/fields/1.json?results=2

I think I have to use the above GET string to get the fields data. But I don't know how to create the request string.
Help would be appreciated.
Thanks.

Connect to the server as usual with espClient.connect(). The following request should return a JSON object containing your channel description and the first 2 entries in your feed:
espClient.println("GET /channels/CHANNEL_ID/feeds.json?results=2 HTTP/1.1");
espClient.println("Host: api.thingspeak.com");
espClient.println("Connection: close");
espClient.println();

If it's a private channel, then you must supply your Read API key like this:
espClient.println("GET /channels/CHANNEL_ID/feeds.json?api_key=<your API key>&results=2 HTTP/1.1");

Notice that I use println() and not print() in order to implicitly terminate each request line properly. You should end each line not with \n but with \r\n. You only need to type this yourself if you use print().
To read the returned JSON data:
while (espClient.available() == 0);  // wait till something comes in; you may want to add a timeout here

unsigned long lastRead = millis();  // keeps track of last time a byte was read
while (millis() - lastRead < 2000) {  // while 2 secs havent passed since a byte was read
  while (espClient.available()) {
    Serial.print(espClient.read());
    lastRead = millis();   // update last time something was read
  }
}
client.stop();  // close socket

To parse the JSON string, you either get a library from GitHub or you parse the string yourself.

authors: Обычный Юзер


text:
Sim800L's library can not compile on Arduino Due
Sim800L's library can not compile on Arduino Due. Is there any way to create a library for Arduino Due?
#include <Sim800l.h>
#include <SoftwareSerial.h>

Sim800l Sim800l;
char* text;
char* number;
bool error;

void setup(){
    Sim800l.begin();
    text = "Testing Sms";
    number = "2926451386";
    error = Sim800l.sendSms(number,text);
    // OR
    //Sim800l.sendSms("+540111111111","the text go here")
}

void loop(){
    //do nothing
}

I guess that the problem is the software serial library, too. However, I don't know how to replace this library for Arduino Due.
Any help appreciated.

Without the error it is not possible to tell you what is happening.  It like walking to a mechanic and saying your car doesn't work.  Without the car or a description of the problem he isn't going to have a scoobies.
SO  Whats the exact error message you see.

You should probably rework thinks to use one of the Due's other hardware UARTs.  If you find a generic demo for using the port (or look at the Due docs) that should be simple, and if you get the Sim800l library in question in editable form and take time to understand it you should be able to make the changes.  But you are going to need to do the work yourself, or else spend some time doing your own web searches to see if someone already has.

Error massage: Error compiling for board Arduino Due (Programming port)

First we must delete the SoftwareSerial and SIM800L libraries, then define Sim800l and assign it to Serial 3 on pins 14 and 15. In setup, call Sim800l.begin() and the rest of the code is unchanged.
#define SIM800l Serial3

void setup () {
  Serial.begin (9600);
  SIM800l.begin (9600);
  while(!Serial);
  SIM800l.write ("AT+CMGF=1\r\n");
  delay (1000);
  SIM800l.write("AT+CMGS=\"5432154552"\"\r\n");
  delay(1000);
  Serial.println("send SMS");
  SIM800l.write ("test send SMS");
  delay (1000);
  SIM800l.write ((char)26);
  delay(1000);
}

void loop (){}


text:
Sleep mode Arduino Due through IR receiver control
I need to put my Arduino Due into sleep mode in order to consume less power. My Arduino Due receives IR data and does some work with it, but I need to make it sleep until there is no data. If data appears it should wake up and do something with data and go back to sleep mode.
Is there any way to do this? I would be grateful for any help.

you can't watch for data if the thing is off. you need another low-power thing to monitor the ir sensor and wake up the MCU if needed; i don't think the mcu itself can do that.

Connect the IR receiver to one of the interrupt pins, and set it so the mcu wakes up in the event of an interrupt.


text:
Problem uploading to Arduino Uno
The problem occurred while testing a ping program with the ethercard examples from github.
Now no program will upload. It will say uploading.... and gets stuck there. The error message below appears:
Arduino: 1.6.7 (Windows 7), Board: "Arduino/Genuino Uno"

WARNING: Category '' in library UIPEthernet is not valid. Setting to 'Uncategorized'

Sketch uses 1,030 bytes (3%) of program storage space. Maximum is 32,256 bytes.
Global variables use 9 bytes (0%) of dynamic memory, leaving 2,039 bytes for local variables. Maximum is 2,048 bytes.
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 1 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 2 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 3 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 4 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 5 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 6 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 7 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 8 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 9 of 10: not in sync: resp=0xdf
avrdude: stk500_recv(): programmer is not responding
avrdude: stk500_getsync() attempt 10 of 10: not in sync: resp=0xdf
Problem uploading to board.  See http://www.arduino.cc/en/Guide/Troubleshooting#upload for suggestions.

  This report would have more information with
  "Show verbose output during compilation"
  enabled in File > Preferences.

ensure that it is connected to the correct port (worked with me)

Other thing to try, if you are using a different board try plugging in a genuine Uno or true clone, setting the board and port, uploading a sketch, then start over with your board. That has helped me. Seems that some boards don't reset the usb properly after a problem. ...or maybe it's just voodoo.

Disconnect everything to Arduino, Plug in your Arduino to your computer - check for the Serial port, Check for your Arduino Model, select programmer as USBasp, open up BLink sketch from Examples and HIT upload.
if you don't see your Arduino in Tools>Port then it should be the problem of USB cable, Computer USB port or "DRIVERS"

No, do not select USBasp unless that is what you are using - the asker clearly isn't.

When you get this error, they have several things to check :

Is my board reconised by Windows ?
Is my board model is the right one ?
Is the serial port is the right one ?
Is my cable damaged ?

Generally the upload problem is easy to fix.
If your board is a custom one

bootload problem
crystal problem.
reset not triggered properly ? (try to push it when arduino ide say "uploading sketch")

I'm having the same issue on my Macbook Pro. It happens randomly. The only solution i found is disconnecting the USB cable from the PC wait for a few mins and reconnect it again (possibly using another USB port).
It worked for me!

Remove the ethercard, return to the basic board.
Disconnect the Arduino from the host.
Reboot the host computer.
Reconnect the Arduino.
Upload the Blink example.

This should sort things out, well it did when it happened to me.

When I started reading that list I thought it was going to end up like this: http://www.snopes.com/humor/business/wordperfect.asp ;)

If you have the Arduino Uno with removable chip then try to remove the IC. Then plug it again and check the power on the IC with a multimeter on pin 7 (+ positive) and pin 8 (- negative). If you are getting 5V there then you need to try to upload a simple blink sketch. If you are not getting the appropriate voltage then you can try to use a different wire to upload the sketch.

This is unlikely to help.  There are better places to measure power, such as the 5v pin on the shield connector.


text:
What is the name of this chip on Arduino Mega ? I am not finding its datasheet 56 TI MSP?

What is the using purpose of this chip?

I think that says M5P not MSP - in which case it's IC5 - the LM358D op-amp used to control the USB power FET.

There is only one 8-pin SMD IC on the top side of the Arduino Mega 2560.

From the schematic
it appears to be the "LMV358IDGKR" a TI dual op-amp used for two separate functions on the Mega.

Selecting power source - VIN vs USB.
Illuminating the built-in "L" LED (on D13) without loading PB7

I solved my problem with your help


text:
Using or creating Wi-Fi Direct (P2P) connection on ESP8266
I want to make a Wi-Fi Direct connection with an android device using my ESP8266. According to ESP8266WiFi Documentation and ESP8266 datasheet, the board has a SoftAP mode which is I think what is needed in a P2P connection (Being an AP and a client at the same time).
There is also ESP-NOW in the Espressif website but I think it's made only for esp-to-esp p2p connection and I can't modify it. (Correct me if I'm wrong)
I couldn't find any pre-made libraries for this job, so I decided to make my own, but I can't seem to find anything related to making a new type of protocol or connection. Is it even possible to develop a new type of protocol? If yes, I'd really appreciate a guide on how to get started.

why not use esp8266 arduino? https://github.com/esp8266/Arduino#installing-with-boards-manager

@Juraj I'm sorry, but I looked into the Documentation mentioned in that repository but I couldn't find anything related to Wi-Fi Direct or P2P. Also when I mentioned "ESP8266WiFi documentation" I meant the library that you just shared. Can you please clarify which part of the library or documentation explains it?

the WiFi library of the "esp8266 Arduino boards support package" handles SoftAP and WiFi STA. AP and STA can be used together. you can receive and send data on both interfaces. btw; I wonder why you call the "esp8266 Arduino  boards support package" "documentation". the docs are here https://arduino-esp8266.readthedocs.io/en/latest/index.html

Maybe explain a little more what you want to achieve and why you need the esp to be both AP and station. I think you confuse some things, a client is usually sth on a different layer (you have websocket/http/... clients).

@SimSon As I explained, I need to establish a P2P connection (More specifically, use Wi-Fi Direct). A Wi-Fi direct connection requires both devices to be an AP & client at the same time (So they don't need to have the same access point to connect to) as explained here

@Juraj Yes, it does handle SoftAP and I can use it, but it's not obvious (or even possible) to make P2P connections with just that. You need more than just being an access point and connecting to an access point; To be able to make a P2P connection. Since ESP supports 802.11, It has the hardware capabilities for it. But I'm stuck at finding the right code/library to do it. Also, the exact link that you mentioned as "The docs are here" is the link in my comment.

what should that library do? P2P or WiFi direct is a connection without separate WiFi AP. if one of the esp starts the SoftAP and the other connects to it as STA, it is P2P.

i read it
can you do it in the end?


text:
Problems with Arduino Uno Usb 2.0 shield when using a keyboard
I have an Arduino Uno and a usb 2.0 shield in which I connected a keyboard to. I have all the necessary libraries installed but what I am trying to figure out is how to light an led when I press a specific key.
I am new to codding Arduino boards and I have done a lot of reading but I cant figure out my issue I feel like if I get this figured out I will be a lot better off in my future projects.
#include <hidboot.h>
#include <usbhub.h>
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

int SKEY = 8;

class KbdRptParser : public KeyboardReportParser
{
    void PrintKey(uint8_t mod, uint8_t key);

  protected:

    void OnKeyDown  (uint8_t mod, uint8_t key);
    void OnKeyUp    (uint8_t mod, uint8_t key);
    void OnKeyPressed            (uint8_t key);
};

void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
{
  MODIFIERKEYS mod;
  *((uint8_t*)&mod) = m;
  Serial.print((mod.bmLeftCtrl   == 1) ? "C" : " ");
  Serial.print((mod.bmLeftShift  == 1) ? "S" : " ");
  Serial.print((mod.bmLeftAlt    == 1) ? "A" : " ");
  Serial.print((mod.bmLeftGUI    == 1) ? "G" : " ");

  Serial.print(" >");
  PrintHex<uint8_t>(key, 0x80);
  Serial.print("< ");

  Serial.print((mod.bmRightCtrl   == 1) ? "C" : " ");
  Serial.print((mod.bmRightShift  == 1) ? "S" : " ");
  Serial.print((mod.bmRightAlt    == 1) ? "A" : " ");
  Serial.println((mod.bmRightGUI  == 1) ? "G" : " ");
};

void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
{
  Serial.print("DN ");
  PrintKey(mod, key);
  uint8_t c = OemToAscii(mod, key);

}

void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
{
  Serial.print("UP ");
  PrintKey(mod, key);
}

void KbdRptParser::OnKeyPressed(uint8_t key)
{
  Serial.print("ASCII: ");
  Serial.println((char)key);
};

USB Usb;
HIDBoot<USB_HID_PROTOCOL_KEYBOARD>    HidKeyboard(&Usb);

KbdRptParser Prs;

void setup() {

 Serial.begin(9600);
#if !defined(__MIPSEL__)
  while (!Serial);
  Serial.println("Start");

  if (Usb.Init() == -1)
    Serial.println("OSC did not start.");

  delay( 1 );

  HidKeyboard.SetReportParser(0, &Prs);

}

void loop() {
 Usb.Task();
}

Anyways I know how to make if statements and how to activate pins on the Arduino but I cant figure it out in this keyboard library. For now I just made it print "TRUE" since there is not need to get complicated if I cant get the first step to work. Before I made that if statement the serial monitor would show the value assigned to the key and label it DN # and when I let up on the key it would say UP # but how can I translate that to sending a pulse to whatever pin when I push a key and stop sending a pulse when I let up on the key?
Also in my if statement that I made I know I need something before == sign but I tried multiple things and they did not work so I just left it blank and the reason I used the number 16 was because that was the value assigned to the S key in which I wanted to use to light an led. Anyways any help would be greatly appreciated!

Does anyone have any ideas?


text:
How to run atmega328p at 8, 4 and 1 mhz?
Instead of using the regular Arduino board I have purchased the atmega328p-pu along with this components:

22pf ceramic capacitor
10K resistor
16mhz crystal
47uF capacitor
3.3 Volts Power supply

The diagram looks like this:

Because the atmega328p chip that I purchased already comes loaded with arduino bootloader I can program this chip right away! This video explains in more detail how to upload the code to the chip. It is very simple.
The reason why I run my atmega328p chip with a 3.3V power supply is because of these reasons:

I have multiple sensors like the NRF24L01 that cannot take 5 volts.
I run this project of a 3.3 battery as well in order to save power.
I do not want to use voltage regulators as they are inefficient and they will waste my battery.
Everything works great.

Even though everything works great if I am running atmega328P at 16mhz @ 3.3V I am not following the specifications. In order to do things correct I will like to run my code at 8mhz so that I am in within the specs
Question
What is the correct way of running this project at 8mhz? If I change the 16mhz crystal for a 8mhz it runs at 8mhz but everything is half the speed. I have to divide all time related functions by 2. Moreover, I cannot upload new code if it has a 8mhz crystal. In order to upload new code I have to place the 16mhz crystal upload the code and then change the crystal again.
Can I still use my 16mhz crystal and run at 8mhz so that I do not have to keep replacing the crystal? I want my millis function and other time dependent functions to have the correct time. I do not want to have to divide everything by 2.
Do I have to burn a different bootloader for this to work? Where can I find a tutorial that can explain me all this?
There are tutorials on how to use the internal 8mhz crystal from the atmega328 chip but still want to use an external crystal as it is much more accurate
Edit
I just found  this link that explains how to do it. Edgar Bonet answer seems a lot simpler so I will stick to that.

If you run your MCU at 8 MHz, everything will run at this frequency: not
only the CPU core but also the timers, including Timer 0 which is used
for millis(), delay(), etc. So you will have to use a modified
version of the Arduino timing functions in order to cope with this clock
frequency.
Fortunately, such version already exists. Actually, it is even supported
by the standard Arduino core, since it supports the 3.3 V version
of the Arduino Pro Mini, which uses an ATmega328P clocked at 8 MHz.
I thus suggest you install an 8 MHz crystal, burn in the bootloader
for the 3.3 V Pro Mini, and tell your IDE that you are using that
board. In the Tools menu:

set board to "Arduino Pro or Pro Mini"
set processor to ""ATmega328P (3.3V, 8 MHz)"

How can I burn the bootloader for the 3.3V Pro mini? Is that a different bootloader than the one that it came with? The rest of the answer I understand perfectly fine. Thanks for the help Edgar.

@TonoNam: you will need an ISP programmer, or an Arduino running the ArduinoISP sketch. The Tools menu of the Arduino IDE has a “Burn Bootloader” item. You can search the internet for instructions on how to use it.


text:
Servo jitter with Arduino
We're complete beginners with Arduino and we're working on a project that moves a pointer based on a color sensor reading.
We used two servo motors each: one performs a specific task, the small servo works pretty fine. The problem is with the larger one.
We used this servo motor model: (towardpro MG996R), Arduino Uno and a color sensor. Because the motor is large we connect it to a 9 V power supply.
But when we run the code it just vibrates in place and the arm won't move :(
Is there anything else we need to add to the circuit like a resistor or some thing?
#include <Servo.h>
Servo largeServo;

void setup() {
  largeServo.attach(6);
  largeServo.write(0);
}

void loop() {
  largeServo.write(0);
  delay (2000);
  largeServo.write(30);
  delay (2000);
  largeServo.write(60);
  delay (2000);
  largeServo.write(90);
  delay (2000);
}

Does the small servo perform well with the very same code on the same pin? If so, chances are there is something wrong with the large servo, or with its power supply.

yes, the code is perfectly fine with the smaller one ,

but if the problem with the battery how would i know ?

"9V power supply" as in 9V PP3 battery...?

YES! exactly , directly connected to the servo and the Arduino GND

Well there you go then. Use a supply that can deliver enough current and you may find it magically starts working...

do you mean we must increase the voltage , because the motor sheet specify 4.4-6 v ?

Welcome to Arduino SE.  Be sure to take the tour to see how this works and to earn a badge:  https://arduino.stackexchange.com/Tour

No, not more voltage.  You need something capable of delivering more current.  A 9V battery is not suitable for driving motors.  They belong in smoke detectors and maybe a transistor radio.  Get 3 or 4 AA or AAA batteries and things will go much better.

Howmany current does the servo draw/need? Stay within the datasheets' voltages and make sure your supply can deliver the required current!

According to (MG996R)'s datasheet
You must connect a 6 volts - 2.5 amps power supply for it's best performance (max. Torque)
Maximum voltage of this servomotor is 6 volts
And be careful, exceeding that voltage can be cause of some damage to it's control board
Try 6 volts 2.5 amps power supply and if doesn't work maybe your servomotor's control-board is damaged by over-voltage.

As already suggested in the comments you need a more powerful current source than your battery.
No device work purely on Voltage, they all operate on Power (watts) or, if you prefer, on a combination of Voltage and Current (ampere).
You are feeding 9V into your beefy motor, but the amount of current your battery can provide is pretty limited due to the battery internal resistance and limited capacity.
Replace the battery with a proper power source capable to deliver 10W or more (1+ ampere at 9 volts equals 9+ watts) and your motor will start to operate and it will also get warm while operating.

Please mind that theoretically putting a higher voltage will give more power. But that soms component can not resist higher voltages. The way to go is to take a supply with a voltage within the voltage range of the device. And to make sure it can supply more current as neccesary. (Not the other way around)

When applied to motors the voltage reflects on speed and current on torque, but if the motor jitters it's because it doesn't get enough current to overcome the windings inductance. So, while it's true higher voltage means more power, that's not going to solve the issue in this case.

Hmm interesting 10v 1a or 20v 0,5a is the same "power". But the first example has more torque and the second one more speed? My conclusion is still true, don't overvolt and be able to supply enough current.

That's correct Paul: higher voltage means you can change the magnetic field in the coils more quickly while higher amperage means you can create stronger magnetic fields. You don't have to exceed in voltage because the the internal windings have a resistance: provide too much voltage and you burn the windings.

To complement the other answers, also make sure that the Arduino itself is being powered properly!
I was attaching Arduino Uno to a nearly out of battery laptop via USB cable, resulting in a jittering servo. As soon as I've put the laptop on charge, the servo started working smoothly!


text:
Fingerprint sensor code won't work correctly with LCD 16x2
I am doing a fingerprint sensor that works with a 16x2 LCD. The code works correctly for the fingerprint sensor, but when I enter LCD code, the LCD works but the fingerprint stops working.
I am using an Arduino Uno and an Adafruit fingerprint sensor. Both the fingerprint and LCD are wired correctly and work separately. I have enrolled and tested fingerprints and it worked perfectly until I added LCD code.
#include <Adafruit_Fingerprint.h>
#include <SoftwareSerial.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

int getFingerprintIDez();
// pin #2 is IN from sensor (GREEN wire)
// pin #3 is OUT from arduino  (WHITE wire)
SoftwareSerial mySerial(2, 3);

Adafruit_Fingerprint finger = Adafruit_Fingerprint(&mySerial);

void setup() {
 // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print a message to the LCD.
  lcd.print("hello, world!");
  Serial.begin(9600);
  Serial.println("fingertest");
  // set the data rate for the sensor serial port
  finger.begin(57600);
  if (finger.verifyPassword()) {
    Serial.println("Found fingerprint sensor!");
  } else {
    Serial.println("Did not find fingerprint sensor :(");
    while (1);
  }
  Serial.println("Waiting for valid finger...");
}

void loop() {
  getFingerprintIDez();
}

uint8_t getFingerprintID() {
  uint8_t p = finger.getImage();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image taken");
      break;
    case FINGERPRINT_NOFINGER:
      Serial.println("No finger detected");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_IMAGEFAIL:
      Serial.println("Imaging error");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK success!
  p = finger.image2Tz();
  switch (p) {
    case FINGERPRINT_OK:
      Serial.println("Image converted");
      break;
    case FINGERPRINT_IMAGEMESS:
      Serial.println("Image too messy");
      return p;
    case FINGERPRINT_PACKETRECIEVEERR:
      Serial.println("Communication error");
      return p;
    case FINGERPRINT_FEATUREFAIL:
      Serial.println("Could not find fingerprint features");
      return p;
    case FINGERPRINT_INVALIDIMAGE:
      Serial.println("Could not find fingerprint features");
      return p;
    default:
      Serial.println("Unknown error");
      return p;
  }

  // OK converted!
  p = finger.fingerFastSearch();
  if (p == FINGERPRINT_OK) {
    Serial.println("Found a print match!");
  } else if (p == FINGERPRINT_PACKETRECIEVEERR) {
    Serial.println("Communication error");
    return p;
  } else if (p == FINGERPRINT_NOTFOUND) {
    Serial.println("Did not find a match");
    return p;
  } else {
   Serial.println("Unknown error");
    return p;
  }

  // found a match!
  Serial.print("Found ID #");
  Serial.print(finger.fingerID);
  Serial.print(" with confidence of ");
  Serial.println(finger.confidence);
}

// returns -1 if failed, otherwise returns ID #
int getFingerprintIDez() {
  uint8_t p = finger.getImage();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.image2Tz();
  if (p != FINGERPRINT_OK)  return -1;
  p = finger.fingerFastSearch();
  if (p != FINGERPRINT_OK)  return -1;
  // found a match!
  Serial.print("Found ID #");
  Serial.println(finger.fingerID);
  Serial.print("This Finger print related to : ");
  switch(finger.fingerID){
   case 0:
     Serial.println("Subhy Mesmar");
     break;
   case 1 :
     Serial.println("Amjad Mesmar");
     break;
  }
  return finger.fingerID;
}

In this image the fingerprint sensor works without LCD code:

And in this one the LCD works after adding code but the fingerprint sensor stopped working:

You have pins 2 and 3 used by both the LCD and the SoftwareSerial used for the fingerprint sensor.
Use different pins for one or the other.
Worth looking at the Software Serial reference to understand more about how it works.

is it safe to use different pins for fingerprint sensor ? , Wont changing pins 2,3 damage the sensor ?Please advise .

Yes it should be safe.


text:
Sending value from Arduino to MySQL using ESP8266
I am trying to send a value from Arduino to a remote MySQL. I am following this tutorial.
I have tried but no data is received on the server. What is the issue? I am new to Arduino. My code is:
int led1=8;
int count=1;
void setup() {
  pinMode(led1, OUTPUT);
  delay(3000);
  // initialize serial communication at 9600 bits per second:
  Serial.begin(115200);
  Serial.println("AT+CWMODE=1");
  delay(1000);
  Serial.println("AT+CWJAP=\"mhboys\",\"mhboys123\"");
  delay(1000);
}

// the loop routine runs over and over again forever:
void loop() {
  digitalWrite(led1,HIGH);
  // turn the LED on (HIGH is the voltage level)
  delay(1000);  // wait for a second
  if(digitalRead(led1)==LOW) {}
  if(digitalRead(led1)==HIGH) {
    count++;
    //code for sending updated count to mysql
  }
  digitalWrite(led1, LOW);
  // turn the LED off by making the voltage LOW
  delay(1000); // wait for a second
  int adjustedValue = count;
  // print out the value you read:
  Serial.println("AT+CIPSTART=\"TCP\",\"www.onemediagroup.in\",80");
  delay(1000);
  Serial.println("AT+CIPSEND=66");
  delay(1000);
  Serial.print("GET /energy/getUsage.php?currentValue=");
  Serial.print(adjustedValue);
  delay(1000);
  Serial.println("AT+CIPCLOSE");
  digitalWrite(13, HIGH);
  delay(100000); // delay in between reads for stability
}

You must post your code. We cannot tell what you are doing wrong unless you show your work.

I am not getting any data in my server.

The wifi module does not blink the blue light. Is it any issue?

You're sending commands blindly without checking if they actually succeeded. If you're not ready to correctly handle the responses, you're better off using a library like this. The 'HTTP GET' example should help.

authors: Андрей Бахтин


text:
How to convert byte *payload to String
I would like to convert a byte *payload to a String, because I want to compare the content of payload to another String.
void mqttCallbackHandler(char *topic, byte *payload, unsigned int length) {
  String payloadstr = ???
  ...
}

Depending on what is setting the message on the topic, payload may, or may not be, a NULL-terminated string.  This is why they provide the length parameter.
You could consider comparing the data with memcmp() which is like strcmp() but doesn't look for a NULL termination - instead it takes a length parameter.  This is good if you may have NULL bytes in your payload.
An alternative is strncmp() which both looks for a NULL termination and also limits the length using a length parameter. Better for payloads you know are strings, but you aren't sure if they have NULL termination or not.
Here is a callback (for PubSubClient on ESP8266) I have in one of my projects which uses strncmp():
void callback(char *topic, byte *payload, unsigned int length) {
    if (!strcmp(topic, SUBTOPIC)) {
        if (!strncmp((char *)payload, "on", length)) {
            digitalWrite(POWERPIN, HIGH);
            powerState = true;
            client.publish(PUBTOPIC, "on", true);
        } else if (!strncmp((char *)payload, "off", length)) {
            digitalWrite(POWERPIN, LOW);
            powerState = false;
            client.publish(PUBTOPIC, "off", true);
        }
    }
}

Simply casting your payload to (char *) is enough for the functions to take it as a string, and the length parameter will prevent looking past the end of the payload if there is no NULL termination.
It's not perfect - a single byte payload of o will falsely match the first on, but if that is a critical problem I am sure you can find a way to work around it by checking what length equals.

strncmp is good for internal comparison, what if I want to send the data to a rest API?

This is an old post but probably somebody can use this info:
void mqtt_callback(char* topic, byte* payload, unsigned int length) {
  String topicStr = topic;
  String recv_payload = String(( char *) payload);

  Serial.println( "mqtt_callback - message arrived - topic [" + topicStr +
                  "] payload [" + recv_payload + "]" );
}

Thanks for answering the actual question.  But how does the String constructor know where the end of the char array is ?

Consider simply using the returned pointer.
Payload is a pointer of type byte.  You can compare each byte in a string to the byte the pointer is pointing at. Then increment the pointer to the next byte and repeat the process. You don't need to allocate more memory for new string.
If a type string is necessary.  For example, if you were using a complex library method which requires a string to be passed to it, you could copy what the returned pointer is pointing at byte by byte into a locally defined string.

For comparing a byte array to a String object, you could convert the
byte array to another String object, but this involves dynamically
allocating memory for a whole copy of the string. This is memory
unfriendly, and preferably avoided on small microcontrollers.
The cheapest way to achieve what you want is to compare them as
character arrays :
if (strcmp((char *) payload, theReferenceString.c_str()) == 0) {
    // the strings are equal
}

strcmp() is a standard C function that does the byte by byte
comparison, exactly as suggested by st2000.

what if the payload string is not terminated with zero?

@Juraj: then memcmp().

Marco's answer worked for me, but worked better with:
payload[length] = 0;
String recv_payload = String(( char *) payload);

Therefore, the full code would be:
void mqtt_callback(char* topic, byte* payload, unsigned int length) {
  String topicStr = topic;
  payload[length] = 0;
  String recv_payload = String(( char *) payload);

  Serial.println( "mqtt_callback - message arrived - topic [" + topicStr +
                  "] payload [" + recv_payload + "]" );
}


text:
Master doesn't receive the correct values in a master/slave SPI link
I've been struggling for 3 weeks looking for a solution to my problem concerning SPI communication.
So, I need to establish a SPI communication between two Arduino devices: for instance, the master sends a letter 'a' to the slave; the slave receives it and does some processing. In my case, it should set one of his  8 pins to high then read all pins and send the report back to the master.
The part where the master sends 'a' and the slave processing it works fine but the master doesn't seem to receive the correct values. Instead it always receives 0.
Here's the code:

Slave:
#include <SPI.h>;

volatile byte command = 0;
byte ett =8; //nbr of test points
byte motif= 0b000000000 ; //intiatition of my varible which will contain my pin's states
byte end[8] = { 2,3,4,5,6,7,8,9}; //array containing the pins

void setup (void) {
  Serial.begin (9600);
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  // turn on interrupts
  SPCR |= _BV(SPIE);
}  // end of setup

// SPI interrupt routine
ISR (SPI_STC_vect) {
  byte c = SPDR;
  switch (command) {
    //////////////Slave traitement/////////////
    // no command? then this is the command
  case 0:
    command = c;
    SPDR = 0;
    break;

  case 'z': ////case 'z", set all pins to INPUT
    for (int i=0; i<8; i++){
      pinMode (end[i], INPUT);
    }
    break;

  case 'a': // //if 'a' : Set one pin to high then read all pin's satete to verify if there is any open circuit or short circuit
    for (int j = 0; j < ett; j++) {
      pinMode(end[j], INPUT);   // set all pins as INPUT
    }
    motif = 0;
    pinMode(end[0], OUTPUT);  // Set one pin as OUTPUT
    digitalWrite(end[0], HIGH); // Set the output pin to HIGH
    Serial.println();
    Serial.print(" ");
    for (int k = 0; k < ett ; k++) { // scan
      if (digitalRead(end[k]) == HIGH) {
        // if pin == HIGH add '1' to my vector
        Serial.print("| ");
        motif = motif + 1; // +1
      } else { // if pin == LOW
        Serial.print(". ");
      }
      motif = motif << 1; // shift left
    }
    Serial.print(" -MOTIF LU= ");
    Serial.print(motif, BIN);
    SPDR = byte (motif); //SPDR is the SPI Data Register: it contains the data that will be sent to the Master
    Serial.print(" ");
    break;
  }
}

void loop (void) {
  // if SPI not active, clear current command
  if (digitalRead (SS) == HIGH)
    command = 0;
}

Master:
#include <SPI.h>

byte CS0=10;
byte CS1=9;

void setup (void) {
  Serial.begin (9600);
  Serial.println ();
  digitalWrite(SS, HIGH);  // ensure SS stays high for now
  // Put SCK, MOSI, SS pins into output mode
  // also put SCK, MOSI into LOW state, and SS into HIGH state.
  // Then put SPI hardware into Master mode and turn SPI on
  SPI.begin ();
  // Slow down the master a bit
  SPI.setClockDivider(SPI_CLOCK_DIV8);
}  // end of setup

byte transferAndWait (const byte what) {
  byte a = SPI.transfer (what);
  delayMicroseconds (1000);
  return a;
} // end of transferAndWait
///traitement au niveau du maitre

void loop (void)  {
  byte esclave0_testpin0;
  /////////////Set the first slave's pin to High then read all pins
  digitalWrite (CS0,LOW); //activate the slave
  transferAndWait ('a'); // set first slave's pin to high
  esclave0_testpin0 = transferAndWait ('z'); //read all slave's pins and report it in the variable esclave0_testpin0
  digitalWrite (CS0,HIGH); //disactivate the slave
  Serial.println ("test_0");
  Serial.println (esclave0_testpin0, BIN);
  delay (1000);  // 1 second delay
}  // end of loop

Double check your SPI protocol. Is the order correct? A state machine might help understand the sequencing. Also avoid Serial print in ISRs.

Some tips: 1) use ctrl-t to autoformat, 2) use { and } consequently regarding new lines, 3) use more clear variable names (also for loop iterators), 4) Write also comments in code in English, 5) motif = motif + 1 , more c is motir++;

@MichelKeijzers : Thank you for the tips, but "motif =motif +1"works in my program; i'll add a screenshot of the simulation.The display on the slave monitor is correct. I made a short circuit between the first and the second pins and i i've got " -MOTIF LU= 11000000 ".

@MikaelPatel: wrote my code based on this link [gammon.com.au/forum/?id=10892&reply=2#reply2] (Part: How to get a response from a slave) . I tested its code and it worked very well. I did not change anything except the process at the slave level: instead of adding or subtracting I read the state of the slave's pins and report it to the master.

@Saha222 Yes it is the same, but it's more 'C'  style to write motif++ instead of motif = motif + 1 ... or motif += 1; ...I'm glad you sorted out the problem.

@MichelKeijzers, Ah, ok I understood .. but it did not work yet, the display at the master level always remains incorrect.

@Saha222 That's why I made it a comment an not an answer, it doesn't solve your problem (sorry). I hope someone else has the answer.

In slave, command is always 0. You problably meant:
void loop(void) {
    command = (digitalRead(SS) == HIGH ? 0 : 1);
}

and at ISR:
ISR (SPI_STC_vect) {

    byte input = SPDR;
    byte output = 0;

    if (command) {

        switch (input) {

            case 'a':
                //...
                break;

            case 'z':
                //...
                break;
        }
    }

     // send data back
     SPDR = output;
}

As a best practice, avoid to implement the logic within the ISR and use global volatile variables to pass state changes to the code in the main loop. Probably you will have to implement a circular buffer to receive from and send to the SPI bus...


text:
passing variable to function
I have the following code to turn on or off led. I would like to modify the function to pass the pin as well. what should X be substituted with?
#define BIN_LED 2
#define PIN_LED 3

void led(uint8_t x, bool on) {
 digitalWrite(x, on ? LOW : HIGH);
}

void setup() {}

void loop() {
 led(BIN_LED, true);
 delay(1000);
 led(BIN_LED, false);
 delay(1000);
}

think ..... what is X in digitalWrite(X, on)?

FWIW, consider why you're doing this as well. If you want a shorter function name, consider just aliasing the fn. If you want a more "meaningful" fn, I'm not sure this achieves that.

You've done it. All that's left is to specify a data-type 'X' in the function declaration, just as you've already done for 'on'. 'uint8_t' would be a reasonable choice.

it didn't work. I updated the question with your suggestion.

@motionchannel  It did not work because you have not configured the pin as an output. The answer is correct, the code compiles and correctly passes the pin number. Put pinMode (BIN_LED, OUTPUT); in your setup() function to make your code light an LED. You could look at some example code from the Arduino IDE to see how this works.


text:
Multiple definition class in arduino
Help me out here. I don't know what I'm missing.
I have this code in my arduino IDE
#include "Foo2.h"
void setup() {
  // put your setup code here, to run once:

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

And I have five files: Foo.h, Foo.cpp, Foo2.h, Foo3.cpp and Foo.h
Foo.h
#ifndef Foo_H
#define Foo_H

class Foo
{
    public:
    Foo();

    public:
    bool Fooa();
    bool Foob();
};
#endif

Foo.cpp
#include "Foo.h"

Foo::Foo()
{

}

bool Foo::Foob()
{
    return true;
}

Foo2.h
#ifndef Foo2_H
#define Foo2_H
#define LIBRARY_VERSION 1.0.0
#include "Foo.h"

bool Foo::Fooa()
{
    return true;
}
#endif

Foo3.h
#ifndef Foo3_H
#define Foo3_H
#include "Foo2.h"

class Foo3
{
    public:
        Foo3();
        Foo _foo;
};
#endif

Foo3.cpp
#include "Foo3.h"

Foo3::Foo3()
{
}

And it is give me an error:
libraries\Foo\Foo3.cpp.o (symbol from plugin): In function `Foo::Fooa()':
(.text+0x0): multiple definition of `Foo::Fooa()'
sketch\kk2.ino.cpp.o (symbol from plugin):(.text+0x0): first defined here
collect2.exe: error: ld returned 1 exit status
exit status 1

what i'm doing wrong
regards,

Please show us "Foo3.cpp" that is mentioned in the error.

If you want Fooa() to be defined in a header that can be included in more than one .cpp file, you would need to declare it as an inline function like so:
#ifndef Foo_H
#define Foo_H

class Foo
{
    public:
    Foo();

    public:
    inline bool Fooa();
    bool Foob();
};
#endif

Alternately, you can provide the function definition directly inside class definition; this also makes the function inline despite not requiring the inline keyword.
Or if you want to keep Fooa as a non-inline function, you'd need to move the definition out of the header and into a .cpp file as you did with Foob().
Making a function inline has a second effect beyond implying that you want a function's code to be generated at the call site; it informs the compiler (or more accurately the linker) to expect to see multiple definitions (that are required to be identical) of the code for the function.  Without that advanced noticed, you will get the multiple definition of error when a function definition is inserted into multiple .cpp file by way of an #include.
As a side note: #include is an automated form of copy-and-paste.  It logically plants the contents of another file (and all of its reachable #include uses transitively) into place where the #include directive appeared.  It does not behave the same way that many similar looking directives in other languages do.  E.g. #include does not behave like the import keyword does in say Java or python for example.

It didn't work adding the 'inline' keyword. I have edit part of my question, because I have other files too.

I'm trying to solve this [https://arduino.stackexchange.com/questions/79641/problemm-with-the-mpu6050-library]. And I think that I have to figure out this problem first.

No, you were right it works. I have to put the 'inline' keyword in the Foo.h and Foo2.cpp


text:
For Loop function to iterate through outputs after interrupt
I would like help to continuously loop over my output pins after each sleep cycle.  I am trying to increment through each output pin during each successive interrupt.  Introducing this myIteration function causes immediate incrementing to final output pin and eliminates sleeping.
EDIT
To clarify a bit and clean up the code, I am having trouble getting the loop to increment over the output pins each time the interrupt is triggered.  It stays on the initialized pin value after each interrupt.
The reason I separate the if (state=HIGH) into two consecutive statements is because when I do not the debug LED remains on.
#include <LowPower.h>

const byte interrupt_pin = 2;                             // declare interrupt pin for PIR trigger
int musicPins[] = {3, 4, 5, 6, 7, 8, 9, 10, 11};          // Initialize pins that play music in array, elements from 0 to 8
volatile byte state = LOW;                                // trigger threshold starts low
int pinCount = 9;
int previous = 0;

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);                           // use builtin LED for debug
  pinMode(interrupt_pin, INPUT);                          // set interrupt pin as input

    for (int thisPin = 0; thisPin < pinCount; thisPin++) {      // set all music pins as High to start with no music during sensor initialization
    digitalWrite(musicPins[thisPin], HIGH);
    }
    for (int thisPin = 0; thisPin < pinCount; thisPin++) {      // set all music pins as outputs
    pinMode(musicPins[thisPin], OUTPUT);
    }

  delay(5000);                                            // wait so sensor can initialize
}

void loop() {

  attachInterrupt(digitalPinToInterrupt(interrupt_pin),interrupt_routine,RISING); // must attach each loop
  LowPower.powerDown(SLEEP_FOREVER,ADC_OFF,BOD_OFF);      // MCU sleep until interrupt
  detachInterrupt(digitalPinToInterrupt(interrupt_pin));  // remove interrupt

  if (previous==10){                                      // when variable gets to 10 reset to zero
    previous=0;
  }

  if (state==HIGH){                                       // PIR senses motion, sends high signal
    digitalWrite(LED_BUILTIN,HIGH);                       // debug LED turns on
    myOnIteration();                                      // musicPin number x turns on
    delay(100);                                           // wait to stabilize
    digitalWrite(LED_BUILTIN,LOW);                        // debug LED turns off
  }
  if (state==HIGH){                                       // separate statements to guarantee next steps happen
    myOffIteration();                                     // musicPin number x turns off
    LowPower.powerDown(SLEEP_8S, ADC_OFF, BOD_OFF);       // sleep for 8s after musicPin plays

  }

  previous++;                                             // increment before attaching next interrupt

}

////////Functions//////////
void interrupt_routine(){
  state = HIGH;
}

void myOnIteration() {                                    // cycle through output pins turning on once per interrupt
for (int count = previous; count < pinCount; count++) {
        digitalWrite(musicPins[count], LOW);
      }
}

void myOffIteration() {                                   // cycle through output pins turning off once per interrupt
for (int count = previous; count < pinCount; count++) {
        digitalWrite(musicPins[count], HIGH);
      }
}

Your problem description is a bit unclear. What did you expect the code to do and what did it actually do instead? Also: myIteration() is never called. Also it wouldn't change the global thisPin variable, since it uses it's own local variable with that name.

Why do you have two directly consecutive tests for if (state==HIGH)? Wouldn't one do? Plus what chrisl said.

I use two consecutive test for if (state==HIGH) because when I do not the debug LED remains on during sleep.  Thanks for the pointer about global variable.  I've edited the original post.  My iteration functions are still not iterating, the code runs only the initialized value at pin 4.

Why are you counting from 4 to 9, when your musicPins array has only has 8 elements? And did you intent to skip the first 4 elements with that? With that pin 4 will never change. Count from 0 to 7 instead

Thanks, the array was indeed incorrect. I've fixed it to be the number of elements in the array and not the pin numbers. I also needed to be incrementing inside the main loop before attaching the interrupt.  The original post is edited with final working version.

Original code is updated with final version. A motion sensing interrupt iterates over multiple voice playback output pins and sleeps at low power for rest of time.

I don't understand this "answer". Stack Exchange is not a forum. Are you saying the problem is fixed? If so, in what way? If not, please edit your question to elaborate, don't use an answer to clarify the question.