text:
Not have to wait for if statement to run
I need some advice. I am trying to code a setup of 4 stepper motors that are connected to a keypad and 2 DC-motors that run a conveyor belt. My goal is to be able to push a key, the correspondning stepper motor starts and the DC-motors starts as well and run for a couple of seconds after the stepper. However, I want to be able to push multiple keys while the DC-motors are running. Right now I need to wait for the DC-motors to be done before I can push another key. How can I make this happen?
I think there will be issues if I code it with a timer since the keys are waiting for an input. I don't have any sensors.
This is my code:
#include <Keypad.h>
#include <Stepper.h>

const int stepsPerRevolution = 1024;

Stepper myStepper1(stepsPerRevolution, 22, 26, 24, 28);
Stepper myStepper2(stepsPerRevolution, 32, 36, 34, 38);
Stepper myStepper3(stepsPerRevolution, 23, 27, 25, 29);
Stepper myStepper4(stepsPerRevolution, 33, 37, 35, 39);

const int IN1 = 47;
const int IN2 = 45;
const int IN3 = 51;
const int IN4 = 49;

const int ENA = 43;
const int ENB = 53;

const byte ROWS = 4; //four rows
const byte COLS = 4; //three columns
char keys[ROWS][COLS] = {
  {'D','C','B','A'},
  {'H','G','F','E'},
  {'L','K','J','I'},
  {'P','O','N','M'}
};

byte rowPins[ROWS] = {2, 3, 4, 5}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {6, 7, 8, 9}; //connect to the column pinouts of the keypad

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup(){
  Serial.begin(9600);
   myStepper1.setSpeed(10);
   myStepper2.setSpeed(10);
   myStepper3.setSpeed(10);
   myStepper4.setSpeed(10);

  pinMode (IN1, OUTPUT);
  pinMode (IN2, OUTPUT);
  pinMode (IN3, OUTPUT);
  pinMode (IN4, OUTPUT);
  pinMode (ENA, OUTPUT);
  pinMode (ENB, OUTPUT);

}

void loop(){
 // char key = keypad.getKey();
 char key = keypad.waitForKey();

   if (key){
    Serial.println(key);
//control speed
  analogWrite(ENA, 200);
  analogWrite(ENB, 200);
//control direction
int onTime   = 5000;
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);

// ----------------------------------Stepper1-----------------------------

        // just print the pressed key
   if (key == 'A' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper1.step(256);
  delay(100);
}

  // just print the pressed key
   if (key == 'E' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper1.step(512);
  delay(100);
}

  if (key == 'I' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper1.step(768);
  delay(100);
  }

  if (key == 'M' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper1.step(1024);
  delay(100);
  }

//-----------------------Stepper2------------------------

if (key == 'B' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper2.step(256);
  delay(100);
}

  // just print the pressed key
   if (key == 'F' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper2.step(512);
  delay(100);
}

  if (key == 'J' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper2.step(768);
  delay(100);
  }

  if (key == 'N' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper2.step(1024);
  delay(100);
  }

 //------------------------Stepper3--------------------

if (key == 'C' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper3.step(256);
  delay(100);
}

  // just print the pressed key
   if (key == 'G' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper3.step(512);
  delay(100);
}

  if (key == 'K' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper3.step(768);
  delay(100);
  }

  if (key == 'O' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper3.step(1024);
  delay(100);
  }

 //------------------------Stepper4--------------------

if (key == 'D' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper4.step(256);
  delay(100);
}

  // just print the pressed key
   if (key == 'H' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper4.step(512);
  delay(100);
}

  if (key == 'L' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper4.step(768);
  delay(100);
  }

  if (key == 'P' ){
    Serial.println(key);
     // step one revolution in one direction:
  Serial.println("clockwise");
  myStepper4.step(1024);
  delay(100);
  }

//---------DC_Motor---------

   delay(onTime);
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
    digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);

 }
}

Have you checked the millis()?

If you want to know how to use the millis() to avoid using delay() check the BlinkWithoutDelay example in the Arduino IDE. File->Examples->02.Digital->BlinkWithoutDelay.

In order to do several things simultaneously you need to get rid of the delay() statements and also of the waitForKey() statement.
Instead the Keypad library offers the possibility to add an event listener with the function  keypad.addEventListener(keypadEvent).
Look into the example on the arduino page: https://playground.arduino.cc/KeypadTutorial/EventKeypad/

The delay(onTime); statement in the //---------DC_Motor--------- section of your code is preventing anything else taking place until the end of the DC motor run. Instead of delaying, you need to test how long the motor has been running, and do nothing if that time has not been reached yet. As others have pointed out, the BlinkWithoutDelay example program demonstrates how to do this. But in short, the motor section needs to do:
// Start motor here
timeMotorStarted = millis();
   :
   :
   :
if( millis() - timeMotorStarted > onTime ){  // has motor run long enough?
  // stop the motor
}


text:
Add nRF24L01 to a project
I Have a Liquid Level Project that Currently uses an Oled display.  I have just discovered the existence of the nRF24L01 wireless communication module; and it is exactly what I need to make my project more user friendly.
Eventually I want to have a dashboard that brings all my info together in one place, but for now I just want to figure out how to get my Liquid Level Project transmitting, and receive the data on another Arduino and view it on the Serial monitor.  As is all it does is print out "?" in the Serial monitor.
I have this Sketch on the Liquid Level Project Arduino:
#include <Wire.h>
#include "SSD1306Ascii.h"
#include "SSD1306AsciiAvrI2c.h"
SSD1306AsciiAvrI2c oled;
#define I2C_ADDRESS 0x3C
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

double SensorAnalogValue;
uint8_t calculation=1;
String Show_value;

//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

void setup()
{

  Serial.begin(9600);
  oled.begin(&Adafruit128x64, I2C_ADDRESS);
  oled.setFont(CalLite24);
  oled.clear();

  radio.begin();

  //set the address
  radio.openWritingPipe(address);

  //Set module as transmitter
  radio.stopListening();

}

void loop()
{

  SensorAnalogValue = analogRead(A0) * 5.0 / 1023.0;
  if (SensorAnalogValue < 1.726) {
    calculation=0;
    Show_value="Low";
  }
  if (SensorAnalogValue > 4.04) {
    calculation=0;
    Show_value="High";
  }
  if(calculation!=0){
  //  Serial.println(SensorAnalogValue);
    Show_value=(String)Liquid_Volume(SensorAnalogValue);
  }
  Serial.println(SensorAnalogValue);

oled.setCursor(20, 0);
  oled.print(Show_value);
  oled.print(" L");
  oled.println(" ");
  oled.print(Show_value);
  oled.print("L");
  oled.println(" ");
delay(500);
   oled.clear();

  radio.write(&Show_value, sizeof(Show_value));
  delay(1000);

  calculation=1;
}
int Liquid_Volume(double Volt) {
  double A =   2.81842;
  double B = -11.00151 ;
  double C =  14.4765 ;
  double D =  28.73579 ;

  return A * Volt * Volt * Volt + B * Volt * Volt + C * Volt + D;
}

And the Receiver has this:
//Include Libraries
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>

//create an RF24 object
RF24 radio(9, 8);  // CE, CSN

//address through which two modules communicate.
const byte address[6] = "00001";

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

  radio.begin();

  //set the address
  radio.openReadingPipe(0, address);

  //Set module as receiver
  radio.startListening();
}

void loop()
{
  //Read the data if available in buffer
  if (radio.available())
  {
    char Show_value[32] = {0};
    radio.read(&Show_value, sizeof(Show_value));
    Serial.println(Show_value);
  }
}

I think the problem is in:
radio.write(&Show_value, sizeof(Show_value));

I believe "radio.write" is used kinda like Serial.print, or oled.print,  But I don't really understand the "sizeof" part, maybe that is the problem?

radio.write(&Show_value, sizeof(Show_value));

I believe "radio.write" is used kinda like Serial.print, or
oled.print, But I don't really understand the "sizeof" part, maybe
that is the problem?

Sort of.  There's kind of two interrelated problems.  The major one is that the actual data of a String is not contained with the actual String type itself.  It's allocated on the heap.  What the String class contains is a pointer to it and some numbers for tracking the allocated size and amount used.
So the first problem is you're not reading the memory that actually contains the text inside the string.
sizeof(Show_value) evaluates to the size in bytes of the String class itself, which is the size of a pointer and a couple of integers, about 6 bytes, and not the size of the content of the string.
So you're sending a pointer (a memory address) that the receiver wouldn't know what to do with, and some information about how much was allocated and used and nothing of the String content.
Try:
radio.write(Show_value.c_str(), Show_value.length());

.c_str() gets a pointer to the actual string content itself.  And .length() is the actual size of the used part of the String's allocated area on the heap.
That said, it's better to avoid String where you reasonably can.

Regarding:

Does this also mean I need to replace radio.read(&Show_value, sizeof(Show_value));

It would. Doing that is a bit more complicated since .c_str() yields const char *; String isn't designed to make write-access to its underlying data as easy.
Without hacking your way around String's expectations, that would require using a temporary buffer. Something like:
char buffer[33] = "";  // Note: this will actually fill the entire buffer with '\0', which some find a surprise.
// The idea in the above is to accommodate the maximum RH24L01 packet size 32 bytes plus room for a null terminator.

radio.read(buffer, sizeof buffer - 1);  // We're only making the 32 byte chunk available to the .read() call, and leaving the last byte to it's '\0' value to force null termination in any case.

String s = buffer;

This assuming that you're either filling the packet with bytes, or including the null terminator in the packet, or both.  If you're using a dynamic payload size, rather than initializing the array with = "";, it could be left uninitialized and the received packet size could be used to place the null terminator at the location needed.
You could wrap this in a function if you plan on doing it a lot.  But again, it's probably better if you can just use the array and not work with String.

Thanks timemage,
Does this also mean I need to replace
radio.read(&Show_value, sizeof(Show_value));
With:
radio.read(Show_value.c_str(), Show_value.length());
In the receive sketch?

I've updated to try to address that, which is more or less "yes" to the first part, "no" to the  second.  I'm going to be done for a bit, so it's written hastily, but it should give some shape to the answer.  Your second part to the above comment didn't exist when I started updating the question.

I missed the fact that you're more or less doing the above already with respect to having a buffer and filling it, just not adding the extra byte room or assigning it to a String.  If the only thing you're doing with the string is sending it out through Serial, you can switch from println() to using write() with the size argument set to the correct number, in which case you don't need to terminate at all.

source: Stack Exchange

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

sort: votes


text:
StoreProhibited error while trying to read file to PROGMEM
I'm trying to read a file from micro SD on an ESP32-cam board and upload to an FTP server, but when I try to read data from the opened file to an unsigned char, it gives me the following error:
Guru Meditation Error: Core  1 panic'ed (StoreProhibited). Exception was unhandled.
Core 1 register dump:
PC      : 0x4008c674  PS      : 0x00060030  A0      : 0x800ed1c7  A1      : 0x3ffb1e20
A2      : 0x00000000  A3      : 0x3ffd7c78  A4      : 0x00000080  A5      : 0x00000000
A6      : 0x474e5089  A7      : 0x0a1a0a0d  A8      : 0x00000000  A9      : 0x3ffb1df0
A10     : 0x00000080  A11     : 0x3ffb66e4  A12     : 0x3ffd7c78  A13     : 0x00000080
A14     : 0x00002494  A15     : 0xff000000  SAR     : 0x00000018  EXCCAUSE: 0x0000001d
EXCVADDR: 0x00000000  LBEG    : 0x4008c670  LEND    : 0x4008c68c  LCOUNT  : 0x00000007

ELF file SHA256: 0000000000000000

Backtrace: 0x4008c674:0x3ffb1e20 0x400ed1c4:0x3ffb1e30 0x400ed245:0x3ffb1e60 0x400d06e7:0x3ffb1e80 0x400d084f:0x3ffb1f20 0x400d2b5a:0x3ffb1fb0 0x4008efde:0x3ffb1fd0

Rebooting...

The code is the following:
// Wifi and FTP Client Lib
#include <WiFi.h>
#include <WiFiClient.h>
#include "ESP32_FTPClient.h"

// MicroSD
#include "driver/sdmmc_host.h"
#include "driver/sdmmc_defs.h"
#include "sdmmc_cmd.h"
#include "esp_vfs_fat.h"

// FTP Server credentials
char ftp_server[] = "192.168.1.50";
char ftp_user[]   = "username";
char ftp_pass[]   = "password";

// wifi access
const char* ssid = "ssid";
const char* password = "psk";

// file to be read and uploaded
FILE *fileUpload = NULL;

// ftp client object
ESP32_FTPClient ftp (ftp_server, ftp_user, ftp_pass);

// micro sd initialization
static esp_err_t init_sdcard()
{
  esp_err_t ret = ESP_FAIL;
  sdmmc_host_t host = SDMMC_HOST_DEFAULT();
  sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT();
  esp_vfs_fat_sdmmc_mount_config_t mount_config = {
    .format_if_mount_failed = false,
    .max_files = 10,
  };
  sdmmc_card_t *card;
  ret = esp_vfs_fat_sdmmc_mount("/sdcard", &host, &slot_config, &mount_config, &card);
}

void FTP_upload( void );
void FTP_upload()
{

  // initialize file name
  char fileName[100];
  sprintf(fileName, "/sdcard/img.png");
  fileUpload = fopen(fileName, "r+");

  // notify reading of the file
  Serial.print("Reading file: ");
  Serial.println(fileName);
  if (fileUpload == NULL)
  {
    Serial.println("Cannot open file");
    return;
  }

  // retrieve file size
  fseek(fileUpload, 0, SEEK_END);
  long int size = ftell(fileUpload);
  fclose(fileUpload);

  // print file size to serial
  Serial.print("File size: ");
  Serial.println(size);

  // Reading data to array of unsigned chars
  fileUpload = fopen(fileName, "r+");
  unsigned char * in PROGMEM = (unsigned char *) malloc(size);

  // display allocated memory
  Serial.print("Allocated memory: ");
  Serial.println(sizeof(in));

  // read file to allocated memory
  int bytes_read = fread(in, sizeof(unsigned char), size, fileUpload); // <------- THIS ROW RISES THE ERROR

// close file
  fclose(fileUpload);

  // Open FTP connection
  Serial.println("Starting FTP upload...");
  ftp.OpenConnection();

  //Create a file and write the image data to it;
  ftp.InitFile("Type I");

  // change remote directory
  ftp.ChangeWorkDir("/Shared/");

  // specify remote file name
  String strNome = "img.png";

  // convert String to char
  const char *f_name = strNome.c_str();

  // create a new file with the given name inside the remote directory
  ftp.NewFile( f_name );

  // write data read above from local file to remote file
  ftp.WriteData(in, sizeof(in));

  // close remote file
  ftp.CloseFile();

  // notify completed upload
  Serial.println("File uploaded successfully");

  // wait
  delay(100);

}

void setup() {

  // begin serial communication
  Serial.begin(115200);

  // initialize micro sd
  esp_err_t errSD = init_sdcard();
  if (errSD != ESP_OK) {
    Serial.printf("Cannot initialize SD. Error code: 0x%x", errSD);
    return;
  }

  // begin wifi connection
  WiFi.begin(ssid, password);

  // wait for the connection to be estabilished
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  // notify successful connection
  Serial.println("");
  Serial.println("WiFi connected");

  // show the assigned IP
  Serial.print("IP: ");
  Serial.println(WiFi.localIP());

  // call the FTP upload procedure
  FTP_upload();

}

void loop() {
  // empty
}

How can I solve this? Thank you

This line doesn't make sense to me: unsigned char * in PROGMEM = (unsigned char *) malloc(size); Either it's in PROGMEM, or it's on the heap. It can't be both. [I don't think that's your problem though, since PROGMEM doesn't exist on the ESP32 ASFAIK]

Heh, that's all we need: progmalloc().  Or is it malloc_P() ? =)  I haven't checked the ESP32, but usually non-AVR cores have dummy F(), PSTR(), PROGMEM, pgm_read_whatever, etc  that just put things the only address space they have.  So there's kind of a notion of having them in the sense that they don't cause errors for unrecognized identifiers.

@timemage That's exactly what I think, yes. In the program above, it may not do anything, but it's just wrong. The data needs to be read to the normal RAM.

@PMF, ah, that makes sense. I'd had a different reading of it before.

@PMF yes sorry, that was an error that I missed, indeed. Removing PROGMEM didn't change anything though. @timemage what do you mean? I successfully used malloc in another code, so I can confirm it gets recognized by the ESP32 core.

Is sizeof(unsigned char) = 1? If it was not, this would explain the crash.

@PMF, for char, regardless of how signedness is (or isn't) specified, sizeof will always yield 1.  It's sort of definitional in the standard.  Basically, the way it's specified, what sizeof returns is the number of char needed to represent something where char is made synonymous with "byte", regardless of whether or not bytes are octets.

@timemage Thanks for the explanation. I wasn't sure about this any more. I'm mainly a C# programmer, where sizeof(char) is just not 1, because strings are by definition unicode.

Solved, I changed the method a little.
In a loop, I read a portion of the file and write it to the opened FTP remote file, then I close both at the end of the cycle
// open FTP connection
ftp.OpenConnection();

// open local file
fileUpload = fopen("/sdcard/img.png", "r+");

// initialize file type
ftp.InitFile("Type I");

// change remote directory
ftp.ChangeWorkDir("/Shared/");

// define remote file name
String strName = "img.png";

// convert to char
const char *f_name = strName.c_str();

// create remote file with given name
ftp.NewFile( f_name );

// read all file in a loop
unsigned char buff[64];
while(!feof(fileUpload)){

    // read a portion of the file
    fread(buff, sizeof(char), sizeof(buff), fileUpload);

    // write that portion to the remote file
    ftp.WriteData(buff, sizeof(buff));
}

// close both the local and the remote file
fclose(fileUpload);
ftp.CloseFile();

It would be good to get a more specific explanation of the cause.  One thing you did was move away from malloc() which is a good idea.  In the process it seems you fixed a memory leak that was caused by not having a corresponding call to free().  You also got rid of ftp.WriteData(in, sizeof(in));, which was writing only the first 4 four bytes of what in points to, because sizeof (in) is the sizeof of the pointer, not the size of the allocated block.

For what remains, there's the possibility of fopen failing, which you should probably check before trying to use fileUpload.  When it comes to feof and fread it's important to know that feof doesn't tell you when you're at the end of the file.  It tells you when you tried to read past the end of the file.  So to make the loop correct, you'd need to first attempt an fread, then check to see if it failed because of an EOF condition, and then either break the loop or write the data.

@timemage The reason for this solution is that the row fread(in, sizeof(unsigned char), size, fileUpload); tries to read size elements (size is the full size of the file) and tries to put those elements in the in char, but in char has only 4 bytes, regardless the malloc function.

If you show up on freenode sometime, I'd go into what I'm thinking about that.  For here, I'll just say I think you may need to keep looking at it a bit longer.

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


text:
Decode rf remote signals with ESP32 or node MCU?
I'm trying to decide my rf remote signals using ESP32 or node MCU. I have tried with Arduino and was successful but for some reason it is not working on either ESP32 or node MCU even using the same GPIO2 pin can anyone please tell me why both the boards are not able to decode the signal. I'm using the rc-switch library to decode and a 433Mhz transmitter reciever combo from amazon

RCSwitch mySwitch = RCSwitch();

void setup() {
  Serial.begin(9600);
  mySwitch.enableReceive(0);  // Receiver on interrupt 0 => that is pin #2
}

void loop() {
  if (mySwitch.available()) {
    output(mySwitch.getReceivedValue(), mySwitch.getReceivedBitlength(), mySwitch.getReceivedDelay(), mySwitch.getReceivedRawdata(),mySwitch.getReceivedProtocol());
    mySwitch.resetAvailable();
  }
}```

Please include the wiring and your code into the question. You can edit it to add these information.

Maybe it's related with 3.3V/5V difference?

@chrisl I have also put up the code

@MichelKeijzers I used the vin pin on both the boards which provide 5v and the reciever also works on 5v so I don't this that's the case and also I used the 5v pin on Arduino just to be sure

io 0 has a pull-up resistor because it is a boot config pin and on esp the interrupt pin numbers are the same as the labels on ocb

I thought ESP32 was 3.3V (but it was just an idea it might be caused by voltage difference).

For ESP32, you should provide real GPIO number.
For instance:
mySwitch.enableReceive(13);
And without deep explanation, believe that it properly works
with GPIO 13 and 27.
Details you can find by google...


text:
Help needed with driving multiple stepper motors on arduino UNO
I am brand new to Arduino but have good experience with Raspberry Pi's and Microchips.
My problem is that I am having trouble driving many stepper motors at once. I am using the AccelStepper library(https://www.airspayce.com/mikem/arduino/AccelStepper/index.html). The code is pretty simple and I got it to work perfectly for a long time with three motors, however it had trouble running more than three motors, I have 5 motors hooked up right now and all of them vibrate or skip steps.
Can anyone help me get the 5 motors working.
Here is the code I'm running:
#include <MultiStepper.h>
#include <AccelStepper.h>
#include <Stepper.h>

AccelStepper stepper1(AccelStepper::FULL4WIRE, 8, 10, 9, 11);
AccelStepper stepper2(AccelStepper::FULL4WIRE, 4, 5, 6, 7);
AccelStepper stepper3(AccelStepper::FULL4WIRE, 12, 13, 2, 3);
AccelStepper stepper4(AccelStepper::FULL4WIRE, A0, A1, A2, A3);
AccelStepper stepper5(AccelStepper::FULL4WIRE, 0, 1, A4, A5);

void setup()
{
    //Serial.begin(9600);
    pinMode(0, OUTPUT);
    pinMode(1, OUTPUT);
    pinMode(A0, OUTPUT);
    pinMode(A1, OUTPUT);
    pinMode(A2, OUTPUT);
    pinMode(A3, OUTPUT);
    pinMode(A4, OUTPUT);
    pinMode(A5, OUTPUT);
    Serial.print(" a0:");
    Serial.print(digitalRead(A0));
    stepper1.setMaxSpeed(600.0);
    stepper1.setAcceleration(50.0);
    stepper1.moveTo(3240);

    stepper2.setMaxSpeed(50);
    stepper2.setAcceleration(1);
    stepper2.moveTo(800);

    stepper3.setMaxSpeed(300.0);
    stepper3.setAcceleration(200.0);
    stepper3.moveTo(1500);

    stepper4.setMaxSpeed(300.0);
    stepper4.setAcceleration(200.0);
    stepper4.moveTo(1500000);

    stepper5.setMaxSpeed(300.0);
    stepper5.setAcceleration(200.0);
    stepper5.moveTo(1500000);
}
void loop()
{
    // Change direction at the limits

    if (stepper1.distanceToGo() == 0)
        stepper1.moveTo(-stepper1.currentPosition());
    if (stepper2.distanceToGo() == 0)
        stepper2.moveTo(-stepper2.currentPosition());
    if (stepper3.distanceToGo() == 0)
        stepper3.moveTo(-stepper3.currentPosition());
    if (stepper4.distanceToGo() == 0)
        stepper4.moveTo(-stepper4.currentPosition());
    if (stepper5.distanceToGo() == 0)
        stepper5.moveTo(-stepper5.currentPosition());
    stepper1.run();
    stepper2.run();
    stepper3.run();
    stepper4.run();
    stepper5.run();
}

I don't think it is the code that is the problem because as I stated before it worked with three motors just fine and the code for 4 and 5 is just copy paste.
I think it could be a power problem, I have a wall outlet that can convert to a range of dc voltages between 3 and 12, at 5V the motors are clearly lacking the power to run. At 6V they do turn on but dont work well at all(as I stated above) and at 7.5V the Arduino seems to continually restart: the motors start for just a second.
Here are the 28BYJ-48 motors with drivers I bought from amazon: https://www.amazon.com/gp/product/B01CP18J4A/ref=ppx_yo_dt_b_asin_title_o02_s00?ie=UTF8&psc=1
Can anyone explain to me why it restarts at 7.5 volts? I've read that the minimum power should be around 7 volts so this doesn't make sense to me.
Appreciate any help I can get, please remember I'm new to this. Thank you.

How is this all wired up? How much power can your supply deliver and how much do the motors need?

@Mat The motors connect to the drivers plug-and-play and the wiring from the drivers to the board can be seen in lines 4-7 of the code. The power to the boards is gotten from the 5V pin of the Arduino and the ground  is also from the Arduino. Amazon states that the motors are rated at 5V. Finally Mat if you read my paragraph above you can see how my power supply works

You're only talking volts. That's not enough, you need amps too to deliver watts (i.e. power).

pins 0 and 1 are used for Serial

@jsotla, they are only used for serial if you have a serial begin statement in your code

@Mat Do I have enough amps to run both the Arduino and the motors?


text:
Unexpected output for simple code involving calculating a time interval of 10ms
I had written some code that involved doing something after 10 milliseconds had elapsed, however it was performing unexpectedly. Upon debugging, I think I have identified the error, and I wrote some code with just that block:
unsigned long int newtime=0;
unsigned long int prevtime=0;
int time;
void setup()
{
  Serial.begin(9600);
}

void loop()
{
newtime=millis();
time=newtime-prevtime;
if(time==10){
  Serial.println(prevtime);
  prevtime+=10;
}

}

The serial monitor "freezes on 150. it shows the values 0,10,20...as expected but it freezes on 150...and then nothing happens.
What exactly is causing this?

You should not relay on that if statement to be called once ever millisecond. Check for >= instead

i didnt properly understand your first comment...

In my original program, I was doing something when exactly 10 milliseconds had elapsed..

Your sketch requires that the if statement is called ever millisecond. If timeis 9 in one iteration and 11 in the next iteration, then the code in the if block will never be executed.

"when exactly 10 milliseconds" - you can't do it this way, you have to check if at leaest 10 ms have elapsed. If you need exact timing you have to use interrupts.

10 not 1. and also, since i am resetting the value of prevtime, the value of the variable time cannot exceed 10

I would say with a frequency of every 10ms you fill up the Serial buffer pretty fast. You could try using a higher baudrate (for example 115200)

just to add on, the code works perfectly fine when I replace 10 with 100.

If (for whatever reason) your loop takes slightly more than 1 millisecond, then there is a chance that the if statement misses the moment when time==10 and the if clause will never become true. At least not before millis() ran over.

@chrisl You are right...it works with that baud rate

The problem is, that you are filling up the Serial buffer rather fast, because you try to send ASCII numbers every 10ms at only 9600ms. When the buffer is full, Serial.println() will wait, until there is enough space free in the buffer for the current data. That makes your loop lasting significantly longer.
In that case the time, where the time is exactly 10 is missed. Thus the code does nothing at that point, until time rolls over and gets 10 again (48 days I think).
While you can mitigate the problem by using a higher baudrate, the main problem is still
if(time==10){

You have only provided an example code. Your real code might sometimes take longer than 10ms out of some other reason (actually this already gets critical, when the loop takes longer than 1ms, since it then might already miss the one moment, where time is 10). To futureproof your code and make sure, that you don't hunt down the same bug again and again, you should do, what you were told in the comments, and use
if(time>=10){

Depending on your code the event will still happen after 10ms the absolute most of the time. But this variant also doesn't break, if the loop takes longer than 10ms sometimes.

"might sometimes take longer than 10ms" - actually the if(time==10) version becomes critical as soon as loop() takes longer than 1 ms, because it has to compare time with ever tick of millis() ;)

@SimSon You are totally right. I will add that to the answer

your logic is just tricky to confuse. It is repeatable because along as you not change the if logic, the code is going to run till it displays 150. then it will stop. You can also check the same behaviour here
Once the time difference is not exactly equal to 10, the if part will not be executed. Hence, the prevtime will not catch up with the newtime anymore. newTime will soon grow to be bigger and the difference will always be greater than 10.
I suggest visiting https://www.arduino.cc/en/Tutorial/BuiltInExamples/BlinkWithoutDelay to get some hints on tracking time in a safer way.


text:
How do I make my Arduino do a specific action when the computer is locked/unlocked?
I have a windows computer connected to my Arduino Uno. I work in a area with a bunch of cubicles and we leave our desk fairly regularly to go and troubleshoot other computers (I'm a service desk technician).
When we leave we are instructed to raise and lower a small flag so management can see whether or not we are sitting at our desk. I've attached my arduino to a servo motor with the following code.

#include <Servo.h>

Servo myservo;  // create servo object to control a servo
#define servoPin 3 //~
#define pushButtonPin 2

int angle =0;    // initial angle  for servo
int angleStep =20;
const int minAngle = 0;
const int maxAngle = 90;

int buttonPushed =0;

void setup() {
  // Servo button demo by Robojax.com
  Serial.begin(9600);          //  setup serial
  myservo.attach(servoPin);  // attaches the servo on pin 3 to the servo object
  pinMode(pushButtonPin,INPUT_PULLUP);
   Serial.println("Nathan's Status flag");
}

void loop() {
  if(digitalRead(pushButtonPin) == LOW){
    buttonPushed = 1;
  }
   if( buttonPushed ){
  // change the angle for next time through the loop:
  angle = angle + angleStep;

    // reverse the direction of the moving at the ends of the angle:
    if (angle <= minAngle || angle >= maxAngle) {
      angleStep = -angleStep;
       buttonPushed = 0;
    }
    myservo.write(angle); // move the servo to desired angle
      Serial.print("Moved to: ");
      Serial.print(angle);   // print the angle
      Serial.println(" degree");
  delay(100); // waits for the servo to get there
   }
}

We also have a policy that we need to keep our computers locked for obvious reasons. I learned my lesson with that early on. I would like to edit my code so that when I lock my computer the flag goes down, then when my computer is unlocked it goes back up. That way as long as I remember to keep my computer locked when I'm away I don't have to worry about the flag. Here is my breadboard/arduino layout.

I also have processing on my computer and am planning on using that. (https://processing.org/)
Any help is greatly appreciated.

The aspect of detecting whether or not the computer is currently locked from within Processing is probably better asked on the regular stackexchange.  If there's a specific question having to do with the Arduino side running the servo your question could be about that.

you could try reversing the sequence of events ... maybe pressing the button at the arduino could lock the computer

https://stackoverflow.com/questions/5881887/running-a-script-before-locking-a-computer-on-windows

Read a value through serial (what exactly is entirely up to you) to do the same job the button does now.
Use Serial.read() to get that data, and Serial.available() to know if there is any data to read.
How you generate that value on the PC to send through serial we cannot help you with, as that is outside the scope of this site.


text:
Why is my Arduino Nano's buzzer clicking?

EDIT: I'm so sorry but the clicking wasn't coming from the Arduino but from the piezo buzzer! I was wrong and I'm so sorry for misguiding you!
I recently bought an Arduino Nano so that I could downsize my arrangement with my Arduino Uno so I soldered everything together and when I plugged in the Nano I extra made sure that nothing was shorting each other out. But the buzzer attached to it kept making this clicking noise. Does anyone know why? Do I actually have a short-circuit?
Here is the code:

#define LED 1
#define twoLED 2
#define threeLED 4
#define fourLED 5
#define fiveLED 6
#define sixLED 7
#define sevenLED 8
#define eightLED 9
#define nineLED 10
#define tenLED 11

int state = 0;
int old = 0;
int buttonPoll = 0;

void setup() {
  pinMode (3,INPUT);
  pinMode (11,OUTPUT);
  pinMode(LED, OUTPUT);
  pinMode(twoLED, OUTPUT);
  pinMode(threeLED, OUTPUT);
  pinMode(fourLED, OUTPUT);
  pinMode(fiveLED, OUTPUT);
  pinMode(sixLED, OUTPUT);
  pinMode(sevenLED, OUTPUT);
  pinMode(eightLED, OUTPUT);
  pinMode(nineLED, OUTPUT);
  pinMode(tenLED, OUTPUT);

  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

}

void loop() {

while (state == old)
{
  buttonPoll = digitalRead (3);
  if (buttonPoll ==1)
  {
    delay (50);
    buttonPoll = digitalRead (3);
    if (buttonPoll == 0)
    {
      state = old + 1;
    }
  }
  else
  {
    delay(100);
  }

  switch (state)
  {
    case 1:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 2:
      digitalWrite(LED, HIGH);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 3:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

case 4:
      digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 5:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

case 6:

  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
    old = state;
    break;

    case 7:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

case 8:
  digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 9:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

case 10:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 11:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

    case 12:
        digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 13:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;
case 14:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 15:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

case 16:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 17:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

case 18:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, LOW);
   old = state;
    break;

  case 19:
    digitalWrite(LED, HIGH);
  digitalWrite(twoLED,HIGH);
  digitalWrite(threeLED,HIGH);
  digitalWrite(fourLED, HIGH);
  digitalWrite(fiveLED, HIGH);
  digitalWrite(sixLED, HIGH);
  digitalWrite(sevenLED, HIGH);
  digitalWrite(eightLED, HIGH);
  digitalWrite(nineLED, HIGH);
  digitalWrite(tenLED, HIGH);

      tone (11,493.88);
      delay(150);

      tone(11, 523.25);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11,329.63);
      delay(150);

      tone(11, 261.63);
      delay(150);

      tone(11, 246.94);
      delay(150);

      tone (11,196.00);
      delay(150);

      tone(11, 246.94);
      delay(150);

      tone(11, 261.63);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11, 523.25);
      delay(150);

      tone (11,493.88);
      delay(150);

      tone(11,493.88);
      delay(150);

      tone(11,392.00);
      delay(150);

      tone(11, 329.63);
      delay(150);

noTone(11);

old = state;
state = 0;
old = 0;

    break;

    default:
  digitalWrite(LED, LOW);
  digitalWrite(twoLED,LOW);
  digitalWrite(threeLED,LOW);
  digitalWrite(fourLED, LOW);
  digitalWrite(fiveLED, LOW);
  digitalWrite(sixLED, LOW);
  digitalWrite(sevenLED, LOW);
  digitalWrite(eightLED, LOW);
  digitalWrite(nineLED, LOW);
  digitalWrite(tenLED, LOW);

    old = 0;

    break;
}

}

  }

Here is a video of the clicking:
https://drive.google.com/file/d/1TprL56p2YyJ3j8cq43U2LYzaWofZpJM7/view?usp=sharing

Uhh, I want to see this. =)  Maybe hear it also.

Not-so-good ceramic capacitors have been known to sing/click...  Does the NANO work or not work at this point?

How could I show it to you?

Well, I've tried it out and not much seemed to work

are you certain that the Nano is clicking? ... maybe the power supply is making the noise

I'm pretty sure it's the Arduino. I connected it to my computer and my computer has never made that sound before.

What's the nature of the clicking? Can you describe it as like a sound that might be familiar? Is it clicking at a steady continuous rate? Just once after power up? Since you soldered it yourself, I would at least check the soldering under a magnifier and check for solder bridges (shorts). You could take a close picture with your phone, making sure it's clear, and post it.

Please post a clear picture. It’s very hard to see if there’s a problem otherwise.

Here, I've uploaded a video of the clicking: https://drive.google.com/file/d/1TprL56p2YyJ3j8cq43U2LYzaWofZpJM7/view?usp=sharing

@Éemia, need to get a public link for it.

Oops, you're right, there, I've updated it.

The simpler piezos click when a voltage is applied, and again when it is removed. To make it buzz, it needs a pulse-train: many clicks makes a buzz. There are piezos that have that feature built-in, but I'm guessing yours hasn't. That's actually a Good Thing in disguise: it allows you to make tones by making pulse-trains at different frequencies. The easiest way to do that is to connect it to one of the PWM pins (5, 6, 9, 10, or 11) and use the tone() library-function (look it up if you need to). Of course, you can do it "manually", too, on any output pin, just by switching it HIGH and LOW at rates that you choose, but that will pretty much tie up your processor, at least for higher frequencies.
Update:

Just why wasn't it clicking when I connected it to the Arduino Uno?

I can't tell without seeing the two sketches but in your video, it sounds like it is being turned on or off, or pulsed, once per second.
Please add your code (both of them, if they're different) to your question. Wiring diagram(s) of the piezo connection to the Arduino boards would help, too.

Thanks so much for your information! Just why wasn't it clicking when I connected it to the Arduino Uno?

Okay, I've uploaded the code but how I wired the piezo buzzer is the simply that I connected the positive side to the digital pin (D13) and the negative side to ground, just like how you should do it according to research.

You've described wiring it to pin 13 but your calls to the tone() function address pin11. Is that an connection error or a typo? Pin 11 is indeed a PWM pin, and connecting the piezo to it should work correctly. If it really is connected to pin 13, I don't see a reason why it should click when running your program, but it might very well click during upload if your bootloader flashes the on-board LED - pin 13.

Oh right, I used pin 11 when I hooked everything up to the Arduino Uno but now I transferred everything to the Arduino Nano and I didn't modify the code. Still, I can't even upload the code to my Arduino Nano. It keeps saying that there is an error. Thanks for your comment!

Please add the error message to your question, and be sure both "Show verbose output" boxes in the IDE preferences are ticked when you run the compilation and upload.


text:
Why ATMEGA328P U-TH doesn't answer to USBasp but work fine with Arduino as ISP?
I ordered ATMEGA328P AU from China recent but I got "ATMEGA328P U-TH". which seem super problematic.
I try to use USBasp to burn bootloader but it fail and show error message as shown.
avrdude: error: program enable: target doesn't answer. 1
avrdude: initialization failed, rc=-1
     Double check connections and try again, or use -F to override
     this check.

which I believed many people face same situation as mine. Then I accidentally found the solution by using Arduino as ISP which successfully birn bootloader. After that I can use USBasp to upload sketch or burn bootloader.  I don't understand what happen here.
Note: I solder ATMEGA328P U-TH in SMD package to Arduino UNO clone.

If you want to upload a sketch via any other interface than ISP, the atmega needs a bootloader.
The bootloader basically is a piece of software which is stored in a dedicated flash section, the "bootloader section". Code stored in this bootloader section has the special ability to write to parts of flash memory where the actual program is stored (this is called the "application section").
In general, a program can not overwrite its own flash section, so the bootloader and the application need to be stored in different sections/partitions.
In principle, a bootloader can do whatever a normal sketch could do: toggle pins, access eeprom, read UART/I2C/etc... and as it can also write to the "application section", you can make it read data from any interface and transfer it to the application section.
This is what happens if you upload code via USBasp (Arduinos have a USB-to-UART converter on board).
But of course, this requires that a bootloader is installed.
avrdude: error: program enable: target doesn't answer. 1 - this might sound misleading, what it actually means is, that the bootloader doesn't answer. That makes sense, as the device doesn't have a bootloader.
When there is no bootloader, the only way to upload code is to use ISP, which doesn't need any software to function. It's a hardware functionality that Atmel implements in silicon.
A code upload via ISP works in (almost) any case.

Both usb-asp and Arduino as ISP is the programmer which be able to upload sketch either bootloader. In my question it do the same job to uploader but the chip not answer to usbasp but it work fine with arduino as isp.
my inspectation is is about factory setting clock speed of the chip the corelate to programmer clock speed. but still no clue.

I think bootloader only use with stk500  Serial UART protocol  upload.


text:
Is it possible to read extended ASCII from the serial port?
My project requires that Serial.read() be able to accept extended ASCII characters (0x80 <=> 0xFF). For example, I would expect reading the character ¥ to yield the decimal value 157. Instead, the read() command has two successful reads, with the values: 194 and 165. Of course, I could create a lookup table and convert, but this is not a viable option. I am conforming to the Grbl standard protocol, which uses these single-byte extended ASCII characters as interrupts. Such a two-byte structure precludes a simple peek/read approach necessitated by the protocol.
Edit I tried to simplify the question for this context, but failed to account for the fact that the Arduino IDE will send the input as Unicode. Regardless, it still does not work when sending bytes directly. Namely, if I send the byte 0x93 via C# as Serial.Write("\u0093"), the Arduino's Serial.read() does not see any bytes available. Sending normal ASCII, e.g., Serial.Write("\u0018"), works fine.

the serial port is just a pipe ... what you stuff into it is up to you ... normally, the serial port carries 8 bit data (bytes) ... what that data means to you is not known to the serial port ... if you see two bytes then you are probably transmitting UNICODE, not ASCII ... anyway, it has nothing to do with the serial port

@jsotola silly me; I tried to simplify the question by using the IDE. I have edited the question to reflect that it is also not working when I send bytes directly, e.g., using the C# SerialPort class.

Your edited question is now a question about C#, not about Arduino. You have to ask “How do I send 0x93 through a serial port in C#?” in a more appropriate venue.

@EdgarBonet if you have an agnostic way to easily send/receive bytes directly from the serial port, I'm all ears. I'm unfamiliar with any shell-ish way to do so, and thus was using these proxies.

I do not know C#, and I do not know what you mean by “agnostic”. If by “shell-ish” you mean “from a Unix shell”, the following works in bash: echo -ne '\x93' > /dev/ttyACM0. But then, again, this is not about Arduino, it's about the shell/environment/programming language of your choice.

By agnostic, I mean exactly what you're saying — how can this be tested without introducing the corrupting influence of the shell/programming language, etc? Because the shell command is exhibiting the exact same problem as C# (Serial.available() == 0).

See Disable Reset when Com Port Connected/Disconnected

Yes, of course, you can read any byte sequence. As you have experienced,
if you send the byte values 194 and 165, your Arduino reliably reads 194
and 165.
Now, you have to be aware that there are tons of incompatible character
encodings that could all be called “extended ASCII”. I do not know which
one you have in mind. Maybe there is such an encoding where “¥” has the
code point 157. Nowadays, however, almost any modern computer system
uses Unicode, and serializes the characters using UTF-8. The character
“¥” is serialized in UTF-8 as the pair of bytes 194 and 165.
If you want to use the Grbl protocol, send interrupts as bytes, do not
think about them as “characters”.

Ack, of course I forgot to account for the IDE using unicode. Please see the edited question. Also, please note that I defined "extended ASCII" in the OP.

@ZaneClaes: If by “extended ASCII” you mean the byte range 0x80–0xff, that's not what most people call “extended ASCII”. In general, these words are taken to mean any of a myriad character encodings (generally 8-bit encodings) that are ASCII-compatible, and thus “extend” ASCII. If you “expect reading the character ¥ to yield the decimal value 157”, then you are thinking of one such encoding.

the fact that the phrase can have multiple interpretations is precisely why I clarified the exact value range I was talking about ;) The Grbl docs comments call these interrupts "extended ascii," so I was merely copying their convention.


text:
Simulate motor encoder quadrature signals using an Arduino UNO
I'm supposed to write a raspberry pi and arduino code to read the RPM of a motor with an encoder attached to it. However, I'm having weird numbers and I'm unsure about the specs on the motor and the encoder. So I thought it would be smart to use a second arduino to simulate the motor with encoder.
The simulator would need to produce a 2 signals representing the two signals from the encoder. I want to be able to set the frequency and phase shift of these signals in software to imitate changes in speed and direction of the motor rotation. Forward would have one signal 90 degrees ahead, and then reverse having that same signal to be 90 degrees behind. So phase difference of plus or minus 90 degrees.
I'd like to eventually have the simulator be able to simulate motor actions like oscillating between forward and reverse 5 seconds each, or forward for 5 seconds and then stop completely.
I found this code by bigjosh which is more or less what I want to do. However, that code doesn't allow for a shift of -90 deg by default. I know there's a comment there to change it, but I'm not knowledgeable enough to understand what's going on exactly. I'd like someone to help me with that.

what is your question? ... this site is a Q&A site, not a forum, and not a brainstorming site

Wow, that turned out to be way harder than I expected. It is very hard to do cleanly on the AVR timer. But I was able to come up with this working function, which I think is what you are looking for...
// freq_hz is frequency in hertz from 122 to 4,000,000
// shift_deg is phase shift between output A and output B in degrees (values outside -180 to +180 are normalized)

// Note that at frequencies above 44KHz you will loose precision on phase shift. At 4Mhz, everything is rounded to just 0 or +/-90 degrees.
// Note that all timing happens in 1/16Mhz increments, so frequencies that do not land on integer multipules of that will be aproximiate.
// Use startWaveforms() directly for more precise control.

void startQuadrature( unsigned long freq_hz , int shift_deg  );

It can glitch at start-up, shutdown, and changes in speed and direction... but so can a motor encoder so I guess that is ok. It would be possible to create a glitch-free version but more work.
Github repo here...
https://github.com/bigjosh/Quadrature
So, to simulate a motor going forward with 50KHz pulse rate, you would use something like...
startQuadrature( 50000 , +90);
...and the same pulse rate going backwards would be...
startQuadrature( 50000 , -90);
Do note that if you connect an Arduino UNO output pin to a Raspberry Pi input pin that it will likely damage the Pi. This is because the UNO outputs 5 volts for a "1" signal, but the Pi can only tolerate a maximum 3.3V on any pin. You can google "5V 3.3V level shifting" for solutions to this problem.

Wow! Thank you so much! I can't believe you actually went all out like that! Much appreciated honestly.
I have a couple of questions:

Are you using a program to simulate the arduino and oscilloscope or are you using real hardware and taking snapshots?
I'm actually getting a lot of glitches that is making this extremely unstable. To the point that it's not working out for me at all. I'm not sure if this is error on my side (receiving arduino) or the hardware cannot do much better.

Thanks again!
For voltage level shifting, I was gonna use resistors until I buy a proper module

@krusion, if you found it useful you should vote it up.

bigjosh - Nice work!  I just dl'd the repo and tried it on a spare Uno here - works like a charm, once I got all my stupidities cleared up ;-)

@user3765883, that indicates it makes sense to "accept" it as the answer.


text:
unexpected behaviour of encoder with increasing rpm
I am using a DC motor with encoder, and I am trying to calculate how many pulses are  recorded in every one second interval. (note that the power source is of 12V for the motor)
Circuit and code:

int encpin=3;
volatile long npc=0; //new pulse count
volatile long opc=0;  //original pulse count
volatile long pulsecount;
unsigned long int newtime;
unsigned long int prevtime=0;
unsigned long int time;
void setup()
{
  pinMode(encpin, INPUT_PULLUP);
  Serial.begin(9600);
  attachInterrupt(digitalPinToInterrupt(encpin),function,RISING);
}
void function(){
  npc++;
}
void loop()
{
 newtime=millis();
 time=newtime-prevtime;
 pulsecount=npc-opc;
  if(time==1000){
    Serial.println(pulsecount);
    prevtime+=1000;
    opc=npc;
  }
}

It seems to be rather intuitive that increasing the rpm should increase the number of pulses recorded in one second. However, the results are rather erratic:
 RPM  PULSECOUNT
  26    2365
  32    2367
  38    2400
  44    2375
  52    2400
 116    2412
 142    2384
 195    2416
 280    2406
 350    3008
 416    1580
 520    1975
 624    2370
 730    2334
2737    2188

Increasing RPM sometimes increases the pulsecount, but sometimes decreases it....what could be the reason for this behaviour?

You still check for time==x? Seriously??!

I think the problem is in the tinkercad simulation:
The encoder is attached to the motor and the motor is always rotating at the same speed. Selecting a different RPM on the component changes the gear ratio and the RPM of the shaft, but not of the motor. That means that the number output after 1s should be always the same.
Why it is not exactly the same, only the programmers of the simulation can tell.
It might have to do with simulation speed, because I get totally different numbers there.
To tell exactly what is going on, a documentation of the components in the simulation and of the simulation would be necessary.

what numbers are you getting on your end? And more importantly, are they following the expected trend: i.e rising with RPM?

they are in the range of ~1600 and changing randomly depending on the RPM setting of the motor, but they are also not consistent during 1 run

One important principle to learn when working with interrupts is that of atomic operations.  It is vital, when working with any data that cannot be manipulated by one single assembly instruction, that you protect against that data being changed midway through any reading of that data.
In your situation you are working with 32-bit values. On an 8-bit microcontroller those take many many instructions to manipulate, and at any time during that manipulation the interrupt can be triggered and change the value, corrupting your readings.
There is a concept in programming called critical sections. These are "blocked off" bits of code where no interrupts are allowed to happen while you do whatever is needed to your shared variables. For obvious reasons you want to keep those sections as brief as possible.
Also you don't need to calculate the pulse count by comparing it to the previous count - just start from 0 each second. And on the topic of a second, it's best to check if at least a second has passed. There's always a chance you may see 1001ms instead of 1000ms. A slim chance, but best to be safe.
Here's an example, using your code as a base:
void loop() {

    if (millis() - prevtime >= 1000) { // you should check for more time passing than you expect
        prevtime += 1000; // Don't assume you always had 1 second, force it instead

        // This block is the "critical section". Keep it as short as possible
        // so just grab the data and reset the count.
        noInterrupts(); // Stop any interrupts happening
        uint32_t currentCount = npc; // Grab this second's count
        npc = 0; // And reset the count to zero
        interrupts(); // Release the block on interrupts

        // And output the results.
        Serial.println(currentCount);
    }

}


text:
void declaration error
I am new to Arduino and C++ and I was practicing with a traffic light project.
This is my code:
int red = 10;
int yellow = 9;
int green = 8;

void setup() {
  pinMode(red,OUTPUT);
  pinMode(yellow,OUTPUT);
  pinMode(green,OUTPUT);
}

void loop() {
  changelights();
  delay (15000);
}

void changelights{
  // 1st action: green off to yellow
  digitalWrite(green, LOW);
  digitalWrite(yellow, HIGH);
  delay (3000)
  // 2nd action: tellow to red
  digitalWrite(yellow, LOW);
  digitalWrite(red, HIGH);
  //3rd action: caution light
  digitalWrite(yellow, HIGH);
  delay (3000)
  //4th action: caution to go
  digitalWrite(red,LOW);
  digitalWrite(yellow, LOW);
  digitalWrite(green, HIGH);
}

I tried compiling it and returned an error message that said that I did not declare my "changelights" function. What should I do to fix this?
Thank you very much

I recommend to put only 1 instruction in 1 line. that improves readability by a lot and makes it easier to find errors.

You forgot the parentheses ( ) for the parameters after the definition of changelights. You need these, even if you don't provide any parameters. Though this is a pure C/C++ syntax question, thus I'm voting to close. Fixing such problems doesn't help any other people, thus I'm always helping in the comments and then vote to close.

Missing semi-colons after the delay(3000) calls.

You forgot to put the parenthenses () after the name of the function changelights. They are there to declare variables you can use later in the code like that:
void function(int a){
  a+=1;
  return a;
}

To fix your error just change
void changelights{

to
void changelights(){

Keep in mind if you want to program C++ (which would be Off-Topic here, but you mentioned it in your question) you have to declare the function in the beginning or mention it.

The Arduino IDE takes care of adding the forward declarations for you.

The problem is with the missing parentheses at the function definition. The forward declaration of the functions is done by the Arduino IDE. And I think we can assume, that he uses it. At that point working with Arduino that is the simplest way.

@chrisl I see, I will edit the answer.


text:
Arduino ADC converter calculation
I am trying to choose a wire encoder for my project. So far, I found this wire encoder (see link). Assuming the measurement range of my cylinder is 1 m. Then, with a 10 bit ADC converter of my Arduino Mega2560, I would have a resolution of 0.09cm (= 100cm/1024). But, lets say some cylinder only have a measurement range of 0.5m. Then the resolution would be 0.048 (=50cm/1024).
I can see that I am missing something here, because the resolution of the later case should be worse than the case with the full measurement range 1m. I would be appreciate for any tipps.

Edit:

Cylinder's movement range 0~1m

Wire encoder's measurement range 0~1.25m

Wire encoder's analog output 0~10v
ADC resolution 10 bit

I guess with "range of my cylinder" you mean its circumference. Then your calculation is right and logical. The ADC has a fixed resolution of 1024 steps. If you distribute these steps onto a smaller range, then it means, that the steps are closer together, thus you are getting a better resolution. Basically you are trading the distance, which is covered by one rotation, for resolution. Higher distance gives a lower resolution and vice versa. I don't see, why this should be different. If this argument didn't convince you, can you explain further, why you think it should be worse?

I meant with "range of my cylinder" the movement range of my cylinder. I added more information. But still not sure, how one should map the encoder movement to the cylinder movement...Could you guide me here a little bit?

Ok, now I don't understand your application. What actually is that cylinder? What are you trying to achieve? What is your project setup? I need a more detailed description to understand, what you are trying to do.

I added some picture to clarify further. Basically, I want to measure the cylinder movement with a wire encoder and since the output of my encoder is voltage, I would like to read in the value using an ADC converter of Arduino Mega2560. And I would like to estimate the resolution in this case...

Ah, ok, with cylinder you mean hydraulic cylinder. Haven't thought of that.

@Joe, you know this thing linked costs like 700+ USD right?  I'm not sure where you got the image from, but even if that's a cheaper one, it seems like you can still swing for a better ADC than the one built into an ATmega2560.  Or maybe one of these with a digital interface.  Otherwise, like chrisl said.

Your calculation is not correct. The encoder has its 0 to 10V output voltage distributed over the whole distance, that the cable can reach, so 1.25m. And that gives you the resolution: 1.25m/1024 = 1.22mm. The resolution doesn't change, if you use less than the maximum length. It's still the same resolution of about 1.22mm. The encoder doesn't care, if you are only using 1m of its range.

But if you try to write the code: 1) with full range 1.25m cylinder_pos = map( analogRead(A0), 0, 1023, 0, 1.25 ) 2) with only 0.5m range cylinder_pos = map( analogRead(A0), 0, 1023, 0, 0.5 ). It matters right?

Only, if you speak about a different encode, that has the range 0.5m. If you are using the encode with 1.25m range you need to use that value for the calculation


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: Interfacing MAX485 TTL-to-RS485 on serial port
I am using the ESP8266 NODEMCU.
I am aware that the CH341 on the NodeMCU is bridged to the serial pins GPIO3(Rx) and GPIO1(Tx).
Hence, any data send on Rx and Tx is also visible on the serial monitor.
I need to interface MAX485 TTL-to-RS485 to the ESP8266 on different serial pins (other than GPIO3 and GPIO1).
Is there a way to configure other pins as Rx and Tx?
Please suggest any other ways to achieve this.
EDIT-1:
I need to use two serial ports at the same time (one with the CH341 and another with TTL-to-RS485). Please help with this.

You need to use the MAX3485 on 3.3V devices.

You can't redefine pins on the ESP8266. You can, though, use SoftwareSerial to emulate a serial port. There's plenty of examples.
Also you need to use the MAX3485 on 3.3V devices. The MAX485 is for 5V devices.

I get the MAX3485 part. However, my main problem is to use two serial ports at the same time (one with the CH341 and another with MAX3485). Need help with this problem.

Regarding this:

Please suggest any other ways to achieve this.

The SoftwareSerial mention in Majenko's answer is one of those other ways.
There's also a .swap() function on the Serial interface that will remap the UART from its normal position talking to the host to GPIO15 and GPIO13.  If you only need to talk to one device at a time, that may also be an option.
There's also a second transmit-only UART (also mentioned in previous link), so if you only need to transmit on one of the interfaces, that is an option.  And there's the possibility of using the transmit-only UART together with using SoftwareSerial (or something like it) to complete the receive half.
Another option might be interpose a SPI-interfaced UART chip, between the ESP8266 and the RS485 transceiver, so that it's just SPI from the ESP8266 side.  It is also possible to find chips that are combined SPI-UART/RS485-transceiver, although the only one I've noticed thus far is a 5V part.


text:
LED not lighting up despite digitalRead displaying 1
As part of a project, I created a simulation of a juncture with 4 traffic signals. The time for the green signal is set based on a function that calculates it based on an algorithm (and it takes the no. of cars, motorcycles, buses and trucks as input).
The number of vehicles in the actual project is calculated using deep learning methods, however for the purpose of the simulation, I am using random() to generate these.
Layout of the entire process

The green light of the current signal stays on for gst(green signal time) seconds, and the red light stays on for the rest of the signals.
When gst seconds have elapsed, the green light of the current signal changes to yellow. Rest all are still red.
The yellow light is intended to stay on for 5 seconds. In these 5 seconds, the gst for the next signal is calculated.
5 seconds after step 3, the yellow signal turns to red, and the next signal turns from red to green, (for an amount that has been calculated).
This process keeps continuing. When we reach the 4th signal, the next signal should be set to 1.

Code explanation

gst has been initialised to 20, and sn (current signal no.) has been initialised to 1.

The if block for calculating the next signal number (and next2next,next2next2next) , is in lieu with point 5.

signal is an array that contains all the LED pins. The colours red,yellow,green have been attributed numbers 0,1,2 , so that the pin number of the "colour" LED of the "ith" signal can be given be signal[i-1][colour]

eg: "red" LED of the "2nd" signal is given by pin signal[1][0], i.e pin 5 .
Wiring and code

int gst=20; //green signal time
int ns=4;  //no.of signals
int sn=1; //current signal number

//pin numbers for LEDS: {{RYG for signal1},{RYG forr signal2}..}
int signal[4][3]={{2,3,4},{5,6,7},{8,9,10},{11,12,13}};

//indexes for the signal array
int red=0;
int yellow=1;
int green=2;

//pin number of "colour" of signal "i" is given by signal[i][colour]
//example: red led of signal 3: signal[2][0]

int c; //cars
int b; //buses
int m; //motorcycle
int t; //trucks

void setup()
{
  for(int i=2;i<=13;i++){
    pinMode(i,OUTPUT);
  }
  Serial.begin(9600);
  randomSeed(analogRead(0));
}

void loop()
{
    int next_sn= sn+1; //next signal
    if(next_sn==5)
      next_sn=1;

    int next2_sn= next_sn+1; //next2next
    if(next2_sn==5)
      next2_sn=1;

    int next3_sn= next2_sn+1; //next2next2next
     if(next3_sn==5)
      next3_sn=1;

   //current signal green (for gst seconds), rest all red.

    digitalWrite(signal[sn-1][green],HIGH);
    digitalWrite(signal[sn-1][red],LOW); //this line will make sense
                                      //for the 2nd iteration

    digitalWrite(signal[next_sn-1][red],HIGH);
    digitalWrite(signal[next2_sn-1][red],HIGH);
    digitalWrite(signal[next3_sn-1][red],HIGH);

    //for debugging purposes

    Serial.println(digitalRead(signal[sn-1][green]));

    delay(gst*1000);

    //gst seconds elapsed, now current signal should become yellow

    digitalWrite(signal[sn-1][green],LOW);
    digitalWrite(signal[sn-1][yellow],HIGH);

    delay(5*1000);

    //snapshot taken for calculating no. of cars, buses etc
    //for now, random numbers used

     c=random(10,17);
     m=random(5,10);
     b=random(0,5);
     t=random(0,5);

     //calculate gst

     gst=calc_gst(c,m,b,t);

  //make current signal red

    digitalWrite(signal[sn-1][red],HIGH);
    digitalWrite(signal[sn-1][yellow],LOW);

  //the next signal is our current signal for the next iteration
  //the green signal should turns on for gst seconds in the next
  //iteration,and the red signal turns off
    sn=next_sn;

  }

//function for calculating green signal time

int calc_gst(int c,int m,int b,int t)  //car bus motorcycle truck
{

int vehicle[4]={c,m,b,t};
int avgtime[4]={2,1,2.5,2.5};
int x=0;
for(int i=0;i<4;i++){
x+=vehicle[i]*avgtime[i];
int gst= x/(ns+1);
return gst;

}

}

Problems
At the start of the simulation, the green light of the first signal is not lighting up. (However Rest three are red, rightly so). After 20 seconds, the first signal turns yellow correctly. Then after 5 seconds, the second signal turns green correctly, but the first signal doesn't turn red. Subsequently, there are many instances where only 3 LEDs in total are lighting up instead of 4.
For testing why the green light is not lighting up, I added a line:
    //for debugging purposes
    Serial.println(digitalRead((3*(sn-1)+green)));

The serial monitor shows 1, so why is the LED not lighting up??
If there are any suggestions/corrections in my process, I will be obliged if someone can point it out.My code is heavily commented, and it explains it the entire process.
Tinkercad link if anyone wants to try out the simulation: https://www.tinkercad.com/things/1Le8m5ouHPc

alright, but any clue why the green LED isnt lighting up immediately? Your suggestion will definitely help "clean up the code", but even with my code, digitalRead()..is 1, and yet the LED does not light up..

following your advice, I have edited the code and have used a 2D array, hopefully that makes it easier..

reduce your code to light all of the LEDs  in setup() ... you will find that top left red and green do not light .... you did not connect the resistors to ground for those two LEDs ... this is a Tinkercad problem that would not happen in real life

I see...what fix do you suggest?

what do you mean? ... you did not connect the resistors at the top end ... there is only one fix for that

one thing that would clean up the code a bit more, would be to number the traffic lights 0, 1, 2, 3

ohh goshh thats a bad blunder. The resistors aren't connected. Thanks a lot @jsotola.


text:
Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to 180 when joy is forward or back
Im trying to map a joystick to a servo but need the servo to be at 0 when the joystick is in nerural. And up to +180 when joy is forward or back.
I just cant seem to figure out the mapping or setup for the code for this part.
I remember seeing it done before but my google skils are failing me and i cant seem to find it again.
Thanks

it is a simple arithmetic problem ... convert -180 0 180 to 180 0 180

jsotola. I know it should be something simple. But cant seem to get it working.  Any help on actually doing it would be appreciated

You could map from -180 to 180 and then take the absolute value of that. I'm sure there is a function for that

use something like this if (val < 0)  val = 0 - val;

Try this one although, the others answered you properly :
#include <Servo.h>
Servo myservo;
int potpin = 1;
int val;

void setup () {
    myservo.attach(9);
}

void loop () {
    val = analogRead(potpin);
    val = map(val, 0, 1023, 0, 360);
    myservo.write(val);
    delay(20);
}

Connect the signal wire of your Servomotor to PWM pin number 9 of Arduino
Connect the output of your joystick to A1 pin of your arduino
Actually i'm not sure about one of that lines and i forgot the correct form, if didn't work, change this line :
val = map(val, 0, 1023, 0, 360);

To this :
val = map(val, 0, 1023, -180, 180);

I think both of them works
Good luck

You can use the map function, see Arduino Map Function.
So in your case, assuming a value of 0..1023 coming from an analog pin, where 0 needs to be mapped to -180 and 1023 to +180, you get
int mappedValue = map(value, 0, 1023, -180, 180);

(note I assume you mean -180 when backwards, +180 when forwards).
UPDATE
It seems value 0 (backward) needs to be mapped to 180, 512 (neutral) to 0, and 1023 (forward) to 180 (again).
For this you need two maps depending on the value:
int mappedValue = 0;
if (value < 512) // Backwards
{
    mappedValue = map(value, 0, 511, 180, 0);
}
else // Forward
{
    mappedValue = map(value, 512, 1023, 0, 180);
}

Im tyring to get the servo to move + 180 when the joy is forward.   And also +180 when the joy is pulled back. And the servo to sit at 0 when the joy is in netural. The servo im using has a range from 0-180

and what are the values of the joystick in forward, neutral and backward positions?

The joystick values are 0 for back. 1023 for forward.   Thank you


text:
I was working on ESP module and got some errors. Can anyone please help to resolve those errors?
Code;
#include <Keypad.h>
#include <Servo.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>

const char* ssid = "";//put your wifi network name here
const char* password = "";//put your wifi password here
const char* mqtt_server = "broker.hivemq.com";

WiFiClient espClient;
PubSubClient client(espClient);

const byte n_rows = 4;
const byte n_cols = 4;

char keys[n_rows][n_cols] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'}
};

byte colPins[n_rows] = {D3, D2, D1, D0};
byte rowPins[n_cols] = {D7, D6, D5, D4};

Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, n_rows, n_cols);
Servo myservo;
String passcode="";
String myPasscode="5432"; //predefined passcode, change as per your desire

void setup(){
  Serial.begin(115200);
  myservo.attach(15); //attach the servo on pin D8)
  myservo.write(150);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  client.setCallback(callback);
}

void setup_wifi() {
    delay(100);
  // We start by connecting to a 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");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {

  Serial.print("Message arrived in topic: ");
  Serial.println(topic);

  Serial.print("Message:");
  String message;

  for (int i = 0; i < length; i++) {
    //Serial.print((char)payload[i]);
    message+=(char)payload[i];
  }
  if(message==myPasscode){
    publish("Approved");
    dispatchMoney();
  }else{
    publish("Denied");
  }
  Serial.println();
  Serial.println("-----------------------");

}

void publish(String msg){

     char message[100];
     msg.toCharArray(message,100);
    client.publish("/ABC/ATM/ACK", message);
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect
    //if you MQTT broker has clientID,username and password
    //please change following line to    if (client.connect(clientId,userName,passWord))
    if (client.connect(clientId.c_str()))
    {
      Serial.println("connected");
     //once connected to MQTT broker, subscribe command if any
      client.subscribe("/ABC/ATM/RCV");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 6 seconds before retrying
      delay(6000);
    }
  }
} //end reconnect()

void loop(){

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

  char myKey = myKeypad.getKey();

  if (myKey != NULL){
    if(myKey =='#'){
      Serial.print("You entered: ");
      Serial.println(passcode);
      if(passcode == myPasscode){
        Serial.println("Your are welcome");

        dispatchMoney();

      }else{
        Serial.println("Password did not match");

      }
      passcode="";
    }else{

      passcode+=myKey;

    }
    delay(200);
  }
}

void dispatchMoney() {
  Serial.println("Dispatching money...");
  myservo.write(90); //rotates the motor counterclockwise at slow speed
  delay(5000);
  myservo.write(150); //rotates the motor counterclockwise at slow speed

}

ERROR:
sketch_apr28a.b:24:25: error: 'D3' was not declared in this scope
 byte colPins[n_rows] = {D3, D2, D1, D0};
                         ^
sketch_apr28a.b:24:29: error: 'D2' was not declared in this scope
 byte colPins[n_rows] = {D3, D2, D1, D0};
                             ^
sketch_apr28a.b:24:33: error: 'D1' was not declared in this scope
 byte colPins[n_rows] = {D3, D2, D1, D0};
                                 ^
sketch_apr28a.b:24:37: error: 'D0' was not declared in this scope
 byte colPins[n_rows] = {D3, D2, D1, D0};
                                     ^
sketch_apr28a.b:25:25: error: 'D7' was not declared in this scope
 byte rowPins[n_cols] = {D7, D6, D5, D4};
                         ^
sketch_apr28a.b:25:29: error: 'D6' was not declared in this scope
 byte rowPins[n_cols] = {D7, D6, D5, D4};
                             ^
sketch_apr28a.b:25:33: error: 'D5' was not declared in this scope
 byte rowPins[n_cols] = {D7, D6, D5, D4};
                                 ^
sketch_apr28a.b:25:37: error: 'D4' was not declared in this scope
 byte rowPins[n_cols] = {D7, D6, D5, D4};
                                     ^
sketch_apr28a.b:27:1: error: 'Keypad' does not name a type
 Keypad myKeypad = Keypad( makeKeymap(keys), rowPins, colPins, n_rows, n_cols);
 ^
C:\Users\Malini\Documents\Arduino\sketch_apr28a.b\sketch_apr28a.b.ino: In function 'void loop()':
sketch_apr28a.b:124:16: error: 'myKeypad' was not declared in this scope
   char myKey = myKeypad.getKey();
                ^
Multiple libraries were found for "Servo.h"
 Used: C:\Users\Malini\AppData\Local\Arduino15\packages\esp8266\hardware\esp8266\2.7.4\libraries\Servo
 Not used: C:\Users\Malini\Documents\Arduino\libraries\ServoESP32
 Not used: C:\Users\Malini\Downloads\Arduino\libraries\Servo
exit status 1
'D3' was not declared in this scope

select a Lolin (Wemos) or NodeMcu board in Tools menu


text:
Using millis() in unsynchronized manner
I am assuming millis() is a Timer ISR function.
If so :
When using millis() as mentioned in Arduino Reference :
unsigned long currentMillis = millis();
What would happen if the ISR asynchronously changes the value being read in a function. I mean if I have read one byte into currentMillis, but millis had changed the value before the remaining 7 bytes are read.
Cheers and TIA

Embedded systems developer? look into the source code of millis() before asking

I am assuming millis() is a Timer ISR function.

It is a function that retrieves a value that is updated by and ISR.

What would happen if the ISR asynchronously changes the value being
read in a function.

Cannot happen: the value is read with interrupts disabled.
See for example, in the AVR core:
// disable interrupts while we read timer0_millis or we might get an
// inconsistent value (e.g. in the middle of a write to timer0_millis)
cli();
m = timer0_millis;
SREG = oldSREG;

I mean if I have read one byte into currentMillis, but millis had
changed the value before the remaining 7 bytes are read.

An unsigned long is only 4 bytes. That is, until someone comes with a
64-bit Arduino platform.

Sure, a 64 bit Arduino with 2k of RAM :-)

@Edgar Bonet ,Just as an aside ( I am actually writing a millis() like function for another uC ) : Is it valid,  to say , use a lock bit to prevent read while timer is updating the variable , instead of  disabling the interrupt? Thanks much !

@EmbSysDev: There is no need to “prevent read while timer is updating the variable”: the ISR is not interruptible, so nothing can read the variable while it is being updated. You need to prevent the update while the main program is reading it.

@EdgarBonet: cli() disables all interrupts, so too many calls to millis() would affect all interrupt based events.Would it not be sufficient to only disable TIM0 ? In the function they don't seem to be enabling the interrupts again, is it being done elsewhere(otherwise no interrupt would be enabled).Would make sense to enable the interrupts again before exiting millis() ? Thanks for your time !

@EmbSysDev: You may indeed disable selectively TIM0, although that would take a few more cycles than cli(). This critical section is very short, so globally disabling interrupts is fine here. Re “they don't seem to be enabling the interrupts again”: that's what SREG = oldSREG; does: re-enable interrupts, but only if they were initially enabled when the function was called.