From fd8c79788071cc11a28f3f4f88a5bef93a35eb68 Mon Sep 17 00:00:00 2001 From: KOSASIH Date: Sat, 3 Aug 2024 13:38:10 +0700 Subject: [PATCH] Create iot_device_code.ino --- .../device_code/iot_device_code.ino | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 blockchain_integration/pi_network/pi_network_university/device_code/iot_device_code.ino diff --git a/blockchain_integration/pi_network/pi_network_university/device_code/iot_device_code.ino b/blockchain_integration/pi_network/pi_network_university/device_code/iot_device_code.ino new file mode 100644 index 000000000..f3338c2d3 --- /dev/null +++ b/blockchain_integration/pi_network/pi_network_university/device_code/iot_device_code.ino @@ -0,0 +1,48 @@ +// iot_device_code.ino + +#include +#include + +// WiFi credentials +const char* ssid = "your_wifi_ssid"; +const char* password = "your_wifi_password"; + +// MQTT broker credentials +const char* mqttServer = "your_mqtt_broker_url"; +const char* mqttTopic = "your_mqtt_topic"; +const char* mqttUsername = "your_mqtt_username"; +const char* mqttPassword = "your_mqtt_password"; + +WiFiClient espClient; +PubSubClient client(espClient); + +void setup() { + Serial.begin(115200); + + // Connect to WiFi + WiFi.begin(ssid, password); + while (WiFi.status() != WL_CONNECTED) { + delay(1000); + Serial.println("Connecting to WiFi..."); + } + Serial.println("Connected to WiFi"); + Serial.println("Initializing MQTT client..."); + + // Connect to MQTT broker + client.setServer(mqttServer, 1883); + client.connect(mqttUsername, mqttPassword); +} + +void loop() { + // Read sensor data (e.g. temperature, humidity, etc.) + int sensorValue = analogRead(A0); + + // Convert sensor data to string + String sensorData = String(sensorValue); + + // Publish sensor data to MQTT topic + client.publish(mqttTopic, sensorData.c_str()); + + // Wait for 1 minute before publishing again + delay(60000); +}