메인
home
소프트웨어
home
🥎

라즈베리파이 피코W : 웹 블루투스 제어

목차

피웹1. 피코 블루투스 제어
# 필요한 모듈 임포트 from machine import Pin import bluetooth from ble_simple_peripheral import BLESimplePeripheral import utime # BLE 객체 생성 ble = bluetooth.BLE() # BLE 간단한 주변장치 클래스 인스턴스 생성 sp = BLESimplePeripheral(ble) # 온보드 LED 설정 led_onboard = Pin("LED", Pin.OUT) led_onboard.value(1) # 연결 확인을 위해 LED 켜기 # LED 핀 설정 (예: GPIO 14, 15, 16번 핀에 LED 연결) led_red = Pin(27, Pin.OUT) led_blue = Pin(18, Pin.OUT) led_yellow = Pin(22, Pin.OUT) # LED 상태 변수 초기화 led_states = { 'red': 0, 'blue': 0, 'yellow': 0 } # 수신한 데이터를 처리하는 콜백 함수 정의 def on_rx(data): print("Data received:", data) command = data.decode('utf-8').strip() # 데이터를 문자열로 디코딩하고 공백 제거 if command in led_states: # 해당 LED의 상태를 토글 led_states[command] = 1 - led_states[command] # LED 상태 적용 led_red.value(led_states['red']) led_blue.value(led_states['blue']) led_yellow.value(led_states['yellow']) # 문자열 포매팅 수정 led_status = 'ON' if led_states[command] else 'OFF' print(command.upper() + " LED " + led_status) elif command == 'off': # 모든 LED 끄기 for key in led_states: led_states[key] = 0 led_red.value(0) led_blue.value(0) led_yellow.value(0) print("All LEDs OFF") else: print("Unknown command") # 메인 루프 while True: if sp.is_connected(): sp.on_write(on_rx) utime.sleep(0.1) # CPU 사용량을 줄이기 위해 약간의 딜레이 추가
Python
복사
추가 코드 업로드
ble_simple_peripheral.py
2.9KB
ble_advertising.py
2.7KB
피웹2. 피코 웹 데이터베이스 제어
피웹3. 피코 웹 블루투스 제어
# Source: electrocredible.com , Language: MicroPython # Import necessary modules import machine import bluetooth from ble_simple_peripheral import BLESimplePeripheral # Create a Bluetooth Low Energy (BLE) object ble = bluetooth.BLE() # Create an instance of the BLESimplePeripheral class with the BLE object sp = BLESimplePeripheral(ble) # Create a Pin object for the onboard LED, configure it as an output led = machine.Pin("LED", machine.Pin.OUT) # Initialize the LED state to 0 (off) led_state = 0 led.on() # Define a callback function to handle received data def on_rx(data): print("Data received: ", data) # Print the received data sp.send(data) if data == b'a': # Check if the received data is "toggle" led.on() # LED 켜기 print("aa") if data == b'b': # Check if the received data is "toggle" led.off() # LED 켜기 print("bb") # Start an infinite loop while True: if sp.is_connected(): # Check if a BLE connection is established sp.on_write(on_rx) # Set the callback function for data reception
Python
복사
제어 사이트 예시
제어사이트 코드
<!DOCTYPE html> <html> <head> <title>Raspberry Pico Web Bluetooth Serial Monitor</title> <style> body { font-family: Arial, sans-serif; } .container { max-width: 500px; margin: 0 auto; padding: 20px; } .button { display: inline-block; padding: 10px 20px; font-size: 16px; background-color: #4CAF50; color: #fff; border: none; cursor: pointer; } .button:hover { background-color: #45a049; } .input-field { width: 100%; padding: 10px; font-size: 16px; border: 1px solid #ccc; border-radius: 4px; box-sizing: border-box; } </style> </head> <body> <div class="container"> <h2>Raspberry Pico Web Bluetooth Serial Monitor</h2> <button id="connectButton" class="button" onclick="connectToDevice()">Connect</button> <button id="disconnectButton" class="button" onclick="disconnectFromDevice()" disabled>Disconnect</button> <br><br> <input type="text" id="messageInput" class="input-field" placeholder="Enter message"> <button class="button" onclick="sendMessage()">Send Message</button> <br><br> <pre id="log"></pre> </div> <script> let device; let logElement; let writeCharacteristic; let readCharacteristic; function log(message) { logElement.innerHTML += message + '\n'; } async function connectToDevice() { try { logElement = document.getElementById('log'); log('Requesting Bluetooth Device...'); if (device && device.gatt.connected) { log('Already connected to ' + device.name); return; } device = await navigator.bluetooth.requestDevice({ filters: [{ name: 'mpy-uart' }], optionalServices: ['6e400001-b5a3-f393-e0a9-e50e24dcca9e'] }); log('Connecting to GATT Server...'); const server = await device.gatt.connect(); log('Getting Serial Service...'); const service = await server.getPrimaryService('6e400001-b5a3-f393-e0a9-e50e24dcca9e'); log('Getting Serial Port Write Characteristic...'); writeCharacteristic = await service.getCharacteristic('6e400002-b5a3-f393-e0a9-e50e24dcca9e'); log('Getting Serial Port Read Characteristic...'); readCharacteristic = await service.getCharacteristic('6e400003-b5a3-f393-e0a9-e50e24dcca9e'); log('Enabling notifications...'); await readCharacteristic.startNotifications(); readCharacteristic.addEventListener('characteristicvaluechanged', handleData); device.ongattserverdisconnected = handleDisconnect; // Assigning the disconnect handler log('Connected to ' + device.name); document.getElementById('connectButton').disabled = true; document.getElementById('disconnectButton').disabled = false; } catch (error) { log('Error: ' + error); } } function handleDisconnect() { log('Connection lost. Device disconnected.'); document.getElementById('connectButton').disabled = false; document.getElementById('disconnectButton').disabled = true; alert('Connection lost. Device disconnected.'); } function disconnectFromDevice() { if (device && device.gatt.connected) { device.gatt.disconnect(); } } function handleData(event) { const value = event.target.value; const decoder = new TextDecoder('utf-8'); const data = decoder.decode(value); log('Received: ' + data); } async function sendMessage() { try { const messageInput = document.getElementById('messageInput'); const message = messageInput.value; const encoder = new TextEncoder('utf-8'); const data = encoder.encode(message); await writeCharacteristic.writeValue(data); log('Sent: ' + message); messageInput.value = ''; } catch (error) { log('Error: ' + error); } } </script> </body> </html>
JavaScript
복사