Skip to content

Commit 5047c10

Browse files
authored
Merge pull request #2761 from adafruit/sht4x_trinkey
adding examples for the SHT4x trinkey
2 parents 99a7ece + 50ef265 commit 5047c10

File tree

10 files changed

+327
-0
lines changed

10 files changed

+327
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
// SPDX-FileCopyrightText: 2024 Limor Fried for Adafruit Industries
2+
//
3+
// SPDX-License-Identifier: MIT
4+
5+
#include <Adafruit_SHT4x.h>
6+
7+
Adafruit_SHT4x sht4 = Adafruit_SHT4x();
8+
9+
void setup() {
10+
Serial.begin(115200);
11+
12+
while (!Serial) {
13+
delay(10); // will pause until serial console opens
14+
}
15+
16+
Serial.println("# Adafruit SHT4x Trinkey Temperature and Humidity Demo");
17+
if (! sht4.begin()) {
18+
Serial.println("# Couldn't find SHT4x");
19+
while (1) delay(1);
20+
}
21+
Serial.println("# Found SHT4x sensor.");
22+
23+
sht4.setPrecision(SHT4X_HIGH_PRECISION);
24+
sht4.setHeater(SHT4X_NO_HEATER);
25+
Serial.println("Temperature in *C, Relative Humidity %");
26+
}
27+
28+
void loop() {
29+
sensors_event_t humidity, temp;
30+
31+
sht4.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
32+
Serial.print(temp.temperature);
33+
Serial.print(", ");
34+
Serial.println(humidity.relative_humidity);
35+
36+
// 1 second between readings
37+
delay(1000);
38+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// SPDX-FileCopyrightText: 2024 Limor Fried for Adafruit Industries
2+
//
3+
// SPDX-License-Identifier: MIT
4+
5+
#include <Adafruit_SHT4x.h>
6+
7+
Adafruit_SHT4x sht4 = Adafruit_SHT4x();
8+
9+
void setup() {
10+
Serial.begin(115200);
11+
12+
while (!Serial) {
13+
delay(10); // will pause until serial console opens
14+
}
15+
16+
Serial.println("# Adafruit SHT4x Trinkey Vapor-Pressure Deficit Demo");
17+
if (! sht4.begin()) {
18+
Serial.println("# Couldn't find SHT4x");
19+
while (1) delay(1);
20+
}
21+
Serial.println("# Found SHT4x sensor.");
22+
23+
sht4.setPrecision(SHT4X_HIGH_PRECISION);
24+
sht4.setHeater(SHT4X_NO_HEATER);
25+
Serial.println("Vapor-Pressure Deficit (kPa)");
26+
}
27+
28+
void loop() {
29+
sensors_event_t humidity, temp;
30+
31+
sht4.getEvent(&humidity, &temp);// populate temp and humidity objects with fresh data
32+
// saturation vapor pressure is calculated
33+
float svp = 0.6108 * exp(17.27 * temp.temperature / (temp.temperature + 237.3));
34+
// actual vapor pressure
35+
float avp = humidity.relative_humidity / 100 * svp;
36+
// VPD = saturation vapor pressure - actual vapor pressure
37+
float vpd = svp - avp;
38+
Serial.println(vpd);
39+
40+
// 1 second between readings
41+
delay(1000);
42+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
// SPDX-FileCopyrightText: 2024 Limor Fried for Adafruit Industries
2+
//
3+
// SPDX-License-Identifier: MIT
4+
5+
#include <Adafruit_FreeTouch.h>
6+
7+
Adafruit_FreeTouch touch = Adafruit_FreeTouch(1, OVERSAMPLE_4, RESISTOR_50K, FREQ_MODE_NONE);
8+
9+
void setup() {
10+
Serial.begin(115200);
11+
12+
while (!Serial) {
13+
delay(10); // will pause until serial console opens
14+
}
15+
16+
if (! touch.begin()) {
17+
Serial.println("Failed to begin QTouch on pin 1");
18+
}
19+
}
20+
21+
22+
void loop() {
23+
24+
Serial.println(touch.measure());
25+
delay(1000);
26+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// SPDX-FileCopyrightText: 2024 Limor Fried for Adafruit Industries
2+
//
3+
// SPDX-License-Identifier: MIT
4+
5+
#include <Adafruit_NeoPixel.h>
6+
7+
Adafruit_NeoPixel pixel(1, PIN_NEOPIXEL, NEO_GRB + NEO_KHZ800);
8+
9+
void setup() {
10+
pixel.begin();
11+
pixel.setBrightness(10);
12+
pixel.show();
13+
}
14+
15+
void loop() {
16+
pixel.setPixelColor(0, 0xFF0000);
17+
pixel.show();
18+
Serial.println("on!");
19+
delay(1000);
20+
pixel.setPixelColor(0, 0x0);
21+
pixel.show();
22+
Serial.println("off!");
23+
delay(1000);
24+
}
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# SPDX-FileCopyrightText: 2024 Liz Clark for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
# Written by Liz Clark (Adafruit Industries) with OpenAI ChatGPT v4 Feb 13, 2024 build
6+
# https://help.openai.com/en/articles/6825453-chatgpt-release-notes
7+
8+
# https://chat.openai.com/share/79f4ba33-c045-4fbb-b468-3625f5622b8b
9+
10+
import time
11+
from threading import Thread, Lock
12+
import serial
13+
from Adafruit_IO import Client, Feed
14+
15+
# Configuration
16+
com_port = 'COM123' # Adjust this to your COM port
17+
baud_rate = 115200
18+
io_delay = 5
19+
20+
# Set to your Adafruit IO key.
21+
# Remember, your key is a secret,
22+
# so make sure not to publish it when you publish this code!
23+
ADAFRUIT_IO_KEY = 'your-io-key-here'
24+
25+
# Set to your Adafruit IO username.
26+
# (go to https://accounts.adafruit.com to find your username)
27+
ADAFRUIT_IO_USERNAME = 'your-io-username-here'
28+
29+
# Shared buffer for sensor data
30+
sensor_data = {'temperature': 0, 'humidity': 0}
31+
data_lock = Lock()
32+
stop_signal = False # Shared stop signal
33+
34+
print("Connecting to Adafruit IO...")
35+
# Create an instance of the REST client.
36+
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
37+
print("Connected!")
38+
39+
try:
40+
sht4x_temp = aio.feeds('temp-feed')
41+
except: # pylint: disable = bare-except
42+
feed = Feed(name='temp-feed')
43+
sht4x_temp = aio.create_feed(feed)
44+
45+
try:
46+
sht4x_humid = aio.feeds('humid-feed')
47+
except: # pylint: disable = bare-except
48+
feed = Feed(name='humid_feed')
49+
sht4x_humid = aio.create_feed(feed)
50+
51+
def read_sensor_data(ser):
52+
while not stop_signal:
53+
line = ser.readline().decode('utf-8').strip()
54+
temperature, humidity = line.split(',')
55+
with data_lock:
56+
sensor_data['temperature'] = temperature
57+
sensor_data['humidity'] = humidity
58+
time.sleep(1)
59+
60+
def send_data_to_io():
61+
while not stop_signal:
62+
time.sleep(io_delay) # Adjust timing as needed
63+
with data_lock:
64+
temperature = sensor_data['temperature']
65+
humidity = sensor_data['humidity']
66+
aio.send_data(sht4x_temp.key, temperature)
67+
aio.send_data(sht4x_humid.key, humidity)
68+
print(f"Logged: Temperature={temperature}°C, Humidity={humidity}%")
69+
70+
def main():
71+
global stop_signal # pylint: disable = global-statement
72+
try:
73+
with serial.Serial(com_port, baud_rate, timeout=1) as ser:
74+
print("Starting data logging to Adafruit IO... Press Ctrl+C to stop.")
75+
sensor_thread = Thread(target=read_sensor_data, args=(ser,))
76+
io_thread = Thread(target=send_data_to_io)
77+
78+
sensor_thread.start()
79+
io_thread.start()
80+
81+
while True:
82+
time.sleep(0.1)
83+
except KeyboardInterrupt:
84+
print("\nShutting down...")
85+
stop_signal = True
86+
finally:
87+
sensor_thread.join()
88+
io_thread.join()
89+
print("Data logging stopped.")
90+
91+
if __name__ == '__main__':
92+
main()
Binary file not shown.
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
# SPDX-FileCopyrightText: 2024 Liz Clark for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
# Written by Liz Clark (Adafruit Industries) with OpenAI ChatGPT v4 Feb 13, 2024 build
6+
# https://help.openai.com/en/articles/6825453-chatgpt-release-notes
7+
8+
# https://chat.openai.com/share/430869c1-e28f-4203-9750-c6bbabe18be6
9+
10+
import os
11+
import time
12+
import csv
13+
import serial
14+
15+
# Configuration
16+
com_port = 'COM121' # Adjust this to your COM port
17+
baud_rate = 115200 # Adjust this to the baud rate of your sensor
18+
base_csv_file_path = 'sensor_readings'
19+
20+
def find_next_file_name(base_path):
21+
"""Finds the next available file name with an incremented suffix."""
22+
counter = 0
23+
while True:
24+
new_path = f"{base_path}_{counter}.csv" if counter else f"{base_path}.csv"
25+
if not os.path.isfile(new_path):
26+
return new_path
27+
counter += 1
28+
29+
def read_sensor_data(ser):
30+
line = ser.readline().decode('utf-8').strip()
31+
temperature, humidity = line.split(',')
32+
return float(temperature), float(humidity)
33+
34+
def save_to_csv(file_path, temperature, humidity):
35+
with open(file_path, mode='a', newline='') as file:
36+
writer = csv.writer(file)
37+
# Convert struct_time to a string for the CSV
38+
timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
39+
writer.writerow([timestamp, temperature, humidity])
40+
41+
def main():
42+
csv_file_path = find_next_file_name(base_csv_file_path)
43+
# Write headers to the new file
44+
with open(csv_file_path, mode='w', newline='') as file:
45+
writer = csv.writer(file)
46+
writer.writerow(["Timestamp", "Temperature", "Humidity"])
47+
48+
with serial.Serial(com_port, baud_rate, timeout=1) as ser:
49+
print(f"Starting data logging to {csv_file_path}... Press Ctrl+C to stop.")
50+
try:
51+
while True:
52+
temperature, humidity = read_sensor_data(ser)
53+
save_to_csv(csv_file_path, temperature, humidity)
54+
print(f"Logged: Temperature={temperature}°C, Humidity={humidity}%")
55+
time.sleep(1)
56+
except KeyboardInterrupt:
57+
print("Data logging stopped.")
58+
59+
if __name__ == '__main__':
60+
main()
Binary file not shown.
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2020 ladyada for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import time
6+
import board
7+
import adafruit_sht4x
8+
9+
i2c = board.I2C() # uses board.SCL and board.SDA
10+
sht = adafruit_sht4x.SHT4x(i2c)
11+
print("Found SHT4x with serial number", hex(sht.serial_number))
12+
13+
sht.mode = adafruit_sht4x.Mode.NOHEAT_HIGHPRECISION
14+
print("Current mode is: ", adafruit_sht4x.Mode.string[sht.mode])
15+
print()
16+
17+
while True:
18+
temperature, relative_humidity = sht.measurements
19+
print(f"Temperature: {temperature:0.1f} C")
20+
print(f"Humidity: {relative_humidity:0.1f} %")
21+
print("")
22+
time.sleep(1)
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
# SPDX-FileCopyrightText: Copyright (c) 2020 ladyada for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
5+
import time
6+
import math
7+
import board
8+
import adafruit_sht4x
9+
10+
i2c = board.I2C() # uses board.SCL and board.SDA
11+
sht = adafruit_sht4x.SHT4x(i2c)
12+
sht.mode = adafruit_sht4x.Mode.NOHEAT_HIGHPRECISION
13+
14+
while True:
15+
temperature, relative_humidity = sht.measurements
16+
# saturation vapor pressure is calculated
17+
svp = 0.6108 * math.exp(17.27 * temperature / (temperature + 237.3))
18+
# actual vapor pressure
19+
avp = relative_humidity / 100 * svp
20+
# VPD = saturation vapor pressure - actual vapor pressure
21+
vpd = svp - avp
22+
print(f"Vapor-Pressure Deficit: {vpd:0.1f} kPa")
23+
time.sleep(1)

0 commit comments

Comments
 (0)