import machine
import bluetooth
import time
import network
import urequests
import sdcard
# I2C Setup for MPU6050
i2c = machine.SoftI2C(scl=machine.Pin(22), sda=machine.Pin(21))
sensor1_address = 0x68 # MPU6050 I2C address
# Wake up the MPU6050 (set SLEEP bit to 0 in PWR_MGMT_1 register)
try:
i2c.writeto_mem(sensor1_address, 0x6B, b'\x00')
print("MPU6050 woken up")
except Exception as e:
print("Failed to wake up MPU6050:", e)
# # Initialize SD card
sdd = machine.SDCard(slot=2, width=1, sck=18, miso=19, mosi=23, cs=5)
# Mount filesystem
vfs = uos.VfsFat(sdd)
uos.mount(vfs, "/sdd")
# Create a file and write something to it
with open("/sdd/test01.txt", "w") as file:
file.write("Hello, SD World!\r\n")
# WiFi Setup - Connect to Wokwi's virtual network
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect("Wokwi-GUEST", "") # No password needed in Wokwi
while not sta.isconnected():
time.sleep(1)
print("Connected to WiFi")
# Initialize BLE
ble = bluetooth.BLE()
ble.active(True)
# Define UUIDs for service and characteristic
service_uuid = bluetooth.UUID(0x1234)
char_uuid = bluetooth.UUID(0x5678)
# Define the service with a writeable characteristic
services = [
(service_uuid, [
(char_uuid, bluetooth.FLAG_WRITE),
]),
]
# Register the services and get handles
handles = ble.gatts_register_services(services)
char_handle = handles[0][1][0] # Characteristic handle
# Set up advertisement data
adv_data = b'\x02\x01\x06\x03\x03\x34\x12'
# Start advertising
ble.gap_advertise(100, adv_data)
# Initialize the characteristic with empty data
ble.gatts_write(char_handle, b'')
# Function to get formatted timestamp (HH:MM:SS)
def get_timestamp():
t = time.localtime()
return f"{t[3]:02d}:{t[4]:02d}:{t[5]:02d}"
# Function to read I2C sensor data
def read_i2c_sensor():
try:
data = i2c.readfrom_mem(sensor1_address, 0x41, 2)
raw_temp = (data[0] << 8) | data[1]
if raw_temp & 0x8000:
raw_temp -= 0x10000
temp = (raw_temp / 340.0) + 36.53
# Print formatted output
# print("Sensor 1 (I2C - MPU6050): Temp :" f"{temp:.2f}C")
# Store in .txt file
with open("/sdd/sensor1_temp.txt", "a") as file:
file.write(f"Temp: {temp:.2f}C at {get_timestamp()} \n")
# Open the file we just created and read from it
with open("/sdd/sensor1_temp.txt", "r") as file:
sensor1_data = file.read()
print(f"Sensor 1 (I2C) data at {get_timestamp()}:", sensor1_data)
return temp
except Exception as e:
print("I2C Error:", e)
# Function to read SPI sensor data
def read_spi_sensor():
try:
# Open the file we just created and read from it
with open("/sdd/test01.txt", "r") as file:
sensor2_data = file.read()
# Store in .csv file with HH:MM:SS timestamp
with open("/sdd/sensor2_data.csv", "a") as file:
file.write(f"{get_timestamp()},{sensor2_data}\n")
# Open the file we just created and read from it
with open("/sdd/sensor2_data.csv", "r") as file:
sensor2_data = file.read()
print(f"Sensor 2 (SPI) data at {get_timestamp()}:", sensor2_data)
except Exception as e:
print("SPI Error:", e)
# Function to read WiFi sensor data - Using a public API
def read_wifi_sensor():
try:
# Make an HTTP GET request to a public API
response = urequests.get("http://httpbin.org/get")
data = response.json()
sensor4_data = data.get('origin', 'Unknown') # Extract 'origin' (IP address) from response
xml_content = f"""<?xml version="1.0" encoding="UTF-8"?>
<sensor4>
<timestamp>{get_timestamp()}</timestamp>
<origin>{sensor4_data}</origin>
</sensor4>
"""
with open("/sdd/sensor4_data.xml", "a") as file:
file.write(xml_content)
# Open the file we just created and read from it
with open("/sdd/sensor4_data.xml", "r") as file:
sensor4_data = file.read()
print(f"Sensor 4 (WiFi) data at {get_timestamp()}:", sensor4_data)
except Exception as e:
print("WiFi Error:", e)
def read_ble_sensor():
try:
# Read the characteristic value
data = ble.gatts_read(char_handle)
if data: # If data is not empty
# Decode data and create JSON object with timestamp
data_str = data.decode('utf-8')
json_obj = {"data": data_str, "timestamp": get_timestamp()}
# Append to JSON file on SD card
with open('/sdd/sensor3_data.json', 'a') as f:
f.write(json.dumps(json_obj) + '\n')
# Read and print the file
with open("/sdd/sensor3_data.json", "r") as file:
ble_data = file.read()
print(f"Sensor 3 (BLE) data at {get_timestamp()}:", ble_data)
# Clear the characteristic
ble.gatts_write(char_handle, b'')
except Exception as e:
print("BLE Error:", e)
# Main loop to read all sensors every 5 seconds
while True:
read_i2c_sensor()
read_spi_sensor()
read_wifi_sensor()
time.sleep(5)