MODULE 2 - For - Programming - For - Iot - Boards
MODULE 2 - For - Programming - For - Iot - Boards
File Name
Tool Bar
Text Editor
Serial
Monitor
Connect
ed Board
and Port
Toolbar Button
• Upload
• The Upload button compiles and runs our code written on the screen. It further
uploads the code to the connected board. Before uploading the sketch, we
need to make sure that the correct board and ports are selected.
• Start Debugging
• It is used to debug the program.
• Verify
• The Verify button is used to check the compilation error of the sketch or the
written code.
• Serial Monitor
• The serial monitor button is present on the right corner of the toolbar. It opens
the serial monitor.
• Serial Plotter
• The serial Plotter is used to plot the graph on a Serial monitor.
5 Steps to program an Arduino
• Programs written in Arduino are known as sketches. A basic sketch
consists of 3 parts
a. Declaration of Variables
b. Initialization: It is written in the setup () function.
C. Control code: It is written in the loop () function.
• The sketch is saved with .ino extension. Any operations like verifying,
opening a sketch, saving a sketch can be done using the buttons on the
toolbar or using the tool menu.
• The sketch should be stored in the sketchbook directory.
• Choose the proper board from the tools menu and the serial port
numbers.
• Click on the upload button or chose upload from the tools menu. Thus
the code is uploaded by the bootloader onto the microcontroller.
Arduino Coding Basics
• Coding Screen: The coding
screen is divided into two
blocks.
• The setup is considered as
the preparation block,
• while the loop is
considered as the
execution block.
• The set of statements in the setup and loop blocks are enclosed with the
curly brackets. We can write multiple statements depending on the coding
requirements for a particular project.
For example:
void setup ( )
{
Coding statement 1;
Coding statement 2;
}
void loop ( )
{
Coding statement 1;
Coding statement 2;
}
• Setup:
• It contains an initial part of the code to be executed.
• The pin modes, libraries, variables, etc., are initialized in the setup section.
• It is executed only once during the uploading of the program and after reset
or power up of the Arduino board.
• Loop:
• The loop contains statements that are executed repeatedly.
• The section of code inside the curly brackets is repeated depending on the
value of variables.
Arduino Syntax
• The two functions that encapsulate the pieces of code in the Arduino program are
shown below:
• void setup ( )
• void loop ( )
• Functions:
• The setup and loop functions have void keywords hence these functions do not return any
value
• The multiple lines of code that a function encapsulates are written inside curly brackets.
• Every closing curly bracket ' } ' must match the opening curly bracket '{ ' in the code.
• We can also write our own functions.
• Spaces: Arduino ignores the white spaces and tabs in the coding statements.
• Semicolon: It is the statement terminator as in the C as well as C++
Program Flow
• Setup(): Acts as and entry point
• Here, the processor enters our code, and the
execution of the code begins.
• After the setup, the execution of the statement in
the loop begins.
• loop(): runs over and over again
Basic Arduino functions
• Time in Arduino: The time in Arduino programming is measured in a millisecond. Where,
1 sec = 1000 milliseconds.
• pinMode ( ): The specific pin number is set as the INPUT or OUTPUT in the pinMode ()
function. The Syntax is: pinMode (pin, mode) where:
• pin: It is the pin number. We can select the pin number according to the requirements.
• Mode: We can set the mode as INPUT or OUTPUT according to the corresponding pin number.
• pinMode (12, OUTPUT);
• digitalWrite( ): The digitalWrite ( ) function is used to set the value of a pin as HIGH or
LOW.
• The syntax is: digitalWrite( pin, value HIGH/LOW)
• digitalRead () function will read the HIGH/LOW value from the digital pin
• analogRead(pin): Reads and returns the analog value from that pin.
• analogWrite(pin, value): Writes the analog value to that pin.
• delay ( ): The delay () function is a blocking function to pause a program from doing a task
during the specified duration in milliseconds.
• serial.begin(bit-rate): Sets the beginning of serial communication by
setting the bit rate.
Functions
• Sometimes, we need to write our functions.
• Function return type: We need a return type for a function.
• For example, we can store the return value of a function in a variable.
• We can use any data type as a return type, such as float, char, etc.
• Function name: It consists of a name specified to the function. It
represents the real body of the function.
• Function parameter: It includes the parameters passed to the function.
• The parameters are defined as the special variables, which are used to pass
data to a function.
• The function must be followed by parentheses ( ) and the semicolon ;
• The actual data passed to the function is termed as an argument.
Example: Add two numbers
void setup()
{
Serial.begin(9600);
}
void loop() {
int a = 5; // initialization of values to the variables a and b
int b = 4;
int c;
c = myAddfunction(a, b); // c will now contains the value 9
Serial.println(c); // to print the resulted value
delay(1000); // time delay of 1 second or 1000 milliseconds
}
int myAddfunction(int i, int j)
{
int sum;
sum = i + j;
return sum;
}
Arduino Data Types byte
It is considered as an unsigned number of 8 bits or 1 byte,
which stores values from 0 to 255.
• The data types that we will use in The syntax is:
the Arduino are listed below: byte var = val;
where,
• void Data Type var is a variable and
• int Data Type val is the value assigned to the variable
For example: byte c=20;
• Char Data Type
• Float Data Type
word
• Double Data Type It is considered as an unsigned number of 16 bits or 2 bytes,
• Unsigned int Data Type which stores values from 0 to 65535.
The syntax is:
• short Data Type word var = val;
where,
• long Data Type var is a variable
• Unsigned long Data Type val is the value assigned to the variable
For example,
• byte data type word c = 2000;
• word data type
Arduino Variables
• Consider the example:
• int pin = 8;
• Here, the int data type is used to create a variable named pin that
stores the value 8. It also means that value 8 is initialized to the
variable pin.
• We can refer the declared variable further in our
program or code. //For example,
• For example, 1.int LEDpin = 7;
2.int pin1 = LEDpin;
• pinMode(pin, OUTPUT); 3.LEDpin = 13;
//The LEDpin now contains the value 13 instead of 7.
But, value of pin1 is still 7.
• Variables Scope: It means that in how many ways the variables can be
declared.
• The variables can be declared in two ways in Arduino, which are listed
below:
• Local variables
• Global variables
• Local Variables:
• The local variables are declared within the function.
• The variables have scope only within the function.
• Global Variables:
• The global variables can be accessed anywhere in the program.
• The global variable is declared outside the setup() and loop() functions.
//Local Variable //Global variable
• Go to sketch-> Library
Manager->search for DHT->
Install.
• R needs to tell T to stop transmitting for a while. This is where flow control comes in.
• Flow control provides extra signaling to inform the transmitter that it should stop
(pause) or start (resume) the transmission.
UART Messages
• In UART communication,
each data frame is
encapsulated by start and
stop bits.
• These bits serve a vital role in
establishing the boundaries
of data transmission and
ensuring synchronization
between the sender and
receiver.
UART Messages: Start Bit
• A single start bit is transmitted at the beginning of each UART frame.
• The primary purpose of the start bit is to indicate the start of the data
transmission and prepare the receiver for data reception.
• The start bit is always logic low (0) for UART communication.
UART Messages : Data Bits
• Data bits are a fundamental component of UART communication as
they carry the actual information to be transmitted.
• The number of data bits in a UART frame can vary, but a common and
widely used configuration is 8 bits.
UART Messages: Character Size
• The character size in UART communication is defined by the number of
data bits within a frame.
• It's essential to choose the appropriate character size to match the
requirements of the data being transmitted. Here are some common
character size configurations:
• 8-Bit: This is the most prevalent character size in UART communication. It allows for
the transmission of a byte of data, which can represent a wide range of values,
including ASCII characters, numerical values, and more.
• 7-Bit: In cases where data size needs to be smaller, 7-bit character size is utilized.
It's suitable for applications that require less data overhead.
• 6-Bit: For even more compact data representation, 6-bit character size can be used.
UART Messages: Data Integrity
• The accuracy of data transmission in UART communication relies on
the proper configuration of data bits.
• It's essential that both the transmitter and receiver agree on the
number of data bits and their encoding.
• If the configuration is incorrect, data can be corrupted.
• For example, if the transmitter sends data as 8-bit characters, but the
receiver is configured to expect 7-bit characters, data may be
misinterpreted, leading to errors in the received information.
UART Messages: Parity
• In addition to data bits, UART communication may include a parity bit
as part of the data frame for error checking.
• Parity can be set to "odd" or "even," and it ensures that the total
number of "1" in a data is either even or odd.
• If the number of "1" bits doesn’t match the expected parity, an error
is detected.
UART Messages: Stop Bits
• One or more stop bits are sent after the data bits within each UART
frame to indicate the end of data.
• The most common configuration is to use 1 stop bit, but in situations
where added reliability is required, 2 stop bits can be employed.
Serial USB To send data from a computer to an Arduino (from
the Serial Monitor), we can make use of the
Examples Serial.available() and Serial.read() functions. First,
• This example will send the string we check if there's any data available, and if so, we
Hello World! from an Arduino to read it and print it.
a computer, using the int incomingByte = 0; // for incoming serial data
Serial.println() function. Data will void setup() {
be sent every one second. Serial.begin(9600)
void setup(){ }
void loop() {
Serial.begin(9600); // send data only when you receive (or have) data:
} if (Serial.available() > 0) {
// read the incoming byte:
incomingByte = Serial.read();
void loop(){
// say what you got:
Serial.println("Hello world!"); Serial.print("I received: ");
delay(1000); Serial.println(incomingByte, DEC);
} } }
RX/TX Pin Examples
• To set it up, connect the TX with RX pins on both boards.
UART in Arduino: Serial Class
• With the Serial class, you can send / receive data to and from your computer over USB, or to a
device connected via the Arduino's RX/TX pins.
• When sending data over USB, we use Serial. This data can be viewed in the Serial Monitor in
the Arduino IDE.
• When sending data over RX/TX pins, we use Serial1.
• The Serial class has several methods with some of the essentials being:
• begin() - begins serial communication, with a specified baud rate (many examples use either 9600 or
115200).
• print() - prints the content to the Serial Monitor.
• println() - prints the content to the Serial Monitor and adds a new line.
• available() - checks if serial data is available (if you send a command from the Serial Monitor).
• read() - reads data from the serial port.
• write() - writes data to the serial port.
• For example, to initialize serial communication on both serial ports, we would write it as:
• Serial.begin(9600); //init communication over USB (opens the serial port on USB and sets data rate)
• Serial1.begin(9600); //communication over RX/TX pins (opens the serial port on UART and sets data rate)
Transmit / Receive Messages example: Send
messages (strings) back and forth between
String devices.
sendMessage; if (Serial.available() > 0) {
String receivedMessage; char inputChar = Serial.read();
void setup() { if (inputChar == '\n') {
Serial.begin(9600); // Initialize the Serial monitor for debugging Serial1.println(sendMessage); // Send the message through
Serial1 with a newline character
Serial1.begin(9600); // Initialize Serial1 for sending data
sendMessage = ""; // Reset the message
}
} else {
void loop() {
sendMessage += inputChar; // Append characters to the
while (Serial1.available() > 0) { message
char receivedChar = Serial1.read(); }
if (receivedChar == '\n') { }
Serial.println(receivedMessage); // Print the received message in }
the Serial monitor
receivedMessage = ""; // Reset the received message
} else {
receivedMessage += receivedChar; // Append characters to the
received message
}
}
• We start by declaring two String variables for our incoming and outgoing
messages.
• String sendMessage;
• String receivedMessage;
• Inside setup() we initialize both Serial and Serial1 with a baud rate of 9600,
establishing a connection with the computer and the other transmitting
Arduino board.
• Serial.begin(9600); - opens the serial port on USB and sets data rate
• Serial1.begin(9600); - opens the serial port on UART and sets data rate
• Reading Messages: If a new byte is received, meaning Serial1.available() is
larger than 0 we check the received message.
while (Serial1.available() > 0) {
...
}
• Send Messages: For sending messages we first check if there are any
characters available in the Serial input buffer. In other words we check
if there is any text written inside the serial monitor, in which case
Serial.available() > 0.
if (Serial.available() > 0) {
...
}
Advantages of UART Protocol
• It has less physical interfacing based on only two lines.
• Simple to configure data and data size.
• Speed is also configurable. In most cases, this baud rate is 9600 for
the UART protocol.
• Full duplex mode configuration is possible by using two wires so that
is the major advantage of UART.
• Error detection is possible
Disadvantages of UART Protocol
• UART is having serial communication, therefore, it has less speed.
• Start bit, stop bit, and the parity bit is other overhead.
• Since this is asynchronous communication so here there are many
things that we need to do in configuration, for instance, we should
configure both devices at the same speed because the clock signal is
absent.