from machine import Pin, I2C, sleep, PWM
import machine
import mpu6050
import time
import math
import dht
import ujson #Used for generating a JSON-String
import network #Needed for WLAN
from umqtt.robust import MQTTClient #Needed for mqtt client
i2c = I2C(scl = Pin(22), sda = Pin(21)) #setup I2C communication for IMU
#Pin Setup
led = Pin(14,Pin.OUT) #configure LED Pin
light_sensor = machine.Pin(27, machine.Pin.IN) #configure Photoresistor Pin
#Wifi connection
print("Connecting to WLAN...")
#WLAN Object
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True) #activate WLAN
sta_if.connect('Wokwi-GUEST','')
while not sta_if.isconnected():
print(".", end = "")
time.sleep(0.05)
print("WIFI connected")
#MQTT Setup
SERVER = "industrial.api.ubidots.com"
port = 1883
client_name = "package_tracker"
topic = b"/v1.6/devices/package_tracker"
token = "BBUS-GR93dskoVvc0NxUnmKWCLmx8yctS2Z"
#MQTT Client Object
client = MQTTClient(client_name, SERVER, port, user = token, password = token)
mpu = mpu6050.accel(i2c) #create IMU Object
damage = 0 #Enables the LED to shine
while True:
msg = ujson.dumps({"Damage":damage})
temps = (mpu.get_values())
#tem = temps["Tmp"]
#gyz = temps["GyZ"]
#gyy = temps["GyY"]
#gyx = temps["GyX"]
acz = temps["AcZ"] #Get the acceleration values
acy = temps["AcY"]
acx = temps["AcX"]
#compute the magnitude of acceleration (Normal 1g)
acceleration_magnitude = math.sqrt(acz*acz+acy*acy+acx*acx) / 16384;
#if magnitude is greater than 2g, damage occurs
if acceleration_magnitude > 2:
damage = 1
client.connect() #connect client
client.publish(topic, msg) #Publish Message to right Topic
client.disconnect() #disconnect client
time.sleep(2) #wait >1s
else:
damage = 0
client.connect() #connect client
client.publish(topic, msg) #Publish Message to right Topic
client.disconnect() #disconnect client
time.sleep(2) #wait >1s
#if the box is opened, the LED will shine
if light_sensor.value() == 0 and damage == 1:
led.value(1)
else:
led.value(0)
#delay to prevent overloading wokwi
time.sleep(0.05)