Skip to content

Commit f5d3043

Browse files
authored
files
1 parent 569df92 commit f5d3043

File tree

2 files changed

+284
-0
lines changed

2 files changed

+284
-0
lines changed

client_picow.py

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
import network # Library to connect WiFi
2+
import socket # Library for communication
3+
import time # Library for time and delays
4+
import machine # Library to control GPIO and hardware
5+
import urequests # Library for making HTTP requests
6+
from machine import I2C, Pin
7+
from ssd1306 import SSD1306_I2C # Libraries for OLED screen
8+
9+
# My WiFi info
10+
ssid = "your_wifi_name"
11+
password = "your_wifi_password"
12+
13+
# My Adafruit IO info
14+
AIO_USERNAME = "your_adafruit_username"
15+
AIO_KEY = "your_adafruit_key"
16+
AIO_BASE_URL = f"https://io.adafruit.com/api/v2/{AIO_USERNAME}/feeds"
17+
18+
# Feeds' names
19+
TEMP_FEED = "temperature"
20+
HUM_FEED = "humidity"
21+
RAIN_FEED = "rain-possibility"
22+
LDR_FEED = "ldr"
23+
AIR_QUALITY_FEED = "air-quality"
24+
25+
# Initialize OLED display
26+
WIDTH = 128
27+
HEIGHT = 64
28+
i2c = machine.SoftI2C(scl=Pin(15), sda=Pin(4))
29+
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c)
30+
31+
# LED pins
32+
RED_LED = Pin(18, Pin.OUT)
33+
GREEN_LED = Pin(19, Pin.OUT)
34+
BLUE_LED = Pin(20, Pin.OUT)
35+
36+
# Turn off all LEDs
37+
def turn_off_leds():
38+
RED_LED.value(0)
39+
GREEN_LED.value(0)
40+
BLUE_LED.value(0)
41+
42+
# Connect to WiFi
43+
def connect_wifi():
44+
wlan = network.WLAN(network.STA_IF)
45+
wlan.active(True)
46+
wlan.disconnect()
47+
wlan.connect(ssid, password)
48+
49+
while not wlan.isconnected():
50+
time.sleep(1)
51+
print("Connecting to WiFi...")
52+
53+
print("Connected to WiFi")
54+
print("IP address:", wlan.ifconfig()[0])
55+
56+
# Publish data to Adafruit IO using REST API
57+
def publish_data(feed, value):
58+
url = f"{AIO_BASE_URL}/{feed}/data"
59+
headers = {"X-AIO-Key": AIO_KEY, "Content-Type": "application/json"}
60+
data = {"value": value}
61+
response = urequests.post(url, json=data, headers=headers)
62+
if response.status_code == 200 or response.status_code == 201:
63+
print(f"Published to {feed}: {value}")
64+
else:
65+
print(f"Failed to publish to {feed}: {response.text}")
66+
response.close()
67+
68+
# Connect to ESP32 server and fetch data
69+
def fetch_data_from_esp32_persistent():
70+
addr = socket.getaddrinfo('192.168.112.125', 8080)[0][-1]
71+
s = socket.socket()
72+
s.settimeout(10) # 10 second timeout for connection and data reception
73+
try:
74+
s.connect(addr)
75+
s.send(b'Hello ESP32') # Request data from server
76+
data = s.recv(1024) # Get data from server
77+
if data:
78+
print("Data received from server:", data.decode())
79+
return data.decode().split(',')
80+
except OSError as e:
81+
print("Error fetching data:", e)
82+
finally:
83+
print("Closing socket")
84+
s.close() # Close connection
85+
return None
86+
87+
88+
89+
90+
# Main loop
91+
def main():
92+
connect_wifi()
93+
94+
while True:
95+
sensor_data = fetch_data_from_esp32_persistent()
96+
97+
if sensor_data:
98+
temp = float(sensor_data[0])
99+
hum = sensor_data[1]
100+
raindrop_value = int(sensor_data[2])
101+
ldr_value = int(sensor_data[3])
102+
mq135_value = int(sensor_data[4])
103+
104+
# Display data on OLED
105+
oled.fill(0)
106+
oled.text(f"Temp: {temp:.1f} C", 0, 10)
107+
oled.text(f"Humidity: {hum} %", 0, 20)
108+
oled.text(f"Rain: {'Yes' if raindrop_value < 3000 else 'No'}", 0, 30)
109+
oled.text(f"Light: {'Night' if ldr_value > 3000 else 'Daytime'}", 0, 40)
110+
oled.text(f"Air Q: {'Good' if mq135_value < 1000 else 'Bad'}", 0, 50)
111+
oled.show()
112+
113+
# Convert analog values
114+
nraindrop_value = 100 - ((raindrop_value - 0) / 4095) * 100
115+
print(nraindrop_value)
116+
nldr_value = 100 - (((ldr_value - 0) / 4095) * 100)
117+
print(nldr_value)
118+
nmq135_value = ((mq135_value - 0) / 4095) * 100
119+
print(nmq135_value)
120+
121+
# Publish data to Adafruit IO
122+
publish_data(TEMP_FEED, temp)
123+
publish_data(HUM_FEED, hum)
124+
publish_data(RAIN_FEED, nraindrop_value)
125+
publish_data(LDR_FEED, nldr_value)
126+
publish_data(AIR_QUALITY_FEED, nmq135_value)
127+
128+
# LED logic
129+
turn_off_leds()
130+
if raindrop_value < 3000: # if there is rain blink BLUE twice
131+
BLUE_LED.value(1)
132+
time.sleep(1)
133+
BLUE_LED.value(0)
134+
time.sleep(0.5)
135+
BLUE_LED.value(1)
136+
time.sleep(1)
137+
BLUE_LED.value(0)
138+
turn_off_leds()
139+
if temp > 30: # if too hot blink GREEN twice
140+
GREEN_LED.value(1)
141+
time.sleep(1)
142+
GREEN_LED.value(0)
143+
time.sleep(0.5)
144+
GREEN_LED.value(1)
145+
time.sleep(1)
146+
GREEN_LED.value(0)
147+
turn_off_leds()
148+
if temp < 20: # if too cold blink BLUE and GREEN once
149+
BLUE_LED.value(1)
150+
GREEN_LED.value(1)
151+
time.sleep(1)
152+
BLUE_LED.value(0)
153+
GREEN_LED.value(0)
154+
time.sleep(0.5)
155+
turn_off_leds()
156+
if 20 <= temp <= 30: # if air condition normal blink RED twice
157+
RED_LED.value(1)
158+
time.sleep(1)
159+
RED_LED.value(0)
160+
time.sleep(0.5)
161+
RED_LED.value(1)
162+
time.sleep(1)
163+
RED_LED.value(0)
164+
turn_off_leds()
165+
if mq135_value > 1000: # if air quailty bad blink BLUE, RED and GREEN
166+
BLUE_LED.value(1)
167+
RED_LED.value(1)
168+
GREEN_LED.value(1)
169+
time.sleep(1)
170+
BLUE_LED.value(0)
171+
RED_LED.value(0)
172+
GREEN_LED.value(0)
173+
turn_off_leds()
174+
if mq135_value < 1000: # if air quailty good blink BLUE and RED
175+
BLUE_LED.value(1)
176+
RED_LED.value(1)
177+
time.sleep(1)
178+
BLUE_LED.value(0)
179+
RED_LED.value(0)
180+
else:
181+
turn_off_leds()
182+
183+
time.sleep(10)
184+
185+
# Run the program
186+
main()
187+

server_esp32.ino

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
#include <WiFi.h>
2+
#include <DHT.h>
3+
4+
const char* ssid = "your_wifi_name";
5+
const char* password = "your_wifi_password";
6+
7+
#define DHTPIN 14
8+
#define DHTTYPE DHT11
9+
DHT dht(DHTPIN, DHTTYPE);
10+
#define RAINDROP_PIN 34
11+
#define LDR_PIN 35
12+
#define MQ135_PIN 39
13+
#define MQ135_DIGITAL_PIN 32
14+
#define RAINDROP_DIGITAL_PIN 25
15+
16+
WiFiServer server(8080);
17+
18+
void setup() {
19+
Serial.begin(115200);
20+
WiFi.begin(ssid, password);
21+
22+
while (WiFi.status() != WL_CONNECTED) {
23+
delay(1000);
24+
Serial.println("Connecting to WiFi...");
25+
}
26+
27+
Serial.println("Connected to WiFi");
28+
Serial.println(WiFi.localIP());
29+
30+
dht.begin();
31+
pinMode(MQ135_DIGITAL_PIN, INPUT);
32+
pinMode(RAINDROP_DIGITAL_PIN, INPUT);
33+
server.begin();
34+
}
35+
36+
void loop() {
37+
38+
WiFiClient client = server.available();
39+
40+
if (client) {
41+
42+
Serial.println("New client connected");
43+
44+
unsigned long connectionStartTime = millis(); // For timeout
45+
46+
while (client.connected()) {
47+
if (millis() - connectionStartTime > 10000) { // Timeout
48+
Serial.println("Connection timed out");
49+
break; // If timeout exit
50+
}
51+
52+
// Read sensor data
53+
float humidity = dht.readHumidity();
54+
float temperature = dht.readTemperature();
55+
int raindropValue = analogRead(RAINDROP_PIN);
56+
int ldrValue = analogRead(LDR_PIN);
57+
int mq135Value = analogRead(MQ135_PIN);
58+
int mq135DigitalState = digitalRead(MQ135_DIGITAL_PIN);
59+
int raindropDigitalState = digitalRead(RAINDROP_DIGITAL_PIN);
60+
61+
// Check if sensors are working
62+
bool dhtWorking = !isnan(temperature) && !isnan(humidity);
63+
bool raindropWorking = raindropValue >= 0 && raindropValue <= 4095;
64+
bool ldrWorking = ldrValue >= 0 && ldrValue <= 4095;
65+
bool mq135Working = mq135Value >= 0 && mq135Value <= 4095;
66+
67+
// Debugging
68+
if (!dhtWorking) {
69+
Serial.println("DHT11 sensor is not working correctly!");
70+
}
71+
if (!raindropWorking) {
72+
Serial.println("Raindrop sensor (analog) is not working correctly!");
73+
}
74+
if (!ldrWorking) {
75+
Serial.println("LDR sensor is not working correctly!");
76+
}
77+
if (!mq135Working) {
78+
Serial.println("MQ-135 sensor (analog) is not working correctly!");
79+
}
80+
// Generate data
81+
String data = String(temperature) + "," + String(humidity) + "," + String(raindropValue) + "," +
82+
String(ldrValue) + "," + String(mq135Value) + "," +
83+
String(mq135DigitalState) + "," + String(raindropDigitalState) + "\n";
84+
85+
// Send data to client
86+
client.print(data);
87+
Serial.println("Data sent to client: " + data);
88+
89+
// Wait
90+
delay(1000);
91+
}
92+
93+
// Close connection
94+
client.stop();
95+
Serial.println("Client disconnected");
96+
}
97+
}

0 commit comments

Comments
 (0)