text:
Can this work as a waterproofing method?
Im making my garden automated with temperature, humidity and soil temperature sensors. I want to be able to connect my Arduino Uno to a solar panel and keep it outside at all times. I dont want to have to remove it to water the plants. Could I cover it in clear nail polish to water proof it?

Is there a reason why you don't want to use a weatherproof enclosure?

need access to changing the pins where cables are connected.

@Tech2025 And how would nail polish be better at that?

Use a LilyPad? They are washable. Might need to cut the power when watering the plants?

If you don't varnish the pin headers, those won't be water-proof. Just get an enclosure. Unrelated; please don't use an UNO for this. An Uno just pisses away power with it's usb-to-serial chip and very inefficient voltage regulator.

Nail polish would work in general as a fair conformal coating. However, conformal coatings are not generally intended as waterproofing, but moisture or humidity resistance.
If you product is going to be regularly submerged or deluged with water, you are better off using a waterproof enclosure with a good watertight gland around the cable entrance.

Thanks. Im using the nail polish and it has worked great. No problems with anything. I've gone ahead and bought my self some Elegoo Uno's since they are so cheap and do the same.


text:
Arduino Nano and SIM800L on Battery Power
I'm very new to Arduino and everything related but I'm highly interested to learn more. However, I've run into a problem right in the beginning.
I want to build some sort of portable emergency/notification button. One pushes the button and an SMS is sent or an HTTP call made to a server. I want to base this project on the Arduino Nano as it's quite small and therefore easily transportable. To have GSM/GPRS connectivity I found the SIM800L which seems quite suitable to what I have in mind. Now to the big question, how to power the Arduino Nano as well as the SIM800L on an portable power source, preferrably only one power source.
From my understanding, the SIM800L requires a peak current of 2A when doing handshakes and sending signals. Is there any way I can power the SIM800L through the Arduino Nano, like Battery -> Arduino Nano -> SIM800L, or do I need to connect both the Arduino Nano and the SIM800L to the battery?
Regarding the lifespan, for now it would be sufficient if I could press the button a few times and afterwards it'd stop working.

Check out

Thin battery to power arduino micro with nRF8001?

Also, I found a 6v battery (A544) at Menards that is about the same diameter as a AA, but is considerably shorter. It has 178 mAh capacity.
I haven't taken the time to test it, but I would guess it wouldn't have as much of a temperature issue.
It's not as small as the CR2032 in the above mentioned link, nor is it flat, but it's an option.
You might consider an Arduino Beetle. They are really super incredibly tiny and still 16mHz. I can't get any more info from where I'm at, but I'd believe they would use even less power than a Nano/Micro.
I found an Instructable that shows how to use a Beetle, a rechargeable 3.7v LiPo battery, and an HC-06 Bluetooth module. Sounds like it's equivalent to what you're looking for.
http://www.instructables.com/id/Beetle-Minimize-Your-Arduino-Projects/

I did use a big electrolytic polarized capacitor in parallel with the sim800l power pins (like 470uF 16v) on an uno.
It will handle the power on peak :)

When you are using a Arduino nano for your project you wont be able get the 2A current draw form the board.You have to use a external power source like a battery.You have to find a better battery with a considerable Ahs.

source: Stack Exchange

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

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

sort: votes


text:
What Ohm Termination Resistor is needed for this schema ? What, Where and How?
I'm building a Master-Slave system using some arduino pro mini as slaves and a Mega 2560 as Master to communicate over RS485 config via MAX485. Since i'm newbie in RS485 i know that i need to put some termination resistor somewhere is the line but i don't know where and how, also i don't know how much ohm should it be. My Baud rate is 9600 and i'm using twisted pair cable (CAT5) and it's 120 meters long.
UPDATE 1:
My goal is to get data from each slave time to time, every slave is connected to a temperature sensor and sends temperature value to master on demand (when master asks for it.) The master asks for temperature value from all slaves separately (of course!) and repeatedly every 500 ms. First it asks slave 1 to send data and then slave 1 sends data to master, then master asks slave 2 to send data and slave 2 sends data to master and so on. after 500 ms, it does this again.

UPDATE 2:
Master side code (Mega 2560):
#include <AltSoftSerial.h>
#define DE 2 //RS485 Data enable pin. HIGH=Transmit, LOW=Receive
String inputS = "";
boolean stringComplete = false;
AltSoftSerial altSerial;

void setup() {
 altSerial.begin(9600);
 Serial.begin(9600);
 pinMode(DE, OUTPUT);
}

void loop() {
 digitalWrite(DE, HIGH); //Transmit
 altSerial.println("MEGA:ProMini1");
 altSerial.flush();
 digitalWrite(DE, LOW); //Receive
 CheckAndReceiveFromMax(); //Check if data received
 if(stringComplete){
   inputS.trim();
   if(inputS.equals("ProMini1:ACK"))
    Serial.println("MEGA: ProMini1 Acknowledged: " + inputS);
   else
    Serial.println("MEGA: Not valid On ProMini1: " + inputS);
   stringComplete = false;
   inputS = "";
 }
delay(100);
digitalWrite(DE, HIGH); //Transmit
altSerial.println("MEGA:ProMini2");
altSerial.flush();
digitalWrite(DE, LOW); //Receive
CheckAndReceiveFromMax();
if(stringComplete){
  inputS.trim();
  if(inputS.equals("ProMini2:ACK"))
    Serial.println("MEGA: ProMini2 Acknowleged: " + inputS);
  else
    Serial.println("MEGA: Not valid On ProMini2: " + inputS);
  stringComplete = false;
  inputS = "";
}
delay(500);
}

void CheckAndReceiveFromMax()
{
 while (altSerial.available()) {
 char inChar = (char)altSerial.read();
 inputS1 += inChar;
 if (inChar == '\n')
  stringComplete1 = true;
 }
}

Slave side code (Pro Mini1):
#include <AltSoftSerial.h>
#define DE 7
String inputS = "";
boolean stringComplete = false;
AltSoftSerial altSerial;

void setup() {
 altSerial.begin(9600);
 Serial.begin(9600);
 pinMode(DE, OUTPUT);
}

void loop() {
 digitalWrite(DE, LOW); //Receive
 CheckAndReceiveFromMax(); //Check if data received
 if(stringComplete){
  Serial.print("String received: ");
  inputS.trim();
  Serial.println(inputS);
  if(inputS.equals("MEGA:ProMini1")){
   Serial.println("ProMini1: Mega called me!");
   digitalWrite(DE, HIGH); //Transmit
   altSerial.println("ProMini1:ACK");
   altSerial.flush();
   digitalWrite(DE, LOW);
  }
 stringComplete = false;
 inputS = "";
 }
}

void CheckAndReceiveFromMax()
{
 while (altSerial.available()) {
 char inChar = (char)altSerial.read();
 inputS += inChar;
 if (inChar == '\n')
  stringComplete1 = true;
 }
}

And the same code for ProMini2, ProMini3 and so on.
OUTPUTS:
When master calls ProMini1, the ProMini2 answers, and when master calls ProMini2, ProMini1 aswers. Also, received data is not always in correct format.
Server Serial Monitor:
 MEGA: Not valid On ProMini1:  roMini1:ACK
  :
MEGA: Not valid On ProMini2: ProMini1:ACK
MEGA: Not valid On ProMini1:  roMini1:ACK

MEGA: Not valid On ProMini2: ProMini1:ACK

MEGA: Not valid On ProMini2:  roMini1:ACK

.
.
.

are you supplying power through the cable? if yes, what is the power voltage at each arduino?

in this schematic yes, but in test environment i used short wire for power supply for each node, but i considered common ground. 5v

remove the ground connections. if the cable is shielded, then connect the shield to ground at one place only. .... have you tested your devices by connecting them a short distance apart? (all on the same bench, for example)

i tested it with short wire just between 1 master and 1 slave and worked properly

Please try it on short wires with all slaves.

why would you not test multiple slave devices? ... how do you even know that your software works correctly? ... you are making assumptions. there is an old saying when you assume, you make an ass of u and me ... lol

You should find your answer here: https://www.maximintegrated.com/en/app-notes/index.mvp/id/763

@Majenko and dear jsotola:
Question Updated

Why are you using software serial on a mega...?

@Majenko: Does it matter ? I can use hardware serial, but no difference

Software serial (of any form) is frowned upon and only used as a last resort.

You might want to take a look at my ICSC library. It's designed for just this kind of environment. https://github.com/MajenkoLibraries/ICSC

@Majenko: your library seems great but there is no tutorial of how to use it and the function list. Can you give me a link of it if exists ? thanks.

@SafaSeed The examples show the use of pretty much all the functions. There's not many. You can find them in the header file near the bottom.

@Majenko if you mean "PingMaster", "PingSlave", "RemoteLEDReceiver" and "RemoteLEDSender" they don't give me of how can i use it in my rs485 bus. For example nowhere in the code DE pin of MAX485 is mentioned! Im totally confused

@SafaSeed Here is an old wiki page - some things may have changed slightly, but not much: https://sourceforge.net/p/arduino-icsc/wiki/Home/

@Majenko:
Please answer to this question:
https://arduino.stackexchange.com/questions/47748/problem-using-icsc-by-majenkotech-in-rs485-bus

For low data speeds, like 9600bps, termination is usually not necessary.

But i cannot get correct data. it works properly when there is just one master and one slave, but as i add a new slave the data received by both master and slaves are incorrect

Your problem may or may not be related to termination. If you revise your question to include more information about what you expect to see, and what you see instead, as well as more information about your setup, such as an example of your code for communication, someone may spot some other solution. See also https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem

Question updated :)

So what does the incorrect data look like? Do you get some answer with wrong values? What values do you send and expect to receive?

Question Updated

try 120ohm carbon resistor, not wirewound, at each end of the line ( two resistors in total)

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


text:
Analog Read gives Erratic behaviour in Struct
I'm getting some very strange behaviour from a Haptic feedback system I'm trying to make.
The test code works fine as a Multiple-In One-Out in the main loop, but once I moved the code to the Struct, I ended up with very erratic behaviour on the motor that is completely independent of pressure on the FSR and bears no correlation.
Bizarrely, the serial data that I have been using to debug the code is also largely unusable now.
Does anyone have any idea what's going on?
(p.s. Don't worry about the current draw of the motor, I'm using tiny mobile phone vibration motors specifically for their low voltage and current draw)
Note: All '[' chars in the code and log have been replaced with '<' and ']' with '>' so that I can actually post this question without the site screaming at me about more than 8 links.
main.cpp:
#include <Arduino.h>
#include "sensorWeighting.h"

const int DIAG_PIN = 2;
short int numMotors;

sensorWeighting* MOTORS;

void setup() {
  Serial.begin(9600);
  MOTORS = new sensorWeighting<1>;
  //motor 1
  MOTORS<0> = sensorWeighting(9,2,new int<2>{0,1},new int<2>{100,60});
  numMotors = 1;//sizeof(MOTORS) / sizeof(sensorWeighting);
}

void loop() {
  //Serial.println("Start Loop.");
  //Serial.print("numMotors = ");
  //Serial.println(numMotors);
  for (short int index = 0; index < numMotors; index++) {
    //Serial.print("Updating Motor: ");
    //Serial.println(index);
    MOTORS<index>.update();
  }
  //Serial.println("End Loop.");
}

sensorWeighting.h:
#include <Arduino.h>
class sensorWeighting {
  private:
    short int output;
    short int inputNum;
    int* input;
    int* weight;

  public:
    sensorWeighting(){}
    sensorWeighting(short int pinOut, short int numInputs, int* inputs, int* weights){
    pinMode(pinOut, OUTPUT);
    output = pinOut;
    inputNum = numInputs;
    input = new int<inputNum>;
    weight = new int<inputNum>;
    for (short int index = 0; index < inputNum; index++) {
      pinMode(inputs<index>, INPUT);
      this->input<index> = inputs<index>;
      this->weight<index> = weights<index>;
    }
  }
    virtual ~sensorWeighting(){
    delete &output;
    delete &inputNum;
    delete<> input;
    delete<> weight;
  }

  void update(){
    Serial.print(inputNum);
    Serial.print(" inputs. ");
    int out = 0;
    for (short int index = 0; index < inputNum; index++) {
      int rawVal = analogRead(input<index>);
      Serial.print("raw input :" + index);
      Serial.println("value: "+rawVal);
      int val = (weight<index>*rawVal)/90;
      if (val>out){
        out = val;
        }
      Serial.print("Evaluating input: Input<");
      Serial.print(input<index>);
      Serial.println("] = " + analogRead(input<index>));
    };
  Serial.println("Raw Output: " + out);
  Serial.print("Trimmed Output: ");
  Serial.println(out/4);
  Serial.println("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
  analogWrite(output, out/4);
    };
};

typedef class sensorWeighting senorWeighting;

Serial Log:

2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :
~w[�?��x��o{Ӿ��˗��{��"����0�������^�������o?WwZ�{����[e���������������?�����/������ѧ����������������}��w����i����s���c�Mo}�����׷ʾ������Ф�m�Y�zo������
  =��������������)��ۺW{r�[w����g׬����-����ߦ]��{�{�w��y�߻��(�?�^���[%}U��7��
  ���|����������}W�ֶo���]��-�ݔ]�������Yo0
  ��쎖w��z9���}��]o���[���K���?9^K����b�����%�s����;S+S���[}Y�1���^
Trimmed Output: 27
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :luating input: Input<
Evaluating input: Input<1> =
put:
Trimmed Output: 1
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
aw input
  :Ӿ��˗��{��"����0�������^�������o?WwZ�{����[e���������������?�����/������ѧ����������������}��w����i����s���c�Mo}�����׷ʾ������Ф�m�Y�zo������
  =��������������)��ۺW{r�[w����g׬����-����ߦ]��{�{�w��y�߻��(�?�^���[%}U��7��
  ���|����������}W�ֶo���]��-�ݔ]�������Yo0
  ��쎖w��z9���}��]o���[���K���?9^K����b�����%�s����;S+S���[}Y�1���^
  ޯ�3���������}�/jv����|��O讝����Ͷ�����������������Ϸ�+�l��s�}m����������������o�~�~�
  8
Evaluating input: Input<1> =
Trimmed Output: 66
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
2 inputs. raw input :value:
Evaluating input: Input<2278> =
aw input :value:
Evaluating input: Input<1> =
Raw Output:
Trimmed Output: 0
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

char array concatenation doesn't work with +.

@gre_gor cheers for that, I'm getting much more usable serial data now.
I can see that the inputs are working, so it's an issue in the workings between I and O.


text:
Sending Multiple Information from BNO055 IMU to BridgeClient on Yun
I have an Arduino Yun which is interfaces via I2C to a Adafruit BNO055 breakout board.
My Aim is to use Python Flask in conjunction with BridgeServer and BridgeClient to obtain the Sensor Information from the ATmega32u4 microcontroller to the Microprocessor and use HTML5 Server Side Event (SSE) to display live sensor information on Network interfaces.
I would like to show the Euler angles and Linear Acceleration values:

heading
pitch
roll
linear_accerlation_x
linear_acceleration_y
linear_acceleration_z

An Example of similar concept can be obtained from Smart Measuring Cup by Adafruit. However, in the code sketch the user sends only one value :
BridgeClient client;
....
client.println(volume, 5);

And at the Python Flask end the code opens up a socket and uses makefile() method to read value
def yunserver_sse():
    try:
        # Connect to YunServer instance that's listening on localhost.
        soc = socket.create_connection(('localhost', 5678))
        socfile = soc.makefile()
        while True:
            # Get data from server.
            line = socfile.readline()
            # Stop if the server closed the connection.
            if not line:
                raise StopIteration
            # Send the data to the web page in the server sent event format.
            yield 'data: {0}\n\n'.format(line)
            # Sleep so the CPU isn't consumed by this thread.
            time.sleep(0)
    except socket.error:
        # Error connecting to socket. Raise StopIteration to quit.
raise StopIteration

Instead of sending just one measured parameter how can I send all above mentioned 6 at the same time?
note
I tried using ArduinoJson library but I find it difficult to parse the JSON on the Python Flask end as readline() expects a \n at the end of the string.

Apparently the solution to my problem was a simple client.println() after my JSON was ready to be printed to the BridgeClient.
Snippet:
root.printTo(client); client.println();

where root is DynamicJsonBuffer from the ArduinoJson library. The client.println() would immediately print \n and this would be read by the readline() python code.


text:
Arduino Mega 2560 serial port location
I am having trouble finding the serial input (or port whatever) on my mega can someone plz show me a pic of this pin thanks

Please read our [ask] page and then edit your question.

what is a port whatever ?

your posting shows no effort to find the answer on your own.

For information on an Arduino board your first stop should always be the product page, which contains some helpful documentation. For the Mega 2560 the page is https://store.arduino.cc/usa/arduino-mega-2560-rev3. If you had checked there you would see this:

Serial: 0 (RX) and 1 (TX); Serial 1: 19 (RX) and 18 (TX); Serial 2: 17 (RX) and 16 (TX); Serial 3: 15 (RX) and 14 (TX). Used to receive (RX) and transmit (TX) TTL serial data. Pins 0 and 1 are also connected to the corresponding pins of the ATmega16U2 USB-to-TTL Serial chip.

You will find those pins on the rightmost header on the top edge of the board in this picture:


text:
Problem : Trigger limit switch to stop DC motor
I want to make a project about automatic gate and garage door via Android app and connected by HC-05 bluetooth module.
Each of the gate and garage door have two limit switches(located at each end of travel) to trigger the DC motor to stop.
I have made some code and do researches, but the DC motor will only stop when I pressed it, if I release it again it will start automatically. I want to make it stop until the bluetooth module send the code again.
I have input the pull-down resistor into the limit switch.
Can anybody please help me?
Here's my current code, thank you
// Motor for Gate (MotorA)
int IN1 = 2;
int IN2 = 3;
int EnableMotorA = 9;

// Motor for Garage Door (MotorB)
int IN3 = 4;
int IN4 = 5;
int EnableMotorB = 10;

const int LimitSwitch1 = A1;
const int LimitSwitch2 = A2;
const int LimitSwitch3 = A3;
const int LimitSwitch4 = A4;

int state;

void setup(){
  pinMode(IN1,OUTPUT);
  pinMode(IN2,OUTPUT);
  pinMode(EnableMotorA,OUTPUT);

  pinMode(IN3,OUTPUT);
  pinMode(IN4,OUTPUT);
  pinMode(EnableMotorB,OUTPUT);

  pinMode(LimitSwitch1, INPUT);
  pinMode(LimitSwitch2, INPUT);
  pinMode(LimitSwitch3, INPUT);
  pinMode(LimitSwitch4, INPUT);

  digitalWrite(LimitSwitch1, LOW);
  digitalWrite(LimitSwitch2, LOW);
  digitalWrite(LimitSwitch3, LOW);
  digitalWrite(LimitSwitch4, LOW);

  Serial.begin(9600);
}

void loop(){
  if(Serial.available() > 0){
    state = Serial.read();
    }
    if(state == 'A') {
      OpenGate();
      if(digitalRead(LimitSwitch2) == HIGH){
      StopMotorA();
      }
    }
    else if(state == 'B') {
      CloseGate();
      if(digitalRead(LimitSwitch1) == HIGH){
      StopMotorA();
      }
    }
    else if(state == 'C') {
      OpenGarageDoor();
      if(digitalRead(LimitSwitch4) == HIGH){
      StopMotorB();
      }
    }
    else if(state == 'D') {
      CloseGarageDoor();
      if(digitalRead(LimitSwitch3) == HIGH){
      StopMotorB();
      }
    }
}

//******************   Motor A control   *******************
void OpenGate(){
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, HIGH);
  analogWrite(EnableMotorA, 250);
  }
void CloseGate(){
  digitalWrite(IN1, HIGH);
  digitalWrite(IN2, LOW);
  analogWrite(EnableMotorA, 250);
}
void StopMotorA(){
  digitalWrite(IN1, LOW);
  digitalWrite(IN2, LOW);
  analogWrite(EnableMotorA, 0);
 }
//******************   Motor B control   *******************
void OpenGarageDoor(){
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, HIGH);
  analogWrite(EnableMotorB, 250);
}
void CloseGarageDoor(){
  digitalWrite(IN3, HIGH);
  digitalWrite(IN4, LOW);
  analogWrite(EnableMotorB, 250);
}
void StopMotorB(){
  digitalWrite(IN3, LOW);
  digitalWrite(IN4, LOW);
  analogWrite(EnableMotorB, 0);
}
//**********************************************************

do not start the motor after the switch is closed. start it with BT only. .... draw up a flowchart on paper, then create the code that emulates the flowchart.

I am sorry but what is BT? I have made the flowchart, it goes like motor DC turn in clockwise -> is limit switch pressed? -> if yes, stop the DC motor. and I thought i have made it that way

BT ... bluetooth   ..... you are getting your states from a serial connection. that is ok, but you need internal states also. example: state E --- status: everything stopped .... enter from state B when limit switch is activated (and from others)

you need at least 4 separate stop states ... door open, door closed, door stop at opening, door stop at closing.   .... do a web search about state machine or arduino state machine

the state is referring the character that is received from the BT.
do the if statement for limit switch also included into the stop state?
okay i will have a research about that, thank you

DISCLAIMER: I haven't tested the code in this answer, but I hope there are no problems.
Your code has a major problem: what happens when one gate is moving and you trigger another movement? (reply: something bad). This design issue can be solved by using a standard way of designing these kind of state machine.
In your case a small state machine is what best fits your problem. Better give your states a meaningful name, no?
Ok, so just to start, let's define the states and how to transition through them.
You have basically an idle state, open gate, close gate, open garage door, close garage door. What should you do in these states, both when entering the state and during the time you are in the state? Here is a table to summarize
State       | Enter         | During time
----------------------------------------------
Idle        | Stop motors   | -
OpenGate    | Start A dir 1 | -
CloseGate   | Start A dir 2 | -
OpenGarage  | Start B dir 1 | -
CloseGarage | Start B dir 2 | -

The transitions are pretty straightforward. Exit from idle when you receive a (valid) command, exit from the others when you reach the endstop.
The implementation is pretty standard:
// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte State_Idle = 0;
const byte State_OpenGate = 1;
const byte State_CloseGate = 2;
const byte State_OpenGarage = 3;
const byte State_CloseGarage = 4;
byte currentState;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentState = 0xFF; // Force a change to enter the idle state
}

void loop(){
    // Check if we need to change state
    byte nextState = currentState;
    switch (currentState)
    {
    case State_Idle:
        { // If we received a valid command, start the operation
            if(Serial.available() > 0)
            {
                switch (Serial.read())
                {
                case 'A':
                    nextState = State_OpenGate;
                    break;
                case 'B':
                    nextState = State_CloseGate;
                    break;
                case 'C':
                    nextState = State_OpenGarage;
                    break;
                case 'D':
                    nextState = State_CloseGarage;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case State_OpenGate:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGate:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_OpenGarage:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    case State_CloseGarage:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = State_Idle;
        break;
    default:
        nextState = State_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentState)
    {
        currentState = nextState; // Move in the new state
        switch (currentState)
        { // Entering the new state
        case State_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case State_OpenGate:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case State_CloseGate:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        case State_OpenGarage:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case State_CloseGarage:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

(Note: I changed some types because your poor 8-bit uC asked me to avoid complicating its calculations unnecessarily)
One modification to your algorithm is to detach the two loops, since they seem, well, detached.
// Motor for Gate (MotorA)
const byte IN1 = 2;
const byte IN2 = 3;
const byte EnableMotorA = 9;

// Motor for Garage Door (MotorB)
const byte IN3 = 4;
const byte IN4 = 5;
const byte EnableMotorB = 10;

const byte LimitSwitch1 = A1;
const byte LimitSwitch2 = A2;
const byte LimitSwitch3 = A3;
const byte LimitSwitch4 = A4;

const byte StateA_Idle = 0;
const byte StateA_Open = 1;
const byte StateA_Close = 2;
byte currentStateA;

const byte StateB_Idle = 0;
const byte StateB_Open = 1;
const byte StateB_Close = 2;
byte currentStateB;

void setup(){
    pinMode(IN1,OUTPUT);
    pinMode(IN2,OUTPUT);
    pinMode(EnableMotorA,OUTPUT);

    pinMode(IN3,OUTPUT);
    pinMode(IN4,OUTPUT);
    pinMode(EnableMotorB,OUTPUT);

    pinMode(LimitSwitch1, INPUT);
    pinMode(LimitSwitch2, INPUT);
    pinMode(LimitSwitch3, INPUT);
    pinMode(LimitSwitch4, INPUT);

    Serial.begin(9600);
    currentStateA = 0xFF; // Force a change to enter the idle state
    currentStateB = 0xFF; // Force a change to enter the idle state
}

void loop()
{
    byte readChar = 0;
    if(Serial.available() > 0)
        readChar = Serial.read();

    stateMachineA(readChar);
    stateMachineB(readChar);
}

void stateMachineA(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateA;
    switch (currentStateA)
    {
    case StateA_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'A':
                    nextState = StateA_Open;
                    break;
                case 'B':
                    nextState = StateA_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateA_Open:
        if(digitalRead(LimitSwitch2)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    case StateA_Close:
        if(digitalRead(LimitSwitch1)) // == HIGH is not necessary
            nextState = StateA_Idle;
        break;
    default:
        nextState = StateA_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateA)
    {
        currentStateA = nextState; // Move in the new state
        switch (currentStateA)
        { // Entering the new state
        case StateA_Idle:
            // Stop motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 0);
            break;
        case StateA_Open:
            // Start motor A
            digitalWrite(IN1, LOW);
            digitalWrite(IN2, HIGH);
            analogWrite(EnableMotorA, 250);
            break;
        case StateA_Close:
            // Start motor A
            digitalWrite(IN1, HIGH);
            digitalWrite(IN2, LOW);
            analogWrite(EnableMotorA, 250);
            break;
        }
    }
}

void stateMachineB(byte readChar)
{
    // Check if we need to change state
    byte nextState = currentStateB;
    switch (currentStateB)
    {
    case StateB_Idle:
        { // If we received a valid command, start the operation
            if(readChar > 0)
            {
                switch (readChar)
                {
                case 'C':
                    nextState = StateB_Open;
                    break;
                case 'D':
                    nextState = StateB_Close;
                    break;
                default:
                    // Here you can notify that there was a bad command
                    break;
                }
            }
        }
        break;
    case StateB_Open:
        if(digitalRead(LimitSwitch4)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    case StateB_Close:
        if(digitalRead(LimitSwitch3)) // == HIGH is not necessary
            nextState = StateB_Idle;
        break;
    default:
        nextState = StateB_Idle;
        break;
    }

    // If there was a change, switch state and trigger enter condition
    if (nextState != currentStateB)
    {
        currentStateB = nextState; // Move in the new state
        switch (currentStateB)
        { // Entering the new state
        case StateB_Idle:
            // Stop motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 0);
            break;
        case StateB_Open:
            // Start motor B
            digitalWrite(IN3, LOW);
            digitalWrite(IN4, HIGH);
            analogWrite(EnableMotorB, 250);
            break;
        case StateB_Close:
            // Start motor B
            digitalWrite(IN3, HIGH);
            digitalWrite(IN4, LOW);
            analogWrite(EnableMotorB, 250);
            break;
        }
    }
}

This second implementation has two parallel state machines (sharing only the serial input). This will allow you to control both gates at the same time (for instance when the gate is closin you can open the garage)

Oh my god! it works perfectly for my circuit. i planned to make it like your second implementation. Thank you so much! :D

@HusnaAmiliansyah did you already test it? Does it work? Really? :-P

of course it works xD, i had tested it on breadboard

btw,
const byte StateA_Idle = 0;
const byte StateA_Open = 1;
const byte StateA_Close = 2;
what is this part mean?

@HusnaAmiliansyah there are tons of jokes on software which runs the first time (for instance this) ;) anyway those lines are to give a meaningful name to states. It's easier to write (and understand) nextstate = StateA_Open; than nextstate = 1;. In order to do this you have usually three ways: use a #define, use an enum or use some constants. I tend to prefer the third because it's, for me, the easiest way to force the 8-bit size to the state variable and values

Alright, got it!! thank you so much for your help!! :) btw, i am sorry i can not vote this answer because i dont have enough poin:(

@HusnaAmiliansyah don't worry, the most important thing is that you understood it ;) and that you marked the answer as accepted, so other people looking at your question can understand that the answer "answers" it.

Okay, i have accepted it long time ago :D. Btw i have another questions in mind... If i want to add buzzer inside the states, do i need to change the 'byte'? And is there any limitation for the number of states in one function (for exampe in statemachineA function)?

The byte type can hold values from 0 to 255, consequently if you have to code 257 states you need at least a 2-bytes int, while for 65537 states you need at least 3 bytes. But IMHO whenever you are exceeding 20-30 states you are going too far. So, theoretically there is no limit (you just have to make the variable holding the state bigger), but any state machine with more than some tens of states is too big to be managed effectively, and maybe re-thinking the machine (as a series of nested machines, for instance) can become a better solution


text:
Store RAM and PROGMEM strings in one variable
I want to store a number of strings in an object. Currently I have:
class MyClass {
  int numStrings = 0;
  ??? strings[20];

  public:
    void addString(const char str[]);
    void print();
};

void MyClass::addString(const char str[]) {
  strings[numStrings] = str;
  numStrings++;
}

void MyClass::print() {
  for (int i = 0 ; i < numStrings ; i++) {
    Serial.println(strings[i]);
  }
}

Serial.println() works with strings in RAM and in PROGMEM alike.
Is there a type that I can give to my strings variable that allows me to store both types of strings?
MyClass s;

s.addString("This should work");
s.addString(F("This should work, too"));

Is there a type that I can give to my strings variable that allows me to store both types of strings?

No, but you could tag the pointer or add a vector with type information or ultimately use a class hierarchy (BaseString<-SRAMString, PROMEMString).
As a pointer is 16-bit (Arduino Uno) and there is limited amount of SRAM it is possible to add a magic number to pointers to determine the address space.
Obviously the print() member function will have to use the right type and you will also need a new addString for F() strings. Check how F() is defined.
Cheers!

I don't know how to "tag a pointer", but when working with a magic number I would make that a void pointer?

Here is an example of mapping EEPROM, SRAM and PROGMEM to a single address space: https://github.com/mikaelpatel/Arduino-Shell/blob/master/Shell.h#L1058

The simplest scheme is to use the sign bit for PROGMEM, i.e. add 0x8000 to PROGMEM pointers.

I don't get it. So when I get a __FlashStringHelper* I add 0x8000 to mark that it points to PROGMEM. But then I still can't store that in a const char* variable, can I?

Tell the compiler what you want: uint16_t str = 0x8000U + (uint16_t) str_P; strings[numStrings++] = (const char*) str;

That is the answer I was looking for. :) Is there a type...? -> Yes, uint16_t.

Actually the standard type (stdint.h) is uintptr_t. Here are the details: http://en.cppreference.com/w/c/types/integer. Please remember that the standard was not intended for a Harvard architecture as the AVR.


text:
Less hardware dependent development?
I'm working on a little Arduino game project that uses neopixel strips as a display. Uploading every code change to the Arduino and testing it on the LEDs is slow and drains hardware lifetime.
Usually I test as much I can using the Serial Monitor, but I can't get it to clear from code which I learned is only possible e.g. when using a terminal. I did that, but it comes with other issues.
Is there a better way to test code on the dev machine instead of the Arduino?
Is there a best practice to have a Serial Monitor (or anything else) act like a display that I can actually refresh/clear? Serial.println() empty lines to scroll the content is not very practical.

I personally always use either a terminal emulator (screen) or cat on a terminal if it's only for logging. I find a terminal quite handy for that sort of work.

UECIDE's terminal is far superior.

I was using "Serial Tools" for Mac and the screen command inside the terminal. Both work and both have the annoying issue that somehow I can't upload changes as the IDE says that the serial port is currently in use. So far I only managed to solve that by disconnecting and reconnecting again. Any advice for that?

Just quit screen before uploading.

just get a $2 AVR that you don't care about "burning out". I often code new chunks in short JS first w/something like jsfiddle/codepen, using as close to C as possible (eg x.substring(0,x.indexOf(y)) instead of x.split(y)[0]. Once it works, i drop it into the sketch and add the types. Once it compiles, you've got a pretty good shot at it working as expected with minimal debugging. of course, you can run C w/o uploading too, but i've not found a decent "emulator", if that's the question.

You can unit test your code by creating stubs of the functions you are calling, like replacing a couple of includes with their dumb counterparts.
My friend Jan Beayens did something very valuable on that front and he is also the main author of a good replacement for the Arduino IDE when you start needing some more advanced capabilities: Sloeber is the product name and it also contains an improved version of the serial monitor with clear and scroll lock capabilities.
Go check it out.
Disclaimer : I'm a contributor of the project

Warning: It's a plugin for Eclipse.

Why are you issuing a warning? Do you believe there's anything wrong with Eclipse? It is OSS and works perfectly on Linux, which are two factors you should appreciate...
BTW, Sloeber also exists as a product, but that it is still dependent on Eclipse CDT.

Eclipse is an horrible IDE. I will not touch Eclipse with a 10 meters pole.

I respect your opinion, but I completely disagree: Eclipse is my IDE of choice.

As you've probably noticed, trying to run tests over the serial port is frustrating.  Worse, the relatively large delays associated with writing serial data can affect the accuracy of your measurements.
To cope with this, I wrote my own unit testing framework for Arduino, which lets you fully mock (simulate) the hardware so that you can verify the operation of the software.
There are some examples of how my library accomplishes that, in the project README.  Here is one for pins:
unittest(pin_history)
{
  GodmodeState* state = GODMODE();
  int myPin = 3;
  state->reset();            // pin will start LOW
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, LOW);
  digitalWrite(myPin, HIGH);
  digitalWrite(myPin, HIGH);

  assertEqual(6, state->digitalPin[1].size());
  bool expected[6] = {LOW, HIGH, LOW, LOW, HIGH, HIGH};
  bool actual[6];

  // convert pin history to an array, and verify expected results
  int numMoved = state->digitalPin[myPin].toArray(actual, 6);
  assertEqual(6, numMoved);

  // verify each element
  for (int i = 0; i < 6; ++i) {
    assertEqual(expected[i], actual[i]);
  }
}

You may also like the example for mocking Serial port data, although I probably need to improve that documentation.
The beauty of all this is that I was able to develop this framework and all these tests without ever plugging an Arduino board into my computer.


text:
How to save a float variable to the EEPROM?
This is my first post here and I'm hoping there are some Arduino hobbyists here to help me.
Does anyone here know how to save a float variable directly to the EEPROM? If so, could you have a look at the program I wrote and hopefully explain how it would be set up to work with the other 2 variables I'm saving to the EEPROM?
The program I wrote displays a voltmeter to the LCD. The program has an adjustable alarm set point as to when to sound an alarm when the voltage drops below a user-set alarm set point. I want to be able to declare the alarm set point as a float variable and save it directly to the EEPROM. I can't seem to find any programs that I could use as an example to try and figure out how to do that.
I did manage to get my program working to save my Volt_Alarm_Set_Point by declaring it as an int var and then comparing it to my Volt_Set_Point (declared as a float var) to 165 if statements to save the right Volt_Alarm_Set_Point value. And it works a treat but uses up 4956 bytes of program space. That's ok if I'm using an Arduino Mega but I'd like to be able to have my program run on an Arduino Nano which could cause problems with some bigger programs.
If anyone here could show me how to do this it would be greatly appreciated and I would be in your dept. Here is my code below. I don't understand how the code is suppose to be put here? Other forums are dead easy to post code but I can't figure this one out. Sorry about that...
Thanks
jessey
 #include <EEPROM.h>
 #include <LiquidCrystal_I2C.h>
 LiquidCrystal_I2C lcd(0x27, 20, 4);

//----------Volt Meter Code----------//
    int analogInput = A6;
    float vout = 0.0;
    float vin = 0.0;
    float R1 = 99300.0;
    float R2 = 9970.0;
    int value = 0;
//----------Volt Meter Code----------//

  int Volt_Alarm_Set_Point; // this works
  float Volt_Set_Point;
//  float Volt_Alarm_Set_Point; // this dosen't work
  int s = 0;
  int a = 0;
  int b = 0;

 int Button_1 = 5;
 int Button_2 = 6;
 int Button_3 = A1;
 int Button_4 = A0;
 int Alarm_Relay_1 = A3;
 int Relay_2 = A2;
 int Relay_3 = 8;
 int Blinking_Led = 3;// this one is ready to be used anytime

 #define VOLT_ALARM_SET_POINT_ADDR 0
 #define A_ADDR VOLT_ALARM_SET_POINT_ADDR + sizeof(int)
 #define B_ADDR A_ADDR + sizeof(int)

 #define Is_Pressed  0  // used for pushbuttons
 #define Is_Turned_On 1  // used for the relays
 #define Is_Turned_Off 0 // used for the relays

 //|---------void setup---------void setup---------|//
void setup() {

    pinMode(Alarm_Relay_1, OUTPUT);
    pinMode(Relay_2, OUTPUT);
    pinMode(Relay_3, OUTPUT);
    pinMode(Blinking_Led, OUTPUT);
    pinMode(Button_1, INPUT); // on pin 5
    pinMode(Button_2, INPUT); // on pin 6
    pinMode(Button_3, INPUT); // on pin A1
    pinMode(Button_4, INPUT); // on pin A0
//-----------Volt Meter Code--------------//
    pinMode(analogInput, INPUT);
//-----------Volt Meter Code--------------//

    lcd.begin();

    lcd.setCursor(0, 0);
    lcd.print(F("  This Program Is   "));
    lcd.setCursor(0, 1);
    lcd.print(F("to try and save a   "));
    lcd.setCursor(0, 2);
    lcd.print(F("float variable      "));
    lcd.setCursor(0, 3);
    lcd.print(F("to the eeprom       "));
    delay(500);

    lcd.clear();

    EEPROM.get(VOLT_ALARM_SET_POINT_ADDR, Volt_Alarm_Set_Point);
    EEPROM.get(A_ADDR, a);
    EEPROM.get(B_ADDR, b);
//  EEPROM.put( VOLT_ALARM_SET_POINT_ADDR, Volt_Alarm_Set_Point);
//  EEPROM.put(A, a);
//  EEPROM.put(B, b);

}// end of the void setup()

//|---------void setup---------void setup---------|//
//|---------void loop---------void loop---------|//

void loop() {

    delay(50);
  //increment & decrement Volt_Alarm_Set_Point
    if (digitalRead(Button_1)==Is_Pressed
      ||digitalRead(Button_2)==Is_Pressed)
      {Adjust_The_Volt_Alarm_Set_Point();}

    Read_Volt_Meter();
    //Multiply_By_0_Point_1;
    Display_A_Float_Voltage_Reference();

    lcd.setCursor(0, 0);
    lcd.print(F("This is the Volt adj"));
    lcd.setCursor(0, 1);
    lcd.print(F("Volt Set Pnt = "));

    if (Volt_Alarm_Set_Point<=9){
    lcd.setCursor(16, 1);
    lcd.print(" ");}
    lcd.setCursor(15, 1);
    lcd.print(Volt_Set_Point);

    lcd.setCursor(0,2);
    lcd.print(F("VoltageX= "));
    lcd.setCursor(10, 2);
    lcd.print(vin);

    if (Volt_Alarm_Set_Point<=9){
    lcd.setCursor(17, 2);
    lcd.print(" ");}
    lcd.setCursor(16, 2);
    lcd.print(Volt_Alarm_Set_Point);

    if (vin < Volt_Set_Point){digitalWrite(Relay_3, Is_Turned_On);}
    if (vin > Volt_Set_Point){digitalWrite(Relay_3, Is_Turned_Off);}

    lcd.setCursor(0, 3);lcd.print("A = ");lcd.setCursor(4, 3);lcd.print(a);
    lcd.setCursor(6, 3);lcd.print("B = ");lcd.setCursor(11, 3);lcd.print(b);

    if (a==0) {digitalWrite(Relay_2, Is_Turned_Off);}
    if (a==1) {digitalWrite(Relay_2, Is_Turned_On);}

    if (b==0) {digitalWrite(Alarm_Relay_1, Is_Turned_Off);}
    if (b==1) {digitalWrite(Alarm_Relay_1, Is_Turned_On);}

    if (digitalRead(Button_4)==Is_Pressed){
      if (a==0){a=1;}else{a=0;}
      while (digitalRead(Button_4)==Is_Pressed){
      if (a==0) {digitalWrite(Relay_2, Is_Turned_Off);}
      if (a==1) {digitalWrite(Relay_2, Is_Turned_On);}
      lcd.setCursor(0, 3);lcd.print("A = ");lcd.setCursor(4,3);lcd.print(a);
      lcd.setCursor(6, 3);lcd.print("B = ");lcd.setCursor(11,3);lcd.print(b);
      }
      EEPROM.put(A_ADDR, a); EEPROM.put(B_ADDR, b);
    }

    if (digitalRead(Button_3)==Is_Pressed){
     if (b==0){b=1;}else{b=0;}
     while (digitalRead(Button_3)==Is_Pressed){
     if (b==0) {digitalWrite(Alarm_Relay_1, Is_Turned_Off);}
     if (b==1) {digitalWrite(Alarm_Relay_1, Is_Turned_On);}
     lcd.setCursor(0, 3);lcd.print("A = ");lcd.setCursor(4,3);lcd.print(a);
     lcd.setCursor(6, 3);lcd.print("B = ");lcd.setCursor(11,3);lcd.print(b);
     }
     EEPROM.put(A_ADDR, a); EEPROM.put(B_ADDR, b);
    }
  }// end of the void loop()

//|---------void loop---------void loop---------|//
//======= Subroutine Area ======= Subroutine Area =======//
///*
void Display_A_Float_Voltage_Reference()
{
if (Volt_Alarm_Set_Point==0){Volt_Set_Point=0.00;}// this code uses 165 if statements for 4956 bytes of program space and 4 bytes of dynamic memory.
if (Volt_Alarm_Set_Point==1){Volt_Set_Point=0.10;}
if (Volt_Alarm_Set_Point==2){Volt_Set_Point=0.20;}
if (Volt_Alarm_Set_Point==3){Volt_Set_Point=0.30;}
if (Volt_Alarm_Set_Point==4){Volt_Set_Point=0.40;}
if (Volt_Alarm_Set_Point==5){Volt_Set_Point=0.50;}
if (Volt_Alarm_Set_Point==6){Volt_Set_Point=0.60;}
if (Volt_Alarm_Set_Point==7){Volt_Set_Point=0.70;}
if (Volt_Alarm_Set_Point==8){Volt_Set_Point=0.80;}
if (Volt_Alarm_Set_Point==9){Volt_Set_Point=0.90;}
if (Volt_Alarm_Set_Point==10){Volt_Set_Point=1.00;}

if (Volt_Alarm_Set_Point==11){Volt_Set_Point=1.10;}
if (Volt_Alarm_Set_Point==12){Volt_Set_Point=1.20;}
if (Volt_Alarm_Set_Point==13){Volt_Set_Point=1.30;}
if (Volt_Alarm_Set_Point==14){Volt_Set_Point=1.40;}
if (Volt_Alarm_Set_Point==15){Volt_Set_Point=1.50;}
if (Volt_Alarm_Set_Point==16){Volt_Set_Point=1.60;}
if (Volt_Alarm_Set_Point==17){Volt_Set_Point=1.70;}
if (Volt_Alarm_Set_Point==18){Volt_Set_Point=1.80;}
if (Volt_Alarm_Set_Point==19){Volt_Set_Point=1.90;}
if (Volt_Alarm_Set_Point==20){Volt_Set_Point=2.00;}

if (Volt_Alarm_Set_Point==21){Volt_Set_Point=2.10;}
if (Volt_Alarm_Set_Point==22){Volt_Set_Point=2.20;}
if (Volt_Alarm_Set_Point==23){Volt_Set_Point=2.30;}
if (Volt_Alarm_Set_Point==24){Volt_Set_Point=2.40;}
if (Volt_Alarm_Set_Point==25){Volt_Set_Point=2.50;}
if (Volt_Alarm_Set_Point==26){Volt_Set_Point=2.60;}
if (Volt_Alarm_Set_Point==27){Volt_Set_Point=2.70;}
if (Volt_Alarm_Set_Point==28){Volt_Set_Point=2.80;}
if (Volt_Alarm_Set_Point==29){Volt_Set_Point=2.90;}
if (Volt_Alarm_Set_Point==30){Volt_Set_Point=3.00;}

if (Volt_Alarm_Set_Point==31){Volt_Set_Point=3.1;}
if (Volt_Alarm_Set_Point==32){Volt_Set_Point=3.2;}
if (Volt_Alarm_Set_Point==33){Volt_Set_Point=3.3;}
if (Volt_Alarm_Set_Point==34){Volt_Set_Point=3.4;}
if (Volt_Alarm_Set_Point==35){Volt_Set_Point=3.5;}
if (Volt_Alarm_Set_Point==36){Volt_Set_Point=3.6;}
if (Volt_Alarm_Set_Point==37){Volt_Set_Point=3.7;}
if (Volt_Alarm_Set_Point==38){Volt_Set_Point=3.8;}
if (Volt_Alarm_Set_Point==39){Volt_Set_Point=3.9;}
if (Volt_Alarm_Set_Point==40){Volt_Set_Point=4.0;}

if (Volt_Alarm_Set_Point==41){Volt_Set_Point=4.1;}
if (Volt_Alarm_Set_Point==42){Volt_Set_Point=4.2;}
if (Volt_Alarm_Set_Point==43){Volt_Set_Point=4.3;}
if (Volt_Alarm_Set_Point==44){Volt_Set_Point=4.4;}
if (Volt_Alarm_Set_Point==45){Volt_Set_Point=4.5;}
if (Volt_Alarm_Set_Point==46){Volt_Set_Point=4.6;}
if (Volt_Alarm_Set_Point==47){Volt_Set_Point=4.7;}
if (Volt_Alarm_Set_Point==48){Volt_Set_Point=4.8;}
if (Volt_Alarm_Set_Point==49){Volt_Set_Point=4.9;}
if (Volt_Alarm_Set_Point==50){Volt_Set_Point=5.0;}

if (Volt_Alarm_Set_Point==51){Volt_Set_Point=5.1;}
if (Volt_Alarm_Set_Point==52){Volt_Set_Point=5.2;}
if (Volt_Alarm_Set_Point==53){Volt_Set_Point=5.3;}
if (Volt_Alarm_Set_Point==54){Volt_Set_Point=5.4;}
if (Volt_Alarm_Set_Point==55){Volt_Set_Point=5.5;}
if (Volt_Alarm_Set_Point==56){Volt_Set_Point=5.6;}
if (Volt_Alarm_Set_Point==57){Volt_Set_Point=5.7;}
if (Volt_Alarm_Set_Point==58){Volt_Set_Point=5.8;}
if (Volt_Alarm_Set_Point==59){Volt_Set_Point=5.9;}
if (Volt_Alarm_Set_Point==60){Volt_Set_Point=6.0;}

if (Volt_Alarm_Set_Point==61){Volt_Set_Point=6.1;}
if (Volt_Alarm_Set_Point==62){Volt_Set_Point=6.2;}
if (Volt_Alarm_Set_Point==63){Volt_Set_Point=6.3;}
if (Volt_Alarm_Set_Point==64){Volt_Set_Point=6.4;}
if (Volt_Alarm_Set_Point==65){Volt_Set_Point=6.5;}
if (Volt_Alarm_Set_Point==66){Volt_Set_Point=6.6;}
if (Volt_Alarm_Set_Point==67){Volt_Set_Point=6.7;}
if (Volt_Alarm_Set_Point==68){Volt_Set_Point=6.8;}
if (Volt_Alarm_Set_Point==69){Volt_Set_Point=6.9;}
if (Volt_Alarm_Set_Point==70){Volt_Set_Point=7.0;}

if (Volt_Alarm_Set_Point==71){Volt_Set_Point=7.1;}
if (Volt_Alarm_Set_Point==72){Volt_Set_Point=7.2;}
if (Volt_Alarm_Set_Point==73){Volt_Set_Point=7.3;}
if (Volt_Alarm_Set_Point==74){Volt_Set_Point=7.4;}
if (Volt_Alarm_Set_Point==75){Volt_Set_Point=7.5;}
if (Volt_Alarm_Set_Point==76){Volt_Set_Point=7.6;}
if (Volt_Alarm_Set_Point==77){Volt_Set_Point=7.7;}
if (Volt_Alarm_Set_Point==78){Volt_Set_Point=7.8;}
if (Volt_Alarm_Set_Point==79){Volt_Set_Point=7.9;}
if (Volt_Alarm_Set_Point==80){Volt_Set_Point=8.0;}

if (Volt_Alarm_Set_Point==81){Volt_Set_Point=8.1;}
if (Volt_Alarm_Set_Point==82){Volt_Set_Point=8.2;}
if (Volt_Alarm_Set_Point==83){Volt_Set_Point=8.3;}
if (Volt_Alarm_Set_Point==84){Volt_Set_Point=8.4;}
if (Volt_Alarm_Set_Point==85){Volt_Set_Point=8.5;}
if (Volt_Alarm_Set_Point==86){Volt_Set_Point=8.6;}
if (Volt_Alarm_Set_Point==87){Volt_Set_Point=8.7;}
if (Volt_Alarm_Set_Point==88){Volt_Set_Point=8.8;}
if (Volt_Alarm_Set_Point==89){Volt_Set_Point=8.9;}
if (Volt_Alarm_Set_Point==90){Volt_Set_Point=9.0;}

if (Volt_Alarm_Set_Point==91){Volt_Set_Point=9.1;}
if (Volt_Alarm_Set_Point==92){Volt_Set_Point=9.2;}
if (Volt_Alarm_Set_Point==93){Volt_Set_Point=9.3;}
if (Volt_Alarm_Set_Point==94){Volt_Set_Point=9.4;}
if (Volt_Alarm_Set_Point==95){Volt_Set_Point=9.5;}
if (Volt_Alarm_Set_Point==96){Volt_Set_Point=9.6;}
if (Volt_Alarm_Set_Point==97){Volt_Set_Point=9.7;}
if (Volt_Alarm_Set_Point==98){Volt_Set_Point=9.8;}
if (Volt_Alarm_Set_Point==99){Volt_Set_Point=9.9;}
if (Volt_Alarm_Set_Point==100){Volt_Set_Point=10.0;}

if (Volt_Alarm_Set_Point==101){Volt_Set_Point=10.1;}
if (Volt_Alarm_Set_Point==102){Volt_Set_Point=10.2;}
if (Volt_Alarm_Set_Point==103){Volt_Set_Point=10.3;}
if (Volt_Alarm_Set_Point==104){Volt_Set_Point=10.4;}
if (Volt_Alarm_Set_Point==105){Volt_Set_Point=10.5;}
if (Volt_Alarm_Set_Point==106){Volt_Set_Point=10.6;}
if (Volt_Alarm_Set_Point==107){Volt_Set_Point=10.7;}
if (Volt_Alarm_Set_Point==108){Volt_Set_Point=10.8;}
if (Volt_Alarm_Set_Point==109){Volt_Set_Point=10.9;}
if (Volt_Alarm_Set_Point==110){Volt_Set_Point=11.0;}

if (Volt_Alarm_Set_Point==111){Volt_Set_Point=11.1;}
if (Volt_Alarm_Set_Point==112){Volt_Set_Point=11.2;}
if (Volt_Alarm_Set_Point==113){Volt_Set_Point=11.3;}
if (Volt_Alarm_Set_Point==114){Volt_Set_Point=11.4;}
if (Volt_Alarm_Set_Point==115){Volt_Set_Point=11.5;}
if (Volt_Alarm_Set_Point==116){Volt_Set_Point=11.6;}
if (Volt_Alarm_Set_Point==117){Volt_Set_Point=11.7;}
if (Volt_Alarm_Set_Point==118){Volt_Set_Point=11.8;}
if (Volt_Alarm_Set_Point==119){Volt_Set_Point=11.9;}
if (Volt_Alarm_Set_Point==120){Volt_Set_Point=12.0;}

if (Volt_Alarm_Set_Point==121){Volt_Set_Point=12.1;}
if (Volt_Alarm_Set_Point==122){Volt_Set_Point=12.2;}
if (Volt_Alarm_Set_Point==123){Volt_Set_Point=12.3;}
if (Volt_Alarm_Set_Point==124){Volt_Set_Point=12.4;}
if (Volt_Alarm_Set_Point==125){Volt_Set_Point=12.5;}
if (Volt_Alarm_Set_Point==126){Volt_Set_Point=12.6;}
if (Volt_Alarm_Set_Point==127){Volt_Set_Point=12.7;}
if (Volt_Alarm_Set_Point==128){Volt_Set_Point=12.8;}
if (Volt_Alarm_Set_Point==129){Volt_Set_Point=12.9;}
if (Volt_Alarm_Set_Point==130){Volt_Set_Point=13.0;}

if (Volt_Alarm_Set_Point==131){Volt_Set_Point=13.1;}
if (Volt_Alarm_Set_Point==132){Volt_Set_Point=13.2;}
if (Volt_Alarm_Set_Point==133){Volt_Set_Point=13.3;}
if (Volt_Alarm_Set_Point==134){Volt_Set_Point=13.4;}
if (Volt_Alarm_Set_Point==135){Volt_Set_Point=13.5;}
if (Volt_Alarm_Set_Point==136){Volt_Set_Point=13.6;}
if (Volt_Alarm_Set_Point==137){Volt_Set_Point=13.7;}
if (Volt_Alarm_Set_Point==138){Volt_Set_Point=13.8;}
if (Volt_Alarm_Set_Point==139){Volt_Set_Point=13.9;}
if (Volt_Alarm_Set_Point==140){Volt_Set_Point=14.0;}

if (Volt_Alarm_Set_Point==141){Volt_Set_Point=14.1;}
if (Volt_Alarm_Set_Point==142){Volt_Set_Point=14.2;}
if (Volt_Alarm_Set_Point==143){Volt_Set_Point=14.3;}
if (Volt_Alarm_Set_Point==144){Volt_Set_Point=14.4;}
if (Volt_Alarm_Set_Point==145){Volt_Set_Point=14.5;}
if (Volt_Alarm_Set_Point==146){Volt_Set_Point=14.6;}
if (Volt_Alarm_Set_Point==147){Volt_Set_Point=14.7;}
if (Volt_Alarm_Set_Point==148){Volt_Set_Point=14.8;}
if (Volt_Alarm_Set_Point==149){Volt_Set_Point=14.9;}
if (Volt_Alarm_Set_Point==150){Volt_Set_Point=15.0;}

} // end of void Display_A_Float_Voltage_Reference()
//*/

  void Adjust_The_Volt_Alarm_Set_Point()
 { s=0;
  // push button to increase this Alarm Set Point
  if (digitalRead(Button_2) == Is_Pressed)
     { s=1;
      if (Volt_Alarm_Set_Point <= 150)
      {
       Volt_Alarm_Set_Point = Volt_Alarm_Set_Point  + 1;// this line is using a int variable
       if (Volt_Alarm_Set_Point > 150)
          {Volt_Alarm_Set_Point = 150;}
      }
     }
 // push button to decrease this Alarm Set Point
  if (digitalRead(Button_1) == Is_Pressed)
    { s=1;
     Volt_Alarm_Set_Point = Volt_Alarm_Set_Point  - 1;// this line is using a int variable
     if (Volt_Alarm_Set_Point <= 0)
     {Volt_Alarm_Set_Point = 0;}
    }
    if (s==1){EEPROM.put( VOLT_ALARM_SET_POINT_ADDR,Volt_Alarm_Set_Point);}
 }

void Read_Volt_Meter()
{
   //-------------------------------Volt Meter Code-------------------------------//
   //-----------------------------------// This code reads the value at analog
   value = analogRead(analogInput);//---// input A6 and this is where we can change
   vout = (value * 4.72) / 1024.0;//----// the volts value to what the actual supply
   vin = vout / (R2/(R1+R2));//---------// voltage is equal to by checking it with an
   if (vin<0.09) {//--------------------// accurate Digital Votl Meter then entering
   vin=0.0;//---------------------------// it here-->(value * 4.79) changing the 4.79
   }//----------------------------------// to whatever your meter reads...
   //-------------------------------Volt Meter Code-------------------------------//
}
//======= Subroutine Area ======= Subroutine Area =======//
// end the Subroutine Area
// end of the program...

Looks like Volt_Set_Point = Volt_Alarm_Set_Point/10.0; :)

Why don't you just EEPROM.put() and EEPROM.get() your float?

@EdgarBonet - That's a new one to me. Thanks!

Since your floating point value always uses only 1 digit after the comma, why not multiply it by 10 and put it in an integer? For a value up to 15.0 (resulting in 150 int), you can use a simple byte and store it in EEPROM directly.
Then you can get rid of all if statements. To make a better formula, you can even add rounding (so adding + 0.5 before converting to an int).
Thus:
EEPROM.put(VOLT_ALARM_SET_POINT_ADDR, (byte) (value * 10.0 + 0.5);

And to retrieve the value:
EEPROM.get(VOLT_ALARM_SET_POINT_ADDR, f);
f = (float) (f / 10.0);

@Michel Keijzers
I tried to use the code suggestion you sent but I couldn't get it set up properly to work with-in my code. I do thank you for your answer though. I did manage to figure out a way to save the value of my float variable to an integer and it works good. I'm including the working program below so if anyone ever googles the question I was asking they will find this and hopefully it'll be helpful to them because this works...
    {
        // this program uses 6986 bytes of program space
    // the old program with all the if statements used 11872 bytes
    // This program uses 4,886 less bytes of program space to accomplish the same thing

     #include <EEPROM.h>
     #include <LiquidCrystal_I2C.h>
     LiquidCrystal_I2C lcd(0x27, 20, 4);

    //----------Volt Meter Code----------//
        int analogInput = A6;
        float vout = 0.0;
        float vin = 0.0;
        float R1 = 99300.0;
        float R2 = 9970.0;
        int value = 0;
    //----------Volt Meter Code----------//

      int Volt_Alarm_Set_Point; // this works
      float Volt_Set_Point;
      int s = 0;
      int a = 0;
      int b = 0;

     int Button_1 = 5;
     int Button_2 = 6;
     int Button_3 = A1;
     int Button_4 = A0;
     int Alarm_Relay_1 = A3;
     int Relay_2 = A2;
     int Relay_3 = 8;
     int Blinking_Led = 3;// this one is ready to be used anytime

     #define VOLT_ALARM_SET_POINT_ADDR 0
     #define A_ADDR VOLT_ALARM_SET_POINT_ADDR + sizeof(int)
     #define B_ADDR A_ADDR + sizeof(int)

     #define Is_Pressed  0  // used for pushbuttons
     #define Is_Not_Pressed  1  // used for pushbuttons
     #define Is_Turned_On 1  // used for the relays
     #define Is_Turned_Off 0 // used for the relays

     //|---------void setup---------void setup---------|//
    void setup() {

        pinMode(Alarm_Relay_1, OUTPUT);
        pinMode(Relay_2, OUTPUT);
        pinMode(Relay_3, OUTPUT);
        pinMode(Blinking_Led, OUTPUT);
        pinMode(Button_1, INPUT); // on pin 5
        pinMode(Button_2, INPUT); // on pin 6
        pinMode(Button_3, INPUT); // on pin A1
        pinMode(Button_4, INPUT); // on pin A0
    //-----------Volt Meter Code--------------//
        pinMode(analogInput, INPUT);
    //-----------Volt Meter Code--------------//

        lcd.begin();

        lcd.setCursor(0, 0);
        lcd.print(F(" This Program Is an "));
        lcd.setCursor(0, 1);
        lcd.print(F("example on how to   "));
        lcd.setCursor(0, 2);
        lcd.print(F("save a float. Named "));
        lcd.setCursor(0, 3);
        lcd.print(F("Save_Float_Using_Int"));
        delay(3500);

        lcd.clear();

        EEPROM.get(VOLT_ALARM_SET_POINT_ADDR, Volt_Alarm_Set_Point);
        EEPROM.get(A_ADDR, a);
        EEPROM.get(B_ADDR, b);

    }// end of the void setup()

    //|---------void setup---------void setup---------|//
    //|---------void loop---------void loop---------|//

    void loop() {

        delay(50);
      //increment & decrement Volt_Alarm_Set_Point
        if (digitalRead(Button_1)==Is_Pressed
          ||digitalRead(Button_2)==Is_Pressed)
          {Adjust_The_Volt_Alarm_Set_Point();}

        Volt_Set_Point = Volt_Alarm_Set_Point*0.1;// this math displays the correct float value to the Lcd

        Read_Volt_Meter();

        lcd.setCursor(0, 0);
        lcd.print(F("This is the Volt adj"));

        if (Volt_Set_Point<10.00)// this if statement gets rid of leftover unwanted #'s
        {lcd.setCursor(19, 1);   // while decrementing the Volt_Set_Point variable
        lcd.print(" ");}
        lcd.setCursor(0, 1);
        lcd.print(F("Volt Set Pnt = "));
        lcd.setCursor(15, 1);
        lcd.print(Volt_Set_Point); // 2nd line of Lcd (displays float variable)

        lcd.setCursor(0,2);
        lcd.print(F("Voltage = "));
        lcd.setCursor(10, 2);
        lcd.print(vin);
        if (Volt_Alarm_Set_Point<10)//this if statement gets rid of leftover unwanted #'s
        {lcd.setCursor(17, 2);      // while decrementing the Volt_Alarm_Set_Point variable
        lcd.print(" ");}
        if (Volt_Alarm_Set_Point<100)// this if statement gets rid of leftover unwanted #'s
        {lcd.setCursor(18, 2);       // while decrementing the Volt_Alarm_Set_Point variable
        lcd.print("  ");}
        lcd.setCursor(16, 2);
        lcd.print(Volt_Alarm_Set_Point);  // 3rd line of Lcd (displays saved integer variable)

        if (vin <= Volt_Set_Point){digitalWrite(Relay_3, Is_Turned_On);}
        if (vin > Volt_Set_Point){digitalWrite(Relay_3, Is_Turned_Off);}

        lcd.setCursor(0, 3);lcd.print("A = ");lcd.setCursor(4, 3);lcd.print(a);
        lcd.setCursor(6, 3);lcd.print("B = ");lcd.setCursor(10, 3);lcd.print(b);

        if (a==0) {digitalWrite(Relay_2, Is_Turned_Off);}
        if (a==1) {digitalWrite(Relay_2, Is_Turned_On);}

        if (b==0) {digitalWrite(Alarm_Relay_1, Is_Turned_Off);}
        if (b==1) {digitalWrite(Alarm_Relay_1, Is_Turned_On);}

        if (digitalRead(Button_4)==Is_Pressed){
          if (a==0){a=1;}else{a=0;}
          while (digitalRead(Button_4)==Is_Pressed){
          if (a==0) {digitalWrite(Relay_2, Is_Turned_Off);}
          if (a==1) {digitalWrite(Relay_2, Is_Turned_On);}
          lcd.setCursor(0, 3);lcd.print("A = ");lcd.setCursor(4,3);lcd.print(a);
          }
          EEPROM.put(A_ADDR, a); EEPROM.put(B_ADDR, b);
        }

        if (digitalRead(Button_3)==Is_Pressed){
         if (b==0){b=1;}else{b=0;}
         while (digitalRead(Button_3)==Is_Pressed){
         if (b==0) {digitalWrite(Alarm_Relay_1, Is_Turned_Off);}
         if (b==1) {digitalWrite(Alarm_Relay_1, Is_Turned_On);}
         lcd.setCursor(6, 3);lcd.print("B = ");lcd.setCursor(10,3);lcd.print(b);
         }
         EEPROM.put(A_ADDR, a); EEPROM.put(B_ADDR, b);
        }
      }// end of the void loop()

    //|---------void loop---------void loop---------|//
    //======= Subroutine Area ======= Subroutine Area =======//

      void Adjust_The_Volt_Alarm_Set_Point()
     { s=0;
      // push button to increase this Alarm Set Point
      if (digitalRead(Button_2) == Is_Pressed)
         { s=1;
          if (Volt_Alarm_Set_Point <= 150)
          {
           Volt_Alarm_Set_Point = Volt_Alarm_Set_Point + 1;// this line is using a int variable
           if (Volt_Alarm_Set_Point > 150)
              {Volt_Alarm_Set_Point = 150;}
          }
         }
     // push button to decrease this Alarm Set Point
      if (digitalRead(Button_1) == Is_Pressed)
        { s=1;
         Volt_Alarm_Set_Point = Volt_Alarm_Set_Point - 1;// this line is using the int variable
         if (Volt_Alarm_Set_Point <= 0)
         {Volt_Alarm_Set_Point = 0;}
        }// the s variable here insures we save once & only when a button is pressed
        if (s==1){EEPROM.put( VOLT_ALARM_SET_POINT_ADDR,Volt_Alarm_Set_Point);}
     }

    void Read_Volt_Meter()
    {
       //-------------------------------Volt Meter Code-------------------------------//
       //-----------------------------------// This code reads the value at analog
       value = analogRead(analogInput);//---// input A6 and this is where we can change
       vout = (value * 4.72) / 1024.0;//----// the volts value to what the actual supply
       vin = vout / (R2/(R1+R2));//---------// voltage is equal to by checking it with an
       if (vin<0.09) {//--------------------// accurate Digital Votl Meter then entering
       vin=0.0;//---------------------------// it here-->(value * 4.79) changing the 4.79
       }//----------------------------------// to whatever your meter reads...
       //-------------------------------Volt Meter Code-------------------------------//
    }
    //======= Subroutine Area ======= Subroutine Area =======//
    // end the Subroutine Area
    // end of the program...
    }

Here, these are universal functions you should be able to use anywhere.
Call this function by using SaveFloat(your float); eg SaveFloat (12.34);
or call float yourfloat = LoadFloat();
void SaveFloat (float input) {

  String valstring = String(input);

  int digitcount = 0;

  for (int index = 0; index < valstring.length(); index++) {

    if (String(valstring.charAt(index)) != ".") {

      String temp = String(valstring.charAt(index));
      int digit = temp.toInt();

      EEPROM.update(index + 10, digit); // Change + 10 to whatever address you want to be the starting address. eg + 11 will be EEPROM.read(11);

    } else {

      EEPROM.update(index + 10, 254); // Change + 10 to whatever address you want to be the starting address. eg + 11 will be EEPROM.read(11);

    }

    digitcount++;

  }

  EEPROM.update(9, digitcount); //This address is important, so set it to an address you arent using.

}

float LoadFloat () {

  String output = "";

  for (int index = 0; index < EEPROM.read(//where you stored "digitcount"); index++) {

    if (EEPROM.read (index + 10) < 10) { // Change + 10 to whatever address you want to be the starting address. eg + 11 will be EEPROM.read(11);

      output += EEPROM.read (index + 10); // Change + 10 to whatever address you want to be the starting address. eg + 11 will be EEPROM.read(11);

    } else {

      output += ".";

    }

  }

  return output.toFloat();

}

Why are you doing all these useless and complex binary ↔ text ↔ BCD conversions just for storing the value? Why not store it as-is, in binary? E.g. void SaveFloat(float x){EEPROM.put(10,x);} and float LoadFloat(){float x;return EEPROM.get(10,x);}

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


text:
Serial Monitor and UART
After uploading the code, can I connect a UART peripheral's RX, TX to TX, RX (D0 ,D1) and use the serial monitor of the arduino together ? Will data reception from the peripheral properly work in this case, or will it conflict with the serial monitor ?

You can use the serial monitor in this way, as long as you ensure you do not send anything from the serial monitor out to the Arduino or peripheral, only to monitor data.
That said, if you try to send debug prints from the Arduino to the serial monitor, they will also be sent to the peripheral device, where there may be conflict, depending on the peripheral.
So you technically can, but it's not advised because there are several ways it can go wrong.
One alternative is to use the SoftwareSerial library to create a second, bit-banged serial port. Note, however, that this library can't operate at high speed (probably best to keep at 9600 bps) reliably.


text:
Overheating Shift-Register(74HC595)
I am working on a project where I need to use around 50 LED's connected to an Arduino UNO board. To begin with i worked on the tutorial provided by Arduino (https://www.arduino.cc/en/Tutorial/ShiftOut) to connect two shift registers(74HC595). Everything works fine, but the shift registers get very hot in just a few minutes. Is this normal?

Check the specs to see how much amps they can drive. Increase the current limiting resistance or buffer the signal using transistors if needed.

Calculate the total current driving your LEDs, and compare to the 74HC595 datasheet about the maximum driving current it can source. You may need to drive the LEDs with larger current-limiting resistors, or use the shift register to control transistors that do the actual switching. For example, the TI SN74HC595 (http://www.ti.com/lit/ds/symlink/sn74hc595.pdf) has an absolute maximum continuous current through Vcc or GND of 70mA.

@josecanuc Yeah I think I drawing too much current than it can provide. Thank you:)

That tutorial has many errors. You should ignore it and find a better one. There is a post here somewhere about all the things wrong with it.

Here's the post I mention: https://arduino.stackexchange.com/questions/39827/is-the-shiftout-tutorial-on-the-official-arduino-website-really-wrong-regarding

I can only think about two things:

(least probably): the entrance (VCC) voltage is too high.
(most probably): the resistors to the LEDs are (too) low .. Recalculate the values and check the max amperes which can be handled by the output pins of the shift registers.

Yeah the problem was with the LEDs having too low resistance. Thanks a lot:)

You are welcome ... you can accept / upvote the answer to let others know the problem has been solved.


text:
Error using Adafruit Feather M0
I am trying to upload an empty program on the Adafruit feather to see if it connects to my PC. So far, it isn't. I'm running a Windows 10 and I followed this guide:
https://learn.adafruit.com/adafruit-feather-m0-wifi-atwinc1500?view=all
But I get this error:
Couldn't find a Board on the selected port. Check that you have the correct port selected.  If it is correct, try pressing the board's reset button after initiating the upload.
And the PORT submenu is greyed out.

Were you able to get this working? I am having the same issue..

I found out the issue I was having, though I have a Gemma.
What worked for me:

Selecting the correct board under "Tools" -> "Board:" (in your case, the Adafruit Feather 32u4 is probably the one you want)
Selecting the "USBtinyISP" under "Tools" -> "Programmer:"

Then it was able to upload to the Gemma, after hitting it's reset button twice to get it into a 'programming mode' (I don't know if the feather has such a feature).
If you are still having problems make sure that you have properly set up your arduino IDE for adafruit boards, and just play around with settings (try different programmers).
I don't know why it was so hard finding this info out, and why it is not more visible on the documentation to set these things up. I think I found out the 'hitting reset twice' thing somewhere buried in a forum... I digress, but Adafruit does need to consolidate their documentation to make it clearer.
Hope this helps

A common problem on Windows for people who may be encountering this type of issue is actually having the wrong USB to UART Bridge drivers or none at all. You can download the most up to date ones here


text:
Problem using ICSC (by majenkotech) in RS485 bus
I want to communicate with an RS485 Bus consisting of 5 Arduino Pro Minis as slaves and one Arduino Mega 2560 as Master. I found a great library for this.
According to the documentation provided by the author of library I can use:
ICSC icsc(1, 9600, 7); //ID, BaudRate, DEpin
But I also have to define a Serial port for ICSC to work with:
ICSC icsc(1, 9600, Serial1);
I cannot mix these two sentences. I mean I cannot define both DEpin and Serial port for the ICSC in one sentence. But I need it to be defined. I don't want to use Serial for that, which I need for Serial Monitor. I want to use Serial1 for this. What can I do? I couldn't find any updated documentation about this.
UPDATE:
I found out how to define Serial port and DEpin for ICSC. The problem is I cannot get an answer!
Here is Master code:
#include <ICSC.h>
ICSC icsc(Serial1, 1, 7); //Stream, ID, DEpin

void setup() {
  Serial.begin(9600);
  Serial1.begin(9600);
  icsc.begin();
  icsc.registerCommand('R', &showTemperature);
}

void loop() {
  icsc.send(2, 'T', 0, NULL);
  icsc.process();
}

void showTemperature() {
  Serial.println("ACK");
}

And here is the Slave code:
#include <ICSC.h>
ICSC icsc(Serial, 2, 7); //Stream, ID, DEpin
String strAck = "ProMini2:ACK";

void setup() {
  Serial.begin(9600);
  icsc.begin();
  icsc.registerCommand('T', &sendTemperature);
}

void loop() {
  icsc.process();
}

void sendTemperature() {
  icsc.send(1, 'R', sizeof(strAck) + 1, (char*)&strAck);
}

Assume that there is just one slave and one master. I tried this code but got no answer. Where is the error?

The documentation for the constructors is out of date (I am re-writing as we speak, and is now here).
The constructors in the header file are like this:
ICSC(Stream *d, uint8_t station);
ICSC(Stream &d, uint8_t station);
ICSC(Stream *d, uint8_t station, int depin);
ICSC(Stream &d, uint8_t station, int depin);

That means you need to provide the serial object as the first entry:
ICSC icsc(Serial1, 'A', 5);

You need to manually start the serial object before ICSC.
void setup() {
    Serial1.begin(9600);
    icsc.begin();
}

This change was made to enable support for software serial and other Stream based devices.

Addendum for your update:

Don't spam the sending like you are. Send periodically, not constantly, or you will never be able to receive.
You cannot use String objects like that.
1 and 2 aren't good choices of station IDs. Yes, they work, but not great, since 1 is the SOH character.

But what if i begin both Serial and Serial1 right after eachother ? Which one will be assigned to ICSC?

Whichever one you assign to ICSC.

I'll give it a try tomorrow and will let you know. Thx in advance.

Can i use this constractors in current version of icsc which i'm using?

That is the constructors for the version on Github.

Question updated :)
I followed your guides, But i still have problem.

Answer updated also.

Thx, I can now send and receive data, but i still have problem sending string to master

Never use String. Use char *.

However, with ICSC there is little call to send strings. It's designed for transferring numerical data from sensors.

Now im able to send strings over ICSC. I realized a problem with ICSC: When i disconnect one of MAX485s from circuit, No other devices respond to master! For example i disconnected just DEpin of ProMiniC and then i couldnt get answer from both ProMiniB and ProMiniD

Disconnecting DE leaves it floating. You have a corrupt transceiver on the bus. Nothing to do with ICSC.

The documentation for the library notes a few different possible initialization methods:
ICSC.begin(stationId, baudRate);
ICSC.begin(stationId, baudRate, &SerialPort);
ICSC.begin(stationId, baudRate, &SerialPort, DEPin);
ICSC.begin(stationId, baudRate, DEPin);

So, if you need to define both a serial port and DE Pin, use the third option.
EDIT: Disregard this answer, as the library has changed initialization methods.

I tried that, but gives error: No overload method matches the (int, int, &, int) was found. Something like that :)

That documentation is out of date.


text:
cheap long lasting options for battery?
I recently made a differential drive using Arduino UNO, two BO dual shaft 9v Motor and ld293d.To power Arduino, I am using a Hi-Watt 9 volt battery, to power the ld293d 5v pin (VCC1) I am using Arduino 5v Vout pin and to power its motor driver pins (VCC2) I am using Hi-Watt 9 volt battery.
The problem is its not long lasting and after moving just a bit like 30 seconds it slows down and stops ,or one of the motor stops working.I have tried this with multiple new 9v batteries, I don't understand why is this happening because the batteries still seems to be work on other projects.Should I use some other kind of battery if yes then what would be the cheapest option?

Don't use the Arduino 5V pin to power motors. Use the battery voltage for the driver. Did you confuse Vcc1 and Vcc2 ? Pin 8 is Vcc2 is the motor power. Pin 16 is Vcc1 is the logic 5V voltage. As @jose-can-u-c wrote, you need a better battery and a there are better mosfet drivers. With your battery it is amazing that it lasts as long 30 seconds.

9V batteries are not meant for high-current discharge, as you would find when powering a motor. Not only that, they are low capacity. If you need to power motors, you should use batteries such as C or D cells in series to build the voltage required, or try Lithium-Polymer (LiPo) for a rechargeable option.
On a side note, the L293 H-Bridge is a poor choice of H-Bridge these days, especially for a battery-powered project, as there are more efficient motor driver ICs these days.


text:
what is arduino adc reference?
I'm using arduino for the first time and don't really understand what am I suppose to plug to the ADC refernce PIN... or if I even have to use it while plugging analog sensor to the arduino,
thanks!

Does https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/ help? You don't have to use it.

The AD converter in the ATMega microcontroller (as used in Arduino) converts an input voltage to a number.
This ADC happens to be 10 bit that means 2^10 states which is 1024.
The number 0 (zero) means 0 Volt input voltage.
The number 1023 means the maximum input voltage.
Since 0 is also a value the scale runs from 0 to 1023 making 1024 values.
The scale is linear so 511 means half of that maximum voltage.
What is this maximum input voltage?
That is the ADC Reference voltage. By default the power supply voltage is used so if you run your Arduino on 5 V, then 1023 = 5 V. But if you run your Arduino on 3.3 V, then 1023 = 3.3 V.
There is also in internal reference of 2.56 V (or 1.1 V depending on your Arduino), if you use that then, you guessed it, 1023 = 2.56 V (or 1.1V).
You might have a very fancy external reference voltage already available and if you want to use that, use the external setting and connect that reference voltage to the AREF pin.
If your analog sensor gives 0 to 5 V and your Arduino is also powered by 5 V then you should use the default setting so that the VCC is used as ADC reference.
If your sensor gives a voltage between 0 and 1 V then you could use the internal reference so that more of the 0 to 1023 range is usable. Giving you get better resolution.

The default behaviour is for the analog reference to be Vcc which on many Arduinos is 5V. In that case do not connect anything to AREF.
However if you have a precision voltage reference then you can connect that to AREF (and GND) and specify in your sketch, before doing an analogRead:
 analogReference (EXTERNAL);

I have a page about the ADC converter which may help explain, or may be too much detail. :)

or if I even have to use it while plugging analog sensor to the arduino

Unless you are planning to use some different reference voltage, don't use it at all.
For a 5V Arduino the voltage measured with the default AREF would roughly be 4.88 mV per unit of measurement (ie. 5V / 1024), but more accurately:
float voltage = ((float) rawADC  + 0.5 ) / 1024.0 * Vref;

The voltage you supply to VREF (if you supply any at all) must be between 1.0V and Vcc where Vcc would be 5V for an Arduino Uno.

“do not connect anything to AREF” and “[call analogReference(EXTERNAL)] before doing an analogRead” (amphasis mine). These are very important points not mentioned in the other answers.

I added the emphasis in my answer in case it was too mild as it was. ;)

The AREF is a reference voltage input pin.
The reference voltage is maximum voltage when you measure analog signal.
In other words, you can measure 0V ~ AREF voltage by using ADC port.
Be aware that the minimum voltage of AREF is 1.0V.

Well, I think you should read the manual first before you use (and even perhaps brake it).
Generally speaking, analog reference is a voltage value between 0.00 and 5.00V, which will be used as virtual reference for all the analog inputs, you connect to your arduino board.
About analog reference is on Arduino site:
https://www.arduino.cc/reference/en/language/functions/analog-io/analogreference/


text:
ESP-01 not running custom firmware
I have two esp-01 micro controllers that I'm trying to flash using the Arduino IDE but found some problems in the process. I followed step 1 of this tutorial to install all the dependencies to the IDE.
As for the code, it's one of the examples:

/*
 ESP8266 Blink by Simon Peter
 Blink the blue LED on the ESP-01 module
 This example code is in the public domain

 The blue LED on the ESP-01 module is connected to GPIO1
 (which is also the TXD pin; so we cannot use Serial.print() at the same time)

 Note that this sketch uses LED_BUILTIN to find the pin with the internal LED
*/

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);     // Initialize the LED_BUILTIN pin as an output
}

// the loop function runs over and over again forever
void loop() {
  digitalWrite(LED_BUILTIN, LOW);   // Turn the LED on (Note that LOW is the voltage level
                                    // but actually the LED is on; this is because
                                    // it is acive low on the ESP-01)
  delay(1000);                      // Wait for a second
  digitalWrite(LED_BUILTIN, HIGH);  // Turn the LED off by making the voltage HIGH
  delay(2000);                      // Wait for two seconds (to demonstrate the active low LED)
}

I'm flashing it using the serial port communication, and the circuit is the following:

Having an MB102 as the power supply and a FT232RL as FTDI. Obviously everything at 3.3V.
I can flash the device properly when using the Arduino IDE. This is the output:
C:\PATH\Arduino15\packages\esp8266\tools\esptool\0.4.9/esptool.exe -vv -cd ck -cb 115200 -cp COM3 -ca 0x00000 -cf
C:\SOMEPATH\Temp\arduino_build_913175/Blink.ino.bin
esptool v0.4.9 - (c) 2014 Ch. Klippel <ck@atelier-klippel.de>
    setting board to ck
    setting baudrate from 115200 to 115200
    setting port from COM1 to COM3
    setting address from 0x00000000 to 0x00000000
    espcomm_upload_file
    espcomm_upload_mem
    setting serial port timeouts to 1000 ms
opening bootloader
resetting board
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    read 0, requested 1
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
warning: espcomm_send_command: wrong direction/command: 0x01 0x00, expected 0x01 0x08
trying to connect
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
    espcomm_send_command: receiving 2 bytes of data
Uploading 226352 bytes from
C:\SOMEPATH\Temp\arduino_build_913175/Blink.ino.bin to flash at 0x00000000
erasing flash
    size: 037430 address: 000000
    first_sector_index: 0
    total_sector_count: 56
    head_sector_count: 16
    adjusted_sector_count: 40
    erase_size: 028000
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    setting serial port timeouts to 15000 ms
    setting serial port timeouts to 1000 ms
    espcomm_send_command: receiving 2 bytes of data
    writing flash
................................................................................ [ 36% ]
................................................................................ [ 72% ]
..............................................................                   [ 100% ]
starting app without reboot
    espcomm_send_command: sending command header
    espcomm_send_command: sending command payload
    espcomm_send_command: receiving 2 bytes of data
closing bootloader
    flush start
    setting serial port timeouts to 1 ms
    setting serial port timeouts to 1000 ms
    flush complete

So everything looks fine, but after rebooting the device (by turning on and off the power supply) and removing the GPIO0 connection to the ground to avoid the flash mode, nothing happens. Looks like the program is not executing successfuly and the LED doesn't blink or anything.
Does anyone know if I'm doing something wrong? Should I connect GPIO0 to the power supply to get a high voltage after flashing the device, to make sure the GPIO0 doesn't stay at low at boot time and it enters flash mode?
Note that I tried with both ESP-01 to make sure it wasn't a deffective one, and also note that the LED of the mcu is ON, so it is obviously powered on.

Try explicitly setting the pin for GPIO1 instead of using LED_BUILTIN, i.e.: pinMode(1, OUTPUT); and then digitalWrite(1, LOW); and digitalWrite(1, HIGH);. It could be that the header you use for the ESP8266 has a different pin set for the built-in LED.

I'll try, but still I belive it's something related to how I flash it or how it runs the firmware since even uploading a program with basic serial communication (a print saying "HELLO") won't work.

@lpares12 I found on my devices that the usual definitions for the pins simply weren't right (the usual Arduino assignments were ignored in the design.) I also found that the LEDs weren't even close to the same number, either. I don't recall, but it was like I had to hard-code a 6 to get to the LED that would otherwise have been 1. Like that. Later... much later... I found some docs that helped. I still have no idea why the designers went the way they did. But everything worked once I pinned down the numbers.

@jonk but still it doesn't explain why other example codes which do not use the LED don't work. For example, only using the serial communication to print "hello" every second doesn't work either, just outputs random symbols in the serial console (even changing the baud rate in both the code and the serial connection, being always the same of course)

@lpares12 I only used the LED and also the WiFi library with the device. So I can't really add anything to your troubles about the serial console part. I wish I could. If I had to guess (and I do), I'd imagine that it was (1) incorrect library code being used, despite the docs you found; or (2) my own misuse of them, somehow. I tend to assume that the hardware works okay (never been wrong about that assumption.) So it is always "my problem" in having the right device info or the right library code or the right compiler setup. I wish I knew more about that particular issue. But I don't.

@RonBeyer didn't work either setting it explicitly. Will try to erase all the flash memory with esptool and upload the program again.

First suggestion: http://www.esp8266.com/viewtopic.php?f=26&t=4014[http://www.esp8266.com/viewtopic.php?f=26&t=4014] second suggestion: http://www.esp8266.com/viewtopic.php?f=6&t=14276[http://www.esp8266.com/viewtopic.php?f=6&t=14276]


text:
boolean always false after 32 seconds
I have a boolean expression (I think it's called), and it will always return false after 32 seconds of running, and I'm very confused now.
if (millis() > stepTime+lightCmd[stepe][5]) {
  stepe = (stepe+1)%STEPS; //I'm bad at naming variables, sorry
  stepTime = millis();
  Serial.println("changing"); // debugging
}

This runs inside the main loop.
Also, I've tried using an exponent when trying to get some lights to appear to fade linearly and in about the same amount of time, 32 seconds, it would start fading in reverse.
EDIT:
millis(); wouldn't go backwards after it stopped working

Use the https://www.arduino.cc/en/tutorial/BlinkWithoutDelay example. You should not compare millis to a value and you should not add something to the millis value. If you have a problem, please provide a full working sketch, so we can test it.

@Jot please turn your comment into an answer.

Is stepTime an unsigned long ?

no, it's an integer, it's the same as previousMilliseconds in the blink without delay, link on first comment

@Jot I tried doing something similar to the example, but it seems to be returning true once it gets to 32 seconds, I'm going to look more carefully at the example

You code is nothing like the blink without delay. There is a specific way to use millis: "the current millis" - "a previous millis value" >= interval. And the current millis and the previous millis must be a "unsigned long". The current millis can also be a call to millis() of course. An integer? And the 32 seconds is perhaps 32767 milliseconds?

@Jot ok, I was going to try making stepTime an unsigned long just now, so thanks!

When you add a value to 'stepTime' and still use the '>' with millis, then you still have the rollover problem.

Glad you got it working. Just note that millis will overflow after about 50 days. So if you project has to run longer that that, the if-statement will fail after 50 days.

@Gerben I won't need to run it nearly that long, so it won't be a problem.

When dealing with millis and micros you must always use unsigned long variables; otherwise, values will be overflow/truncate.
When doing time arithmetic, you must always use differences, not additions, because of the nature of unsigned arithmetic.
Your updated sketch is this:
void setup()
{
    Serial.begin(9600);
    while(!Serial);
    Serial.println(); Serial.println("Test");
}

#define STEPS 3
unsigned long lightCmd[STEPS] = {4000, 60000, 90000};
int stepe = 0;
unsigned long stepTime = 0;

void loop()
{
    if(millis() - stepTime >= lightCmd[stepe]) {
        Serial.print(stepe);
        Serial.print(".- ");
        stepe = (stepe+1)%STEPS; //I'm bad at naming variables, sorry
        stepTime = millis();
        Serial.print(stepTime);
        Serial.println(" changing"); // debugging
    }
}


text:
How does Arduino UNO deal with bit shifting?
Explanatory comment: I'm a beginner. I'm examining the feasibly of bit shifting to the right 6 places to divide up the range of the Arduino ADC (has a range of 0 to 1023) to something much smaller. Such that any number in the ADC registers, between 0 and 63 produces a value of 0, a number between 64 and 127 a 1, between 128 and 191 a 2, between 192 and 255 a 3, etc. There is a change every 64 increase in the initial number.
I think this is possible to do. But some doubt has been expressed I think.
As far as I have determined, after right shifting 6 places to the right the following values of numbers are resident in the ADC registers: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15.
I wish you to consider, is there anything in the way Arduino's IDE works, or with the nature of the initial number in the register (signed/unsigned) that makes the results I have indicated false.  I think, that the initial number will be unsigned, just guessing.

analogRead(pin_number) >> 6 will give you wat you want, as a signed integer in the range 0 – 15.

There are two types of right-shift in C - logical and arithmetic.
GCC (which is the compiler the Arduino IDE uses) selects which one to use depending on whether the type you are shifting is signed or not:

If it's signed then use an arithmetic shift
If it's unsigned then use a logical shift

In a logical shift, the value is literally shifted to the right padding the left side with zeros. An arithmetic shift, however, shifts and extends the sign. I.e., it performs an arithmetical "divide by 2".  That means if you right shift a negative value to still have a negative value (Note: this behaviour is implementation specific, so is only applicable to GCC. For other compilers in other situations you will have to check the documentation of that compiler).
So if you store the results of analogRead() in an unsigned integer variable >> N will right shift the value N times. If you store it in a signed integer it will divide the value by 2 N times.
For a positive value, which the results of analogRead() will be, the end result is the same - divide by 2 N times.
So if you right-shift 6 times you reduce a 10-bit value down to (10-6) 4 bits. 24 is 16, so you get 16 possible values.  24-1 is 15, so you get values 0-15 in your final value.

Why should it make a difference in terms of efficiency? On the AVR at least, both lsr (logical shift right) and asr (arithmetic shift right) are one-cycle instructions.

I was not aware of asr.


text:
Using Visual Studio Code with Arduino
I'm trying to figure out how you can work with multiple sketches using Visual Studio Code and the Arduino.
Let's say I have three projects that I want to actively develop.
Motors.ino
Motors_with_controls.ino
Motors_with_lights.ino

Each one is a different project, but I want to quickly be able to upload one, then upload another.
My folder for Visual Studio Code is set up as such:
ArduinoProjects
   .vscode
       arduino.json
       c_cpp_properties.json
   Motors
       Motors.ino
   Motors_with_controls
       Motors_with_controls.ino
   Motors_with_lights
       Motors_with_lights.ino

But it seems like the only way to upload a particular ino is to go into the arduino.json file and hand edit the "sketch" parameter.
"sketch": "Motors\\Motors.ino"

Is there a quicker way? Ideally I'd like it to upload the ino I am currently editing without having to go and edit the arduino.json file.


text:
digitalRead keeps giving 1
I am new to arduino programming and I have bought arduino UNO a few days ago.
I am trying to read the value of pin 4 using digitalRead with pinMode INPUT_PULLUP but it keeps giving me 1 even when the pin 4 is not connected to anything.
Here is the code:
void setup() {
  pinMode(2,OUTPUT);
  pinMode(4,INPUT_PULLUP);
  Serial.begin(9600);
  digitalWrite(2,HIGH);
}

void loop() {
  Serial.print(digitalRead(4));
  Serial.print('\n');
  delay(150);
}

Pin 2 is connected to one side of the button and Pin 4 is connected to other side of the button.
According to condition, when the button should be off , the value should be 0 and when the button  should be on , the value should be 1 , but the value is 1 even when I press the button is off or on.
On the other way , if I replace INPUT_PULLUP with INPUT then the value is floating.
Why the value with INPUT_PULLUP is 1?

“when the button should be off , the value should be 0”: what led you to this assumption?

You have set Pin 2 to HIGH, which is 5V. You have set Pin 4 to INPUT_PULLUP, which means if no signal is driving it, it will be HIGH.
You have connected a button between Pins 2 and 4. So, if you don't press the button, the input is pulled HIGH. And if you do press the button, Pin 2 is driving it HIGH.

@J.Doe: The standard way to wire a push button is to connect it between a digital input and ground. If you set the digital input to INPUT_PULLUP mode, the pin will read LOW when the button is pressed and HIGH when it's not.

There are to simple options how to connect a simple button. You mixed them.
Better option is connect the button between pin with INPUT_PULLUP and ground. The pin is HIGH when the button is open and LOW when the button grounds the pin. This option is better because if you disconnect the button, the pin is still pulled up to HIGH and not floating.
If you connect the button with a pull-down circuit, then the pin is HIGH when the button is pressed and LOW when the button is open, but when you disconnect the circuit, the pin floats and the sketch reads chaos.

This looks as it is operating as wired and programmed.  When the button is open, the INPUT_PULLUP is pulling pin 4 to HIGH, and when the button is closed & shorted to pin 2, the digitalWrite(2,HIGH) would also pull the pin 4 to HIGH.
Maybe you want digitalWrite(2,LOW) so that connecting pin 4 to pin 2 through the button would pull pin 4 low.

But then there is no point in using pin 2 instead of GND.

I don't know why Doe did that, but he wasn't doing it correctly.  I sometimes provide power or ground through the output pins so I can plug a device directly into a header, or so I can switch the device on or off, but it kind of a sloppy, cheap hack.

"digitalWrite" was misspelled as "digitalWtite" here. Not sure why it was rolled back.

@Pikamander2 Tiny, trivial edits are discouraged and you added &nbsp at the end. https://arduino.stackexchange.com/help/privileges/edit