Skip to content

Instantly share code, notes, and snippets.

@mirontoli
Created September 3, 2023 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mirontoli/69f41c599331fc62e8d5d571e9c922b2 to your computer and use it in GitHub Desktop.
Save mirontoli/69f41c599331fc62e8d5d571e9c922b2 to your computer and use it in GitHub Desktop.
import bluetooth
import struct
import time
from machine import Pin, ADC
from micropython import const
# Set up the ADC to read the temperature sensor
adc = ADC(4)
conversion_factor = 3.3 / (65535)
# Set up the Bluetooth Low Energy (BLE) advertising payload
adv_payload = bytearray(3)
adv_payload[0] = 0x02 # Length of this data
adv_payload[1] = 0x01 # Flags data type value
adv_payload[2] = 0x06 # Flags data
# Set up the Bluetooth Low Energy (BLE) advertising interval
adv_interval_ms = const(1000)
# Set up the Bluetooth Low Energy (BLE) advertising name
adv_name = "Temperature Sensor"
# Set up the Bluetooth Low Energy (BLE) advertising service UUID
adv_service_uuid = bluetooth.UUID("6E400001-B5A3-F393-E0A9-E50E24DCCA9E")
# Set up the Bluetooth Low Energy (BLE) advertising characteristic UUID
adv_characteristic_uuid = bluetooth.UUID("6E400002-B5A3-F393-E0A9-E50E24DCCA9E")
# Set up the Bluetooth Low Energy (BLE) advertising service and characteristic
adv_service = bluetooth.Service(adv_service_uuid)
adv_characteristic = bluetooth.Characteristic(
adv_characteristic_uuid,
properties=bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,
value=struct.pack("<h", 0),
permissions=(bluetooth.PERMISSION_READ,),
)
# Set up the Bluetooth Low Energy (BLE) advertising service and characteristic on the device
bluetooth.set_advertisement(
name=adv_name,
service_uuid=adv_service_uuid,
service_data=adv_payload,
manufacturer_data=None,
solicitation_data=None,
service_complete=True,
connectable=True,
)
bluetooth.add_service(adv_service)
adv_service.add_characteristic(adv_characteristic)
bluetooth.start_advertising(adv_interval_ms)
while True:
# Read the temperature sensor and convert it to Celsius
reading = adc.read_u16() * conversion_factor
temperature_celsius = round((27 - (reading - 0.706) / 0.001721), 2)
# Update the value of the characteristic with the current temperature in Celsius
adv_characteristic.value(struct.pack("<h", int(temperature_celsius * 100)))
# Wait for a short time before updating again
time.sleep_ms(100)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment