Python Programming with Raspberry Pi - Complete Guide
1. Python Basics
Python is a simple, high-level programming language.
1.1 Variables and Data Types:
x=5 # Integer
name = "Raspberry" # String
temp = 23.5 # Float
status = True # Boolean
1.2 Conditional Statements:
if temp > 30:
print("Hot")
1.3 Loops:
for i in range(5):
print(i)
1.4 Functions:
def greet(name):
print("Hello", name)
greet("Pi")
1.5 Lists:
fruits = ["apple", "banana"]
Python Programming with Raspberry Pi - Complete Guide
for fruit in fruits:
print(fruit)
1.6 File Handling:
with open("data.txt", "w") as file:
file.write("Hello Pi")
2. Getting Started with Raspberry Pi
- Download Raspberry Pi OS using Raspberry Pi Imager
- Burn it to SD card (16GB+)
- Boot Pi with monitor, or enable SSH/VNC for headless setup
- Use Thonny IDE for Python programming
- Access terminal via Ctrl+Alt+T or remotely via SSH
Update Pi:
sudo apt update && sudo apt upgrade
Open Thonny (Python IDE) from Menu > Programming > Thonny
3. Interfacing Output Devices (LED, Buzzer)
Use RPi.GPIO to control GPIO pins.
import RPi.GPIO as GPIO
import time
Python Programming with Raspberry Pi - Complete Guide
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT) # LED
GPIO.output(18, GPIO.HIGH)
time.sleep(1)
GPIO.output(18, GPIO.LOW)
GPIO.setup(23, GPIO.OUT) # Buzzer
GPIO.output(23, GPIO.HIGH)
time.sleep(0.5)
GPIO.output(23, GPIO.LOW)
4. Interfacing Input Devices (Button, PIR Sensor)
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
if GPIO.input(17) == GPIO.LOW:
print("Button Pressed")
GPIO.setup(24, GPIO.IN)
if GPIO.input(24):
print("Motion Detected")
5. Reading Analog Sensors with MCP3008
Install SPI library:
sudo pip3 install spidev
Python Programming with Raspberry Pi - Complete Guide
Code:
import spidev
spi = spidev.SpiDev()
spi.open(0, 0)
spi.max_speed_hz = 1350000
def read_adc(channel):
adc = spi.xfer2([1, (8 + channel) << 4, 0])
data = ((adc[1]&3) << 8) + adc[2]
return data
while True:
value = read_adc(0)
print("Analog Value:", value)
time.sleep(1)
6. Cleanup Code
Always end scripts with:
GPIO.cleanup()
to reset pin state and avoid warnings.
7. Summary
This guide introduced Python basics, Raspberry Pi setup, and GPIO interfacing.
It covers LED, buzzer, button, PIR sensor, and analog sensor reading with MCP3008.
Python Programming with Raspberry Pi - Complete Guide
For projects, diagrams, and I2C/SPI examples, refer to the upcoming parts.