text:
FastLED-driven strip acts weird when using PN532
A LED-strip (WS2812B, 46 pieces, PIN 8) and an Adafruit PN532 RFID shield (IRQ 2) are attached to my Arduino Mega 2560.
The GRB based strip seems to be working fine with FastLED in the beginning, I can confirm this by cycling through all three base colours in setup().
Once I call nfc.readPassiveTargetID(...) and use an NFC tag on it, things start to get weird. Whenever I comment out the line, it works properly again.
The colors RGB are randomly swapped (as if I had passed a different color ordering), brightnesses may change randomly as well, and sometimes a few LEDs in the beginning or end of the strip have different brightness/color as the rest.
As I have put the brightness down to 32, I'm sure it's not a power problem.
My assumption is that there is either some memory corruption, or some PIN interference with the two libraries, although I don't know why it would do it. Please find my code below, any help is appreciated.
  #include <FastLED.h>
  #include <Adafruit_PN532.h>

  #define LED_COUNT 46
  #define LED_DATA_PIN 8
  CRGB leds[LED_COUNT];

  #define PN532_IRQ (2)
  #define PN532_RESET (3) // Not connected

  Adafruit_PN532 nfc(PN532_IRQ, PN532_RESET);

  void setLeds(CRGB color) {
    Serial.print("setLeds("); Serial.print(color.r, DEC ); Serial.print(","); Serial.print(color.g, DEC ); Serial.print(","); Serial.print(color.b, DEC ); Serial.println(")");
    for (int i = 0; i < LED_COUNT; i++) {
      leds[i] = color;
    }
    FastLED.show();
  }

  void ledStartSequence() {
    setLeds(CRGB::Black);
    for (int crtLed = 0; crtLed < 23; crtLed++) {
      leds[crtLed] = CRGB::Blue;
      leds[crtLed + 23] = CRGB::Blue;
      FastLED.show();
      delay(20);
    }
    Serial.println("Red");
    setLeds(CRGB::Red);
    delay(1000);
    Serial.println("Green");
    setLeds(CRGB::Green);
    delay(1000);
    Serial.println("Blue");
    setLeds(CRGB::Blue);
    delay(1000);

    Serial.println("Off");
    setLeds(CRGB::Black);
  }

  void initLeds() {
    FastLED.addLeds<WS2812B, LED_DATA_PIN, GRB>(leds, LED_COUNT);
    FastLED.setBrightness(32);
  }

  void initSerial() {
    Serial.begin(9600);
    Serial.println("Hello!");
  }

  void initNFC() {
    nfc.begin();
    uint32_t versiondata = nfc.getFirmwareVersion();
    Serial.print(versiondata);
    if (! versiondata) {
      Serial.print("Error: Didn't find PN53x board");
      while (1); // halt
    }
    // Got ok data, print it out!
    Serial.print("Found chip PN5"); Serial.println((versiondata >> 24) & 0xFF, HEX);
    Serial.print("Firmware ver. "); Serial.print((versiondata >> 16) & 0xFF, DEC);
    Serial.print('.'); Serial.println((versiondata >> 8) & 0xFF, DEC);

    nfc.SAMConfig();
  }

  void setup() {
    initSerial();
    initLeds();
    initNFC();
    ledStartSequence();
  }

  void loop(void) {
    Serial.println("Waiting for an ISO14443A Card ...");
    setLeds(CRGB::Red); // only displayed correctly in the first iteration
    uint8_t success;
    uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };
    uint8_t uidLength;

    success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, &uid[0], &uidLength);
    /*
     *  Here's where things start to go nuts!
    */
    delay(1000);
    setLeds(CRGB::Green); // usually not displayed correctly
    delay(1000);
    setLeds(CRGB::Blue); // usually not displayed correctly
    delay(1000);
  }

You have an array uid with 7 bytes. If after nfc.readPassiveTargetID the uidLength value is > 7 you'll have a buffer overflow. Do you know how many bytes the UID of the RFID card containes? Another possibillity is that the PN532 driver uses a timer (e.g. for Hardware I2C) that the LED lib also uses. Then it possibly might help if you reinitialize the LEDs initLeds() after die call to readPassiveTargetID. Both are just guesses.

What happens when after the delay and before setLeds(CRGB::Green); you disable interrupt 2? Or when you don't connect the interrupt line of the RFID shield at all? Just out of curiosity. See https://www.arduino.cc/reference/en/language/functions/external-interrupts/detachinterrupt/

After spending way too much time on the code, I figured that it had to do with something entirely different:
The RFID reader created an RF interference on the data wire towards the LED strip... Shielding it properly did the trick, no matter which pin is being used.
Thanks for the help anyway.


text:
Cannot write to HID USB device (Arduino, V-USB, HidSharp)
I am currently prototyping an HID USB device using Arduino Nano and V-USB library. The problem is that although I can read from the device I cannot write to it.
Here is the schema:

As for the firmware I'm using the hid-serial library.
Here is the Arduino code:
#include <HIDSerial.h>

HIDSerial serial;

unsigned char buffer[32];

void setup() {
  serial.begin();
}

void loop() {
  if(serial.available()) {
    int size = serial.read(buffer);
    if (size!=0) {
      serial.write((const uint8_t*)buffer, size);
      serial.write('\n');
    }
  }
  serial.poll();
}

Here is the HID report descriptor:
    0x06, 0x00, 0xff,              // USAGE_PAGE (Generic Desktop)
    0x09, 0x01,                    // USAGE (Vendor Usage 1)
    0xa1, 0x01,                    // COLLECTION (Application)
    0x15, 0x00,                    //   LOGICAL_MINIMUM (0)
    0x26, 0xff, 0x00,              //   LOGICAL_MAXIMUM (255)
    0x75, 0x08,                    //   REPORT_SIZE (8)
    0x95, 0x08,                    //   REPORT_COUNT (8)
    0x09, 0x00,                    //   USAGE (Undefined)
    0x82, 0x02, 0x01,              //   INPUT (Data,Var,Abs,Buf)
    0x95, HIDSERIAL_INBUFFER_SIZE, //   REPORT_COUNT (32)
    0x09, 0x00,                    //   USAGE (Undefined)
    0xb2, 0x02, 0x01,              //   FEATURE (Data,Var,Abs,Buf)
    0xc0                           // END_COLLECTION

And lastly, here is the code running on host (.NET/C# using HidSharp library):
var devices = DeviceList.Local;
var hidDeviceCollection = devices.GetHidDevices(this.vendorId, this.productId).ToList();
var device = hidDeviceCollection.First();
var stream = device.Open();
var buffer = new byte[9];
buffer[0] = 0;
buffer[1] = 42;
stream.Write(buffer);
buffer = stream.Read();

When I run the code above despite stream.CanRead being true I receive an exception "Can't write to this device.". However if I change the code to the "Hello World" example provided by the library I can read from the device without issue.

Found the error.
While the HidSharp was sending output reports, the device driver expected feature reports.
Changing the line
0xb2, 0x02, 0x01,              //   FEATURE (Data,Var,Abs,Buf)

to
0x92, 0x02, 0x01,              //   OUTPUT (Data,Var,Abs,Buf)

resolved the issue.

source: Stack Exchange

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

sort: votes


text:
press button: servo move - hold X time - move back issue
Besides being a total noob I've been lurking and reading like mad over the last week to understand how to get my servo to move to X position when a button is pushed, have it wait Y time, and return to the starting position.  I've come up with this code but could use some guidance.
#include <Servo.h>

const int buttonPin = 8;
const int servoPin = 9;
int buttonState = 0;
int directionState = 0;
Servo servoOne;
int pos = 0;

void setup() {
  servoOne.attach(9);
  servoOne.write(directionState);
  pinMode(buttonPin, INPUT);
}

void loop() {
  buttonState = digitalRead(buttonPin);
  if (directionState == 0) {
    if (buttonState == HIGH) {
      directionState = 1;
      for (pos = 0; pos < 180; pos = pos + 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  } else if (directionState == 1) {
    delay(5000); {
      directionState = 0;
      for (pos = 180; pos > 1; pos = pos - 1) {
        servoOne.write(pos);
        delay(5);
      }
    }
  }
}

Besides an unnecessary  pair of curly brackets after the delay(5000) I don't see any obvious errors. What exactly is the problem with your current code? You wrote that you need guidance, but you didn't explain with what.

You should be more precise. What do you expect your code to do and what does it instead? A state machine is probably the simplest way to implement what you need, but for a user behaving appropriately I would expect your code to work

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


text:
Change MKR Zero SD SPI Pins
I have been trying to learn more about using the ATSAMD21 MCU with Arduino.  I designed and assembled a bare bones breakout board and have successfully flashed the MKR Zero bootloader and uploaded sketches via an SD card using the SDU library.
It would be nice to be able to change which pins are used for the SD card but every attempt I make is unsuccessful (using the Adafruit guide for adding a new SPI).  The steps I follow are:

Upload a sketch that is compiled using the original variant files.
Change the variant files.
Restart IDE (I've tried rebooting the machine as well).
Compile sketch, copy binary file to SD card.
Upload with SD breakout attached to original SD SPI pins.

At this point I would expect the SD SPI pins to update to PA20, PA21, PA22, PA23 as shown in the modified code below.  However, the sketch fails to upload unless I keep the SD breakout connected to the original SD SPI pins.
MKR Zero Original Variant.h:
// SPI1: Connected to SD
#define PIN_SPI1_MISO (29u)
#define PIN_SPI1_MOSI (26u)
#define PIN_SPI1_SCK  (27u)
#define PIN_SPI1_SS   (28u)
#define PERIPH_SPI1   sercom4
#define PAD_SPI1_TX   SPI_PAD_0_SCK_1
#define PAD_SPI1_RX   SERCOM_RX_PAD_3

MKR Zero Modified Variant.h:
// SPI1: Connected to SD
#define PIN_SPI1_MISO (6u) //PA20
#define PIN_SPI1_MOSI (0u) //PA22
#define PIN_SPI1_SCK  (7u) //PA21
#define PIN_SPI1_SS   (1u) //PA23
#define PERIPH_SPI1   sercom3
#define PAD_SPI1_TX   SPI_PAD_0_SCK_3
#define PAD_SPI1_RX   SERCOM_RX_PAD_2

MKR Zero Original Variant.cpp:
  { PORTA, 12, PIO_SERCOM_ALT, (PIN_ATTR_NONE), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // MOSI: SERCOM4/PAD[0]
  { PORTA, 13, PIO_SERCOM_ALT, (PIN_ATTR_NONE), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SCK:  SERCOM4/PAD[1]
  { PORTA, 14, PIO_DIGITAL,    (PIN_ATTR_NONE), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SS:   as GPIO
  { PORTA, 15, PIO_SERCOM_ALT, (PIN_ATTR_NONE), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // MISO: SERCOM4/PAD[3]

MKR Zero Modified Variant.cpp:
  { PORTA, 22, PIO_SERCOM,     (PIN_ATTR_NONE), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // MOSI: SERCOM3/PAD[0]
  { PORTA, 21, PIO_SERCOM_ALT, (PIN_ATTR_NONE), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SCK:  SERCOM3/PAD[3]
  { PORTA, 23, PIO_DIGITAL,    (PIN_ATTR_NONE), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // SS:   as GPIO
  { PORTA, 20, PIO_SERCOM_ALT, (PIN_ATTR_NONE), No_ADC_Channel, NOT_ON_PWM, NOT_ON_TIMER, EXTERNAL_INT_NONE }, // MISO: SERCOM3/PAD[2]

Am I doing something wrong?  Do the changes have anything to do with the bootloader?  Any help is appreciated.

The SDU library contains binaries of the SDUBoot sketch built for specific boards.
Since the SDUBoot sketch was built for specific board with its default SPI pins and selected CS pin, it is no possible to change the SPI pins or the CS pin in the sketch which uses the SDU library.

Looking through the SDUBoor sketch, I do not see anything indicating which pins are used.  Is there a certain process that can be followed to change the pins?  Maybe change the variant files like I have, open the SDUBoot sketch in the Arduino IDE, compile and do something with the output files?

@SolveEtCoagula07, every board has default SPI pins defined as they are marked on the pinout diagram for the board

Wouldn't build.sh be used to generate the binaries for the SDUBoot sketch?  I made changes and compared the output header file with the header file for the same board on github.  It seemed that this would work but when I tried to compile a new sketch that includes SDU.h, I receive an error "too many initializers for 'unsigned char [16384]".

@SolveEtCoagula07 your bin of SDUBoot is larger than the space reserved for the SDU boot binary (0x4000). do you have debug enabled?

The original mkrzero.h file is 91.4k while the one I generate when running build.sh is 106.5.  Are there parameters I need to add to the command that will reduce the size?  I have not modified anything in the variant files or SDUBoot.ino.


text:
Is it possible to program an atmega32 via internet or remotely with Android app?
There is a board with atmega32 microcontroller, sim card and Bluetooth modules. I used to program this microcontroller using a serial port cable. As long as the circuit is able to connect to internet, is it possible to program atmega32 via internet remotely?

if you can use a SD bootloader and SD card, it could download the update binary to SD card and reset. but it is very possible that you don't have enough memory left for the SD library

@Juraj Could you please explain it a bit more, if you had the same experience?

I enhanced the Arduino OTA library for SAMD to support classic ATmega Arduinos with at least 64 kB of flash. there are two ways: storing the uploaded update in upper half of the flash or on SD card. with less then 64 kB of flash there is no space for networking library + flash space or networking library + SD library. but maybe you can fit it with download over cellular network or bluetooth. https://github.com/jandrassy/ArduinoOTA/blob/master/examples/Advanced/OTASketchDownload_SD/OTASketchDownload_SD.ino


text:
Question: how to join two different codes
I’m dabbling in Arduino and having trouble running two sketches on my Arduino UNO simultaneously. The first is about a program that reads temperature and relative humidity and the second is a program that reads barometric pressure. Both programs work independently, but when I try to combine the two, No
help
this is the code for temperature and relative humidity:

#include <Adafruit_Sensor.h>
#include <LiquidCrystal.h>
#include <DHT.h>
#include <DHT_U.h>

//VARIABLES
//Asignación de los pines digitales
int SENSOR = 2; //Este es el pin #2
int RS = 4;
int E = 5;
int D4 = 6;
int D5 = 7;
int D6 = 8;
int D7 = 9;
//Variables de lectura de tempratura y humedad
int temp;
int hume;
//Creación de variables para el sensor y el display
DHT dht(SENSOR,DHT11);                    //Formato general: DHT <var_name>(PIN, MODELO DEL SENSOR)
LiquidCrystal lcd(RS, E, D4, D5, D6, D7); // Formato general: LiquidCrystal <var_name>(RS, RW, ENABLE, D0, D1, D2, D3, D4, D5, D6, D7)
//Variable para salida del abanico
int motor = 12;

void setup(){

  //Iniciar el sensor de temp
  dht.begin();
  //Iniciar el LCD
  lcd.begin(16,2); //(tipo 16 columnas, 2 líneas)
  //Setea el Pin 12 como salida
  pinMode(motor,OUTPUT);

}

void loop(){ //Este es el buclé principal del programa

  //Lee valores físicos
  hume = dht.readHumidity();
  temp = dht.readTemperature();

  //Limpia el LCD
  lcd.clear(); //esta instrucción coloca el cursor en la pos 0,0 (columna, fila)
  lcd.setCursor(0,0); //(no necesaria porque la linea de arriba ya lo hace)
  //Escribe los valores leídos en el LCD
  lcd.print("TEMPERATURA: ");
  lcd.print(temp);
  lcd.print("C");
  lcd.setCursor(0,1); //esta instrucción coloca el cursor en la pos 0,1 (columna, fila)
  lcd.print("HUMEDAD: ");
  lcd.print(hume);
  lcd.print("%");

  //Activa el motor si la temperatura pasa el valor deseado
  if(temp>=30){ // Compara si la temp ya es 30 grados
    digitalWrite(motor,HIGH); //Si lo es manda un 1 lógico a teavés del pin digital #12
  }
  else{
    digitalWrite(motor,LOW);// sino, manda un 0, lo que apagaría el motor
  }

  delay(2000);//valor en milisengundos para que repita el ciclo

}

and this is the barometric pressure code:
#include <Wire.h>
#include <Adafruit_BMP085.h>

// Connect VCC of the BMP085 sensor to 3.3V (NOT 5.0V!)
// Connect GND to Ground
// Connect SCL to i2c clock - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 5
// Connect SDA to i2c data - on '168/'328 Arduino Uno/Duemilanove/etc thats Analog 4
// EOC is not used, it signifies an end of conversion
// XCLR is a reset pin, also not used here

Adafruit_BMP085 bmp;

void setup() {
  Serial.begin(9600);
  if (!bmp.begin()) {
    Serial.println("Could not find a valid BMP085 sensor, check wiring!");
    while (1) {}
  }
}

void loop() {
    Serial.print("Temperature = ");
    Serial.print(bmp.readTemperature());
    Serial.println(" *C");

    Serial.print("Pressure = ");
    Serial.print(bmp.readPressure());
    Serial.println(" Pa");

    // Calculate altitude assuming 'standard' barometric
    // pressure of 1013.25 millibar = 101325 Pascal
    Serial.print("Altitude = ");
    Serial.print(bmp.readAltitude());
    Serial.println(" meters");

    Serial.print("Pressure at sealevel (calculated) = ");
    Serial.print(bmp.readSealevelPressure());
    Serial.println(" Pa");

  // you can get a more precise measurement of altitude
  // if you know the current sea level pressure which will
  // vary with weather and such. If it is 1015 millibars
  // that is equal to 101500 Pascals.
    Serial.print("Real altitude = ");
    Serial.print(bmp.readAltitude(101500));
    Serial.println(" meters");

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

If the problem is with your joint code, show that code, not the individual sketch that works. You also need to elaborate more on the meaning of "no help", what does it means? Got error? can't compile? etc..

write a new sketch that does everything that the two sketches do ... replace some of the serial.print with lcd.print ... for example, in setup() do dht.begin, lcd.begin, clear lcd, display start message on lcd, if bmp.begin fails then display error message ..... etc

you can refer to how to combine two Arduino code

You need to write one program using elements from each block of code. There is no way the Arduino will run both programs concurrently, it will only run one or the other.  You can copy and paste them together but unless done correctly it will not work. This is why it is important to understand the code you are using.


text:
Trouble with ESP8266 on Eero network
I have an ESP8266 Node MCU and am learning to use its wifi capabilities. In my home I have a router provided by my ISP that runs a network we'll call 'network1'. I also have an Eero mesh network that runs in the house, called 'network2'.
When I upload the following minimal example and use network1,

my 8266 device connects to network1 (the messages in the serial monitor confirm this) and
I can use my phone and laptop to connect to the 8266 - i.e., I can put the IP into my browser and see a webpage telling me 'Hello World'.

However, I have trouble with network2, the Eero network.

I can connect my 8266 device to network2 (the messages in the serial monitor confirm this)
but
I can't connect to the 8266 device with my phone/laptop. (Yes, I switch these over to network2 first.) I put the new IP into my browser and I am told the page is taking too long to respond.

I haven't done anything special with my network1 router; things just worked. With network2, I've tried various settings with my Eero - given the 8266 a static IP address, enabled port forwarding (on port 80) and established a firewall rule for it, but nothing works.
I can run many different programs through network1, and nothing works on the Eero network. Any suggestions on getting things to work?
My minimal working example:
#include <ESP8266WiFi.h>

const char* ssid = "network1"; // or 'network2'
const char* password = "thepassword"; // real password used in code

WiFiServer server(80); //just pick any port number you like

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

  // Connect to WiFi network
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

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

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

  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
  //gateway = WiFi.gatewayIP();
  Serial.print("GATEWAY: ");
  Serial.println(WiFi.gatewayIP());

  // print your subnet mask:
  //subnet = WiFi.subnetMask();
  Serial.print("NETMASK: ");
  Serial.println(WiFi.subnetMask());
}

void loop() {
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\n";
  s += "Content-Type: text/html\r\n\r\n";
  s += "<!DOCTYPE HTML>\r\n\r\n";
  s += "\r\n";
  s+= "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\r\n";
  s+= "<title>ESP Web Server</title>\r\n";
  s+= "\r\n";
  s += "Hello World";
  s += "\n";

  client.flush();

  // Send the response to the client
  client.print(s);
  delay(1);
}

I'm not totally sure, but have you successfully connected any two devices on the Eero network? I wonder if you could add some Serial.println() to the loop() to verify that things are working as expected in network1 and then see where things break down for network2.

@garson Do you mean connecting two ESP8266s & have them talk to each other? I have done things like get my iPhone to screencast to my Roku; in that sense, I've had devices on the Eero network talk together just fine. But not any devices that I've programmed.

Yes, that's what I meant. Hmm. This suggests restarting the eero. https://support.eero.com/hc/en-us/articles/207613706-Help-I-m-having-trouble-with-my-eeros. Printing confirmations to the log when someone accesses the ESP (on network1, and then trying on network2) may point you in the right direction but I'm not sure.

no matter what, you want to use the server.on() methods instead of that painful low level packet handling in loop().

@dandavis Will that help with the Eero issue, or just make for better page building once I get to making real applications? At the moment, learning to write good code is secondary to getting something working.

I was able to find an answer though I'm not sure why it works. It comes down to adding WiFi.mode(WIFI_STA); in the setup, as in
void setup() {

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  ...
  }

I was able to replicate success with another file on my ESP8266 device and Eero network as well.


text:
ATTiny13 Interrupt Issue
I have recently been working on a project that I had initially been designing with an Arduino Nano, and I was able to create functioning code for my application, but for cost / space reduction I decided to port the application to an ATTiny13 (because I had a few on hand). The problem is that for some reason, I cannot get the interrupt on the device to behave properly, and I was wondering if anybody could possibly give me a hand. I already performed a few experiments to narrow the problem down, and I think I understand the nature of the problem, but I have no idea on how to mitigate it.
Here is a rough schematic of my setup:

And here is the code I started with:
// Pin defines
#define ALERT_LED 4

// Variables
bool LED_STATE = false;

ISR(PCINT0_vect) {
  LED_STATE = true;
}

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

  // Configure the button-pin to have a pull-up
  DDRB |= (1<<DDB3);
  PORTB |= (1<<PORTB3);

  // Enable a pin-change interrupt on the PCINT3 (falling-edge)
  MCUCR |= (1 << ISC01);  // This and following line setup for falling-edge
  MCUCR &= ~(1 << ISC00);
  GIMSK |= (1 << PCIE);   // Enable pin-change interrupts
  PCMSK |= (1 << PCINT3); // Setup the pin-mask so that PB3 triggers the interrupt
  sei();                  // enable all interrupts

}

void loop() {
  if(LED_STATE == true) {
    digitalWrite(ALERT_LED, HIGH);
    delay(2000);
    digitalWrite(ALERT_LED, LOW);
    delay(2000);
    LED_STATE = false;
  }
}

In theory, this should setup the pin that the button is on to have a pull-up resistor internally, and when the button is pressed, it should trigger a falling-edge interrupt which would thus set "LED_STATE" equal to 1. When the code returns to the main loop, it should see the flag and blink the LED before clearing the flag.
Now before I go any further, here is what I validated up to this point:
1.) The LED circuit is definitely wired up properly because I can manually set the "LED_STATE" flag to true in the main loop, and it will constantly blink at a rate of about once a second (given the clock frequency of 600kHz)
2.) The pull-up is definitely being configured properly, as I can see the voltage sitting at 5V until I press the button at which point the voltage falls to 0V.
So I decided to experiment a bit, and I set the LED high inside the interrupt, and removed that line from the main loop to see if the interrupt was even working, and to my surprise the LED was actually turning on, but it was not turning off:
// Pin defines
#define ALERT_LED 4

// Variables
bool LED_STATE = false;

ISR(PCINT0_vect) {
  LED_STATE = true;
  digitalWrite(ALERT_LED, HIGH);
}

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

  // Configure the button-pin to have a pull-up
  DDRB |= (1<<DDB3);
  PORTB |= (1<<PORTB3);

  // Enable a pin-change interrupt on the PCINT3 (falling-edge)
  MCUCR |= (1 << ISC01);  // This and following line setup for falling-edge
  MCUCR &= ~(1 << ISC00);
  GIMSK |= (1 << PCIE);   // Enable pin-change interrupts
  PCMSK |= (1 << PCINT3); // Setup the pin-mask so that PB3 triggers the interrupt
  sei();                  // enable all interrupts

}

void loop() {
  if(LED_STATE == true) {
    //digitalWrite(ALERT_LED, HIGH);
    delay(2000);
    digitalWrite(ALERT_LED, LOW);
    delay(2000);
    LED_STATE = false;
  }
}

At this point, I started to think that the ISR was not returning to the main loop or something, but by adding an 'else' case to shut the LED off in the main loop, I could see that the loop was definitely running after the ISR, because the LED would not turn on (implying that the main loop had to be shutting it off the moment the ISR returned to the loop).
// Pin defines
#define ALERT_LED 4

// Variables
bool LED_STATE = false;

ISR(PCINT0_vect) {
  LED_STATE = true;
  digitalWrite(ALERT_LED, HIGH);
}

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

  // Configure the button-pin to have a pull-up
  DDRB |= (1<<DDB3);
  PORTB |= (1<<PORTB3);

  // Enable a pin-change interrupt on the PCINT3 (falling-edge)
  MCUCR |= (1 << ISC01);  // This and following line setup for falling-edge
  MCUCR &= ~(1 << ISC00);
  GIMSK |= (1 << PCIE);   // Enable pin-change interrupts
  PCMSK |= (1 << PCINT3); // Setup the pin-mask so that PB3 triggers the interrupt
  sei();                  // enable all interrupts

}

void loop() {
  if(LED_STATE == true) {
    //digitalWrite(ALERT_LED, HIGH);
    delay(2000);
    digitalWrite(ALERT_LED, LOW);
    delay(2000);
    LED_STATE = false;
  }
  else {
    digitalWrite(ALER_LED, LOW);
  }
}

At this point, I can really only think that there must be a problem with how I am defining the "LED_STATE" parameter, because all signs point towards this variable not actually holding the information properly when traversing from the ISR back to the loop. I don't see what would be the problem though since I defined the parameter globally. Can anybody lend a hand here, this is honestly the last thing I need to finish this part of the project, and I am honestly at a bit of a loss at this point.

You would want your bool LED_STATE = false; to be volatile qualified like volatile bool LED_STATE = false; otherwise the compiler's optimizer may assume that the value cannot be changing between loads and this can cause bugs in the generated code.  This sounds like the principal problem you're having.
The ISC01 and ISC00 in MCUCR are for controlling edges detected on the "external interrupt" INT0 pin, which is PB1, package pin 6.  This is essentially what attachInterrupt() does, which should be available to you in your board support package.  If you can, it's probably best to just use that.  In the case of using attachInterrupt() the use of volatile would still apply.
The other pins, like the one you've chosen, only only do Pin Change interrupts, hence PCINTn rather than INTn.  Pin change interrupts only fire to tell that a pin changed, but not which pin (out of the group) or in what direction it changed.  That is, it's ignoring what you've set in MCUCR.
If you want an external interrupt's ability to detect falling or rising edges using PCINTn interrupts, you must effectively synthesize this in software by tracking the old and new states of the pins, XORing them to determine what changed, and then either looking at the old or new state to determine what direction.  NicoHood's PinChangeInterrupt library does this for you, and appears to support the ATTiny13.  Likewise, volatile usage applies here as well.

Holy crap, that’s actually crazy! I never knew the compiler would do me so dirty like that! I really appreciate it man, that literally fixed it!

Good deal.  I will probably add in the above later that if you use attachInterrupt() or the PinChangeInterrupt library, everything said about volatile stands.  Because with those. whatever callback function you give is likewise executing in the context of an interrupt, no different from your more direct ISR() code.


text:
How to get arduino to always be connected as /dev/ttyUSB0 and with chmod 0777?
I've got Debian 10 as OS and for a Project, I need my arduino to always be connected as /dev/ttyUSB0, not any other ttyUSB-number, and I need it to be connected with the 0777 rights for a script to work.
I've read some things about udev, but nothing I tried yet worked.
I tried creating
/etc/udev/rules.d/51-my_usb_device
with the content
SUBSYSTEM=="tty", MODE="0777", KERNELS=="ttyUSB0"
but it does not work, even after reboot (like nothing changed). I must admit though that I do not really understand udev.
How to do this?

https://majenko.co.uk/blog/making-your-boards-unique-linux

Have you considered not trying to force ttyUSB0 but instead creating a symlink to whatever tty is assigned? Your software then just uses the symlink.
A problem with forcing a particular tty is what if you boot without the Arduino but another device is attached? You then need to convince the other device to skip ttyUSB0.
If you would consider a symlink then something like:
ACTION=="add", KERNEL=="ttyUSB*", ATTRS{idVendor}=="1a86", ATTRS{idProduct}=="7523", SYMLINK+="arduino"

might get you started. Check the VID and PID using lsusb or similar. To set permissions as well you can use e.g. MODE="0777" as you already have.
There is an example at https://wiki.debian.org/udev that might give more background.


text:
How to know the data type of constant in arduino IDE?
For example constant of MSBFIRST, It used to as input in SPI.setBitOrder(MSBFIRST). But sadly i don't know the type data of MSBFIRST. This is applied to like SPI_MODE0 and other.

short and universal answer: look in the .h files of the library for function parameter type

From SPI.h:
#ifndef LSBFIRST
#define LSBFIRST 0
#endif
#ifndef MSBFIRST
#define MSBFIRST 1
#endif

As you can see, there is no type. The compiler merely substitutes literally "1" for "MSBFIRST". So your code would read, after pre-processing:
 SPI.setBitOrder(1)

To know exactly what type "1" is (I'm not sure why you need to know) then you would look up "C++ integer promotion". In other words, how are literal integers handled by the C++ compiler.

From a comment:

In which case it's better to look at the desired type of the destination function not the type of the macro or const.

Quite right. If you look further into the SPI.h file you see this:
  // This function is deprecated.  New applications should use
  // beginTransaction() to configure SPI settings.
  inline static void setBitOrder(uint8_t bitOrder) {

So, ignoring what type MSBFIRST is, you can see that the function expects uint8_t.

Maybe he wants to know what the type is so he can use it as a parameter to some form of wrapper function or another form of abstraction layer? In which case it's better to look at the desired type of the destination function not the type of the macro or const.

@Majenko Indeed. I've amplified my reply to show this.

@Majenko you are right, i want to know type so i can use it as parameter for my abstraction layer. Nevermind, I already know the data type with using Serial.println(MSBFIRST),  it was displaying  1 in serial monitor. So i assume the data type is unsigned integer aka byte.


text:
Replacing the IC (atmega328) if lifespan has been arrive
Consider if the lifespan of atmega328 has been wear out.
It said on datasheet of atmega how many times we can upload sketch about 10.000times (cmiiw), should i change the arduino or only the microcontroller after 10.000 times have been arrive? what if that times has been arrive? What happened with that IC? If it will starting problem, can we change only the microcontroller (atmega328PU)?? Or any there's thing or stuff we must change too?
Should i burn the bootloader to that IC after replace it?

You realize, I hope, that it's very unlikely that you will ever upload a sketch to an Arduino 10000 times.

10,000 is 30 times a day for a year, surely it deserves a retirement with benefits after that service.

You only need to change the IC, not the entire board. The microcontroller IS the IC.
Also, you will not see any degradation, it will just 'suddenly' fail, or starting to fail sometimes, without any warning or counter that counts up/down to 10,000.
Also keep in mind that this number is the MINIMUM guaranteed value, most ICs will go much further.
The best way to prevent getting into problems related with this issue is:

When you have a finished project and it works, just keep that IC for that project.
In case you fear getting into this problem during development, only change it if you are sure you have problems (i.e. you cannot upload your sketch anymore).
Think before uploading 100 times per day a sketch for debugging purposes (add Serial.print lines, or even better, use a PC to debug all non Arduino related code.

So what you mean is Serial.print  for debugging instead of uploading code many times which it makes lifespan of atmega328 decreased, i was used to use arduino simulator on tinkercad.com, until i bought arduino board. So it's a bad habit to upload many times only for debug?

I don't have experience with the simulator. Uploading 100 times per day is quite a lot, and you can do it for 100 days to reach 10K, and probably many more. I wouldn't worry that much. However, another reason to add Serial.print statements or testing code on a PC is that is normally saves a lot of time (to really see what is happening and not 'guessing' or trying randomly to get things right.

It will be a long time before you reach the maximum number of sketch uploads so don't worry too much about it. Serial.print is meant to speed up the development/debugging process and can help reduce the amount of testing and code uploads needed as well as reduce the overall time needed for your software to work.

Can i debug with only with Serial.print without upload to board, i think it's impossible. So what u mean with reduce and overall time needed? I was debugging with lcd 16×2. Which that lcd actually a part of my project.

Actually Serial.print is not really debugging (meaning stepping through the code), but it's better than nothing. You have to upload to the board because the code only is executable on the Arduino. What I meant was that you can create some code on a PC, test it, and copy it to the Arduino, but only if it's not related to the hardware. E.g. a class that calculates something.  In principle you could create a class that 'mimics' the 16x2 to be run on a PC but that is quite tricky to do. In your case, I would just use print statements to see if your code is functioning well.

you can use tinkercad's online Arduino simulator to test code without any wear on equipment. it even simulates some hardware. I use it to work on libraries since it's faster than constantly uploading.

@dandavis That sounds like a good approach too. Myself used for one project self written stubs using a PC, more work but it was for a dedicated DMX (light) project.


text:
does EEPROM reset itself when a new code is uploaded?
I have a Nodemcu with which i'm doing a project. So whenever there is a power loss i want values of some of the variables to not be reset, because of that im trying to store the values in EEPROM of the nodemcu. But the problem is i want to know if the EEPROM will get reset when a new code is uploaded and also since the nodemcu stores wifi credentials in the EEPROM i dont want to accedentally select an EEPROM address in which the wifi credentials are stored and cause a problem. Can anyone tell me the safe EEPROM addresses to use and also if EEPROM will get rest if  a new code is uploaded?

The esp family chips do not have EEPROM. Instead they just dedicate a small section of flash to pretend to be EEPROM.
That flash section, depending on the core version, is either a dedicated EEPROM partition, or a dedicated key in the nvram partition. Either way it's separate to the wi-fi credentials, which are stored in their own key in the nvram partition.
EEPROM can be erased when you upload code if the partition layout changes. It's less likely to be erased if it's a newer version of the core where it's stored in the nvram.
For safety, don't change the partition size, and ideally use ArduinoOTA which will never change the partitions or erase the nvram.

and in Tools menu don't set "Erase flash" to "All flash content"


text:
Can i connect in pin of relay module to Analog pins of arduino instead of digital pin?
Im a complete beginner
Im making a project using relay modules and arduino. but all the digital pins of my arduino are filled.
I wanted to ask if i can use the analog pins to connect my relay module to my arduino? If yes can anyone give me the statements to write high and low using analog.

pins that have analog functionality are multi purpose ... they can also be used for digital outputs ... the command is the same for all digital output pins

Yes, you can  use the analog pins as digital pins.
Quoting this Arduino tutorial:
pinMode(A0, OUTPUT);
digitalWrite(A0, HIGH);

EDIT:
Here is the code snippet for digital input:
pinMode(A0, INPUT);
digitalRead(A0);

Your answer is certainly correct, but it would be better to show an example of using an analog pin as a digital INPUT, since that's what the OP is asking about.

worked for me thanks


text:
arduino parking lot
I want to make a project where there is a parking lot and a ir sensor which senses when a car comes and displays a message on lcd saying to insert a rfid card and then it opens a gate and there are many ir sensors in the slots to detect where there are cars and sends a message saying which slot is free.but the problem is many parts need the 5v pin but there is only one on the arduino board so i wanted to ask if any problem will occur if we connect multiple parts to one 5v pin if there will be a problem what is the work around.

You can connect multiple devices or modules to the same 5v pin, as long as it does not exceed the maximum current that the on-board 5v regulator can handled. If you are using a genuine Arduino Uno, it has a NCP1117 which has a maximum current of 1A. If you don't have a genuine Arduino Uno, check the part number and find the datasheet to find out the maximum current.

Thank you very much

Welcome. If this help and answered your question, please consider to accept the answer.


text:
Not able to upload code to NodeMCU
Im now working on a Node MCU based project but the problem is that i cannot upload the code to the board. Further more whenever i connect the usb to the NodeMCU my keyboard stops working and only works again after i turn off and on my pc this happens whenever i disconnect and connect the Node MCU. The error is COM port is not found or board is not connected and sometimes after i disconnect the Node MCU my system gives a message The Last USB device malfunctioned
Can anyone help I'm using a basic NodeMCU 12E CP2021??

I'd check 3 things:

If it's a specific USB port/cable problem, not related to the NodeMCU itself (your said it interacted with your USB keyboard, what makes sense if it's a computer-usb issue). Try to connect the NodeMCU to a different USB port/hub in your computer using another USB cable.

Of course it could be a USB-Serial driver issue. Please make sure what chip is used on your NodeMCU (CH340 or CP1202) and make sure the correct driver is installed.

Most important - you must make sure your Serial pins on the NodeMCU (TX, RX) are not connected to anything during program upload. They are bridged to the Serial connection that is coming from the computer (through the USB-to-Serial chip) and interact and interfere with them.

Good luck!

Thank you apparently its y breadboard which had a problem as it made a connextion between the rx and tx


text:
run a function for a certain amount of time!
i'm working on a project where i need to run a function for 20 minutes and the function writes to memory using EEPROM every minute. How can i make the function run for 20 minutes, i was thinking of using millis to measure the time between starting time and current but i'm afraid that when the millis rolls over and the the difference in time becomes negative my program will break and my function will run forever . Is there any way to make a function run for a certain amount of time, or will millis handle the rollover if we use unsigned variables for all variables for millis();

the difference will not become negative ... this has been covered here many times

See this answer for an explanation. Using unsigned variables, and subtracting will definitely work.
Not only will unsigned variables not become negative (by their very nature) but the rollover will be handled smoothly and accurately.

I would flag this as not an answer. it is a comment

Well, it perfectly answers will millis handle the rollover if we use unsigned variables for all variables for millis();

it is a comment - it answers the question. It looks "short enough" to be a comment, and I note there is such a comment under the question. However comments under the question are for clarifying the question and not answering it. If I am wrong, then someone can explain why, and perhaps vote it down. Which I note hasn't happened.

Another way to solve this problem is using cronAlarm. It can provide precise control on timings and you can schedule your job also. https://www.arduino.cc/reference/en/libraries/cronalarms/


text:
Node MCU not functioning correctly
i have a node mcu and i uploaded one example code to test it for rf signal decoding it worked. so after that i have written a code based on that and when i uploaded the code my node MCU suddenly isn't working as it should be. It is giving out some random things onto the serial monitor like this:
⸮L⸮⸮⸮ՋR(⸮⸮^⸮̓#⸮⸮;'⸮⸮(Zs"⸮⸮Z|⸮⸮⸮'⸮⸮⸮'⸮⸮⸮!#⸮⸮⸮G⸮⸮⸮⸮⸮h⸮y⸮⸮⸮⸮'⸮⸮LD⸮⸮J⸮*J⸮⸮⸮⸮⸮⸮⸮LD⸮⸮⸮⸮F(⸮y⸮⸮؁'1⸮L⸮⸮⸮

THE CODE:
#include <ESP8266WiFi.h>
#include <BlynkSimpleEsp8266.h>
#include <RCSwitch.h>
BlynkTimer clocktime;

#define relayfan 5
#define relaylight 6
#define relaylightb 7
#define relayrandom 2

#define VPIN_BUTTON_1    V12
#define VPIN_BUTTON_2    V13
#define VPIN_BUTTON_3    V14
#define VPIN_BUTTON_4    V15

RCSwitch mySwitch = RCSwitch();

int relayfanstate = HIGH;
int relaylightstate = HIGH;
int relaylightbstate = HIGH;
int relayrandomstate = HIGH;
int mainstate = HIGH;
long code;

char auth[] = "rJUG7fhgXk9Y7OlowTontA1C2irfpgs2";

const char *ssid =  "Nag";
const char *pass =  "87654321";

BLYNK_CONNECTED()
{
  Serial.println("blynk connected first function");
  Blynk.syncVirtual(VPIN_BUTTON_1);
  Blynk.syncVirtual(VPIN_BUTTON_2);
  Blynk.syncVirtual(VPIN_BUTTON_3);
  Blynk.syncVirtual(VPIN_BUTTON_4);
}

BLYNK_WRITE(VPIN_BUTTON_1)
{
  Serial.println("blynk write");
  relayfanstate = param.asInt();
  digitalWrite(relayfan, relayfanstate);
}

BLYNK_WRITE(VPIN_BUTTON_2)
{
  Serial.println("blynk write");
  relaylightstate = param.asInt();
  digitalWrite(relaylight, relaylightstate);
}

BLYNK_WRITE(VPIN_BUTTON_3)
{
  Serial.println("blynk write");
  relaylightbstate = param.asInt();
  digitalWrite(relaylightb, relaylightbstate);
}

BLYNK_WRITE(VPIN_BUTTON_4)
{
  Serial.println("blynk write");
  relayrandomstate = param.asInt();
  digitalWrite(relayrandom, relayrandomstate);
}

void setup()
{
  Serial.begin(9600);
  mySwitch.enableReceive(0);
  pinMode(relayfan, OUTPUT);
  pinMode(relaylight, OUTPUT);
  pinMode(relaylightb, OUTPUT);
  pinMode(relayrandom, OUTPUT);
  digitalWrite(relayfan, HIGH);
  digitalWrite(relaylight, HIGH);
  digitalWrite(relaylightb, HIGH);
  digitalWrite(relayrandom, HIGH);
  Serial.println("Start");
  WiFi.begin(ssid, pass);
  Serial.println("wifi config done");
  Blynk.config(auth);//, ssid, pass);
  Serial.println("Blynk config done");
}

void loop()
{

  if (WiFi.status() != WL_CONNECTED)
  {
    Serial.println("Not Connected");
    Serial.println("Without internet rf code recieving started");
    delay(500);
    if (mySwitch.available())
    {
      Serial.println("Switch available");
      code = mySwitch.getReceivedValue();
      if (mySwitch.getReceivedValue() == 8594433)
      {
        Serial.println("code matched without internet");
        mainstate = !mainstate;
        digitalWrite(relayfan, mainstate);
        digitalWrite(relaylight, mainstate);
        digitalWrite(relaylightb, mainstate);
        digitalWrite(relayrandom, mainstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594447)
      {
        digitalWrite(relayfan, LOW);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594445)
      {
        digitalWrite(relayfan, HIGH);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594436)
      {
        relaylightstate = !relaylightstate;
        digitalWrite(relaylight, relaylightstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594437)
      {
        relaylightbstate = !relaylightbstate;
        digitalWrite(relaylightb, relaylightbstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594439)
      {
        relayrandomstate = !relayrandomstate;
        digitalWrite(relayrandom, relayrandomstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
    }
  }
  else
  {
    Serial.println(" Connected");
    Blynk.run();
    with_internet();
  }
  clocktime.run();
}

void with_internet()
{
  Serial.println("With internet rf code recieving started");
  delay(500);
  if (mySwitch.available())
  {
    Serial.println("Switch available");
    code = mySwitch.getReceivedValue();
    if (mySwitch.getReceivedValue() == 8594433)
      {
        Serial.println("code matched without internet");
        mainstate = !mainstate;
        digitalWrite(relayfan, mainstate);
        digitalWrite(relaylight, mainstate);
        digitalWrite(relaylightb, mainstate);
        digitalWrite(relayrandom, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_1, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_2, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_3, mainstate);
        Blynk.virtualWrite(VPIN_BUTTON_4, mainstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594447)
      {
        digitalWrite(relayfan, LOW);
        Blynk.virtualWrite(VPIN_BUTTON_1, LOW);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594445)
      {
        digitalWrite(relayfan, HIGH);
        Blynk.virtualWrite(VPIN_BUTTON_1, HIGH);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594436)
      {
        relaylightstate = !relaylightstate;
        digitalWrite(relaylight, relaylightstate);
        Blynk.virtualWrite(VPIN_BUTTON_2, relaylightstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594437)
      {
        relaylightbstate = !relaylightbstate;
        digitalWrite(relaylightb, relaylightbstate);
        Blynk.virtualWrite(VPIN_BUTTON_3, relaylightbstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
      else if(mySwitch.getReceivedValue() == 8594439)
      {
        relayrandomstate = !relayrandomstate;
        digitalWrite(relayrandom, relayrandomstate);
        Blynk.virtualWrite(VPIN_BUTTON_4, relayrandomstate);
        delay(1000);
        mySwitch.resetAvailable();
      }
  }
}

can anyone tell me what is wrong with my code or my nodemcu module?
Is it because i uploaded two codes one after the other and messed up the module?

Did you set the right BAUD rate in the Serial Monitor?

yes 9600 exactly the same but even if i did it should be able to connect to my wifi right which it didnt

If you have concerns about whether the NodeMCU is working, upload a example sketch.

Set the baud to 74880 and read the boot error messages.

@PythonSchlange I have tried the blynk basic example and it works and it also connects to my wifi and blynk server but my code is not working

@Majenko the error i get when i plug out and plug in my node mcu is                                     ⸮⸮⸮PV⸮⸮ET⸮⸮⸮⸮T⸮⸮K⸮⸮u⸮U+UZ⸮Z⸮T⸮⸮T⸮⸮⸮⸮Eu⸮⸮T⸮UQ⸮⸮jP⸮,⸮⸮⸮UP⸮⸮TZT⸮(E⸮⸮⸮⸮QUE⸮jQUE⸮⸮⸮+RU⸮/⸮Ţ⸮⸮PV⸮⸮ET⸮⸮⸮⸮T⸮⸮K⸮⸮u⸮U+UZ⸮Z⸮T⸮⸮T⸮⸮⸮⸮Eu⸮⸮T⸮UQ⸮⸮jP⸮,⸮⸮⸮UP⸮⸮TZT⸮(E⸮⸮⸮⸮QUE⸮jQUE⸮⸮⸮+RU⸮/⸮   if it makes sense

@rohithrathodbanoth At 74800 baud?

@majenko yes at 74800 baud

But some normal 6 line code is working just fine but not mine.

Can anyone just try to upload this code to their node MCU with changing the WiFi credentials and the blynk Auth token to one of your own project by following the blynk guide and check if it is connecting to blynk and it's only a problem with my module or there is some problem in my code

Can anyone just try to upload this code to their node MCU with
changing the WiFi credentials and the blynk Auth token to one of your
own project by following the blynk guide and check if it is connecting
to blynk and it's only a problem with my module or there is some
problem in my code

This might be necessary to see more problems.  But it isn't necessary to see at least one important one.  Here's what I cut your code down to:
#define relayfan 5
#define relaylight 6
#define relaylightb 7
#define relayrandom 2

void setup() {
  Serial.begin(9600);
  pinMode(relayfan, OUTPUT);
  pinMode(relaylight, OUTPUT);
  pinMode(relaylightb, OUTPUT);
  pinMode(relayrandom, OUTPUT);
  digitalWrite(relayfan, HIGH);
  digitalWrite(relaylight, HIGH);
  digitalWrite(relaylightb, HIGH);
  digitalWrite(relayrandom, HIGH);
  Serial.println("Start");
}

void loop() {
  Serial.println("loop()");
}

So, you have:
#define relaylight 6

One thing to make clear about here is that this is GPIO6, and not D6, which would be mapped to GPIO12, which would make more sense.  GPIO6 is actually used internally to the ESP8266 module to access the SPI flash chip that stores your code.  Basically when you do this:
pinMode(relaylightb /* GPIO6 */, OUTPUT);

you're kind of ripping the rug out from underneath the the microcontroller inside the ESP8266 module.  It's a bit like reaching into a computer and pulling out harddrive while it's running.  It's trying to load code and data from the SPI flash, but you've reconfigured that pin.
The ESP8266 brings code from SPI flash into some smaller chunk of internal RAM that it executes the instructions from.  So, I suppose it might be possible to get in the situation where you're continuing to run cached instructions while trying and failing to load data from the spi flash, which maybe could explain part of why the problem manifests the way it does for you.
In case you're wondering, it is possible to get the microchip used in the ESP8266 to load code from sources other than SPI flash, in which case GPIO6 might actually be available for your own general purposes, but not with the way most of modules are set up and used.  If you look at the pinout for the common ESP8266 modules, the smaller board mounted to your NodeMCU board, you'll notice GPIO6 doesn't actually leave the module; it just goes from the microcontroller to the SPI flash chip, which is all hidden away under the RF shield on the NodeMCU.
There may be other problems here with pin selection.  E.g., GPIO7 is not mentioned in the pin mapping, nor does it seem to leave common modules, so #define relaylightb 7 is a bad sign.  Have a look through this guide with regard what you can do with each pin and what sort of behaviours they have at boot.  E.g. GPIO2 (your relayrandom) is "pin is high on BOOT, boot failure if pulled LOW" according to the guide.  So perhaps it will pulse your relay which you might not like.  And it may be that whatever circuit you have for the relay tugs GPIO2 toward LOW, which would also be bad.  Do keep in mind that the D# labeling is different from the GPIO# labeling.

I just checked GPIO7 (randomlightb), and like GPIO6 (randomlight), it was sufficient to execute pinMode with OUTPUT on it cause a reset.


text:
ESP8266 keeps restarting after a few hours of use and dead after 1 month of use
I have tried to make a water heater relay controlled by an ESP8266 (NodeMCU v1.0). The ESP8266 is connected to a central WiFi in my house, the ESP8266 also has its own WiFi so I use STA and AP mode for the ESP8266. The ESP8266 will give a webpage when its IP address accessed. I have been able to use it for about a month, even though sometimes the ESP8266 restarting after 4-24h of use. But then after 1 month the ESP8266 just die. I have tried to upload blink led, and it doesn't work, even though I can upload the program successfully using Arduino IDE.
Here is my Arduino ESP8266 code
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Arduino.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <FS.h>
#include <Hash.h>
#include <Ticker.h>
#include <SD.h>
#include <SPI.h>

//Client
#define STASSID "******"
#define STAPSK  "*********"

//Host
#define APSSID "**********"
#define APPSK "*********"

#define relayheaterPin D1
#define relaypompaPin D2
#define temperaturPin 3
#define CS_PIN  D8
#define voltagedetectorPin 1

IPAddress staticIP(192, 168, 100, 186); //ESP8266 static ip
IPAddress gateway(192, 168, 100, 1); //IP Address of your WiFi Router (Gateway)
IPAddress subnet(255, 255, 255, 0); //Subnet mask
IPAddress DNS(8, 8, 8, 8); //DNS
IPAddress DNS2(8, 8, 4, 4); //DNS

OneWire oneWire(temperaturPin);
DallasTemperature sensors(&oneWire);

AsyncWebServer server(80);

Ticker timer_pompa;
Ticker get_Temperature;

File dataFile;
String dataMessage;
unsigned long seeks;

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
unsigned long timeOffset = 25200;
String formattedDate;
String dayStamp;
String timeStamp;

const char* ssid = STASSID;
const char* password = STAPSK;
const char* APssid = APSSID;
const char* APpassword = APPSK;

bool b_Pompa = 0;
bool b_Pompa_Temp=0;
bool b_Heater = 0;
unsigned int i = 0;

unsigned long ret=0;
float f_temp;
unsigned long ul_max_temp = 38;
unsigned long ul_min_temp = 36;

void v_SD_setup() {
  if (!SD.begin(CS_PIN)) {
//    Serial.println("An Error has occurred while mounting SD Card");
    return;
  }
  dataFile = SD.open("temperature.csv", FILE_WRITE);
  dataFile.close();
}

void v_OTA_setup () {
//  Serial.begin(115200);
  WiFi.persistent(false);
  WiFi.disconnect(true);
  WiFi.mode(WIFI_AP_STA);
  WiFi.softAP(APssid, APpassword);
  WiFi.config(staticIP, subnet, gateway, DNS, DNS2);
  WiFi.begin(ssid, password);
  while (WiFi.waitForConnectResult() != WL_CONNECTED) {
    delay(5000);
    ESP.restart();
  }
//  Serial.println(WiFi.localIP());
//  Serial.println(WiFi.softAPIP());
  ArduinoOTA.onStart([]() {
    String type;
    if (ArduinoOTA.getCommand() == U_FLASH) {
      type = "sketch";
    } else { // U_SPIFFS
      type = "filesystem";
    }
  });
  ArduinoOTA.begin();
}

void getTimeStamp() {
  timeClient.update();
  formattedDate = timeClient.getFormattedDate();

  // Extract date
  int splitT = formattedDate.indexOf("T");
  dayStamp = formattedDate.substring(0, splitT);

  // Extract time
  timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);
}

// Write the sensor readings on the SD card
void logSDCard() {
  dataFile = SD.open("temperature.csv", FILE_WRITE);
  dataMessage = String(dayStamp) + "T" + String(timeStamp) + "," +
                String(f_temp) + "," + String(b_Pompa) + "," + String(!digitalRead(voltagedetectorPin))+ "\r\n";
  if (dataFile) {
    dataFile.print(dataMessage);
    dataFile.close();
  }
}

//Send Temperature, Pump, and Heater Condition Data from SD Card until EOF
String s_Read_Data(){
  String dataString= "Waktu, Temperature, Pompa, Heater\r\n";
  unsigned int len;
  dataFile = SD.open("temperature.csv");
  if (dataFile) {
    if (dataFile.size()>5580) {
      seeks=dataFile.size()-5580;
    } else {
      seeks=0;
    }
    dataFile.seek(seeks);
    while(dataFile.available()) {
     dataString+=dataFile.readString();
    }
    dataFile.close();
  } else {
    dataString="Error Opening File";
  }
  return dataString;
}

char* v_Pompa_On(){
   b_Pompa=1;
   digitalWrite(relaypompaPin, b_Pompa);
   return "Pompa is ON";
}

char* v_Pompa_Off(){
   b_Pompa=0;
   digitalWrite(relaypompaPin, b_Pompa);
   timer_pompa.detach();
   return "Pompa is OFF";
}

char* v_Heater(){
   b_Heater=!b_Heater;
   digitalWrite(relayheaterPin, b_Heater);
   if(digitalRead(voltagedetectorPin) ==0) {
    return "Heater is ON";
   } else {
    return "Heater is OFF";
   }
}

char* c_Heater_Condition(){
   if(digitalRead(voltagedetectorPin) ==0) {
    return "Heater is ON";
   } else {
    return "Heater is OFF";
   }
}

char* c_Pompa_Conditon(){
   if(b_Pompa ==1) {
    return "Pompa is ON";
   } else {
    return "Pompa is OFF";
   }
}

void v_getTemp () {
//  char buf[20];
  sensors.requestTemperatures();
  f_temp = sensors.getTempCByIndex(0);
  if (f_temp!=-127) {
   getTimeStamp();
   if (dayStamp!="1970-01-01") {
    logSDCard();
   }
  }
}

char* c_getTemperature () {
  char buf[20];
  sensors.requestTemperatures();
  sprintf(buf, "%f", sensors.getTempCByIndex(0));
  return buf;
}

void v_Timer_Pompa() {
  if (b_Pompa ==0) {
     v_Pompa_On();
  }
  if (ret<=0) {
    v_Pompa_Off();
    timer_pompa.detach();
    return;
  }
  ret--;
}

char* v_Pompa_10_min () {
  ret=10;
  v_Timer_Pompa();
  timer_pompa.attach(60, v_Timer_Pompa);
  return "Pompa is ON";
}

void v_server_setup () {
  // Initialize SPIFFS
  if(!SPIFFS.begin()){
//    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html");
  });
  server.on("/phone", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index-phone.html");
  });
  server.on("/pompa_timer", HTTP_POST, [](AsyncWebServerRequest * request){},NULL,[](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) {
     char str[30];
     char *ptr;
     for (size_t i = 0; i < len; i++) {
       str[i]=data[i];
     }
     ret = strtol(str, &ptr, 10);
     v_Timer_Pompa();
     timer_pompa.attach(60, v_Timer_Pompa);
     request->send(200);
  });
  server.on("/max_temp", HTTP_POST, [](AsyncWebServerRequest * request){},NULL,[](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) {
     char str[30];
     char *ptr;
     for (size_t i = 0; i < len; i++) {
       str[i]=data[i];
     }
     ul_max_temp = strtol(str, &ptr, 10);
     request->send(200);
  });
  server.on("/min_temp", HTTP_POST, [](AsyncWebServerRequest * request){},NULL,[](AsyncWebServerRequest * request, uint8_t *data, size_t len, size_t index, size_t total) {
     char str[30];
     char *ptr;
     for (size_t i = 0; i < len; i++) {
       str[i]=data[i];
     }
     ul_min_temp = strtol(str, &ptr, 10);
     if (ul_min_temp<=ul_max_temp) {
        request->send(200, "text/plain", "Success!");
     } else {
        request->send(200, "text/plain", "Minimum Temperature has to be lower than Maximum Temperature");
     }
  });
  server.on("/read_data", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/plain", s_Read_Data());
  });
  server.on("/time_left", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/plain", (String)ret);
  });
  server.on("/heater_condition", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/plain", c_Heater_Condition());
  });
  server.on("/pompa_condition", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(200, "text/plain", c_Pompa_Conditon());
  });
  server.on("/heater", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain",v_Heater() );
  });
  server.on("/pompa_on", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain",v_Pompa_On() );
  });
  server.on("/pompa_off", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain",v_Pompa_Off() );
  });
  server.on("/get_temperature", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain",c_getTemperature() );
  });
  server.on("/10_min_on", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send_P(200, "text/plain",v_Pompa_10_min() );
  });
  server.begin();
}

void setup() {
  //WiFi Setup
  v_OTA_setup();
  v_server_setup();
  v_SD_setup();

  //Pin Setup
  pinMode(relayheaterPin,OUTPUT);
  pinMode(relaypompaPin,OUTPUT);
  pinMode(temperaturPin,INPUT);
  pinMode(voltagedetectorPin,INPUT_PULLUP);

  //Sensors and time Setup
  sensors.begin();
  timeClient.begin();
  timeClient.setTimeOffset(timeOffset);

  //Get Sensors Reading
  v_getTemp();
  get_Temperature.attach(120, v_getTemp);
}

void loop() {
  ArduinoOTA.handle();
  if (WiFi.status() != WL_CONNECTED) {
    delay(5000);
    ESP.restart();
  }
  if ((b_Pompa ==1) && ((f_temp-ul_max_temp) <= 0)) {
    b_Pompa_Temp=1;
    b_Heater=1;
    digitalWrite(relayheaterPin, b_Heater);
  } else {
    if (b_Pompa_Temp==0) {
     if (f_temp<=ul_min_temp) {
       b_Heater=1;
       digitalWrite(relayheaterPin, b_Heater);
     } else if(f_temp>=ul_max_temp){
       b_Heater=0;
       digitalWrite(relayheaterPin, b_Heater);
     }
    } else {
      b_Heater=0;
      digitalWrite(relayheaterPin, b_Heater);
      b_Pompa_Temp=0;
    }
  }
}

Additionally, sometimes when I access ip_address/read_data I got no response, but after waiting for a while I got some response. Before the ESP8266 dies (after 1 month of use) when I accessed ip_address/read_data I got no response, and then when I restart the ESP8266 It just dies. Any idea why? 2 of my ESP8266s have died this past 2 months :(
Note: I powered my ESP8266 using LM7805 with supply from 12V 1A switching power supply.

one problem is the String class. the esp8266 arduino is always unreachable on network after a while even it works and accesses the network as client. that is a know issue and the solution is not merged into the library yet https://github.com/esp8266/Arduino/pull/6889

Is it possible for me to solve the String class problem by changing the String class into array of char? I have tried changing the string into array of char and getting the char from SD card file by using dataFile.readString().c_str(); but then the hardware wdt turns on and the esp restarts when I access ip_address/read_data.

How do you control the relay?

Exactly how are you connecting the microcontroller to the relay? Exactly how are you connecting the 5V power to the microcontroller?


text:
I want a bar type display for my Arduino Project
I am trying to make a smart table project. But I have stumbled upon one problem, that is I don't know which display should I use. I need a display that has roughly aspect ratio of 2:1 but also has a relatively high pixel density. I have purchased a 2.42 inch display based on SSD1309 but the display is way too pixelated for my use. Do you have any display recommendations for me?
This is the display that I have bought:

The display I am trying to achieve is like this:

It looked like the display that I'm trying to achieve uses a custom made display. Is there anyway I can achieve that kind of look (at least similar in quality) with displays on the market?

Yes, that is a custom display. No, not without a really high res screen, and those are really expensive and hard to drive from an Arduino. You could always use a mobile phone...

As Majenko already stated, the second image shows a custom display. It is not pixelated, because each shown element/symbol has it's own element in the LCD. When you have one of these displays, you might be able to reuse it for your project, but that is advanced.
In the case of pixel based displays with a significantly higher resolution than the standard SSD1309 driven LCD or OLED displays, you are mostly out of luck. There might be fitting products, though they most likely will be expensive and are not as easy to drive, as the standard ones. AVR based Arduinos, like Uno, Nano or Mega, are also not really good for driving high res displays.
The way to go depends on your exact requirements.

You could - as Majenko suggested - ditch the Arduino and use an old smartphone. If you need more control over the smartphone for your project, than the standard Andriod gives you, you could install an open source OS on the phone.

You could move to a Single Board Computer, like the Raspberry Pi Zero, and buy a display for it. There are many displays for Raspberry Pis, that should have enough resolution. Though most of them are larger than a normal smartphone display.


text:
Arduino Uno & Wemos (0.66” Across) OLED Shield
As I wrote in title, I have Arduino Uno and Wemos (0.66” Across) OLED Shield which i bought along wemos d1 mini.
For some reason I want to use it with uno. but there are just 0.96 tutorials internet and I don't know which pins to connect. I would appreciate any help.
PINS UNDER blue stick are
TX
RX
D1
D2
D3
so on..

how do you know i didn't?

were you this informative when you asked your first question?

I can find the code i have problem with connecting pins. i would appreciate if you help

The first thing I see when googling "0.66 lolin oled" is the link to https://wiki.wemos.cc/products:d1_mini_shields:oled_shield and their Get started guide. This yields the libraries to be used with it:

for the OLED: https://github.com/mcauser/Adafruit_SSD1306/tree/esp8266-64x48 with the dedicated test sketch
for the A & B buttons: https://github.com/wemos/LOLIN_OLED_I2C_Button_Library

thanks for the help man, but my problem is mainly connecting pins

You just stack it ontop of the D1 mini? what hardware are you working with? Also the included schematics (https://wiki.wemos.cc/_media/products:d1_mini_shields:sch_oled_v2.1.0.pdf) show you all the pins.

No, the thing is, I am not using it with D1 mini, i just bought it along that's it. right now, i need to use it with arduino uno.

The Uno is a 5V device and the OLED runs on 3.3V logic. You need a logic level shifter (for example this one https://www.sparkfun.com/products/12009) and then just conned the SCL and SDA pins to your Uno for the I2C connection (see schematics for which pin), plus power. I'm not sure if the library is Arduino-Uno compatible though, you'll have to find out and adapt it as necessary.


text:
RFID RC522 card reader project(servo, buzzer, two led) with FreeRTOS
So I wrote simple code which turns on led, buzzes and rotates servo motor when card readed. It works normally. But I want buzz, rotate and on off functions to work asynchorous. I will paste the code which I tried to apply freertos. Any help is appreciated!
void loop() {
 if (!mfrc522.PICC_IsNewCardPresent()) {
 return;
}

if (!mfrc522.PICC_ReadCardSerial()) {
    return;
}

for (byte i = 0; i < mfrc522.uid.size; i++) {
  card_ID += mfrc522.uid.uidByte[i];
}

if (card_ID == rfid) {

  //
  // I want to create async tasks here...
  //
  buzz(750, 1000); // task 1

  green_on();      //
  delay(1500);     // task 2
  off();           //

  rotate();        // task 3

}
//Serial.print(card_ID);
else {
  red_on();
  delay(700);
  off();
  red_on();
  delay(700);
  off();

  buzz();
}

card_ID = "";
}`

my freertos applied code is this. i will just paste the rotate function of all task functions for showing purposes:
void setup() {
// some code here  - inits and other things
  xTaskCreate(Main,(const portCHAR *) "Main", 128, NULL, 1, NULL );
  vTaskStartScheduler();
}

void Main(void *pvParameters) {
(void) pvParameters;

for(;;) {
  if ( ! mfrc522.PICC_IsNewCardPresent()) {
      return;
    }

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

    //mfrc522.PICC_DumpToSerial(&(mfrc522.uid));

    for (byte i = 0; i < mfrc522.uid.size; i++) {
     card_ID += mfrc522.uid.uidByte[i];
   }

   if(card_ID==rfid){
    xTaskCreate(Buzz,(const portCHAR *) "Buzz", 128, NULL, 2, NULL );
    xTaskCreate(GreenLed,(const portCHAR *) "GreenLed", 128, NULL, 3, NULL );
    xTaskCreate(Rotate,(const portCHAR *) "Rotate", 128, NULL, 4, NULL );

   }
   //Serial.print(card_ID);

   else {
     xTaskCreate(RedLed,(const portCHAR *) "RedLed", 128, NULL, 2, NULL );
     xTaskCreate(Buzz,(const portCHAR *) "Buzz", 128, NULL, 3, NULL );
   }

   card_ID="";
 }
}

void Rotate(void *pvParameters) {
(void) pvParameters;

 for(;;) {
    for (pos = 0; pos <= 180; pos += 1) { // goes from 0 degrees to 180 degrees
    // in steps of 1 degree
    myservo.write(pos);              // tell servo to go to position in variable 'pos'
    delay(15);                      // waits 15ms for the servo to reach the position
}
    for (pos = 180; pos >= 0; pos -= 1) { // goes from 180 degrees to 0 degrees
      myservo.write(pos);              // tell servo to go to position in variable 'pos'
      vTaskDelay(15 / portTICK_PERIOD_MS);                       // waits 15ms for the servo to reach the position
    }
  vTaskDelay(1);
}

}

what do you mean by work asynchorous? ... please provide a clear description of the desired behavior

sorry if I'm mistaken, I am trying to say that I want three tasks to work at the same time, I also have written it in first code, line 12


text:
Running stepper motors with A4988's, and might have shorted the Uno when checking voltages with multimeter. Is my circuit design faulty?
What Happened
I'm working on a project to run two peristaltic pumps from an Uno. The previous version used DC motors and L298N's, but I am attempting to upgrade it by using stepper motors and A4988's. I haven't used these motor controllers before, so was using a solderless breadboard while following some basic tutorials and was able to get one functioning how I want. During this, the Arduino was being powered through the barrel jack with a 12V/3A source; VMOT was connected to Vin; and VDD to the 5V pin. I checked the pins with a multimeter, and the voltages were all as expected, and the current limiters were set to 1A. The pump was able to run for a while with no issues.
After that, I drew up a diagram for how to lay it out on a smaller breadboard and soldered everything together.

Once that was done, I disconnected the motors and once again checked the voltages on each pin to make sure I didn't miss soldering a connection. When doing that, one lead of the multimeter might have caused a short (smell) and I quickly unplugged the barrel jack, but saw some smoke come from the arduino just after it was unplugged.
The Question
I know that a lot of people/examples (like this and this) recommend putting a 100 uF capacitor across VMOT and GND of the A4988's as close as possible to the inputs, to smooth out voltage spikes. However, those all use a separate power supply than what is used to power the Arduino. Before I just replace the burnt out board (I have some Nanos and a Mega lying around that could also do the trick, with some rewiring or an external voltage regulator), I want to eliminate the possibility that the way I'm powering everything is the cause of the burn out, so I don't just immediately ruin another board. Is it bad practice to use the onboard voltage regulator this way? By using Vin to run the motors and 5V to control the logic?
How or Why?
(All this after is extra, and really a secondary question/curiosity)
And is there a way to salvage the board, or figure out exactly what went wrong? The board can still be powered by USB or barrel jack, but the COM port doesn't show up when connected to my laptop to upload a new sketch. I was working through this answer to try and figure out what actually burnt out.

With both USB and barrel jack power (12V/0.5A) the "on" LED lights up, and Vin/3V3 read correctly on a multimeter. 5V read correctly on USB power, but when on barrel jack power its actually outputting about 9V. However, for both methods of powering the board, the voltage regulator itself has a 5V difference. From this point on, I just used the USB for power while troubleshooting.
The power-on LED does not flash when initially connected or the reset button is pressed, and TX/RX do not light up at all. That question indicates this could be bootloader problems or a damaged main processor chip.
Using a Mega 2560 board to try and burn the bootloader to the Uno, the "Burn Bootloader" process fails with the error message:

avrdude: Device signature = 0x000000 avrdude: Yikes!  Invalid device
signature.
Double check connections and try again, or use -F to override
this check.
avrdude done.  Thank you.
Failed chip erase: uploading error: exit status 1

Device signature 0x000000 seems to be a default message that indicates the board is not actually connected, which makes sense seeing as my computer wasn't able to identify that it was plugged in with the USB.
This leaves it at a possibly damaged Atmega328P. If I had another Uno, I would try swapping out those chips from the good and bad board to see if it fixes the issue, and if so I would just get a new Atmega instead of trashing the whole board.

But I've spent more time than its worth now trying to salvage the board, hence the main question asked previously. To rephrase that: do I need to use an external voltage regulator secondary power supply to provide 5V to the Arduino while giving 12V to the A4988's, or is it fine to give 12V to the board and run Vin to the motor controllers?

your question at the end indicates that maybe you have not learned anything from your experience

@jsotola Well, in the old configuration I mentioned using L298N's and DC motors I ran the 12V power supply through the uno and took Vin to the motor controllers for months and had no issues. So my experience has been that this is fine, and I wasn't able to find info saying to absolutely never do that, which is why I asked.

"Is it bad practice to use the onboard voltage regulator this way? By using Vin to run the motors and 5V to control the logic?"
Between the power jack socket and Vin on the Uno there is an M7 diode to prevent Vin back feeding the power jack. If you use Vin to tap the power entering at the jack socket, it goes via this diode. See schematic (D1) https://content.arduino.cc/assets/UNO-TH_Rev3e_sch.pdf . This diode is rated at 1A only and loads like motors, especially at startup, are likely to stress this. A silicon diode has a nominal voltage drop of 0.7 volts which, for example, must dissipate 1.4 watts as heat if the load is 2 amps. So, for large loads, do not use Vin as an output.
To calculate the heat dissipated by the Arduino's linear voltage regulator you multiply the voltage drop, in your case 12v - 5v = 7v, by the current drawn by the load, let's say 1 Amp which yields 7 watts. The recommendation is to power large loads separately using an appropriately dimensioned power supply. Buck converters are to be preferred over linear voltage regulators. Smaller loads in the order of say 100 mA or less for logic circuits etc. should be OK even if the Arduino is powered at 12 volts.

So then as a followup: Instead of running external power through the Arduino, and taking out from Vin and 5V, if I supply the 12V through Vin in parallel with the two VMOT pins. That way the current for the motor controllers isn't running through the arduino, but I can still use the onboard regulator to get the needed 5V supply for logic. I'm trying to avoid getting extra parts like a separated regulator/converter, since I have a limited budget.

@Vera using an arduino as a fuse is not the way to save money

@jsotola Can you explain what you mean by that? I found this answer to a similar question that indicates otherwise.

@Vera a fuse burns up when too much current flows through it ... an arduino behaves the same way

@Vera 12 volts at the barrel jack (or Vin) is OK for the standard Uno: https://store.arduino.cc/products/arduino-uno-rev3. Important only is that the connected peripherals do not draw too much current otherwise the regulator gets hot. If you tap the 12 volts from the barrel jack at Vin it goes through a diode (D1 here) : https://content.arduino.cc/assets/UNO-TH_Rev3e_sch.pdf . Your motors may stress this. A silicon diode has a nominal 0.7 volt drop so 2 amps would be 1.4 watts

@6v6gt Got it, from the datasheet for the drivers I have it looks like the logic inputs only pull a few mA at most, and I'll eventually add a few LEDs as status indicators, so the peripherals connected through the board should be fine for the onboard regulator. Thanks for your help!


text:
Can't connect to Arduino Nano 33 BLE while MicroPython file is running
I am using a Arduino Nano 33 BLE and I'm using MicroPython to write code for my board using Arduino Lab for MicroPython. I uploaded a file with the name main.py to my Arduino to test if it would work and it does. But the problem is that now it won't stop and I can't connect to it while the file is running (it keeps running because of infinite loop in the code). And if I change it to bootloader mode, Arduino Lab detects it but won't connect. It will connect to the Arduino IDE in the bootloader mode, so this should also work. If anybody is able to help out it would be greatly appreciated.
PS: the code that is in main.py is just blinking the RGB

change your sketch so that it has some serial output

Just use OpenMV to connect to the Arduino Nano and update the firmware, there will be a toggleable option to erase the internal file system. Maybe also try reinstalling Arduino Lab for Micropython.


text:
Bluetooth communication between 2 Arduinos using HC-05
I am trying to send sensor values from an MPU6050 Accelerometer from one Arduino to another continuously using 2 HC-05 modules, one on each Arduino. I have done the following:

Entered AT Mode on both HC-05 and set one as master and another as slave using AT+ROLE.

Paired the modules (Apparently) by entering the slave's Address in the AT+BIND as well as the AT+PAIR command on the master.

All this was done while RX was connected to Arduino's RX and the same for TX.

Tried sending sample values (like small integers and strings) using the Serial.read() and Serial.write() functions after exiting AT Mode. (TX and RX remained connected to the same)

After these steps, the master is receiving -1 values no matter what is sent in Serial.write() on the slave. This problem is very persistent and I feel like I am missing some fundamental steps, but can't figure it out from anywhere.
Please point out if I am doing something wrong or missing something important. I deeply appreciate any help.
I also tried the SoftwareSerial library and the BTSerial.read and BTSerial.write commands, still there is no avail.

Ensure that TX of the master HC-05 is connected to RX of the Arduino and vice versa for both modules.
Use voltage dividers for TX from HC-05 to RX on Arduino if using a 5V Arduino since HC-05 operates at 3.3V logic.
Check for loose connections or bad jumper wires.


text:
Arduino IDE Serial Monitor is working, but not Putty - esp8266
I have an esp8266 that most often won't work with Putty, but always works with Serial Monitor in Arduino IDE.
Baudrate is set to 115200. Putty fills the terminal window with odd characters and the power to the esp8266 seams to disappear when opening a Putty window.
The esp is programmed to wait for commands via serial and write response to serial. I am using the serialEvent() method for this.
I have tried to add Serial.setTimeout(10000), but it did not help.
Any ideas?

make sure that the settings in PuTTY are the same as the serial monitor

The main difference between the PuTTY and the Arduino serial monitor is
that the latter sends one message at a time, with all the characters of
the message immediately following each other, whereas PuTTY sends each
character as soon as you type it. If you want you sketch to be
compatible with both, you have to read the serial port until you find a
proper line terminator. See Reading Serial on the Arduino, by
Majenko.
You should also watch your line terminators. IIRC, PuTTY defaults to
sending CR ('\r') when you hit the return key, and it expects your
sketch to terminate its output lines with CRLF ("\r\n"):

CR moves the cursor horizontally all the way to the left
LF moves the cursor vertically, one line down.

The Arduino Serial.println() method does end the lines with CRLF.


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:
Audio stops playing after rtc is connected
I am trying to play a song using arduino while at the same time display time using a rtc board using the tmrpcm library. However, if the rtc board is connected no sound is played.
I do understand that the tmrpcm may be interfering with the wire.h library but even commenting the same doesn't resolve the problem.
I am using the following code:
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <RTClib.h>
#include<Wire.h>
#include <Arduino.h>
#include "SevenSegmentTM1637.h"
#include "SevenSegmentExtended.h"
#include "SevenSegmentFun.h"
#include "SD.h"
#define SD_ChipSelectPin 4
#include "TMRpcm.h"
#include "SPI.h"

TMRpcm tmrpcm;

const int ProxSensor=3;
int inputVal = 0;
#define CLK 8
#define DIO 7

// The amount of time (in milliseconds) between tests
#define TEST_DELAY   2000

SevenSegmentFun    display(CLK, DIO);

RTC_DS1307 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  Serial.begin(9600);
  if(!SD.begin(SD_ChipSelectPin))
  {
    Serial.println("SD fail");
    return;
  }
  while (!Serial); // for Leonardo/Micro/Zero
  tmrpcm.speakerPin=9;
  Serial.begin(57600);
  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC is NOT running!");
    // following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(2019, 10, 19, 01,41,00));
    // This line sets the RTC with an explicit date & time, for example to set
    // January 21, 2014 at 3am you would call:
    // rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
  }
  pinMode(ProxSensor,INPUT);    //Pin 2 is connected to the output of proximity sensor
  display.begin();
}

void loop(){
  DateTime now = rtc.now();
  display.print((now.unixtime() / 86400L )-17963);
  Serial.print((now.unixtime() / 86400L )-17963);
  while(digitalRead(ProxSensor)==LOW)      //Check the sensor output
  {
    tmrpcm.setVolume(5);
    tmrpcm.play("test.wav");
      repeat:
    if(digitalRead(ProxSensor==LOW))
      goto repeat;
  }
}

Can anyone please help me?

The TMRpcm and one of your other libraries might use the same timer on Uno which causes one of them to break. Either get a Arduino Mega which can run TMRpcm on TIMER3,4 or 5 or use libraries that don't require a timer.

In what way does the Wire library use a timer?

@Majenko probably for timing the SCK pulses.

I can't find any reference of what it is used for and if used at all but it seems that the usage of the TWBR breaks many things related to timer one.

Can you cite some evidence for this? This is new to me - and the TWI peripheral has nothing to do with any timer peripherals - the baud rate generator is internal to TWI and uses the system clock as its source.

@SoumendraDey, explain please how did this answer help, because it should not

The problem is
repeat:
if(digitalRead(ProxSensor==LOW))
  goto repeat;

ProxSensor==LOW is false so 0. you read the pin 0 and the outcome is random. The surrounding wiring can affect that. If digitalRead(0) is zero the wav starts playing immediately again. At least use
while (digitalRead(ProxSensor) == LOW);

I am already using while (digitalRead(ProxSensor) == LOW) in my code

@SoumendraDey,  read the answer again and slow