0% found this document useful (0 votes)
6 views

IOT Lab

The document outlines various experiments conducted in an IoT lab using Raspberry Pi and Python programming. It includes a list of Linux commands, Python programs for basic arithmetic operations, string manipulation, and shape area calculations. Additionally, it details the implementation of hardware interactions like lighting LEDs and displaying information on an OLED screen.

Uploaded by

chirayumishra24
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)
6 views

IOT Lab

The document outlines various experiments conducted in an IoT lab using Raspberry Pi and Python programming. It includes a list of Linux commands, Python programs for basic arithmetic operations, string manipulation, and shape area calculations. Additionally, it details the implementation of hardware interactions like lighting LEDs and displaying information on an OLED screen.

Uploaded by

chirayumishra24
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/ 27

INSTITUTE OF ENGINEERING AND TECHNOLOGY

Mohanlal Sukhadia University, Udaipur


Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

INDEX

S.No. Topic Date Signature

1. Start Raspberry Pi and try various Linix commands in


command terminal window: ls, cd, touch, mv, rm,
man, mkdir, rmdir, tar, gzip, cat, more, less, ps, sudo,
cron, chown, chgrp, ping etc.
2. Run some python programs on Pi like:
a) Read your name and print Hello message with
name
b) Read two numbers and print their sum, difference,
product and division.
c) Word and character count of a given string.
d) Area of a given shape (rectangle, triangle and
circle) reading shape and appropriate values from
standard input.
3. Run some python programs on Pi like:
a) Print a name 'n' times, where name and n are read
from standard input, using for and while loops.
b) Handle Divided by Zero Exception.
c) Print current time for 10 times with an interval of
10 seconds.
d) Read a file line by line and print the word count of
each line
4. a) Light an LED through Python program
b) Get input from two switches and switch on
corresponding LEDs
c) Flash a RGB LED through python program.
5. a) A program to display Raspberry Pi logo, text, and a
simple timer animation on an SSD1306 OLED
display connected to a Raspberry Pi Pico.
b) A program to demonstrate the use of a 7-segment
display by implementing an ascending/descending
hexadecimal counter based on the state of an input
switch.
c) Create a calculator using Arduino microprocessor.
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

Experiment – 1

Aim : Start Raspberry Pi and try various Linix commands in command terminal
window: ls, cd, touch, mv, rm, man, mkdir, rmdir, tar, gzip, cat, more, less, ps, sudo,
cron, chown, chgrp, ping etc.

Linux Commands:

1. ls: It lists directory contents of files and directories.


• Display All Information About Files/Directories Using $ ls -l
• Open Last Edited File Using ls -t
• Display File Size in Human Readable Format Using ls –lh

2. cd: cd command in linux known as change directory command. It is used to change


current working directory.

Syntax:
• $ cd [directory]
• cd /: this command is used to change directory to the root directory
• cd dir_1/dir_2/dir_3: This command is used to move inside a directory
from a directory
• cd .. : this command is used to move to the parent directory of current
directory, or the directory one level up from the current directory.
• cd “dir name”: This command is used to navigate to a directory with
white spaces.

3. touch: Used to create, change and modify timestamps of a file. It is used to create a
file without any content.

Touch command Syntax to create a new file:

touch file_name

Touch command to create multiple files:

touch File1_name File2_name File3_name


INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

4. mv: mv stands for move. mv is used to move one or more files or directories from
one place to another in file system.
It has two distinct functions:
• It rename a file or folder.
• It moves group of files to different directory.
Syntax:
mv [Option] source destination

5. rm: rm stands for remove here. rm command is used to remove objects such as
files, directories, symbolic links and so on from the file system.
Syntax:
rm [OPTION]... FILE...

6. man: man command in Linux is used to display the user manual of any command
Syntax :
$man [OPTION]... [COMMAND NAME]...

7. mkdir: mkdir command in Linux allows the user to create directories


Syntax :
$man [OPTION]... [COMMAND NAME]...

8. rmdir: rmdir command in Linux allows the user to create directories


Syntax:
rmdir [-p] [-v | –verbose] [–ignore-fail-on-non-empty] directories …

9. tar: The Linux ‘tar’ stands for tape archive, is used to create Archive and extract
the Archive files.
Syntax:
tar [options] [archive-file] [file or directory to be archived]

10. gzip: gzip command compresses files.


Syntax :
gzip [Options] [filenames]

Example:
$ gzip mydoc.txt]
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

11. cat: It reads data from the file and gives their content as output. It helps us to
create, view, concatenate files.
Command:
$cat filename

12. more: more command is used to view the text files in the command prompt,
displaying one screen at a time in case the file is large (For example log files). The
more command also allows the user do scroll up and down through the page.
Syntax:
more [-options] [-num] [+/pattern] [+linenum] [file_name]
• [-options]: any option that you want to use in order to change the way the
file is displayed. Choose any one from the followings: (-d, -l, -f, -p, -c, -
s, -u)
• [-num]: type the number of lines that you want to display per screen. ∙
[+/pattern]: replace the pattern with any string that you want to find in the
text file.
• [+linenum]: use the line number from where you want to start displaying
the text content.
• [file_name]: name of the file containing the text that you want to display
on the screen.

13. Less: less command is linux utility which can be used to read contents of text file
one page (one screen) per time. It has faster access because if file is large, it don’t
access complete file, but access it page by page.
syntax :
less filename

14. ps: ps for viewing information related with the processes on a system which stands
as abbreviation for “Process Status”
Syntax –
ps [options]

15. sudo: sudo (Super User DO) command in Linux is generally used as a prefix of
some command that only superuser are allowed to run.

16. cron: automates the scheduled task at a predetermined time. It is a daemon


process, which runs as a background process.

Syntax:
cron [-f] [-l] [-L loglevel]
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

17. chown: chown command is used to change the file Owner or group. Whenever
you want to change ownership you can use chown command.
Syntax:
chown [OPTION]… [OWNER][: [GROUP]] FILE…
chown [OPTION]… –reference=RFILE FILE…

18. chgrp: chgrp command in Linux is used to change the group ownership of a file or
directory.
Syntax:
Chgrp [OPTION]… GROUP FILE…
chgrp [OPTION]… –reference=RFILE FILE…

19. ping: PING (Packet Internet Groper) command is used to check the network
connectivity between host and server/host.

20. chmod: the chmod command is used to change the access mode of a file.
The name is an abbreviation of change mode.
Syntax :
chmod [reference][operator][mode] file...

21. curl: curl is a command line tool to transfer data to or from a server, using any of
the supported protocols
Syntax:
curl [options] [URL...]

22. echo: echo command in linux is used to display line of text/string that are passed
as an argument .
Syntax :
echo [option] [string]

23. exit: exit command in linux is used to exit the shell where it is currently running. It
takes one more parameter as [N] and exits the shell with a return of status N.
Syntax:
exit [n]

24. find: It can be used to find files and directories and perform subsequent operations
on them. It supports searching by file, folder, name, creation date, modification date,
owner and permissions.
Syntax :
$ find [where to start searching from]
[expression determines what to find] [-options] [what to find]
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

25. Finger: command is a user information lookup command which gives details of
all the users logged in
Syntax:
$finger[username]

26. Free: command which displays the total amount of free space available along with
the amount of memory used and swap memory in the system, and also the buffers used
by the kernel.
Syntax:
$free [OPTION]

27. Grep: The grep filter searches a file for a particular pattern of characters, and
displays all lines that contain that pattern.
Syntax:
grep [options] pattern [files]

28. Kill: command in Linux (located in /bin/kill), is a built-in command which is used
to terminate processes manually. kill command sends a signal to a process which
terminates the process.
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

Experiment-2
Aim: Run some python programs on Pi:
2(a) Read your name and print Hello message with name

Python Program:
# modulos
from machine import Pin, I2C
from time import sleep
from pico_i2c_lcd import I2cLcd
i2c=I2C(0,sda=Pin(0), scl=Pin(1), freq=400000)
I2C_ADDR=i2c.scan()[0]
#crear objeto tipo lcd
lcd=I2cLcd(i2c,I2C_ADDR,2,16)
#LOOP
while True:
name = input('Enter Your Name:')
#print ('Hello %s.' % name)
lcd.putstr("Hello "+name)
sleep(5)
lcd.clear()

Output:
Enter Your Name: Reeya
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

2(b) Read two numbers and print their sum, difference, product and division.

Python Program:

import time
time.sleep(0.1) # Wait for USB to become ready

num1 = int(input("Enter First Number: "))


num2 = int(input("Enter Second Number: "))
print("Enter which operation would you like to perform?")
ch = input("Enter any of these char for specific operation +,-,*,/: ")
result = 0
if ch == '+':
result = num1 + num2
elif ch == '-':
result = num1 - num2
elif ch == '*':
result = num1 * num2
elif ch == '/':
result = num1 / num2
else:
print("Input character is not recognized!")
print(num1, ch , num2, ":", result)

Output:
Enter First Number: 5
Enter Second Number: 10
Enter which operation would you like to perform?
Enter any of these char for specific operation +,-,*,/: +
5 + 10 : 15
MicroPython v1.22.0 on 2023-12-27; Raspberry Pi Pico with RP2040
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

2(c) Word and character count of a given string.

Python Program:

import time
time.sleep(0.1) # Wait for USB to become ready

word_count = 0
char_count = 0
usr_input = input("Enter a string : ")
split_string = usr_input.split()
word_count = len(split_string)
for word in split_string:
char_count += len(word)
print("Total words : {}".format(word_count))
print("Total characters : {}".format(char_count))

Output:
Enter a string : Hello World!
Total words : 2
Total characters : 11
MicroPython v1.22.0 on 2023-12-27; Raspberry Pi Pico with RP2040
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

2(d) Area of a given shape (rectangle, triangle and circle) reading shape and
appropriate values from standard input.

Python Program (Rectangle):

import time
time.sleep(0.1) # Wait for USB to become ready

print("Rectangle!")
width = float(input('Please Enter the Width of a Rectangle: '))
height = float(input('Please Enter the Height of a Rectangle: '))
Area = width * height
Perimeter = 2 * (width + height)
print("\n Area of a Rectangle is: %.2f" %Area)
print(" Perimeter of Rectangle is: %.2f\n" %Perimeter)

Output:
Rectangle!
Please Enter the Width of a Rectangle: 10
Please Enter the Height of a Rectangle: 20

Area of a Rectangle is: 200.00


Perimeter of Rectangle is: 60.00

MicroPython v1.22.0 on 2023-12-27; Raspberry Pi Pico with RP2040

Python Program (Triangle):

import time
time.sleep(0.5) # Wait for USB to become ready

print("Triangle!")
x = float(input('Enter first side: '))
y = float(input('Enter second side: '))
z = float(input('Enter third side: '))
s = (x + y + z) / 2
area = (s*(s-x)*(s-y)*(s-z)) ** 0.5
print('The area of the triangle is %0.2f' %area)
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

Output:

Triangle!
Enter first side: 3
Enter second side: 4
Enter third side: 5
The area of the triangle is 6.00
MicroPython v1.22.0 on 2023-12-27; Raspberry Pi Pico with RP2040

Python Program (Circle):

import time
time.sleep(0.1) # Wait for USB to become ready

print("Circle!")
PI = 3.14
radius = float(input('Please Enter the radius of a circle: '))
diameter = 2 * radius
circumference = 2 * PI * radius
areac = PI * radius * radius
print("Diameter of a Circle = %.2f" %diameter)
print("Circumference of a Circle = %.2f" %circumference)
print("Area of a Circle = %.2f" %areac)

Output:

Circle!
Please Enter the radius of a circle: 10
Diameter of a Circle = 20.00
Circumference of a Circle = 62.80
Area of a Circle = 314.00
MicroPython v1.22.0 on 2023-12-27; Raspberry Pi Pico with RP2040
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

Combined Python Program:


import time
time.sleep(0.1) # Wait for USB to become ready

#Area
print("Select one of the following:")
print("1. Rectangle\n2. Triangle\n3. Circle")
s=input("Enter your choice: ")
if s=='1':
x=int(input("Enter length:"))
y=int(input("Enter breadth:"))
print("Area={}".format(x*y))
elif s=='2':
x=int(input("Enter base:"))
y=int(input("Enter height:"))
print("Area={}".format(0.5*x*y))
elif s=='3':
x=int(input("Enter radius:"))
print("Area={}".format(3.14*x*x))
else:
print("Enter a valid choice")

Output:
Select one of the following:
1. Rectangle
2. Triangle
3. Circle
Enter your choice: 1
Enter length:5
Enter breadth:2
Area=10
MicroPython v1.22.0 on 2023-12-27; Raspberry Pi Pico with RP2040
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

Experiment-3
Aim: Run some python programs on Pi:
3(a) Print a name 'n' times, where name and n are read from standard input,
using for and while loops.

Python Program(for):

import time
time.sleep(0.1) # Wait for USB to become ready

i=1
name=input("enter the name")
num=int(input ("enter the no of time" ))
#print (type(num))
for i in range(1,num+1):
print (i , name)
i=i+1

Output:
Enter the name: Reeya
Enter the no of time: 5
1 Reeya
2 Reeya
3 Reeya
4 Reeya
5 Reeya
MicroPython v1.22.0 on 2023-12-27; Raspberry Pi Pico with RP2040

Python Program(while):

import time
time.sleep(0.1) # Wait for USB to become ready

name=input("Enter the name: ")


num=int(input ("Enter the no of time: " ))
num=int(num)
i=1
while(i!=num):
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

print(name)
i=i+1

Output:

Enter the name: Reeya


Enter the no of time: 5
Reeya
Reeya
Reeya
Reeya
Reeya
MicroPython v1.22.0 on 2023-12-27; Raspberry Pi Pico with RP2040
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

3(b) Handle Divided by Zero Exception.

Python Program:

import time
time.sleep(0.1) # Wait for USB to become ready

print ("Enter two no N1 and N2")


n1 = int(input("Enter N1:"))
n2 = int(input("Enter N2:"))
try:
div=n1/n2
print (div)
except ZeroDivisionError:
print ("zero division is handled")
print ("out of try catch block ")

Output:

Enter two no N1 and N2


Enter N1:2
Enter N2:6
0.3333333
out of try catch block
MicroPython v1.22.0 on 2023-12-27; Raspberry Pi Pico with RP2040
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

3(c) Print current time for 10 times with an interval of 10 seconds.

Python Program:

import time
time.sleep(0.1) # Wait for USB to become ready

print("Hello, Pi Pico!")
for i in range(1,11):
zz=time.asctime(time.localtime(time.time()))
zz=zz[11:19]
print (zz)
print (time.asctime(time.localtime(time.time())))
time.sleep(10)

Output:

Hello, Pi Pico!
16:45:22
Tue Jan 14 16:45:22 2025
16:45:32
Tue Jan 14 16:45:32 2025
16:45:42
Tue Jan 14 16:45:42 2025
16:45:52
Tue Jan 14 16:45:52 2025
16:46:02
Tue Jan 14 16:46:02 2025
16:46:12
Tue Jan 14 16:46:12 2025
16:46:22
Tue Jan 14 16:46:22 2025
16:46:32
Tue Jan 14 16:46:32 2025
16:46:42
Tue Jan 14 16:46:42 2025
16:46:52
Tue Jan 14 16:46:52 2025
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

3(d) Read a file line by line and print the word count of each line

Python Program:

import time
time.sleep(0.1) # Wait for USB to become ready

print("Hello, Pi Pico!")
file=open("eee.txt","r")
line=1
for i in file:
print ("print the line no=" , line , "and line is =" , i)
z=i.split()
print ("no of word in line =" , line ,"is = " , len(z))
line = line+1

eee.txt:

Hello!
My name is Reeya

Output:

Hello, Pi Pico!
print the line no= 1 and line is = Hello!

no of word in line = 1 is = 1
print the line no= 2 and line is = My name is Reeya
no of word in line = 2 is = 4
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

Experiment-4
4(a) Light an LED through Python program

Python Program :

from machine import Pin


from time import sleep

led = Pin(5,Pin.OUT)

while True:
led.toggle()
sleep(0,5)
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

4(b) Get input from two switches and switch on corresponding LEDs

Python Program :

from machine import Pin


from time import sleep

led = Pin(28,Pin.OUT)
BUTTON=Pin(15,Pin.IN,Pin.PULL_DOWN)
led2 = Pin(21,Pin.OUT)
BUTTON2=Pin(14,Pin.IN,Pin.PULL_DOWN)
buttonState = 0
buttonState2 = 0 #contador de 0 a 1

while True:
if BUTTON.value()==1 :
buttonState = 1-buttonState
sleep(0.03)
if buttonState==1:
led.on()
else:
led.off()
elif BUTTON2.value()==1 :
buttonState2 = 1-buttonState2
sleep(0.03)
if buttonState2==1:
led2.on()
else:
led2.off()
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

4(c) Flash a RGB LED through python program.

Python Program :

from machine import Pin


import utime

red = Pin(16, Pin.OUT)


green = Pin(18, Pin.OUT)
blue = Pin(20, Pin.OUT)

while True:
red.value(0)
green.value(1)
blue.value(1)
utime.sleep(1)
red.value(1)
green.value(0)
blue.value(1)
utime.sleep(1)
red.value(1)
green.value(1)
blue.value(0)
utime.sleep(1)
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

Experiment-5
5(a) A program to display Raspberry Pi logo, text, and a simple timer animation
on an SSD1306 OLED display connected to a Raspberry Pi Pico.

Python Program :

from machine import Pin, I2C


from ssd1306 import SSD1306_I2C
import framebuf, sys
import utime
pix_res_x = 128
pix_res_y = 64
def init_i2c(scl_pin, sda_pin):
# Initialize I2C device
i2c_dev = I2C(1, scl=Pin(scl_pin), sda=Pin(sda_pin), freq=200000)
i2c_addr = [hex(ii) for ii in i2c_dev.scan()]
if not i2c_addr:
print('No I2C Display Found')
sys.exit()
else:
print("I2C Address : {}".format(i2c_addr[0]))
print("I2C Configuration: {}".format(i2c_dev))
return i2c_dev
def display_logo(oled):
# Display the Raspberry Pi logo on the OLED
buffer =
bytearray(b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00|?\x00\x01\x86
@\x80\x01\x01\x80\x80\x01\x11\x88\x80\x01\x05\xa0\x80\x00\x83\xc1\x00\x00C\xe
3\x00\x00~\xfc\x00\x00L'\x00\x00\x9c\x11\x00\x00\xbf\xfd\x00\x00\xe1\x87\x00\x0
1\xc1\x83\x80\x02A\x82@\x02A\x82@\x02\xc1\xc2@\x02\xf6>\xc0\x01\xfc=\x80\x
01\x18\x18\x80\x01\x88\x10\x80\x00\x8c!\x00\x00\x87\xf1\x00\x00\x7f\xf6\x00\x00
8\x1c\x00\x00\x0c
\x00\x00\x03\xc0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00")
fb = framebuf.FrameBuffer(buffer, 32, 32, framebuf.MONO_HLSB)
oled.fill(0)
oled.blit(fb, 96, 0)
oled.show()
def display_text(oled):
# Display text on the OLED
oled.text("Raspberry Pi", 5, 5)
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

oled.text("Pico", 5, 15)
oled.show()
def display_anima(oled):
# Display a simple timer animation on the OLED
start_time = utime.ticks_ms()

while True:
elapsed_time = (utime.ticks_diff(utime.ticks_ms(), start_time) // 1000) + 1

# Clear the specific line by drawing a filled black rectangle


oled.fill_rect(5, 40, oled.width - 5, 8, 0)

oled.text("Timer:", 5, 30)
oled.text(str(elapsed_time) + " sec", 5, 40)
oled.show()
utime.sleep_ms(1000)
def main():
i2c_dev = init_i2c(scl_pin=27, sda_pin=26)
oled = SSD1306_I2C(pix_res_x, pix_res_y, i2c_dev)
display_logo(oled)
display_text(oled)
display_anima(oled)

if __name__ == '__main__':
main()
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

5(b) A program to demonstrate the use of a 7-segment display by implementing


an ascending/descending hexadecimal counter based on the state of an input
switch.

Python Program :

from machine import Pin


from utime import sleep

pins = [
Pin(2, Pin.OUT), #A
Pin(3, Pin.OUT), #B
Pin(4, Pin.OUT), #C
Pin(5, Pin.OUT), #D
Pin(6, Pin.OUT), #E
Pin(8, Pin.OUT), #F
Pin(7, Pin.OUT), #G
Pin(0, Pin.OUT) # DP (not connected)
]

# Common anode 7-segment display digit patterns


digits = [
[0, 0, 0, 0, 0, 0, 1, 1], # 0
[1, 0, 0, 1, 1, 1, 1, 1], # 1
[0, 0, 1, 0, 0, 1, 0, 1], # 2
[0, 0, 0, 0, 1, 1, 0, 1], # 3
[1, 0, 0, 1, 1, 0, 0, 1], # 4
[0, 1, 0, 0, 1, 0, 0, 1], # 5
[0, 1, 0, 0, 0, 0, 0, 1], # 6
[0, 0, 0, 1, 1, 1, 1, 1], # 7
[0, 0, 0, 0, 0, 0, 0, 1], # 8
[0, 0, 0, 0, 1, 0, 0, 1], # 9
[0, 0, 0, 1, 0, 0, 0, 1], # a
[1, 1, 0, 0, 0, 0, 0, 1], # b
[0, 1, 1, 0, 0, 0, 1, 1], # C
[1, 0, 0, 0, 0, 1, 0, 1], # d
[0, 1, 1, 0, 0, 0, 0, 1], # E
[0, 1, 1, 1, 0, 0, 0, 1], # F
]

def reset():
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

"""Turns off all segments on the 7-segment display."""


for pin in pins:
pin.value(1)

reset()

switch = Pin(13, Pin.IN)

while True:
if switch.value() == 1:
# Ascending counter
for i in range(len(digits)):
if switch.value() == 0:
break
for j in range(len(pins) - 1):
pins[j].value(digits[i][j])
sleep(0.5)
else:
# Descending counter
for i in range(len(digits) - 1, -1, -1):
if switch.value() == 1:
break
for j in range(len(pins)):
pins[j].value(digits[i][j])
sleep(0.5)
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

5(c) Create a calculator using Arduino microprocessor.

Program :

#include <LiquidCrystal.h>
#include <Keypad.h>
#include <Servo.h>
/* Display */
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
/* Keypad setup */
const byte KEYPAD_ROWS = 4;
const byte KEYPAD_COLS = 4;
byte rowPins[KEYPAD_ROWS] = {5, 4, 3, 2};
byte colPins[KEYPAD_COLS] = {A3, A2, A1, A0};
char keys[KEYPAD_ROWS][KEYPAD_COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'.', '0', '=', '/'}
};
Keypad keypad = Keypad(makeKeymap(keys), rowPins, colPins, KEYPAD_ROWS,
KEYPAD_COLS);
uint64_t value = 0;
void showSpalshScreen() {
lcd.print("GoodArduinoCode");
lcd.setCursor(3, 1);
String message = "Calculator";
for (byte i = 0; i < message.length(); i++) {
lcd.print(message[i]);
delay(50);
}
delay(500);
}
void updateCursor() {
if (millis() / 250 % 2 == 0 ) {
lcd.cursor();
} else {
lcd.noCursor();
}
}
void setup() {
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

Serial.begin(115200);
lcd.begin(16, 2);
showSpalshScreen();
lcd.clear();
lcd.cursor();
lcd.setCursor(1, 0);
}
char operation = 0;
String memory = "";
String current = "";
uint64_t currentDecimal;
bool decimalPoint = false;
double calculate(char operation, double left, double right) {
switch (operation) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
}
}
void processInput(char key) {
if ('-' == key && current == "") {
current = "-";
lcd.print("-");
return;
}
switch (key) {
case '+':
case '-':
case '*':
case '/':
if (!operation) {
memory = current;
current = "";
}
operation = key;
lcd.setCursor(0, 1);
lcd.print(key);
lcd.setCursor(current.length() + 1, 1);
return;
INSTITUTE OF ENGINEERING AND TECHNOLOGY
Mohanlal Sukhadia University, Udaipur
Name- Reeya Varanjani | Class- B.Tech-CSE (VII Sem) | Subject- IOT Lab

case '=':
float leftNum = memory.toDouble();
float rightNum = current.toDouble();
memory = String(calculate(operation, leftNum, rightNum));
current = "";
lcd.clear();
lcd.setCursor(1, 0);
lcd.print(memory);
lcd.setCursor(0, 1);
lcd.print(operation);
return;
}
if ('.' == key && current.indexOf('.') >= 0) {
return;
}
if ('.' != key && current == "0") {
current = String(key);
} else if (key) {
current += String(key);
}
lcd.print(key);
}
void loop() {
updateCursor();

char key = keypad.getKey();


if (key) {
processInput(key);
}
}

You might also like