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

Raspberry Pi 3 b+ Codes-converted

Uploaded by

kishore
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)
14 views

Raspberry Pi 3 b+ Codes-converted

Uploaded by

kishore
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/ 26

RASPBERRY PI 3 B+ COMMANDS AND

CODES

BASIC CODES:
Read two numbers and print their sum, difference, product and division
# variable

num1=30
num2=5

# add
answer=num1 + num2
print('the answer is',answer)

# substraction
answer=num1 - num2
print('the answer is',answer)

# multiplication
answer=num1 * num2
print('the answer is',answer)

# division
answer=num1/num2
print('the answer is',answer)

Area of a given shape (rectangle, triangle, circle, square, parallelogram)reading


shape and appropriate values from standard input

# define a function for calculating


# the area of a shapes
def calculate_area(name):\

# converting all characters


# into lower cases
name = name.lower()

# check for the conditions


if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))

# calculate area of rectangle


rect_area = l * b
print(f"The area of rectangle is{rect_area}.")

elif name == "square":


s = int(input("Enter square's side length: "))

# calculate area of square


sqt_area = s * s
print(f"The area of square is{sqt_area}.")

elif name == "triangle":


h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))

# calculate area of triangle


tri_area = 0.5 * b * h
print(f"The area of triangle is{tri_area}.")

elif name == "circle":


r = int(input("Enter circle's radius length: "))
pi = 3.14

# calculate area of circle


circ_area = pi * r * r
print(f"The area of triangle is{circ_area}.")

elif name == 'parallelogram':


b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))

# calculate area of parallelogram


para_area = b * h
print(f"The area of parallelogram is {para_area}.")

else:
print("Sorry! This shape is not available")

# driver code
if __name__ == "__main__" :

print("Calculate Shape Area")


shape_name = input("Enter the name of shape whose area you want to
find: ")

# function calling
calculate_area(shape_name)
Print current time for 10 times with an interval of 10 seconds
import time;

localtime = time.asctime(time.localtime(time.time()))
print ("Local current time :"), localtime

import time
from datetime import datetime

for x in range(10):
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print(current_time)
time.sleep(1)

Print a name n times

# To print a given Name in n Times


a = input("Enter your name: ")
n = int(input("Enter the number you want to print that times: "))
i = 1
while i<= n:
print( a )
i+=1

If condition:
marks=90
if(marks>35):
print('Marks are greater than 35')
print('Results :Pass')
else:
print('Marks are greater than 35')
print('Results :Fail')
print('Results printed')
Projects commands and codes:
1. Switch-LED:

Code:

import RPi.GPIO as io
from time import sleep
io.setmode(io.BOARD)
led=38
switch=40
io.setwarnings(False)
io.setup(led,io.OUT)
#io.setup(switch,io.IN)
io.setup(switch,io.IN,pull_up_down=io.PUD_UP)
io.output(led,io.LOW)
while 1:
state=io.input(switch)
print(state)
sleep(0.1);
if state==0:
io.output(led,io.HIGH)
else:
io.output(led,io.LOW)
io.cleanup();

2. Two switch two LED:

Code:

import RPi.GPIO as io
from time import sleep
led1=21
led2=20
switch1=16
switch2=12
io.setmode(io.BCM)
io.setwarnings(False)
io.setup(led1,io.OUT)
io.setup(led2,io.OUT)
#io.setup(switch,io.IN)
io.setup(switch1,io.IN,pull_up_down=io.PUD_UP)
io.setup(switch2,io.IN,pull_up_down=io.PUD_UP)
io.output(led1,io.LOW)
io.output(led2,io.LOW)
while 1:
state1=io.input(switch1)
state2=io.input(switch2)
print(state1)
print(state2)

if state1==0:
io.output(led1,io.HIGH)
else:
io.output(led1,io.LOW)
if state2==0:
io.output(led2,io.HIGH)
else:
io.output(led2,io.LOW)

io.cleanup()

3. 3 Times blinking LED:

Code:

import RPi.GPIO as io
from time import sleep
io.setmode(io.BOARD)
led=38
switch=40
io.setwarnings(False)
io.setup(led,io.OUT)
#io.setup(switch,io.IN)
io.setup(switch,io.IN,pull_up_down=io.PUD_UP)
io.output(led,io.LOW)
while 1:
state=io.input(switch)
print(state)
sleep(0.1);
if state==0:
io.output(led,io.HIGH)
sleep(1)
io.output(led,io.LOW)
sleep(1)
io.output(led,io.HIGH)
sleep(1)
io.output(led,io.LOW)
sleep(1)
io.output(led,io.HIGH)
sleep(1)
io.output(led,io.LOW)
sleep(1)
else:
io.output(led,io.LOW)
io.cleanup();

4. Buzzer:

Code:

import RPi.GPIO as io
import time
io.setmode(io.BCM)
buzzer=19
io.setwarnings(False)
io.setup(buzzer,io.OUT)
while 1:
io.output(buzzer,io.HIGH)
print('BUZZER ON')
time.sleep(1)
io.output(buzzer,io.LOW)
print('BUZZER OFF')
time.sleep(1)
io.cleanup()

5. Relay:

Code:

import RPi.GPIO as io
import time
io.setmode(io.BCM)
relay=19
io.setwarnings(False)
io.setup(relay,io.OUT)
while 1:
io.output(relay,io.HIGH)
print('RELAY ON')
time.sleep(1)
io.output(relay,io.LOW)
print('RELAY OFF')
time.sleep(1)
io.cleanup()

6. LCD:

Commands:

1. sudo apt-get update


2. sudo apt-get upgrade
3. git clone https://github.com/adafruit/Adafruit_Python_CharLCD
4. cd Adafruit_Python_CharLCD
5. sudo python setup.py install

Code:
import time
import Adafruit_CharLCD as LCD
lcd_rs = 26
lcd_en = 19
lcd_d4 = 13
lcd_d5 = 6
lcd_d6 = 5
lcd_d7 = 0
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2

lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,


lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)

lcd.message('16x2 LCD \nsttmani.com')

7. Ultrasonic sensor:

Code:

import RPi.GPIO as io
import time
trig=23
echo=24
def setup():
io.setmode(io.BCM)
io.setwarnings(False)
io.setup(trig,io.OUT)
io.setup(echo,io.IN)
io.output(trig,False)

def distance():
io.output(trig,True)
time.sleep(0.00001)
io.output(trig,False)
while io.input(echo)==0:
pulse_start = time.time()
while io.input(echo)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
dis = pulse_duration * 17150
dis = round(dis+1.15,2)
return dis
#print(dis,"CM")

setup()
while 1:
x=distance()
print(x,"cm")
time.sleep(1)
io.cleanup()

Ultrasonic with LCD:

Code:

import RPi.GPIO as io
import time
import Adafruit_CharLCD as LCD
lcd_rs = 26
lcd_en = 19
lcd_d4 = 13
lcd_d5 = 6
lcd_d6 = 5
lcd_d7 = 0
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2
trig=20
echo=21
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,
lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)

def setup():
io.setmode(io.BCM)
io.setwarnings(False)
io.setup(trig,io.OUT)
io.setup(echo,io.IN)
io.output(trig,False)

def distance():
io.output(trig,True)
time.sleep(0.00001)
io.output(trig,False)
while io.input(echo)==0:
pulse_start = time.time()
while io.input(echo)==1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
dis = pulse_duration * 17150
dis = round(dis+1.15,2)
return dis
#print(dis,"CM")

setup()

while 1:
x=distance()
print(x,"cm")
lcd.clear()
lcd.message(' distance')
lcd.message('\n ')
lcd.message(str (x))
time.sleep(1)
io.cleanup()

8. DHT11 :

Commands:

1. git clone https://github.com/adafruit/Adafruit_Python_DHT


2. cd Adafruit_Python_DHT
3. sudo python setup.py install
Code:
import Adafruit_DHT
import time
print("packages imported")
sensor = Adafruit_DHT.DHT11
pin = 21
while True:

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)


print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature,
humidity))

DHT11 with LCD:

Commands:

1.sudo apt-get update


2.sudo apt-get upgrade
3. git clone https://github.com/adafruit/Adafruit_Python_DHT
4. cd Adafruit_Python_DHT
5. sudo python3 setup.py install

Code:
import Adafruit_DHT
import time
import Adafruit_CharLCD as LCD
lcd_rs = 26
lcd_en = 19
lcd_d4 = 13
lcd_d5 = 6
lcd_d6 = 5
lcd_d7 = 0
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2
pin = 21

sensor = Adafruit_DHT.DHT11
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,
lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
lcd.message('Temp Hum\n')
while True:

humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)


lcd.clear()
lcd.message('Temp Hum\n')
lcd.message(str(temperature))
lcd.message(' ')
lcd.message(str(humidity))
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature,
humidity))

9.Thingspeak for IOT using DHT11+LCD :

Commands:
1.sudo apt-get update
2.sudo apt-get upgrade
3. git clone https://github.com/adafruit/Adafruit_Python_DHT
4. cd Adafruit_Python_DHT
5. sudo python3 setup.py install

Code:

import urllib.request
import requests
import threading
import json
import random
import Adafruit_DHT
import time
import Adafruit_DHT
import Adafruit_CharLCD as LCD
lcd_rs = 26
lcd_en = 19
lcd_d4 = 13
lcd_d5 = 6
lcd_d6 = 5
lcd_d7 = 0
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2
sensor = Adafruit_DHT.DHT11
pin = 21
sensor = Adafruit_DHT.DHT11
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,
lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
def thingspeak_post():
threading.Timer(15,thingspeak_post).start()
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature,
humidity))
lcd.clear()
lcd.message('Temp Hum\n')
lcd.message(str(temperature))
lcd.message(' ')
lcd.message(str(humidity))
URl='https://api.thingspeak.com/update?api_key='
KEY='6QAXDRZADORL9MSR'
HEADER='&field1={}&field2={}'.format(temperature,humidity)
NEW_URL = URl+KEY+HEADER
print(NEW_URL)
data=urllib.request.urlopen(NEW_URL)
print(data)

if __name__ == '__main__':
thingspeak_post()

10. Blynk IOT APP:

Commands:
1. sudo apt-get install git-core
2. git clone https://github.com/blynkkk/blynk-library.git
3. cd blynk-library/linux
4. ls
5.make clean all target=raspberry
6../build.sh raspberry
7. sudo ./blynk --token=fabkBlWAXDvn1A8_Wh7x_OXYD4NR0011

Code:

import RPi.GPIO as io
import blynklib
import Adafruit_DHT
import time
io.setmode(io.BCM)
led=20
pin = 21
io.setwarnings(False)
io.setup(led,io.OUT)
io.output(led,io.LOW)
'''BLYNK_AUTH = 'VIFNnYnKKrwvbh11pdVkq0elNRq65q3z'''
BLYNK_AUTH = 'fabkBlWAXDvn1A8_Wh7x_OXYD4NR0011'
sensorr = Adafruit_DHT.DHT11
blynk = blynklib.Blynk(BLYNK_AUTH)
WRITE_EVENT_PRINT_MSG = "[WRITE_VIRTUAL_PIN_EVENT] Pin: V{} Value:
'{}'"
@blynk.handle_event('write V4')
def write_virtual_pin_handler(pin, value):
#print(WRITE_EVENT_PRINT_MSG.format(pin, value))
if int(format(value[0])) == 1:
print("led on")
io.output(led,io.HIGH)
blynk.notify('led on')
else:
print("led off")
io.output(led,io.LOW)
blynk.notify('led off')

def sensor():
humidity, temperature = Adafruit_DHT.read_retry(sensorr, pin)
print('Humidity = {:.2f}%\tTemperature = {:.2f}C'.format(humidity,
temperature))
blynk.virtual_write(1, '{:.2f}'.format(temperature))
blynk.virtual_write(2, '{:.2f}'.format(humidity))

while True:
blynk.run()
sensor()
time

11. Camera:
Open cv installation commands:

open cv 4.1.0 installation commands

1. sudo apt-get update && sudo apt-get upgrade && sudo rpi-update
2. sudo nano /etc/dphys-swapfile
3. #CONF_SWAPSIZE=100
CONF_SWAPSIZE=2048
sudo systemctl restart dphys-swapfile
4. sudo apt-get install build-essential cmake pkg-config
5. sudo apt-get install libjpeg-dev libtiff5-dev libjasper-dev
libpng12-dev
6. sudo apt-get install libavcodec-dev libavformat-dev libswscale-dev
libv4l-dev
7. sudo apt-get install libxvidcore-dev libx264-dev
8. sudo apt-get install libgtk2.0-dev libgtk-3-dev
9. sudo apt-get install libatlas-base-dev gfortran
if you do not have Python installed, you can install it by the
following command 10,11 otherwise no need
10.sudo apt-get install python3-dev
11.sudo apt-get install python3-pip

12.wget -O opencv.zip
https://github.com/opencv/opencv/archive/3.4.16.zip
13.wget -O opencv_contrib.zip
https://github.com/opencv/opencv_contrib/archive/3.4.16.zip
14.unzip opencv.zip
15.unzip opencv_contrib.zip
16.sudo pip3 install numpy
17.cd ~/opencv-3.4.16/
18.mkdir build
19.cd build
20.cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D INSTALL_PYTHON_EXAMPLES=ON \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-4.1.0/modules \
-D BUILD_EXAMPLES=ON ..
21.make -j4 or make -j$(nproc)
22. sudo make install && sudo ldconfig
23.sudo reboot

testing opencv

24. python3
25. import cv2
26. cv2.__version__

(or)
1. sudo apt update
2. sudo apt upgrade
3. sudo apt install cmake build-essential pkg-config git
4. sudo apt install libjpeg-dev libtiff-dev libjasper-dev libpng-dev
libwebp-dev libopenexr-dev
5. sudo apt install libavcodec-dev libavformat-dev libswscale-dev
libv4l-dev libxvidcore-dev libx264-dev libdc1394-22-dev libgstreamer-
plugins-base1.0-dev libgstreamer1.0-dev
6. sudo apt install libgtk-3-dev libqtgui4 libqtwebkit4 libqt4-test
python3-pyqt5
7. sudo apt install libatlas-base-dev liblapacke-dev gfortran
8. sudo apt install libhdf5-dev libhdf5-103
9. sudo apt install python3-dev python3-pip python3-numpy
Begin modifying the swap file configuration by running the following
command.

10.sudo nano /etc/dphys-swapfile

after open config file While we are within this file, we need to find
and replace the following line.

11.CONF_SWAPSIZE=100 into CONF_SWAPSIZE=2048

Once changed, save the file by pressing CTRL+X followed by Y then


Enter.

12.sudo systemctl restart dphys-swapfile


13.git clone https://github.com/opencv/opencv.git
14.git clone https://github.com/opencv/opencv_contrib.git
15.mkdir ~/opencv/build
16.cd ~/opencv/build

17.cmake -D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/usr/local \
-D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules \
-D ENABLE_NEON=ON \
-D ENABLE_VFPV3=ON \
-D BUILD_TESTS=OFF \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D OPENCV_ENABLE_NONFREE=ON \
-D CMAKE_SHARED_LINKER_FLAGS=-latomic \
-D BUILD_EXAMPLES=OFF ..

18.make -j$(nproc) this command take 2 hours of time for building


19.sudo make install
20.sudo ldconfig
21.sudo nano /etc/dphys-swapfile
22.CONF_SWAPSIZE=2048 replace with CONF_SWAPSIZE=100
23.sudo systemctl restart dphys-swapfile

testing opencv

24. python3
25. import cv2
26. cv2.__version__
https://www.youtube.com/watch?v=rdBTLOx0gi4&t=173s

Code:

'''from picamera import PiCamera


from time import sleep
camera = PiCamera()
camera.start_preview()
sleep(5)
camera.stop_preview()'''

import cv2

cam = cv2.VideoCapture(0)

while True:
ret, image = cam.read()
cv2.imshow('live stream',image)
if cv2.waitKey(1) & 0xFF==ord('b'):
break
cv2.imwrite('/home/pi/Desktop/codes/2.jpg', image)
cam.release()
cv2.destroyAllWindows()

12. Bluetooth:

Commands:

Steps

1. Installation

1-1. Install a serial terminal application on Raspberry Pi. In this post,


I’ll use minicom[2].
sudo apt-get install minicom -y

2. Enable SPP on Raspberry Pi

In order to use SPP, Bluetooth service needs to be restarted with


‘compatibility’ flag[3].
2-1. Open Bluetooth service configuration file.
sudo nano /etc/systemd/system/dbus-org.bluez.service
2-2. Look for a line starts with “ExecStart” and add compatibility flag ‘-
C’ at the end of the line.
ExecStart=/usr/lib/bluetooth/bluetoothd -C
2-3. Add a line below immediately after “ExecStart” line, then save and
close the file.
ExecStartPost=/usr/bin/sdptool add SP
2-4. Reload the configuration file.
sudo systemctl daemon-reload
2-5. Restart the service.
sudo systemctl restart bluetooth.service

3. Pairing

To establish a connection, Raspberry Pi and the phone need to be paired.


3-1. Launch bluetoothctl.
bluetoothctl
3-2. Enter below in order to be discovered from the phone.
discoverable on
3-3. On the phone, scan for Raspberry Pi and pair. You should be able to
see something like below.
[CHG] Device XX:XX:XX:XX:XX:XX Paired: yes
3-4. Press Ctrl+D to quit.

4. Establishing Connection from Phone

4-1. Listen for incoming connection on Raspberry Pi.


sudo rfcomm watch hci0
4-2. Install and launch “Serial Bluetooth Terminal” app[4] on the phone.
4-3. In the app, go to “Device” menu and select Raspberry Pi. If
everything goes well and the connection is established, you should be able
to see like this:
$ sudo rfcomm watch hci0
Waiting for connection on channel 1
Connection from XX:XX:XX:XX:XX:XX to /dev/rfcomm0
Press CTRL-C for hangup

4. Connecting Serial Terminal on Raspberry Pi

5-1. Open another terminal and launch the serial terminal.


minicom -b 9600 -o -D /dev/rfcomm0

Code:

import RPi.GPIO as io
import serial
import time
x=21
y=20
z=16
io.setmode(io.BCM)
io.setwarnings(False)
io.setup(x,io.OUT)
io.setup(y,io.OUT)
io.setup(z,io.OUT)
io.output(x,io.LOW)
io.output(y,io.LOW)
io.output(z,io.LOW)
print('modules imported')
ser = serial.Serial("/dev/rfcomm0", baudrate=9600, timeout=0.5)
# ser = serial.Serial("/dev/ttyS0", baudrate=9600, timeout=0.5)
ser.reset_input_buffer()
while True:
rcv=ser.readline().decode(errors='ignore').rstrip()
print(rcv)
data=rcv

if data <='0' and data >='15':


io.output(x,io.HIGH)
io.output(y,io.HIGH)
io.output(z,io.HIGH)
print('0')
time.sleep(10)

elif data >='15' and data <= '55':


io.output(x,io.LOW)
io.output(y,io.HIGH)
io.output(z,io.HIGH)
print('1')
time.sleep(10)
elif data >='55' and data <='95':
io.output(x,io.HIGH)
io.output(y,io.LOW)
io.output(z,io.HIGH)
print('2')
time.sleep(10)
elif data >='95' and data <= '130':
io.output(x,io.LOW)
io.output(y,io.LOW)
io.output(z,io.HIGH)
print('3')
time.sleep(10)
elif data >='130' and data <= '175':
io.output(x,io.HIGH)
io.output(y,io.HIGH)
io.output(z,io.LOW)
print('4')
time.sleep(10)
elif data >='175' and data <= '210':
io.output(x,io.LOW)
io.output(y,io.HIGH)
io.output(z,io.LOW)
print('5')
time.sleep(10)
elif data >='210' and data <= '230':
io.output(x,io.HIGH)
io.output(y,io.LOW)
io.output(z,io.LOW)
print('6')
time.sleep(10)
elif data >='230' and data <= '254':
io.output(x,io.LOW)
io.output(y,io.LOW)
io.output(z,io.LOW)
print('7')
time.sleep(10)

13. LDR using ADC (MCP3008)+LCD:

Commands:

1.sudo apt-get update


2.sudo apt-get upgrade
3.sudo apt-get install python-dev
4. wget https://github.com/doceme/py-spidev/archive/master.zip
5. unzip master.zip
6. cd py-spidev-master
7. sudo python setup.py install
8.git clone https://github.com/adafruit/Adafruit_Python_MCP3008
9. cd Adafruit_Python_MCP3008
10.sudo python setup.py install

Code:
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import Adafruit_CharLCD as LCD
lcd_rs = 26
lcd_en = 19
lcd_d4 = 13
lcd_d5 = 6
lcd_d6 = 5
lcd_d7 = 0
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2

lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,


lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
CLK = 11
MISO = 9
MOSI = 10
CS = 8
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
print('Reading MCP3008 values, press Ctrl-C to quit...')
while True:
value = mcp.read_adc(0)
adc_voltage=(value / 1023.0 * 3.3)
lcd.clear()
lcd.message('ADC_val ADC_vol\n')
lcd.message(str(value))
lcd.message(' ')
lcd.message(str(value / 1023.0 * 3.3))
print("ADC voltage: %.2f" % adc_voltage)
print('ADC value : %.2f' %(value))
time.sleep(1)

14. LM35 using ADC (MCP3008)+LCD:

Commands:

1.sudo apt-get update


2.sudo apt-get upgrade
3.sudo apt-get install python-dev
4. wget https://github.com/doceme/py-spidev/archive/master.zip
5. unzip master.zip
6. cd py-spidev-master
7. sudo python setup.py install
8.git clone https://github.com/adafruit/Adafruit_Python_MCP3008
9. cd Adafruit_Python_MCP3008
10.sudo python setup.py install

Code:
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import Adafruit_CharLCD as LCD
lcd_rs = 26
lcd_en = 19
lcd_d4 = 13
lcd_d5 = 6
lcd_d6 = 5
lcd_d7 = 0
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2

lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,


lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
CLK = 11
MISO = 9
MOSI = 10
CS = 8
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
print('Reading MCP3008 values, press Ctrl-C to quit...')
while True:
value = mcp.read_adc(0)
adc_voltage=(value / 1023.0 * 3.3)
lcd.clear()
lcd.message('ADC_val ADC_vol\n')
lcd.message(str(value))
lcd.message(' ')
lcd.message(str(value / 1023.0 * 3.3))
print("ADC voltage: %.2f" % adc_voltage)
print('ADC value : %.2f' %(value))
time.sleep(1)

15.10k Pot using ADC (MCP3008)+LCD:

Commands:

1.sudo apt-get update


2.sudo apt-get upgrade
3.sudo apt-get install python-dev
4. wget https://github.com/doceme/py-spidev/archive/master.zip
5. unzip master.zip
6. cd py-spidev-master
7. sudo python setup.py install
8.git clone https://github.com/adafruit/Adafruit_Python_MCP3008
9. cd Adafruit_Python_MCP3008
10.sudo python setup.py install

Code:

import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import Adafruit_CharLCD as LCD
lcd_rs = 26
lcd_en = 19
lcd_d4 = 13
lcd_d5 = 6
lcd_d6 = 5
lcd_d7 = 0
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,
lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
CLK = 11
MISO = 9
MOSI = 10
CS = 8
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
print('Reading MCP3008 values, press Ctrl-C to quit...')
while True:
value = mcp.read_adc(0)
adc_voltage=(value / 1023.0 * 3.3)
lcd.clear()
lcd.message('ADC_val ADC_vol\n')
lcd.message(str(value))
lcd.message(' ')
lcd.message(str(value / 1023.0 * 3.3))
print("ADC voltage: %.2f" % adc_voltage)
print('ADC value : %.2f' %(value))
time.sleep(1)

16. MQ2 Sensor using ADC (MCP3008)+LCD:

Commands:

1.sudo apt-get update


2.sudo apt-get upgrade
3.sudo apt-get install python-dev
4. wget https://github.com/doceme/py-spidev/archive/master.zip
5. unzip master.zip
6. cd py-spidev-master
7. sudo python setup.py install
8.git clone https://github.com/adafruit/Adafruit_Python_MCP3008
9. cd Adafruit_Python_MCP3008
10.sudo python setup.py install

Code:
import time
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008
import Adafruit_CharLCD as LCD
lcd_rs = 26
lcd_en = 19
lcd_d4 = 13
lcd_d5 = 6
lcd_d6 = 5
lcd_d7 = 0
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2

lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,


lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
CLK = 11
MISO = 9
MOSI = 10
CS = 8
mcp = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CS, miso=MISO, mosi=MOSI)
print('Reading MCP3008 values, press Ctrl-C to quit...')
while True:
value = mcp.read_adc(0)
adc_voltage=(value / 1023.0 * 3.3)
lcd.clear()
lcd.message('ADC_val ADC_vol\n')
lcd.message(str(value))
lcd.message(' ')
lcd.message(str(value / 1023.0 * 3.3))
print("ADC voltage: %.2f" % adc_voltage)
print('ADC value : %.2f' %(value))
time.sleep(1)

17. MQ2 Sensor (Digital) + LCD:

Commands:

1. sudo apt-get update


2. sudo apt-get upgrade
3. git clone https://github.com/adafruit/Adafruit_Python_CharLCD
4. cd Adafruit_Python_CharLCD
5. sudo python setup.py install

Code:
import RPi.GPIO as io
from time import sleep
import Adafruit_CharLCD as LCD
lcd_rs = 26
lcd_en = 19
lcd_d4 = 13
lcd_d5 = 6
lcd_d6 =5
lcd_d7 =0
lcd_backlight = 4
lcd_columns = 16
lcd_rows = 2
mq2=21
buzzer=20
io.setmode(io.BCM)
lcd = LCD.Adafruit_CharLCD(lcd_rs, lcd_en, lcd_d4, lcd_d5, lcd_d6,
lcd_d7,
lcd_columns, lcd_rows, lcd_backlight)
io.setwarnings(False)
io.setup(mq2,io.IN)
io.setup(buzzer,io.OUT)
lcd.message('mq2 sensor\n')
while 1:
mq2_state=io.input(mq2)
print(mq2_state)
if mq2_state==True:
io.output(buzzer,io.HIGH)
lcd.clear()
lcd.message('gas sensor\n activated ')
sleep(1)
else:
io.output(buzzer,io.LOW)
lcd.clear()
lcd.message('gas sensor not \nactive ')
sleep(1)
sleep(0.5)
io.cleanup()

18. IR Sensor + Buzzer:

Code:
import RPi.GPIO as io
from time import sleep
io.setmode(io.BOARD)
ir=40
buzzer=39
io.setwarnings(False)
io.setup(ir,io.IN)
io.setup(buzzer,io.OUT)
while 1:
ir_state=io.input(ir)
print(ir_state)
if ir_state==False:
io.output(buzzer,io.HIGH)
else:
io.output(buzzer,io.LOW)
sleep(0.5)
io.cleanup()

NOTE:

1. BCM means Raspberry pi 3 b+ GPIO Pins.


2. Raspberry pi also considers space as an error.

You might also like