0% found this document useful (0 votes)
29 views43 pages

Print Merged

The document discusses different control flow statements in C/C++ like if, if-else, if-else-if statements and provides examples of their syntax and usage. It also covers other statements like switch, while, do-while and for loops along with operators like arithmetic, comparison, boolean and compound operators. Examples are given to demonstrate how to use these control structures and operators to control program flow and perform operations.

Uploaded by

vvjain2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views43 pages

Print Merged

The document discusses different control flow statements in C/C++ like if, if-else, if-else-if statements and provides examples of their syntax and usage. It also covers other statements like switch, while, do-while and for loops along with operators like arithmetic, comparison, boolean and compound operators. Examples are given to demonstrate how to use these control structures and operators to control program flow and perform operations.

Uploaded by

vvjain2002
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

if Statement if Syntax

if (condition)
{
// do something here
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 20 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 21

if Statement Example if-else Statement


if (x > 120) {
digitalWrite(LEDpin1, HIGH);
digitalWrite(LEDpin2, HIGH);
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 22 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 23

if-else Syntax If-else Statements


if (condition) if (x > 120) {
{ digitalWrite(LEDpin1, HIGH);
// action A digitalWrite(LEDpin2, HIGH);
} } else {
else digitalWrite(LEDpin1, LOW);
{ digitalWrite(LEDpin2, LOW);
// action B }
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 24 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 25
if-else-if Syntax if-else-if Example
if (condition) { if (x > 120) {
do Something;} digitalWrite(LEDpin1, HIGH);
else if (condition2) { digitalWrite(LEDpin2, HIGH);
do Something Else;} } else if (x > 200) {
else { digitalWrite(LEDpin1, LOW);
do Another Thing;} digitalWrite(LEDpin2, HIGH);
} else {
digitalWrite(LEDpin1, LOW);
digitalWrite(LEDpin2, LOW);
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 26 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 27

Switch Syntax Switch Example


switch (var) { char grade = 'B';
case label: switch(grade)
// statements {
break; case 'A' :
case label: printf("Excellent!\n" );
// statements break;
break; case 'B' :
default: case 'C' :
// statements printf("Well done\n" );
break; break;
} …

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 28 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 29

Goto Syntax Goto Example


label: for(byte r = 0; r < 255; r++) {
if (analogRead(0) > 250) { goto bailout;}
goto label; }

bailout:

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 30 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 31
While Loop Statement While Loop Syntax
while(expression) {
// statement(s)
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 33 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 34

While Loops Examples Do While Loop Statement


int i = 10;
while ( i > 0 ) {
printf("Hello %d\n", i );
i = i - 1;
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 35 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 36

Do While Loops Syntax Do While Loops Examples


do do{
{ delay(50);
// statement block x = readSensors();
} while (test condition); } while (x < 100);

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 37 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 38
For Loop Statement For Loops Syntax
for (initialization; condition; increment) {
//statement(s);
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 39 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 40

For Loops Example Break


for (x = 0; x < 255; x ++) {
for (int i=0; i <= 255; i++){ analogWrite(PWMpin, x);
analogWrite(PWMpin, i); sens = analogRead(sensorPin);
delay(10); if (sens > threshold) {
} x = 0;
break;
}
delay(50);
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 41 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 42

Continue Arithmetic Operators


for (x = 0; x < 255; x ++) {
if (x > 40 && x < 120){ = (assignment operator)
continue; + (addition)
} - (subtraction)
* (multiplication)
analogWrite(PWMpin, x); / (division)
delay(50); % (modulo)
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 43 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 45
Comparison Operators Boolean Operators
&& (and)
== (equal to) || (or)
!= (not equal to) ! (not)
< (less than)
> (greater than)
<= (less than or equal to)
>= (greater than or equal to)

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 46 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 47

Compound Operators Function Example


++ (increment) int checkSensor()
-- (decrement)
+= (compound addition) {
-= (compound subtraction) if (analogRead(0) > 400) {
*= (compound multiplication) return 1;
/= (compound division) else{
%= (compound modulo) return 0;
&= (compound bitwise and) }
|= (compound bitwise or) }

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 48 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 50

Comment

Single line comment


// ….
Multiple lines comment
/*
…..
Preprocessor
*/

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 52 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 53
#define #include

#define Name value #include <Wire.h>


#define ledPin 3

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 54 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 55

Resistor Color Code Potentiometer

Variable Resistor

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 62 EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 64

Arduino Program Structure

Define variables here

Define INPUT/OUTPUT Pins here Sketch = Program =


Source Code

Create your main program here

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 68


PinMode Syntax

pinMode(pin, INPUT/OUTPUT)

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 70

Digital Output

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 71


digitalWrite
Syntax:
digitalWrite(pin, HIGH/LOW)

Eg
digitalWrite(9,HIGH)

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 72

delay
Pauses the program for the amount of
time (in miliseconds) specified as
parameter

Syntax
delay(ms)

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 73


Connection

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 74

Exercise: pinMode, digitalWrite


1. Write a sketch to turn on one LED
Use digital pin 12 and use digitalWrite

2. Write a sketch to blink one LED

3. Write a sketch to alternate blinking 2 LEDs

Time for Exercise: 10 mins

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 75


Turn on LED

// the setup function runs once when you


press reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an
output.
pinMode(12, OUTPUT);
}

// the loop function runs over and over again


forever
void loop() {
digitalWrite(12, HIGH); // turn the LED on
(HIGH is the voltage level)
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 76

Blink LED
// the setup function runs once when you press
reset or power the board
void setup() {
// initialize digital pin LED_BUILTIN as an
output.
pinMode(12, OUTPUT);
}

// the loop function runs over and over again


forever
void loop() {
digitalWrite(12, HIGH); // turn the LED on
(HIGH is the voltage level)
delay(1000); // wait for a second
digitalWrite(12, LOW); // turn the LED off by
making the voltage LOW
delay(1000); // wait for a second
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 77


Two LED: Hint on Connection

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 78

Analog Output

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 79


Pulse Width Modulation (PWM)
To create an analog signal, the microcontroller
use a technique called PWM. By varying the
pulse width or duty cycle, we can create an
analog voltage.

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 81

Analog Output
A few PINs on the Arduino Digital PINs allow to
modify the output to mimic analog signal

Pin 3, 5, 6, 9, 10, 11

They are indicated by a "~" besides the pin no.

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 82


Analog Write Pin

The analog write


pins are those pins
with ~ sign

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 83

analogWrite Syntax
Syntax
analogWrite(PIN, value)

Eg
analogWrite(9, 125)

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 84


Connection

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 85

LED analog value


void setup() {
// initialize digital pin LED_BUILTIN as an
output.
pinMode(9, OUTPUT);
}

// the loop function runs over and over again


forever
void loop() {
analogWrite(9, 0) ;
delay(1500); // wait for a second
analogWrite(9, 50) ;
delay(1500);
analogWrite(9, 150) ;
delay(1500);
analogWrite(9, 255);
delay(1500); // wait for a second
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 86


Exercise: analogWrite
1. Write a simple sketch to change the
brightness the LED light from low to high
repeatedly

2. Write a sketch to fade the LED brightness


from low to high, and high to low repeatedly.

Time: 10 mins

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 87

Analog Input

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 88


AnalogRead Syntax
Syntax
analogRead(PIN)

Eg
analogRead(A0)

• 10-bit analog to digital converter


• map input voltages between 0 and 5 volts into
integer values between 0 and 1023.
EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 89

Exercise: analogRead
Write a simple sketch to read the analog output
of a potentiometer and output to the serial
monitor

Time: 10 mins

A0
EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 90
Map
Syntax:
map(value, fromLow, fromHigh, toLow, toHigh)

Eg

int val = analogRead(0);


val = map(val, 0, 1023, 0, 255);
analogWrite(9, val);

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 91

Map

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 92


Map

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 93

Challenge 1: Digital Read/Write


Parts Needed:
● Arduino Uno
● Solderless breadboard
● 1 LED
● 1 220 resistor
● 1 10K resistor
● 1 pushbutton
● Wires

10KΩ
● Connect the circuit shown on
the left
● Write a sketch from bare
minimum to turn on the LED
Time: 15mins when the button is pressed

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 95


Challenge 2: Analog Read/Write
Parts Needed:
● Arduino Uno
● Solderless breadboard
● 1 LED
● 1 220 resistor
● 1 Potentiometer
● Wires

● Connect the circuit shown


on the left
● Code a sketch to vary the
brightness of the LED
using potentiometer.

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 96


Controlling of Servo Motors Servo Motor Control
BITS Pilani BITS Pilani

• We will use PWM control signals to control the servo motor.

• The frequency of the control signal should be 50Hz i.e. a pulse should
occur every 20ms.

• The width of pulse determines angular position of the servo. Servos


generally can rotate upto 180 degrees.

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani

5 6

Servo Commands Sketch to control servo


BITS Pilani BITS Pilani

Import Servo Library: #include <Servo.h> #include <Servo.h>


Create Servo Object: Servo myServo; Servo myservo;
Attach Servo Pin: myServo.attach(9);
void setup()
Set the angle: myServo.write(angle);
{
myservo.attach(9);
}
void loop()
{
myservo.write(95);
delay(2000);
myservo.write(150);
delay(2000);
}

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani
8 9

Challenge: Servo Hint to Challenge


BITS Pilani BITS Pilani

Use the potentiometer to control the angle of


the servo motor potVal = analogRead(potPin);
angle = map(potVal, 0, 1023, 0, 179);
myServo.write(angle);
delay(15);

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani

Steps for connecting Servo motor and potentiometer with Arduino Servo Motor
BITS Pilani BITS Pilani

1. The servo has a three pin female connector. The brown (or darkest pin) is
usually ground. Connect this to ground of Arduino.
Potentiometer

2. Connect the Red ( Power ) pin to 5V on the Arduino.

3. Connect the Yellow pin on the servo to Arduino’s digital pin 11.

4. Connect the servo Vout (Potentiometer) to the Arduino’s Analog Pin 0.

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani
Servo Motor
Potentiometer in Servo Motor Interfacing
BITS Pilani BITS Pilani

• The potentiometer is connected to the Arduino’s analog input pin.

• The PWM signal’s duty cycle is determined by the position of the


potentiometer. The PWM value, will be in the range of 0 to 1023. (10-bit
ADC on Arduino Uno).

• This value is mapped to an angular position between 0 and 180 degrees.

• Thus, the position of the potentiometer precisely controls the servo motor’s
rotation.

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani

Servo Motor Coding BITS Pilani

#include <Servo.h>
Servo myservo; // create servo object to control a servo
int potpin = 0; // analog pin used to connect the potentiometer
int val; // variable to read the value from the analog pin

void setup() {
myservo.attach11); // attaches the servo on pin11 to the servo object
}

void loop() {
val = analogRead(potpin);
// reads the value of the potentiometer (value between 0 and 1023)
val = map(val, 0, 1023, 0, 180);
// scale it to use it with the servo (value between 0 and 180)
myservo.write(val); // sets the servo position according to the scaled value
delay(15);
} EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani
EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 3

Trigger the start of pulse


digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 4


EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 5

PulseIn
Reads a pulse (either HIGH or LOW) on a pin. For
example, if value is HIGH, pulseIn() waits for the
pin to go HIGH.

Syntax:
pulseIn(pin, value)
pulseIn(pin, value, timeout)

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 6


Compute the distance

duration = pulseIn(echoPin, HIGH);


distance= duration*0.034/2;

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 7

EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 8


Sketch to compute distance
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);

// Reads the echoPin, returns the sound wave travel time in


microseconds
duration = pulseIn(echoPin, HIGH);

// Calculating the distance


distance= duration*0.034/2;

Ex: ultrasonics
EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 9

const int trigPin = 4; // defining the pins


const int echoPin = 2;
// defining variables
long duration;
int distance;
void setup() {
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
Serial.begin(9600); // Starts the serial communication
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in micros
econds
duration = pulseIn(echoPin, HIGH);
// Calculating the distance
distance= duration*0.034/2;
// Prints the distance on the Serial Monitor
Serial.print("Distance: ");
Serial.println(distance); EEE F411, IoT course, Dr. Vinay Chamola, BITS-Pilani 10
}
BIRLA INSTITUTE OF TECHNOLOGY AND SCIENCE, PILANI
EEE-F411: Internet of Things
Execute the codes provided in the examples below and see the results-
Lab 1: Serial Monitor
Example 1: Print what's sent in the serial monitor

void setup() {
Serial Communication Serial.begin(9600); //set up serial library baud rate to 9600
A serial bus consists of just two wires - the transmitter TX wire for sending data and receiver RX
wire for receiving data. }
void loop() {
if(Serial.available()) //if number of bytes (characters) available for reading from serial port
{
Serial.print(" I received: "); //print- I received
Serial.write(Serial.read()); //send what you read
}
}

Example 2: Serial Read

void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() == 0);
int val = Serial.read() -'0';
Serial Communication on Arduino/ NodeMCU - Serial Serial.println(val);
}
Monitor
Some basic functions: Example 3: In this example, we will learn how to send messages to a computer via a USB port.
● Serial.begin(baudrate) - This function is used to set the speed of transferring data at a
specific baud rate. Put this inside the setup function. Code:
● Serial.print() - This function converts the data in the ASCII text which is easily readable // serial_print
by human beings and prints it on the serial monitor.
● Serial.println() - This function works similarly to print() but in addition, it adds a new line int number;
● Serial.write() - Writes binary data to the serial port. This data is sent as a byte or series
of bytes; to send the characters representing the digits of a number use the print() void setup() {
function instead. number = 0;
● Serial.read() - This function is used to read incoming serial data (i.e. can read input data Serial.begin(9600); // Initialize serial communication at 9600 bits per second
from user) }
● Serial.available() - This function gets the number of bytes available for reading from the
serial port. We will usually use this inside an if statement to check whether we have data void loop() {
to read or not. For eg: if(Serial.available() > 0) { … }. number++;
Serial.print("Hello World! "); // Next print would happen on the same line
Serial.println(number % 10); // Next print would happen on a new line
#include <DHT.h>
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ThingSpeak.h>
#define DHTPIN D5
#define DHTTYPE DHT11
DHT dht(DHTPIN, DHTTYPE);
const char* ssid = "abcde"; //Enter your Wi-Fi hotspot ID
const char* password = "123456789"; //Enter your Wi-Fi hotspot password here
WiFiClient client;
unsigned long myChannelNumber = 12345; // Enter your channel ID
const char * myWriteAPIKey = "FALKDFJALDLAS"; //Paste your Write API here
uint8_t temperature, humidity;
void setup()
{
Serial.begin(115200);
dht.begin();
delay(10);
// Connect to WiFi network
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
// Print the IP address
Serial.println(WiFi.localIP());
ThingSpeak.begin(client);
}
void loop()
{
static boolean data_state = false;
temperature = dht.readTemperature();
humidity = dht.readHumidity();
Serial.print("Temperature Value is :");
Serial.print(temperature);
Serial.println("C");
Serial.print("Humidity Value is :");
Serial.print(humidity);
Serial.println("%");
// Write to ThingSpeak. There are up to 8 fields in a channel, allowing you to store
up to 8 different
// pieces of information in a channel. Here, we write to field 1.
if( data_state )
{
ThingSpeak.writeField(myChannelNumber, 1, temperature, myWriteAPIKey);
data_state = false;
}
else
{
ThingSpeak.writeField(myChannelNumber, 2, humidity, myWriteAPIKey);
data_state = true;
}
delay(30000); // ThingSpeak will only accept updates every 15 seconds.
}
Connections
• LED Pos -> Pin 11 (GPIO17)
• Led Neg -> Ground (Pin 6)

Code: Blinking LED


with GPIO
Code: Varying LED
Brightness with
PWM

Servo Motor
• A servo motor is a type of a DC motor that, upon
receiving a signal of certain frequency , can rotate
itself to any angle from 0- 180 degrees.

• Its 90 degree position is generally referred to as


neutral position because it can rotate equally from
that position.
Servo Motor Interfacing

• The servo motor has 3 pins :


1. Power Pin (5V)
2. Data Pin(3.3V)
3. Ground Pin
• The power Pin is connected to the 5V power
supply.
• The Data pin is interfaced with the GPIO pin of
the R-Pi.
• The Gnd pin of the servo motor is connected
with the Gnd pin of the R-Pi.
• The Data pin of the Servo motor is provided with
PWM modulated voltage to control the rotation
of the R-Pi.
PWM Calculation – Using Datasheet Information
• Rotational Range: 180°
• Pulse Cycle: ca. 20 ms
• Pulse Width: 500-2400 μs

• 500 μs = 0.5 ms = 2.5% of 20ms


• 2400 μs = 2.4 ms = 12% of 20ms

Code: Servo
Motor Control
Temperature • The DHT 11 is a temperature and a Humidity
and sensor that provides digital temperature and
humidity readings.
Humidity • Popular for use in remote weather stations, soil
monitors and home automation systems.
Sensor

Connections

RPI
1. Request Data

Response from DHT11


3. Data Reading

Identifying Data Bits


Installing a
DHT Library

Code:
Interfacing
DHT11 Sensor

You might also like