import network
import time
import urequests
from machine import Pin, I2C
import math
# Adafruit IO credentials
ADAFRUIT_AIO_USERNAME = "Aswathvikram"
ADAFRUIT_AIO_KEY = "aio_awwx79uAeeHK8jkZRkM3cN3ON5j5"
FEED_MAGNITUDE = "resultant" # Send only the magnitude to Adafruit IO
# Wi-Fi credentials
wifi_ssid = "Wokwi-GUEST"
wifi_password = ""
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(wifi_ssid, wifi_password)
print("Connecting to WiFi", end="...")
while not wlan.isconnected():
time.sleep(1)
print(".", end="")
print(" Connected!")
print("IP Address:", wlan.ifconfig()[0])
# Initialize I2C for MPU6050
i2c = I2C(0, sda=Pin(16), scl=Pin(17), freq=400000)
addr = i2c.scan()[0]
# MPU6050 Register Addresses
PWR_MGMT_1 = 0x6B
ACCEL_XOUT_H = 0x3B
ACCEL_YOUT_H = 0x3D
ACCEL_ZOUT_H = 0x3F
def init_mpu():
i2c.writeto_mem(addr, PWR_MGMT_1, bytearray([0])) # Wake up the MPU6050
def read_accel_data():
data = i2c.readfrom_mem(addr, ACCEL_XOUT_H, 6)
ax = int.from_bytes(data[0:2], 'big') / 16384
ay = int.from_bytes(data[2:4], 'big') / 16384
az = int.from_bytes(data[4:6], 'big') / 16384
return ax, ay, az
def calculate_magnitude(ax, ay, az):
return math.sqrt(ax**2 + ay**2 + az**2)
# Normalize the accelerometer values to Richter scale (0.0 to 10.0)
def map_to_richter_scale(value):
# The magnitude from accelerometer is expected between 0.0 to 3.464 (max value from sqrt(2^2 + 2^2 + 2^2))
max_magnitude = 3.464 # max possible value from sqrt(2^2 + 2^2 + 2^2)
# Map to the Richter scale (0.0 to 10.0)
# Normalize to 0-10 scale
return min((value / max_magnitude) * 10, 10) # Ensure it doesn't go beyond 10
# Send data to Adafruit IO
def send_to_adafruit(feed, value):
url = f"https://io.adafruit.com/api/v2/{ADAFRUIT_AIO_USERNAME}/feeds/{feed}/data"
headers = {
"X-AIO-Key": ADAFRUIT_AIO_KEY,
"Content-Type": "application/json"
}
payload = {"value": value}
try:
response = urequests.post(url, json=payload, headers=headers)
if response.status_code == 200:
print(f"Data sent to Adafruit IO: {value}")
else:
print(f"Failed to send data: {response.status_code}")
response.close()
except Exception as e:
print(f"Error: {e}")
# Connect to Wi-Fi
connect_wifi()
# Initialize MPU6050
init_mpu()
while True:
# Read accelerometer data
ax, ay, az = read_accel_data()
# Calculate magnitude
magnitude = calculate_magnitude(ax, ay, az)
# Map magnitude to the Richter scale (0.0 to 10.0)
richter_magnitude = map_to_richter_scale(magnitude)
# Print to Serial Monitor
print(f"Richter Magnitude: {richter_magnitude:.2f}")
# Send only the mapped magnitude to Adafruit IO
send_to_adafruit(FEED_MAGNITUDE, richter_magnitude)
# Wait for 1 second
time.sleep(0.5) # Adjust time for faster updates