NotesWhat is notes.io?

Notes brand slogan

Notes - notes.io

void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(14, INPUT);
pinMode(16,OUTPUT);
}

void loop() {
int v=analogRead(14);
int intensity=map(v,0,4095,0,255);
analogWrite(16,intensity);
Serial.println(v);
Serial.println("Value:"+String(v));
Serial.println("Intensity"+String(intensity));

// put your main code here, to run repeatedly:
delay(1000); // this speeds up the simulation
}

2222222222222222222222222222222222222222222222222222222

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
const char* publishTopic = "sensor1"; // Sending Encrypted Data
const char* subscribeTopic = "sensor2"; // Receiving Decrypted Data

WiFiClient espClient;
PubSubClient client(espClient);

// Sensor Pins
#define DHTPIN 2
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

// AES Encryption Key (16-byte = 128-bit)
const byte key[16] = { 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, 0x80,
0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0, 0x00 };

// Buffers
byte plaintext[16];
byte ciphertext[16];
char hexCiphertext[33]; // 32 hex chars + null terminator
byte decryptedtext[16];

// Convert Byte Array to HEX String
void bytesToHexString(const byte *bytes, char *hexString, int length) {
for (int i = 0; i < length; i++) {
sprintf(hexString + (i * 2), "%02X", bytes[i]);
}

hexString[length * 2] = ''; // Null-terminate
}

// Convert HEX String to Byte Array
void hexStringToBytes(const char *hexString, byte *bytes, int length) {
for (int i = 0; i < length; i++) {
sscanf(hexString + (i * 2), "%02X", &bytes[i]);
}
}

// Function to connect to WiFi
void setup_wifi() {
Serial.print("Connecting to WiFi...");
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("nWiFi Connected!");
}

// MQTT Callback Function - Handles Incoming Messages
void callback(char* topic, byte* payload, unsigned int length) {
Serial.println("nn📩 Received Encrypted Data via MQTT:");

// Convert payload to a null-terminated string
char receivedHex[33]; // 32 hex chars + null terminator
if (length > 32) length = 32;
memcpy(receivedHex, payload, length);
receivedHex[length] = '';

Serial.printf("Received HEX String: %sn", receivedHex);
Serial.printf("Received Payload Length: %dn", length);

// Validate message length
if (strlen(receivedHex) != 32) {
Serial.println("❌ Error: Invalid payload length. Expected 32 hex characters.");
return;
}

// Convert HEX String to Byte Array
hexStringToBytes(receivedHex, ciphertext, 16);

// Decrypt Data using AES
AES128 aes;
aes.setKey(key, aes.keySize());
aes.decryptBlock(decryptedtext, ciphertext);

// Ensure null termination for safe printing
decryptedtext[15] = '';

// Print decrypted sensor data
Serial.println("🔓 Decrypted Sensor Data:");
Serial.println((char*)decryptedtext);

// Publish decrypted data back via MQTT
client.publish(subscribeTopic, (char*)decryptedtext);
}

// Reconnect to MQTT Broker
void reconnect() {
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
String clientId = "ESP32Client-" + String(random(0xffff), HEX);
if (client.connect(clientId.c_str())) {
Serial.println("Connected!");
client.subscribe(publishTopic); // Listen for encrypted data
} else {
Serial.print("Failed, retry in 5s...");
delay(5000);
}
}
}

void setup() {
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
dht.begin();
delay(2000);
}

void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();

unsigned long now = millis();
static unsigned long lastMsg = 0;

if (now - lastMsg > 5000) {
lastMsg = now;

// Read Sensor Data
float temp = dht.readTemperature();
float hum = dht.readHumidity();

if (isnan(temp) || isnan(hum)) {
Serial.println("Error: Sensor Read Failed!");
return;
}

// Prepare Sensor Data as a String
char sensorData[16];
snprintf(sensorData, sizeof(sensorData), "T1:%.1f H:%.1f", temp, hum);
memcpy(plaintext, sensorData, 16);

// Encrypt Sensor Data
AES128 aes;
aes.setKey(key, aes.keySize());
aes.encryptBlock(ciphertext, plaintext);

// Convert Encrypted Data to HEX String
bytesToHexString(ciphertext, hexCiphertext, 16);

// Debugging: Check the length of the encrypted hex string before sending
Serial.println("n🔐 AES-128 Encrypted Data:");
Serial.println(hexCiphertext);
Serial.print("Hex String Length: ");
Serial.println(strlen(hexCiphertext)); // Ensure it's 32 characters

// Ensure that the length is exactly 32 characters
if (strlen(hexCiphertext) == 32) {
// Publish HEX Encrypted Data as a String
if (client.publish(publishTopic, hexCiphertext)) {
Serial.println("Data sent successfully!");
} else {
Serial.println("Failed to send data!");
}
} else {
Serial.println("Error: Invalid HEX string length. Must be 32 characters.");
}
}
}

3333333333333333333333333333333333333333333333333333333333333333333

#include <WiFi.h>
#include <ThingSpeak.h>
#include <HX711.h>
#include <LiquidCrystal_I2C.h>

#define LED 2
#define LED2 4

LiquidCrystal_I2C lcd(0x27, 16, 2);

const int LOADCELL_DOUT_PIN = 15;
const int LOADCELL_SCK_PIN = 2;
const float calibration_factor = 100.0;

HX711 scale;
long units;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

WiFiClient client;
unsigned long myChannelNumber = 2279390;
const char * myWriteAPIKey = "DMV9RHKW37I550XH";
int statusCode;

void setup() {
Serial.begin(115200);

WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);

scale.begin(LOADCELL_DOUT_PIN, LOADCELL_SCK_PIN);
scale.set_scale(calibration_factor);
scale.tare();

Serial.println("Hello, ESP32!");

lcd.init();
lcd.backlight();

pinMode(LED, OUTPUT);
pinMode(LED2, OUTPUT);
}

void loop() {
// Generate a random weight value between 0 and 5 kg
float simulated_weight = random(0, 5000) / 1000.0; // Random weight between 0 and 5 kg

// LED control logic
digitalWrite(LED, HIGH);
digitalWrite(LED2, LOW);
delay(500);
digitalWrite(LED, LOW);
digitalWrite(LED2, HIGH);
delay(500);

// Attempt to connect to WiFi if not connected
if(WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
Serial.print(".");
delay(1000);
}
Serial.println("nConnected.");
}

// Print the simulated weight on the LCD and serial monitor
Serial.print("Weight: ");
lcd.setCursor(2, 0);
lcd.print("Weight :");
lcd.print(simulated_weight);
lcd.print(" kg");
Serial.print(simulated_weight);
Serial.println(" kg");

delay(1000);

// Update ThingSpeak channel with the simulated weight data
ThingSpeak.setField(1, simulated_weight);
statusCode = ThingSpeak.writeFields(myChannelNumber, myWriteAPIKey);

if(statusCode) { // Successful writing code
Serial.println("Channel update successful.");
} else {
Serial.println("Problem Writing data. HTTP error code :" + String(statusCode));
}

delay(1000);
}

44444444444444444444444444444444444444444444444444444444444444444

// channel id : 2226105
//channel api key : 5ZZNFKTB60NEJIV9

#include <WiFi.h>
#include "DHTesp.h"
#include "ThingSpeak.h"

const int DHT_PIN = 15;
const int LED_PIN = 13;
const char* WIFI_NAME = "Wokwi-GUEST";
const char* WIFI_PASSWORD = "";
const int myChannelNumber =2911014 ;
const char* myApiKey = "4DW6LDEI52JCCK03";
const char* server = "api.thingspeak.com";

DHTesp dhtSensor;
WiFiClient client;

void setup() {
Serial.begin(115200);
dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
pinMode(LED_PIN, OUTPUT);
WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED){
delay(1000);
Serial.println("Wifi not connected");
}
Serial.println("Wifi connected !");
Serial.println("Local IP: " + String(WiFi.localIP()));
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
}

void loop() {
TempAndHumidity data = dhtSensor.getTempAndHumidity();
ThingSpeak.setField(1,data.temperature);
ThingSpeak.setField(2,data.humidity);
if (data.temperature > 35 || data.temperature < 12 || data.humidity > 70 || data.humidity < 40) {
digitalWrite(LED_PIN, HIGH);
}else{
digitalWrite(LED_PIN, LOW);
}

int x = ThingSpeak.writeFields(myChannelNumber,myApiKey);

Serial.println("Temp: " + String(data.temperature, 2) + "°C");
Serial.println("Humidity: " + String(data.humidity, 1) + "%");

if(x == 200){
Serial.println("Data pushed successfull");
}else{
Serial.println("Push error" + String(x));
}
Serial.println("---");

delay(10000);
}

5555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555555

#include <DHT.h>
#include <OneWire.h>
#include <DallasTemperature.h>
#include <Wire.h>
#include <MPU6050_tockn.h>
#include <WiFi.h> // Include the WiFi library for ESP32
#include "ThingSpeak.h"

// Wi-Fi credentials
const char* ssid = "Wokwi-GUEST"; // Replace with your Wi-Fi network SSID
const char* password = ""; // Replace with your Wi-Fi network password

// ThingSpeak settings
const unsigned long channelID = 2546601; // Replace with your ThingSpeak Channel ID
const char* apiKey = "8OJ0YPPZ8IZE7LFT"; // Replace with your ThingSpeak Write API Key

#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT22 // DHT 22 (AM2302)

#define ONE_WIRE_BUS 4 // Data pin of DS18B20 sensor (Use a GPIO pin that supports OneWire)
#define PIR_PIN 5 // Digital pin connected to the PIR motion sensor
#define LDR_ANALOG_PIN 34 // Analog pin connected to the LDR sensor
#define LDR_DIGITAL_PIN 16 // Digital pin connected to Pin 2 (D0) of the LDR sensor

DHT dht(DHTPIN, DHTTYPE);
OneWire oneWire(ONE_WIRE_BUS);
DallasTemperature sensors(&oneWire);
MPU6050 mpu6050(Wire);

WiFiClient client; // Create a WiFiClient object

void setup() {
Serial.begin(9600);
dht.begin();
sensors.begin();
pinMode(PIR_PIN, INPUT);
pinMode(LDR_DIGITAL_PIN, INPUT); // Set LDR digital pin as input

// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");

// Print Wi-Fi network information
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());

// Initialize ThingSpeak
ThingSpeak.begin(client);
}

void loop() {
delay(2000); // Wait for 2 seconds between measurements

// Read temperature and humidity from DHT22
float humidity = dht.readHumidity();
float temperature = dht.readTemperature();

// Read temperature from DS18B20
sensors.requestTemperatures(); // Send the command to get temperature readings
float temperatureDS18B20 = sensors.getTempCByIndex(0); // Get temperature in Celsius

// Read motion status from PIR sensor
int motionStatus = digitalRead(PIR_PIN);

// Read light intensity from LDR sensor (analog pin)
int lightIntensity = analogRead(LDR_ANALOG_PIN);

// Read digital output from LDR sensor
int digitalOutput = digitalRead(LDR_DIGITAL_PIN);

// Read accelerometer data from MPU6050 sensor
mpu6050.update();
float accelerometerX = mpu6050.getAccX();
float accelerometerY = mpu6050.getAccY();
float accelerometerZ = mpu6050.getAccZ();

// Update ThingSpeak with sensor data
ThingSpeak.writeField(channelID, 1, temperature, apiKey);
ThingSpeak.writeField(channelID, 2, humidity, apiKey);
ThingSpeak.writeField(channelID, 3, temperatureDS18B20, apiKey);
ThingSpeak.writeField(channelID, 4, motionStatus, apiKey);
ThingSpeak.writeField(channelID, 5, lightIntensity, apiKey);
ThingSpeak.writeField(channelID, 6, digitalOutput, apiKey);
ThingSpeak.writeField(channelID, 7, accelerometerX, apiKey);
ThingSpeak.writeField(channelID, 8, accelerometerY, apiKey);
ThingSpeak.writeField(channelID, 9, accelerometerZ, apiKey);

// Print sensor data
Serial.print("DHT22 - Humidity: ");
Serial.print(humidity);
Serial.print(" %tTemperature: ");
Serial.print(temperature);
Serial.println(" *C");

Serial.print("DS18B20 - Temperature: ");
Serial.print(temperatureDS18B20);
Serial.println(" *C");

Serial.print("PIR Motion Sensor - Motion Detected: ");
Serial.println(motionStatus == HIGH ? "Yes" : "No");

Serial.print("LDR Sensor (Analog) - Light Intensity: ");
Serial.println(lightIntensity);

Serial.print("LDR Sensor (Digital) - Output: ");
Serial.println(digitalOutput);

Serial.print("MPU6050 - Accelerometer (X,Y,Z): ");
Serial.print(accelerometerX);
Serial.print(", ");
Serial.print(accelerometerY);
Serial.print(", ");
Serial.println(accelerometerZ);

// Wait for a few seconds before sending the next update
delay(15000); // 15 seconds delay as per ThingSpeak rate limits
}

     
 
what is notes.io
 

Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...

With notes.io;

  • * You can take a note from anywhere and any device with internet connection.
  • * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
  • * You can quickly share your contents without website, blog and e-mail.
  • * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
  • * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.

Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.

Easy: Notes.io doesn’t require installation. Just write and share note!

Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )

Free: Notes.io works for 14 years and has been free since the day it was started.


You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;


Email: [email protected]

Twitter: http://twitter.com/notesio

Instagram: http://instagram.com/notes.io

Facebook: http://facebook.com/notesio



Regards;
Notes.io Team

     
 
Shortened Note Link
 
 
Looding Image
 
     
 
Long File
 
 

For written notes was greater than 18KB Unable to shorten.

To be smaller than 18KB, please organize your notes, or sign in.