text:
Arduino sketch uses too much memory storage space?
I've never used arduino before but am using one for a school project. I am using an arduino leonardo and I've uploaded the sample code below
#include "Adafruit_CCS811.h"
Adafruit_CCS811 ccs;

void setup() {
    Serial.begin(9600);
    Serial.println("CCS811 test");
    if(!ccs.begin()){
        Serial.println("Failed to start sensor! Please check your wiring.");
        while(1);
    }

    //calibrate temperature sensor
    while(!ccs.available());
    float temp = ccs.calculateTemperature();
    ccs.setTempOffset(temp - 25.0);
}

void loop() {
    if(ccs.available()){
        float temp = ccs.calculateTemperature();
        if(!ccs.readData()){
            Serial.print("CO2: ");
            Serial.print(ccs.geteCO2());
            Serial.print("ppm, TVOC: ");
            Serial.print(ccs.getTVOC());
            Serial.print("ppb Temp:");
            Serial.println(temp);
        } else {
            Serial.println("ERROR!");
            while(1);
        }
    }
    delay(500);
}

But when I upload it, all I see a message that states
Sketch uses 8830 bytes (30%) of program storage space. Maximum is 28672 bytes.
Global variables use 487 bytes (19%) of dynamic memory, leaving 2073 bytes for local variables. Maximum is 2560 bytes.

Does this mean there is not enough storage in my computer or is there not enough space in the arduino? This arduino was given to me second hand.
I'm unsure if it is now appropriate to be able to see results show up on the serial monitor? Because nothing is showing up.

Where it is a Leonardo, you may want to put while (!Serial) {} immediately following your Serial.begin.  This will essentially wait until the Serial monitor establishes a connection so that you are not losing any diagnostic messages.

Please read your problem carefully. It says that your program uses 30% of your space and 19% of dynamic memory. You are nowhere close to full. @jwh20 answered it perfectly.

There is no problem here, please read the message carefully!
It says you are ONLY using 30% of the available program memory and 19% of the dynamic memory.
You have a LOT more room left.

So is this not a real error message then? This should show up after every upload? I'm unsure whether to tell if it was successful because there are no data values that show in the serial monitor.

This is not an error message.  It's an informational message.  Yes, this will show up after every upload to the Arduino.

As far as nothing showing up in the serial monitor, that's another issue altogether.  Perhaps you should try one of the simpler examples as a starting point to help get yourself familiar with the Arduino and its toolchain?  The Blink Example is a good place to start.

@jwh20 your comment about the message showing after an upload is incorrect ... the message shows at the end of the code compile process .... the upload happens afterward

Thanks for the clarification.  It's too late to edit the comment.

What you are seeing there is not an error message, it is only for information. It shows how much memory you have left on the Arduino.

Sketch uses 8830 bytes (30%) of program storage space. Maximum is 28672 bytes.

This is about the program storage, also known as flash storage (which is the type of storage technology used here). It is, where the actual program is saved, and is non-volatile (which means, that it holds the data/your code even during power loss). The message tells you, that the Arduino Leonardo has a total of 28672 bytes of storage for your program. When you write bigger programs, you will also use more of the flash/program storage. That means, that the size of the flash/program storage (which is a hardware limit in the microcontroller) gives you an upper limit to the size of the compiled program, as it cannot be more than 100% of the maximum given there and still upload. Though note, that the compiler does a lot of optimization to your code, so there is no easy relation between C/C++ code size and compiled code size. You need to actually compile your code to see, what size it will be and if it fits onto your Arduino. And that is exactly, what this message is meant for.
The message tells you, that you are using 30% of the flash/program storage. Thus you are very well inside the limits.

Global variables use 487 bytes (19%) of dynamic memory, leaving 2073 bytes for local variables. Maximum is 2560 bytes.

The second line is about the memory, where variables are stored, aka dynamic memory aka RAM. Of course this means the RAM inside of the Arduino. The RAM is volatile, which means, that every data in it will vanish, when the Arduino is powered off or reset.
Every time, that you declare a variable in your code, this variable is put into the RAM. Calculating the maximum amount of RAM, that will be used in your code, is rather complex, as variables are created and destroyed very often, when calling functions or other programming constructs. But global variables (the ones declared outside of any function) are created right at the start of the program, thus the compiler can easily calculate their size.
This message gives you a hint, if you are going to run out of RAM with your program. It is only a hint. Because of that, the compiler will show a warning at that point, if you are going in the realm of 75% or higher of the available RAM, that this might not leave enough room for local variables and thus risks instability in the program. (Note, that I'm not sure about the exact limit, from which on the warning is displayed. You may try to research this detail).
When you program runs out of RAM, it will fail or producing instability. So you want to prevent that from happening. Currently you are at 19%. Also you are using few local variables, so you are save here.

I'm unsure if it is now appropriate to be able to see results show up on the serial monitor? Because nothing is showing up.

You should at least be able to see the message CCS811 test on the Serial monitor. If not, please make sure, that you really uploaded the code (by clicking on the upload button, not on the verify button). In the preferences you can turn on verbose output for compilation and upload, to find possible problem sources. Also make sure, that you chose the correct port and that your Serial Monitor is configured for the same baudrate as your sketch (in this case 9600 baud).
If that still doesn't give any output at all, try to upload the Blink example, that you can find in the Arduino IDE in the menu under examples -> Basics. If it uploads successfully, watch, if the buildin LED starts to blink. If yes, that code is working correctly.
If the init message is showing up, but the temperature values are not, you need to first check for your connections. Then you could try to upload the standard I2C scanner sketch, that shows you, what devices can be found on the I2C bus and what addresses they have.


text:
Why does the LED state behave differently?
I wanted the sensor to be high when I press the button, but when DigitalRead does low, the LED turns on, when it does high, the LED goes off.
Whereas when the digitalRead is high, isn't it supposed to turn on the led?
int pirPin = 8;
int ledPin = 13;
int state;
unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 1000;

void setup() {
  pinMode(pirPin, INPUT);
  pinMode(ledPin, OUTPUT);

}

void loop() {

  unsigned long currentMillis = millis();
  state = digitalRead(pirPin);
  Serial.println(durum);

  if (state == HIGH) {
    previousMillis = currentMillis;
     }
    if (currentMillis - previousMillis >= interval) {
      digitalWrite(ledPin, LOW);
    }
    else
      digitalWrite(ledPin, HIGH);
  }

What about the button? Have you connected a button to pirPin or a PIR sensor?

"isn't it supposed to turn on the led?" - how should we know that? It's your code. You tell us what it's supposed to do. If you want the LED to go on, the code is wrong.

This way the led lights up.But I don't understand why the led turns on when I make low

@ chrisl. yes i connected.code already works this way.I'm wondering why the led lights up when it's low

Probably because it’s wired so that it lights up when the output is low, for example by putting the LED between the positive supply and the output pin (with a resistor in between).

Check out this link. The LED could be a common anode LED

Please provide a schemtic or wiring diagram of your circuit. And please better describe your problem. What behavior did you expect? What did actually happen? I currently don't understand you. "I make it low" is not really a helpful description of what you are doing

Your code is a bit of a mess. You log the value of something called durum, but never define it. You have an if statement, if (state == HIGH) that only affects the value of previousMillis, despite misleading indentation.  It looks like pulling pirPin HIGH would cause your LED pin to be pulled high for 1 second.

I suggest you check your {} in the if(state==HIGH) section, they sre probably wrong. You'd better use those braces consistently: though you wouldn't need them on any of those three lines, you use them on the first two, but you don't use them on the last.

Atm, you refresh the timestamp if the button is pressed. Then, if the timestamp has expired you turn the led off, otherwise on. This should behave as follows: when the button is pressed, the led should go on, one second after the button is released, the led turns off. As pointed out, this all depends pn how your button is wired.

Thank you all, I took care of the problem

source: Stack Exchange

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

sort: votes


text:
i am working on rfid module and the module is not detecting sny of the cards
i am working on uno.
i am using mfrc522.
the module is not detecting aby of the cards. nothing is poping up on the screen.
this is the code-
#include <deprecated.h>
#include <MFRC522.h>
#include <MFRC522Extended.h>
#include <require_cpp11.h>

// RFID door access system.

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

#define SS_PIN 10
#define RST_PIN 9
#define LED_G 5 //define green LED pin
#define LED_R 4 //define red LED
#define BUZZER 2 //buzzer pin
MFRC522 mfrc522(SS_PIN, RST_PIN);   // Create MFRC522 instance.
Servo myServo; //define servo name

void setup()
{
  Serial.begin(9600);   // Initiate a serial communication
  SPI.begin();      // Initiate  SPI bus
  mfrc522.PCD_Init();   // Initiate MFRC522
  myServo.attach(3); //servo pin
  myServo.write(0); //servo start position
  pinMode(LED_G, OUTPUT);
  pinMode(LED_R, OUTPUT);
  pinMode(BUZZER, OUTPUT);
  noTone(BUZZER);
  Serial.println("Put your card to the reader...");
  Serial.println();

}
void loop()
{
  // Look for new cards
  if ( ! mfrc522.PICC_IsNewCardPresent())
  {
    return;
  }
  // Select one of the cards
  if ( ! mfrc522.PICC_ReadCardSerial())
  {
    return;
  }
  //Show UID on serial monitor
  Serial.print("UID tag :");
  String content= "";
  byte letter;
  for (byte i = 0; i < mfrc522.uid.size; i++)
  {
     Serial.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ");
     Serial.print(mfrc522.uid.uidByte[i], HEX);
     content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "));
     content.concat(String(mfrc522.uid.uidByte[i], HEX));
  }
  Serial.println();
  Serial.print("Message : ");
  content.toUpperCase();
  if (content.substring(1) == "76 2B E3 93") //change here the UID of the card/cards that you want to give access
  {
    Serial.println("Authorized access");
    Serial.println();
    delay(500);
    digitalWrite(LED_G, HIGH);
    tone(BUZZER, 500);
    delay(300);
    noTone(BUZZER);
    myServo.write(180);
    delay(5000);
    myServo.write(0);
    digitalWrite(LED_G, LOW);
  }

 else   {
    Serial.println(" Access denied");
    digitalWrite(LED_R, HIGH);
    tone(BUZZER, 300);
    delay(1000);
    digitalWrite(LED_R, LOW);
    noTone(BUZZER);
  }
}

please help me

have you tried the example codes of the mfrc522 library? Are they working?

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


text:
How can I fix this error "invalid operands of types 'const char [17]' and 'float' to binary 'operator+'"?
#include <Wire.h>

long aX,aY,aZ,gX,gY,gZ;
float rtX,rtY,rtZ,gfX,gfY,gfZ;

void setup()
{
  Serial.begin(9600);
  Wire.begin();
  setupMPU ();
}

void loop()
{
  recordAccelregisters();
  recordGyroregisters();
  printData();
  delay(100);
}

void setupMPU()
{

  Wire.beginTransmission(0b1101000);
  Wire.write(0x6B);
  Wire.write(0b00000000);
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000);
  Wire.write(0x1B);
  Wire.write(0b00000000);
  Wire.endTransmission();
  Wire.beginTransmission(0b1101000);
  Wire.write(0x1C);
  Wire.write(0b00000000);
  Wire.endTransmission();
}

void recordAccelregisters()
{
  Wire.beginTransmission(0b1101000);
  Wire.write(0x3B);
  Wire.endTransmission();
  Wire.requestFrom(0b1101000,6);
  while(Wire.available()<6)
  {
    aX = Wire.read()<<8|Wire.read();
    aY= Wire.read()<<8|Wire.read();
    aZ = Wire.read()<<8|Wire.read();
    processAData();
  }
}

void processAData()
{
  gfX= aX/16384.0;
  gfY = aY/16384.0;
  gfZ = aZ/16384.0;
}

void recordGyroregisters()
{
  Wire.beginTransmission(0b1101000);
  Wire.write(0x43);
  Wire.endTransmission();
  Wire.requestFrom(0b110100,6);
  while(Wire.available()>6)
  {
    gX = Wire.read()<<8|Wire.read();
    gY = Wire.read()<<8|Wire.read();
    gZ = Wire.read()<<8|Wire.read();
    processGdata();
  }

}

void processGdata()
{
  rtX= gX/131.0;
  rtY = gY/131.0;
  rtZ= gZ /131.0;
}

void printData()
{
  Serial.print("Gyro degree(x)= "+ rtX + " ");// this line shows error mentioned above in the question
  Serial.print("Gyro degree(y)= "+ rtY + " ");// this line shows error mentioned above in the question
  Serial.print("Gyro degree(z)= "+ rtZ + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(x)= "+ gfX + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(y)= "+ gfY + " ");// this line shows error mentioned above in the question
  Serial.print("Accel Gforce(z)= "+ gfZ + " ");// this line shows error mentioned above in the question
}

this is a code of mpu6050.  Why am I getting this error and How Can I resolve it?

Side note: you should not write Wire.read()<<8|Wire.read() because the order of evaluation of the calls to Wire.read() is unspecified. See also this thread in the Arduino forum. Use gX=Wire.read()<<8;gX|=Wire.read(); instead.

These lines give you errors, because you cannot simply add character arrays (aka c-strings) and floats together with the + operator. C/C++ is very strict, when it comes to variable types. The compiler does not know, how it should add these types together.
In other high level languages a string literal (characters enclosed by " in the source code) are more complex types, than c-strings. They mostly have various different methods and also an implementation of the + operator for adding a float number in human readable form. This complex type in the Arduino world is the String type. You can convert the float variable into a String and then add them together. But that's not the way, that you should do it. Strings on AVR based Arduinos (like Uno, Nano, ...) can be very evil due to the limited RAM. See Majenko's blog entry about The Evils of Arduino Strings for more information.
Instead you should just use multiple print statements. As Serial data is send out serially (one byte after another), it doesn't matter, if you put all the data to send in one print statement, or in multiple onces. So each of the offending lines can be converted to something like this:
Serial.print("Gyro degree(x)= ");
Serial.print(rtX);
Serial.print(" ");

It does exactly, what your code does. But it will not produce an error, since the Serial.print() method is also implemented for using float arguments.


text:
Arduino Sketch Crashes in working procedure when adding extra call
I am trying to drive a couple of motors to make a car.
I successfully wrote some code then tidied it up to procedurise it and it just kept crashing.
I've put some debug code in and narrowed it down a bit but what I am seeing makes no sense. With the code below I just call the TLeft procedure which works and drives the motor and I get the serial output:
RWheel Forward
1
2
3
4
5
ReTurn L
RWheel Forward
1
2
3
4
5
ReTurn L
RWheel Forward
1
2
3
4
5
ReTurn L
/************************
  Exercise the motor using
  the L293D chip
************************/

#define RW_ENABLE 11
#define RW_DIRA 28
#define RW_DIRB 30
#define LW_ENABLE 10
#define LW_DIRA 48
#define LW_DIRB 50

int i;

void setup() {
  //---set pin direction
  pinMode(RW_ENABLE, OUTPUT);
  pinMode(RW_DIRA, OUTPUT);
  pinMode(RW_DIRB, OUTPUT);
  pinMode(LW_ENABLE, OUTPUT);
  pinMode(LW_DIRA, OUTPUT);
  pinMode(LW_DIRB, OUTPUT);
  Serial.begin(9600);
  Serial.println("Prog Start");
  delay(1000);
}

void loop(){
    //Serial.println("Wheels Forwards");
  //GoForward();
  //delay(2000);
  //Serial.println("Turn Left");
  TLeft();
  Serial.println("ReTurn L");
  delay(5000);
  //Serial.println("Turn Right");
  //TRight();
  delay(5000);
  //Serial.println("Wheels Backwards");
  //Backwards();
  delay(5000);
  //Stop();
  delay(5000);
}

void TRight() {
  Serial.println("LWheel Forwards");
  delay(1000);
  analogWrite(LW_ENABLE, 254); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  digitalWrite(RW_ENABLE, LOW); //RWheel off

}
void TLeft() {
  Serial.println("RWheel Forward");
  delay(1000);
  analogWrite(RW_ENABLE, 254); //halfspeed
  Serial.println("1");
  delay(1000);
  digitalWrite(RW_DIRA, HIGH); //one way
  Serial.println("2");
  delay(1000);
  Serial.println("3");
  delay(1000);
  digitalWrite(RW_DIRB, LOW);
  Serial.println("4");
  delay(1000);
  digitalWrite(LW_ENABLE, LOW); //RWheel off
  Serial.println("5");
  delay(1000);

}
void Backwards() {
    Serial.println("Both Back");
    analogWrite(LW_ENABLE, 250); //halfspeed
    digitalWrite(LW_DIRA, LOW); //back
    digitalWrite(LW_DIRB, HIGH);
    analogWrite(RW_ENABLE, 250); //halfspeed
    digitalWrite(RW_DIRA, LOW); //back
    digitalWrite(RW_DIRB, HIGH);
  }

void Forwards() {
  Serial.println("Both Forw");
  analogWrite(LW_ENABLE, 250); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  analogWrite(RW_ENABLE, 250); //halfspeed
  digitalWrite(RW_DIRA, HIGH); //one way
  digitalWrite(RW_DIRB, LOW);
}

void Stop () {
  Serial.println("Stop");
  digitalWrite(LW_ENABLE, LOW); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  digitalWrite(RW_ENABLE, LOW); //halfspeed
  digitalWrite(RW_DIRA, HIGH); //one way
  digitalWrite(RW_DIRB, LOW);

}

When I uncomment out the call to Backwards as below.....
/************************
  Exercise the motor using
  the L293D chip
************************/

#define RW_ENABLE 11
#define RW_DIRA 28
#define RW_DIRB 30
#define LW_ENABLE 10
#define LW_DIRA 48
#define LW_DIRB 50

int i;

void setup() {
  //---set pin direction
  pinMode(RW_ENABLE, OUTPUT);
  pinMode(RW_DIRA, OUTPUT);
  pinMode(RW_DIRB, OUTPUT);
  pinMode(LW_ENABLE, OUTPUT);
  pinMode(LW_DIRA, OUTPUT);
  pinMode(LW_DIRB, OUTPUT);
  Serial.begin(9600);
  Serial.println("Prog Start");
  delay(1000);
}

void loop(){
    //Serial.println("Wheels Forwards");
  //GoForward();
  //delay(2000);
  //Serial.println("Turn Left");
  TLeft();
  Serial.println("ReTurn L");
  delay(5000);
  //Serial.println("Turn Right");
  //TRight();
  delay(5000);
  //Serial.println("Wheels Backwards");
  Backwards();
  delay(5000);
  //Stop();
  delay(5000);
}

void TRight() {
  Serial.println("LWheel Forwards");
  delay(1000);
  analogWrite(LW_ENABLE, 254); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  digitalWrite(RW_ENABLE, LOW); //RWheel off

}
void TLeft() {
  Serial.println("RWheel Forward");
  delay(1000);
  analogWrite(RW_ENABLE, 254); //halfspeed
  Serial.println("1");
  delay(1000);
  digitalWrite(RW_DIRA, HIGH); //one way
  Serial.println("2");
  delay(1000);
  Serial.println("3");
  delay(1000);
  digitalWrite(RW_DIRB, LOW);
  Serial.println("4");
  delay(1000);
  digitalWrite(LW_ENABLE, LOW); //RWheel off
  Serial.println("5");
  delay(1000);

}
void Backwards() {
    Serial.println("Both Back");
    analogWrite(LW_ENABLE, 250); //halfspeed
    digitalWrite(LW_DIRA, LOW); //back
    digitalWrite(LW_DIRB, HIGH);
    analogWrite(RW_ENABLE, 250); //halfspeed
    digitalWrite(RW_DIRA, LOW); //back
    digitalWrite(RW_DIRB, HIGH);
  }

void Forwards() {
  Serial.println("Both Forw");
  analogWrite(LW_ENABLE, 250); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  analogWrite(RW_ENABLE, 250); //halfspeed
  digitalWrite(RW_DIRA, HIGH); //one way
  digitalWrite(RW_DIRB, LOW);
}

void Stop () {
  Serial.println("Stop");
  digitalWrite(LW_ENABLE, LOW); //halfspeed
  digitalWrite(LW_DIRA, HIGH); //one way
  digitalWrite(LW_DIRB, LOW);
  digitalWrite(RW_ENABLE, LOW); //halfspeed
  digitalWrite(RW_DIRA, HIGH); //one way
  digitalWrite(RW_DIRB, LOW);

}

It seems to crash in the TLeft procedure, no motor turns and I get the serial output:
Prog Start
RWheel Forward
Prog Start
RWheel Forward
Prog Start
RWheel Forward
Prog Start
RWheel Forward
Prog Start
I even bought a new Arduino mega thinking it was a hardware fault, downloaded the program to the new mega which has no hardware connections at all just connected to the serial port to download the program and it crashes in exactly the same way.
How can adding another call make it fail in the bit of code that previously ran ok? This is driving me nuts. Can anyone help please?
Also I noticed in the Arduino program installation area there is a program called Arduino_debug.exe, what is this and how does one use it?

which version of Arduino AVR boards you use? I would try the old 1.6.21. The newer versions have have updated compiler and there are problems reported.

Looks so strange that I guess it's a power supply problem when your motor wants to run. Are you sure it happens on a naked Arduino the same way? i.E. you don't see the "1" output after your analogWrite(11,254); ?

Yes it happens on the new naked board. I don't see the "1" output. It just reboots.

did you try to install AVR boards package 1.6.21 in Boards Manager?

Your code (including the Backwards part) runs without issues on my Mega2560 and Arduino 1.8.9.

I had version 1.8.1, I tried downloading 1.6.21 but wouldn't download , so tried 1.8.2, no difference. I then tried 1.6.20 and that made no difference. I then uninstalled arduino and re-installed it, and phew it now works ok.

Thanks for help in assuring me it must have been some environment related issue. I'm thinking it might have been something to do with trying out different learning projects which required installation of different libraries. I installed the pitches library and a remote library. There is plenty of info telling you how to add a new library and sometimes it says one library may interfere with another. But I cannot find any information on how to remove a library to avoid interference. A complete uninstall and re-install is a bit overthe top.


text:
How can I send Arduino sensors data to java application?
my final year project is to do an Arduino watch that has heart rate and body temperature sensors and also a location tracking module. I need to send all the watch data to my java app but I don't how do I need to send it to a database first and then use it? and how can i do that.
I'm using arduino uno and i want to send the data to a database on a server.
I'm using android studio and coding with java
please help :(

To what database do you want to send the data? Where does the database run? How is the Arduino Uno connected to the system running the database?

I asked my teacher and she told me I have to read the data and send it to the server and the server will store it in a database and then display it in the application

i don't know how to work with Arduino it is my first time and i just want to know how i will receive the data to display it in the app

Then you first need to think about how to contact your server, so you need a network connection. Do you need to use an Arduino Uno? Do you have a wifi network available? Or do you need a mobile data connection over LTE? Have you done research about these things?

To send the data from the Arduino, you just need to do this:
Serial.println(the_data);

But then you have to manage some communication link between the Arduino
and whatever is going to collect the data. Typical choices are the USB
link or a Bluetooth module. Then, whatever you do with this data (send
to an Android phone, a Java app, a server, a database, whatever...) is
up to you, and is not an Arduino question.


text:
Fading out a led with reed switch loop
I was hoping to get some help on the fading led which I am working on.
For my project I need to have a led, which when it is placed next to a magnet, continuously shines, but as soon as it is taken away it has to fade out in a certain amount of time. So far I managed to write the code which detects when the light is taken away from the magnet and fades out, but when the magnet is nearby again, the led lights up and keeps shining, no matter  if I take it away from the magnet or not. So how I could solve this? I tried to exit the loop function, but then this process happens only once, which is not what I want. I am also using reed switch to detect the magnet, but if you have other sensor suggestions, let me know. I'm including the code down here.
Thank you for your help in advance:)
int ledPin = 9;
int brightness = 255;
int fadeAmount = 5;
const int reedPin = 2;

void setup() {
  Serial.begin(9600);
  pinMode(ledPin, OUTPUT);
  pinMode(reedPin, INPUT_PULLUP);
}

void loop() {
  int proximity = digitalRead(reedPin);
  if (proximity == HIGH) {
    Serial.println("Switch opened");
    while (brightness >= 0) {
      analogWrite(ledPin, brightness);
      brightness = brightness - fadeAmount;
      delay(30);
      Serial.println(brightness);
    }
  }
  else {
    Serial.println("Switch closed");
    analogWrite(ledPin, brightness);
    Serial.println(brightness);
  }
}

First, please don't provide code as an image. Instead copy and paste the code as text into the question and format it correctly by selecting the code and clicking the {} button in the question editor

Your current problem probably comes from the fact, that you execute the fading loop, even if brightness is already zero, and that you don't reset it to zero after fading.
while(brightness >= 0){
   ...
   brightness = brightness - fadeAmount;
   ...
}

Imagine we are at the point, where brightness is 5. The while condition is true, since 5 > 0. Then we execute the code in the loop, setting brightness to 0. We again check the while condition. It is still true, since 0>=0. So after executing the code in the loop again, brightness is now -5. But analogWrite() only takes a 1 byte unsigned (!) integer, aka uint8_t, while int is a 2 byte signed (!) integer. So only the lower byte of that integer will be used and interpreted as unsigned. So -5 gets interpreted as 251, which you see as lighting up in full brightness.
Easy fix would be to set brightness to zero after the while loop:
brightness = 0;

That said, I would suggest a completely different route, which will make your code way more responsive, by using the non-blocking coding principle from the BlinkWithoutDelay example, that comes with the Arduino IDE.
As you did, I would use a global brightness and fadeAmount variable, but also one to hold a timestamp:
unsigned long timestamp=0;

Then in loop() we can first do the fading to zero by using the millis() function as a clock:
if(millis()-timestamp > 30){
    brightness = brightness - fadeAmount;
    if(brightness < 0) brightness = 0;
    timestamp = millis();
}

That will decrement the brightness variable to zero without blocking with a delay(). The speed can be changed by changing the number 30 to something different. This number has the unit milliseconds.
Then we can check for the reed switch and set brightness to 255, if it is activated:
if(!digitalRead(reedPin)){
    // reedPin is LOW
    brightness = 255;
}

So as long as the magnet is at the reed switch, this code will set brightness to 255.
And finally we need to write the value of brightness to the output pin:
analogWrite(ledPin, brightness);

So as a full code:
int ledPin = 9;
int reedPin = 2;

int brightness = 0;
int fadeAmount = 5;
unsigned long timestamp = 0;

void setup(){
    pinMode(ledPin, OUTPUT);
    pinMode(reedPin, INPUT_PULLUP);
}

void loop(){
    if(millis()-timestamp > 30){
        brightness = brightness - fadeAmount;
        if(brightness < 0) brightness = 0;
        timestamp = millis();
    }

    if(!digitalRead(reedPin)){
        // reedPin is LOW
        brightness = 255;
    }

    analogWrite(ledPin, brightness);
}

I've tested this with a normal button (currently no reed switch here). It should work as expected.

I tested it, it works. Thank you so much!


text:
How to program ATTiny85 running 3.3V
I have a working project built around ATTiny85 on a breadboard running at 5V. Now I want to move this prototype on a PCB where it will be powered from batteries. All components used are capable of running 3.3V so I want to run the ATTiny85 at 3.3V as well.
I don't have a programmer so I use ArduinoISP to program the ATTiny. If I change the fuses on Tiny to run it at 3.3V can I still use the 5V Arduino to program the tiny?
Since the ATTiny can easily run at 5V I don't see any problem with programming it at 5V levels and then run it at 3.3V. Is that correct?

Since the ATTiny can easily run at 5V I don't see any problem with programming it at 5V levels and then run it at 3.3V. Is that correct?

Yes. But if there are any components on the board that can't run at 5V then you must provide some way of protecting them from the excessive voltage.

If I change the fuses on Tiny to run it at 3.3V can I still use the 5V Arduino to program the tiny?

There are no fuses required to change the actual operating voltage of the device. There is the BOD threshold, but you can still operate the device at a higher voltage without issue regardless.

Most ideal would be to use a buffer chip (like there is on the AVR Pocket Programmer).
But in your case you could get away with just placing some resistors (1k or something) on the ISP lines. This is because if the chip is powered by 3v and you put a 5v signal on one of the pins it's clamping diodes will redirect the higher voltage to VCC, raising VCC to 5v. In your case the 5v is not necessarily a problem. But if you circuit is using e.g. 100mA, that means 100mA will go through the clamping diode. It's not designed for that.

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


text:
How to stop Arduino from drawing power through USB
I'm working on an embedded project, where I use arduinos as a "sensor shield" for RaspberryPi (I have model B).
The problem is, that the RaspberryPi's USB port is not powerfull enough to drive WiFi adapter and arduino with sensors. The solution is easy, I will power the sensors externally, not through the RPi.
But I was wondering, is it possible to power whole Arduino externally (through Vin) and use the USB only for serial communication.
To clarify, I know how to solve my problem - use some other mean of communication, than USB - GPIO serial, I2C, wireless, etc... I'm just interested if the whole thing will work, with USB cable which has 5V lead cut, for example.
The main issue I can see with this is, that the USB<->Serial chip is powered through USB only, then it will now work.

Any particular Arduino?

I'm using Nano v3 and Mini, but I'm looking for general solution preferably.

The general solution is to stick to bare MCUs, since each board's power circuitry is slightly different.

If you provide power to the Arduino through Vin this will disconnect USB power through the MOSFET switch.

There are a couple of alternative solutions to the question that I think are worth mentioning.

Use a data only USB cable or manually cut  the VCC and GND wires of the cable.
Remove the USB poly fuse from the arduino board.
Connect external power to one of the input pins to measure the voltage. This measurement can then be used to determine if the external power is connected and is providing sufficient voltage.
If it does the USB power should not be use anyways, otherwise an if statement can be used to disable the code that turns devices that draw power.
USB power will still be used to power the arduino board itself. It also has a limitation in that because the power supply could provide insufficient current it could draw the remaining required current from USB.

Suggestion #1 didn't seem to work for me, which was really confusing.  I'm working with a 3D printer scenario running Marlin on the Arduino.  When I power on the printer/power supply, everything connects like it should when using an unmodified cable.  But, when I try the cable without the VCC & GND wires, nothing will connect.  Could the RAMPS board not be powering the serial bus or something?  Kinda scratching my head on this one.

Only cut VCC and keep ground connected. AFAIR it won‘t work with GND connected

The FTDI chip requires power from the USB side to operate so suggestion 1 will not work

Just cut the VCC line (usually red) in the USB cable.

There are four wires in a USB cable:

Ground
VCC
Data +
Data -

You cannot send data along without a reference ground as you need a potential difference. Hence you must keep the ground connected and just snip the power line (red VCC).

Note that this is not usually necessary as VIN is favoured over USB power.

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


text:
Interrupts don't work
I tried to run a sketch that tests my AVR's interrupts,
I have an UNoriginal Arduino Uno, and I've checked pins 2 and 3 like the following:
- at void setup()
attachInterrupt(2, inter, CHANGE);
- at void inter()
Serial.println("Interrupt pin 2");

I did the same on pin 3, I checked them by attaching the pins to a button with a Pull-Up,
When I click the button it goes from HIGH to LOW.
But yet, the arduino doesn't run the 'inter'.
Is it possible that because my Arduino is not original it won't work?
And this type of interrupts are software not hardware right?

On all Arduino boards except the DUE, attachInterrupt() does not use the pin number as first argument but the interrupt number, which is different:
void attachInterrupt(uint8_t interrupt, void (*ISR)(void), int mode);

As documented on Arduino reference, for an Arduino UNO, the mapping is as follows:

Interrupt 0 -> Pin 2
Interrupt 1 -> Pin 3

So just change the code in setup() to:
attachInterrupt(0, inter, CHANGE);

And that should work for pin 2.


text:
Arduino and ATtiny84 w/RF
I'm trying to send data from an ATtiny84 [1mhz] to Arduino Uno using a 433Mhz rf module and Manchester lib.
Now I came across a weird problem, no matter what value I transmit, When I receive it on the arduino and to the Serial monitor, it always shows value of 806,No matter what I have really transmitted.
ATtiny side
void setup()
{
  man.workAround1MhzTinyCore(); //add this in order for transmitter to work with 1Mhz Attiny85/84
  man.setupTransmit(transmit_pin, MAN_1200);
}

// And how I transmit
// RGBread is int, I also tried man.transmit((uint16_t)RGBread[i]); same result.
  for(int i=0; i<3; i++)
  {
    man.transmit(RGBread[i]);
  }

Uno
void setup()
{
  man.setupReceive(reciever_pin, MAN_1200);
  man.beginReceive();
}

  if (man.receiveComplete()) {
    Serial.println(man.getMessage());
    man.beginReceive(); //start listening for next message right after you retrieve the message
  }

Thanks to all helpers.

As a test, make your transmit value explicitly count in a loop to rule out problems with the ultimate data source.  Are you sure that man.getMessage() returns something meaningful for printing?  If you don't have a scope to validate the received data waveform, you could try substituting a direct connection for the RF modules.

The values are analogRead's returns.

I did tried to put my own inputs instead of that analogRead, 0 125 and 255 low mid and high, same results its all 806 on the reciever side.

Either substitute a direct connection for the RF modules and test that, or see if you can use a PC soundcard as a crude scope to examine the transmitted and received data signals.

Check what? And if you connect the reciever directly to a led, you can see it blinking all the time, lots of interference, but that's okay. You get what you paid for ;)- Thought it's the lib's job to make the link work right?

The library can't do anything unless there is signal in the noise, something you've yet to prove.  I'm still recommending you try a direct connection to verify that the transmitter and receiver are working, and at the same settings.


text:
ARDUİNO MODBUS TCP CONNECTİON
I am trying to communicate with PC by using modbus TCP communicate. When I use this code I can't communicate. Dou you know guys what is the problem? My ethernet Module is working I know that because I can ping it when I use different code from EtherCard.h library. But when I try to use Ethernet and Modbus library I can't communicate. I can't ping it.
#include <ModbusIP.h>
#include <SPI.h>
#include <Ethernet.h>
#include <Modbus.h>

int setPoint;zz
const int setPoint_IR = 100;

ModbusIP mb;

void setup() {
  Serial.begin(9600);
  byte mac [] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  byte ip [] = {10, 0, 58, 37};
  mb.config (mac, ip);

  mb.addIreg(setPoint_IR);

}

void loop() {
  mb.task();
  setPoint = analogRead(A0);
  mb.Ireg(setPoint_IR, setPoint);
}

void DisplaySetPointValues(){
  String Printstr;
  Printstr = "Set point values = " + String(setPoint);
  Serial.println(Printstr);
}

you can use my EthernetENC library

remove the 3.3V wire

Ethernet.h is for W5100 based cards (Arduino Ethernet shields). You cannot use it for an ENC28J60.

Thank you so much guys.


text:
why is my arduino stuck on uploading?
my arduino for the playground adafruit express gets stuck uploading, and is saying that it is not recognizing the ports. <Arduino: 1.8.16 (Windows Store 1.8.51.0) (Windows 10), Board: "Adafruit Circuit Playground"
Sketch uses 6360 bytes (22%) of program storage space. Maximum is 28672 bytes.

Global variables use 351 bytes of dynamic memory.

Forcing reset using 1200bps open/close on port COM13

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

PORTS {COM13, } / {COM13, } => {}

Uploading using selected port: COM13

C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\hardware\tools\avr/bin/avrdude -CC:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -PCOM13 -b57600 -D -Uflash:w:C:\Users\Owner\AppData\Local\Temp\arduino_build_570140/sorting_numbers_test.ino.hex:i

avrdude: Version 6.3-20190619

         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/

         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.51.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM13

         Using Programmer              : avr109

         Overriding Baud Rate          : 57600

         AVR Part                      : ATmega32U4

         Chip Erase delay              : 9000 us

         PAGEL                         : PD7

         BS2                           : PA0

         RESET disposition             : dedicated

         RETRY pulse                   : SCK

         serial program mode           : yes

         parallel program mode         : yes

         Timeout                       : 200

         StabDelay                     : 100

         CmdexeDelay                   : 25

         SyncLoops                     : 32

         ByteDelay                     : 0

         PollIndex                     : 3

         PollValue                     : 0x53

         Memory Detail                 :

                                  Block Poll               Page                       Polled

           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack

           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------

           eeprom        65    20     4    0 no       1024    4      0  9000  9000 0x00 0x00

           flash         65     6   128    0 yes     32768  128    256  4500  4500 0x00 0x00

           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00

           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00

           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : butterfly

         Description     : Atmel AppNote AVR109 Boot Loader

Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

Found programmer: Id = "F"; type = @

    Software Version = �.v; Hardware Version = �.

avrdude: butterfly_recv(): programmer is not responding

avrdude: butterfly_recv(): programmer is not responding

avrdude: error: buffered memory access not supported. Maybe it isn't

a butterfly/AVR109 but a AVR910 device?

avrdude: initialization failed, rc=-1

         Double check connections and try again, or use -F to override

         this check.

avrdude: butterfly_recv(): programmer is not responding

avrdude: error: programmer did not respond to command: leave prog mode

avrdude: butterfly_recv(): programmer is not responding

avrdude: error: programmer did not respond to command: exit bootloader

avrdude done.  Thank you.

the selected serial port

 does not exist or your board is not connected

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

Not sure how windows works, I'm not using it, but it looks like serial protocol error, board might have been unplugged (physical or software side), in both case, the board is no more on that serial port number. This can occur when too many devices are serialized, consuming too much. Try to dispatch better all your serial devices on all serial ports.  Reinitialize hardware numbering & re associate the new serial port in Arduino IDE if needed, then it will be OK.

Do you have the correct hardware selected and if like the nano you may have to select a loder.

...for the playground adafruit express gets stuck...

avrdude: initialization failed, rc=-1

You appear to have selected the "Classic" rather than "Express" version of the board, which are different things.

The classic you have selected uses an AVR ATMega32u4 like you'd find in the Arduino Micro/Leonardo.

The "Express" uses an ATSAMD21 chip like an Arduino Zero.

They don't use the same family of microcontroller, bootloader, bootloader protocol, or upload tool. The boards manager package that supports the Class board is completely different from the one that supports the Express board; they are divided support along the lines of the AVR (8-bit) vs SAMD (32-bit arm) chips.
In short, choose the "Express" version of the board after you've gone through setup process for the Express.  If you have problems uploading to an Express with the Express board selected, you're likely to see errors that mention bossac, but you're not going to see anything about avrdude.


text:
why the p-mos is acting as a constant switch when the source is connect to any port in the circuit iam not able find the solution ?i

if my circuit has mistake please refer me the proper image.
#define pwm 6
void setup() {
  // initialize serial communication at 9600 bits per second:
  pinMode(6,OUTPUT);
  Serial.begin(9600);
}

// the loop routine runs over and over again forever:
void loop() {
  // read the input on analog pin 0:
  int sensorValue = analogRead(A0);
  //Serial.println(sensorValue);
  // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
  float voltage = sensorValue * (5.0 / 1023.0);
  //Serial.println(voltage);
  float vol1=voltage*11;
  Serial.print("convertd voltageg ");
  Serial.println(vol1);
  int s=0;
  if (vol1>24){
  float duty=(24)/(vol1);
  Serial.print("Duty cycle ");
  duty=duty*100;
  Serial.println(duty);
   s=map(duty,0,100,0,255);
  Serial.print("maped values");
  Serial.println(s);
    analogWrite(6,s);}
  else if(vol1>18 && vol1<25){
    s=255;
    analogWrite(6,s);
    Serial.println(s);
  }
  //Serial.println(x);
}

Read MOSFET as a switch.

DV & VTC. Your question is not about Arduino, and should be moved to EE.

Is it standard practice here to down vote an answer simply because it is deemed that the question belongs elsewhere? I'd have thought that any down voting of an answer should be accompanied by a specific comment stating how the answer is factually, or otherwise, incorrect.

The Arduino when the output is High is ~5V referencing. The MOSFET gate sees it as -7V referencing the source. It is always best to use the source as the reference point for a MOSFET. Look at the data sheet and it shows it is doing what it is doing. The gate needs to about 0V referencing the source to be off. The exact value is dependent on the MOSFET used.You will need to add a transistor or mosfet to drive the P-Channel MOSFET with the Arduino. You could also use a opto isolator to switch the mosfet.

You have to be careful with such a circuit because you risk applying 12 volts to an arduino pin. To switch that P channel mosfet off, 12 volts has to be applied to the gate. Search for "mosfet high side switch". Usual solutions use both a P channel  mosfet and either an npn transistor or an N channel mosfet. A simpler alternative is to switch the motor using an N channel mosfet (low side switch). See https://gammon.com.au/motors for a full description.
Note: that circuit you have used appears to have come from here https://circuitjournal.com/how-to-use-a-p-channel-mosfet-with-an-arduino and is particularly risky because it relies on the grounds between the 5 volt and 12 volt circuits not being interconnected. It may work as shown, however not recommended for the reasons stated above, but your simulation does not appear to have the 12 volt power supply sharing a common positive rail with the 5 volt supply.


text:
I am attempting to control two stepper motors by using serial input. My code works, however I have to press the new directional command multiple times
I am using two 28BYJ-48 stepper motors with two motor drivers that they come with. (I don't know the name of them.)
Here is my code:
/*
 * Code to control two stepper motors simultaneously using the stepper library function calls
 * This code has functions which make calls to initiate one step from each of the two motors at a time
 * therefore each motor takes it in turn to step with the end result of them both running together
 * the variable 'lastCall' allows for a continuous input to keep the steppers running if there is no serial input
 * Written by Gabriel Adams  - March 2023 -
 */
#include <Stepper.h>

//definitions for each command to be recieved via serial port
#define COMMAND_LEFT 'a'
#define COMMAND_RIGHT 'd'
#define COMMAND_FORWARD 'w'
#define COMMAND_BACK 's'
#define COMMAND_STOP ' '

//Number of steps per internal motor revolution
const float STEPS_PER_REV = 32;

//Amount of gear reduction
const float GEAR_RED = 64;

//Number of steps per geared output rotation
const float STEPS_PER_OUT_REV = STEPS_PER_REV * GEAR_RED;

//enter the steps per rev for your motors here
int stepsInRev = STEPS_PER_OUT_REV ;

//this sets the value for the for loops and therefore sets the amount of steps in each call
int num_of_steps = 1;
// setup pins for each driver motor1 ~ IN1, IN2, IN3, IN4; motor2 ~ IN1, IN2, IN3, IN4
Stepper myStepper1(STEPS_PER_OUT_REV, 4, 6, 5, 7);
Stepper myStepper2(STEPS_PER_OUT_REV, 8, 10, 9, 11);
// variable to store the last call to the serial port
char lastCall = ' ';

//I had prototyped all of the functions here, but for some reason the Arduino IDE didn't like it
//so they are coded out until I an figure out why
//void forwardStep();
//void backwardStep();
//void leftStep();
//void rightStep();
//void allStop();

//to move the motors forward
void forwardStep(int steps){
  Serial.println("forward");
  // step one step each forward
  myStepper1.step(1);
  myStepper2.step(1);
  delay(10);
}

// to move the motors back
void backwardStep(int steps){
  Serial.println("backward");
  // step one step each backward
  myStepper1.step(-1);
  myStepper2.step(-1);
  delay(10);
}

// to move the motors in opposite directions (left)
void leftStep(int steps){
  Serial.println("left");
 // step one step each left
  myStepper1.step(1);
  myStepper2.step(-1);
  delay(10);
}

// to move the motors in opposite directions (right)
void rightStep(int steps){
  Serial.println("right");
  // step one step each right
  myStepper1.step(-1);
  myStepper2.step(1);
  delay(10);
}

// to power down the motor drivers and stop the motors
void allStop(){
  Serial.println("stop");
  // steppers stop
  PORTD = B00000000; //sets all of the pins 0 to 7 as LOW to power off stepper1
  PORTB = B00000000; //sets all of the pins 8 to 13 as LOW to power off stepper2
}
void setup() {
  Serial.begin(9600);//start the bluetooth serial port - send and recieve at 9600 baud
  // set the speed at 60 rpm:
  myStepper1.setSpeed(700);
  myStepper2.setSpeed(700);
}

void loop() {
//check to see if there is serial communication and if so read the data
if(Serial.available()) {
char data = (char)Serial.read();
// switch to set the char via serial to a command
switch(data) {
  case COMMAND_FORWARD:
    forwardStep(num_of_steps);
    break;
  case COMMAND_BACK:
    backwardStep(num_of_steps);
    break;
  case COMMAND_LEFT:
    leftStep(num_of_steps);
    break;
  case COMMAND_RIGHT:
    rightStep(num_of_steps);
    break;
  case COMMAND_STOP:
    allStop();
    break;
}
// set the 'lastCall' variable to the last call from the serial
lastCall = data;
}

char data = lastCall;

Loop(lastCall);
Serial.read();

}

void Loop(char x){
switch(lastCall) {
  case COMMAND_FORWARD:
    forwardStep(num_of_steps);
    break;
  case COMMAND_BACK:
    backwardStep(num_of_steps);
    break;
  case COMMAND_LEFT:
    leftStep(num_of_steps);
    break;
  case COMMAND_RIGHT:
    rightStep(num_of_steps);
    break;
  case COMMAND_STOP:
    allStop();
    break;
}
return lastCall;

(char)Serial.read();
}

Why are you doing these two Serial.read()s without using the result outside of your serial code? If your data arrives right before that, it will just be discarded.

I am still in the learning process of object-oriented coding. I was thinking the Serial.read() command would ensure more immediate reads of serial inputs. How would I better assess this? As in, instead of how at the moment it won't immediately change direction when I give a new command, how do I ulitize the Serial.read() command to quickly move to a new loop.

Seems you have a strange understanding of function parameters, which are not used by the functions. BTW: function prototyping is done by the IDE for you, but if you do it yourself, do it right: parameters should fit.

The problem is, that you are reading from the Serial buffer without using the data. There are three places in your code, where you use Serial.read();:

You use in in the block with your serial code and you set lastCall accordingly. This is ok.
Then you use it at the end of void loop(), but you don't assign the value to anything.
And you use it at the end of your own Loop() function, again without assigning the value to anything.

Short explanation how Serial works: The Uno has hardware to handle Serial communication in the background via interrupts. The data arrives at the Uno and gets automatically (in the background) places in the internal buffer of the Serial object. The call to Serial.read() removes the oldest byte from the buffer (so that you get the bytes in order of arrival) and returns it. If there is no new data byte available it will return -1.
So when you just use Serial.read() without assigning the value to anything, you are basically throwing away data bytes from the Serial buffer.

I was thinking the Serial.read() command would ensure more immediate reads of serial inputs.

Reading the data from the buffer is not enough. You actually have to do something with it. Otherwise you are just reading without reacting. So please remove the two calls to Serial.read(), only leaving the the one in your if(Serial.available()) block.

how at the moment it won't immediately change direction when I give a new command, how do I utilize the Serial.read() command to quickly move to a new loop?

You should remove all the calls to delay(). Currently your code spends the most time in these delays, doing nothing. Instead you can use the non-blocking coding style from the BlinkWithoutDelay example, that comes with the Arduino IDE. It uses millis() as a time keeper, only executing the code (blinking an LED in the example; doing a step in your code) when it is time to do  so. There are many tutorials about that online.
If you want you can even go further and switch to the AccelStepper library, which is more capable than the standard Stepper library. It lets you set the speed and acceleration and then you simply run the motor by executing the run() method often enough. No need for your own timing of steps then, because the library is handling that. Though this will be a bigger change to your code.


text:
What is the raw value & scale value functionality of analog read() of ESP32 ? (Provided for UNO for reference)
What is the difference between ESP32 Dev kit & Uno for analogread() Function?
As Uno -0 to 1023
As Esp 32 Dev Kit -0 to 4095
So what will be the raw val & scale val ?
For UNO -
int Rawval = analogRead(analogPin);
Serial.print("Rawvalue from Analog input =");
Serial.print(Rawval);
Scaleval = map(Rawval, 0, 675, 0, 20);
Serial.print(" Scaled Value =");

What will be for ESP32 Dev Kit?
Ref UNO-
// For 3V3 input to read 100%, 3V3 of 5V ref = (3.3 / 5) * 1023 = 675
/// === RELAY code ===
// raw value 675 correspond to 20%, so for 5% we will get 169
  if ( Rawval < 169) digitalWrite(RELAY_pin, HIGH);
  else  digitalWrite(RELAY_pin, LOW);
}

What will be for ESP32 Dev Kit?

Look in the help section under the question mark  in the editor about code quoting. I'd use the triple-backtick method for you, but you've got something weird around For UNO -int Rawval and I don't want to break things as much as fix them.

one is 10 bits of data and the other is 12 bits of data ... it appears that the question is not about analogread() at all, but about something else ... please update your question and ask about the real focus of your question

what is raw val and scale val?

QUESTION IS CLEAR?

no, it is not ... the code is also not formatted properly, so it is difficult to read ... please format the code ... as @timemage already said, put ``` on a separate line before the code and also after the code

Raw value is analogous sensor value..
Scale value is after mapping using the map function of raw value of the sensor.

I want exactly the same functionality at ESP32 dev kit as reference of UNO

When the read voltage is maximum that is 3.3V digital output is equal to 4095 for ESP32

Well then, go ahead. Use your transfer power to compare that with the 1023 maximum of the Uno. -- And, please, format your question.

Confusion! Here also, As you said that code for UNO was provided by someone expert.

As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.

How to map for ESP32 (As 4095 for 3.3v)? Enclosed Logic is for uno.
''' // For 3V3 input to read 100%, 3V3 of 5V ref = (3.3 / 5) * 1023 = 675
Scaleval = map(Rawval, 0, 675, 0, 20); '''
''' // raw value 675 correspond to 20%, so for 5% we will get 169'''
Kindly modify this for ESP32 (4095)-- Enclosed Logic is for uno.
If you can enclose logic behind that will also fine for me based on calculations
Also for 0.1%


text:
Simple debounce coding
am a complete beginner at coding with Arduino, although I have used them for a few years by copying other peoples code. I only understand a tiny fraction of the layout of a sketch and would really appreciate some help to solve, what I believe, is a simple problem.
I have a sketch to control the speed and direction of a stepper motor:-
/*
  Stepper Motor Test
  stepper-test01.ino
  Uses MA860H or similar Stepper Driver Unit
  Has speed control & reverse switch

  DroneBot Workshop 2019
  https://dronebotworkshop.com
*/

// Defin pins

int reverseSwitch = 2;  // Push button for reverse
int driverPUL = 7;    // PUL- pin
int driverDIR = 6;    // DIR- pin
int spd = A0;     // Potentiometer

// Variables

int pd = 500;       // Pulse Delay period
boolean setdir = LOW; // Set Direction

// Interrupt Handler

void revmotor (){

  setdir = !setdir;

}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  pinMode (driverPUL, OUTPUT);
  pinMode (driverDIR, OUTPUT);
  attachInterrupt(digitalPinToInterrupt(reverseSwitch), revmotor, FALLING);

}

void loop() {

    pd = map((analogRead(spd)),0,1023,1000,150);
    digitalWrite(driverDIR,setdir);
    digitalWrite(driverPUL,HIGH);
    digitalWrite(LED_BUILTIN, HIGH);
    delayMicroseconds(pd);
    digitalWrite(driverPUL,LOW);
    delayMicroseconds(pd);

}

This works perfectly with my stepper driver and stepper motor with good speed control. However, the author did warn that debounce might be a problem and this has proved to be the case. I understand the principal of debounce and I have studied a number of debounce sketches and can also understand the method of reduction using a few milliseconds delay. I believe that the following code is as simple as it can get but I have no idea how to incorporate this in the above sketch.
bool debounce() {
  static uint16_t state = 0;
  state = (state<<1) | digitalRead(btn) | 0xfe00;
  return (state == 0xff00);
}

(The author appears to have split the code into two parts (I think)
#define btn 2  //assuming we use D2 on Arduino

void setup() {
  pinMode(btn, INPUT_PULLUP);
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  if (debounce()) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
  }
}

Can anyone look at these sketches and advise me if a) they are compatible and b) how do incorporate the debounce code into the working sketch?
Thanks in advance from a complete coding numptee (Scottish expression!)

what's the purpose of digitalWrite(LED_BUILTIN, HIGH); in the first code? ... it makes no sense to execute it repeatedly

The author appears to have split the code into two parts ... the author used a function ... it is grouping code into sections that are more easily managed

There are some simple to use debouncing libraries out there. I suggest you just use one of these instead of coding the debounce logic yourself.

My apologies, I was trying to use the digital write for the internal LED to see if I could spot when a transition from Hi to Lo took place. Thank you fpr pointing out that the author has used a function, but at my level of learning that still does not mean anything to me. Please be aware - I am a total novice at coding. This is why I am looking to you guys for help. Give me block of aluminium and I weill machine the most intricate device you want but show me an Arduino sketch and my brain does not compute.

Edgar Bonet - I'm aware that there are simple debounce libraries out there but I don't even know how to add a library to the simple code that I have working. Also, I cannot define a "simple" debounce library from a complicated one, hence why I need help.

I was trying to use the digital write for the internal LED to see if I could spot when a transition from Hi to Lo took place ... you cannot accomplish that by blindly turning on the LED a few microseconds after the program starts and never turning it off ... set it to value of setdir, instead of the value of HIGH

You can try replacing the function revmotor() with this code. That is instead of using the separate debounce code that you have found.
It works by locking out presses of the switch for 100ms following the last press.
void revmotor (){
  static uint32_t lastSwitchAtMs = 0 ;
  if ( millis() - lastSwitchAtMs > 100UL ) {  // debounce 100ms
    setdir = !setdir;
  }
  lastSwitchAtMs = millis() ;
}

Note that the variable setdir should really be declared so volatile boolean setdir = LOW; // Set Direction
EDIT:
Incidentally, found the article that you followed here: https://dronebotworkshop.com/big-stepper-motors/ which includes the code and a schematic diagram.

This has worked perfectly. Thank you. I have tweaked the debounce delay up to 400 millis which works best with the switch that I am using. Thanks again.

@Solmod 400ms ? That must be some rough old switch but, anyway, I am happy that you have something which you can use. The code I supplied is a special case because it is not so usual  to use an interrupt service routine to read a switch/button (overkill or sledgehammer to crack a nut) but there are cases where it is valid for example when the loop contains some blocking code.

The "switch" is actually the bare end of two wires at the moment until I could get everything working. Now that it works, I will be building up the physical circuit in a control box with a good quality press button switch - I may be able to reduce the period after that ;-). Anyway, thank you for you assistance - it has helped me a lot.

I believe that the debounce() function and example was from me that I described in my blog post The simplest button debounce solution, in fact I was not the one who first write it, I adapted it from Jack Gansslle's A Guide to Debouncing - Part 2 that was first published way back to 2004.
In your case, all you need to do is when revmotor() event is triggered, called the debounce function and alter the state of setdir only if debounce return true.

int reverseSwitch = 2;  // Push button for reverse

void revmotor (){

  if (debounce())
    setdir = !setdir;

}

bool debounce() {
  static uint16_t state = 0;
  state = (state<<1) | digitalRead(reverseSwitch) | 0xfe00;
  return (state == 0xff00);
}

void setup() {
  // your pin setup code here
  pinMode(reverseSwitch, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(reverseSwitch), revmotor, FALLING);
}

I must say that I did not test this particular code before post this answer, but I've been using it in similar use case in the past many times.

Thank you for getting involved - it is much appreciated. I have tried to follow your suggestions and I have altered my code accordingly, however, I get an error message saying "debounced" not declared in this scope. I'm not sure if I am reading this correctly but  I see that the if (debounced) statement comes before the Bool debounce statement - does this have an impact on the program?

My code now looks like this:
void revmotor (){
if (debounced())
setdir = !setdir;
}
bool debounce() {
static uint16_t state = 0;
state = (state<<1) | digitalRead(reverseSwitch) | 0xfe00;
return (state == 0xff00);
}
void setup() {
pinMode (driverPUL, OUTPUT);
pinMode (driverDIR, OUTPUT);
attachInterrupt(digitalPinToInterrupt(reverseSwitch), revmotor, FALLING);
}

OK - problem solved - tiny spelling error debounce / debounced. code is running now although the debounce action is still a little erratic. I'll keep experimenting. Thank you.

You could change the 0xfe00 to 0x8000 and 0xff00 to 0xc000 to have longer debouncing period.

Thank you again for your input. For me to understand what this change will do, could you explain what the changes mean please.

The 0xfe00 is B1111,1110,0000,0000, as the button bounced between 1 and 0 until it finally reach to stable 0, the debounce() function is basically looking for a train of consecutive 0 after the last bouncing, 0xfe00 is looking for a train of consecutive 8-bit of 0. The 0x8000 is looking for a longer consecutive of 14-bit of 0 (0x8000 is B1000,0000,0000,0000) so after the last bouncing (i.e. the 1) occured. Read my original blog or Jack Ganslle's article for more detail explanation.

If this still not sufficient to handle the bouncing, you could add a slight delay(1) in the debounce() to improve the reliability.


text:
Infrared Low Frequency Transmission
I have some basic code that I will soon expand for my project which is a universal remote for air conditioners. I have all of the codes but the problem is 3 of the codes are below 1khz. (500hz). My sketch doesn't allow for anything to go lower and the frequency in the actual code doesn't seem to go that low. 108 is 38khz.
uint16_t fuck[] = {0,108,0,0,347,173,22,22,22,22,22,22,22,65,22,65,22,65,22,22,22,22,22,65,22,65,22,65,22,22,22,22,22,22,22,65,22,65,22,22,22,65,22,22,22,22,22,65,22,22,22,22,22,22,22,65,22,22,22,65,22,65,22,22,22,65,22,65,22,65,22,1527,347,87,22,3692};
static uint16_t sent_array_numbers;
static uint8_t ir_seq_index = 4;
static uint8_t pin_state;

void ir_on()
{
  TCCR1A |= 192;
  pin_state = 1;
}

void ir_off()
{
  TCCR1A &= -193;
  pin_state = 0;
}

void ir_toggle()
{
  if (pin_state)
    ir_off();
  else
    ir_on();
}

void ir_start()
{
  DDRB |= 10;
  ICR1 = 416;
  OCR1A = 104;
  TCCR1A = 2;
  TCCR1B = 24;
  TIMSK1 = 1;
  ir_on();
  TCCR1B |= 1;
}

ISR(TIMER1_OVF_vect) {

  sent_array_numbers++;

  if (sent_array_numbers == fuck[ir_seq_index]) {
    ir_toggle();
    sent_array_numbers = 0;
    ir_seq_index++;

       }
}

void setup() {
  ir_start();
}

void loop() {

}

what is your question?

what is running at the frequency of 500 Hz, and how did you determine it?

You have nothing to reset ir_seq_index, so once you got through the array, it will still increment. Then you will get garbage, since you are reading from outside the array.

If you want the timer to run slower, you could change its settings, for example raising the prescaler

Where did you get this code from? Also the array for the IR code looks very odd. There shouldn't be any zeros in it. Also, most IR codes start with a long pulse, while yours kind of ends with two.

@jsotola I can't go down to 500hz, how would I go about solving that? And I determined it because I checked the frequency :O

@chrisl it's example code to get the concept, not the actual project. Also what do you mean by prescaler?

@Gerben some parts of ir codes arent actually required, some ir spammers actually cut out like half the code and works fine. Also the code is the real ir code. The actual microseconds sent. It's just prontohex converted into uint16 (uint16 seems to only be the working one). It's so I don't have to waste time, and space decoding pronto hex back into uint. When I can just use less memory etc and send the real code.

Your whole question is not very clear, so I will mainly give you explanations, of how the Timer code works (since you don't seem to understand that) and give hints.
Let's look at ir_start(), where you configure Timer1 for the IR operation:
void ir_start()
{
  DDRB |= 10;
  ICR1 = 416;
  OCR1A = 104;
  TCCR1A = 2;
  TCCR1B = 24;
  TIMSK1 = 1;
  ir_on();
  TCCR1B |= 1;
}

First you should better not use the decimal representation of numbers here. Most of them consist of single or few bits, that a bound to a specific configuration option. You can better see, what is going on, when you use hex or better binary. So instead of DDRB |= 10; you would write DDRB |= 0b1010; (0b marking the binary representation, and 1010 being the binary representation of 10). That makes it easier to read by others or by you, when you leave that code for a time and come back to it. Using decimal is good in the cases, where you write registers, that represent a single value (like ICR1).
Now let's go through each line. Here I will only state, what the line does, not if that makes sense or if it is correct.
DDRB |= 10;

is equal to DDRB |= 0b1010 and will set will configure PB1 and PB3 (pin 9 and 11 on the Uno) as output pins.
ICR1 = 416;

sets the input capture register 1, which - when not in input capture mode - sets the TOP value of the Timer, meaning the max value, to which it will count until overflow.
OCR1A = 104;

sets the timer value, where the Timer will toggle the output compare pin A of Timer1 (PB1, aka pin 9) (of course only, if the output compare mode is activated).
TCCR1A = 2;

is equivalent to TCCR1A = 0b00000010. It disables the output compare mode, thus normal port operation. Also bit WGM11 is set to 1 and WGM10 is set to 0 (explanation with the next line).
TCCR1B = 24;

is equal to TCCR1B = 0b00011000. It sets WGM12 and WGM13 to one. Together with the other bits of the last line, this sets the Timer mode to FastPWM, counting to the value in ICR1, resetting there. Also the clock source bits are all set to zero, so disabling the Timer.
TIMSK1 = 1;

This enables the Timer1 overflow interrupt, and is of course equal to TIMSK1 = 0b1.
In ir_on() you use
TCCR1A |= 192;

which is equal to TCCR1A |= 0b11000000. It enables the output compare for OC1A, configured for setting it at the compare match and clearing it on resetting (also called inverted mode).
TCCR1B |= 1;

will set the clock source of the Timer to the main clock without any prescaler. A prescaler would scale the counter values. For example with a prescaler of 8 (setting the clock source bits to 0b010) would mean, that the Timer value would increment by one every 8 clock transitions, instead of on every transition. Here you have no prescaler, so the Timer runs with full speed. You can make it slower by changing the prescaler. The fine tuning can then be done by changing the ICR1 value, which is used as TOP. Setting the clock source will also turn the Timer on.
Then in ir_off() you use
TCCR1A &= -193;

Decimal -193 is a value, that needs 2 bytes as a signed integer (twos-complement). It's binary value is 0b11111111 00111111. You assign to a 1 byte register, so the high byte will be cut off. So you actually use the decimal value 63. It will disable the output compare for OC1A, so disabling the PWM output on the OC1A pin.
So, to sum up the actual function of that code: The Timer is configured to run from 0 to 416 without any prescaler. At the value 104 the OC1A pin is set, on timer reset/overflow it is reset. The frequency of the signal will be 16MHz / 416 = 38,5 kHz, with a duty cycle of (416 - 104) / 416 = 75%.
By changing ICR1 and OCR1A, you can go down to 16MHz / 65535 = 244Hz. So for a frequency of 500Hz, you could use the ICR1 value 32000. For the same duty cycle you then need the OCR1A value of 8000.
If you need an even lower frequency, you could use the prescaler by setting the clock source bits correspondingly.
Note: You use the timer overflow as your smallest time measure (since you are incrementing sent_array_numbers in the ISR). So by changing the Timer frequency, you also change the amount of time, that one increment of sent_array_numbers represents. While this time is 1 / 38.5kHz = 26.3us with 38.5kHz, it will be 1 / 500Hz = 2ms for 500Hz. Just keep that fact in mind, when writing the IR pulse values into the array.
You can read about all this in the datasheet of the Atmega328p, which is used in the Arduino Uno.

Notes besides the Timer configuration:

Make sure, that all variables, that get changed inside of an ISR, are declared as volatile, so that the compiler knows, that the variable can change at any time and that it cannot optimize the access to it.

Make sure, that the index, that you use with the array, is not exceeding the size of the array. Otherwise you will read from whatever was placed behind that array in the memory.

Every variable should have a fitting speaking name, which tells exactly, what it is. Its function might not be that obvious, when you look at your code after a few years.

The first 4 values in the array with the IR codes are not used. From your code I cannot understand, why. (Though you suggested, that this is not the complete code).

I hope, that helps. If not, then you need to be more precise with your question. And provide a complete compilable minimal example code.

I can't yet test it (Arduino broke) but from the looks of it this looks to be correct. Thanks alot <3. I'll post code when I can get my arduino to work again :)


text:
Programming custom Arduino Mega with Arduino Uno
I'm making a custom board with AtMega2560-16AU as MCU and CH340G as bootloader (schematic can be seen in the picture).  I have printed the custom PCB and soldered everything in place now I want to program the bootloader.

I connected my Arduino UNO with my custom board like shown in the fritzing schematic below. My custom pcb doesn't look like Arduino MEGA but the connections are the same.

I go to Arduino IDE and upload the ArduinoISP example (baudrate:115200) while choosing programmer as "Arduino as ISP".

And when I upload the example I get a response like this:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : arduino
         Overriding Baud Rate          : 115200
         AVR Part                      : ATmega328P
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PC2
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff
           flash         65     6   128    0 yes     32768  128    256  4500  4500 0xff 0xff
           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : Arduino
         Description     : Arduino
         Hardware Version: 3
         Firmware Version: 4.4
         Vtarget         : 0.3 V
         Varef           : 0.3 V
         Oscillator      : 28.800 kHz
         SCK period      : 3.3 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.00s

avrdude: Device signature = 0x1e950f (probably m328p)
avrdude: reading input file "C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex"
avrdude: writing flash (4354 bytes):

Writing | ################################################## | 100% 0.68s

avrdude: 4354 bytes of flash written
avrdude: verifying flash memory against C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex:
avrdude: load data flash data from input file C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex:
avrdude: input file C:\Users\ahmet\AppData\Local\Temp\arduino_build_251950/ArduinoISP.ino.hex contains 4354 bytes
avrdude: reading on-chip flash data:

Reading | ################################################## | 100% 0.53s

avrdude: verifying ...
avrdude: 4354 bytes of flash verified

avrdude done.  Thank you.

As far as I know so far there's no problem.
And now I move to step 2 which now requires me to switch the board to ArduinoMega from tools. And click burn bootloader.

When I click burn bootloader I get a response like this:
avrdude: Version 6.3-20190619
         Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/
         Copyright (c) 2007-2014 Joerg Wunsch

         System wide configuration file is "C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\hardware\tools\avr/etc/avrdude.conf"

         Using Port                    : COM4
         Using Programmer              : stk500v1
         Overriding Baud Rate          : 19200
         AVR Part                      : ATmega2560
         Chip Erase delay              : 9000 us
         PAGEL                         : PD7
         BS2                           : PA0
         RESET disposition             : dedicated
         RETRY pulse                   : SCK
         serial program mode           : yes
         parallel program mode         : yes
         Timeout                       : 200
         StabDelay                     : 100
         CmdexeDelay                   : 25
         SyncLoops                     : 32
         ByteDelay                     : 0
         PollIndex                     : 3
         PollValue                     : 0x53
         Memory Detail                 :

                                  Block Poll               Page                       Polled
           Memory Type Mode Delay Size  Indx Paged  Size   Size #Pages MinW  MaxW   ReadBack
           ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- ---------
           eeprom        65    10     8    0 no       4096    8      0  9000  9000 0x00 0x00
           flash         65    10   256    0 yes    262144  256   1024  4500  4500 0x00 0x00
           lfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           hfuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           efuse          0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           lock           0     0     0    0 no          1    0      0  9000  9000 0x00 0x00
           calibration    0     0     0    0 no          1    0      0     0     0 0x00 0x00
           signature      0     0     0    0 no          3    0      0     0     0 0x00 0x00

         Programmer Type : STK500
         Description     : Atmel STK500 Version 1.x firmware
         Hardware Version: 2
         Firmware Version: 1.18
         Topcard         : Unknown
         Vtarget         : 0.0 V
         Varef           : 0.0 V
         Oscillator      : Off
         SCK period      : 0.1 us

avrdude: AVR device initialized and ready to accept instructions

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0xffffff (probably .avr8x_mega) (retrying)

Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000 (retrying)

Error while burning bootloader.
Reading | ################################################## | 100% 0.02s

avrdude: Device signature = 0x000000
avrdude: Yikes!  Invalid device signature.
         Double check connections and try again, or use -F to override
         this check.

avrdude done.  Thank you.

Now when I clicked burn the bootloader I got a response saying invalid signature.
So far I tried to:

Change baudrates and try the same steps.
Tried to change the avrdude.txt file. I tried to change the
signature that was searched for which I couldn't change it because
windows 10 wouldn't allow me even though I gave myself all the admin
permissions.

So as a solution to this signature problem people have put an electrolytic capacitor that has 10nF or 10uF value between GND and RST pins of the programmer Arduino.
Also when I tried this for the first time I got a value different than "Off" for oscillator in the 2nd step.
So what should I do? Do I need to change my oscillator and try again or do I need that polarized 10uF capacitor?
Sorry for poorly formatting this post. Thank you so much for reading. Any answers would be appreciated.

Please no capslock. Thats like shouting and its difficult to read

"10nF or 10uF".  10nF will not to the job.  If you've been testing with 10nF switch to 10uF an see what happens.

@timemage I haven't tried either of those. I'm asking if it would help at all.

Defeating the UNO's DTR reset mechanism is a necessity when using it as a programmer (arduinoisp.ino).  A 10uFcap between RESET and GND is a a way to do that.  In short, yes it will help.  It should have been mentioned in whatever tutorials and documentation you've been following.

A 10-100uF capacitor on the reset pin of the "master" Arduino prevents it from resetting when the Serial port is opened, which would interfere with the process of writing the bootloader to the Mega2560. There are other ways to prevent this, but this is one of the simplest.

@StarCat I tried both 10uF and 100uF capacitors (16V polarized electrolytic) they both didn't work. 10uF made it so that I couldn't upload sketches to UNO. 100uF didn't change anything but I could upload sketches.

Have you tried dedicated ISP programmer like USBasp or USBtinyISP? Have you tried Avrdudess to read out fuse settings and or just trying to detect the MCU to see if it still responses to ISP command?

@SimonVu14 No I haven't, thank you for your recommendation.

I finally found the problem with this board. I had a 22pF capacitor between RST and GND on the board I had ordered.
You should not have a capacitor there or it should be 100nF, values such as 22pF or 10nF will cause the board to malfunction and therefore you can't burn the bootloader.

I have not yet tried the 100nF cap but I soon will try and update the answer.


text:
when i compile my code i get th is error stating "checkbutton" not declared in this scope
// After 2 seconds have passed, stop ignoring the button.
  // If the button is pressed, call the checkbutton function.
  if (millis() > ignore && digitalRead(0) == LOW)
  {
    checkbutton();
  }
}
// This function waits for the button to be released,
// then waits for it to be pressed to start the next run.
void checkbutton(){
  delay (50);  // Button pressed, debounce.
  while (digitalRead(0) == LOW) // While button is pressed,
  {}                            // do nothing while waiting.
  delay (50);                   // Button pressed, debounce.
  while (digitalRead(0) == HIGH)// While button is released,
  {}                            // do nothing while waiting.

  ignore = 2000 + millis();     // Set the now ignore time,
}                              // and return to the main loop.

Please update your sketch to add a setup() and loop() function, then add your code to it with proper formatting.

please do not be offended, but i downvoted your question because you posted a complete mess ... did you not look at what you posted? ... please format your code ... use the {} button to do the formatting ... also, please ask a question

You need to provide a fully functional code, not only a snippet of your code. That will not work alone. Also you need to include the complete error message, including the line number, where the error happened.

Are you using the Arduino IDE to compile? It will automatically add function prototypes to the top of your code. When you are using something else to compile, you need to declare every function above where you are using it

You are using checkbutton() before you have told the program what checkbutton() is.
You need to move the whole method definition void checkbutton(){ ... } more to the top, i.e. in front of any call to it (checkbutton();).
Another option would be a forward declaration, but I doubt it's widely used in Arduino projects.

@jsotola: that's true. I don't think this is widely used in Arduino projects. Anyway, I added that to the answer

The only reason it isn't widely used is because the IDE does it for you - invisibly. While that helps people just learning C and C++ to get something up and running quickly, they miss learning about forward declarations, which inevitably bites them when they move to another environment.


text:
How esp8266 gets response from server..?
#include <SoftwareSerial.h>

const byte rxPin = 2;
const byte txPin = 3;

SoftwareSerial ESP8266 (rxPin, txPin);

void setup() {
  Serial.begin(115200);
  ESP8266.begin(115200);
  delay(2000);
}

void printResponse() {
  String s="";
  while (ESP8266.available()) {
    s+=ESP8266.readStringUntil('\n');
  }

  Serial.println(s);
  // now here you can parse and look for "+IPD" look for another line ending (if there is) and then extract the numeric value.
}

void loop() {

  ESP8266.println("AT+CIPMUX=1");
  delay(1000);
  printResponse();

  ESP8266.println("AT+CIPSTART=4,\"TCP\",\"www.tcpss.000webhostapp.com\",80");
  delay(1000);
  printResponse();

  String cmd = "GET /test.html HTTP/1.1";
  ESP8266.println("AT+CIPSEND=4," + String(cmd.length() + 4));
  delay(1000);

  ESP8266.println(cmd);
  delay(1000);
  ESP8266.println();
  delay(1000);
  printResponse();

  delay(5000);
}

i have run this code and i am able to get this  response from server like "+ipd 4,41".... what does it mean?
here is the response after run the code in arduino......
WIFI GOT IP
AT+CIPLUX=1

OK
AT+CHPSTART=4,"TCP","www.tcpss.000webhostapp.com",80

4,CONNEC
AR)CR5NB⸮b⸮⸮k

j⸮L⸮⸮
Recv 27 bytes

SEND OK

+IPD,4,41

Thanks in advance.....

Your seeing corruption from running software serial at 115200 baud.

There's two things to know here:

You're seeing corruption in your output because SoftwareSerial is not capable of working reliably at 115200 baud. You need to reconfigure your ESP8266 to operate at a lower baud rate (such as 9600) to be able to use it with an Arduino that doesn't have enough physical UARTs.
The response +IPD,4,41 is telling you about the response. It's not itself the response.

It means "IP Data on channel 4 of length 41". It is then your responsibility to request that data from the ESP8266 using whatever AT command the ESP8266 requires.
Personally I would scrap the AT firmware and program the ESP8266 directly. That way you solve both problems: you can choose what baud rate to communicate at (if you even need to communicate to an Arduino at all), and you have no AT commands to parse or craft. It is a far more efficient way of working with the ESP8266 that trying to fudge things with the AT firmware and an Arduino.

Thanks this answer was helpful for me...

But i want to know that when i change the baud rate in serial moniter, its changed but the response from esp8266 on AT commands not show why? if i did wrong, then what i need to to solve this issue.

secondly, i want to know which AT commands esp8266 requires to to request data from esp8266 or code which i need to used in the arduino ide....

You have to change the baud rate on the ESP itself as well as the Arduino. There's an AT command to do it, but it has been known to brick the ESP. there's different versions of the firmware and commands differ between them. There's a PDF available online somewhere that lists all the commands.

SoftwareSerial does not works well for baud rate higher than 9600bps, you need to change your Arduino and ESP8266 to operate at 9600bps.

Use the AT+UART_DEF=9600,8,1,0,0 to set the ESP8266 to 9600Baud, with 8 bit, 1 stop bit and no parity. And also remember to configure the Arduino accordingly. The AT command with _DEF suffix means it will only need to be set once and the configuration will be saved in the ESP8266. ESP8266 AT Command Set would be handy when programming the ESP8266 with AT Commands.

Add longer delay after sending AT+CIPSEND and Get request as those network activities sometime take longer time to establish.

The +IPD,4,41 means that Connect 4 (which you established with AT+CIPSTART is connected and there are 41 bytes payload waiting to be read. You can refer to ESP8266 AT Command Examples for more information.


text:
How to combine two codes in arduino?
bine
#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

#define sensor A0
#define led 13
#define ledd 8  // d out from mq3
#define buz 9
#define motor 10
void setup()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("ALCOHOL MONITORING");
  lcd.setCursor(0,1);
  lcd.print(" VEHICLE SYSTEM ");
  delay(2000);
  pinMode(sensor, INPUT);
  pinMode(buz, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(ledd, OUTPUT);
  pinMode(motor, OUTPUT);
  lcd.clear();
}

void loop()
{
  float adcValue=0;
  for(int i=0;i<10;i++)
  {
    float actualanalogReading =  analogRead(sensor);
    adcValue = adcValue + actualanalogReading;
    Serial.println("In loop counter >"); // logging
    Serial.print(i);
    Serial.print(" input reading : ");
    Serial.print(actualanalogReading);
    Serial.print(" cumulative input reading : ");
    Serial.print(adcValue);

    delay(10);
  }
    float v= (adcValue/10) * (3.0/1024.0);
    float mgL= 0.67 * v;
    Serial.println("");
    Serial.print("Post calculation v value >" );
    Serial.print(v);
    Serial.print(" mg/L > ");
    Serial.print(mgL);
    Serial.println("");
    Serial.print("BAC:");
    Serial.print(mgL);
    Serial.print(" mg/L");
    lcd.setCursor(0,0);
    lcd.print("BAC: ");
    lcd.print(mgL,4);
    lcd.print(" mg/L        ");
    lcd.setCursor(0,1);
    if(mgL > 0.8)
    {
      lcd.print("Drunk ENGINE OFF ");
      Serial.println("Drunk ENGINE OFF ");
      digitalWrite(buz, HIGH);
      digitalWrite(led, HIGH);
      digitalWrite(ledd, LOW);
      digitalWrite(motor, LOW);
    }
    else
    {
      lcd.print("Normal ENGINE ON ");
      Serial.println(" Normal ENGINE ON ");
      digitalWrite(buz, LOW);
      digitalWrite(led, LOW);
      digitalWrite(ledd, HIGH);
      digitalWrite(motor, HIGH);
    }

    delay(100);

}

top code^^^
combines with this>>
const int LED = A5;
const int DO = 6;
void setup() {
 Serial.begin(9600);
 pinMode(LED, OUTPUT);
 pinMode(DO, INPUT);
}
void loop() {
 int alarm = 0;
 float sensor_volt;
 float RS_gas;
 float ratio;
//-Replace the name "R0" with the value of R0 in the demo of First Test -/
 float R0 = 0.10;
 int sensorValue = analogRead(A1);
 sensor_volt = ((float)sensorValue / 1024) * 5.0;
RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module
 ratio = RS_gas / R0; // ratio = RS/R0
//------------------------------------------------------------/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 alarm = digitalRead(DO);
 if (alarm == 1) digitalWrite(LED, LOW);
 else if (alarm == 0) digitalWrite(LED, HIGH);
 delay(1000);
}

Do you know how both "codes" work?

@majenko both works just need to know how to combine them

@chrisl still not that familiar with them terms can you help me combine them and maybe i can see what you add and remove

I didn't ask if they both worked. I asked if you knew how they both worked. If you don't know how they work then there is no way you will be able to combine them.

What exactly is your problem in combining them? With what terms aren't you familiar? I will gladly answer your questions, but honestly I don't want to write the code for you. There is no simple answer to your current questions (other than the one I linked), because it is a rather broad question unless we do all your work for you. As Majenko stated, the key in combining 2 sketches is to understand how they work. Then you can decide how the final program should work and write a new code with fitting snippets of the previous codes

And you should look into the BlinkWithoutDelay example, which comes with the Arduino IDE. It shows how you can use the millis() function to write non-blocking code without delay() calls. It is an important principle to learn and may be really helpful when combining your sketches

While I'd like to direct you to ways to set up a nice tasking system with a frame counter, your system is likely simple enough that it is unnecessary.  You can likely just replace the delay(1000); of the second program with approximately 5 calls of the first program's loop.  May you instead learn something when cleaning up the following (which is literally a copy paste with minimal changes).

#include <LiquidCrystal.h>
LiquidCrystal lcd(12,11,5,4,3,2);

#define sensor A0
#define led 13
#define ledd 8  // d out from mq3
#define buz 9
#define motor 10
void setup1()
{
  Serial.begin(9600);
  lcd.begin(16,2);
  lcd.print("ALCOHOL MONITORING");
  lcd.setCursor(0,1);
  lcd.print(" VEHICLE SYSTEM ");
  delay(2000);
  pinMode(sensor, INPUT);
  pinMode(buz, OUTPUT);
  pinMode(led, OUTPUT);
  pinMode(ledd, OUTPUT);
  pinMode(motor, OUTPUT);
  lcd.clear();
}

void loop1()
{
  float adcValue=0;
  for(int i=0;i<10;i++)
  {
    float actualanalogReading =  analogRead(sensor);
    adcValue = adcValue + actualanalogReading;
    Serial.println("In loop counter >"); // logging
    Serial.print(i);
    Serial.print(" input reading : ");
    Serial.print(actualanalogReading);
    Serial.print(" cumulative input reading : ");
    Serial.print(adcValue);

    delay(10);
  }
    float v= (adcValue/10) * (3.0/1024.0);
    float mgL= 0.67 * v;
    Serial.println("");
    Serial.print("Post calculation v value >" );
    Serial.print(v);
    Serial.print(" mg/L > ");
    Serial.print(mgL);
    Serial.println("");
    Serial.print("BAC:");
    Serial.print(mgL);
    Serial.print(" mg/L");
    lcd.setCursor(0,0);
    lcd.print("BAC: ");
    lcd.print(mgL,4);
    lcd.print(" mg/L        ");
    lcd.setCursor(0,1);
    if(mgL > 0.8)
    {
      lcd.print("Drunk ENGINE OFF ");
      Serial.println("Drunk ENGINE OFF ");
      digitalWrite(buz, HIGH);
      digitalWrite(led, HIGH);
      digitalWrite(ledd, LOW);
      digitalWrite(motor, LOW);
    }
    else
    {
      lcd.print("Normal ENGINE ON ");
      Serial.println(" Normal ENGINE ON ");
      digitalWrite(buz, LOW);
      digitalWrite(led, LOW);
      digitalWrite(ledd, HIGH);
      digitalWrite(motor, HIGH);
    }

    delay(100);

}

const int LED = A5;
const int DO = 6;
void setup() {
 setup1(); //Serial.begin(9600);
 pinMode(LED, OUTPUT);
 pinMode(DO, INPUT);
}
void loop() {
 int alarm = 0;
 float sensor_volt;
 float RS_gas;
 float ratio;
//-Replace the name "R0" with the value of R0 in the demo of First Test -/
 float R0 = 0.10;
 int sensorValue = analogRead(A1);
 sensor_volt = ((float)sensorValue / 1024) * 5.0;
RS_gas = (5.0 - sensor_volt) / sensor_volt; // Depend on RL on yor module
 ratio = RS_gas / R0; // ratio = RS/R0
//------------------------------------------------------------/
 Serial.print("sensor_volt = ");
 Serial.println(sensor_volt);
 Serial.print("RS_ratio = ");
 Serial.println(RS_gas);
 Serial.print("Rs/R0 = ");
 Serial.println(ratio);
 Serial.print("\n\n");
 alarm = digitalRead(DO);
 if (alarm == 1) digitalWrite(LED, LOW);
 else if (alarm == 0) digitalWrite(LED, HIGH);

 for(int dd = 0; dd < 5; dd++) loop1();
}