# main.py (for Raspberry Pi Pico W)
import network
import urequests
import ujson
import time
from machine import Pin, ADC
# WiFi Configuration
WIFI_SSID = "YOUR_WIFI_SSID"
WIFI_PASSWORD = "YOUR_WIFI_PASSWORD"
# OKWI API Configuration
OKWI_API_URL = "https://api.okwi.com/sensor/data" # Replace with actual OKWI endpoint
OKWI_API_KEY = "your_okwi_api_key"
# Initialize WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
print("Connecting to WiFi...")
time.sleep(1)
print("Connected to WiFi:", wlan.ifconfig())
# Read sensor data (simulated or real)
def read_sensor():
# Example: Read from ADC (Pico's analog pin)
adc = ADC(Pin(26)) # Replace with actual sensor pin
sensor_value = adc.read_u16()
return {
"temperature": sensor_value * 0.1, # Simulate temp (adjust scaling)
"vibration": sensor_value % 100, # Simulate vibration
"timestamp": time.time()
}
# Send data to OKWI
def send_to_okwi(data):
headers = {
"Authorization": f"Bearer {OKWI_API_KEY}",
"Content-Type": "application/json"
}
try:
response = urequests.post(
OKWI_API_URL,
headers=headers,
data=ujson.dumps(data)
)
print("Data sent to OKWI:", response.text)
response.close()
except Exception as e:
print("Failed to send data:", e)
# Fault detection logic (simple threshold)
def detect_fault(sensor_data):
if sensor_data["temperature"] > 50: # Threshold for fault
return "HIGH_TEMP_FAULT"
elif sensor_data["vibration"] > 80: # Threshold for vibration
return "HIGH_VIBRATION_FAULT"
else:
return "NORMAL"
# Main loop
def main():
connect_wifi()
while True:
sensor_data = read_sensor()
fault_status = detect_fault(sensor_data)
if fault_status != "NORMAL":
print("FAULT DETECTED:", fault_status)
# Send alert to OKWI
alert_data = {
"device_id": "pico-001",
"fault_type": fault_status,
"sensor_data": sensor_data
}
send_to_okwi(alert_data)
time.sleep(5) # Send data every 5 sec
if __name__ == "__main__":
main()