Published on

Workshop Day 2 Session 1

Table of Contents

Basic Components

This text will aim to give a basic introduction of the components that will be used in the workshop and to familiarise with their general uses.

  • Breadboard

    IR

    A breadboard is a construction base for prototyping of electronics. It is used to build and test circuits quickly before finalizing any circuit design. It has many holes into which circuit components like ICs and resistors can be inserted.

  • LED

    IR

    A Light Emitting Diode or LED is a semiconductor diode that produces light when a voltage is applied across it. It is primarily used for lighting purposes in electronics and automative industries.

  • Resistors

    IR

    A resistor is a passive two-terminal electrical component that implements electrical resistance as a circuit element.

  • Multimeter

    IR

    A Multimeter is a device that can measure multiple electrical properties. It is mostly used in debugging our circuits.

  • Arduino Uno

    Arduino is basically an open source electronics platform providing both software and hardware. Arduino Uno is perhaps the most widely used microcontroller developed by Arduino.

    On a personal note, the board is pretty robust and is easy to work around.

    Your board looks like this,

    IR
  • Arduino Cable

    IR

    This is a Cable For Arduino UNO/MEGA (USB A to B). You can use it to connect “Arduino Uno”, “Arduino Mega 2560″ or any board with the USB female A port of your computer.

  • LDRs

    IR

    A Light Dependent Resistor or LDR is basically a resistor whose resistance varies depending on the intensity of light falling on it. It can be used in building alarm clocks, burglar alarm circuits, etc. We would be using these to build a Light Follower robot in the workshop.

  • IR Module

    IR

    IR Sensors are crucial components for building the Line Follower robot. These sensors will be required to keep our bot on the path and is pretty much what will guide our bot.

  • BO Motors

    IR

    Bo motor (Battery Operated) lightweight DC geared motor which gives good torque and rpm at lower voltages. We will be using 2 BO motors for our purpose. These motors will be connected to the L293D motor driver which will help us control the direction of motion of the motor as well as the torque generated.

  • L293D Motor Driver

    IRIR

    A motor driver is an integrated circuit chip which is usually used to control motors in autonomous robots. Motor driver act as an interface between Arduino and the motors . L293D, the motor driver included in your kit, is one of the most popular motor drivers.

  • HC-SR04

    IR

    HC-SR04 is an Ultrasonic Sensor that is used for detecting the distance to an object. This sensor would be a key component in building the Obstacle Avoidance robot.

  • HC-05

    IR

    HC-05 is a bluetooth module that gives bluetooth properties to your robot. It enables you to wirelessly control your robot using your phone. This would be a key component in building the Bluetooth Controlled Bot.

  • Jumper Wires

    IR

    Jumper wires are simply wires that have connector pins at each end, allowing them to be used to connect two points to each other without soldering. Jumper wires are typically used with breadboards and other prototyping tools in order to make it easy to change a circuit as needed.

  • Chassis

    A chassis is basically the load bearing framework of an artificial object, say a car or in our case a robot. It provides structural support to our framework. Following are few pictures to give an idea what a chassis would look like -

    IR 

    IR

How to make connections on a Breadboard?

As mentioned before, a breadboard is a circuit board that is used to make temporary circuits. It is a device having electronics and test circuit designs. The electronic elements inside the electronic circuits can be interchanged by inserting the terminals and leads into holes and later connecting it with the help of appropriate wires.

The metal strips are laid out as shown below. Note that the top and bottom rows of holes are connected horizontally and split in the middle while the remaining holes are connected vertically.

IR

In the below image, you can see how all holes in the selected row and selected column are connected together. The set of connected holes can be called a node.

IR

To interconnect the selected row (node A) and column (node B) a cable going from any hole in the row to any hole in the column is needed:

IR

Now the selected column (node B) and row (node A) are interconnected:

IR

Thus, in a Breadboard

IR

You can refer to the following video for more information - Understanding How Breadboards Work

Basic LED - Breadboard connection

The below image shows how to make a simple LED - Breadboard connection.

IR

Explanation

Power connections:

  • The positive terminal of the 9V battery is connected to one of the horizontal rails on the breadboard, in this case the one marked with the + sign, through a Red wire.
  • Similarly, the negative terminal of the 9V battery is connected to the other horizontal rail on the breadboard, in this case the one marked with the - sign, through a Black wire.

LED connections:

  • The positive terminal of the LED, which is longer and bent, is connected to the positive rail (+) on the breadboard through a Red wire.
  • The negative terminal of the LED, which is shorter and straight, is connected to a resistor.

Resistor connections:

  • One end of the resistor is connected to the negative terminal of the LED.
  • The other end of the resistor is connected to the negative rail (-) on the breadboard through a Black wire.

You can take a look at the TinkerCAD Simulation here.

Using a Multimeter

What is a multimeter?

A multimeter is a device that can measure many electrical properties depending on its mode.

Connections of Multimeter

IR
  1. Knob:- This is used to select the functions and desired ranges as well as to turn ON/OFF the device.
  2. Display:- It is used to display the values it reads based on the functions it selected.
  3. “COM” Jack:- Use to plug in black connector for negative test lead.
  4. “V ΩmA” Jack:- Use to plug in red connector for positive test lead for all voltage, resistance, and current ( up to 200mA ) measurements.
  5. “10 A” Jack:- Use to plug in red connector for positive test lead for current ( between 200mA and 10A ) measurement. There is no fuse for the "10A" jack. To use safely, each measurement can not last for more than 10 seconds, and the interval between each measurement must be more than 15 minutes.

Function’s of Multimeter

IR

AC Voltage (V~)

  • There will be a region up-right to the knob marked with the above symbol.
  • It is used to measure AC voltages between 2 terminals.
  • The various options given in this specify the maximum AC voltage it is going to read.
  • Readings will be shown in V.

DC Voltage (V⎓)

  • There will be a region up-left to the knob marked with the above symbol.
  • It is used to measure DC voltages between 2 terminals.
  • The various options given in this specify the maximum DC voltage it is going to read.
  • If you select 2000m or 200m, the reading will be shown in mV. For other cases, it will show in V.

DC Current (A⎓)

  • There will be a region right to the knob marked with the above symbol.
  • It is used to measure DC currents across a circuit.
  • The various options given in this specify the maximum DC current it is going to read.
  • For measuring upto 10A, connect red connector in “10A” jack. For other than 10A, connect red to “V ΩmA” jack. If you select 2000μ, then the readings will be displayed in μA. If you have selected 20m or 200m, it will show reading in mA and if you have selected 10A, it will show in A.

Caution - Do not connect the multimeter directly with a voltage source in this mode. If you do so, you will end up blowing your multimeter.

Resistance (Ω)

  • There will be a region bottom-left to the knob marked with the above symbol.
  • It is used to measure resistance between 2 terminals.
  • The various options are used to select the maximum resistance.
  • If you select max resistance 2000k, 200k, 20k, it will show reading in kΩ. For the rest of the cases, readings will show in Ω.

Continuity (IR)

  • There will be a region bottom-left to the knob marked with the above symbol.
  • When you will touch 2 terminals to some point on a circuit, if there is continuity (if those points are directly connected to each other), it will make ‘beep’ sound.

OFF mode

  • Located at top of knob.
  • For switching off multimeter.

Microcontrollers

What is a microcontroller?

A microcontroller is a compact integrated circuit designed to govern a specific operation in an embedded system. A typical microcontroller includes a processor, memory, and input/output (I/O) peripherals on a single chip.

Also known as embedded controllers or microcontroller units (MCUs), they are found in a variety of devices, including automobiles, robotics, office equipment, medical devices, mobile wireless transceivers, vending machines, and home appliances. They are essentially simple miniature personal computers (PCs) with no complex front-end operating system, designed to operate small features of a bigger component (OS).

How do microcontrollers work?

A microcontroller is embedded inside a system and controls a single function. It accomplishes this by employing its core Processor to evaluate data received from its I/O peripherals. The microcontroller's temporary information is stored in its data memory, where the processor accesses it and decodes and applies the incoming data using instructions stored in its programme memory. It then communicates with its I/O peripherals and takes the required action.

Core Elements of a Microcontroller

The processor (CPU) A processor might be compared to the device's brain. It interprets and responds to a variety of commands that control the microcontroller's operation. This includes basic arithmetic, logic, and input/output (I/O) operations. It also performs data transfer operations that send commands to other embedded system components.

Memory The memory of a microcontroller is used to retain the data that the processor receives and to respond to commands that it has been programmed to carry out. There are two types of memory in a microcontroller:

Program memory is where the CPU keeps long-term information about the instructions it executes. Program memory is non-volatile memory, which means it may store data indefinitely without the need for a power source.

Data memory is needed to store temporary data while the instructions are being executed. Data memory is volatile, which means that the data it stores is only transient and is only kept if the device is powered up.

I/O peripherals The processor's input and output devices serve as its interface to the outside world. The input ports take in information and transfer it to the processor as binary data. The processor receives that data and sends the necessary instructions to output devices that execute tasks external to the microcontroller.

While the processor, memory, and I/O peripherals are the most important components of a microprocessor, other components are typically incorporated as well. Supporting components that interface with the memory and CPU are referred to as I/O peripherals. Peripherals are a broad category that includes a wide range of supporting components. Because they are the method via which the processor is applied, having some form of an I/O peripheral is essential to a microprocessor.

Examples of Microcontrollers

  • Most Arduino boards consist of an Atmel 8-bit AVR microcontroller (ATmega8, ATmega168, ATmega328, ATmega1280, or ATmega2560)
  • ARM is a family of microcontroller developed by makers like ST Microelectronics and Motorola.
IR

Fig 1.2: Arduino with ATmega328 Microcontroller

Introduction to Arduino

Arduino is an open-source electronics platform based on easy-to-use hardware and software. It consists of both a physical programmable circuit board (a microcontroller) and a piece of software, or IDE (Integrated Development Environment) that runs on your computer and allows you to write and upload computer code to the physical board.

Arduino boards are able to read inputs such as lights on a sensor, pressure on a button, etc., and turn them into desired outputs such as activating a motor or turning on an LED. The set of instructions required to perform such tasks are given to the Arduino board using the IDE.

Unlike most previous programmable circuit boards, the Arduino does not need a separate piece of hardware (called a programmer) to load new code onto the board - you can simply use a USB cable. Additionally, the Arduino IDE uses a simplified version of C++, making the programming easier.

Arduino manufactures a wide range of boards. These have different sizes, different microcontrollers, and different processing capabilities. The Uno is one of the most popular boards in the Arduino family and an excellent choice for beginners.

Main components

IR
  1. Power (USB): The Arduino UNO is connected to a power source via a USB cable that is terminated in a barrel jack. The USB connection is also used to load code onto your Arduino board. The recommended voltage for most Arduino models is between 6 and 12 Volts. A power supply greater than 20 Volts will damage the Arduino board.

  2. Pins: The pins on the Arduino board are where the connections are made in order to construct the required circuit (in conjunction with a breadboard and connecting wires). The Arduino has several kinds of pins, each of which is used for a different purpose.

    • 5V and 3.3V Pins: These pins are used for power supply to the Arduino. 5V or 3.3V is sufficient for most of the simple components used.
    • GND: These pins are used to 'ground' the circuit.
    • GPIO (General Purpose Input Output Pins): These are specific pins that are programmed to input/output signals.
  3. RX and TX LEDs: RX and TX stand for Receiving and Transmitting, and these LEDs are used to indicate Serial communication (like when we're loading a new program onto the board). The TX and RX LEDs blink whenever there is communication between the onboard microcontroller and the computer through the USB to serial converter chip present near the USB port. The lighting up of the LEDs indicates the direction of the flow of data. When a bit of data goes from the Arduino board to the computer, the TX LED glows. The RX LED glows when a bit of data goes from the computer to the Arduino board.

  4. Reset Switch: This functions as a reset button. Pushing it will temporarily connect the reset pin to ground and restart any code that is loaded on the Arduino. This can be very useful if your code doesn't repeat, but you want to test it multiple times.

  5. Main IC: This functions as the brain of the Arduino. The main IC on the Arduino is slightly different from board type to board type but is usually from the ATmega line of IC's from the ATMEL company. This can be important, as you may need to know the IC type (along with your board type) before loading up a new program from the Arduino software. This information can usually be found in writing on the top side of the IC.

  6. Voltage regulator: It is used to regulate the power supply to the Arduino board. The regulator still has limitations, and hence a supply greater than 20 Volts must not be used as it may damage the board.

Arduino Uno

Arduino Uno is a microcontroller board based on the ATmega328P. It has 14 digital input/output pins (of which 6 can be used as PWM outputs), 6 analog inputs, a USB connection, a power jack, an ICSP header, and a reset button. It contains everything needed to support the microcontroller; simply connect it to a computer with a USB cable to get started.

General Purpose Input Ouput Pins (GPIO)

IR

GPIO pins are programmed to input/output signals. These bridge the gap between programming and electronics. There are two types of GPIO pins:

  • Digital GPIO pins
  • Analog GPIO pins
IR

1. Digital Pins

The digital pins in the Arduino are labelled 0-13 (14 pins). These pins can be used for both digital input as well as digital output.

The pins on the Arduino that are marked with a tilde symbol (~) are known as PWM pins, and are used for analog output. On most Arduino boards (those with the ATmega168 or ATmega328), the PWM pins are 3, 5, 6, 9, 10, and 11 (6 pins). More information about PWM will be provided later.

Pin 13 of the Arduino Uno has a special function. It has an LED and a resistor attached to it. This makes it difficult to configure in the input modes.

Pins 0 and 1 (named RX and TX) are for serial connection and should not be used for other uses.

IR

In order to use the pins for digital input, the digitalRead() function is used. In order to use the pins for digital output, the digitalWrite() function is used.

NOTE - The digitalRead() and digitalWrite() functions will be explained later.

2. Analog Pins

The analog pins in the Arduino are labeled A0-A5 (6 pins). The Arduino has an analog-to-digital (A/D) converter. The converter has 10 bit resolution, returning integers from 0 to 1023. Hence the pins can read analog input voltages between 0 and the operating voltage (usually 5 V). This input is mapped to a value between 0 and 1023 appropriately using the analog to digital converter.

The analog pins are primarily used for analog input signals. But they can also be used like digital GPIO pins (HIGH or LOW input/output). Thus, pins marked as "ANALOG IN" on the board can work either as analog input (using the Analog to Digital Converter), digital input, or digital output.

IR

In order to use the pins for reading analog input signals, analogRead() function is used. NOTE - You will learn more about the analogRead() function in the further sessions.

NOTE - The analogWrite() function is reserved to PWM pins. A more detailed explanation of PWM pins, their function, and the analogWrite() function will be provided later.

Digital/AnalogPin NumberFunction used
Digital Input0-13, A0-A5digitalRead()
Digital Output0-13, A0-A5digitalWrite()
Analog InputA0-A5analogRead()
Analog Output3,5,6,9,10,11analogWrite()

Digital Vs Analog

By the time you are reading this, you would be having a fair idea of what an Arduino is, and what exactly are GPIO pins. On a brief note, Arduino is a microcontroller, while GPIO pins stand for General Purpose Input Output pins. These GPIO pins are further classified into Digital and Analog pins. Now let’s look into what these are and by the end of this document let’s try to make a small circuit using Arduino and a LED.

Before we look into Digital and Analog pins, let's see what are Digital and Analog Signals.

Signals

Signals, in electrical engineering, mean time-varying quantities, usually voltages. These signals are of two types, one is Digital Signal, other is Analog Signal.

Digital Signals

Digital signals refer to signals which are finite or discrete. Meaning different values passed by these signals are finite. For example, in Arduino the digital signals that can be passed are two, **5V5V and 0V0V**. They can be more than two too. But remember, Digital signals are never infinite.

IR

This is how a Digital Signal looks like.

Analog Signals

Unlike Digital signals, Analog Signals are infinite. Meaning it can take any number of values, but usually restricted in an continues interval. For example, in Arduino, the Analog signals sent can vary between 0V0V and 5V5V, both inclusive.

IR

This is how a Analog Signal looks like.

Getting Started With Arduino

You will be learning how to talk to your Arduino and interface it with other sensors to make it smarter.

The Sketch

Every individual program that is written for the Arduino is called as a "sketch", the most basic of all the sketches is the "blank sketch" its the first sketch you see when you open a new IDE page. Which kinda looks like this

void setup(){
    // Code written here will be only be executed once

}

void loop(){
    // Code written here will be run indefinitely

}


Go ahead and open your IDE, open a new sketch in case you have some other sketch pre-loaded.

Every (mostly) arduino sketch has two components and they are the void setup() and the void loop().

void setup() The setup() function is called when a sketch starts. Use it to initialise variables, pin modes, start using libraries, etc. The setup() function will only run once, after each power up or reset of the Arduino board.

In layman terms, the setup() part of the sketch contains code that needs to be only run once.

void loop() After creating a setup() function, which initialises and sets the initial values, the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. Use it to actively control the Arduino board.

In layman terms, the loop() part of the sketch contains code that is to be run indefinitely.

Now that you understand the basic layout of a sketch, lets start learning how to code.

Input/Output

Like the laptop/desktop through which your currently reading this walk-through can be connected to external devices like keyboards, mouse, printers, joysticks. The Arduino which is a microcontroller can also be connected to external input/output devices (input devices are usually called sensors) and just like devices for your laptop most of these sensors can be classified into two categories.

  1. Input
  2. Output

The names are self-explanatory but lets go through a few examples for better understanding.

CategoryLaptopArduino Uno
InputMouse, Keyboard, JoystickPush Button, Keypad, IR Sensor, Temp Sensor, LDR
OutputMonitor, PrinterMotors, LED, LCD Display

Just like your laptop has USB, HDMI and microUSB ports that can be used to connect external devices, the Arduino has a set of pins called the GPIOs (General Purpose Input/Output pins) that can be used to connect external devices to the Uno.

pinMode()

Now that you know what kinda external devices you will be working with its high time you also learn how to let your arduino know what device it is about to work with using pinMode().

pinMode() Configures the specified pin to behave either as an input or an output. See the description of digital pins for details on the functionality of the pins.

Example Sketch

void setup(){
    // The "8" refers to the digital pin 8 on the arduino board
    pinMode(8,INPUT); // for an INPUT device
    // The "9" refers to the digital pin 9 on the arduino board
    pinMode(9,OUTPUT); // for an OUTPUT device
}

void loop(){

}

Since the nature of a device (input/output) and the pin its connected to, doesn't change mid-program, its often sufficient to let the Arduino know about the devices its dealing with once at the start of the sketch, hence pinMode() is placed inside the void setup() and not inside the void loop().

The pin numbers for the Arduino board are mentioned on the board and can be used as it is inside the pinMode() function.

Talking Digital

Now that the Arduino has an heads up about the kind of device its dealing with its time we start talking with these devices.

Most of these devices while they can be Input/Output can be also classified as Digital/Analog.

Digital Devices Examples include push buttons/switches that can either be ON(Logic HIGH) or OFF(logic LOW), these devices have discrete set of states in which they can exist.

Analog Devices Examples include LED, Motors, LDR these devices have a continuous set of states in which they can exist. For example an LED can stay turned ON with different amounts of brightness and a motor can be rotating at different speeds based on the control voltage.

NOTE: Some devices can be both digital and analog based on how they are interfaced.

Microprocessors

What is a microprocessor?

A microprocessor is an integrated circuit (IC) that houses the central processing unit (CPU) of a computer . It is a clock-driven, register-based programmable multipurpose silicon device that accepts binary data as input and processes it according to instructions stored in the memory.

Why we need a Microprocessor?

A microprocessor, like our brain, can be trained to perform any task. Based on its instruction set and capabilities, it can be programmed to perform anything we desire. When we try to solve a problem without programming, the solution can be exceedingly complex.

When we try to solve a problem without programming, the solution can be exceedingly complex.

Assume you wish to construct a large structure. The use of BRICKS will simplify and reduce the cost of building. It will also allow you to design the building in whatever shape or size you like. The bricks that you can employ to solve your problem are instructions stored in a microprocessor. You can quickly solve difficult programmes by following those guidelines.

How does a Microprocessor work ?

A processor is the brain of a computer which basically consists of Arithmetical and Logical Unit (ALU), Control Unit and Register Array.

  • ALU performs all arithmetic and logical operations on the data received from input devices or memory.
  • Register array consists of a series of registers like accumulator (A), B, C, D etc. which acts as temporary fast access memory locations for processing data.
  • Control Unit controls the flow of instructions and data throughout the system.

So basically a microprocessor takes input from input devices, process it as per instructions given in the memory and produces output.

Advantages of Microprocessors

Low Cost Microprocessors are available at low cost due to integrated circuit technology which reduces the cost of a computer system.

High Speed Microprocessor chips can work at very high speed due to the technology involved in it. It is capable of executing millions of instructions per second.

Small Size Due to very large scale and ultra large scale integration technology, a microprocessor is fabricated in a very less footprint. This will reduce the size of the entire computer system.

Versatile Microprocessors are very versatile, the same chip can be used for a number of applications by simply changing the program (instructions stored in the memory).

Low Power Consumption Microprocessors are usually manufactured using metal oxide semiconductor technology, in which MOSFETs (Metal Oxide Semiconductor Field Effect Transistors) are working in saturation and cut off modes. So the power consumption is very low compared to others.

Less Heat Generation Compared to vacuum tube devices, semiconductor devices won’t emit that much heat.

Reliable Microprocessors are very reliable, failure rate is very less as semiconductor technology is used.

Portable Devices or computer system made with microprocessors can be made portable due to the small size and low power consumption.

Examples of Microprocessors

  • Intel 4004 – The First Microprocessor
  • Intel 8085
  • Intel 8086
  • Intel Pentium 4
  • Intel Core i7
  • AMD Athlon

Key differences between Microcontrollers & Microprocessors:

MicroConrollersMicroProcessors
StructureCPU, Memory, I/O port and all other devices are connected on the single chip. The structure is fixed. Once it is designed the user cannot change the peripheral devices.It has only the CPU in the chip. Other devices like I/O port, memory & timer are connected externally. The structure of the microprocessor is flexible. Users can decide the amount of memory, the number of I/O ports and other peripheral devices
ApplicationIt is used where the task is fixed & predefined. It is used in the washing machine, alarm, microwave oven etc.It is used where intensive processing is required. It is used in personal computers, laptops, mobiles, video games, etc.
ProgrammingThe program for the microcontroller is fixed once it is designed.The program for the microprocessor can be changed for different applications. The programming of the microprocessor is difficult compared to the microcontroller.
Clock SpeedThe clock speed of the microcontroller is less. It is in terms of the MHz. it ranges between 1 MHz to 300 MHz.The clock speed of the microprocessor is high. It is in terms of the GHz. It ranges between 1 GHz to 4 GHz.
Power ConsumptionThe power consumption for the microcontroller is less.The power consumption for the microprocessor is more.
Peripheral InterfaceThe common peripheral interface for the microcontroller is I2C, SPI, and UART.The common peripheral interface for the microprocessor is USB, UART, and high-speed Ethernet.
RAMThe volatile memory (RAM) for the microcontroller is in the range of 2 KB to 256 KB.The volatile memory (RAM) for the microprocessor is in the range of 512 MB to 32 GB.
ROMThe hard drive or flash memory (ROM) is in the range of 32 KB to 2 MB.The hard disk (ROM) for the microprocessor is in the range of 128 GB to 2 TB.
Bit SizeIt is available in 8-bit, 16-bit, and 36-bit.It is available in 32-Bit and 64-bit.
SizeThe overall size of the system is small.The overall size of the system is large.
ExampleArduino UNORaspberry Pi
CostThe cost of the microcontroller is low compared to the microprocessor.Comparatively expensive.

Here is a YouTube video you might refer to: Difference Between MicroController & Microprocessor. (use subtitles)

digitalWrite()

Since digital devices usually have only two known states either HIGH(ON) or LOW(OFF), we will be using the digitalWrite() function to either make a pin go HIGH or LOW, therefore turning ON or OFF the external device connected to the Arduino pin.

A pin in its HIGH state is set to 5 Volts, a pin in LOW state has 0 Volts.

NOTE: A pin has to be set to OUTPUT using pinMode() before you can do a digitalWrite() on it

Turning on an LED

void setup(){
    /* LED_BUILTIN is a special keyword for the inbuilt LED connected
    to digital pin 13 on the arduino, it is usually used for debugging */
    pinMode(LED_BUILTIN,OUTPUT); // Setting the LED as an OUTPUT device
}

void loop(){
    digitalWrite(LED_BUILTIN,HIGH); // Turning on the LED by sending it 5V
}

Compile and upload the above sketch, you should see a tiny orange LED near the digital pin 13 light up, congratulations on your first step towards getting to play with digital devices.

NOTE: Upload a new "blank sketch" after your done staring at the LED, if you don't want it to be turned ON forever. Alternatively you can change the HIGH to LOW in the above sketch and upload it as well.

Now that we know how to turn ON an LED, let us go one step further and make it blink (Turn ON and OFF periodically).

The most intuitive way of doing this would be to first turn ON the LED and then turn it OFF and do this in a loop forever, which when translated into code looks like this.

Blinking Attempt 1

void setup(){
    // Set the pin (D13) the LED is connected to as OUTPUT
    pinMode(LED_BUILTIN,OUTPUT);
}
void loop(){
    digitalWrite(LED_BUILTIN,HIGH); // Turn the LED ON
    digitalWrite(LED_BUILTIN,LOW); // Turn the LED OFF
}

Compile and upload the above sketch and try to look very closely at the LED you should see it flicker very slightly. Just kidding, don't strain your eyes too much. You won't be able to see it blink unless your Barry Allen. So to help normal mortals make sense and visualise digital signals that are usually super fast, humans have invented a few instruments (Logic Analyzers, Oscilloscope). I went ahead and connected a logic analyzer to see exactly what's happening to the LED in the above sketch.

IR

Lo and behold, the LED does blink but it stays on for a mere fraction of 3.375 microseconds and stays off for another 3.375 microseconds. Welcome to the world of an Arduino Uno, the ATmega328p thanks to the 16MHz external crystal runs at such incredible speeds due to which it appears like as if the LED has never been turned OFF.

Now that we know whats causing the problem its time we try to fix it.

Bitsian Standard Time - (BST)

Bitsian Lore While the whole of India follows the India Standard Time, we Bitsians unfortunately take pride in following the Bitsian Standard Time which basically is a time zone that runs anywhere from 10 to 40 minutes behind the IST. Most event timings during fests are not inclusive of BST due to which participants from other colleges often think the events are delayed, if only there were as lite as we are.

delay()

In great pride, lets meet the next function delay() which is like the Bitsian Standard Time equivalent in the world of Arduino, while it does cause delays it isn't as unpredictable as we bitsians are.

delay() Pauses the program for the amount of time (in milliseconds) specified as parameter. (There are 1000 milliseconds in a second.)

Lets use the delay() function to stall the arduino for a second after and before changing the state of the LED.

Blink Attempt 2

void setup(){
    pinMode(LED_BUILTIN,OUTPUT);
}
void loop(){
    digitalWrite(LED_BUILTIN,HIGH);//turn ON the LED
    delay(1000); // Do nothing for 1 second
    digitalWrite(LED_BUILTIN,LOW); // turn OFF the LED
    delay(1000); // Do nothing for 1 second
}

Compile and upload the above sketch and viola, you should now finally have an blinking LED.

The above code in a logic analyzer looks like the following

IR

As we can see the LED is on for almost a second, while not exact its close enough.

NOTE: Using delay() will cause your Arduino to sit idle for the specified amount of time without doing anything, which might be fine if our only intention is to blink an LED, but the use of delay should be avoided if we want the arduino to perform multiple tasks

Building your first Arduino Circuit : Blinking an LED

Now that you have gained a basic understanding of digital and analog pins, let's build a simple circuit using an Arduino. For this circuit, we will be using an Arduino, a LED, and a resistor. The circuit connection looks as below :

IR

The code of this circuit is :

void setup()
{
  pinMode(9, OUTPUT);//Declaring the mode of pin
}

void loop()
{
  digitalWrite(9, HIGH);//Providing 5V
  delay(1000); // Wait for 1000 millisecond(s)
  digitalWrite(9, LOW);//Providing 0V
  delay(1000); // Wait for 1000 millisecond(s)
}

By the above circuit connection and the usage of the above code, the LED will blink until the Arduino is given power.

There maybe a lot in the above code that you might not understand at present, but still try to copy the code and replicate the circuit and run the simulation. This will help you grasp the concepts better in the later sessions.

How Not To Blowup Your Laptop

The Arduino Uno has undergone many revisions, and hence the Arduino power supply circuit has evolved to an almost foolproof design. In this project, we will learn about the three different ways in which we can power up the Arduino Uno. While making any Arduino project, it is necessary to know these techniques, since there are instances when flexibility with regards to the power supply is required.

Modern Arduino Uno boards allow the board to have more than one source of power to be connected simultaneously. An intelligent switching circuitry ensures that the highest available voltage is selected and sent to the onboard voltage regulator, and eventually powers up the board.

Power Scheme 1

Using the USB Cable The USB port of the Arduino Uno can be connected to a desktop/laptop. If the computer recognizes the device, the current supplied to the board is 500mA at 5V. If the connection is not enumerated, 100mA is supplied at 5V.

IR

Power Scheme 2

Using an AC to DC adapter plugged into the barrel connector The barrel connector can be supplied with an input of 7-12V. This is regulated to 5V by the onboard voltage regulator, and the board is powered on.

IR

Power Scheme 3

Using Vin pin Connect a 9V battery with the positive terminal connected to the Vin pin and the negative terminal connected to the GND pin. The Vin port allows an input between 7 and 12 Volts, and the current should not exceed 500mA.

IR

NOTE - If the Vin / 5V and GND pins are being used to power up the Arduino, double-check the polarity because if the GND and 5V/Vin pins are mixed up, it can potentially damage the Arduino board.

TV Serial

Sometimes its really useful to see what's going on inside the brain of a microcontroller. Whilst there are many ways to send and receive information to and from a microcontroller and the computer, using the Serial port turns out to be the easiest. Serial communication is the process of sending one bit of data at a time, sequentially from one device to another. The main purpose of this serial communication is to transfer the sketch from computer to Arduino, to send information to computer etc. All Arduino boards have at least one serial port and it communicates on digital pins 0 (RX) and 1 (TX). The serial port is connected to the USB port on the board, and we can use the built-in Arduino Serial library to send data to the serial monitor in the Arduino IDE or to an external serial monitor.

Monitor

The Serial Monitor is basically a window in the Arduino IDE that allows you to send messages from your computer to an Arduino board (over USB) as well as receive messages from the Arduino.

Here's how you can access the Serial Monitor

  1. Open your Arduino IDE. Click on 'Tools' in the Menu bar, and select 'Serial Monitor'.
  2. Alternatively, you can use the hotkey Ctrl+Shift+M

This is how your Serial Monitor will typically look like

IR

begin()

The Serial.begin( ) function is a part of the serial object in the Arduino. It tells the serial object to perform initialization steps to send and receive data on the Rx and Tx (pins 1 and 0). It sets the baud rate for serial communication between your Arduino board and another device.

The most common reason to use serial.begin() is when you want to output some information from your Arduino to your computer screen. 99% of the time, you’ll be putting the Serial.begin() function inside of the setup() function. As you may know, setup() only runs once, and since you’ll only need to establish the Serial Communication one time – it makes sense to have it there.

Syntax: Serial.begin(speed)

speed: It signifies the baud rate. The default baud rate in Arduino is 9600. We can specify other baud rates as well, such as 4800, 14400, 38400, 28800, etc.

Probably the most important practical thing you need to know is that for serial communication to work, the baud rate in Serial.begin() and the baud rate set on the receiving device need to match. If you are using the Arduino IDE Serial Monitor window to read the information from your Arduino, then you can use the baud rate drop down to set the baud rate. But remember! If these two values don’t match – then anything you try to send over serial will not work right.

The Serial.print( ) function in Arduino prints data to the serial port. It allows you to send information from your Arduino to your computer, so that you can see the value displayed on your Serial Monitor.

Syntax: Serial.print(value, format)

value: It signifies the value to print, which includes any data type value.

format: It consists of number bases, such as OCT (Octal), BIN (Binary), HEX (Hexadecimal), etc. for the integral data types. It also specifies the number of decimal places.

You can read more about this function here.

If we wish to print the data in different lines, we can use the Serial.println() function. This function is basically the same as the Serial.print() function (except that it prints data in different lines) and has the same syntax.

Getting To Know Your Digital Companion

digitalRead()

digitalRead() function is used to read the logic state at a pin. It is capable of telling us whether the voltage at a pin is 5V or 0V, or in other words, if the pin is at logic state 1 (HIGH) or 0 (LOW).

NOTE: A pin has to be set to INPUT using pinMode() before you can do a digitalRead() on it.

Take a look at the following code to understand better

int ledPin = 13;  // LED connected to digital pin 13
int inPin = 7;    // pushbutton connected to digital pin 7
int val = 0;      // variable to store the read value

void setup() {
  pinMode(ledPin, OUTPUT);  // sets the digital pin 13 as output
  pinMode(inPin, INPUT);    // sets the digital pin 7 as input
}

void loop() {
  val = digitalRead(inPin);   // read the input pin
  digitalWrite(ledPin, val);  // sets the LED to the button's value
}

The IR Module

The IR sensor (or Infrared sensor) is an electronic device that senses objects around it by emitting light, which usually in the infrared spectrum. It is also capable of measuring the heat radiated by an object and can sense motion.

Working principle of IR Module

An IR sensor consists of two parts, the emitter circuit and the receiver circuit. This is collectively known as a photo-coupler or an optocoupler.

The emitter is an IR LED and the detector is an IR photodiode. The IR phototdiode is sensitive to the IR light emitted by an IR LED. The photo-diode’s resistance and output voltage change in proportion to the IR light received. This is the underlying working principle of the IR sensor. When the IR transmitter emits radiation, it reaches the object and some of the radiation reflects back to the IR receiver. Based on the intensity of the reception by the IR receiver, the output of the sensor is defined.

IR
Distinguishing Between Black and White Colors:

It is universal that black color absorbs the entire radiation incident on it and white color reflects the entire radiation incident on it. Based on this principle, the second positioning of the sensor couple can be made. The IR LED and the photodiode are placed side by side. When the IR transmitter emits infrared radiation, since there is no direct line of contact between the transmitter and receiver, the emitted radiation must reflect back to the photodiode after hitting any object. The surface of the object can be divided into two types: reflective surface and non-reflective surface. If the surface of the object is reflective in nature i.e. it is white or other light color, most of the radiation incident on it will get reflected back and reaches the photodiode. Depending on the intensity of the radiation reflected back, current flows in the photodiode.

If the surface of the object is non-reflective in nature i.e. it is black or other dark color, it absorbs almost all the radiation incident on it. As there is no reflected radiation, there is no radiation incident on the photodiode and the resistance of the photodiode remains higher allowing no current to flow. This situation is similar to there being no object at all.

The pictorial representation of the above scenarios is shown below

IR

Pins description

IR
Pin NameDescription
VCCPower Supply Input
GNDPower Supply Ground
OUTDigital Output

Interfacing with Arduino

We shall now take a look at how we can use the IR sensor with an Arduino Uno and better understand the digitalRead() function.

Connections:

  1. Connect VCC of IR sensor to the 5V pin of Arduino Uno
  2. Connect GND of IR sensor to the GND pin of Arduino Uno
  3. Connect OUT pin of IR sensor to any digital pin on the Uno board. In the demonstration, we will be connecting it to digital pin 6.

Code:

void setup()
{
  pinMode(13,OUTPUT); // pin 13 on Uno set as output
  pinMode(6,INPUT); // pin 6 on Uno set as input
}
void loop()
{
  if(digitalRead(6) == LOW) // if pin 6 reads low
  {
    digitalWrite(13,HIGH); // LED connected to digital pin 13 turns ON
    delay(10); // delay time
  }
  else  // if pin 6 reads high
  {
    digitalWrite(13,LOW); // LED connected to digital pin 13 turns OFF
    delay(10); // delay time
  }
}

The digitalRead() function is used to read the state of pin 6 and performs the desired function based on the state of this pin.

  • If digitalRead() reads LOW from the pin, pin 13 on the Uno is set to high, which turns ON the onboard LED.
  • If digitalRead() reads HIGH from the pin, pin 13 on the Uno is set to low, which turns OFF the onboard LED.

PWM

By now you must be fairly familiar with GPIO pins (Digital and Analog pins). Now let’s discuss about PWM and a special set of Digital pins, called PWM pins.

  • Pulse Width Modulation, or PWM, is a technique for getting analog results with digital means.
  • Digital control is used to create a square wave, a signal switched between on and off. This on-off pattern can simulate voltages in between the full Vcc of the board (e.g., 5 V on Uno, 3.3 V on a MKR board) and off (0 Volts) by changing the portion of the time the signal spends on versus the time that the signal spends off.
  • The duration of "on time" is called the pulse width. To get varying analog values, you change, or modulate, that pulse width.
  • If you repeat this on-off pattern fast enough with an LED for example, the result is as if the signal is a steady voltage between 0 and Vcc controlling the brightness of the LED.

Duty Cycle

When the Arduino sends a 5V5V signal we can call it “on time”. Now Duty Cycle is defined as the ratio of on time by total time :

Duty Cycle = tON/(tON+tOFF)

The Average voltage is :

Vaverage = 5V5V X Duty Cycle

Thus, Duty Cycle specifically describes the percentage of time a digital signal in ON (5V) over an interval or period of time.

IR

PWM Pins

PWM pins are special-purpose Digital pins that are capable of sending voltage signals between 0V0V and 5V5V too.

Let us consider a simple circuit consisting of an LED, a resistor, a pushbutton, and an Arduino. When the pushbutton is pressed, the LED turns ON because it receives a 5V voltage. When the pushbutton is released, the LED turns OFF because it does not receive any voltage as the circuit is broken, or in other words, it receives 0V. This is demonstrated below using an oscilloscope.

When pushbutton is pressed, 5V output

IR

When pushbutton is released, 0V output

IR

Now let's say you want to control the brightness of the LED instead of having a simple ON-OFF circuit. This can be achieved using the PWM pins on the Arduino, by varying the portion of time for which the signal stays ON (5V) versus the time for which the signal stays OFF (0V). This is demonstrated below using an oscilloscope.

IR

Where are they present on the Arduino?

Identifying a PWM pin is an easy task. There are 6 PWM pins in total in an Arduino (3,5,6,9,10,11). If we observe we can see that the above-mentioned pins are accompanied by a ‘~’ symbol. This is the indication saying that a particular pin is a PWM pin. See the picture below :

IR

Sending Analog Signals using PWM pins

For usage purposes, the PWM pins are of 8bit8-bit resolution is used. In this, voltages varying between 0V0Vto 5V5V are divided into 256 (28, hence 8bit8-bit resolution) parts, such that 0V0V is 00 and 5V5V is 255255. Using this we can send analog signals through PWM pins. As to how we do that will be covered in the upcoming topics.

For further clarity on PWM check out this video.

The Ancient Art of Analog

analogRead()

Description

analogRead() is an inbuilt function in the Arduino IDE which takes the name of the analog pin to be read as its parameter and reads the value of that specified analog pin. This is facilitated by a built in 10-bit ADC(Analog to Digital Convertor). The Analog pins on the Arduino UNO are shown in the diagram below.

IR

What is an ADC?

An ADC converts an analog signal picked up by the pin to a digital signal which can further be processed by the microcontroller. The input signals are stored electronically in binary within the ADC.The conversion is achieved by quantising the input signal into discrete values. The resolution of an ADC indicates the number of discrete values it can produce over the allowed range of analog input values. The Arduino UNO is equipped with a 10-bit analog to digital converter. This means that it will map input voltages between 0 and 5V into integer values between 0 and 1023. This yields a resolution between readings of: 5 volts / 1024 units or, 0.0049 volts (4.9 mV) per unit.

IRIR

Syntax

analogRead(analogPin)

Parameter: The name of the analog input pin to read from. The analog pins vary from board to board. In the case of the Arduino UNO it is from A0 to A5.

Return Value: It returns the analog reading of the pin

Code:

int analogPin = A2; // A2 chosen as analog pin
int val = 0; // variable initialized to store analog read

void setup(){
    pinMode(analogPin, INPUT);
    Serial.begin(9600);
}

void loop()
{
    val = analogRead(analogPin);
    Serial.println(val);
    delay(500);
}

Watch this video for a better understanding - Video

LDR - An analog sensor

A Light Dependent Resistor (a.k.a photoresistor or LDR) is a device whose resistivity varies with the incident electromagnetic radiation. Hence, they are light-sensitive devices. Also called photoconductors photoconductive cells or simply photocells. When the light of enough energy falls on it, the number of electrons available for the conduction increases proportional to the intensity of light

Follow these resources for a circuit diagram and a better understanding.

Video

Project using LDR, LED and Arduino

int ldr = A0; // Set A0 (analog input) for LDR
int value = 0;

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

void loop()
{
    value = analogRead(ldr); // Reads the value of LDR
    Serial.print("LDR Value is: "); // Prints the value of LDR to Serial Monitor
    Serial.println(value);

    if(value < 200)
    {
        digitalWrite(3, HIGH); // Makes the LED glow in dark
    }
    else
    {
        digitalWrite(3, LOW); // Turns the LED OFF in light
    }
}

analogWrite()

Description

analogRead is an inbuilt function in the Arduino IDE which takes the name of the analog pin to which an analog value has to be written as its parameter and a duty cycle which takes values between 0 and 255.

Parameters

  1. The Arduino pin to write to
  2. The Duty Cycle between 0 and 255

Return Value

There is no return value

Syntax

int ledPin = 9; // LED connected to digital pin 9
int analogPin = 3; // potentiometer connected to analog pin 3
int val = 0; // variable to store the read value

void setup(){
    pinMode(ledPin, OUTPUT); // sets the pin as output
}

void loop(){
    val = analogRead(analogPin); // read the input pin
    analogWrite(ledPin, val / 4); // analogRead values go from 0 to 1023, analogWrite values from 0 to 255
}

You can read more about this function here. Also, you can watch this video for a better understanding.

Dimming an LED using analogWrite()

int brightness = 0;

void setup(){
    pinMode(9, OUTPUT);
}

void loop()
{
    // increase brightness from 0 to 255
    for (brightness = 0; brightness <= 255; brightness += 5)
    {
        analogWrite(9, brightness);
        delay(30);
    }
    // decrease brightness from 255 to 0
    for (brightness = 255; brightness >= 0; brightness -= 5)
    {
        analogWrite(9, brightness);
        delay(30);
    }
}