Introduction to Arduino Programming



We will first look at the basics of the Arduino Language and Arduino Programming in general. You can be very productive very quickly, very early on just by doing the basics. The Arduino Language is C++, an efficient language, used very often for various equipment parts, and C++ is everywhere. C++ is fairly complicated with a very steep learning curve, and you will only be using a small subset that is very easy to learn even if you don't have any programming experience in the past. The most important thing is that C++ is object-oriented, a common characteristic of many modern programming languages. In such a language, an object is a construct that combines functional code (turning on a motor, etc.) with a state (part of the object that remembers things and stores calculations in memory) and this has made programming much more productive in most types of applications. OOP allows programmers to use abstraction for complicated programs. Most modern languages have been influenced heavily by C++.

A lot of code will be inferencing libraries that consist of definitions, which are called classes, making you productive right away just by learning a small subset of C++. Arduino IDE has a C++ compiler open-source, but every time you click, the IDE starts up the compiler to convert the human-readable code to machine code and sends it to the microcontroller via the USB cable. C++ is made up of conditionals, objects, structures, data structures, and other aspects.

Hardware-wise, the only thing you need to do is to take your Arduino and connect it to the USB port for this section.  

void setup() {

  // put your setup code here, to run once:

}


void loop() {

  // put your main code here, to run repeatedly:

}

The simplest possible Arduino sketch is the setup() and loop() and directly into a blank sketch. The setup() code indicates that these functions do not take parameters. After the setup loop, the code will be continuously run in a loop and anything inside the loop() function will be executed. Notice that both of these functions have open and closed parentheses with nothing inside them. There will be a compilation error if you try to add parameters in any of these functions. You can't remove these functions, otherwise, the compilers will produce an error message. The one thing is you first enable the serial monitor, and give it the speed of communication and just print something out. 

Serial is a collection of functions. .begin starts the channel at a particular speed, between the computer and arduino, or 9600 bits per second. println is used to print out a message and create a new line (ln). .print just has "hello" printed to monitor, but with no new line. 

void setup() {

  // put your setup code here, to run once:

  Serial.begin(9600);

  Serial.println("Hello");

  Serial.print("Hello");

}


void loop() {

  // put your main code here, to run repeatedly:

}

Now we want to upload this to the board through Tools, which shouldn't be too difficult to perform. We select the right board and port. Opening up the Serial monitor prints ("Hello"). The speed of the sketch and serial monitor should be the same.

Now we can print a familiar serial kit, and we'll see what the following code does. 

void setup() {

  // put your setup code here, to run once:

  Serial.begin(9600);

  Serial.println("Hello");

  Serial.print("hello again");

}


void loop() {

  // put your main code here, to run repeatedly:

  Serial.println(millis());

  delay(1000);

}

It will leave a new line and print the number of milliseconds since the sketch began executing or power was applying (millis()).


The bottom right helps adjust the baud rate to send such a signal. Edit --> Comment/Uncomment forward slashes things out and writes the necessary lines, and we try to verify now, and clicking on the tick button, verify will not work, since there will yield an error attempting to link everything together since the Arduino default always automatically invokes the loop() function internally. 

Next, we want to get over custom functions. A function is a group of instructions that you put together with a  name of a specific task, and you can call the function by its name. The name of the setup function I used to call the serialization instructions and have them executed one after the other. You can organize sketches by grouping instructions inside functions.

To create a function, you need a definition. The definition has a return type, then a name, and a set of parameters. In the case of the loop, we have no parameters, meaning the function doesn't have parameters. But let's say we want to create another function like the following. The return type tells the compiler what to return. You can name your functions anything you would like as long as you don't use a reserved word. 

You can't use // % $ # _ (space) (tab)

Only use lowercase, uppercase, numerics, hyphens, and underscores. Also, don't start with a number in the beginning. 


void setup() {

  // put your setup code here, to run once:

  Serial.begin(9600);

  Serial.println("Simple Calculation Using Functions");

}


void loop() {

  // put your main code here, to run repeatedly:

}


int do_a_calc() {

  Serial.println(1+1);

}

We got our print statement but there is no result for the calculation. We can figure out we don't have our result due to lacking to reference and invoking the function instead of the setup() or the loop() function. The setup() will execute the function once, and the loop() function has the function modify continuously. Let's make a call in the setup: 

void setup() {

  // put your setup code here, to run once:

  Serial.begin(9600);

  Serial.println("Simple Calculation Using Functions");

  do_a_calc();

}


void loop() {

  // put your main code here, to run repeatedly:

}


int do_a_calc() {

  Serial.println(1+1);

}

And now the result is 2, which is exactly what we wanted in the first place.

Now let's make the function receive more than one parameter. We need to give a data type for variables as well. 

void setup() {

  // put your setup code here, to run once:

  Serial.begin(9600);

  Serial.println("Simple Calculation Using Functions");

  do_a_calc(1, 2);

}


void loop() {

  // put your main code here, to run repeatedly:

}


int do_a_calc(int number_1, int number_2) {

  Serial.println(number_1 + number_2);

}

This result would be 3 after the function is successfully invoked.

Here's the log in the case of curiosity and studying what it said: 

C:\Program Files (x86)\Arduino\arduino-builder -dump-prefs -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\cchu3\OneDrive\Documents\Arduino\projects\libraries -fqbn=arduino:avr:uno -vid-pid=2341_0043 -ide-version=10813 -build-path C:\Users\cchu3\AppData\Local\Temp\arduino_build_326956 -warnings=none -build-cache C:\Users\cchu3\AppData\Local\Temp\arduino_cache_55569 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\cchu3\OneDrive\Documents\Arduino\projects\sketch_feb21a\sketch_feb21a.ino

C:\Program Files (x86)\Arduino\arduino-builder -compile -logger=machine -hardware C:\Program Files (x86)\Arduino\hardware -tools C:\Program Files (x86)\Arduino\tools-builder -tools C:\Program Files (x86)\Arduino\hardware\tools\avr -built-in-libraries C:\Program Files (x86)\Arduino\libraries -libraries C:\Users\cchu3\OneDrive\Documents\Arduino\projects\libraries -fqbn=arduino:avr:uno -vid-pid=2341_0043 -ide-version=10813 -build-path C:\Users\cchu3\AppData\Local\Temp\arduino_build_326956 -warnings=none -build-cache C:\Users\cchu3\AppData\Local\Temp\arduino_cache_55569 -prefs=build.warn_data_percentage=75 -prefs=runtime.tools.arduinoOTA.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.arduinoOTA-1.3.0.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avrdude-6.3.0-arduino17.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -prefs=runtime.tools.avr-gcc-7.3.0-atmel3.6.1-arduino7.path=C:\Program Files (x86)\Arduino\hardware\tools\avr -verbose C:\Users\cchu3\OneDrive\Documents\Arduino\projects\sketch_feb21a\sketch_feb21a.ino

Using board 'uno' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr

Using core 'arduino' from platform in folder: C:\Program Files (x86)\Arduino\hardware\arduino\avr

Detecting libraries used...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956\\sketch\\sketch_feb21a.ino.cpp" -o nul -DARDUINO_LIB_DISCOVERY_PHASE

Generating function prototypes...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -flto -w -x c++ -E -CC -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956\\sketch\\sketch_feb21a.ino.cpp" -o "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956\\preproc\\ctags_target_for_gcc_minus_e.cpp" -DARDUINO_LIB_DISCOVERY_PHASE

"C:\\Program Files (x86)\\Arduino\\tools-builder\\ctags\\5.8-arduino11/ctags" -u --language-force=c++ -f - --c++-kinds=svpf --fields=KSTtzns --line-directives "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956\\preproc\\ctags_target_for_gcc_minus_e.cpp"

Compiling sketch...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-g++" -c -g -Os -w -std=gnu++11 -fpermissive -fno-exceptions -ffunction-sections -fdata-sections -fno-threadsafe-statics -Wno-error=narrowing -MMD -flto -mmcu=atmega328p -DF_CPU=16000000L -DARDUINO=10813 -DARDUINO_AVR_UNO -DARDUINO_ARCH_AVR "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\cores\\arduino" "-IC:\\Program Files (x86)\\Arduino\\hardware\\arduino\\avr\\variants\\standard" "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956\\sketch\\sketch_feb21a.ino.cpp" -o "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956\\sketch\\sketch_feb21a.ino.cpp.o"

Compiling libraries...

Compiling core...

Using precompiled core: C:\Users\cchu3\AppData\Local\Temp\arduino_cache_55569\core\core_arduino_avr_uno_0c812875ac70eb4a9b385d8fb077f54c.a

Linking everything together...

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-gcc" -w -Os -g -flto -fuse-linker-plugin -Wl,--gc-sections -mmcu=atmega328p -o "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956/sketch_feb21a.ino.elf" "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956\\sketch\\sketch_feb21a.ino.cpp.o" "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956/..\\arduino_cache_55569\\core\\core_arduino_avr_uno_0c812875ac70eb4a9b385d8fb077f54c.a" "-LC:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956" -lm

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -j .eeprom --set-section-flags=.eeprom=alloc,load --no-change-warnings --change-section-lma .eeprom=0 "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956/sketch_feb21a.ino.elf" "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956/sketch_feb21a.ino.eep"

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-objcopy" -O ihex -R .eeprom "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956/sketch_feb21a.ino.elf" "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956/sketch_feb21a.ino.hex"

"C:\\Program Files (x86)\\Arduino\\hardware\\tools\\avr/bin/avr-size" -A "C:\\Users\\cchu3\\AppData\\Local\\Temp\\arduino_build_326956/sketch_feb21a.ino.elf"

Sketch uses 1562 bytes (4%) of program storage space. The maximum is 32256 bytes.

Global variables use 222 bytes (10%) of dynamic memory, leaving 1826 bytes for local variables. The maximum is 2048 bytes.

C:\Program Files (x86)\Arduino\hardware\tools\avr/bin/avrdude -CC:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf -v -patmega328p -carduino -PCOM6 -b115200 -D -Uflash:w:C:\Users\cchu3\AppData\Local\Temp\arduino_build_326956/sketch_feb21a.ino.hex:i 

avrdude: Version 6.3-20190619

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

         Copyright (c) 2007-2014 Joerg Wunsch


         System wide configuration file is "C:\Program Files (x86)\Arduino\hardware\tools\avr/etc/avrdude.conf"


         Using Port                    : COM6

         Using Programmer              : arduino

         Overriding Baud Rate          : 115200

         AVR Part                      : ATmega328P

         Chip Erase delay              : 9000 us

         PAGEL                         : PD7

         BS2                           : PC2

         RESET disposition             : dedicated

         RETRY pulse                   : SCK

         serial program mode           : yes

         parallel program mode         : yes

         Timeout                       : 200

         StabDelay                     : 100

         CmdexeDelay                   : 25

         SyncLoops                     : 32

         ByteDelay                     : 0

         PollIndex                     : 3

         PollValue                     : 0x53

         Memory Detail                 :


                                  Block Poll               Page                       Polled

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

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

           eeprom        65    20     4    0 no       1024    4      0  3600  3600 0xff 0xff

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

           lfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           hfuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           efuse          0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

           lock           0     0     0    0 no          1    0      0  4500  4500 0x00 0x00

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

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


         Programmer Type : Arduino

         Description     : Arduino

         Hardware Version: 3

         Firmware Version: 4.4

         Vtarget         : 0.3 V

         Varef           : 0.3 V

         Oscillator      : 28.800 kHz

         SCK period      : 3.3 us


avrdude: AVR device initialized and ready to accept instructions


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

avrdude: Device signature = 0x1e950f (probably m328p)

avrdude: reading input file "C:\Users\cchu3\AppData\Local\Temp\arduino_build_326956/sketch_feb21a.ino.hex"

avrdude: writing flash (1562 bytes):


Writing | ################################################## | 100% 0.27s

avrdude: 1562 bytes of flash written

avrdude: verifying flash memory against C:\Users\cchu3\AppData\Local\Temp\arduino_build_326956/sketch_feb21a.ino.hex:

avrdude: load data flash data from input file C:\Users\cchu3\AppData\Local\Temp\arduino_build_326956/sketch_feb21a.ino.hex:

avrdude: input file C:\Users\cchu3\AppData\Local\Temp\arduino_build_326956/sketch_feb21a.ino.hex contains 1562 bytes

avrdude: reading on-chip flash data:


Reading | ################################################## | 100% 0.21s

avrdude: verifying ...

avrdude: 1562 bytes of flash verified

avrdude done.  Thank you.

So this function detects libraries first, then generates function prototype, compiles sketch, and finally links everything together.

The next thing that I want to go over is the return function. The void keyword means the function will return something.

Here's how to generate the function with a return type which will be sent to whoever is invoking the call: 

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Simple Calculation Using Functions");
  do_a_calc(1, 2);
}

void loop() {
  // put your main code here, to run repeatedly:
}

int do_a_calc(int number_1, int number_2) {
  Serial.println(number_1 + number_2);
  return number_1 + number_2;
}

.............................
Always put your return keyword at the end of a function, and the return keyword and the result of the calculation would go back to a line, and we use a Serial.println() function to print things out, doing the modification of the function.

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Simple Calculation Using Functions");
  Serial.println(do_a_calc(1, 2));
}

void loop() {
  // put your main code here, to run repeatedly:
}

int do_a_calc(int number_1, int number_2) {
  return number_1 + number_2;
}

Now we have a return data type and I'm doing printing in the line where the calling of the function also takes place.

The next thing is what happens with a return datatype in the custom function. int means that a function may return something, whether it does or not really depends on the function.

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Simple Calculation Using Functions");
  do_a_calc(1, 2);
}

void loop() {
  // put your main code here, to run repeatedly:
}

int do_a_calc(int number_1, int number_2) {
  Serial.println(number_1 + number_2);
}

However, note that whatever code is below the return line will not be executed. You can't also return anything in a void type or return a  different type. 

Regardless of the place where the program gets its data from, it must store it in memory. To do that, we use variables. Instead of using a memory address, we use an easy-to-remember name like number_1 and number_2. Variables can hold booleans, char, byte, int, unsigned int, word, long, unsigned long, float, string - char, and array.  A char and boolean occupy 1 byte and a long represents 4 bytes.

Boolean holds "true" or "false" and char holds a number between  -128 to 127. The byte is from 0 to 255 and int holds from -32728 to 32727. Longs consume double the amount of space without any benefit from -2147483648 to 2146483647. Unsigned long comes from 0 to 4294967295. 

Floating point number include decimals but the Atmega CPU doesn't have the hardware for this from -3.4028235E38 to 3.4028235E38. string-char is a way to store multiple characters as an art of chars. array is a string object that offers more flexibility and can also be a structure that holds multiple data elements all of the same type.

Every variable is enumerated with the data type first, then the designator name. We want to be able to send values to the function and pass it in by value rather than parameters to the function. Instatiation is the operation where we allocate a value to the variable, and we can do instantiation of offering a value to a variable, and once you declare a variable, we can always assign/change the first value.

void setup() {
Serial.begin(9600);
Serial.println("Simple Calculation using functions");
int first_number = 5;
int second_number;
second_number = 6;
Serial.println(do_a_calc(first_number, second_number));
}

void loop() {

}

int do_a_calc(int number_1, int number_2) {
int result = number_1 + number_2;
return result;

This function returns the following: 

Simple Calculation using Functions

11


Now the next topic is the concept of the scope. A variable needs to be defined in a function, or within a scope that includes within that function. Putting something outside a function makes the variable automatically in the scope in the inner function, and in this function, the first_number is passed in the root function, which is just defined inside the sketch folder in the Arduino program. Try to use as many local variables as possible to pass into parameters, and try not to use too many global variables because it makes it harder to debug problems that arise from the incorrect use of variables because it can have an effect everywhere. Only declare a global variable if you have a good reason to do so. E.g.

int first_number = 5; 

void setup() {
  Serial.begin(9600);
  Serial.println("Simple Calculation using functions");
  int second_number;
  second_number = 6;
  Serial.println(do_a_calc(second_number));
}

void loop() {
  

}

int do_a_calc(int number_2) {
  first_number = 10;
  int result = first_number + number_2;
  return result;
}


results in this: 

Simple Calculation using functions
16
.

It's possible to assign a different value to a variable at any time. But what if a value must not change in the entire life cycle of a program? We would not want to change an LED when we connect it to a pin, so we have the concept of a constant to cater for situations like that. Let's say the first number represents a pin. What you can do is you can add the keyword "const" which stands for "constant" and we have changed the type of variable from a variable to a constant variable that doesn't change.  

The program operates in the same way if the const keyword is the only reference, but if the variable attempted to change, even verifying the program has the compiler complaining, saying the assignment of a read-only variable results in an error, because we try to assign a value to a variable that has been marked as constant. A constant can only recieve a value one time only when you instantiate a variable. 

The next thing that we want to talk about are loops and conditionals. 

int counter = 0;

void setup() {
  //setup the baud rate
  Serial.begin(9600);
}

void loop() {
  if(counter < 10) {
    Serial.print(counter);
    Serial.print(", ");
    Serial.println("Counter is smaller than 10");
  } else {
    Serial.print(counter);
    Serial.print(", ");
    Serial.println("Counter is not smaller than 10");
  }
      delay(500);
      counter++;
}

Conditionals are useful when you want to change the flow of execution in your steps. The simplest conditional out here is the if statement.   

Sometimes there's extra text in serial monitor. That's totally okay.  

Let's have a look at while next, a way to create a loop and send an example. This is pretty much self explanatory. There's a boolean condition in the while loop. Here's the input:

int counter = 0;

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

void loop() {
  while(counter < 10) {
    Serial.print(counter);
    Serial.print(", ");
    Serial.println("Counter is smaller than 10");
    delay(500);
    counter++;
  }
}

And the corresponding output: 

0, Count is smaller than 10 
1, Count is smaller than 10 
2, Count is smaller than 10 
3, Count is smaller than 10 
4, Count is smaller than 10 
5, Count is smaller than 10 
6, Count is smaller than 10 
7, Count is smaller than 10 
8, Count is smaller than 10 
9, Count is smaller than 10 

Now let's go over a for statement design.

For loops repeat blocks of code a specific number of times that we have predetermined so we know beforehand how many times we want to repeat a segment of code. 

Here's a for loop input:

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

void loop() {
  for(int counter = 0; counter < 20; counter++) {
    if(counter < 10) {
      Serial.print(counter);
      Serial.print(", ");
      Serial.println("Counter is smaller than 10"); 
    } else {
       Serial.print(counter);
       Serial.print(", ");
       Serial.println("Counter is not smaller than 10");
     }
  }
  delay(250);
}

and the corresponding output: 




remember command will repeat so loop() will keep going in a loop.

The next structure is the switch structure. Switch will jump to the particular part of a structure depending on the variable. This is useful when you have a lot of buttons and you want your gadget to do something different, depending on what button was pressed. The following says what will happen if integer 1 or integer 2 was pressed, or default if something else was pressed. 

Example code: 

int button_pressed = 1;

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

  switch(button_pressed) {
    case 1: 
      Serial.println("Button 1 pressed");
      break;
    case 2:
      Serial.println("Button 2 pressed");
      break;
    default: 
      Serial.println("I don't know which button was pressed");
      break;
  }
  
}

void loop() {
}

What was pressed depends on the external variable outside of the setup. You can go to the arduino reference sheet for more information. 

Now there are 2 types of pins in the Arduino : Digital and Analog Pins. Digital Pins read the state of devices like buttons, switches, transistors, or LEDs. Digital Pins have only 2 possible states. A button can be pressed/not pressed LED be lit/not lit. We can configure digital pin as an input and read the state of a pin if it is pressed (5V) and similarly with an LED. 

Here's how to connect the LED with the Arduino and control the state programmatically. The purpose of resistors is to protect LEDs from burning out.  Make sure the resistance is not too low. The Long pin of an LED is an Anode (+) and the short side of the LED is the Cathode (-) and this is the short side of the LED. Positive goes to one of Arduino's pins and the negative will go to ground. The amount of current with both devices will limit itself based on the resistance. Take the Jumper wire and connect the unconnected side into any one of the unconnected digital pins. Digital pin 8, then connect the other wire to the cathode of the LED and need to connect to one of the ground pins of the Uno. Let's make a blinking sketch now.

First, we want to configure the pin Mode (as the first thing). We need to tell the Arduino whether we will control an input or output pin. Every digital pin is set to be an input, unless you explicitly set the mode. The first parameter is the channel, and the second parameter is to configure the pin as an OUTPUT/INPUT. 

We want to control the State of Pin #8 and the instruction we use to do that is digital write, and the first parameter is the pin number and the second is the state of the pin either HIGH or LOW. We want to keep the value there for a small amount of time, so delay() allows us to insert a delay/pause in our sketch, then we can change it in the next instruction when we go to pin number 8 and now switch it off and keep that instruction for one more second by delaying. This helps to blink the LED on and off, switching it once a second.

Now, we want to connect a button to a digital pin to the arduino and to be able to read the button's state and depending on whether the button's pressed or not, display a message to the serial monitor. Here is the Schematic:




We want one end of the button connected to the power source and the other end connected to one of the digital pins.

The pin of the button is neither on or off and a microcontroller needs to be able to read a definite state/voltage and to rectify this, we use a super large resistor and connect that to ground. When the button is not pressed. The yellow jumper wire would convey the voltage to the pulldown resistor and since the pulldown resistor is connected to ground, the yellow jumper wire would convey a ground level. When the button is pressed the yellow wire would convey the voltage of the other wire not groud since the resistor is large enough to not allow much current to flow through it to go to ground. Most of the current will go to the digital pin number 2. 

Comments

Popular Posts