#include <WiFi.h>
#include <Wire.h>
// WiFi settings
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// MQTT settings
const char* mqttServer = "test.mosquitto.org";
const int mqttPort = 1883;
const char* mqttTopic = "iot/esp32/lm75a/temperature";
WiFiClient client;
// LM75A I2C settings
#define LM75A_ADDR 0x48
#define TEMP_REG 0x00
float readTemperature() {
Wire.beginTransmission(LM75A_ADDR);
Wire.write(TEMP_REG);
Wire.endTransmission();
Wire.requestFrom(LM75A_ADDR, 2);
if (Wire.available() == 2) {
uint8_t msb = Wire.read();
uint8_t lsb = Wire.read();
int16_t raw = ((msb << 8) | lsb) >> 5;
return raw * 0.125;
}
return NAN;
}
void setup() {
Serial.begin(115200);
Wire.begin();
// Connect to WiFi
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected");
Serial.println(WiFi.localIP());
}
void loop() {
float temp = readTemperature();
if (!isnan(temp)) {
// Create a simple JSON string manually
char json[64];
snprintf(json, sizeof(json), "{\"temperature\": %.3f}", temp);
// Connect to MQTT server
if (client.connect(mqttServer, mqttPort)) {
// Send raw MQTT message manually
client.print("MQTT");
client.write(0x30); // PUBLISH packet type
uint8_t topicLen = strlen(mqttTopic);
uint8_t jsonLen = strlen(json);
uint8_t length = 2 + topicLen + jsonLen;
client.write(length); // Remaining length
client.write((uint8_t)(topicLen >> 8));
client.write((uint8_t)(topicLen & 0xFF));
client.write((const uint8_t*)mqttTopic, topicLen);
client.write((const uint8_t*)json, jsonLen);
Serial.print("Published: ");
Serial.println(json);
} else {
Serial.println("MQTT connection failed");
}
client.stop(); // Close connection
} else {
Serial.println("Invalid temp reading");
}
delay(2000);
}