text:
How to attempt connection to WiFi only once?
I am working on a garden timer project, I connect to WiFi once and if its successful show time from NTPClient or else show time from RTC.
I have been done the above, and it works in the sense that if I turn off the WiFi while the program is running, it switches to the RTC and back to NTPClient when  WiFi is available again.
PROBLEM- If the WiFi is not available when the board boots, the program just waits for WiFi where I want it to use RTC.
Hardware-ESP8266 based NodeMCU, I2C RTC, I2C 16x2 LCD.
Software-Blynk
My code:-
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include <DS3231.h>
#include <Wire.h>
#include "DHT.h"
#include "LiquidCrystal_PCF8574.h"

#define BLYNK_PRINT Serial
#define DHT_PIN_DATA  12
// LCD definitions
#define LCD_ADDRESS 0x27
#define LCD_ROWS 2
#define LCD_COLUMNS 16
#define SCROLL_DELAY 150
#define BACKLIGHT 25
#define DHTTYPE DHT22

// Auth code and wifi credentials here
char auth[] = "ymri80lFL9_xjZppphf6WIRHtQ1kqEWOt9zBy";
char ssid[] = "Hotspot-82DB";
char pass[] = "qqnbkbbbk";
int autoSch;
int waterNow;
int morTime;
int afterTime;
int postNoon;
int eveTime;
int schTime;
int minStep;
int interval;
int count;
int flag = 0;
int soilHum = A0;
int waterItr;
int checkRun;
int waterItr1;
int oneTime;
bool h12Flag;
bool pmFlag;

unsigned long previousMillis = 0;
byte wifi[] = {
  B00001,
  B00001,
  B00101,
  B00101,
  B00101,
  B10101,
  B10101,
  B10101,

};

DHT dht(DHT_PIN_DATA, DHTTYPE);
LiquidCrystal_PCF8574 lcdI2C;
WiFiUDP ntpUDP;
DS3231 Clock;
NTPClient timeClient(ntpUDP, "in.pool.ntp.org", 19800, 600000);

BLYNK_CONNECTED() {
  Blynk.syncAll();
}

BLYNK_WRITE(V0)
{
  autoSch = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V1)
{
  morTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V2)
{
  afterTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V6)
{
  postNoon = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V3)
{
  eveTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V10)
{
  waterNow = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V4)
{
  schTime = param.asInt(); // assigning incoming value from pin V1 to a variable
}

BLYNK_WRITE(V7)
{
  minStep = param.asInt(); // assigning incoming value from pin V1 to a variable
}

void setup()
{
  Wire.begin();
  dht.begin();
  lcdI2C.begin(LCD_COLUMNS, LCD_ROWS, LCD_ADDRESS, BACKLIGHT);
  pinMode(LED_BUILTIN, OUTPUT);
  digitalWrite(LED_BUILTIN, HIGH);
  pinMode(14, OUTPUT);
  pinMode(15, OUTPUT);
  digitalWrite(14, LOW);
  digitalWrite(15, LOW);
  Blynk.virtualWrite(V5, 0);
  Blynk.virtualWrite(V8, 0);
  pinMode(0, INPUT_PULLUP);
  Serial.begin(9600);
  Blynk.begin(auth, ssid, pass);
      timeClient.begin();
  /*
    while ( WiFi.status() != WL_CONNECTED ) {
      delay ( 500 );
      Serial.print ( "." );
    }
  */

  Blynk.syncAll();
  lcdI2C.createChar(0, wifi);
}

void loop()
{
  Blynk.run();
  time_run();
  lcd();
  butPress();
  butCheck();
  /*if (waterNow != 1) {
    Blynk.virtualWrite(V10, 0);
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
    Blynk.virtualWrite(V8, minStep * 60);
    }*/
  if (waterNow == 1) {
    if (waterItr < minStep * 60) {
      waterOn();
      waterItr++;
      delay(500);
    }
    else {
      waterOff();
    }

  } else if (autoSch == 0) {
    auto_run1();
    waterItr = 0;
  } else if (autoSch == 1) {
    sch_run2();
    waterItr = 0;
  } else {
    //Blynk.virtualWrite(V10, 0);
    waterItr = 0;
    digitalWrite(14, LOW);
    Blynk.virtualWrite(V5, 0);
  }
  Blynk.syncAll();

}

void butPress() {
  if (digitalRead(0) == LOW) {
    delay (100);
    if (flag == 0) {
      flag = 1;
    }
    else if (flag == 1) {
      flag = 0;
      waterItr1 = 0;
      digitalWrite(15, LOW);
      Blynk.virtualWrite(V5, 0);
    }
  }
}

void butCheck() {
  if (flag == 1) {
    digitalWrite(15, HIGH);
    Blynk.virtualWrite(V5, 255);
    lcdI2C.selectLine(2);
    lcdI2C.print("Wtr B Now :  ");
    lcdI2C.print(600 - waterItr1);
    if (waterItr1 < 600) {
      waterItr1++;
      delay(500);
    }
    else {
      waterItr1 = 0;
      flag = 0;
      digitalWrite(15, LOW);
      Blynk.virtualWrite(V5, 0);
    }
  }
}

void lcd() {
  if (oneTime == 0){

    oneTime=0;
    }
  //lcdI2C.clear();
  lcdI2C.setCursor(0, 0);

  if (WiFi.status() == WL_CONNECTED) {
    timeClient.update();
    lcdI2C.print("T:");
    lcdI2C.print(timeClient.getFormattedTime());
    Clock.setHour(timeClient.getHours());
    Clock.setMinute(timeClient.getMinutes());
    Clock.setSecond(timeClient.getSeconds());
  } else {
lcdI2C.print("R:");
lcdI2C.print(Clock.getHour(h12Flag, pmFlag)); lcdI2C.print(":"); lcdI2C.print(Clock.getMinute()); lcdI2C.print(":"); lcdI2C.print(Clock.getSecond());
  }
  if (autoSch == 0) {
    lcdI2C.setCursor(10, 0);
    lcdI2C.print(" Auto   ");
  } else {
    lcdI2C.print(" Sch   ");
  }

  if (WiFi.status() == WL_CONNECTED) {
    lcdI2C.setCursor(15, 0);
    lcdI2C.write(0);
  }

  if (digitalRead(14) == 1) {
    lcdI2C.selectLine(2);
    lcdI2C.print("Wtr Now           ");
  }
  else
  {
    if (int(timeClient.getHours()) < 6 && morTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6a ");
    } else if (int(timeClient.getHours()) < 12 && afterTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 12n ");
    } else if (int(timeClient.getHours()) < 14 && postNoon == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at:14pn ");
    } else if (int(timeClient.getHours()) < 18 && eveTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 18e ");
    } else if (int(timeClient.getHours()) >= 18 && morTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6a ");
    } else if (int(timeClient.getHours()) >= 6 && morTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 6a ");
    } else if (int(timeClient.getHours()) >= 12 && afterTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 12a ");
    }   else if (int(timeClient.getHours()) >= 14 && postNoon == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 14a ");
    }  else if (int(timeClient.getHours()) >= 18 && eveTime == 1 && autoSch == 0) {
      lcdI2C.selectLine(2);
      lcdI2C.print("Auto Wtr at: 18a ");
    } else {
      if (autoSch == 0) {
        lcdI2C.selectLine(2);
        lcdI2C.print("  Switch to Sch  ");
      } else {
        lcdI2C.selectLine(2);
        lcdI2C.print("  Schedule mode ");
      }
    }
  }
}

void waterOn() {
  lcdI2C.setCursor(0, 0);
  digitalWrite(14, HIGH);
  Blynk.virtualWrite(V5, 255);
  lcdI2C.selectLine(2);
  lcdI2C.print("Wtr Now :");
  lcdI2C.print((minStep * 60)  - waterItr);
  Blynk.virtualWrite(V8, (minStep * 60)  - waterItr);
  Blynk.syncAll();
}

void waterOff() {
  Blynk.virtualWrite(V10, 0);
  digitalWrite(14, LOW);
  Blynk.virtualWrite(V5, 0);
  Blynk.virtualWrite(V8, 0);
  waterItr = 0;
  Blynk.syncAll();
}

void sch_run2() {
  if (schTime == 1) {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
    Blynk.syncAll();
  } else if (schTime == 0) {
    checkRun = 0;
    if (checkRun == 0) {
      digitalWrite(14, LOW);
      Blynk.virtualWrite(V5, 0);
      Blynk.syncAll();
    }
  }
}

void time_run() {
  Blynk.virtualWrite(V11, int(timeClient.getHours()));
  Blynk.virtualWrite(V12, int(timeClient.getMinutes()));
  Blynk.virtualWrite(V13, float(dht.readTempC()));
  Blynk.virtualWrite(V14, float(dht.readHumidity()));
}

void auto_run1() {
  if (morTime == 1 && String(timeClient.getFormattedTime()) > "06:00:00" && String(timeClient.getFormattedTime()) < "06:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
  }
  else if (afterTime == 1 && String(timeClient.getFormattedTime()) > "12:00:00" && String(timeClient.getFormattedTime()) < "12:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
  }
  else if (postNoon == 1 && String(timeClient.getFormattedTime()) > "14:00:00" && String(timeClient.getFormattedTime()) < "14:20:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
  }
  else if (eveTime == 1 && String(timeClient.getFormattedTime()) > "11:49:00" && String(timeClient.getFormattedTime()) < "11:50:00") {
    digitalWrite(14, HIGH);
    Blynk.virtualWrite(V5, 255);
    checkRun = 1;
  }
  else  {
    //(String(timeClient.getFormattedTime() == "06:20:00" || "12:20:00" || "14:20:00" || "13:48:00"))
    //waterNowrun();
    checkRun = 0;
    if (checkRun == 0) {
      //Blynk.virtualWrite(V10, 0);
      digitalWrite(14, LOW);
      Blynk.virtualWrite(V5, 0);
      Blynk.virtualWrite(V8, 0);
      Blynk.syncAll();
    }
  }
}

Blynk.begin waits for the WiFi connection. is that what you ask? then it has nothing to do with RTC or NTP. is that your real Blynk token? the esp8266 SDK has NTP, don't use NTPClient library on esp8266.

@juraj No its not the real one, still would like to use NTPClient

@juraj What's the problem with NTP, Blynk.begin waits for the WiFi connection. How to prevent it?

your question is all about NTP and RTC, but you ask about WiFi connection. so I don't know what do you ask. Blynk.begin() calls Blynk.config() and then waits for WiFi. you can use Blynk.config only

@juraj Forget about NTP and RTC, the code does not execute until its connected to wifi, how do I prevent it?

replace Blynk.begin with Blynk.config(key) and handle the WiFi connection as usual without Blynk

@Coder9390 For details see the Blynk docs.

Instead of using blynk.begin() use WiFi.begin() and blynk.config() to achieve non-blocking code
void setup(){
//  Blynk.begin(auth, ssid, pass); don't use this
  WiFi.begin(ssid, pass);
  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }
  Blynk.config(auth);
}


text:
AT 09 BLE module not transmitting data
I have recently started working with the Arduino Pro Mini 5v/16Mhz and an AT 09 BLE module for an IoT project. I am controlling the BLE module using Software Serial and am leaving the hardware serial for for my laptop. I am using an app called "Serial Bluetooth Terminal" on Android to send/receive messages. The BLE module is able to receive messages and the "AT" command is also working. But when I try to get the BLE module to send a message, I get no response in the app. Any idea why this is happening and how can I resolve it?
My connections are:

Laptop -> Arduino UNO, MB-102(USB to breadboard power adapter)
Arduino UNO(without IC) Rx -> Pro mini Tx0
Arduino UNO(without IC) Tx -> Pro mini Rx1
Arduino UNO(without IC) RESET -> Pro mini Rst
MB-102 5V -> Pro Mini Pin RAW
MB-102 GND -> Pro Mini Pin GND
Pro Mini Pin 2 -> AT 09 TXD
Pro Mini Pin 3 -> AT 09 RXD
Pro Mini Pin VCC -> AT 09 VCC
Pro Mini Pin GND -> AT 09 GND

This is my code:
#include<SoftwareSerial.h>

SoftwareSerial ble(2, 3);

int statePin = 4;
char c;
void setup()
{
  Serial.begin(9600);
  ble.begin(9600);
  ble.print("AT\r\n");
  delay(100);
  while(!ble.available())
    Serial.print(".");
  while(ble.available())
  {
    Serial.print(char(ble.read()));
  }
}

void loop()
{
  while(ble.available() > 0)
  {
    c = char(ble.read());
    delay(10);
    Serial.print(c);
    ble.print(c);
  }
}

This is the first time I am posting here so please tell me if I missed out on any information.

You have not connected the STATE signal?

Yes. That is correct. Was I supposed to? Edit: The state pin does not seem to be doing anything. It seems to be grounded irrespective of connection status. Verified with a multimeter.

So my AT 09 module is most likely faulty. I got a new HM 10 and connected it without changing any connections or code and it worked like a charm.
I do not know the exact nature of the defect but since the chip was responding to commands, I think the PCB might have been damaged.

source: Stack Exchange

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

sort: votes


text:
Message is sent multiple times from one arduino to another, using nRF24L01
I am trying to build a bidirectional communication channel, using nRF24L01 and two arduinos. The message is introduced using a button (but) in Morse code, decoded and then sent when another button (but_send) is pressed.
Although everything seems to work fine, the message is sent multiple times even though I added delays. I am a beginner in Arduino and I have no idea what else i could do. I even tried deleting the string right after radio.write, but it doesn't seem to work either. If anyone has an idea, please help!

These are the two codes. They are quite similar, but i added them both just in case:
#include <LiquidCrystal.h>
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
struct record
{
  char mesaj[10];
  boolean state = 1;
};

typedef struct record Record;
Record  button_state, button_state1 ;
RF24 radio(9, 10); // CE, CSN(pini nrf01)
const byte addresses [][6] = {"00001", "00002"};  //Setting the two addresses. One for transmitting and one for receiving
String code = "";
int len = 0;
char ch;
int ok;
char new_char;
int i1 = 0;
int i2 = 1;
const int but_send = 8;
const int but = 5;
const int led = 4;
const int del = 3;
String a = "";
unsigned long pres_len = 0, rel_time, pres_time = 0, old_time_len = 0, old_pres = 0, space = 0;
int state = 0;
int unit_delay = 250;
int min_delay = 10;
int buttonState = 0;

char MakeString()
{
  if (pres_len < (unit_delay * 3) && pres_len > 50)
  {
    return '.';                        //if button press less than 0.6sec, it is a dot
  }
  else if (pres_len > (unit_delay * 3))
  {
    return '-';                        //if button press more than 0.6sec, it is a dash
  }
}

void Morse_decod()
{
  static String morse[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
                           "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
                           ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "!"
                          };
  int i = 0;
  while (morse[i] != "!")
  {
    if (morse[i] == code)
    {
      Serial.print(char('A' + i));
      a = a + char('A' + i);
      Serial.print(" ");
  }
  if (morse[i] == "!")
  {
    Serial.println("");
    Serial.println("This code is not exist!");
  }

  code = "";
}
void sendText()
{
  // Aici trebuie sa fe codul pentru trimiterea efectiva a msj
  if (ok == 1) {
    Serial.println("Lavinia:" + a);
  }
  ok = 0;

  delay(100);
}
void setup() {
  Serial.begin(9600);
  pinMode(but, INPUT_PULLUP);
  pinMode(but_send, INPUT_PULLUP);
  pinMode(del, INPUT_PULLUP);

  pinMode(led, OUTPUT);
  radio.begin();                           //Starting the radio communication
  radio.openWritingPipe(addresses[0]);     //Setting the address at which we will send the data
  radio.openReadingPipe(1, addresses[1]);  //Setting the address at which we will receive the data
  radio.setPALevel(RF24_PA_MIN); //You can set it as minimum or maximum depending on the distance between the transmitter and receiver.

}
void loop() {

label:
  while (digitalRead(but) == HIGH) {
    delay(5);
    radio.startListening();

    if (radio.available())                     //Looking for incoming data
    {
      radio.read(&button_state, sizeof(button_state));
      if (button_state.state == 0)
      {

        ok = 1;
        sendText();
        String final = "";

        for (int i = 0; i < strlen(button_state.mesaj); i++)
        {
          final += String(button_state.mesaj[i]);
        }
        ok = 1;
        Serial.println("Iulia: " + final);
        button_state.state = 1;
        radio.stopListening();
      }
      else
      {
        //nu se intampla nimic daca eu nu am trimis mesaj

      }
      delay(5);

      radio.stopListening();                           //This sets the module as transmitter
      button_state1.state = digitalRead(but_send);
      int n = a.length();
      char char_array[n + 1];
      strcpy(char_array, a.c_str());
      strcpy(button_state1.mesaj, char_array);
      radio.write(&button_state1, sizeof(button_state1));   //Sending the data
    }

    if (digitalRead(del) == LOW && a[0] != '\0' ) {
      Serial.println("Deleted string");
      a = "\0";
      Serial.println(a);
    }

  }
  old_pres = rel_time;
  pres_time = millis();
  digitalWrite(led, HIGH);
  while (digitalRead(but) == LOW) {}
  rel_time = millis();
  digitalWrite(led, LOW);
  pres_len = rel_time - pres_time;
  space = pres_time - old_pres;
  if (pres_len > min_delay)
  {
    code += MakeString();
  }
  while ((millis() - rel_time) < (unit_delay * 3))
  {
    if (digitalRead(but) == LOW)
    {
      goto label;
    }

  }

  Morse_decod();
  delay(1000);

}

#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10); // CE, CSN(pini nrf01)
#include <LiquidCrystal.h>
struct record
{
  char mesaj[10];
  boolean state = 1;
};

typedef struct record Record;
const byte addresses [][6] = {"00001", "00002"};  //Setting the two addresses. One for transmitting and one for receiving
String code = "";
int len = 0;
char ch;
int ok;
int ok2;
char new_char;
int i1 = 0;
int i2 = 1;
const int but_send = 8;
const int but = 5;
const int led = 4;
const int del = 3;
String a = "";
unsigned long pres_len = 0, rel_time, pres_time = 0, old_time_len = 0, old_pres = 0, space = 0;
int state = 0;
int unit_delay = 250;
int min_delay = 10;
Record  button_state, button_state1 ;

char MakeString()
{
  if (pres_len < (unit_delay * 3) && pres_len > 50)
  {
    return '.';                        //if button press less than 0.6sec, it is a dot
  }
  else if (pres_len > (unit_delay * 3))
  {
    return '-';                        //if button press more than 0.6sec, it is a dash
  }
}

void Morse_decod()
{
  static String morse[] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....",
                           "..", ".---", "-.-", ".-..", "--", "-.", "---", ".--.", "--.-",
                           ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--..", "!"
                          };
  int i = 0;
  while (morse[i] != "!")
  {
    if (morse[i] == code)
    {
      Serial.print(char('A' + i));
      a = a + char('A' + i);
      Serial.print(" ");
  }
  if (morse[i] == "!")
  {
    Serial.println("");
    Serial.println("This code is not exist!");
  }

  code = "";
}
void sendText()
{
  // Aici trebuie sa fe codul pentru trimiterea efectiva a msj
  if (ok == 1) {
    Serial.println("Iulia:" + a);
  }
  ok = 0;

  delay(100);
}
void setup() {
  Serial.begin(9600);
  pinMode(but, INPUT_PULLUP);
  pinMode(but_send, INPUT_PULLUP);
  pinMode(del, INPUT_PULLUP);

  pinMode(led, OUTPUT);
  radio.begin();                           //Starting the radio communication
  radio.openWritingPipe(addresses[1]);     //Setting the address at which we will send the data
  radio.openReadingPipe(1, addresses[0]);  //Setting the address at which we will receive the data
  radio.setPALevel(RF24_PA_MIN); //You can set it as minimum or maximum depending on the distance between the transmitter and receiver.

}
void loop() {
label:
  while (digitalRead(but) == HIGH) {

    delay(5);
    radio.stopListening();                             //This sets the module as transmitter
    button_state.state = digitalRead(but_send);

    int n = a.length();
    char char_array[n + 1];
    strcpy(char_array, a.c_str());
    strcpy(button_state.mesaj, char_array);
    radio.write(&button_state, sizeof(button_state));  //Sending the data
    delay(5);

    radio.startListening();                            //This sets the module as receiver
    if (radio.available())
    {
      radio.read(&button_state1, sizeof(button_state1)); //Reading the data
      String final = "";
      if (button_state1.state == 0)      {
        ok = 1;

        sendText();
        for (int i = 0; i < strlen(button_state1.mesaj); i++)
        {
          final += String(button_state1.mesaj[i]);
        }
        Serial.println("Lavinia: " + final);
        button_state1.state = 1;
      }

    }

    if (digitalRead(del) == LOW && a[0] != '\0' ) {
      Serial.println("Deleted string");
      a = "\0";
      Serial.println(a);
    }

  }
  old_pres = rel_time;
  pres_time = millis();
  digitalWrite(led, HIGH);
  while (digitalRead(but) == LOW) {}
  rel_time = millis();
  digitalWrite(led, LOW);
  pres_len = rel_time - pres_time;
  space = pres_time - old_pres;
  if (pres_len > min_delay)
  {
    code += MakeString();
  }
  while ((millis() - rel_time) < (unit_delay * 3))
  {

    if (digitalRead(but) == LOW)
    {
      goto label;

    }

  }

  Morse_decod();
  delay(1000);

}

I believe the relevant part would be:
    int n = a.length();
    char char_array[n + 1];
    strcpy(char_array, a.c_str());
    strcpy(button_state.mesaj, char_array);
    radio.write(&button_state, sizeof(button_state));  //Sending the data
    delay(5);

where a is the message to be sent.

Try creating a new, simple project that sends a number from 1 arduino to the other. If you send it from the setup() function, it should only be sent once. If you get that working, try creating a simple program that sends a "1" when a button is pressed and a "0" if the button is released. When that works, build your morse project from that. It's easier to debug short, simple programs and make one bit work at a time.

@jkp Hi there. Thanks for answering this! I have tried doing this, as i started from a simple project which worked. But since i added more functionalities, it seems like something goes wrong somewhere. Do you have any general idea what could be wrong in the code, perhaps the delays?

(Too few characters in comments, so writing as answer instead)
It's a bit hard to figure out without having the setup here and I don't think I have any of the radio modules in my box.
What I think is happening is this.
It seems like the first code will not send anything unless it receives a message from the second code, because the radio.write is inside the radio.available if-block. But when it receives a message, the message to send back must be present, so you start by entering a message on Arduino1.
Then you enter a message on Arduino2. You press the button, it skips the while loop below the label. When you release the button, it will enter the while loop and send the message. For both versions, the message will be sent as soon as 'but' is released. but_send is copied to the record that is sent, but the sending does not depend on the state of this button. You need an if statement that checks but_send to do this. The effect is, that you can only send '.' or '-' because the message is sent right away, before you get to enter more dots or dashes.
Anyways, the message from Arduino2 is received by Arduino1. If the state field of the message is 1, the message is written to Serial. Then the message from Arduino1 is send to Arduino2. Since we are not pressing any buttons, the message from Arduino 2 is send again and again and again. The state field will be 0, because but_send is not pressed, but the message is sent anyway. This triggers a new send on Arduino 1, because it receives something from Arduino 2 and gets into the radio.available part.
It seems like the messages will bounce back and forth. The only reason you don't see your Serial console filled with letters is that state is 0 for most of the messages, because you release btn_send. But as long as you hold down btn_send, it will set state=1 and print the message at the receiving end.
To prevent this, you should not call radio.write unless btn_send is released. That is going from LOW to HIGH. To test this, have a variable called old_btn_send and do something like this:
Initialize old_btn_send to HIGH in setup()
if (old_btn_send == LOW && digitalRead(btn_send) == HIGH {
    [do the sending thing]
}
old_btn_send = digitalRead(btn_send);

That is, you press btn_send. We will not enter the if block, but old_btn_send will be LOW. When you release, the condition will be true, but only once, because old_btn_send will be HIGH after the if block.
Please note, that what I write is from reading the code and not doing any testing, so I might be completely wrong :)

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


text:
How do I wire a ground rail to a VEROboard?
I’m looking to move my project from a breadboard to a vero board. However, I’m not sure how to go about soldering in my ground and power connections as the veroboard doesn't seem to have dedicated ground and power rails like the breadboard.
I’ve also attached a photo of my schematic in its current state.
Also, I’m using an Arduino Nano Board as opposed to the UNO featured in the schematic. (I’ve just used it as a placeholder as I could find a component for the nano.
Any help would be greatly appreciated.

Here’s a photo of the type of veroboard I have:

A minor correction in terminology: Your board - one with no interconnections - is usually known as perf-board. Veroboard, aka strip board, has holes already connected in rows. Thus it's easy to assign power, ground, and signal rails, and with a layout that takes good advantage of the strips, it requires fewer hand-wired connections.

Ahh got it - thanks!

sometimes i solder a striped 20AWG solid wire along the edge for an ad-hoc easily solder-able ground rail.

Ahh good shout @dandavis

There's nothing special about ground. It's just a wire like any other.
You could designate a row of holes as ground then link them all together, but you don't need to. Just wire your grounds together as you would any other connection.

Ahh fair enough! So does this also apply to power?

Yep. Everything is just wires.

Makes sense! Thanks for your help!


text:
Serial communication between Arduinos
I'm trying to send data from Arduino Mega to UNO.
The master code sends characters 'x' and 'a' every half second to the slave Arduino UNO.
Slave receives the characters and switches the state of the onboard LED.
Here I'm trying to print some text in the beginning of the loop and the characters received.
Instead of the letters it is printing numbers as given below.
Why this line Serial.println('Soft serial avaialble') prints numbers?
How to print real text received from the master?
> 27749
> 97
> 27749
> 120
> 27749

Master code:
// Include the Software Serial library
#include <SoftwareSerial.h>
// Define a Software Serial object and the used pins
SoftwareSerial softSerial(8, 9);  // RX, TX
void setup()  {
    Serial.begin(9600);
    softSerial.begin(9600);
}
void loop()  {
    // Sends characters 'x' and 'a' every half second.
    if (Serial.available())  {
        softSerial.write('x');
        delay(500);
        digitalWrite(LED, LOW);
        delay(500);
    }
}

Slave code:
// Include the Software Serial library
#include <SoftwareSerial.h>
// Define a Software Serial object and the used pins
SoftwareSerial softSerial(8, 9);
// LED Pin
int LED = 13;

void setup()  {
    softSerial.begin(9600);
    Serial.begin(9600);
    pinMode(LED, OUTPUT);

}
void loop()  {
    Serial.println('Soft serial avaialble');
    if (softSerial.available())  {
        int com = softSerial.read();
        if (com == 'x')  {
            Serial.println(com);
            digitalWrite(LED, LOW);
        } else if (com == 'a'){
            Serial.println(com);
            digitalWrite(LED, HIGH);
        }
    }
}

In your slave, you've declared com as an int, so Serial.println() interprets it that way. If you want to keep it as int except for printing, cast Serial.println()'s argument to char:
Serial.println((char)com);

Thanks. It works!

In addition to JRobert's remark, note that strings in C++ are delimited by double quotes, thus:
Serial.println("Soft serial avaialble");

Thanks a lot. I wasn't aware of that.

Good catch, @EdgarBonet - I missed that one.


text:
Using arduino mega is making my cnc claw buggy. Help
I have three nema 23 steppers with one 8 channel relay(all the pins used) powering two dc motors and 4 IR sensors for feedback on the machine.
The problem is my machine is working fine for only 2 to 3 minutes until it just resets itself in the middle of the routine and crashes my whole system.
I am using 1/2 step microstepping with TB6600 stepper driver.
Also my arduino is mega 2560, maybe thats the problem I don't know about.

Here I am attaching the code
const int dirPin1=2;
const int stepPin1=3;
const int dirPin2=4;
const int stepPin2=5;
const int dirPin3=6;
const int stepPin3=7;
int del=1;
void setup() {
 pinMode(2,OUTPUT);
 pinMode(3,OUTPUT);
 pinMode(4,OUTPUT);
 pinMode(5,OUTPUT);
 pinMode(6,OUTPUT);
 pinMode(7,OUTPUT);
 pinMode(8,OUTPUT);
pinMode(9,OUTPUT);
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
pinMode(14,OUTPUT);
pinMode(15,OUTPUT);
pinMode(16,INPUT);
pinMode(17,INPUT);
pinMode(18,INPUT);
pinMode(19,INPUT);
digitalWrite(8,HIGH);
digitalWrite(9,HIGH);
digitalWrite(10,HIGH);
digitalWrite(11,HIGH);
digitalWrite(12,HIGH);
digitalWrite(13,HIGH);
digitalWrite(14,HIGH);
digitalWrite(15,HIGH);

}
void picker_up(){
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,LOW);
  digitalWrite(11,LOW);
  delay(570);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(11,HIGH);
  delay(100);
}
void picker_down(){
  digitalWrite(8,LOW);
  digitalWrite(8,LOW);
  digitalWrite(10,HIGH);
  digitalWrite(11,HIGH);
  delay(320);
  digitalWrite(8,HIGH);
  digitalWrite(9,HIGH);
  digitalWrite(10,HIGH);
  digitalWrite(11,HIGH);
  delay(100);
}
void claw_close(){
  digitalWrite(12,LOW);
  digitalWrite(13,LOW);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  delay(100);
  digitalWrite(12,HIGH);
  digitalWrite(13,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  delay(100);
}
void claw_open(){
  digitalWrite(12,HIGH);
  digitalWrite(13,HIGH);
  digitalWrite(14,LOW);
  digitalWrite(15,LOW);
  delay(100);
  digitalWrite(12,HIGH);
  digitalWrite(13,HIGH);
  digitalWrite(14,HIGH);
  digitalWrite(15,HIGH);
  delay(100);
}

void loop() {
  // put your main code here, to run repeatedly:
digitalWrite(dirPin1,HIGH);
digitalWrite(dirPin2,HIGH);
digitalWrite(dirPin3,LOW);
for(int i=0;i<=1200;i++){
  digitalWrite(stepPin1,HIGH);
  digitalWrite(stepPin2,HIGH);
  digitalWrite(stepPin3,HIGH);
  delay(del);
  digitalWrite(stepPin1,LOW);
  digitalWrite(stepPin2,LOW);
  digitalWrite(stepPin3,LOW);
  delay(del);
}
for(int i=1;i<=400;i++){
  digitalWrite(stepPin1,HIGH);
  delay(del);
  digitalWrite(stepPin1,LOW);
  delay(del);
}
delay(1000);
picker_down();
claw_open();
claw_close();
picker_up();
delay(2000);
digitalWrite(dirPin1,LOW);
digitalWrite(dirPin2,LOW);
digitalWrite(dirPin3,HIGH);
for(int i=1;i<=400;i++){
  digitalWrite(stepPin1,HIGH);
  delay(del);
  digitalWrite(stepPin1,LOW);
  delay(del);
}
for(int i=0;i<=1200;i++){
  digitalWrite(stepPin1,HIGH);
  digitalWrite(stepPin2,HIGH);
  digitalWrite(stepPin3,HIGH);
  delay(del);
  digitalWrite(stepPin1,LOW);
  digitalWrite(stepPin2,LOW);
  digitalWrite(stepPin3,LOW);
  delay(del);
}
delay(2000);
}

I am not getting why this is happening. Or do I need some more electronic components  included in the machine and I know I could have used mosfets to control the motors but I am just way too lazy.
I used uno before this and it used to work fine, so should I just go back to using it?
Also I have modified the code to be compatible with the uno again so please bare with the pin numbers.

I don't believe there's any reasonable way to answer the question with the information provided. It could be literally anything. I would not recommend doing stepper driving "by hand" when there are libraries available. At the very least you'd need to include a schematic.

I'm going out on a limb here with no schematic, but a common reason for resetting is low voltage caused by too much current draw. "I know I could have used mosfets to control the motors but I am just way to lazy." suggests a possible cause. Are your motors powered through the Arduino?

I am using external power sources for everything even the relay is not powered by the arduino mega

add some debugging code

Still not much to go on (this is a block diagram, not a schematic). Since there's essentially no code other than digital writes, I would suspect an electrical problem.

I actually thought of using a stepper motor library but the library accelstepper blocks every other actuator to make the stepper rotate which means my two motors that are running together will not work.
@DaveNewton

Non AccelStepper is not blocking. You just have to use it right by setting the target position and then execute the run function of the corresponding accelstepper objects very regularily and fast, so that they don't miss a step. Actually the library is meant for that. It also has a blocking function, but more for completeness and special situations. The non-blocking way is actually the intended way of use

I actually kind of figured out the problem on my own till now and it is related to using the relay to power my motors as arduino is not able to handle the relay switching so I am using a slave arduino to not mess up the the system.

If you solved the problem ypu can write an answer to your own question. That way your oearninga might help others in the future

Ok so first of all I ditched the 12 volt and 5 volt motor(this one was a hacked tower pro servo) and used two pneumatic cylinders as I happen to have compression engines in my firm to make the actuator. While now its more rugged but better. I also had solved the problem I asked about, this was done by using a slave arduino nano so I just made the use of serial communication to fire the relay subroutine onto the nano this way even if my relay throw some errors nothing would go wrong with my system. Also another mistake I did was power up the relay and motor together.


text:
Global array doesn't get assigned the space it would take up in memory
I have this sketch:
const uint32_t len = 65536;
uint8_t arr[len];

void setup() {}

void loop() {}

The length of the array should fit into the dynamic memory. However, when I compile the sketch it says this in the output window:
Sketch uses 10528 bytes (0%) of program storage space. Maximum is 2031616 bytes.
Global variables use 13504 bytes (1%) of dynamic memory, leaving 1034224 bytes for local variables. Maximum is 1048576 bytes.

If I change len to 10, that doesn't change. The compiler is set to "Debug", so it should not get optimized away. This indicates, that the memory isn't actually being allocated. What seems to be the problem here?
I am compiling for the Teensy 4.0, but the output is the same in essence for the Arduino Uno and other boards (with lower memory sizes).

How are you compiling it? If you're not actually using the array it may just be optimized away.

My guess would be this is due to not putting any data in it.

There is no problem here. Only the compiler is a bit smarter than you anticipated. It sees, that you are not using arr anywhere, so it just optimizes it out.
There are two ways to prevent that, if you really want to:

I think you can use flags to tell the compiler, that this shouldn't be optimized out. I'm no expert in this, others might know more about this and add their own answer
You can just start using it.

That is a good point, however I had already thought of that. See the updated question.

Nevermind, apparently this setting still leads to the compiler optimizing it away. Once there is a line that writes data to the array, the proper memory usage for global variables gets displayed.

The only thing that remains after this is that malloc() doesn't seem to work this way.

@LukasFun Correct--malloc does precisely what it's supposed to, allocate the memory, at the time it's called. Whether or not that memory is used is irrelevant.


text:
Send packet of multiple sensors data to Bluetooth module
In my project I am using 3 sensors. I am sending a regular stream of sensors data to Bluetooth module  but now I want to send data in form of packet (which may be 30 bytes or 40 bytes of size) in which first 10 bytes contain the first sensor data while next 10 bytes contain second sensor data and so on. But problem here is I am not finding something relevant to my approach. Can any one suggest me some link or some way to do this.
Thanks in advance.

https://en.wikipedia.org/wiki/Struct_(C_programming_language)

It is unclear to me, what the actual problem is here. For imposing a packet protocol onto the serial stream for binary data you normally just send a start byte (or start byte sequence), which you defined, then send the length of the packet and then the data. Not much more to it. Is that, what you are asking for?

Yes i want this. Can you please help me how to do this using arduino IDE software?

There are many ways to transmit binary data over a byte-stream based interface like Serial (which is used by common bluetooth modules like the HC-05/HC-06). I will only describe one here.
First we need to define a start byte, which marks the start of a new packet. That can be any arbitrary value, for example 0xFF. It is also possible to use a specific byte sequence as start marker. This start byte/sequence is what we send first when transmitting a packet.
Then we want to transmit the size of the following data. With small to normal packet sizes a single byte is enough here (giving room for up to 255 bytes).
Sometimes you might want to compute a CRC hash value to check for data corruption. That could also be send here. But unless you have a system, which really is loosing/corrupting data, you don't need it. I suggest you first try it without and check, if corrupted data is really a thing for your setup.
And then we are sending the actual data. How exactly you are doing this depends on how the data is stored in your code. Though you will use Serial.write() in some way. If you want a more specific answer in this regard, you need to include your code, so that we can see how you are storing your sensor data.
On the receiving side you would then wait for the start marker, read the size byte and then read bytes until you have received as many, as the size byte said. As you have multiple sensors, you could send the sensor data of each sensor in it's own packet. The data could then be formatted like: 1 byte sensor ID, X byte sensor data.


text:
Why does Adafruit guide for motors use transistors on ground rather than modulating the power source
I'm going through the Adafruit Motors guide for Arduino, found here, and I'm struggling to understand how each of these parts play in. From what I understood, pulse width modulation is basically a way to send varying levels of power through a digital output source. Additionally, it seems that the guide is using a transistor with the PWM signal as the gate, so it can allow the percentage given by the PWM signal to control how much flow is given to the motor. However, what I'm confused here is that both the power and ground are interfacing with this transistor/diode setup.
This is more specifically what I mean, on the bottom seems really simple: the PWM signal comes on the yellow wire, fed through the resistor so that it doesn't fry the transistor into the gate.
After this though, there's a ground signal being passed into the source leg of the transistor, and the sink leg is connected to both a diode for power AND the ground of the motor? I might be misunderstanding how a diode works but this doesn't seem to make sense as to why the ground signal is being modulated.

My initial thought for this would be a system where only the power of the motor is varied by the PWM signal, sorta like in this way (apologies for the terrible drawing style, I haven't gotten used to some of the Arduino sketching software online):

I've not gotten to try this yet, but I assume it wouldn't work or would destroy components somehow since this does seem to be a simpler solution, and it's not being used. I was sorta trying to figure out 1) why my solution would be bad and 2) how the official solution works, as they haven't really given any actual schematic (not that I would understand it, haha) Any help would be appreciated! Thanks!

Tip: the blue line "going up" that you marked GND, is not really GND but one of the motor connections. The motor is connected between 5V and the diode's Anode (and the transistor's collector). You can use the integrated schematic editor to make a clearer drawing.

There's a schematic on the transistor page.

do keep in mind that electrons flow from negative to positive, so it does modulate the source of power as shown.

I think your confusion does indeed stem from the diode. You can forget the diode, it doesn't feature in the switching of the motor. When a motor runs it can generate large negative voltages caused by the repeatedly collapsing magnetic field. The diode, which is connected backwards, exists to take those negative voltages and prevent them damaging the rest of the circuit.
The transistor arrangement in use is called common emitter, and is also known as a low-side switch when used in saaturation between the load and GND, as in this situation.  It doesn't matter to the motor if you have the switch between the motor and GND (using an N-channel MOSFET or NPN bipolar transistor) or between power and the motor (using a P-channel MOSFET or PNP bipolar transistor), but it does matter to the Arduino.
It is harder to switch a "high side switch" from an Arduino, especially if your power supply is higher than the voltage the Arduino runs at. Since the switching is controlled by the difference in voltage between the "common" point (emitter [BJT] / source [MOSFET]) and the switching signal (Arduino), which is limited to 5V, any "common" point voltage that is higher than that is unreachable by the switching signal, so ends up in being always on and the switching fails.
It is possible to switch the high side, but you need an extra driving stage to allow the higher voltage switching.
For this specific circuit where the power is 5V it's not as susceptible to the problem, but this is a rare case. Normally you will be driving motors at a higher voltage, such as 12V, and there you will need an extra driving stage, or just use the far simpler low-side switch arrangement this circuit teaches you.

this makes a lot of sense but I had one question regarding that flyback diode, does it matter whether the end of it feeds back into the pulse-modulated ground or could I feed it back into a normal ground wire?

@Daneolog Not sure what you mean there--it needs to be explicitly across the motor since it's the motor generating the negative voltage.

Its purpose is to form a circuit between the two pins of the motor in reverse.

oh yeah no I meant like, the other side of it, that's pointing at the same line as the transistor's output, is pointing to a modulated ground

oh, I see, so it's not just a means of emptying out all the negative energy into a ground, it's feeding it back in

@Daneolog I think you're under the impression that "ground" is something special. It's not. It's just a wire in the circuit. There's no "modulated ground", only a switch in series with the motor.

but the thing about that is that there's definitely a difference in signal between the ground that comes directly from the Arduino and the output of the transistor, that's what I'm referring to as some kind of modulated signal

"ground" is nohing more than an arbitrary point in the circuit against which other volatges are refereced.

do you mind if I talked about this in chat for a bit? I'm still a bit confused as to how this diode works as it relates to both ground and power

Let us continue this discussion in chat.

Your schematic
The blue line in your first schematic "going up" that you marked GND, is not really GND but one of the motor connections. If you look at the Adafruit schematic you can see this.
The motor in the Adafruit schematic in the link you provided is connected between 5V and the diode's Anode (and the transistor's collector).
Flyback diode
The diode is a so-called "flyback diode", connected between the motor connections to "soak up" back-EMF that occurs when the motor is turned off and its magnetic field collapses. If the diode would not be there, there would be a voltage spike on the transistor's collector, possibly damaging it.
Low-side switching
The "Adafruit" solution uses an NPN transistor as a switch on the low side of the motor when the I/O pin is high, like the schematic on the right. This is a very common setup as it has almost no disadvantages.
High-side switching
Your own suggestion (called high-side switching, shown on the right) would work as well (with the addition of a flyback diode) but it would need a different type of transistor, a PNP transistor. Also, the I/O inputs would work in an inverted way: when the I/O pin is low, the motor will be on and when the I/O pin is high, it will be off.
Note that high-side switching will only work when the supply voltage is lower or equal to the voltage that's on the I/O pins. You can't turn on a 12V motor this way, for example. With low side switching, you will not have this problem and you can switch higher voltages.

simulate this circuit – Schematic created using CircuitLab

ohhh, I see. so basically motors can run both ways, if you block ground by a specific amount, it would block movement by that amount in the same way you blocked power by that amount, but the method of blocking ground is easier because it allows you to have the same setup for any size motor, just having a power source strong enough for the motor. that makes lots of sense! thank you so much!


text:
How to combine Read/Write Data Code for RFID tag?
I have the two example codes from MFRC522 Library and I want to combine them together so I can at first read the data from the tag and then write something new on it by using the serial input. I´ve already tried but I cant figure out why it doesnt work. While it waits for an input to write on the chip the Serial Monitor shows: "PCD_Authenticate() failed: Timeout in communication".
This is the code for read data:
* Initial Author: ryand1011 (https://github.com/ryand1011)
 *
 * Reads data written by a program such as "rfid_write_personal_data.ino"
 *
 * See: https://github.com/miguelbalboa/rfid/tree/master/examples/rfid_write_personal_data
 *
 * Uses MIFARE RFID card using RFID-RC522 reader
 * Uses MFRC522 - Library
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
*/

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

//*****************************************************************************************//
void setup() {
  Serial.begin(9600);                                           // Initialize serial communications with the PC
  SPI.begin();                                                  // Init SPI bus
  mfrc522.PCD_Init();                                              // Init MFRC522 card
  Serial.println(F("Read personal data on a MIFARE PICC:"));    //shows in serial that it is ready to read
}

//*****************************************************************************************//
void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  //some variables we need
  byte block;
  byte len;
  MFRC522::StatusCode status;

  //-------------------------------------------

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  Serial.println(F("**Card Detected:**"));

  //-------------------------------------------

  mfrc522.PICC_DumpDetailsToSerial(&(mfrc522.uid)); //dump some details about the card

  //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));      //uncomment this to see all blocks in hex

  //-------------------------------------------

  Serial.print(F("Name: "));

  byte buffer1[18];

  block = 4;
  len = 18;

  //------------------------------------------- GET FIRST NAME
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 4, &key, &(mfrc522.uid)); //line 834 of MFRC522.cpp file
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer1, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT FIRST NAME
  for (uint8_t i = 0; i < 16; i++)
  {
    if (buffer1[i] != 32)
    {
      Serial.write(buffer1[i]);
    }
  }
  Serial.print(" ");

  //---------------------------------------- GET LAST NAME

  byte buffer2[18];
  block = 1;

  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, 1, &key, &(mfrc522.uid)); //line 834
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Authentication failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  status = mfrc522.MIFARE_Read(block, buffer2, &len);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("Reading failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  //PRINT LAST NAME
  for (uint8_t i = 0; i < 16; i++) {
    Serial.write(buffer2[i] );
  }

  //----------------------------------------

  Serial.println(F("\n**End Reading**\n"));

  delay(1000); //change value if you want to read cards faster

  mfrc522.PICC_HaltA();
  mfrc522.PCD_StopCrypto1();
}
//*****************************************************************************************//

and for writing data:
/*
 * Write personal data of a MIFARE RFID card using a RFID-RC522 reader
 * Uses MFRC522 - Library to use ARDUINO RFID MODULE KIT 13.56 MHZ WITH TAGS SPI W AND R BY COOQROBOT.
 * -----------------------------------------------------------------------------------------
 *             MFRC522      Arduino       Arduino   Arduino    Arduino          Arduino
 *             Reader/PCD   Uno/101       Mega      Nano v3    Leonardo/Micro   Pro Micro
 * Signal      Pin          Pin           Pin       Pin        Pin              Pin
 * -----------------------------------------------------------------------------------------
 * RST/Reset   RST          9             5         D9         RESET/ICSP-5     RST
 * SPI SS      SDA(SS)      10            53        D10        10               10
 * SPI MOSI    MOSI         11 / ICSP-4   51        D11        ICSP-4           16
 * SPI MISO    MISO         12 / ICSP-1   50        D12        ICSP-1           14
 * SPI SCK     SCK          13 / ICSP-3   52        D13        ICSP-3           15
 *
 * Hardware required:
 * Arduino
 * PCD (Proximity Coupling Device): NXP MFRC522 Contactless Reader IC
 * PICC (Proximity Integrated Circuit Card): A card or tag using the ISO 14443A interface, eg Mifare or NTAG203.
 * The reader can be found on eBay for around 5 dollars. Search for "mf-rc522" on ebay.com.
 */

#include <SPI.h>
#include <MFRC522.h>

#define RST_PIN         9           // Configurable, see typical pin layout above
#define SS_PIN          10          // Configurable, see typical pin layout above

MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance

void setup() {
  Serial.begin(9600);        // Initialize serial communications with the PC
  SPI.begin();               // Init SPI bus
  mfrc522.PCD_Init();        // Init MFRC522 card
  Serial.println(F("Write personal data on a MIFARE PICC "));
}

void loop() {

  // Prepare key - all keys are set to FFFFFFFFFFFFh at chip delivery from the factory.
  MFRC522::MIFARE_Key key;
  for (byte i = 0; i < 6; i++) key.keyByte[i] = 0xFF;

  // Reset the loop if no new card present on the sensor/reader. This saves the entire process when idle.
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
    return;
  }

  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial()) {
    return;
  }

  Serial.print(F("Card UID:"));    //Dump UID
  for (byte i = 0; i < mfrc522.uid.size; i++) {
    Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
    Serial.print(mfrc522.uid.uidByte[i], HEX);
  }
  Serial.print(F(" PICC type: "));   // Dump PICC type
  MFRC522::PICC_Type piccType = mfrc522.PICC_GetType(mfrc522.uid.sak);
  Serial.println(mfrc522.PICC_GetTypeName(piccType));

  byte buffer[34];
  byte block;
  MFRC522::StatusCode status;
  byte len;

  Serial.setTimeout(20000L) ;     // wait until 20 seconds for input from serial
  // Ask personal data: Family name
  Serial.println(F("Type Family name, ending with #"));
  len = Serial.readBytesUntil('#', (char *) buffer, 30) ; // read family name from serial
  for (byte i = len; i < 30; i++) buffer[i] = ' ';     // pad with spaces

  block = 1;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("PCD_Authenticate() success: "));

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  block = 2;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write block
  status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  // Ask personal data: First name
  Serial.println(F("Type First name, ending with #"));
  len = Serial.readBytesUntil('#', (char *) buffer, 20) ; // read first name from serial
  for (byte i = len; i < 20; i++) buffer[i] = ' ';     // pad with spaces

  block = 4;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write block
  status = mfrc522.MIFARE_Write(block, buffer, 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  block = 5;
  //Serial.println(F("Authenticating using key A..."));
  status = mfrc522.PCD_Authenticate(MFRC522::PICC_CMD_MF_AUTH_KEY_A, block, &key, &(mfrc522.uid));
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("PCD_Authenticate() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }

  // Write block
  status = mfrc522.MIFARE_Write(block, &buffer[16], 16);
  if (status != MFRC522::STATUS_OK) {
    Serial.print(F("MIFARE_Write() failed: "));
    Serial.println(mfrc522.GetStatusCodeName(status));
    return;
  }
  else Serial.println(F("MIFARE_Write() success: "));

  Serial.println(" ");
  mfrc522.PICC_HaltA(); // Halt PICC
  mfrc522.PCD_StopCrypto1();  // Stop encryption on PCD

}


text:
First Arduino Project - Need Advice (powering WS2812B LEDs)
I'm making a long LED display made up of 3 (8x32) LED matrices to go inside of a car. I can't seem to find any in-depth guides on this sort of thing. If anybody has examples that they would like to share please do!
The major issue I'm having is power. I'm extremely new to electronics, and I don't understand how these lights can be powered separately, and still be addressably lit by the Arduino?
Parts:
3* LED matrices (8x32)
https://www.amazon.com/gp/product/B088BTXHRG/ref=ppx_yo_dt_b_asin_title_o01_s00?ie=UTF8&psc=1
1* Mega 2560
Here's the mock-up schema:

I forgot to draw in a switch, and a power line leading to the Arduino. But let's assume there will be a switch before the resistor and a line that feeds power to the MEGA 2560.
What in this schematic doesn't look or sound right?
Thank you all in advance for your help. This is probably not at all how to go about building circuits, and I'm trying my best to learn. All advice is wanted!

In addition to the answer, you might want to read https://learn.adafruit.com/adafruit-neopixel-uberguide?view=all#powering-neopixels and https://learn.adafruit.com/sipping-power-with-neopixels. It's not shown in your diagram but keep in mind that the Arduino and power supply/ies need to share a ground as well.

you should get 12v LEDs instead of 5.

Powering the LED panels
Powering your panels will be your greatest challenge!
These LED panels are powered by a single +5V power input per panel and do not need a resistor in the power supply path (they actually need a very low resitance path). You do need a good quality +12V DC -> +5V DC power supply (or multiple, as explained below).
Since 3 x 256 RGB LEDs require a large amount of power when they're all lighted at the same time (something like 60mA * 768 =~ 46A), the power supply should be able to accomodate that. It might be better to use three individual, smaller (~15A) power supplies. You could opt for power supplies smaller than 15A, but you should ensure that all LEDs will never light up at full intensity at the same time.
For supplying power from a 12V car battery, you could use high quality 12V DC to 5V DC buck converters (they're efficient). Use good quality cable with a diameter large enough for transporting the large currents necessary. If you need connections in the path of the power supply, make sure they are good quality as well. To reduce losses in long stretches of wire, you should place the buck converter(s) near the LED panels.
Connecting the data lines
The color and intensity of Individual LEDs is controlled via the data input coming from your Arduino and it only needs one input to control all 768 LEDs. The first panel's "data out" should be connected to the next panel's "data in" and so on, like your drawing.
Software
I recommend you look up the FastLED library and some of its examples to get familiar with controlling large amounts of addressable RGB LEDs. There are many good examples and interesting projects out there.

I think it should be mentioned that this whole idea is very impractical for a car, all but impossible w/o great expense and expertise, and would be non-trivial even with mains power available. A cigarette lighter socket for example can only do 15A, and it will quickly overheat at that load. You alternator probably only kicks out about 50A, and your car needs some to run, so you'll likely kill the engine and drain the battery in no time even if you managed to get everything safely wired up. Use LCD displays if you need that many pixels..

@dandavis, I agree, but it is feasible, especially if not using lighter sockets (which are about the worst sockets in the world i.m.o.) but direct, fused connections and not keeping the intensity at maximum. It’s up to the asker.


text:
Error in I2C Communication Between Arduino and Raspberry Pi
The code below sends data to Raspberry Pi every 20 millisecond. The code works fine but sometimes python throws an error. Why this is happening? Should I give more time between writeData?
Error:
> Traceback (most recent call last):   File "rpi-I2C.py", line 33, in
> <module>
> writeData("360")   File "rpi-I2C.py", line 12, in writeData
> bus.write_i2c_block_data(address,0x00,byteValue) OSError: [Errno 121] Remote I/O error

Python code:
import smbus
import time
# for RPI version 1, use bus = smbus.SMBus(0)
bus = smbus.SMBus(1)

# This is the address we setup in the Arduino Program
address = 0x04

#http://www.raspberry-projects.com/pi/programming-in-python/i2c-programming-in-python/using-the-i2c-interface-2
def writeData(value):
    byteValue = StringToBytes(value)
    bus.write_i2c_block_data(address,0x00,byteValue)
    #first byte is 0=command byte.. just is.
    return -1

def StringToBytes(val):
        retVal = []
        for c in val:
                retVal.append(ord(c))
        return retVal

while True:
    print("sending test")
    writeData("left")
    time.sleep(0.02)

    #print('Sending OPEN-00-00');
    writeData("right")
    time.sleep(0.02)

    #print('Sending WIN-12-200');
    writeData("360")
    time.sleep(0.02)

Arduino code:
#include <Wire.h>
#define SLAVE_ADDRESS 0x04

volatile boolean receiveFlag = false;
char temp[32];
String command;

void setup() {
  Wire.begin(SLAVE_ADDRESS);
  // define callbacks for i2c communication
  Wire.onReceive(receiveEvent);
  Serial.begin(115200);
  Serial.println("Ready!");
}

void loop() {
  if (receiveFlag == true) {
    Serial.println(temp);
    receiveFlag = false;
  }
}

void receiveEvent(int howMany) {
  for (int i = 0; i < howMany; i++) {
    temp[i] = Wire.read();
    temp[i + 1] = '\0';  //add null after ea. char
  }

  //RPi first byte is cmd byte so shift everything to the left 1 pos so temp contains our string
  for (int i = 0; i < howMany; ++i)
    temp[i] = temp[i + 1];
    receiveFlag = true;
  }

Slowing it down a bit would be the first thing I'd try, e.g., crank it up to .5sec. If that fixes it you'll know it's a timing issue. You could also speed up the Arduino side by temporarily removing the Serial.println because it could just be the Arduino can't keep up since it's serial-ing while the host is still blasting I2C data. (Only do one change at a time, obviously).

Changing sleep time to 0.5Sec works but I want to send data every 20ms. Is there any way to do this? What causes the problem exactly? Is Arduino reading data slower than expected?

Serial output is relatively slow.

Got it. Thanks.

Are you using an active level translator for the Arduino and the Pi. This I would expect with a passive (resistor) level translator. A simple trick is to transmit with 2 stop bits and receive with 1. This gives you a free bit time for each character.

A RPI uses 3.3v logic while an arduino uses 5v logic you can use a logic converter but by now it's probly to late and maybe your arduino or RPI is broken (Sorry!)


text:
How to get version of Arduino board remotely
I have multiple Arduino WeMos D1 boards, with a mix of versions bought months apart.  One of these boards is working but I need to update it and I am not sure if it is R1 or R2 (the pinouts are different).  I do not have physical access to it (it is 200+ miles away in an area that is locked down) but I can connect through another device over WiFi.
It has the following included:
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

#include <WiFiUdp.h>
#include <ArduinoOTA.h>

So, I can even browse to a Webserver to run commands.  How can I add to the code (or even replace it) to return a value that tells me which version the board is?  According to this you can do it with an AT command, but I am not sure how to pass an AT command from the WebServer interface (or any other way).
EDIT: I guess I may have confused the issue with my phrasing.  I can connect to the board and upload a new sketch (using OTA).  My question is, can I put something in a new sketch to determine the board details and upload it.  Once I get that, I can then put in a the actual sketch that I want.

If you upload your own sketch it replaces the AT firmware. Do you have the original code you burned to it? That would indicate (based on pin defs) which version--in hindsight, it's always a good idea to track what software goes onto which board, e.g., by MAC address or sthng.

the AT command is for AT firmware version, not for board id. the software running on esp8266 doesn't have to know the pinout of the board. io 5 is still io 5 no matter where it is on board's headers. so unless you have something special in your sketch what tells you the version of board set at compilation, there is no way to know if it is a D1 (R1) or D1 R2

@Juraj The two versions use different ESP8266 modules - 12B/E vs 12F. There may be a way (in software) to find that out.

you could replace the sketch with a new simple one that compares the boards config names to a numeric literal, ex: if(D4==2){...}. Make sure you have OTA on your test sketch. Then reflash the board with the current sketch. This is why I moved to an interpreted language on top of arduino c: you can see the code from SPIFFS in plain text, edit it from the web, and re-run, all w/o flahsing.

@dandavis Can you elaborate?  Which language?  Links?

@Majenko that sounds promising.  Perhaps that AT command or similar that I linked to? But how do I use it?

@Majenko and Chiwda, not with currently uploaded sketch. but I doubt it with any program. it is still the same esp8266 chip. you may get the serial number but I am not sure if that would help you.

I don't need to do it with the currently uploaded sketch!  I can upload a new one (as I said in my question "...or even replace it...") and then, when I have determined the correct version, put the correct sketch back on there.

I think about all you'd be able to do is exercise the board itself, e.g., is something connected to some pin, that's different on the two versions you created. Or if the code allows you to read the code that's on the board you might be able to reverse-engineer it to figure out what pins are defined as what. It's super-important to understand what code is deployed where. The easiest solution is to have somebody take a picture of it and send it to you.

dave is on the right track about reading the hex back off.  search "rip code off arduino" to find a forum post that may be relevant.  Once you have it, compare to your code's builds

There's nothing you can do with your currently loaded sketch. The board can only do exactly what you have programmed it to do and nothing more.

There are no "AT" commands. They only exist if you load the AT firmware instead of your own firmware
You can't magically make your code do things it wasn't programmed to do1

However the only real differences between the two boards is the version of the ESP8266 module in use: ESP-12E vs ESP-12F, (and the only difference between those modules is the layout of the PCB antenna in order to achieve FCC certification) and the addition of some unpopulated serial and I2C pins.
Aside from that the only other differences are purely cosmetic or of no consequence to your software.
So it really doesn't matter which board you have or which you compile your code for.

1: Unless you can cause some buffer overflow and inject new code into memory to execute, but to do that you'd need to be a l33t h4x0r.

Addendum:
It appears they have two boards, named the same, with different pin arrangements (both sadly very stupidly designed, but there you are).  All I can suggest is compile for one, install it, and see if it works. If it doesn't, then compile for the other and see if that works.
Or compile some special firmware that will probe what you have attached and work out what is attached where - then install and run that.

the problem is that on the same header pin R1 has a different io pin then R2.

@Juraj Well that's stupid of them, isn't it? TBH the pinouts of both boards are just stupid, since there are far more "pins" than the ESP8266 actually has, so the pinout is pretty much meaningless.


text:
Why would a serial device not be sending the correct start code?
I am unable to get any reading from a PMS5003 connected to an ESP32.
In trying to debug this problem, I have a very minimal setup. Only the PMS5003 is connected to the ESP32, and using the following the code.
#include <Arduino.h>
#define PMS_DEBUG
#include <PMSerial.h>

SerialPM pms(PMSx003,Serial2)

void setup() {
  Serial.begin(9600);
  Serial2.begin(9600);
  pms.init();
}

void loop() {
  pms.read();
  Serial.println(pms.pm25);
  Serial.println(pms.status);
}

pms25 always returns 0. When the PMS5003 is properly connected to the ESP32, status always returns "Wrong message start".
Why would the device be sending the wrong start code, and what steps can I take to debug this?
I have tried connecting to different serial pins, including following the ESP32 software serial example provided by the PMSerial library. In all cases, it simply looks as though the PMS5003 sensor is mot transmitting anything - indeed no fans are switching on and there is no sign of life at all from the device. However, I am very much a beginner, and don't know enough to tell whether this is a problem with the device, the library or something I have done.
Very grateful for suggestions how to debug this.
Edit
example serial data
0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0xC0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x1, 0x6D, 0x0, 0xE0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x97, 0x0, 0x0, 0x0, 0xF8,

0x0, 0x0, 0x0, 0x0, 0xA, 0x0, 0x0, 0x1, 0x0, 0xB0, 0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xF0, 0x0, 0x80, 0x0, 0x0, 0x0, 0x0, 0x0, 0xBB, 0x1, 0x0, 0x5F, 0x0,

Are you sure, that the device ia working at 9600baud?

It would be helpful if you know what library you use. I found this one https://github.com/avaldebe/PMserial. The author provides some examples. Each of these  checking the state of pms with if (pms) after read. and only use the data if this is true. So perhaps the sensor is permanently read, but need some time to generate new data. So you have to check if the data is valid.

It seems the sensor signalizes that the data is valid with sending a 0x42 as a start byte. I've found an Arduino Project, which only uses the seirial connection, no extra driver and they only use the data if this 0x42 is received. Here is the link: https://how2electronics.com/interfacing-pms5003-air-quality-sensor-arduino/

thanks @PeterPaulKiefer! pms is never true because the 0x42 start byte is never received. I've added above an example of the data I'm receiving. I have double checked all my connections. As the start byte is not received, should I assume there is a problem with the sensor? Or are there other possible causes?

thanks @chrisl, the datasheet claims a default baud rate of 9600bps. added some links above

Can you show us how you have it wired to the ESP32?

The bytes you show have many sequences of consecutive bits. Please double check your connections and baudrate. Do you happen to have an oscilloscope? If so, probe the line and check the baudrate.

Sorry for the late answer. I was not notified, perhaps because of the ! behind the Name??   Perhaps (like mentioned in other comments) the baud rate is set to a non default. If you have access to an osci you could check that. Alternatively you could try out some common baud rates. Another good approach is to add a picture of your setup and the schematics. Then you got some reviews, that's also a form of trouble shooting. There are some rules mentioned in the documentation of the sensors. Did you pay attention to those. (e.g. Do not connect RESET if it is not used.)

thanks everyone for these suggestions. apologies for slow reply, things became very busy! I managed to borrow some spare components to test my project. Turns out there was a fault with the cable I was using to attach the PMS5003 sensor. Replaced the cable, everything works. Simple fix, but quite annoyed with myself for not checking this sooner!


text:
I2S read() is which channel?
The Arduino I2S reference describes the I2S standard and functions available with the standard I2S library, (Bizarrely it doesn't reference the existing read() function which is used in the examples but that is beside the point). There also exists an ArduinoSound library, however I have the same issue with this.
I would like to record audio from WM8731 connected up to Arduino. I am using an SAMD arduino part.
But, I have a tremendous issue with the I2S.read() function. The I2S.read() function only returns a singular value, however the I2S standard is intrinsically stereo.
This is particularly important for my project as I am only interested in the LEFT channel as the RIGHT channel is muted.
I would expect this to either:

return a pair of values (i.e left /right) samples for that particular point in time , OR
return a singular sample with extra information telling me which channel that is was retrieved from.

However it seems this is not the case. (Github)
I also assume that the I2S is buffered making it impossible to simply read the WS pin state, as I will probably be popping a sample from the buffer that was push into the buffer at some point in the past.
So, is it possible to know which channel the sample was returned from the I2S.read() function or does this mean that the library needs to be modified?
I am more interested in using the samd library as other libraries such as AudioLibrary is limited to 16-bit - I need 32-bit resolution.

From my understanding it's just retrieving subsequent samples from the DMA buffer, which means you will alternately get left and right samples from each read. It would be more normal to use the read(buffer, len) variant to read two (or more) samples at once.
int16_t pair[2]; // change to int32_t for 32 bit samples
I2S.read(pair, sizeof(pair));

Thanks. It helps, however using this method would there not still be a possibility that the channels may be swapped? Will this ensure that the first member of the pair is always the LEFT or RIGHT (e.g.)? I find that the Arduino documentation, library and examples are extremely lacking with this regard and to my astonishment does not seem to concern most folk in the community

Your always dealing with an entire dma buffer, so should always be the same.

Thanks, I have tested this however occasionally I am getting all LEFT and sometimes all RIGHT on pair[0]  depending when I start reading. which is my main problem

I think part of the problem is that the whole library's methodology is flawed. You hjave DMA driven ping-pong buffers which receive the data constantly, and you must deal with an entire buffer in less time that it takes to fill the other buffer. You may be better off using the onReceive() callback to run a function at the moment the buffers swap, at which point you must read the entirety of the buffer, otherwise it will stall (by the looks of things).

thanks for the help - you've certainly understood the problem and it is worth recording (no pun intended) for others to know about. For now as my project only requires one channel I can simply put split the one channel into both left and right so that in this case it doesn't matter and I will always read the same channel regardless, however that's just a sticking plaster.


text:
Arduino motor shield not compatible with nodemcu
Hi to all first of All my english is not good I brought Arduino motor shield  and n..d. E.p 8266 but the connect pin are not compatible how i will connect to node i want to make robo car

Hard to say. There are at least two issues: mapping the Arduino shield pins to the 8266, and whether or not the shield library would work as-is on the 8266. You might be better off with a generic motor driver board.

Please provide a link to the motor shield.


text:
2 way switch with Arduino?
Hey I'm working on a home automation system where I can replace one of my 2 way switches to an Arduino Or node MCU controlled one but I want to avoid normal relays because as of what I know they can be unreliable and tend to fail. So is there any way I can replace my switch with an Arduino controlled switch and also I cannot use solid state relay as it has only two terminals and it cannot replace my two way switch.

I think you are calling what is called a three way switch a two way switch. A three way switch SPDT has three terminals and the identified one will connect to one or the other of the two remaining terminals.  A two way switch SPST is simply on/off. I have over 100 relays in my home automation system, and it has not had a single failure in about 20 years. I used top of the line relays, not the hobby relays sold as Arduino add on's.

Can you send me links to the ones you used
@Gil

And are the ones you used 3 way relays?   @Gil

Why are you trying to emulate a 3-way switch? Just automate 1 of the switches and control it from 2 different places. There are COTS products that do exactly this.  Further, likely you need two solid state switches to emulate a 3 way switch. So solid state switches are not "off the table", they are just expensive alternatives to reasonably priced relays. Respond if you want me to draft a solution based on these comments.  Otherwise do pick an answer to your question. Pick a "best" or "correct" answer.  Don't leave future stackexchange users in similar situations wondering what you finally did.

I'm not trying to emulate 2 3-way switches I'm trying to replace one of my 3-way switches with a relay so that I can control with node MCU and also the 2nd 3-way switch

Like Gil said, it sounds like what you are calling a two-way switch is actually a three-way switch. These are typically wired like this (but not always, make sure to double check!):

To replace one of the two switches with a relay, you can simply connect a SPDT relay with the load/hot wire (depending on which side you're adding the relay from) to the common contact, and then the two traveler wires to the normally open and normally closed contacts. This effectively takes your existing wiring and directly swaps in a relay -- after all, the relay is literally a switch, just electrically activated instead of manually.
I can't speak to the reliability or lack thereof of a specific model of relay, but a normal power relay is more than adequate for home automation in almost all cases; you don't need anything too fancy. Yes, there will be a mechanical point of failure, but they are typically rated for 100,000+ actuations minimum on a decent relay (like this one from SparkFun, for example) which will take quite some time to reach. Avoid the super cheap relays both for safety and reliability, and you should be fine.

Is this a good relay in your opinion @Reid Sox-Harris
https://www.electronicscomp.com/1-channel-5v-relay-module?search=Relay

Personally in this situation I would choose a latching relay so you don't have to keep it energised for extended periods.

@rohithrathodbanoth If you trust the datasheet, that isn't bad (claimed min. 100k actuations, 10A@240V). I might look for a higher-amperage relay depending on your expected load. And like Majenko said, a latching relay would better for this application.

@Majenko I have a question about latching relays will the relay retain its state even after the power is removed like the 5v wire is removed or disconnected

@rohithrathodbanoth Yes, the relay will retain its state. Whether the Arduino will, though, is another matter.

I have not had good luck with these relays, the modules themselves are OK I just solder in a new relay. Try looking for: "solid state 3 way switch"  I found this on my first try. DPST 1NO 1NC 8Amp Power Relay Module. It was labeled "OONO". Consider what happens when the power fails in just the controls, light circuit or both. What will you have then, and then when the power comes back on. I use larger relays and have not have any failures, they are rated at 20A 277V with 24VDC coile.

i did not find any solid state relays or switches with 3 way switching can give a link if you can

Not directly, it has one NO and 1 NC which when combined one side of each you have a SPDT.


text:
How to program and arduino UNO via NodeMCU ESP8266?
I don't have my USB type A cable to program my UNO, I would like to program it via a NodeMCU ESP8266.
Maybe with the TX and Rx pins, I've seen people program certain versions of ESP with a UNO board.
How do I do this and is it possible?

The UNO's USB connection is little more than a USB to UART converter.  The NodeMCU's USB connection is also little more than a USB to UART converter.
With a little jiggery pokery (yes, that's a technical term) you can replace one with the other.
By keeping the NodeMCU in RESET mode (tie the EN pin low, or hold the RESET button) you can use the TX and RX pins as the output to the onboard USB to UART converter to connect to the TX and RX pins of the Arduino.
The tricky part is getting the Arduino to reset at the right time: you have to press the Arduino's RESET button at just the right time. Normally this is done by a small capacitor between the DTR signal of the USB to UART converter and the RESET pin, but you don't have access to the DTR signal, so you will have to do it manually. Timing here is everything. Press upload, and just as AVRDude starts to execute you press RESET. Having verbose compilation turned on in the IDE can help.
It may take a few attempts to get it right.

Just for clarification, as I'm a beginner... TX goes to RX and vise versa, right?

And should the target be UNO or NodeMCU?

No, TX goes to TX and RX to RX. You're mirroring the NodeMCU functions with the Arduino board. And the target is UNO, since that's what you're programming. The NodeMCU ceases to be an NodeMCU and is merely a USB to UART adaptor (like an FT232 cable).

I cannot believe my eyes, IT WORKED!

Congratulations.


text:
Is it possible to upload a private root certificate to an Arduino Nano33?
I'm trying to connect an Arduino Nano 33 to an mqtt broker with TLS authenticaton on the broker side. To do that I need my Arduino board to have access to the the root certificate.
My understanding is that unlike ESP32, the Nano's NINA wifi module does not have a WiFiSSLClient object with a setCACert method that you can use to pass the root certificate. Instead, the NINA's client has a connectSSL() method which uses whatever root certificate you have uploaded to the Nano using Arduino's IDE. However, as it can bee seen in this tutorial, it looks like it is only possible to upload public domain root certificates by entering the website.
But what if I wanted to upload a root certificate that I have generated using OpenSSL. Would that be possible?

https://www.arduino.cc/en/Tutorial/WiFiNINAFirmwareUpdater#certificate-uploading


text:
HX711 Ridiculous speeds
I'm using a SparkFun HX711 board and an Adafruit AdaLogger (M0) Featherboard. I have cut the trace on the back of the HX711 to get a faster data rate (should be about 80 sps). I did this by reviewing the spec sheet and confirming with this post (Github link for faster rates).
Before I read from the board I get startTime from micros() and immediately after I get get the scale data, I call micros() again and record the endTime. I then write this data along with the load cell data to an SD card. Then to check the time, after the experiment is over in excel I take 1/((endTime - startTime)*10^-6) to get the approximate number of samples per second.
My issue is that apparently, I'm recording at a max of around 6000 SPS but commonly around 600 SPS. Which, would be awesome if I wasn't so sure that it was a lie. I was hoping someone could take a look and see what I'm doing wrong? I used this same code on a different M0 with an unmodified HX711 and was getting around 10 SPS. The only thing different (I thought) was cutting the trace on the back of the board to enable the higher rate.
In the GitHub link above, they do mention that you can get a faster rate if you splice in a faster crystal with a cap to bridge pins 13 and 14. I have not done this, but perhaps the faster processor on the Feather might be playing some of a role in this?
VCC and VDD are both connected to 3.3V and GND is connected to the ground pin on the Feather. Pin 11 is connected to DAT and Pin 10 is connected to CLK
#include <SPI.h>
#include <SD.h>
#include "HX711.h"

#define FILE_BASE_NAME "FAST" // max six characters
#define DOUT_one 11   // Red
#define CLK_one  10   // Orange

const uint8_t CS_PIN = 4;
const uint8_t BASE_NAME_SIZE = sizeof(FILE_BASE_NAME) - 1;

char fileName[] = FILE_BASE_NAME "00.csv";

float calibration_factor_one = -7050; // needs to be calibrated still

File file;

long startTime=0;
long endTime =0;

String dataString = "";

double scale_one_value = 0.0;

HX711 scale_one;

void SetUpSDCard(){
  if (!SD.begin(CS_PIN)) {
    Serial.println(F("begin failed"));
    return;
    }
   while (SD.exists(fileName)) {
    if (fileName[BASE_NAME_SIZE + 1] != '9') {
      fileName[BASE_NAME_SIZE + 1]++;
    } else if (fileName[BASE_NAME_SIZE] != '9') {
      fileName[BASE_NAME_SIZE + 1] = '0';
      fileName[BASE_NAME_SIZE]++;
    } else {
      Serial.println(F("Can't create file name"));
      return;
    }
  }
   file = SD.open(fileName, FILE_WRITE);
  if (!file) {
    Serial.println(F("open failed"));
    return;
  }
  Serial.print(F("opened: "));
  Serial.println(fileName);
  }

void SetUpLoadCell(){
  Serial.println("Remove all weight from scale");
  scale_one.begin(DOUT_one, CLK_one);
  scale_one.set_scale();
  scale_one.tare();

  long zero_factor_one = scale_one.read_average(); //Get a baseline reading
  Serial.print("Zero factor: ");
  Serial.println(zero_factor_one);
  Serial.println("Load cell one initialized");
  scale_one.set_scale(calibration_factor_one); //Adjust to this calibration factor
  }

void LogData(){
  startTime= micros();
  scale_one_value = scale_one.get_units();
  endTime = micros();

  dataString = String(startTime) + "," + String(scale_one_value) + "," + String(endTime);
  file.println(dataString);
  file.flush();
  }

void setup() {
  Serial.begin(9600);
  SetUpSDCard();
  Serial.println("Remove all weight from scale");
  SetUpLoadCell();
}

void loop() {
  LogData();
}

Then the saved data that is on the SD card is as follows, this is just the first 20 lines.
3383895,    0,      3384049
3401786,    0,      3401938
3411851,    0,      3412004
3421850,    -0.02,  3422004
3432012,    -0.03,  3432164
3442074,    0.01,   3442226
3452118,    0,      3452269
3462299,    0,      3462450
3472441,    0.03,   3473497
3483434,    0.03,   3485070
3495011,    0.02,   3496638
3506580,    0.01,   3508211
3518576,    0.03,   3519785
3529783,    0.02,   3531353
3541282,    0,      3542924
3552831,    0,      3554495
3564476,    0,      3566070
3575900,    0.01,   3577638
3587476,    -0.01,  3589209
3599068,    -0.03,  3600782

You're not measuring how many samples you do in a second, instead you're measuring the amount of time it takes to retrieve one sample from the HX711.
You store the time, retrieve the next sample, then store the time again. Then you spend a comparative age storing that data to the SD card, during which time the HX711 is taking any number of other samples.  By the time you eventually get around to reading from the HX711 again it's already ready to give you a sample.
You need to factor in the amount of time it takes to write to the SD card to have any kind of meaningful results - that is, the total amount of time that it takes to execute a loop(), or more simply: how long since the last time your logData() function has been run.
The actual sampling time of the HX711 will probably pale into insignificance compared to all the rest of your sequential code.

oh god. lmao. Yup.. That is exactly what is going on! I feel like a moron hahaha

To measure data sampling rate, measure elapsed time to fill an array with 10 (or better yet - 100) measurements.
N = 100;
t0 = millis();
for (i=0; i<N; i++){
    s[i] = get_sample();
}
samplingTime = (millis()-t0)/N;

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


text:
Calibrating Adafruit TCS34725 for RGB colors
I am new to Arduino. I am currently working on a project which requires color detection using the TCS34725 Adafruit sensor module.
For the project, I need to calibrate the sensor with RGB colors. Color patches of RGB will be exposed to the sensor. After exposing each color patch, a push button will be pressed and then the calibration for that color should start.

Calibrate for Red

Calibrate for Green

Calibrate for Blue

After calibration, the sensor needs to detect the colors of objects.
I have no idea what is meant by calibrating the sensor for RGB values. Can someone please be kind enough to explain it to me.
Thank you in advance.

It means exposing a known color with known lighting and using the returned sensor data to define that data as, e.g., "red". Subsequent "unknown" colors can then use the calibration data to attempt to identify unknown colors. You might want to check out the Learning Guide which also includes a link discussing (roughly) this topic.

your question is off topic here because it is unrelated to the arduino


text:
Reading and writing to GD25B32CPIG flash memory
I recently removed a GD25B32CPIG flash memory chip from a commercial coin-operated arcade game. Apparently it has all the game's sounds stored directly on the chip. I decided to see if I can learn to communicate with the chip to read the current data and write new data to it so that I can possibly change the game's sounds as the game itself doesn't have the ability to do that.
After searching online, I found schematics for the chip, including its functions and pinouts.

I've wired it up to my Arduino Uno's MOSI, MISO, CK, and SS pins as well as the 3.3V and GND for power. This is the only part I know is correct.
Unfortunately, I am lost on what to do next since I've never used the SPI library by itself (normally other libraries handle the SPI connections in my other projects). Nobody else has a tutorial on this particular chip and I'm a little bit lost by the datasheet's commands. I also did some research on SPI and found the tutorials to be a bit confusing.
I haven't tested anything because I don't want to alter the data unless I know what I'm doing.
The question:
Is there a way to read all data at once and write to a particular register?

https://github.com/Marzogh/SPIMemory may work.


text:
How to test custom cables?
I'm trying to make a cable checker to help me make custom cables for my computer. I'm thinking I plug the cable ends into sockets on the device, then the Arduino checks between different pins to make sure that no wires are in the wrong spot or unplugged.
So I'm thinking it runs through like this:
I plug the cable into connectors on the device. The Arduino has the PSU pinouts saved. Pin 1 represents one end of the cable, pin 2 represents the opposite end. Same with 3-4/5-6 etc. If the cable is assembled correctly, it should act as a connection between pins 1-2, pins 3-4, 5-6 etc.
tests pin 1 - 2 to see if they're connected, if yes, light up a green LED, if not, light up a red LED
tests pin 3 - 4, does the same thing
Repeats this  for every wire in the cable
Am I on the right track? How would I do this? I've seen people talking about pullup resistors but I'm also seeing people say that shorting can damage the board

Am I on the right track? ... that depends on whether pins 1 and 2 are supposed to be shorted together

write down the exact step-by-step procedure in great detail ... the resulting description will translate to code almost directly, if you include enough detail

@jsotola yes, done

if that is the most detailed description that you can write down, then you have a lot of thinking to do ... tests pin 1 - 2 to see if they're connected is not anywhere near one line of code  ......... a cable has two ends ... call them left and right ... I am talking about a description something like, set each pin on left as inputs, set each pin on right as inputs, set left pin 1 to output, output LOW on left pin 1, check state of right pin 1 ......

Do you consider shortcuts as an error? Then you need to check for them, too. -- At least in the history of computer cables, there are a several variants that have connections between two (or more) pins on the same side, without being connected to the other side. -- Other cables might connect one pin of one side to multiple pins on the other side, for example for ground. -- Some USB charger cables have resistors between pins that must fall into a certain range. -- You see, this task is not trivial, if you like to check non-trivial cables.

connectivity, resistance, cross-talk, capacitance, insulation integrity... check what matters for your uses.  There's no end to what you can check; arduino on its own may not be the best way to check everything though.

The scope of your question is too wide for a simple answer so let us constrain it to slow signals (audio frequencies or less) over short cables (not more than several meters) in a electrically clean environment (such as found in most homes).
That said, it is likely most looking for similar solutions reading your question will have different specific requirements.  So to make this question and answer useful to others let us consider the most generic, economical and Arduino based solution.

Most cables worth automatically testing will have far more individual connections than common Arduino boards, such as the Arduino Uno, have GPIO pins.  Consider using a GPIO expander or multiple Arduinos which communicate with each other to coordinate efforts.
When testing a cable that will be used for low frequencies, short distance and low immunity to noise it is likely the only faults that are of concern are OPENS and SHORTS.
As this design uses GPIO pins we have the following options at any given GPIO pin: Drive High, Drive Low and Input With Pull Ups.
Build a cable test rig where one end (the near end) of the cable under test is connected to GPIO pins designated as the driver side and the other end of the cable under test (the far end) is connected to GPIO pins designated as the sensing side.
For a SHORTS and OPENS test set all the sensing  and driving GPIO pins to Input With Pull Ups.  Verify that all sensing GPIO pins report a 1.  Next change one and only one of the driver GPIO pins to an output and send a 0.  Record that state of all sensing GPIO pins.  Return the driver GPIO pin to Input with NO PULL UPS and repeat these steps for the next GPIO driver pin.
If this is a STRAIGHT THROUGH cable only 1 sensing GPIO pin should report a 0 in each testing pattern recorded.  If more than 1 sensing GPIO pin reports a 0 then there is a short between the 0 reporting pins.  If none of the GPIO pins reports a 0 then there is an open for that GPIO pin.
Use the same test for cables containing intentional SHORTS (perhaps multiple ground pins are shorted together) expecting to see the associated GPIO pins to all change to 0 at the same time.
For even more complex cables containing loop backs at both ends consider only the "GPIO pin set to an output sending 0" as the driver and record the state of ALL OTHER GPIO pins as they are now all possible outputs.