#include <WiFi.h>
#include <HTTPClient.h>
#include <Wire.h>
#include <Adafruit_MPU6050.h>
#include <cmath>
Adafruit_MPU6050 mpu;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* dweet = "http://dweet.io/dweet/for/KNUS-12-09-L3";
WiFiClient client;
HTTPClient http;
void setup() {
Serial.begin(115200);
Wire.begin(21, 22);
while (!mpu.begin()) {
Serial.println("MPU6050 not connected!");
delay(1000);
}
Serial.println("MPU6050 ready!");
connectWiFi();
http.begin(dweet);
}
double radToDeg(float rad) {
return rad * 180.0 / M_PI;
}
sensors_event_t event;
void loop() {
sensors_event_t a, g, temp;
mpu.getEvent(&a, &g, &temp);
float ax, ay, az, gx, gy, gz;
ax = a.acceleration.x / 10;
ay = a.acceleration.y / 10;
az = a.acceleration.z / 10;
gx = radToDeg(g.gyro.x);
gy = radToDeg(g.gyro.y);
gz = radToDeg(g.gyro.z);
float t = temp.temperature;
Serial.print("\n Acceleration");
Serial.print("");
Serial.print(" X: "); Serial.print(ax);
Serial.print(", Y: "); Serial.print(ay);
Serial.print(", Z: "); Serial.print(az);
Serial.println(" m/s^2");
Serial.print("\n Rotation");
Serial.print(" X: "); Serial.print(gx);
Serial.print(", Y: "); Serial.print(gy);
Serial.print(", Z: "); Serial.print(gz);
Serial.println(" degrees");
Serial.print("\n Temperature ");
Serial.print(t);
Serial.print("°C");
postToDweet(ax, ay, az, gx, gy, gz, t);
delay(5000);
}
void connectWiFi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
}
void postToDweet(float ax, float ay, float az, float gx, float gy, float gz, float t) {
http.addHeader("Content-Type","application/json");
String content = String("{\n") +
"\n\"ax\":\"" + String(ax,1) + "\"," +
"\n\"ay\":\"" + String(ay,1) + "\"," +
"\n\"az\":\"" + String(az,1) + "\"," +
"\n\"gx\":\"" + String(gx,1) + "\"," +
"\n\"gy\":\"" + String(gy,1) + "\"," +
"\n\"gz\":\"" + String(gz,1) + "\"," +
"\n\"t\":\"" + String(t,1) + "\""
"\n}";
int httpResponseCode = http.POST(content);
if (httpResponseCode == 200) {
Serial.println("\n\n Data pushed successfully");
} else {
Serial.println("\n\n Push error: " + String(httpResponseCode));
}
}