🍓
TPs Raspberry Pi & Linux
3 Projets Pratiques - GPIO Python, Scripts Bash, Serveur Web
🍓 Raspberry Pi
🐧 Linux
🐍 Python GPIO
TP1 : GPIO Python - LED et Bouton
Controle des GPIO avec RPi.GPIO et gpiozero
🎯 Objectifs
- Configurer les GPIO en entree/sortie
- Utiliser les bibliotheques RPi.GPIO et gpiozero
- Gerer les evenements et interruptions
- Creer un systeme de controle LED par bouton
Schema de câblage
Raspberry Pi GPIO Composants
┌─────────────────┐
│ 3.3V (Pin 1) ├────────────────┐
│ │ │
│ GPIO17 (Pin 11)├───[220Ω]───LED──┤
│ │ │
│ GPIO27 (Pin 13)├───[Bouton]──────┤
│ │ │
│ GND (Pin 6) ├─────────────────┘
└─────────────────┘
Note: GPIO27 avec resistance pull-up interne activee
Code avec RPi.GPIO
#!/usr/bin/env python3 # TP1 : LED et Bouton avec RPi.GPIO import RPi.GPIO as GPIO import time # Configuration LED_PIN = 17 BUTTON_PIN = 27 GPIO.setmode(GPIO.BCM) GPIO.setup(LED_PIN, GPIO.OUT) GPIO.setup(BUTTON_PIN, GPIO.IN, pull_up_down=GPIO.PUD_UP) # Variable d'etat led_state = False def button_callback(channel): global led_state led_state = not led_state GPIO.output(LED_PIN, led_state) print(f"LED: {'ON' if led_state else 'OFF'}") # Detection d'evenement avec anti-rebond GPIO.add_event_detect(BUTTON_PIN, GPIO.FALLING, callback=button_callback, bouncetime=300) print("Appuyez sur le bouton (Ctrl+C pour quitter)") try: while True: time.sleep(0.1) except KeyboardInterrupt: print("\nNettoyage GPIO...") finally: GPIO.cleanup()
Code avec gpiozero (plus simple)
#!/usr/bin/env python3 # Version gpiozero - plus Pythonique from gpiozero import LED, Button from signal import pause led = LED(17) button = Button(27) # Le bouton controle la LED button.when_pressed = led.toggle print("Appuyez sur le bouton...") pause() # Attendre indefiniment
Exercices
- Faire clignoter une LED a frequence variable
- Creer un chenillard avec 4 LEDs
- Implementer un compteur d'appuis affiche dans le terminal
TP2 : Scripts Bash - Automatisation Linux
Scripts systeme, monitoring et tâches planifiees
🎯 Objectifs
- Écrire des scripts Bash pour automatiser des tâches
- Utiliser les variables, conditions et boucles
- Planifier des tâches avec cron
- Creer un script de monitoring systeme
Script : Monitoring Systeme
#!/bin/bash # TP2 : Script de monitoring systeme # Usage: ./monitor.sh # Couleurs RED='\033[0;31m' GREEN='\033[0;32m' YELLOW='\033[1;33m' NC='\033[0m' echo -e "${GREEN}====== MONITORING RASPBERRY PI ======${NC}" echo "Date: $(date)" echo "" # Temperature CPU TEMP=$(vcgencmd measure_temp | cut -d= -f2 | cut -d\' -f1) echo -e "🌡️ Temperature CPU: ${YELLOW}${TEMP}°C${NC}" # Utilisation CPU CPU=$(top -bn1 | grep "Cpu(s)" | awk '{print $2}' | cut -d% -f1) echo -e "⚙️ Utilisation CPU: ${YELLOW}${CPU}%${NC}" # Memoire RAM MEM_TOTAL=$(free -m | awk '/Mem:/ {print $2}') MEM_USED=$(free -m | awk '/Mem:/ {print $3}') MEM_PCT=$((MEM_USED * 100 / MEM_TOTAL)) echo -e "💾 Memoire RAM: ${YELLOW}${MEM_USED}MB / ${MEM_TOTAL}MB (${MEM_PCT}%)${NC}" # Espace disque DISK=$(df -h / | awk 'NR==2 {print $5}') echo -e "💿 Espace disque utilise: ${YELLOW}${DISK}${NC}" # Uptime UPTIME=$(uptime -p) echo -e "⏱️ Uptime: ${YELLOW}${UPTIME}${NC}" # Adresse IP IP=$(hostname -I | awk '{print $1}') echo -e "🌐 Adresse IP: ${YELLOW}${IP}${NC}" # Alerte si temperature > 70°C if (( $(echo "$TEMP > 70" | bc -l) )); then echo -e "${RED}⚠️ ALERTE: Temperature elevee!${NC}" fi echo -e "${GREEN}======================================${NC}"
Script : Backup automatique
#!/bin/bash # Script de backup avec rotation BACKUP_DIR="/home/pi/backups" SOURCE_DIR="/home/pi/projets" DATE=$(date +%Y%m%d_%H%M%S) BACKUP_FILE="backup_${DATE}.tar.gz" # Creer le dossier de backup si necessaire mkdir -p "$BACKUP_DIR" # Creer l'archive tar -czf "${BACKUP_DIR}/${BACKUP_FILE}" "$SOURCE_DIR" # Garder seulement les 5 derniers backups ls -t "${BACKUP_DIR}"/backup_*.tar.gz | tail -n +6 | xargs -r rm echo "Backup cree: ${BACKUP_FILE}"
Configuration Cron
# Éditer crontab crontab -e # Exemples de tâches planifiees: # Monitoring toutes les heures 0 * * * * /home/pi/scripts/monitor.sh >> /var/log/monitor.log # Backup quotidien a 3h du matin 0 3 * * * /home/pi/scripts/backup.sh # Redemarrage hebdomadaire (dimanche a 4h) 0 4 * * 0 sudo reboot
TP3 : Serveur Web Flask + GPIO
Interface web pour controler le Raspberry Pi
🎯 Objectifs
- Installer et configurer Flask
- Creer une interface web responsive
- Controler les GPIO via HTTP
- Afficher les donnees capteurs en temps reel
Installation
# Installer Flask et dependances pip3 install flask gpiozero # Structure du projet projet/ ├── app.py ├── templates/ │ └── index.html └── static/ └── style.css
Code : app.py
#!/usr/bin/env python3 # TP3 : Serveur Web Flask + GPIO from flask import Flask, render_template, jsonify, request from gpiozero import LED, CPUTemperature import psutil import os app = Flask(__name__) # Configuration GPIO leds = { 'led1': LED(17), 'led2': LED(27), 'led3': LED(22) } @app.route('/') def index(): return render_template('index.html') @app.route('/api/led/<led_id>/<action>') def control_led(led_id, action): if led_id in leds: if action == 'on': leds[led_id].on() elif action == 'off': leds[led_id].off() elif action == 'toggle': leds[led_id].toggle() return jsonify({'status': 'ok', 'led': led_id, 'state': leds[led_id].is_lit}) return jsonify({'status': 'error'}), 404 @app.route('/api/status') def get_status(): cpu = CPUTemperature() return jsonify({ 'temperature': round(cpu.temperature, 1), 'cpu_percent': psutil.cpu_percent(), 'memory_percent': psutil.virtual_memory().percent, 'disk_percent': psutil.disk_usage('/').percent, 'leds': {k: v.is_lit for k, v in leds.items()} }) if __name__ == '__main__': app.run(host='0.0.0.0', port=5000, debug=True)
Template : index.html
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>Raspberry Pi Control</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body { font-family: Arial; background: #1a1a2e; color: #fff;
text-align: center; padding: 20px; }
.card { background: #16213e; border-radius: 15px; padding: 20px;
margin: 15px auto; max-width: 400px; }
.btn { padding: 15px 30px; margin: 5px; border: none;
border-radius: 10px; font-size: 16px; cursor: pointer; }
.btn-on { background: #3fb950; color: white; }
.btn-off { background: #f85149; color: white; }
.stat { font-size: 24px; color: #00f5d4; }
</style>
</head>
<body>
<h1>🍓 Raspberry Pi Control</h1>
<div class="card">
<h2>📊 Systeme</h2>
<p>🌡️ Temperature: <span class="stat" id="temp">--</span>°C</p>
<p>⚙️ CPU: <span class="stat" id="cpu">--</span>%</p>
<p>💾 RAM: <span class="stat" id="mem">--</span>%</p>
</div>
<div class="card">
<h2>💡 LEDs</h2>
<div>
<button class="btn btn-on" onclick="led('led1','on')">LED1 ON</button>
<button class="btn btn-off" onclick="led('led1','off')">LED1 OFF</button>
</div>
<div>
<button class="btn btn-on" onclick="led('led2','on')">LED2 ON</button>
<button class="btn btn-off" onclick="led('led2','off')">LED2 OFF</button>
</div>
</div>
<script>
function led(id, action) {
fetch('/api/led/' + id + '/' + action);
}
function updateStatus() {
fetch('/api/status')
.then(r => r.json())
.then(data => {
document.getElementById('temp').textContent = data.temperature;
document.getElementById('cpu').textContent = data.cpu_percent;
document.getElementById('mem').textContent = data.memory_percent;
});
}
setInterval(updateStatus, 2000);
updateStatus();
</script>
</body>
</html>
Criteres d'evaluation
| Critere | Points |
|---|---|
| TP1 : GPIO Python fonctionnel | /6 |
| TP2 : Scripts Bash + Cron | /6 |
| TP3 : Serveur Web Flask | /8 |
| Total | /20 |