0% found this document useful (0 votes)
3 views9 pages

SPPU IoT Python Arduino Answers

The document provides an overview of control statements in Python, including if-else statements, while loops, for loops, and nested if-else structures, along with their syntax and examples. It also covers functions in the Arduino IDE such as Serial.begin(), pinMode(), Serial.println(), analogRead(), digitalWrite(), and analogWrite(), explaining their syntax and usage. Additionally, it describes the Arduino IDE's features, components, and working process, emphasizing its user-friendly interface for programming Arduino boards.

Uploaded by

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

SPPU IoT Python Arduino Answers

The document provides an overview of control statements in Python, including if-else statements, while loops, for loops, and nested if-else structures, along with their syntax and examples. It also covers functions in the Arduino IDE such as Serial.begin(), pinMode(), Serial.println(), analogRead(), digitalWrite(), and analogWrite(), explaining their syntax and usage. Additionally, it describes the Arduino IDE's features, components, and working process, emphasizing its user-friendly interface for programming Arduino boards.

Uploaded by

koynangp
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

SPPU – TE Electrical (2019 Course)

Internet of Things | Python & Arduino IDE – Question Answers


Reference: Savitribai Phule Pune University

Question 2: Control Statements in Python


Explain with syntax and example the following control statements in Python.

i) If-Else Statement
The if-else statement is a conditional control structure that executes one block of code if a condition
is true, and another block if the condition is false.
Syntax:
if condition: # block executed if condition is True else: # block
executed if condition is False

Example:
num = int(input('Enter a number: ')) if num % 2 == 0: print('The number is
Even') else: print('The number is Odd')
In the above example, the modulus operator checks whether the number is divisible by 2. If the
remainder is 0 it prints 'Even', otherwise 'Odd'.

ii) While Loop


The while loop repeatedly executes a block of code as long as the given condition remains True. It
is used when the number of iterations is not known in advance.
Syntax:
while condition: # body of the loop # update statement

Example:
i = 1 while i <= 5: print('Count:', i) i = i + 1 print('Loop ended')
Output: Prints Count: 1 through Count: 5. The loop terminates when i becomes 6 and the condition i
<= 5 becomes False.

iii) For Loop


The for loop is used to iterate over a sequence (such as a list, tuple, string, or range). It is used
when the number of iterations is known.
Syntax:
for variable in sequence: # body of the loop

Example:
fruits = ['Apple', 'Banana', 'Mango'] for fruit in fruits: print(fruit) #
Using range() for i in range(1, 6): print(i * i) # prints squares 1 to
25
The range(1, 6) generates numbers from 1 to 5 (excluding 6). The for loop iterates through each
value.

iv) Nested If-Else


Nested if-else refers to an if or if-else statement placed inside another if or else block. It is used
when multiple conditions need to be checked in a hierarchical manner.
Syntax:
if condition1: if condition2: # block A else: # block
B else: # block C

Example:
marks = int(input('Enter marks: ')) if marks >= 35: if marks >= 75:
print('Grade: Distinction') elif marks >= 60: print('Grade: First
Class') else: print('Grade: Pass') else: print('Result: Fail')
Here, the outer if checks if the student passes (marks >= 35). If true, the inner if-elif-else further
classifies the grade.
Question 4: Arduino IDE Functions
Explain with syntax and example the following functions from Arduino IDE.

i) [Link]()
[Link]() initializes serial communication at a specified baud rate. It must be called in the
setup() function before using any other Serial functions.
Syntax:
[Link](baud_rate);

Example:
void setup() { [Link](9600); // Initialize serial at 9600 bps }
void loop() { [Link]('Hello World'); delay(1000); }
Common baud rates: 9600, 115200. The baud rate of the Serial Monitor must match this value.

ii) pinMode()
pinMode() configures a specified digital pin to behave either as an INPUT or an OUTPUT. It is
called in the setup() function.
Syntax:
pinMode(pin_number, mode);
Where mode can be: INPUT, OUTPUT, or INPUT_PULLUP
Example:
int ledPin = 13; int btnPin = 2; void setup() { pinMode(ledPin, OUTPUT);
// Pin 13 as output pinMode(btnPin, INPUT); // Pin 2 as input }

iii) [Link]()
[Link]() prints data to the serial port followed by a newline character (\r\n). It is used to
display messages and variable values in the Serial Monitor.
Syntax:
[Link](data); [Link](data, format); // optional format: DEC,
HEX, BIN, OCT

Example:
int sensorVal = 512; void loop() { [Link]('Sensor Value:');
[Link](sensorVal); // prints 512 [Link](sensorVal,
HEX); // prints 200 delay(500); }

iv) analogRead()
analogRead() reads the value from the specified analog pin and returns an integer value between 0
and 1023 (10-bit ADC). It is used to read sensor data like temperature, light, etc.
Syntax:
int value = analogRead(analog_pin);

Example:
int sensorPin = A0; int sensorValue; void setup() { [Link](9600); }
void loop() { sensorValue = analogRead(sensorPin);
[Link]('Analog Value: '); [Link](sensorValue); // prints 0
to 1023 delay(500); }
v) digitalWrite()
digitalWrite() writes a HIGH (5V) or LOW (0V) value to a digital pin configured as OUTPUT. It is
used to control LEDs, relays, motors, etc.
Syntax:
digitalWrite(pin_number, value); // value = HIGH or LOW

Example:
int ledPin = 13; void setup() { pinMode(ledPin, OUTPUT); } void loop() {
digitalWrite(ledPin, HIGH); // Turn LED ON delay(1000);
digitalWrite(ledPin, LOW); // Turn LED OFF delay(1000); }

vi) analogWrite()
analogWrite() writes an analog (PWM) value to a pin. It generates a square wave with a duty cycle
proportional to the value (0-255), simulating an analog output. Used for dimming LEDs, controlling
motor speed, etc.
Syntax:
analogWrite(pin_number, value); // value: 0 (off) to 255 (fully on)

Example:
int ledPin = 9; // PWM pin (~) void setup() { pinMode(ledPin, OUTPUT); }
void loop() { for (int brightness = 0; brightness <= 255; brightness++) {
analogWrite(ledPin, brightness); // Gradually increase brightness
delay(10); } }
Note: analogWrite() only works on PWM-capable pins, marked with ~ on the Arduino board
(typically pins 3, 5, 6, 9, 10, 11 on Uno).
Question 8: Operators in Python Programming
List various types of operators used in Python programming and give examples of each.
An operator is a symbol that performs a specific operation on one or more operands. Python
supports the following types of operators:

1. Arithmetic Operators
Used to perform basic mathematical operations.
Operator Description Example Result
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division (float) 5/2 2.5
// Floor Division 5 // 2 2
% Modulus 5%2 1
** Exponentiation 2 ** 3 8

2. Relational (Comparison) Operators


Compare two values and return True or False.
Operator Description Example Result
== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5>3 True
< Less than 3<5 True
>= Greater or equal 5 >= 5 True
<= Less or equal 3 <= 5 True

3. Assignment Operators
Assign values to variables.
x = 10 # Simple assignment x += 5 # x = x + 5 => 15 x -= 3
# x = x - 3 => 12 x *= 2 # x = x * 2 => 24 x /= 4 # x = x / 4
=> 6.0 x **= 2 # x = x ** 2 => 36.0

4. Logical Operators
Used to combine conditional (Boolean) expressions.
Operator Description Example Result
and True if both true (5>3) and (4>2) True
or True if any true (5>3) or (1>10) True
not Inverts boolean not(5>3) False

5. Bitwise Operators
Operate on binary representations of integers.
a = 10 # Binary: 1010 b = 6 # Binary: 0110 print(a & b) # AND => 2
(0010) print(a | b) # OR => 14 (1110) print(a ^ b) # XOR => 12 (1100)
print(~a) # NOT => -11 print(a << 1) # Left Shift => 20 print(a >> 1)
# Right Shift => 5

6. Membership Operators
Test whether a value is a member of a sequence (list, string, tuple, etc.).
fruits = ['Apple', 'Banana', 'Mango'] print('Apple' in fruits) # True
print('Grape' not in fruits) # True name = 'Python' print('P' in name)
# True

7. Identity Operators
Compare the memory location (identity) of two objects.
a = [1, 2, 3] b = a c = [1, 2, 3] print(a is b) # True (same object)
print(a is c) # False (different objects, same value) print(a is not c)
# True
Question 11: Serial Monitor in Arduino IDE
What is a Serial Monitor in Arduino IDE? Explain any 4 functions in detail with respect to serial
monitor.

What is a Serial Monitor?


The Serial Monitor is a built-in tool in the Arduino IDE that allows communication between the
Arduino board and the computer via a serial (UART) connection over the USB cable. It is used for:
• Debugging sketches by printing variable values and messages
• Monitoring sensor outputs in real time
• Sending commands from the computer to the Arduino
• Displaying status and error information
The Serial Monitor is accessed via Tools > Serial Monitor or by pressing Ctrl+Shift+M. The baud
rate selected in the Serial Monitor must match the rate used in [Link]().

Serial Monitor Functions:


1. [Link](baud_rate)
Initializes serial communication. Must be called in setup() before using any other serial functions.
• baud_rate: Speed of communication in bits per second (bps)
• Common values: 9600, 19200, 57600, 115200
void setup() { [Link](9600); // Opens serial port at 9600 bps
[Link]('System Ready'); }

2. [Link]() and [Link]()


These functions display data on the Serial Monitor.
• [Link](data) – prints data without a newline
• [Link](data) – prints data followed by newline (\r\n)
• Optional second argument specifies format: DEC, HEX, BIN, OCT
int temperature = 28; void loop() { [Link]('Temperature: '); // No
newline [Link](temperature); // Prints 28 then newline
[Link](temperature, BIN); // Prints 11100 (binary) delay(1000); }

3. [Link]()
Reads the first available byte of incoming serial data. Returns -1 if no data is available.
• Used to receive commands or characters from the Serial Monitor input box
• Returns an integer (ASCII code) which can be cast to char
void loop() { if ([Link]() > 0) { char received = (char)
[Link](); [Link]('You sent: ');
[Link](received); } }

4. [Link]()
Returns the number of bytes available in the serial receive buffer. Used to check if data has been
received from the Serial Monitor before reading.
• Returns 0 if no data is waiting
• Returns count of bytes in the buffer otherwise
void loop() { if ([Link]() > 0) { // Check if data is
available int inByte = [Link](); // Read one byte
[Link]('Received: '); [Link](inByte); } }
Question 12: Arduino Integrated Development Environment (IDE)
Write a short note on Arduino Integrated Development Environment (IDE).

Introduction
The Arduino IDE (Integrated Development Environment) is an open-source software application
used to write, compile, and upload code to Arduino microcontroller boards. It provides a simple and
user-friendly environment for both beginners and advanced users working on embedded systems
and IoT applications.
The Arduino IDE is available for Windows, macOS, and Linux. The programs written in Arduino IDE
are called Sketches, which are saved with a .ino extension.

Features of Arduino IDE


• Free and open-source software developed by the Arduino community
• Supports multiple Arduino boards (Uno, Mega, Nano, Due, ESP8266, etc.)
• Cross-platform: available for Windows, macOS, and Linux
• Built-in library manager for adding external libraries
• Serial Monitor and Serial Plotter for debugging
• Auto-format and syntax highlighting for code
• Board Manager for installing board definitions

Components / Structure of Arduino IDE


1. Menu Bar
Contains File, Edit, Sketch, Tools, and Help menus providing access to all functions like
opening/saving files, compiling, uploading, preferences, and library management.
2. Toolbar
Contains quick-access buttons: Verify (compile), Upload, New, Open, Save, and Serial Monitor.
3. Code Editor
The main text area where the sketch (program) is written. It provides syntax highlighting, auto-
indentation, and auto-complete features to assist coding.
4. Structure of an Arduino Sketch
Every Arduino sketch consists of two mandatory functions:
void setup() { // Runs once at startup // Initialize pins, Serial,
libraries } void loop() { // Runs repeatedly (infinite loop) // Main
program logic goes here }

5. Console / Message Area


Displays compilation status messages, error messages, upload progress, and the size of the
compiled code.
6. Serial Monitor
A built-in tool for serial communication between the Arduino and the PC. Used for debugging,
printing sensor values, and sending commands to the board.
7. Board and Port Selection
Under Tools menu, the user selects the correct Arduino board (e.g., Arduino Uno) and the COM
port to which the board is connected.

Working of Arduino IDE


• Step 1: Write the sketch (program) in the code editor
• Step 2: Click Verify/Compile to check for syntax errors
• Step 3: Connect the Arduino board via USB
• Step 4: Select correct Board and Port from Tools menu
• Step 5: Click Upload to transfer compiled code to the board
• Step 6: Monitor output using Serial Monitor if required

Advantages of Arduino IDE


• Simple and beginner-friendly interface
• Supports C and C++ programming languages
• Large community support and abundant example code
• Easily integrates with sensors, modules, and IoT components
• Free to download and use

References
T1: Daniel Minoli, 'Building the Internet of Things with IPv6 and MIPv6', Willy Publications
R5: Michael Margolis, Arduino Cookbook, 2nd Edition, O'Reilly Media, 2011
R6: Alex Bradbury & Ben Everard, Learning Python with Raspberry Pi, John Wiley & Sons, 2014
R7: Charles Bell, Beginning Sensor Networks with Arduino and Raspberry Pi, Apress, 2014

— End of Answers —

You might also like