#include <PubSubClient.h>
#include <WiFi.h>
#include <ArduinoJson.h>
const char *mqtt_server =
"bme.vsb.cz"; // Replace with your MQTT broker IP address or hostname
const int mqtt_port =
1883; // Replace with your MQTT broker port (default: 1883)
const char *mqtt_topic =
"test/json-data" ; // Replace with the MQTT topic to
// Analog-digital conversion constants
const int ecgPin = 35;
const int tempPin = 34;
const float vref = 3.3; // adc voltage range
// Time reference constants
const int measurementPeriod = 50;
int timeOfLastMeasurement = 0;
// Measurements buffer
const int ecgBufferLength = 20;
int ecgBufferIndex = 0;
float ecgBuffer[ecgBufferLength];
// WIfi and MQTT libs
WiFiClient espClient;
PubSubClient mqtt_client(espClient);
void setup() {
Serial.begin(115200);
pinMode(ecgPin, INPUT);
pinMode(tempPin,INPUT);
// Connect to WiFi network
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
// Connect to MQTT broker
mqtt_client.setServer(mqtt_server, mqtt_port);
while (!mqtt_client.connected()) {
if (mqtt_client.connect("ESP32")) {
Serial.println("Connected to MQTT broker");
} else {
delay(1000);
}
}
}
void loop() {
int currentTime = millis();
if(currentTime - timeOfLastMeasurement < measurementPeriod) {
delay(1);
return;
}
// Read the analog input and calculate the voltage
int adc_value = analogRead(ecgPin);
float voltage = adc_value * (vref / 4096);
ecgBuffer[ecgBufferIndex++] = voltage;
if(ecgBufferIndex >= ecgBufferLength) {
// Get value from the temp adc pin
int rawTemp = analogRead(tempPin);
// Reset the buffer index
ecgBufferIndex = 0;
// Create general document
DynamicJsonDocument jsonToSend(2048);
// Fill in the values
jsonToSend["measurement period"] = measurementPeriod;
jsonToSend["temperature"] = rawTemp;
for (int i = 0; i < ecgBufferLength; i++) {
jsonToSend["ecg"][i] = ecgBuffer[i];
}
// Serialize created structure into a String type
String json = "";
serializeJson(jsonToSend, json);
// Publish the voltage to the MQTT topic
mqtt_client.publish(mqtt_topic, json.c_str());
delay(2000);
}
}