Skip to content

Instantly share code, notes, and snippets.

@ochilab
Created May 20, 2024 07:16
Show Gist options
  • Save ochilab/ff155515dded9d619020a1ed583d0ff4 to your computer and use it in GitHub Desktop.
Save ochilab/ff155515dded9d619020a1ed583d0ff4 to your computer and use it in GitHub Desktop.
PC側からM5Stackへデータを送信する
import asyncio
from bleak import BleakScanner, BleakClient
ADDRESS = None
async def ble_scan():
global ADDRESS
device_name = "ESP32"
devices = await BleakScanner.discover()
target_device = next((d for d in devices if d.name == device_name), None)
if target_device:
ADDRESS = target_device.address
print(f"Found device: {target_device.name} at {ADDRESS}")
else:
print("Device not found")
async def connect_and_write():
global ADDRESS
if not ADDRESS:
print("No device address available")
return
client = BleakClient(ADDRESS, use_cached=False)
try:
await client.connect()
print("Connected to device")
write_UUID = "6E400002-B5A3-F393-E0A9-E50E24DCCA9E" #ここは適切な値に変える
while True:
val = input("Input message to send (or 'exit' to quit): ")
if val.lower() == 'exit':
break
write_value = bytearray(val.encode('utf-8'))
await client.write_gatt_char(write_UUID, write_value)
print(f"Written: {val}")
except Exception as e:
print(f"An error occurred: {e}")
finally:
await client.disconnect()
print("Disconnected from device")
if __name__ == "__main__":
asyncio.run(ble_scan())
asyncio.run(connect_and_write())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment