Skip to content

Instantly share code, notes, and snippets.

@aki-nishikawa
Last active December 4, 2023 15:08
Show Gist options
  • Save aki-nishikawa/b3c8c4ec889c03d3f240fc4eec9b8e31 to your computer and use it in GitHub Desktop.
Save aki-nishikawa/b3c8c4ec889c03d3f240fc4eec9b8e31 to your computer and use it in GitHub Desktop.
Raspberry Pi Pico W の温度センサで取得したデータを Prometheus Pushgateway に Push する Micro Python コード
import gc
import machine
import network
import urequests
import utime
GATEWAY_HOST = "<Pushgateway host IP>"
GATEWAY_PORT = "<Pushgateway host port>"
WIFI_PASSWORD = "<your password>"
WIFI_SSID = "<your SSID>"
def connect_to_wifi(ssid, password):
""" Connect to WiFi network
"""
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
wifi.connect(ssid, password)
while not wifi.isconnected():
print("Trying to connect to WiFi network...")
utime.sleep(1)
print("Connected to WiFi network.")
def read_temperature(sensor):
""" Read temperature from sensor and convert to Celsius degrees
The temperature sensor measures the Vbe voltage of a biased bipolar diode, connected to the fifth ADC channel
Typically, Vbe = 0.706V at 27 degrees C, with a slope of -1.721mV (0.001721) per degree.
See: https://datasheets.raspberrypi.org/pico/raspberry-pi-pico-python-sdk.pdf
"""
conversion_factor = 3.3 / 65535
reading = sensor.read_u16() * conversion_factor
temperature = 27 - (reading - 0.706) / 0.001721
return temperature
def post_temperature(host, port, temperature):
""" Post temperature to Prometheus gateway
"""
url = f"http://{host}:{port}/metrics/job/temperature/instance/pico"
data = f"temperature {temperature}\n"
try:
urequests.post(url, data=data)
except Exception as e:
print("Failed to post temperature:", e)
def main():
""" Main function
"""
connect_to_wifi(WIFI_SSID, WIFI_PASSWORD)
sensor_temp = machine.ADC(4)
while True:
temperature = read_temperature(sensor_temp)
print(temperature)
post_temperature(GATEWAY_HOST, GATEWAY_PORT, temperature)
utime.sleep(15)
gc.collect()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment