Cours Raspberry Pi Complet
Mini-ordinateur et Systemes Embarques
Chapitre 1 : Introduction au Raspberry Pi
Decouverte du mini-ordinateur
1.1 Qu'est-ce que le Raspberry Pi ?
Historique
- 2012 : Lancement du Raspberry Pi Model B (256 MB RAM)
- 2014 : Raspberry Pi B+ avec 40 broches GPIO
- 2015 : Raspberry Pi 2 (quad-core ARM Cortex-A7)
- 2016 : Raspberry Pi 3 (WiFi et Bluetooth integres)
- 2019 : Raspberry Pi 4 (jusqu'a 8 GB RAM)
- 2023 : Raspberry Pi 5 (performances doublees)
Avantages du Raspberry Pi
Abordable
A partir de 35 euros
Linux Complet
OS desktop fonctionnel
GPIO
40 broches programmables
Connectivite
WiFi, Bluetooth, Ethernet
Multimedia
HDMI 4K, Camera
Communaute
Millions d'utilisateurs
1.2 Comparaison des Modeles
| Modele | CPU | RAM | WiFi | USB | GPIO |
|---|---|---|---|---|---|
| Pi Zero W | 1 GHz single-core | 512 MB | Oui | 1x micro | 40 |
| Pi 3 B+ | 1.4 GHz quad-core | 1 GB | Oui | 4x USB 2.0 | 40 |
| Pi 4 B | 1.5 GHz quad-core | 2/4/8 GB | Oui | 2x USB 3.0 + 2x USB 2.0 | 40 |
| Pi 5 | 2.4 GHz quad-core | 4/8 GB | Oui | 2x USB 3.0 + 2x USB 2.0 | 40 |
Chapitre 2 : Architecture Materielle
Composants et connecteurs
2.1 Le SoC Broadcom
Le Raspberry Pi 4 utilise le SoC (System on Chip) Broadcom BCM2711, qui integre tous les composants principaux sur une seule puce.
Specifications du BCM2711
- CPU : ARM Cortex-A72 quad-core @ 1.5 GHz (64-bit)
- GPU : VideoCore VI @ 500 MHz
- Video : Decode H.265 4K60, H.264 1080p60
- RAM : LPDDR4-3200 SDRAM (2/4/8 GB)
┌─────────────────────────────────────────────────────┐ │ RASPBERRY PI 4 MODEL B │ │ │ │ ┌──────────┐ ┌─────────┐ │ │ │ Ethernet │ │ GPIO │ │ │ │ Gigabit │ ┌──────────────┐ │40 pins │ │ │ └──────────┘ │ │ └─────────┘ │ │ │ BCM2711 │ │ │ ┌──────────┐ │ SoC │ ┌─────────┐ │ │ │ USB 3.0 │ │ │ │ micro │ │ │ │ (x2) │ └──────────────┘ │ HDMI x2 │ │ │ ├──────────┤ └─────────┘ │ │ │ USB 2.0 │ ┌──────────────┐ │ │ │ (x2) │ │ RAM 2/4/8GB │ ┌─────────┐ │ │ └──────────┘ └──────────────┘ │ USB-C │ │ │ │ Power │ │ │ ┌──────────┐ ┌──────────────┐ └─────────┘ │ │ │ WiFi/BT │ │ SD Card │ │ │ └──────────┘ └──────────────┘ │ └─────────────────────────────────────────────────────┘
2.2 Connecteurs et Interfaces
| Connecteur | Type | Utilisation |
|---|---|---|
| USB-C | Alimentation | 5V / 3A minimum |
| micro HDMI (x2) | Video | Double ecran 4K @ 60Hz |
| USB 3.0 (x2) | Peripheriques | Disques, clavier, souris |
| USB 2.0 (x2) | Peripheriques | Clavier, souris, webcam |
| Ethernet RJ45 | Reseau | Gigabit (1000 Mbps) |
| microSD | Stockage | Systeme d'exploitation |
| GPIO 40 pins | I/O | Capteurs, actionneurs |
| CSI | Camera | Module camera officiel |
| DSI | Display | Ecran tactile officiel |
| Audio Jack | Audio/Video | Sortie audio analogique |
Chapitre 3 : Installation du Systeme
Raspberry Pi OS et configuration
3.1 Raspberry Pi Imager
Raspberry Pi Imager est l'outil officiel pour installer le systeme d'exploitation sur la carte SD.
Etapes d'installation
- Telecharger Raspberry Pi Imager depuis
raspberrypi.com/software - Inserer la carte microSD dans l'ordinateur
- Lancer Raspberry Pi Imager
- Choisir l'OS : Raspberry Pi OS (64-bit)
- Selectionner la carte SD
- Cliquer sur l'icone roue dentee pour les options avancees
- Configurer : hostname, SSH, WiFi, utilisateur
- Cliquer sur "Ecrire"
3.2 Premier Demarrage
- Inserer la carte SD dans le Raspberry Pi
- Connecter clavier, souris, ecran
- Brancher l'alimentation USB-C
- Attendre le demarrage (LED verte clignote)
- Suivre l'assistant de configuration
Configuration avec raspi-config
# Lancer l'outil de configuration sudo raspi-config # Options importantes : # 1. System Options -> Password (changer mot de passe) # 3. Interface Options -> SSH (activer acces distant) # 3. Interface Options -> VNC (activer bureau distant) # 3. Interface Options -> I2C (activer bus I2C) # 3. Interface Options -> SPI (activer bus SPI) # 5. Localisation -> Locale, Timezone, Keyboard
Chapitre 4 : Commandes Linux Essentielles
Navigation et gestion du systeme
4.1 Navigation dans le Systeme de Fichiers
# Afficher le repertoire courant pwd # Lister les fichiers ls # Liste simple ls -l # Liste detaillee ls -la # Avec fichiers caches # Changer de repertoire cd /home/pi # Aller dans /home/pi cd .. # Remonter d'un niveau cd ~ # Aller dans le dossier home cd - # Retour au repertoire precedent
4.2 Gestion des Fichiers et Dossiers
# Creer un dossier mkdir mon_projet mkdir -p projets/python/test # Creer arborescence # Creer un fichier vide touch fichier.txt # Copier cp source.txt destination.txt cp -r dossier/ nouveau_dossier/ # Copier dossier # Deplacer/Renommer mv ancien.txt nouveau.txt mv fichier.txt /home/pi/Documents/ # Supprimer rm fichier.txt rm -r dossier/ # Supprimer dossier rm -rf dossier/ # Forcer suppression
rm -rf supprime definitivement sans confirmation. Utilisez-la avec precaution !
4.3 Gestion des Paquets (APT)
# Mettre a jour la liste des paquets sudo apt update # Mettre a jour les paquets installes sudo apt upgrade # Installer un paquet sudo apt install python3-pip # Supprimer un paquet sudo apt remove nom_paquet # Rechercher un paquet apt search mot_cle
4.4 Gestion des Services (systemd)
# Verifier le statut d'un service sudo systemctl status ssh # Demarrer un service sudo systemctl start ssh # Arreter un service sudo systemctl stop ssh # Activer au demarrage sudo systemctl enable ssh # Desactiver au demarrage sudo systemctl disable ssh # Redemarrer un service sudo systemctl restart ssh
Chapitre 5 : Acces a Distance
SSH et VNC
5.1 Connexion SSH
SSH (Secure Shell) permet de controler le Raspberry Pi en ligne de commande depuis un autre ordinateur.
Activer SSH
# Via raspi-config sudo raspi-config # -> Interface Options -> SSH -> Enable # Ou via systemctl sudo systemctl enable ssh sudo systemctl start ssh
Se connecter depuis un PC
# Trouver l'adresse IP du Raspberry Pi hostname -I # Connexion SSH (depuis PC Windows/Mac/Linux) ssh pi@192.168.1.100 # Ou avec le hostname ssh pi@raspberrypi.local
5.2 Bureau a Distance VNC
VNC permet d'acceder a l'interface graphique du Raspberry Pi a distance.
Activer VNC
# Via raspi-config sudo raspi-config # -> Interface Options -> VNC -> Enable
Se connecter avec VNC Viewer
- Telecharger VNC Viewer sur votre PC
- Entrer l'adresse IP du Raspberry Pi
- Saisir les identifiants (pi / mot_de_passe)
- Le bureau s'affiche dans la fenetre
Chapitre 6 : Le Port GPIO
Broches et interfaces
6.1 Presentation du GPIO
Brochage du GPIO (40 pins)
GPIO HEADER (Vue de dessus)
┌──────────────────────────────────────────┐
│ 3.3V (1) (2) 5V │
│ GPIO2 (3) (4) 5V │
│ GPIO3 (5) (6) GND │
│ GPIO4 (7) (8) GPIO14 (TX) │
│ GND (9) (10) GPIO15 (RX) │
│ GPIO17 (11)(12) GPIO18 (PWM0) │
│ GPIO27 (13)(14) GND │
│ GPIO22 (15)(16) GPIO23 │
│ 3.3V (17)(18) GPIO24 │
│ GPIO10 (19)(20) GND (MOSI) │
│ GPIO9 (21)(22) GPIO25 (MISO) │
│ GPIO11 (23)(24) GPIO8 (SCLK) │
│ GND (25)(26) GPIO7 (CE1) │
│ GPIO0 (27)(28) GPIO1 (ID_SD) │
│ GPIO5 (29)(30) GND │
│ GPIO6 (31)(32) GPIO12 (PWM0) │
│ GPIO13 (33)(34) GND (PWM1) │
│ GPIO19 (35)(36) GPIO16 │
│ GPIO26 (37)(38) GPIO20 │
│ GND (39)(40) GPIO21 │
└──────────────────────────────────────────┘
6.2 Types de Broches
| Type | Broches | Description |
|---|---|---|
| Alimentation 3.3V | 1, 17 | Sortie 3.3V (50 mA max total) |
| Alimentation 5V | 2, 4 | Sortie 5V (depuis alimentation) |
| Masse (GND) | 6, 9, 14, 20, 25, 30, 34, 39 | Reference 0V |
| GPIO | 26 broches | Entrees/sorties programmables 3.3V |
| I2C | GPIO2 (SDA), GPIO3 (SCL) | Bus I2C pour capteurs/afficheurs |
| SPI | GPIO10, 9, 11, 8, 7 | Bus SPI haute vitesse |
| UART | GPIO14 (TX), GPIO15 (RX) | Communication serie |
| PWM | GPIO12, 13, 18, 19 | Sorties PWM materielles |
Chapitre 7 : Programmation GPIO en Python
Bibliotheque RPi.GPIO et gpiozero
7.1 Bibliotheque RPi.GPIO
import RPi.GPIO as GPIO import time # Configuration GPIO.setmode(GPIO.BCM) # Numerotation BCM (GPIO) GPIO.setwarnings(False) # Definir une LED sur GPIO18 LED = 18 GPIO.setup(LED, GPIO.OUT) # Faire clignoter la LED try: while True: GPIO.output(LED, GPIO.HIGH) # Allume time.sleep(1) GPIO.output(LED, GPIO.LOW) # Eteint time.sleep(1) except KeyboardInterrupt: GPIO.cleanup()
7.2 Lecture d'un Bouton
import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) BOUTON = 17 LED = 18 GPIO.setup(BOUTON, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Pull-up interne GPIO.setup(LED, GPIO.OUT) try: while True: if GPIO.input(BOUTON) == GPIO.LOW: # Bouton appuye GPIO.output(LED, GPIO.HIGH) print("Bouton appuye!") else: GPIO.output(LED, GPIO.LOW) time.sleep(0.1) except KeyboardInterrupt: GPIO.cleanup()
7.3 Bibliotheque gpiozero (Plus Simple)
from gpiozero import LED, Button from time import sleep # Creation des objets led = LED(18) bouton = Button(17) # Methode simple led.on() # Allume led.off() # Eteint led.toggle() # Inverse led.blink() # Clignotement automatique # Avec bouton bouton.when_pressed = led.on bouton.when_released = led.off # Ou boucle classique while True: if bouton.is_pressed: led.on() else: led.off()
gpiozero est plus simple et intuitive pour les debutants. Elle gere automatiquement le cleanup.
7.4 PWM avec gpiozero
from gpiozero import PWMLED from time import sleep led = PWMLED(18) # Variation de luminosite while True: # Augmente progressivement for i in range(101): led.value = i / 100 # 0.0 a 1.0 sleep(0.02) # Diminue progressivement for i in range(100, -1, -1): led.value = i / 100 sleep(0.02)
Chapitre 8 : Capteurs et Actionneurs
Interfacage avec des composants
8.1 Capteur de Temperature DS18B20 (1-Wire)
# Activer 1-Wire dans raspi-config # Interface Options -> 1-Wire -> Enable import glob import time # Trouver le capteur base_dir = '/sys/bus/w1/devices/' device_folder = glob.glob(base_dir + '28*')[0] device_file = device_folder + '/w1_slave' def lire_temperature(): with open(device_file, 'r') as f: lignes = f.readlines() while lignes[0].strip()[-3:] != 'YES': time.sleep(0.2) with open(device_file, 'r') as f: lignes = f.readlines() pos = lignes[1].find('t=') temp_string = lignes[1][pos+2:] temp_c = float(temp_string) / 1000.0 return temp_c while True: print(f"Temperature: {lire_temperature():.2f} C") time.sleep(1)
8.2 Capteur DHT11/DHT22
# Installation : pip3 install adafruit-circuitpython-dht # sudo apt install libgpiod2 import adafruit_dht import board import time # Initialisation du capteur sur GPIO4 dht = adafruit_dht.DHT11(board.D4) # Pour DHT22 : dht = adafruit_dht.DHT22(board.D4) while True: try: temperature = dht.temperature humidite = dht.humidity print(f"Temp: {temperature} C Humidite: {humidite}%") except RuntimeError as e: print(f"Erreur: {e}") time.sleep(2)
8.3 Servomoteur
from gpiozero import Servo from time import sleep servo = Servo(18) while True: servo.min() # Position minimale (-90 degres) sleep(1) servo.mid() # Position centrale (0 degres) sleep(1) servo.max() # Position maximale (+90 degres) sleep(1) # Position precise (valeur entre -1 et 1) servo.value = 0.5 # 45 degres
Chapitre 9 : Serveur Web
Flask et controle via interface web
9.1 Serveur Flask Basique
# Installation : pip3 install flask from flask import Flask, render_template_string app = Flask(__name__) @app.route('/') def index(): return ''' <h1>Raspberry Pi Server</h1> <p>Bienvenue sur le serveur web!</p> <a href="/led/on">Allumer LED</a><br> <a href="/led/off">Eteindre LED</a> ''' if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)
9.2 Controle GPIO via Web
from flask import Flask, render_template_string from gpiozero import LED app = Flask(__name__) led = LED(18) HTML = ''' <!DOCTYPE html> <html> <head> <title>Controle LED</title> <style> body { font-family: Arial; text-align: center; margin-top: 50px; } .btn { padding: 20px 40px; font-size: 20px; margin: 10px; cursor: pointer; } .on { background: #4CAF50; color: white; } .off { background: #f44336; color: white; } </style> </head> <body> <h1>Controle LED Raspberry Pi</h1> <p>Etat: {{ etat }}</p> <a href="/led/on"><button class="btn on">ALLUMER</button></a> <a href="/led/off"><button class="btn off">ETEINDRE</button></a> </body> </html> ''' @app.route('/') def index(): etat = "ON" if led.is_lit else "OFF" return render_template_string(HTML, etat=etat) @app.route('/led/on') def led_on(): led.on() return index() @app.route('/led/off') def led_off(): led.off() return index() if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
http://IP_RASPBERRY:5000
Chapitre 10 : Projets Complets
Applications pratiques
10.1 Station Meteo Connectee
from flask import Flask, jsonify import adafruit_dht import board app = Flask(__name__) dht = adafruit_dht.DHT22(board.D4) @app.route('/api/meteo') def get_meteo(): try: return jsonify({ 'temperature': dht.temperature, 'humidite': dht.humidity, 'status': 'ok' }) except: return jsonify({'status': 'error'}) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
10.2 Systeme de Surveillance avec Camera
# Installation : pip3 install picamera2 opencv-python from picamera2 import Picamera2 import cv2 from datetime import datetime picam2 = Picamera2() picam2.configure(picam2.create_preview_configuration()) picam2.start() def capture_photo(): timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"photo_{timestamp}.jpg" picam2.capture_file(filename) print(f"Photo sauvegardee: {filename}") return filename # Capture une photo capture_photo()
10.3 Domotique - Relais Connecte
from flask import Flask, render_template_string from gpiozero import OutputDevice from datetime import datetime app = Flask(__name__) # Relais sur GPIO17, 18, 27, 22 relais = { 'lumiere': OutputDevice(17), 'ventilo': OutputDevice(18), 'chauffage': OutputDevice(27), 'prise': OutputDevice(22) } @app.route('/toggle/<appareil>') def toggle(appareil): if appareil in relais: relais[appareil].toggle() return index() @app.route('/') def index(): etats = {nom: "ON" if r.is_active else "OFF" for nom, r in relais.items()} return render_template_string(HTML_DOMOTIQUE, etats=etats) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)