text:
Sending arduino sensor data via WiFi to a MySQL server
I'm aware this question has probably been asked many times but I'm pulling my hair out.
I'm trying to get sensor data from an arduino to a MySQL server. I've checked the apache access log and the request is there. But it just isn't being inserted into the database. Manually adding the data using the browser works so the php code seems fine. I've allowed apache through the firewall and updated the permissions all to no avail. Code below:
Arduino Main Code:
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
#include <WiFi.h>

WiFiClient client;

void setup() {
  // Initialize serial and wait for port to open:
  Serial.begin(9600);
  // This delay gives the chance to wait for a Serial Monitor without blocking if none is found
  delay(1500);

  //Connect to WiFi network
  int status = WL_IDLE_STATUS;
  while (status != WL_CONNECTED){
    Serial.print("Attempting to connect to SSID: ");
    Serial.println(SSID);
    status = WiFi.begin(SSID, PASS);
    delay(10000);
  }
  Serial.println("This is connected.");

  if (!ENV.begin()) {
  Serial.println("Failed to initialize MKR ENV shield!");
  while(1);
  }
  pinMode(2, INPUT);
}

void loop() {
 relativeHumidity = int(ENV.readHumidity());
 lightIntensity = (ENV.readIlluminance());
 airPressure = int(ENV.readPressure(MILLIBAR));
 temperature = int(ENV.readTemperature());
 if(digitalRead(2) == LOW){
   rain = 1;
 }else if(digitalRead(2) == HIGH){
   rain = 0;
 }
 Serial.println("httpRequest");
 httpRequest();
 delay(10000);
}

void httpRequest(){
  // if there's a successful connection:
  if (client.connect(SERVER, 80)) {
    Serial.println("Connecting to server...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    Serial.println("GET /weather_data.php?);
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.print(" Host: ");
    client.println(SERVER);
    client.println();
    Serial.println("Added.");
  } else {
    Serial.println("Not connected.");
  }
  if (client.connected()){
    client.stop();
  }
}

thingProperties.h:
#include <WiFi.h>
#include <SPI.h>

const char THING_ID[] = "c942a18f-7696-4431-952c-76eaea3214ea";

const char SSID[]     = SECRET_SSID;    // Network SSID (name)
const char PASS[]     = SECRET_PASS;    // Network password (use for WPA, or use as key for WEP)
const char SERVER[]   = SECRET_IP;      // Server IP Address

int airPressure;
float lightIntensity;
float relativeHumidity;
bool rain;
float temperature;

So your Arduino is using a WiFi library to submit HTTP commands to a server running an Apache web server stack? And you are seeing the commands logged to the server? If so, you're going to have to debug the sever side of this. Is the command well formed when received? What is being done with it? You say "Manually adding the data using the browser works so the php code seems fine." That is too much of a leap. Using a web client to submit your request vs. doing it from a raw HTTP GET command exercises a different path on your server.

does the record get inserted when you use a web browser? ... if it does, copy the URL and include as a comment in your code

The following is an example of the requests directly from the access log: 192.168.0.3 - - [24/Jun/2020:21:26:58 +0100] "GET /weather_data.php?temp=32.00&pressure=1009&humidity=40.00&illumination=3.23&rain=0 HTTP/1.1" 400 311

the 400 is HTTP response code? see the WebClient example on how to print the HTTP response in Arduino

So I don't quite know why, but I started from scratch and it works now. I've put the new code below in case it helps someone in my situation.
// Arduino Low Power - Version: Latest
//#include <ArduinoLowPower.h>
//#include <ArduinoIoTCloud.h>
#include "thingProperties.h"
#include <Arduino_MKRENV.h>
/*
  Repeating Wifi Web Client

  This sketch connects to a a web server and makes a request
  using a WiFi equipped Arduino board.

  created 23 April 2012
  modified 31 May 2012
  by Tom Igoe
  modified 13 Jan 2014
  by Federico Vanzati

  http://www.arduino.cc/en/Tutorial/WifiWebClientRepeating
  This code is in the public domain.
*/

#include <SPI.h>
#include <WiFiNINA.h>

int status = WL_IDLE_STATUS;

// Initialize the Wifi client library
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for native USB port only
  }

  // check for the WiFi module:
  if (WiFi.status() == WL_NO_MODULE) {
    Serial.println("Communication with WiFi module failed!");
    // don't continue
    while (true);
  }

  String fv = WiFi.firmwareVersion();
  if (fv < WIFI_FIRMWARE_LATEST_VERSION) {
    Serial.println("Please upgrade the firmware");
  }

  // attempt to connect to Wifi network:
  while (status != WL_CONNECTED) {
    //Serial.print("Attempting to connect to SSID: ");
    //Serial.println(SSID);
    // Connect to WPA/WPA2 network. Change this line if using open or WEP network:
    status = WiFi.begin(SSID, PASS);

    // wait 10 seconds for connection:
    delay(10000);
  }
  // you're connected now, so print out the status:
  //printWifiStatus();
  //Start arduino cloud.
  //ArduinoCloud.begin(ArduinoIoTPreferredConnection);
  //Begin ENV shield.
  if (!ENV.begin()) {
    Serial.println("Failed to initialize MKR ENV shield!");
    while (1);
  }
}

void loop() {
  //ArduinoCloud.update();
  // if there's incoming data from the net connection.
  // send it out the serial port.  This is for debugging
  // purposes only:
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }
    //Serial.println("Start reading sensors.");
    relativeHumidity = int(ENV.readHumidity());
    //Serial.println(relativeHumidity);
    lightIntensity = int(ENV.readIlluminance());
    //Serial.println(lightIntensity);
    airPressure = int(ENV.readPressure(MILLIBAR));
    //Serial.println(airPressure);
    temperature = int(ENV.readTemperature());
    //Serial.println(temperature);
    UV_Index = int(ENV.readUVIndex());
    //Serial.println(UV_Index);
    if (digitalRead(2) == LOW) {
      rain = 1;
    } else if (digitalRead(2) == HIGH) {
      rain = 0;
    }
    //Serial.println(rain);
    //Serial.println("Sensor data read.");
    //Serial.println("Start http request.");
    httpRequest();
    //Serial.println("Stop http request");
    delay(60000);
}

// this method makes a HTTP connection to the server:
void httpRequest() {
  // close any connection before send a new request.
  // This will free the socket on the Nina module
  client.stop();

  // if there's a successful connection:
  if (client.connect(server, 80)) {
    //Serial.println("connecting...");
    // send the HTTP PUT request:
    client.print("GET /weather_data.php?temp=");
    client.print(temperature);
    client.print("&pressure=");
    client.print(airPressure);
    client.print("&humidity=");
    client.print(relativeHumidity);
    client.print("&illumination=");
    client.print(lightIntensity);
    client.print("&UV_Index=");
    client.print(UV_Index);
    client.print("&rain=");
    client.print(rain);
    client.print(" ");
    client.println("HTTP/1.1");
    client.println("Host: 192.168.0.29");
    client.println("User-Agent: ArduinoWiFi/1.1");
    client.println("Connection: close");
    client.println();
  } else {
    // if you couldn't make a connection:
    //Serial.println("connection failed");
  }
}

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

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

  // print the received signal strength:
  long rssi = WiFi.RSSI();
  Serial.print("signal strength (RSSI):");
  Serial.print(rssi);
  Serial.println(" dBm");
}

I see you don't use the WiFi library but the WiFiNINA library

WiFi.h is for Arduino WiFi shield. Use the WiFiNINA library for MKR1010

Made that change but still doesn't seem to be working

@SamAnderson, maybe it doesn't work yet, but with WiFiNINA it has at least a chance to work.


text:
HC-08 Bluetooth module not showing up on iPad
I have an HC-08 Bluetooth module Bluetooth module hooked up to an Arduino Uno but for some reason, it doesn’t show up in the Bluetooth menu in my iPad settings. Can you help?

Can you check, if you show up on other devices? Maybe you have access to an android device? That can show you, if the problem is with the iPad side or with the HC-08 side

Ok, I will try that.

Just tried that and it worked. Weird.

This article describes, that the HC-08 should work with iPhones. I think iPads are similar. Maybe on your iPad try to turn off and on bluetooth, restart the iPad or try to update it. Difficult to say, what the problem is here. And we are experts in Arduino, not in iPads.

source: Stack Exchange

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

sort: votes


text:
Can I force a function to live in the boot sector without overwriting the bootloader?
Not for any practical purpose but just out of curiosity, I want to abuse the flash memory and write it dynamically at run-time.  This is, in a sense, what the bootloader does.  If I understand it, the only way to modify flash is to do so from instructions written to the boot sector.  Is it possible to stick a simple function in there that writes to flash memory, and call it from running code?  If so, how do I put it there?  I have no issue with calling functions from function pointers, so I don't think I'll have an issue actually calling the function once I get there, but I need to know how to stick into flash in the first place.

The Optiboot version 8 has a do_spm function which can be called from application. The Optiboot repository contains an example for the use of this function.
SPM is the AVR CPU instruction to write to flash memory. The Optiboot wraps this in a function. A pointer to this function is put in a 'vector table' at the beginning of the bootloader. The first pointer jumps to main, the second pointer jumps to do_spm. The optiboot.h then has the function as (version for small Optiboot)
typedef void (*do_spm_t)(uint16_t address, uint8_t command, uint16_t data);
const do_spm_t do_spm = (do_spm_t)((FLASHEND-511+2)>>1)

I made an enhancement of this, a copy_flash_pages function with reset option to bootload an AVR from its own flash. It is added as third entry in the 'vectors table' of Optiboot. It is used in my ArduinoOTA library for AVR MCUs.
typedef void (*copy_flash_pages_t)(uint32_t dest, uint32_t src, uint16_t page_count, uint8_t reset);
const copy_flash_pages_t copy_flash_pages = (copy_flash_pages_t)((FLASHEND-1023+4)>>1);

That's very interesting, thanks.  I will check it out

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


text:
How to connect HC-06 with HC-08 with the HC-06 as master and HC-08 as slave?
How do you connect HC-06 with HC-08 with the HC-06 as master and HC-08 as slave? I will try it using 2 Arduino Unos.

Ok sorry. Thanks.

You cannot. The HC-06 is a slave only device.
So you need to use a device as master, that is actually capable of it. I don't know, if the HC-08 can do it. Another typical bluetooth master device is the HC-05. Just like HC-06, but can also be a master.

Ok thanks for the help.


text:
Workflow when using Emacs, Arduino-makefile and Serial monitor?
I'm trying to develop code, compile, upload and use the Serial monitor for debugging of a script for an Arduino Pro Mini. I'm using Emacs as my IDE. I'm having trouble determining the exact sequence of commands to do this most efficiently. What I'd like to do is:

Edit my code, compile and upload from Emacs (able to do this now)
Switch to a window running minicom (or putty, etc.) and observe the debug output.
rinse and repeat

My problem is that now, I have to stop and start minicom each iteration, after I upload the code. Sometimes, restarting minicom causes my Arduino to reboot, and that then displays the debugging output correctly. Sometimes, it takes two minicom restarts to accomplish this. Also, if I don't kill minicom before uploading, it just prints garbage to the screen, and seems to hang. I'm hoping for something like the Arduino IDE Serial monitor, that just runs continuously, and that correctly displays the debugging output.
Ideally, I'd like help coming up with the exact commands to run a Serial monitor that wouldn't require stopping and starting it. Is this possible?
Thanks for all your suggestions and advice.
-Kevin

that is the advantage of the Serial Monitor in IDE. IDE disconnects it before upload and connects it back after upload.

There's no way to disconnect and reconnect minicom remotely. All you can do is kill the process, and then manually restart it.


text:
usb host shield + wireless mouse (Read 5 times)
hello guys i have a problem ,
i have a usb host shield v2.0 from circuits @home  attached to an arduino mega and to a usb wireless reciever mouse ,
this is the serial monitor  output :
x=0 dy=3
dx=0 dy=-1
dx=0 dy=-1
dx=0 dy=-1
dx=0 dy=-1
dx=0 dy=-1
dx=0 dy=1
dx=0 dy=-2
dx=0 dy=-2
dx=0 dy=2
dx=0 dy=9
dx=0 dy=6
dx=0 dy=-1
dx=0 dy=2
dx=0 dy=-1
dx=0 dy=-1
dx=1 dy=0
dx=2 dy=0
dx=1 dy=0
dx=2 dy=0

and this is the code from the library usbhidbootmouse :
#include <hidboot.h>
#include <usbhub.h>

// Satisfy the IDE, which needs to see the include statment in the ino too.
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>

class MouseRptParser : public MouseReportParser
{
protected:
    void OnMouseMove    (MOUSEINFO *mi);
    void OnLeftButtonUp (MOUSEINFO *mi);
    void OnLeftButtonDown   (MOUSEINFO *mi);
    void OnRightButtonUp    (MOUSEINFO *mi);
    void OnRightButtonDown  (MOUSEINFO *mi);
    void OnMiddleButtonUp   (MOUSEINFO *mi);
    void OnMiddleButtonDown (MOUSEINFO *mi);
};
void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
{
    Serial.print("dx=");
    Serial.print(mi->dX, DEC);
    Serial.print(" dy=");
    Serial.println(mi->dY, DEC);
};
void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi)
{
    Serial.println("L Butt Up");
};
void MouseRptParser::OnLeftButtonDown   (MOUSEINFO *mi)
{
    Serial.println("L Butt Dn");
};
void MouseRptParser::OnRightButtonUp    (MOUSEINFO *mi)
{
    Serial.println("R Butt Up");
};
void MouseRptParser::OnRightButtonDown  (MOUSEINFO *mi)
{
    Serial.println("R Butt Dn");
};
void MouseRptParser::OnMiddleButtonUp   (MOUSEINFO *mi)
{
    Serial.println("M Butt Up");
};
void MouseRptParser::OnMiddleButtonDown (MOUSEINFO *mi)
{
    Serial.println("M Butt Dn");
};

USB     Usb;
USBHub     Hub(&Usb);
HIDBoot<USB_HID_PROTOCOL_MOUSE>    HidMouse(&Usb);

MouseRptParser                               Prs;

void setup()
{
    Serial.begin( 115200 );
#if !defined(__MIPSEL__)
    while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
    Serial.println("Start");

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

    delay( 200 );

    HidMouse.SetReportParser(0, &Prs);
}

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

i wanna know the dx is equal to 1 when i press the left button on mouse and is equal to 2 when i press the right button on mouse and the dy is responsible for the x and y coordinates from - to + ? how a single value is responsible for x and y both ?

what is preventing you from reading the value of dx when you press the left mouse button? ... your question is somewhat unclear ... what single value are you talking about?

the dy value is responsible for both x and y co-ordinates together ... it should be responsible for only 1 movement so now how to extract the 2 coordinates? ithink there is a correction with the library i dunno


text:
Adafruit v2.3 Motor Shield Initialization Failure
I would appreciate any help solving this as I have spent several hours trying to debug. My code seems to stop when I get to the initialization of the motor shield.

motorShield.begin();

#include <Wire.h>
#include <Adafruit_MotorShield.h>
#include "utility/Adafruit_MS_PWMServoDriver.h"
#include <LiquidCrystal.h>

//CREATE LCD OBJECTm
LiquidCrystal lcd = LiquidCrystal(2, 3, 4, 5, 6, 7);

//CREATE MOTOR SHIELD OBJECT
Adafruit_MotorShield motorShield = Adafruit_MotorShield();

//SET MOTOR VALUES
Adafruit_DCMotor *frontRight = motorShield.getMotor(1);
/*Adafruit_DCMotor *rearRight = motorShield.getMotor(2);
Adafruit_DCMotor *frontLeft = motorShield.getMotor(3);
Adafruit_DCMotor *rearLeft = motorShield.getMotor(4);*/

//DEFINE SENSORS
#define centerTrigPin A2
#define centerEchoPin A3

//DEFINE SENSOR VALUES
long centerDuration; // Variable for the duration of sound wave travel
int centerDistance; // Variable for the distance measurement

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

  lcd.begin(16, 2); //Set LCD dimensions

  //motorShield.begin();

  //frontRight->setSpeed(50);
  /*rearRight->setSpeed(50);
  frontLeft->setSpeed(50);
  rearLeft->setSpeed(50);*/

  //frontRight->run(RELEASE);
  /*rearRight->run(RELEASE);
  frontLeft->run(RELEASE);
  rearLeft->run(RELEASE);*/

  pinMode(centerEchoPin, INPUT);
  pinMode(centerTrigPin, OUTPUT);
}
void loop() {
  //GET CENTER SENSOR
  digitalWrite(centerTrigPin, LOW);
  delayMicroseconds(2);
  digitalWrite(centerTrigPin, HIGH);
  delayMicroseconds(10);
  centerDuration = pulseIn(centerEchoPin, HIGH);
  centerDistance = centerDuration * 0.034 / 2;

  if (centerDistance <= 10){
    //SERIAL OUTPUT
    Serial.print("OBJECT: ");
    Serial.print(centerDistance);
    Serial.println(" cm");

    //LCD OUTPUT
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("OBJECT");
  }else{
    //SERIAL OUTPUT
    Serial.print("DRIVE: ");
    Serial.print(centerDistance);
    Serial.println(" cm");

    //LCD OUTPUT
    lcd.clear();
    lcd.setCursor(0, 0);
    lcd.print("DRIVE");
  }//End Forward/Reverse Check
}//End loop

reduce your code to the minimum ... no LCD, no serial ... use an LED blink to indicate that the code is not frozen ... then add back serial so that you can send debug messages


text:
Motor noise on my Arduino RC?
I want to make an RC car based on two Arduino Nanos, two nRF24L01s (Rx and Tx), and a Pololu brushed motor driver, and it works, more or less.
Sometimes it works very well and everything goes nicely and suddenly it will "freeze" and stop receiving and when it does, the servo always goes to 0° (I think it must be the Rx because it prints the same value until the next restart in the serial monitor).
It seems the servo trebles in the same direction (to 0°) only when I send high PWM values until it stops reading new data and "freezes".
I have 2 batteries, one for the Nano with a step-up converter, and another for the servo and the brushed motor;  they share a common ground. Everything is close to each other and connected by wires soldered to a prototype breadboard. It is really messy but makes a good contact.
So it seems it is a noise problem, doesn't it? But what else could it be? How can I suppress that noise? I have already watched the Pololu guide about noise but I didn't try the bypass capacitors since I don't know how to solder them properly (can they burn the servo?)
Here is the code for the Tx
#include <SPI.h>
#include "RF24.h"

const int ledBot = 8;
const int padx = A0;
const int pady = A1;
const int sw = 3;
int sws;
int x;
int y;
int botState;
int aBotState;
int ledState;
const float un = 0.25;
const float fy = 0.176;
int sens [4]; // 0: throttle, 1: foward/backwards, 2: steering, 3: lights

RF24 radio(9, 10); // CE, CSN
const byte address[6] = "00001";
void setup() {
  //Serial.begin(9600);
  pinMode(padx, INPUT);
  pinMode(pady, INPUT);
  pinMode(sw, INPUT);
  pinMode(ledBot, INPUT_PULLUP);
  radio.begin();
  radio.setDataRate (RF24_2MBPS);
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}

void loop() {
  x = analogRead(padx);
  y = analogRead(pady);
  sws = digitalRead(sw);
  botState = digitalRead(ledBot);
  y = 1024-y;

  switch (sws){ //foward and backwards

  case 0:
    sens [0] = un*x;
    sens [1] = 0;
    sens [2] = min(135, max(50, y*fy-2));
    break;

  case 1:
    sens [0] = un*x;
    sens [1] = 1;
    sens [2] = min(135, max(50, y*fy-2));
    break;
  }

  if ( botState == HIGH && aBotState == LOW) { //button switch part
    if (ledState == 0) {
      ledState = 1;
      sens [3] = ledState;
    }
    else {
      ledState = 0;
      sens [3] = ledState;
    }
  }
  aBotState = botState;
  radio.write(&sens, sizeof(sens));

  //Serial.println(sens[0]);
  //Serial.println(ledState);
  // Serial.println(sens[1]);
  //Serial.println(sens [3]);
}

And here for the Rx:
#include <Servo.h>
#include <SPI.h>
#include "RF24.h"

int sens [4];
const int polph = 7;
const int polen = 6;
const int led1 = 2;
const int led2 = 3;
const int ledError = 8;

Servo servo;
RF24 radio(9, 10); //
const byte address[6] = "00001";

void setup() {
  pinMode(polph, OUTPUT);
  pinMode(polen, OUTPUT);
  pinMode(led1, OUTPUT);
  pinMode(led2, OUTPUT);

  pinMode(ledError, OUTPUT);
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  delay(300);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  delay(300);
  digitalWrite(led1, HIGH);
  digitalWrite(led2, HIGH);
  delay(300);
  digitalWrite(led1, LOW);
  digitalWrite(led2, LOW);
  servo.attach(5);
  //Serial.begin(9600);
  radio.begin();
  radio.setDataRate (RF24_2MBPS);
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}

void loop() {
  if (radio.available()) {
    digitalWrite(ledError, LOW);
    radio.read(&sens, sizeof(sens));
    analogWrite(polen, sens [0]);
    digitalWrite(polph, sens[1]);
    servo.write(sens [2]);
    digitalWrite(led1, sens [3]);
    digitalWrite(led2, sens [3]);
  }
}

It’s really hard to diagnose a problem when you can’t see it.  Post the codes and a wiring diagram so someone can actually have a hope of seeing the problem.

Electrical noise is the problem quite often. In order to minimize noise, several key points must be observed:

Solder one 0.1uF ceramic capacitor from each terminal to the motor case. These are called decoupling capacitors and are used to suppress HF noise creeping in from the motors due to sparking/arching.

Choose appropriate AWS rating for your motor leads and adequate power supply. Inappropriately thin leads or insufficient battery discharge current can cause abrupt voltage drop on acceleration which will lead to sudden MCU resets (brown out resets).

Twist the leads around each other. This helps to further nullify arching noise.

As for Arduino, it is not the best way for making reliable RC software because it does simple things terribly wrong, e.g. sequential software polling instead of using hardware input capture. I would highly recommend learning how to write firmware for MCUs in native mode.
Check out this link to gain some inspiration on how to build an RC motor driver:
https://github.com/neoxic/STM8-RC-Dual-Motor-Driver#building-a-dual-12a-bidirectional-esc


text:
ESP-NOW host not receiving data
I'm trying to set up a network like the following:
|Host| <-------> |Node x 3|
I want to have a two-way connection between a host and each node, but each node cannot communicate with other nodes. The host and nodes are all NodeMCU 1.0 ESP8266 12E with the same software on each node (has to be this way). The problem I'm dealing with at the moment is that I can send messages successfully, but my host is not receiving any messages from the nodes. Right now I'm only testing it with one node, and I'm only testing sending from the node to the host just to make sure the devices are connected properly. Here's my code for both the node and host:
#include <espnow.h>
#include <ESP8266WiFi.h>
#include <string.h>

//Macros

#define PORT 80
#define CHANNEL 1
#define ESP_OK 0

//-----Anonymous Project----//
//-----Author: Anonymous----------//
//
// Last Date Modified: 6/18/20
//
// Description: This project is designed to have several node arduinos connected to a host arduino. Whenever an
// event is triggered on a node arduino, the host reacts to this and activates the corresponding LEDs.
// The host arduino acts as a server while the node arduinos act as clients. Both the hosts and clients send data
// back and forth to each other to ensure arduinos are still active and are responding properly.
// All the software is the same on host and client arduinos, so whether an arduino is a host
// or client is determined by its MAC Address.
//
// Progress: At the moment, this project successfully establishes connections between the host and the nodes.
// I am currently working on figuring out why the nodes do not successfully send to the host.

//Global Variables
char hostMACAdd [18] = "XX:XX:XX:XX:XX:XX"; //change this MAC address to change the host node
String SSID = "NETWORK NAME"; //change this SSID to change the network name
String Password = "PASSWORD"; //change this to change the password required to connect. If node, connect to SSID with password given

bool isHost; //flag that controls whether host or node code executes
bool A = true; //flag for event A
bool B = false; //flag for event B

//Server-Specific Globals
bool haveMessage;        //global for detecting readings

//Client-Specific Globals

//Function Prototypes
uint8_t * MACAddrToInt(String MAC);
void configDeviceAP(void);
void initESPNow();
void wifiConnect();

void setup() {
    Serial.begin(115200);
    Serial.println();
    delay(500);

    //is it a host or node?
    if(strcmp(WiFi.macAddress().c_str(),hostMACAdd)){
      //node
      isHost = false;
      Serial.println("Client powered!");
      Serial.println();

      //set device in station mode if it's a node
      WiFi.mode(WIFI_STA); // Station mode for esp-now sensor node

      //Enable ESP Now
      initESPNow();

      Serial.println("Initialization successful!");

      //attempt to connect to host
      Serial.println("Connecting to " + SSID);

      esp_now_set_self_role(ESP_NOW_ROLE_COMBO);
      if(esp_now_add_peer(MACAddrToInt(hostMACAdd), ESP_NOW_ROLE_SLAVE, CHANNEL, NULL, 0)!=ESP_OK){
        Serial.println("Error connecting to host.");
        //TODO: make this station a host and a node
      }

      Serial.println("Connection to host successful!");
    }
    else{
      //host
      isHost = true;
      Serial.println("Host powered!");
      Serial.println();

      //set device in AP mode if it's the host
      WiFi.mode(WIFI_AP);

      //Enable ESP Now
      initESPNow();

      Serial.println("Initialization successful!");
      esp_now_set_self_role(ESP_NOW_ROLE_COMBO);

      int unsuccessfullyRegistered = esp_now_register_recv_cb([](uint8_t *mac, uint8_t *data, uint8_t len) {

        String deviceMac = "";
        deviceMac += String(mac[0], HEX);
        deviceMac += String(mac[1], HEX);
        deviceMac += String(mac[2], HEX);
        deviceMac += String(mac[3], HEX);
        deviceMac += String(mac[4], HEX);
        deviceMac += String(mac[5], HEX);

        Serial.println("Message received from device: ");
        Serial.println(deviceMac);
        Serial.println(*data, DEC);
        //haveMessage = true;
      });

      if(!unsuccessfullyRegistered){
        Serial.println("Callback function registered!");
      }
      else{
        Serial.println("Callback function not registered.");
      }

      Serial.println("Waiting for clients...");
    }
}

void loop() {

  if(isHost){

  }
  else{

    String IP = WiFi.localIP().toString();
    uint8_t flagMsg;                  //message for events A and B.

    //             Inputs | Output
    //                    |
    //             A   B  |  flagMsg
    //             0   0  |  0
    //             0   1  |  1
    //             1   0  |  2
    //             1   1  |  3

    //FOR TESTING
    A = true;
    B = true;

    if(A){
      if(B){
        flagMsg = 3;
      }
      else{
        flagMsg = 2;
      }
    }
    else{
      if(B){
        flagMsg = 1;
      }
      else{
        flagMsg = 0;
      }
    }

    //String message = IP + " " + String(flagMsg); //maybe add pattern to this as well

    uint8_t * intMAC = MACAddrToInt(hostMACAdd);

    while(esp_now_send(intMAC, &flagMsg, sizeof(flagMsg))!=ESP_OK){
      Serial.println("Failed to send.");
      delay(2000);
    }

    Serial.println("Message Sent!");
    delay(5000);
  }

}

//convert MAC Address string to int
uint8_t * MACAddrToInt(String MAC){
  uint8_t hostMACAddArray [6];
  int values[6];

  sscanf(hostMACAdd, "%x:%x:%x:%x:%x:%x", &values[0], &values[1], &values[2], &values[3], &values[4], &values[5]);

  for(int i = 0; i<6; ++i){
    hostMACAddArray[i] = (uint8_t) values[i];
  }
  return hostMACAddArray;
}

//set as Access Point
void configDeviceAP(){
  bool result = WiFi.softAP(SSID.c_str(), Password.c_str(), CHANNEL, 0);
  if (!result)
  {
    Serial.printf("AP Config failed.");
  }
  else
  {
    Serial.printf("AP Config Success. Broadcasting with AP: ");
    Serial.printf("%s", SSID.c_str());
  }
}

void initESPNow(){
  WiFi.disconnect();
  if (esp_now_init() == ESP_OK) {
    Serial.println("ESPNow Init Success");
  }
  else
  {
    Serial.println("ESPNow Init Failed");
    ESP.restart();
  }
}

void wifiConnect() {
  WiFi.mode(WIFI_STA);
  Serial.printf("");
  Serial.printf("Connecting... "); //Serial.printf("%s",SSID.c_str());
  WiFi.begin(SSID, Password);
  while (WiFi.status() != WL_CONNECTED) {
     delay(250);
     Serial.print(".");
  }
  Serial.print("\nWiFi connected."); //Serial.printf("%s",WiFi.localIP().c_str());
}

The code isn't near finished yet, but theoretically the nodes should send an integer to the host and the host should print it. The console output for the node shows that the message is being sent, but the last thing that shows up on the host console output is "Waiting for clients", which would indicate that the host isn't receiving anything. I'm pretty new to ESP_NOW but I've been reading a lot of documentation on it recently and my code shouldn't be breaking any rules, but here we are.
Some potential problems that I suspect:

I had to define ESP_OK in my file for whatever reason. In most examples I've looked at, this macro hasn't had to be defined, and it's possible the value isn't actually 0.
Maybe I need to set up the host as a WIFI_AP_STA instead of WIFI_AP. Not sure why this would cause problems, but I'm just speculating at this point.

imho, there is some poorly document connections between wifi settings and espnow. I found a way to avoid much of the config each boot by using "cached" wifi settings. That is, you flash each chip w/ a sketch that connects to your wifi, run it, then re-flash with your espnow sketch. The only wifi config in setup is then WiFi.mode(WIFI_STA);WiFi.disconnect();. Then the only espnow stuff in setup becomes esp_now_set_self_role,esp_now_add_peer,esp_now_register_send_cb, and esp_now_send.

@dandavis What do you think the issue I'm dealing with is? I don't have SendCB functions registered, but should that really affect anything?

The ESP-Now slave must be in AP mode because you can then set the MAC address. Your code did set the AP mode with       WiFi.mode(WIFI_AP); but it doesn't explicitly set the AP Mac address, so all the sensor nodes are sending data to a pre-defined remote hostMACAdd, but your AP is using the default physical MAC address, you need to set it to match the sensor node configuration with wifi_set_macaddr(SOFTAP_IF, &hostMacAdd[0]);. See my working example.

@hcheung Thanks for the help! Now I'm curious why you have to set the MAC address in the pattern you detailed. Shouldn't I be able to set the MAC address to whatever I want?

Connect with MAC is faster than connect with SSID, as SSID need to establish a connection which take up to 5 seconds or sometime even more. Another benefits of setting your own local-administrated MAC address is that if you for any reason to replace your board in future, you don't need to change the sketch to put in new MAC address of your board. If you looks at my example, you will see on the comment of the sketch on how to create a valid local administrated MAC address.

The pattern of the local administrated MAC address is defined in IEEE specification.


text:
Error while inputting EEPROM.read() and EEPROM.write()
I am trying to store data in ATmega328 (Arduino Uno) using the following code using tinkercad:
#include <EEPROM.h>

void setup() {
  int addr, data=1;
  Serial.begin(9600);
  for (addr=0; addr<1023; addr++) {
    EEPROM.write(addr, data);
  }
  for (addr=0; addr<1023 ; addr++) {
    Serial.print(EEPROM.read(addr), DEC);
  }
}

When I simulate the code in the tinkercad, then i get the following error:
In function `main':
43: undefined reference to `loop'
 error: ld returned 1 exit status

Please help me where is the error in my code. I am not able to understand the error source.

Have you looked at any Arduino IDE example programs?
They all have a setup() and loop() function.
Apparently, Tinkercad is missing the loop() function in your code.
You can solve the issue by adding an empty void loop() { } after your void setup() { ... } code.

Thank you, now the code works. But I have a question in this code why there is use of the empty void loop() because it executes infinitely. It may be a silly question, I am a beginner to Arduino programming. But please tell what is the significance of empty void loop() in this code?

In most projects, Arduino code does not just execute once, but runs in a continuous loop, for example to service button presses, display data, take sensor measurements and act on them. The creators of the Arduino IDE have made the loop() function a standard part of every Arduino program to facilitate this. It's not part of standard C++. In your case your program just executes once and the loop() function does not have any significance. It's just doing nothing in a "controlled" way (continuous loop) and waiting for a reset.


text:
Speed control of BLDC with an integrated controller (Hall out, PWM in)
I am aiming at precise speed control of this BLDC motor: it has an integrated controller, outputting digital Hall signal (period 20.8ms on oscilloscope, w/o load) and taking PWM as input for speed regulation.
As far as my knowledge goes, this is a task for PID: measure Hall pulses at input, adjust duty cycle of the PWM based on target period/frequency of the Hall output.
The speed should be controlled with <1% error (even less is better).

Is this goal realistic with this particular motor?
How should I measure pulse duration?
Is pulseIn (with interrupts disabled) going to be sufficiently precise? Should I measure lows or highs?
Should I measure several pulses instead (and how)? Or should I accept imprecision in the pulse period and compensate (smooth) it using integral/derivative terms?
Do I need more than 8-bit PWM resolution for this task? (I will use Nano at first, but might switch to Nano Every, which has 10-bit PWM).

Any other comments/suggestions are welcome.

you can have 16bit PWM with Timer1 (library) on Nano

This is only a partial answer, about measuring pulse period or duration.
For best accuracy, I would recommend using the “input capture” feature
of a 16-bit timer. This is not as easy as using pulseIn() or timing
the signal with micros(): you will have to carefully study the MCU's
datasheet and manually configure the bits of some I/O registers. You
will be rewarded with high accuracy (single-cycle if the timer runs at
the MCU clock speed) and without the jitter inherent to any
software-based approach.
Beware that the Nano and Nano Every use different MCUs, with very
different timers. Both have input capture capability, but if you switch
from one to the other you will have to redo most of the work. Note that
the Nano is capable of 10-bit PWM if you program it low-level.
A software-based approach (pulseIn() or attachInterrupt() +
micros()) has the advantage of portability.

To expand a little on Edgar's answer:
There are two main ways of measuring frequency, and both require different resources and are better for different situations.
The method Edgar describes using the Input Capture method, is good for rapidly changing low frequency signals where you want to respond very quickly to changes in the frequency. It works by measuring the time between two pulses using a free-running timer. Of course you can only measure frequencies as fast as the timer can run, which is pretty fast anyway, and if configured right it can run almost entirely asynchronously so you can just query the current recorded time whenever you need to.
The other option is to count the number of pulses within a given time period. This can also be done in hardware but using a different set of peripherals.
For this you have two timers. Timer 1 has the ability to us an external signal on pin D5 as its clock. This basically turns it into a pulse counter, and every time a pulse arrives on the timer pin it increments the count by one.
Then you have a second timer which triggers an interrupt at a predefined period. What that period is depends on the responsiveness you want and the frequency range you want to measure.  You can also use the "prescaler" of Timer 1 to increase the frequency measurement range by only counting every 2nd or 4th or 8th etc edge.
Of course, all that timer use would interfere with PWM generation on the Nano, but should be better on the Nano Every, but you'd want to check the datasheet for timer usages.
So in summary:
Input capture

Fast response
Limited frequency range

Pulse counting with timer 1

Slower response
Naturally smoothed output
Greater frequency range
Understands the concept of zero Hz
Interferes with PWM generation

Whichever method you choose, sure, feed it through PID to create a stable output RPM.


text:
NRF24L01 Transmission Problems between Arduino UNO and Arduino Nano
I'm a beginner in using NRF24L01 tranceiver module. I tried sending a simple "Hello world" using Arduino Nano and a Arduino UNO with the use of two NRF24L01 modules. I don't get any output in the serial monitor at the receiver side. I checked the wire connection numerous times. Also checked the baud rate of both receiver code and the serial monitor are same and adddresses of the tranceiver code and the receiver code are same. Looking for a solution. Thanks in advance.
This is my tranceiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
void setup() {
  radio.begin();
  radio.openWritingPipe(address);
  radio.setPALevel(RF24_PA_MIN);
  radio.stopListening();
}
void loop() {
  const char text[] = "Hello World";
  radio.write(&text, sizeof(text));
  delay(1000);
}

And this is my Receiver code:
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(7, 8); // CE, CSN
const byte address[6] = "00001";
void setup() {
  Serial.begin(9600);
  radio.begin();
  radio.openReadingPipe(0, address);
  radio.setPALevel(RF24_PA_MIN);
  radio.startListening();
}
void loop() {
  if (radio.available()) {
    char text[32] = "";
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

I had the same problem and when I tried the isChipConnected () function, it told me that one of the nrf24l01 was not connected to the SPI and I assumed that one was bad. I bought 2 nrf24l01 with antenas and they work well (mostly). ( Here is the link to the library reference. Also, make sure you are using the TMRh20 version of the library, This one. This is more updated and better as far as I'm aware.
Like everyone would suggest, try to solder a 10uF capacitor between GND and VCC (that module requires more power sometimes). And the last thing I tried was to use one of this socket adaptors for the 2 modules here to use the 5v output from the arduino since it can deliver more mA and thus the module can work better.
This guide help me a little bit, I'll drop it here
I don't see anything wrong in the code, but I'm a newbie like you so (It seems we are using the same adress in our codes)

@Erick Navarrte @dragonflyrobotics Thank you so much for your response, I've tried each an every option you've mentioned, but for an unknown reason it didn't work out for me. Then I researched more on and found out the NRF24L01 base module.This NRF24L01 base module help you to fix 8 pin NRF24L01 series RF module without any problem. And also this module comes with 3.3V regulator and a built in capacitor and easy pin connection to connect PIC or arduino. Using NRF24L01 module and NRF24L01 base module I was successfully able to transmit data.Thanks again for taking time in answering, highly appreciate it.

I use Chinese clone nRF24L01. It has very narrow voltage tolerance. My Arduino is also clone.
The 3.3V output voltage was 3.27. The nRF24L01 was not working.  I added a 3 terminal regulator between Arduino 5V output pin and nRF24L01. The voltage was 3.303V.
Then nRF24L01 was working normally.
///////////////////////////////////////////////
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);
const byte rxAddr[6] = "00001";
void setup()
{
  radio.begin();
  radio.setRetries(15, 15);
  radio.openWritingPipe(rxAddr);
radio.stopListening();
pinMode(4,OUTPUT);
}
void loop()
{
  const char text[] = "Kawasaki_JP";
  radio.write(&text, sizeof(text));

  delay(1000);
}
////////////////////////////////////////////////

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10);
const byte rxAddr[6] = "00001";
void setup()
{
  Serial.begin(9600);
  while (!Serial);
  radio.begin();
  radio.openReadingPipe(0, rxAddr);
   radio.startListening();
}
void loop()
{
  if (radio.available())
  {
    char text[32] = {0};
    radio.read(&text, sizeof(text));
    Serial.println(text);
  }
}

////////////////////////////////////////////

library ;  https://downloads.arduino.cc/libraries/github.com/TMRh20/RF24-1.4.0.zip

Nevermind, I get it.  That is weirdly specific on the voltage.  Often what happens when you add a regulator closer to the nRF24L01 (on anything else for that matter) is just that you also happen to wind up with better decoupling, or just better current capacity.

You can also try using the NRFLite library. It is a lot easier to use. Also make sure you have a minimum of 3.3V and 0.5A power at the radio pin. If not, it may not transmit.
Here is a TX and RX example of sending text using the NRFLite. It worked perfectly for me!
TX:
/*

Demonstrates sending and receiving packets of different length.

Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND

*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 1;
const static uint8_t DESTINATION_RADIO_ID = 0;
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket1
{
    uint8_t FromRadioId;
    uint8_t Counter;
};

struct RadioPacket2
{
    uint8_t FromRadioId;
    char Message[31];    // Note the max packet size is 32, so 31 is all we can use here.
};

NRFLite _radio;
RadioPacket1 _radioData1;
RadioPacket2 _radioData2;

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

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }

    _radioData1.FromRadioId = RADIO_ID;
    _radioData2.FromRadioId = RADIO_ID;
}

void loop()
{
    // Pick a number from 0 - 60,000.
    uint16_t randomNumber = random(60001);

    if (randomNumber > 30000)
    {
        // Send RadioPacket1.

        _radioData1.Counter++;

        Serial.print("Sending ");
        Serial.print(_radioData1.Counter);

        if (_radio.send(DESTINATION_RADIO_ID, &_radioData1, sizeof(_radioData1)))
        {
            Serial.println("...Success");
        }
        else
        {
            Serial.println("...Failed");
        }
    }
    else
    {
        // Send RadioPacket2.

        // Create a message and assign it to the packet.
        // Strings need to be converted to a char array and note they cannot be longer
        // than 31 characters since that is the size of _radioData2.Message.
        String msg = "Hello " + String(randomNumber);
        msg.toCharArray(_radioData2.Message, msg.length() + 1);

        Serial.print("Sending '");
        Serial.print(msg);
        Serial.print("'");

        if (_radio.send(DESTINATION_RADIO_ID, &_radioData2, sizeof(_radioData2)))
        {
            Serial.println("...Success");
        }
        else
        {
            Serial.println("...Failed");
        }
    }

    delay(1000);
}

RX:
/*

Demonstrates sending and receiving packets of different length.

Radio    Arduino
CE    -> 9
CSN   -> 10 (Hardware SPI SS)
MOSI  -> 11 (Hardware SPI MOSI)
MISO  -> 12 (Hardware SPI MISO)
SCK   -> 13 (Hardware SPI SCK)
IRQ   -> No connection
VCC   -> No more than 3.6 volts
GND   -> GND

*/

#include <SPI.h>
#include <NRFLite.h>

const static uint8_t RADIO_ID = 0;
const static uint8_t PIN_RADIO_CE = 9;
const static uint8_t PIN_RADIO_CSN = 10;

struct RadioPacket1
{
    uint8_t FromRadioId;
    uint8_t Counter;
};

struct RadioPacket2
{
    uint8_t FromRadioId;
    char Message[31];    // Note the max packet size is 32, so 31 is all we can use here.
};

NRFLite _radio;
RadioPacket1 _radioData1;
RadioPacket2 _radioData2;

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

    if (!_radio.init(RADIO_ID, PIN_RADIO_CE, PIN_RADIO_CSN))
    {
        Serial.println("Cannot communicate with radio");
        while (1); // Wait here forever.
    }
}

void loop()
{
    // 'hasData' returns the size of the packet that was received, or 0 if there is no data.
    uint8_t packetSize = _radio.hasData();

    if (packetSize == sizeof(RadioPacket1))
    {
        _radio.readData(&_radioData1);

        Serial.print("Received ");
        Serial.print(_radioData1.Counter);
        Serial.print(" from radio ");
        Serial.println(_radioData1.FromRadioId);
    }
    else if (packetSize == sizeof(RadioPacket2))
    {
        _radio.readData(&_radioData2);

        String msg = String(_radioData2.Message);

        Serial.print("Received '");
        Serial.print(msg);
        Serial.print("' from radio ");
        Serial.println(_radioData2.FromRadioId);
    }
}


text:
Arduino Pro Micro not recognized by PC
so I've got myself a Arduino Pro Micro ATmega32U4 5V 16MHz and my PC (Win10 64bit) won't recognize it.
So, after I firstly plugged it in, it was detected as a Leonardo, rather than a Pro Micro, afterwards I installed hte drivers as noted by Sparkfun, and added the board to the IDE. Afterwards, my Arduino got detected as an unknown device where I can't use it anymore. I tried installing the drivers as given by sparkfun over the "unknown device" and no luck by trying, I always get an error saying that Windows has already the best drivers for it already installed.
And later, I uninstalled the "uknown device" in hope that it will re-install itself upon pluggin it back it, and it actually disappeard totally and got repalced by "Unknown USB Device (Device Descriptor Request Failed)" under USB controllers in the Device manager.
And I'm stuck here. In the IDE, the Pro Micro is detected as being on "COM1" no matter what COM port it really is, or is it even plugged it at all. Uploading a code results in the bar being filled up and "Uploading..." message, while maybe after a few minutes a very long error pops up without anything specific since you can plug out the board and get the same error.
I also tried a different PC with Windows 7 64bit on it, and instead of getting recognized as a Leonardo, this time it came straight to becoming a "Unknown device". I tried installing drivers multiple times with no luck, also again tried manually overiding the drivers in the Device manager and it always says that the best drivers are already installed.
I'm really stuck here.
Pics of  the board: https://postimg.cc/gallery/rwCDRfv

What happens if you press RESET (bridge between RST and GND briefly) twice?

Device Descriptor Request Failed has nothing to do with drivers. the PC can't read the PID/VID to install appropriate drivers. it may have many causes from bad cable or a broken solder on the usb socket, to the firmware itself which doesn't provide the needed information for PC.

@Majenko nothing special. The Arduino disconects briefly, and reconnects with the same error. Also, the two leds around the crystal oscilator briefly blink, but with very very very low brigthness compares to the main led which glows all the time, even when you reset the Arduino

@TirdadSadriNejad I heard something about flashing a new bootloader if it's a firmware problem? Could that be it. I'll also check (try to atleast) if the usb socket is badly soldered.

you can use another arduino as a programmer and burn the bootloader on the Pro micro

If it detects ok for a few seconds when you reset then it's good. It's just the sketch that is loaded onto it that is bad. Did you install something to it and then it stopped working? Also, don't install any drivers: you don't need them. The fact that it "says" Leonardo is meaningless.

I made it. I shorted the RST and GND pins in the right moment while uploading the code, and it just uploaded. Now it works perfectly, without the need of reseting it. Thanks for the assistance. It detects the port now, it uploads the code and no more errors show up. Blink code works.

It was wrong of you to try and install the driver as this board SHOULD be recognized as Leonardo. I would try to reinstall the Arduino IDE, it will also reinstall the drivers (hopefully)

I made it. I shorted the RST and GND pins in the right moment while uploading the code, and it just uploaded. Now it works perfectly, without the need of reseting it.

I got similar problem, I was trying to burn some HEX files and somehow, my windows wasn't able to recognize my atmega32u4 anymore, not even in Device Manager. I found that the bootloader was "bricked", and to fix it, you need to burn a valid HEX file, like the simplest led blink code. I've done that by the prompt command, using avrdude. So you reset twice, and you have 8 seconds to upload the hex file. It's faster doing that with prompt command than arduino software. After I uploaded the LED blink code successfully, the windows naturally recognized my atmega32u4 instantly, I could identify it in Device Manager as PCOM 4 since then. So you need to revive your bricked atmega's bootloader.
I guess there's nothing to do with the drivers in this case.


text:
Getting enum name from enum instance
Hello Arduino Stack Exchange,
I have an an enum instance called state:
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;
States state = SLEEP;

I would like to convert the value of state to a String so I can serially print it using Serial.println().
Currently, when I type String(state), I get a value 0, 1, etc.  I suppose this corresponds with the index of the enum's key.
How can I get it to return "SLEEP", "AWAKE", etc.?

your question is unrelated to the Arduino ... it is a C++ question ... please do some research about enums and about arrays

Will do @jsotola, thanks!

the arrays is a hint towards the solution

States state = IDLE; will not compile :)

Ah shoot @DataFiddler thanks for pointing that out.  My actual code has more enum cases, IDLE was one of them.  I updated the question to remove it

and did you read my answer?

Yes I had already read it, finally got around to testing it.  Thank you @Juraj

You can print the value as it is:
Serial.println(state);

This will print the the ordering number of the enum, but you can specify the value as any number or char.
enum States
{
  SLEEP = 'S',
  AWAKE = 'A',
  CRAZY = 'C'
};

Now if you print it with cast to char Serial.println((char) state); it will print a character, which in my opinion is much better then some number.
If you want to convert the enum values identifiers to strings you can do it with a preprocessor macro.
enum States
{
  SLEEP,
  AWAKE,
  CRAZY
} state;

#define IDNAME(name) #name
const char* stateNames[] = {IDNAME(SLEEP), IDNAME(AWAKE), IDNAME(CRAZY)};

I don't think this is better then to print the char values. To do a pretty print it is better to use descriptions.
const char* stateStr[] = {"Sleep", "Awake", "Undefined"};
Serial.println(stateStr[state]);

Love it.  Took me a minute (coming from Python) to realize #name wasn't a comment.  I used the preprocessor macro method, thank you!


text:
Possible to drive Waveshare E-ink without driver hat?
I bought and E-Ink display from waveshare and it came with such a “driver hat”: https://www.waveshare.com/wiki/E-Paper_Driver_HAT#Display_Config_Switch
I am wondering what exactly is the role of this component? Why can’t I directly connect the cables from the display to the GIPO pins and drive the display without the driver hat - given the right software?
(I am also happy to get a pointer to a better forum to ask in if this here isn’t the right place.)

Have you completed the steps in the "Working With Arduino" section: https://www.waveshare.com/wiki/E-Paper_Driver_HAT#Working_with_Arduino

No, you need the hat, or something equivalent. Turn it over. You see all those components? They exist to generate the right voltages for the ePaper display. Without those it won't work.
Sure, you can recreate it from the schematic, but why bother when you have it already?

I think i was hoping that it could be emulated in software. Of course I assumed that it was not possible, but i was wondering WHY not.


text:
Liquid Crystal LCD and serial monitor not playing well together
On my Arduino Uno, when I'm not using the serial everything seems in order:
#include <LiquidCrystal.h>

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup()
{
    // put your setup code here, to run once:
    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("Prints");
    lcd.setCursor(0, 1);
    lcd.print("Well");
}

void loop()
{
    delay(1000);
}

However the moment I open the serial port with:
Serial.begin(9600);

The problem starts.
Clearing the LCD does not clear it but prints a character with 4 horizontal lines. Trying to move the cursor will print a different  unrecognisable character. Sending things to the Arduino via the Serial port prints gibberish on the LCD.

Any idea why? Is there a way to work with the LCD and the serial port simultaneously? I require the serial port in order to control the Arduino from NodeJS.
#include <LiquidCrystal.h>

LiquidCrystal lcd(1, 2, 4, 5, 6, 7);

void setup()
{
    // put your setup code here, to run once:
    lcd.begin(16, 2);
    lcd.clear();
    lcd.print("Prints");
    lcd.setCursor(0, 1);
    lcd.print("Well");

    Serial.begin(9600);

    while (!Serial)
    {
        ; // wait for serial port to connect. Needed for Native USB only
    }
}

void loop()
{
    lcd.clear(); // This will print 4 horizontal lines character instead of clearing
    delay(500);
}

What type of Arduino?  On some pin 1 is one of the hardware serial pins. You can’t use that pin for other things like LCDs if you are using serial.

@Delta_G The board is Arduino Uno and you are right. Changing the pin from 1 to 3 solved the issue. Tnx! I wonder how many of 846,000 viewers of this youtube had the same issue? https://www.youtube.com/watch?v=dZZynJLmTn8&pbjreload=101 :-)

I will make it an answer.  Please accept

@jsotola the question was downvoted so I thought perhaps I misrepresented the issue. I restored the previous title to your suggestion. tnx.

somebody probably downvoted the post because you did not check which pins are used by the serial port

On an UNO pin 1 is one of the hardware serial pins.  You can’t use pin 0 or pin 1 for other things if you are using Serial in your code.
Even if you aren’t using Serial, you use pins 0 and 1 when uploading your code and having other things connected can mess up that process.  It’s generally advisable to stay away from pins 0 and 1 unless you absolutely must use them.


text:
Motor does not work for a specific case when programming with L293D motor driver shield
I tried to make a car that moves using a 4x4 keypad.
Pressing "12" unlocks the car and sets the motors to move forward. After that, if I press 4, the speed of the left motor is reduced to half allowing the motor to turn left, and vice versa for right wheel when key 6 is pressed.
Here is the code:
#include <Key.h>
#include <Keypad.h>

char* startCar = "12";
int position = 0, state = 0;

/*
 * state 0: off
 * state 1: forward
 * state 2: backward
 *
 */

const byte rows = 3;
const byte cols = 3;
char keys[rows][cols] = {
  {'1','2','3'},
  {'4','5','6'},
  {'7','8','9'}
};

byte rowPins[rows] = {2,3,4};
byte colPins[cols] = {PD7, PD6, PD5};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, rows, cols);

int a=12,b=11,c=10,d=9;
void setup()
{
  pinMode(a,OUTPUT);
  pinMode(b,OUTPUT);
  pinMode(c,OUTPUT);
  pinMode(d,OUTPUT);
  Serial.begin(9600);
  setLocked(true);
}

void loop()
{
  char key = keypad.getKey();
  Serial.print(key);
  if (key == '9')
  {
    position = 0;
    setLocked(true);
  }
  if (key == startCar[position])
  {
    position ++;
  }
  if (position == 2)
  {
    setLocked(false);
  }
  if(state)
  {
    if(key=='2')
     {
      //Move forward
        state = 1;
        runmotors(255,0,0,255);
     }
     if(key=='8')
     {
      //Move backward
        state = 2;
        runmotors(0,255,255,0);
     }
    if(key == '4')
    {
      if(state == 1)
      {
        runmotors(127.5,0,0,255);
      }

      else if(state==2)
        runmotors(0,127.5,255,0);
    }
    if(key == '6')
    {
      if(state == 1)
        runmotors(255,0,0,127.5);
      else if(state==2)
        runmotors(0,255,127.5,0);

    }
  }
  delay(100);
}

void setLocked(int locked)
{
  if (locked)
  {
    state = 0;
    runmotors(0,0,0,0);
  }
  else
  {
    state = 1; // Moves forward
    runmotors(127.5,0,0,255);
  }
}
void runmotors(int s1,int s2,int s3,int s4)
{
  analogWrite(a,s1);
  analogWrite(b,s2);
  analogWrite(c,s3);
  analogWrite(d,s4);
}

Everything works perfectly, except for the fact that when the state is 1, i.e. car is running forward, and I press 4 the left motor completely stops instead of reduced speed. The LED on the motor driver shield which shows whether a motor is running or not also goes off.
It is not a fault of the motor shield or the arduino as it worked when I test it individually with the motors (i.e. without the keypad etc).
Here is a photo of the shield:

Although my problem is not quite visible in this, but here is a video of the car: https://www.youtube.com/watch?v=bq19gNOL8Pg

If you pick the car up off the ground do the motors turn?  In my experience you can't control speed on DC motors all the way to 0.  At some point you hit a point where you're giving the motor power but just not enough to turn.  On my tank robot a PWM of 127 usually just gets me a hum and no movement.  Sometimes if I pick it up so that there is less rolling resistance the motor will turn a little.  Try using like 200 or so instead and see if it works like that.  That will at least tell you that the code is working.

Also note that analogWrite only takes integer values.  Sending 127.5 is the same as 127 in that case.

@Delta_G, The LED on the motor shield shows whether a motor is getting power or not. That LED itself goes off.
I think the particular pin (pin 12) of L293D is defective and is only supplying digital power, either full or 0.

What board?  On an UNO pin 12 is not a PWM pin.  It will give full power for anything above 127 and nothing for 127 and below.  It is truly a digital pin.

Yes an Arduino Uno board using the L293D motor driver shield. https://www.robomart.com/l293d-motor-driver-shield-for-arduino-raspberry-Pi-robotics?search=l293d&dsearch=l293d.  According to the documentation, the pins for connecting the robots are 9,10,11,12. All other pins are working perfectly except pin 12.

On an UNO pin 12 is not a PWM pin.  Pin 12 can only be high or low.  If you try to use analogWrite on a pin that isn’t capable of PWM then it will give you HIGH for any value greater than 127 and will give LOW for values 127 and below.  It will not produce PWM at all.

Yeah, this seems right.
I am a beginner at this and so just be confirm, when I say pin 12 in my code, it is the same pin irrespective of whether I have shield attached or not, right?
This makes sense. If you add this as an answer, I will mark it as correct. Thank you.

Yes, the pin numbers in the code are the pin numbers on the Arduino board itself regardless of what is connected to them.

On an UNO only certain pins are capable of PWM.  Pin 12 is not one of them.  When you try to call analogWrite with pin 12 it will recognize this and will simply call digitalRead for you with HIGH or LOW depending on whether your input is greater than 127.
With most motor controllers you can use one pin as a direction pin and the other as a PWM pin.  So to go one direction you set pin 12 HIGH and do inverted PWM on 11 (if those indeed go to the same motor I didn't look at your shield).  To go the other direction you write LOW on 12 and PWM on 11.
The motor turns when one pin is HIGH and the other is LOW.  When you set pin 12 high then PWM pin 11, whenever 11 is LOW in the PWM cycle it is turning the motor on and when it is HIGH it is turning it off.  So to make it run you might have to PWM 0 for go and 255 for stop.  Sometimes your PWM is on the enable line and then you still use 255 for go and 0 for stop.  It just depends on how things are wired.
When pin 12 is set to LOW then the motor is on when 11 is at the high part of the PWM cycle and off when it's low so you use 255 for go and 0 for stop.  But the whole time pin 12 doesn't have to change.
Now I am not 100% sure that this is the case with your particular motor controller, I'm more of a coder than a hardware guy.  But I've written enough code for motor controllers to know that you usually either need two direction lines and one PWM line or one direction and one PWM.  If that's not the case here then we can let someone else work on why.


text:
Can anyone find out why when I run this code for a GPS and BME680 sensor I have no errors but nothing happens
Here is the code
#include <Wire.h>
#include <SPI.h>
#include <Adafruit_Sensor.h>
#include "Adafruit_BME680.h"
#include <SoftwareSerial.h>

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

#define SEALEVELPRESSURE_HPA (1013.25)

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

SoftwareSerial gpsSerial(5, 11); // RX, TX (TX not used)
const int sentenceSize = 80;
char sentence[sentenceSize];

void setup() {
  Serial.begin(9600);
  while (!Serial);
  Serial.println(F("BME680 test"));
  gpsSerial.begin(9600);

  if (!bme.begin()) {
    Serial.println("Could not find a valid BME680 sensor, check wiring!");
    while (1);
  }

  // Set up oversampling and filter initialization
  bme.setTemperatureOversampling(BME680_OS_8X);
  bme.setHumidityOversampling(BME680_OS_2X);
  bme.setPressureOversampling(BME680_OS_4X);
  bme.setIIRFilterSize(BME680_FILTER_SIZE_3);
  bme.setGasHeater(320, 150); // 320*C for 150 ms
}

void loop() {

 static int i = 0;
  if (gpsSerial.available())
  {
    char ch = gpsSerial.read();
    if (ch != '\n' && i < sentenceSize)
    {
      sentence[i] = ch;
      i++;
    }
    else
    {
     sentence[i] = '\0';
     i = 0;
     displayGPS();
    }
  }
}

void displayGPS()
{
  char field[20];
  getField(field, 0);
  if (strcmp(field, "$GPRMC") == 0)
  {
    Serial.print("Lat: ");
    getField(field, 3);  // number
    Serial.print(field);
    getField(field, 4); // N/S
    Serial.print(field);

    Serial.print(" Long: ");
    getField(field, 5);  // number
    Serial.print(field);
    getField(field, 6);  // E/W
    Serial.println(field);
  }
}

void getField(char* buffer, int index)
{
  int sentencePos = 0;
  int fieldPos = 0;
  int commaCount = 0;
  while (sentencePos < sentenceSize)
  {
    if (sentence[sentencePos] == ',')
    {
      commaCount ++;
      sentencePos ++;
    }
    if (commaCount == index)
    {
      buffer[fieldPos] = sentence[sentencePos];
      fieldPos ++;
    }
    sentencePos ++;
  }
  buffer[fieldPos] = '\0';

  if (! bme.performReading()) {
    Serial.println("Failed to perform reading :(");
    return;
  }
  Serial.print("Temperature = ");
  Serial.print(bme.temperature);
  Serial.println(" *C");

  Serial.print("Pressure = ");
  Serial.print(bme.pressure / 100.0);
  Serial.println(" hPa");

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

  Serial.print("Gas = ");
  Serial.print(bme.gas_resistance / 1000.0);
  Serial.println(" KOhms");

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

  Serial.println();
  delay(2000);
}

What exactly does "nothing happens" mean? You have print statements in setup. Are these showing up in your Serial Monitor?

All that will show up on the serial monitor is "BME680 test" Then it will just do nothing.

put in more serial.print statements ... figure out where it stops

You have the BME pins defined for an SPI connection, but your created an instance for I2C connection with Adafruit_BME680 bme;, so how exactly you wire your BME sensor with the Arduino?


text:
How do i efficiently write this code for PS2 controller to USB convertion sketch for Arduino Pro Micro?
I am really new to coding and building stuff, so forgive me if it is anything offensive.i have been trying to convert my PS2 dualshock controller to USB using arduino. there is a library called ps2x that i can use to read the data and Joystick.h library to send it over USB-HID.
i just want to know if this is efficient code, if not how can i improve it.
This is the loop:

 ps2x.read_gamepad(); //This needs to be called at least once a second
                        // to get data from the controller.

  Joystick.setXAxis(ANALOGSTATE1); //Joystick.setButton(-127 to 127); 0 is center
  Joystick.setYAxis(ANALOGSTATE2);
  Joystick.setZAxis(ANALOGSTATE3);
  Joystick.setThrottle(ANALOGSTATE4); //This one is different, (0 to 255) 127 is center

  Joystick.setButton(0, DIGITALSTATE1); //Joystick.setButton(0-31, 0-1);
                                        //Joystick.setButton(Select Button to Use, Specify ON/OFF of Button);
  Joystick.setButton(1, DIGITALSTATE2);
  Joystick.setButton(2, DIGITALSTATE3);
  Joystick.setButton(3, DIGITALSTATE4);
  Joystick.setButton(4, DIGITALSTATE5);
  Joystick.setButton(5, DIGITALSTATE6);
  Joystick.setButton(6, DIGITALSTATE7);
  Joystick.setButton(7, DIGITALSTATE8);
  Joystick.setButton(8, DIGITALSTATE9);
  Joystick.setButton(9, DIGITALSTATE10);
  Joystick.setButton(10, DIGITALSTATE11);
  Joystick.setButton(11, DIGITALSTATE12);
  Joystick.setButton(12, DIGITALSTATE13);
  Joystick.setButton(13, DIGITALSTATE14);
  Joystick.setButton(14, DIGITALSTATE15);
  Joystick.setButton(15, DIGITALSTATE16);

if(ps2x.ButtonPressed(PSB_TRIANGLE)) {
  DIGITALSTATE1 = 1;
}
  else if (ps2x.ButtonReleased(PSB_TRIANGLE)){
  DIGITALSTATE1 = 0;
}
if(ps2x.ButtonPressed(PSB_CIRCLE))
  {
    DIGITALSTATE2 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_CIRCLE)){
    DIGITALSTATE2 = 0;
  }
if(ps2x.ButtonPressed(PSB_CROSS))
  {
    DIGITALSTATE3 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_CROSS)){
    DIGITALSTATE3 = 0;
  }
if(ps2x.ButtonPressed(PSB_SQUARE))
  {
    DIGITALSTATE4 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_SQUARE)){
    DIGITALSTATE4 = 0;
  }
if(ps2x.ButtonPressed(PSB_PAD_RIGHT))
  {
    DIGITALSTATE5 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_RIGHT)){
    DIGITALSTATE5 = 0;
  }
if(ps2x.ButtonPressed(PSB_PAD_UP))
  {
    DIGITALSTATE6 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_UP)){
    DIGITALSTATE6 = 0;
  }
if(ps2x.ButtonPressed(PSB_PAD_LEFT))
  {
    DIGITALSTATE7 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_LEFT)){
    DIGITALSTATE7 = 0;,
  }
if(ps2x.ButtonPressed(PSB_PAD_DOWN))
  {
    DIGITALSTATE8 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_PAD_DOWN)){
    DIGITALSTATE8 = 0;
  }
if(ps2x.ButtonPressed(PSB_L1))
  {
    DIGITALSTATE9 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_L1)){
    DIGITALSTATE9 = 0;
  }
if(ps2x.ButtonPressed(PSB_L2))
  {
    DIGITALSTATE10 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_L2)){
    DIGITALSTATE10 = 0;
  }
if(ps2x.ButtonPressed(PSB_R1))
  {
    DIGITALSTATE11 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_R1)){
    DIGITALSTATE11 = 0;
  }
if(ps2x.ButtonPressed(PSB_R2))
  {
    DIGITALSTATE12 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_R2)){
    DIGITALSTATE12 = 0;
  }
if(ps2x.ButtonPressed(PSB_L3))
  {
    DIGITALSTATE13 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_L3)){
    DIGITALSTATE13 = 0;
  }
if(ps2x.ButtonPressed(PSB_R3))
  {
    DIGITALSTATE14 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_R3)){
    DIGITALSTATE14 = 0;
  }
if(ps2x.ButtonPressed(PSB_START))
  {
    DIGITALSTATE15 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_START)){
    DIGITALSTATE15 = 0;
  }
if(ps2x.ButtonPressed(PSB_SELECT))
  {
    DIGITALSTATE16 = 1;
   }
  else if (ps2x.ButtonReleased(PSB_SELECT)){
    DIGITALSTATE16 = 0;
  }

  ANALOGSTATE1 = map(ps2x.Analog(PSS_LX), 0, 255, -127, 127);
  ANALOGSTATE2 = map(ps2x.Analog(PSS_LY), 0, 255, -127, 127);
  ANALOGSTATE3 = map(ps2x.Analog(PSS_RX), 0, 255, -127, 127);
  ANALOGSTATE4 = (ps2x.Analog(PSS_RY));

}```

I would move the part where you send the data with Joystick.setButton and stuff to after the part where you parse the data with all those if statements for the obvious reasons.  You shouldn't send a message before you write it.  But other than that if it's written and it works it's great.  It could be shortened with an OOP approach maybe, but that has some costs as well.  Anytime you're putting numbers on the ends of variable names what you really want is an array.  That might be something worth going and learning about.

you could use ternary statement like DIGITALSTATE1 = (ps2x.ButtonPressed(PSB_TRIANGLE))? 1 : 0;  ... or, since true and false are 1 and 0, you could use DIGITALSTATE1 = ps2x.ButtonPressed(PSB_TRIANGLE); ... or Joystick.setButton(0, ps2x.ButtonPressed(PSB_TRIANGLE));

you could also put all of the PS2 button names in an array and use a loop for the joystick.setbutton()

Thanks! i put the buttons in an array but set the joystick variables separate since i would get confused. it works great. but i guess dpad doesn't function as buttons but as Hat switch. so i got some more coding to do.


text:
SPI Slave Programming for Arduino
In my application Arduino Due is configured as master and instead of the actual slave device I am making use of Arduino Uno as Slave.I will share the Master code which I have worked out. Can Anyone please help me with respect to slave code of Arduino Uno to display the data in serial monitor at slave side. Any Help With respect to this aspect will be greatly greatly appreciated.
#include <SPI.h>

SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
const uint8_t ss = 10;

void setup() {
  pinMode(ss, OUTPUT);

  SPI.begin();

  digitalWrite(ss, LOW);
  SPI.beginTransaction(mySettting);
  SPI.transfer(0x00);
  SPI.transfer(0x25);
  SPI.transfer(0x1C);
  SPI.endTransaction();
  digitalWrite(ss, HIGH);
}

void loop() {
}

Thanks for the reply.
Referring to the code attached below at the slave side as you have mentioned that HEX to be displayed in serial monitor window, Do I need to add the HEX at the master side I mean Do I need to load the Hexadecimal data (0x00251C) into HEX buffer??
Thanks in Advance
#include <SPI.h>

SPISettings mySettting(125000, MSBFIRST, SPI_MODE0);
const uint8_t ss = 10;

void setup() {
  pinMode(ss, OUTPUT);

  SPI.begin();

  digitalWrite(ss, LOW);
  SPI.beginTransaction(mySettting);
  SPI.transfer(0x00);
  SPI.transfer(0x25);
  SPI.transfer(0x1C);
  SPI.endTransaction();
  digitalWrite(ss, HIGH);
}

void loop() {
}

Please edit your question to add more information if required.

SPI.h library by default only support Master mode, the SPI.begin() will automatically set slave select (ss) pin to HIGH whether you have pinMode(ss, OUTPUT) in your setup() code or not and set the Arduino as an SPI master. This can be see on SPI library source code.
As the SPI library does not contain the functionality for slave mode, in order to use Arduino as a Slave, you will need to do some customised setup, mainly on 1) setting MISO as OUTPUT for slave to send data; 2) enable slave mode by setting the SPCR register; 3) enable interrupt when data is received. Here is an example for an SPI slave on Arduino.
#include<SPI.h>

volatile boolean received;
volatile byte receivedData;

ISR (SPI_STC_vect)        //Inerrrput routine function
{
  receivedData = SPDR;   // Get the received data from SPDR register
  received = true;       // Sets received as True
}

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

  pinMode(MISO,OUTPUT);   //Sets MISO as OUTPUT
  SPCR |= _BV(SPE);       //Turn on SPI in Slave Mode
  received = false;
  SPI.attachInterrupt();  //Activate SPI Interuupt
}

void loop()
{
  if(received) {
    SPDR = receivedData;    // send back the received data, this is not necessary, only for demo purpose
    received = false;
    Serial.print(receivedData, HEX);
  }
}

Thanks for the reply. Now the data is transferred on MOSI line at Master end. I would like to monitor that MISO pin incoming data in slave side. In the above code which you have posted once I define MISO pin and in place of HEX  in the last line of the code I don't want the HEX value to be written in the last line.  I just want to display the HEX value written at MASTER side. I don't want to include it at slave side.


text:
How to get data out of loop?
hi i wrote a code(i modified it actually, please forgive me, im in a mess please help me if you can) for my esp8266 to serial communicate with at tiny 85 ,it will monitor switch state and publish accordingly. now i want to write a code where it wont publish but whenever the serial is available i want it to directly take it and digital write in void callback.
//ItKindaWorks - Creative Commons 2016
//github.com/ItKindaWorks
//
//Requires PubSubClient found here: https://github.com/knolleary/pubsubclient
//
//ESP8266 Simple MQTT light controller

#include <PubSubClient.h>
#include <ESP8266WiFi.h>

int LED3 = 12;
int LED4 = 14;
int LED2 = 13;
int LED1 = 15;

bool switch1;
bool switch2;
bool switch3;
bool switch4;
char data ;
// the number of the pushbutton pin

//EDIT THESE LINES TO MATCH YOUR SETUP

#define MQTT_SERVER "192.168.0.223"
const char* ssid = "TACHYON_HOME";
const char* password = "qwertyui";

//LED on ESP8266 GPIO2

char* lightTopic = "/test/light1";
char* lightTopic1 = "/test/light2";
char* lightTopic2 = "/test/light3";
char* lightTopic3 = "/test/light4";

WiFiClient wifiClient;
void callback(char* topic, byte* payload, unsigned int length);
PubSubClient client(MQTT_SERVER, 1883, callback, wifiClient);

void setup() {
  //initialize the light as an output and set to LOW (off)
  Serial.begin(9600);
  pinMode(LED3 , OUTPUT);
  pinMode(LED4 , OUTPUT);
  pinMode(LED1 , OUTPUT);
  pinMode(LED2 , OUTPUT);

    delay(100);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

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

    Serial.println("");
    Serial.println("WiFi connected.");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());

}

void loop(){
  //reconnect if connection is lost
  if (!client.connected() && WiFi.status() == 3) {reconnect();}

  //maintain MQTT connection
  client.loop();

  //MUST delay to allow ESP8266 WIFI functions to run
  delay(10);
   if (Serial.available()>0) /* If data available at serial port, enter if loop */
  {
    data = Serial.read(); /* Read data present at serial port */
    /* Print string with \r\n */
    Serial.print(data); /* Print data received */
    if (data == 'q') {
      client.publish(lightTopic,"1");

    }
else  if (data == 'w') {
      client.publish(lightTopic,"0");
    }
 else  if (data == 'e') {
      client.publish(lightTopic1,"1");
    }
    else if (data == 'r') {
      client.publish(lightTopic1,"0");

    }
     else if (data == 't') {
      client.publish(lightTopic2,"1");

    }
     else if  (data == 'y') {
      client.publish(lightTopic2,"0");

    }
     else if (data == 'u') {
      client.publish(lightTopic3,"1");

    }
     else if  (data == 'i') {
      client.publish(lightTopic3,"0");

    }

  }
}

void callback(char* topic, byte* payload, unsigned int length)
{
  //convert topic to string to make it easier to work with
  String topicStr = topic;

  //Print out some debugging info
  Serial.println("Callback update.");
  Serial.print("Topic: ");
  Serial.println(topicStr);

 if(topicStr.equals(lightTopic)){

   if(payload[0] == '1'){
      digitalWrite(LED1 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED1 , LOW);
    }
 }
 if(topicStr.equals(lightTopic1)){

   if(payload[0] == '1'){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED2 , LOW);
    }
 }
 if(topicStr.equals(lightTopic2)){

   if(payload[0] == '1'){
      digitalWrite(LED3 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED3 , LOW);
    }
 }
  if(topicStr.equals(lightTopic3)){

   if(payload[0] == '1'){
      digitalWrite(LED4 , HIGH);
    }

    else if (payload[0] == '0'){
      digitalWrite(LED4 , LOW);
    }
  }

}

void reconnect() {

  //attempt to connect to the wifi if connection is lost
  if(WiFi.status() != WL_CONNECTED){
    //debug printing
    Serial.print("Connecting to ");
    Serial.println(ssid);

    //loop while we wait for connection
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }

    //print out some more debug once connected
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
  }

  //make sure we are connected to WIFI before attemping to reconnect to MQTT
  if(WiFi.status() == WL_CONNECTED){
  // Loop until we're reconnected to the MQTT server
    while (!client.connected()) {
      Serial.print("Attempting MQTT connection...");

      // Generate client name based on MAC address and last 8 bits of microsecond counter
      String clientName;
      clientName += "esp8266-";
      uint8_t mac[6];
      WiFi.macAddress(mac);
      clientName += macToStr(mac);

      //if connected, subscribe to the topic(s) we want to be notified about
      if (client.connect((char*) clientName.c_str())) {
        Serial.print("\tMTQQ Connected");
        client.subscribe(lightTopic);
        client.subscribe(lightTopic1);
        client.subscribe(lightTopic2);
        client.subscribe(lightTopic3);

      }

      //otherwise print failed for debugging
      else{Serial.println("\tFailed."); abort();}
    }
  }
}

//generate unique name from MAC addr
String macToStr(const uint8_t* mac){

  String result;

  for (int i = 0; i < 6; ++i) {
    result += String(mac[i], 16);

    if (i < 5){
      result += ':';
    }
  }

  return result;
}

//////////////////i want to write some thing like///////////////////////////////////////
////////////////////////////////
if(topicStr.equals(lightTopic1)||Serial.available()>0){

   if(payload[0] == '1'|| data =q){
      digitalWrite(LED2 , HIGH);
    }

    else if (payload[0] == '0'|| data = w){
      digitalWrite(LED2 , LOW);
    }
/////////////////////////////////////////

so, what is your question?

how to do that i tried it but it isnt working its only taking data from mqtt but not from the switch state

Please, be more specific about what you want to achieve. And show your code! You wrote “I wrote a code for my esp8266”, yet the code you are showing is visibly not something you wrote. You also wrote you want “a code where it wont publish”: if it won't publish, then what interactions should it have with the MQTT server? Should it do MQTT at all? If not, why are you showing a sketch that is al about MQTT?

sorry i modified this code correction i want it to monitor the switches and turn off devices with mqtt and without mqtt too. i want it to control relays even when the network is off.

your post still says that you wrote the code

So you want your program to react to both MQTT and serial messages. You
wrote this snippet:
if (topicStr.equals(lightTopic1) || Serial.available() > 0) {
    if (payload[0] == '1' || data = q) {
        digitalWrite(LED2, HIGH);
    }
    else if (payload[0] == '0' || data = w) {
        digitalWrite(LED2 , LOW);
    }
    // ...
}

Other than a couple of syntactic problems (you mean data == 'q', not
data = q), the logic is not appropriate. This is because:

The test payload[0] == '1' only makes sense in the context of
parsing an MQTT message, otherwise payload cannot be meaningfully
defined.
For the same reason, the test data == 'q' only makes sense in the
context of parsing a serial command.

Since MQTT and serial use completely different commands, you will have
to handle them independently. You can keep the MQTT callback as is, and
implement the parser for the serial commands. Maybe something like:
if (Serial.available()) {
    char command = Serial.read();
    Serial.print(command);  // echo to the serial port
    switch (command) {
        case 'q':
            digitalWrite(LED1, HIGH);
            break;
        case 'w':
            digitalWrite(LED1, LOW);
            break;
        // ...
    }
}

Alternatively, use an if ... else if ... chain if you are not
comfortable with the switch syntax.
I personally would rather store the topic names, LED pins and serial
commands in an array of structs, and loop through the array in both the
MQTT callback and the serial parser. But I assume that may be too
advanced for your current programming level, so maybe just stick with
the simple, albeit verbose solution.


text:
ESP-01 does not run code after Deep Sleep
When using the deep sleep functionality on several ESP-01 boards, the boards require two resets in order to wake up properly (regardless of whether the resets are done by manually bridging the rst pin or by soldering a wire to do it from an interrupt). The boards do wake up and print some text automatically, but they do not run their firmware/code.
#include <ESP8266WiFi.h>
void setup() {
    Serial.begin(74880);
    Serial.print("\n--------------STARTING----------------\n");

    //pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
    //digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off (gpio @ high= off)

    delay(500);
    ESP.deepSleep(2000000, WAKE_RF_DEFAULT );
}

void loop() {
}

I have not been able to just wake the board and run the code like most examples on the web intend to work, so I suppose the problem is not with this code.
On a successful wake up, the serial output looks like this:
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)
load 0x4010f000, len 3456, room 16
tail 0
chksum 0x84
csum 0x84
va5432625
~ld

--------------STARTING---------------

After the first reset, the board does indeed wake up, but it does not run it's code. It only prints this
 ets Jan  8 2013,rst cause:2, boot mode:(3,6)

And then hangs there. After another reset, it successfully runs it's code.
This issue persists across all the esp 01 boards i own, and i have tried pulling UP and DOWN almost every combination of pins recommended. The line that is printed in the fauly cases does indeed say it is booting in the right mode, but still the code does not run, nor mine nor the one that runs before mine

Had you tried ESP.deepSleep(2000000); instead of ESP.deepSleepInstant(2000000, WAKE_RF_DEFAULT ); ?

@fabiuz7 yes, i tried deepSleepInstant to test if it had any different results from deepSleep, with no effect

Are you using this board ? It seems not exposing the pin 16, required to make the deep sleep working.  https://www.mouser.it/ProductDetail/SparkFun/WRL-13678?qs=WyAARYrbSnZdmwzlRTs1Tw%3D%3D&vip=1&gclid=Cj0KCQjw3Nv3BRC8ARIsAPh8hgJygBYf_pJV_0gmP_mQjns1tsS1YFMyzQ1WgaypqsutPeeVbyJw27caAmcNEALw_wcB

I've tested your code on a Wemos D1 mini and it works as expected

@fabiuz7 pin16 is actually needed to wake the chip from deepsleep. I mentioned in my post that i have the issue when resetting manually as well as from an interrupt.
For example, if i don't connect pin16 i have to manually reset twice. If i connect that pin16 to the rst pin, i still have to reset manually once.

GPIO16 provides the Reset signal after wake. The GPIO16 pin needs to be connected to RST. This is difficult with the ESP-01/ESP-01S module, as the GPIO-16 is not exposed, nor is it connected to the RST pin on the board. Big bummer. Connecting GPIO16 to RST on a ESP-8266 module with all the pins exposed does work. I was also able to connect the GPIO16 on my ESP01 to Reset and it also works.

Yeah, i'm sorry but i specifically described that i got weird behaviours even when using the RESET pin. This default answer of "oh you just didn't know to solder a wire" is what made me go insane at the time, because it's repeated like a mantra even to completely unrelated issues.

What sasso is describing is classic Deep Sleep Zombie mode. There's someone else here with ESP-01 boards with the same issue.  I'd bet you got your boards in blister packs from Inland.  I didn't see any ESP-01 boards from Inland at my local computer store, only ESP-01S, and that one works with Deep Sleep just fine.  I only bought the one for a test.  I believe it's the Flash chip, but we haven't proven that yet.  I have plenty of Winbond flash in case I find a board that goes zombie, and can prove or disprove my theory.  I have 8 different types of boards and modules, and all come out of Deep Sleep correctly.
edit: If the pic at Ali is correct, the Puya Flash shouldn't be causing an issue, presuming it's real and not a clone.  Half the time the pics are only 'representative examples' of what they ship.  The ESP8266 Arduino core has supported Puya for a while now.  Also, on sober reflection the Inland package I bought said ESP-01S, and it's actually an ESP-01 (false advertising).  I looked closer and didn't see the pull-up resistors. :-(
If you're powering it from that USB programmer board, it should work.  If you have a separate 3.3V supply, I'd be suspicious of the supply.  The current spikes as the ESP is booting will cause many switching supplies to drop below 2V briefly, and the ESP goes insane.  Without having a zombie in front of me, I'm at a loss to go a lot further as my 'scope leads aren't that long.

Thank you very much for answering, the fact that almost no one ever aknowledged this problem around the net was driving me crazy. I got 8 boards from aliexpress from china, none of them works after deep sleep. I recentrly tried ordering a couple more to see if it was an hardware issue or not. Let me know if you need any info on the boards i got

Do you have the ali link, or a very good photo of the top of the board so that I can read the ID on the Flash chip?  I suspect it says T25S80 (supposedly Bright Moon Semi) which you can also get by doing Serial.println(ESP.getFlashChipId(), HEX); after you've started the serial port.  I get 14605E with what I think is a Bright Moon chip, although the manufacturer ID doesn't match their datasheet.

https://www.aliexpress.com/item/32834727685.html?spm=a2g0s.9042311.0.0.4c334c4ddxlsF5 this is where i got them, the  ESP-01S  variety


text:
Add char at intervals in a String
I'm trying to create a function that will take a String as an input, and at every 20 characters, it will instert "\n" so that the string doesn't go off the side of my screen (I'm using an oled with the SSD1306Ascii library).
This is my code so far, but when I run it nothing appears on the screen (I have another part of the code which passes the string to the funtion):
String message = "";
String newMessage = "";

void printMessage(String message) {
  oled.clear();
  if(message.length() > 20) {
    current = 20;
    while(current < message.length()) {
      newMessage = message.substring(current-20, current) + "\n";
      newMessage = newMessage + message.substring(current+1);
      current+20;
    }
    oled.println(newMessage);
  }
  else {
    oled.println(message);
  }
}

Sorry, forgot to mention the variables I have decalered, will change that now

One problem that strikes me is that if the length of the passed message is 20 or less, newMessage will remain empty.

@DarioP Good point, I've updated the code.

I think that your implementation is fundamentally flawed. In the while loop, when you assign newMessage to a message.substring you are discarding all the work done in the previous iterations.
Also I would recommend keeping the splitting and the printing separated. The operator += also is very handy here. This code (untested) should implement your original idea in a correct way
String splitMessage( const String & message, const unsigned limit) {
  String newMessage = "";
  unsigned i = 0;
  while ( i+limit < message.length() ) {
    newMessage += message.substring(i, i+limit);
    newMessage += '\n';
    i += limit;
  }
  newMessage += message.substring(i);
  return newMessage;
}

Then you can do:
whatever.println(splitMessage(myMessage, 20));

Note that I retained the use of String from your original implementation, although, being in an embedded environment, it is likely better to avoid it in favor of stack-allocated c-strings.
I have found a substantial amount of pretty enlightening information in the various answers to this question: Is using malloc() and free() a really bad idea on Arduino?

Ah, thats far better than what I came up with, thanks. Your code worked perfectly, however I did need to change "message.size()" to "message.length()"

String object create a memory block at the heap using malloc(), dynamically create a String object newMessage and return the String object from a function is not a good practise as it could create memory leak in long run because the heap memory for newMessage never get free up. For each call to the splitMessage(), a new block of memory is created at the heap....

@hcheung I got you. I am a C++ programmer still getting familiar with the flaws of Arduino "language". Would it be better to return the result through a non const reference argument? Like void splitMessage(String & out, const String & in, const unsigned limit)?

As a c++ programmer, you should know the pitfall of malloc() and heap usage well. String object behind he scene uses malloc() to create a variable when you do something like String newMessage = "";, and each iteration of concatenation also cause heap fragmentation. The general idea is not to use String in Arduino (with only 2k RAM), if you really want to use it, in this particular case, I would declare it as a global, so that you can free it afterward, but again, if you are doing it that way, it make not much different to just use c array instead of String object.

@hcheung as a C++ programmer I always enforce RAII so that the allocated memory is automatically freed when the variable goes out of scope, and I have no further concerns about the heap.

One issue with both your failed implementation and the previous answer
is that they do loads of dynamic allocations and copies. Every time you
use the String’s + or += operators you are allocating heap memory
for a brand new String, copying the original character data into the
newly allocated space, and eventually destroying the original Strings
when you don’t need them anymore.
The simplest way to avoid all these copies and allocations is to not
build the String you want. Instead, just write() the pieces one after
the other on the display. Here is a zero-copy, zero-dynamic allocation
solution:
void printMessage(const char *message) {
    size_t length = strlen(message);
    while (length > 20) {
        oled.write(message, 20);
        oled.write('\n');
        message += 20;  // point to the rest of the message
        length  -= 20;  // remaining length
    }
    oled.write(message);
}

Note that the method Print::write(const char *, size_t) is used here
to print a slice of the message without ever building it as a string in
memory.
On these memory-constrained devices it is always preferable to avoid
heap allocation, and thus String objects. However, if for whatever
reason you really need to print a String object, then you can use
the following overload to print it’s internal buffer without making any
extra copy:
void printMessage(const String &message) {
    printMessage(message.c_str());
}


text:
Serial Output on ESP8266 doesn't work on 2/3 of my boards
I have 3 NodeMCU 1.0 12E ESP8266 boards.
Issues
Two of them require me to unplug and replug in the boards every time I want to flash code, and nothing appears on the serial output with this simple blink modified sketch I've shown below on those same boards. I don't have any special pin configurations on either of these boards, I simply have the NodeMCU boards connected to the PC through MicroUSB. The other board has no issues with uploading and displaying serial output also with no special pin configurations.
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  Serial.begin(115200);
  pinMode(4, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  Serial.println("ON");
  digitalWrite(4, HIGH);   // turn the LED on (HIGH is the voltage level)
  delay(1000);                       // wait for a second
  Serial.println("OFF");
  digitalWrite(4, LOW);    // turn the LED off by making the voltage LOW
  delay(1000);                       // wait for a second
}

Interestingly enough, the LED connected to the corresponding PIN behaves correctly, which would indicate flashing the code works fine, but serial output doesn't work on 2 of the boards.
What I've tried

Making sure the baud rate of the serial monitor is 115200.

Tried the sketch with different baud rates.

Made sure the correct board and ports are being recognized.

I have tried using certain pin configurations on some of my boards, (grounding GPIO pin 0, connecting Rx and Tx, etc), but like I said, I don't do this in general when uploading code. Maybe the ESP8266 requires some sort of initialization process that I haven't done?

I can't tell if my other two boards are defective or if I need to take extra steps for the two boards that are acting strange. Has anyone here experienced something like this?
Thanks

If you can upload code you should also be able to communicate via serial, it's the same interface. Do you see anything on the serial line? In general there is nothing more to do than calling Serial.begin() for initialization.

@SimSon I see a bunch of reverse question marks sometimes, and sometimes, I see absolutely nothing in the nonworking boards. As far as I can tell, in both the serial monitor and the Tools settings, the settings are exactly the same for both the working and nonworking boards. The LEDs still blink in the non-working boards.

@SimSon Also in the working board, the serial output of a simple program that prints "Message Sent" always prints garbage like "⸮Message ⸮⸮!H⸮", "MessagLR⸮⸮4:, etc". Its usually not perfect and has some soft of problems. Are my boards just simply not working?


text:
Connecting microSD reader and e-paper display to Nano at the same time?
Pretty much as the question states, I'm wondering if it's possible to connect (this: https://www.waveshare.com/7.5inch-HD-e-Paper-HAT.htm ) 7.5" e-paper display that has raspberry pi HAT and an SD card reader to Arduino nano/micro for reading images off SD and displaying on the screen. I'm an novice and a not sure if i can use the same pins for multipurpose
Thanks!

Did you read the warning about the Arduino Uno on that page? This goes for the Nano as well. That said, yes, it's probably technically possible.if you can find a suitable library and you can overcome the memory limits stated on the product page and the fact that you have to share the SPI bus between two devices. I really don't recommend it for a novice. You're probably better of with a shield designed for and supported by the Arduino.

The SPI sharing part is the one that I'm mostly confused about. Also if i go with a shield, that would limit me to arduino UNO

The physical difference between Uno and Nano is the least problem. RAM problem already inhibits using a Nano/Uno with that 880×528 display. Using an SD reader alone takes at least half of the Uno/Nano RAM. A Jetson Nano is not an Arduino Nano.

What would be the ideal solution (not limited to arduino) to use the display and sd card together, using least amount of power, meaning no power wasted on any other processes?

Sharing an SPI bus should not be a problem If you design it well. The MISO, MOSI, and SCLKs can be connected to both devices, the Chip Selects (CS) need to be separate. This is the way many commercially available shields (for example the Arduino Ethernet shield with Ethernet / SD card or many TFT shields with TFT / Touch interface and SD card combined on one SPI bus) work,

No. Even the e-Paper alone is not usable by an Arduino Nano.