我正在尝试将传感器数据从 ESP32 (Devkit V1) 获取到 Firebase 实时数据库。我看到了一些教程,但它们都使用 Arduino 代码,而我在 ESP32 上运行 Micropython 代码,因为我在 Arduino 方面遇到了问题,而且我在 Python 方面更有经验。
有人可以帮助我使用 Micropython 将数据获取到 Firebase。 预先感谢您。
在您需要在 firebase 中创建帐户之前。使用firebase实时数据库。拿到凭证后。输入类似以下的代码后:
import urequests
import ujson
import network
# Your WiFi credentials
WIFI_SSID = "YourWiFiSSID"
WIFI_PASSWORD = "YourWiFiPassword"
# Firebase project credentials
FIREBASE_URL = "https://your-project-id.firebaseio.com"
SECRET_KEY = "YourFirebaseSecretKey"
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print("Connecting to WiFi...")
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
pass
print("WiFi Connected")
print("IP:", wlan.ifconfig()[0])
def send_to_firebase(data):
headers = {
"Content-Type": "application/json",
"Authorization": "Bearer " + SECRET_KEY
}
url = FIREBASE_URL + "/your-collection.json" # Change 'your-collection' to your Firebase collection
response = urequests.post(url, data=ujson.dumps(data), headers=headers)
print("Firebase Response:", response.text)
response.close()
sensor_data = {
"temperature": 25.5,
"humidity": 60
}
connect_wifi()
send_to_firebase(sensor_data)
也许你需要在 Arduino IDE 中安装一些库:json、wifi 等。