Skip to content

Commit db9408c

Browse files
authored
Merge pull request #2431 from adafruit/picowbell_adalogger
Adding PiCowbell Adalogger Examples
2 parents 3a1edef + 7721280 commit db9408c

File tree

4 files changed

+285
-0
lines changed

4 files changed

+285
-0
lines changed

PiCowbell_Adalogger_Examples/Arduino_PiCowbell_Adalogger_Example/.none.test.only

Whitespace-only changes.
Lines changed: 163 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,163 @@
1+
// SPDX-FileCopyrightText: 2023 Liz Clark for Adafruit Industries
2+
//
3+
// SPDX-License-Identifier: MIT
4+
5+
const int _MISO = 16;
6+
const int _MOSI = 19;
7+
const int _CS = 17;
8+
const int _SCK = 18;
9+
10+
#include <SPI.h>
11+
#include <SD.h>
12+
#include <Wire.h>
13+
#include "Adafruit_MCP9808.h"
14+
#include "RTClib.h"
15+
16+
RTC_PCF8523 rtc;
17+
18+
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
19+
20+
// Create the MCP9808 temperature sensor object
21+
Adafruit_MCP9808 tempsensor = Adafruit_MCP9808();
22+
23+
File logfile;
24+
25+
// blink out an error code
26+
void error(uint8_t errno) {
27+
while(1) {
28+
uint8_t i;
29+
for (i=0; i<errno; i++) {
30+
digitalWrite(LED_BUILTIN, HIGH);
31+
delay(100);
32+
digitalWrite(LED_BUILTIN, LOW);
33+
delay(100);
34+
}
35+
for (i=errno; i<10; i++) {
36+
delay(200);
37+
}
38+
}
39+
}
40+
41+
void setup() {
42+
43+
Serial.begin(115200);
44+
while (!Serial);
45+
Serial.println("\r\nPiCowbell Adalogger Test");
46+
47+
// Ensure the SPI pinout the SD card is connected to is configured properly
48+
SPI.setRX(_MISO);
49+
SPI.setTX(_MOSI);
50+
SPI.setSCK(_SCK);
51+
52+
pinMode(LED_BUILTIN, OUTPUT);
53+
54+
if (!tempsensor.begin(0x18)) {
55+
Serial.println("Couldn't find MCP9808! Check your connections and verify the address is correct.");
56+
while (1);
57+
}
58+
Serial.println("Found MCP9808!");
59+
60+
tempsensor.setResolution(3);
61+
62+
if (! rtc.begin()) {
63+
Serial.println("Couldn't find RTC");
64+
Serial.flush();
65+
while (1) delay(10);
66+
}
67+
68+
if (! rtc.initialized() || rtc.lostPower()) {
69+
Serial.println("RTC is NOT initialized, let's set the time!");
70+
// When time needs to be set on a new device, or after a power loss, the
71+
// following line sets the RTC to the date & time this sketch was compiled
72+
rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
73+
// This line sets the RTC with an explicit date & time, for example to set
74+
// January 21, 2014 at 3am you would call:
75+
// rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
76+
//
77+
// Note: allow 2 seconds after inserting battery or applying external power
78+
// without battery before calling adjust(). This gives the PCF8523's
79+
// crystal oscillator time to stabilize. If you call adjust() very quickly
80+
// after the RTC is powered, lostPower() may still return true.
81+
}
82+
83+
// When time needs to be re-set on a previously configured device, the
84+
// following line sets the RTC to the date & time this sketch was compiled
85+
// rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
86+
// This line sets the RTC with an explicit date & time, for example to set
87+
// January 21, 2014 at 3am you would call:
88+
// rtc.adjust(DateTime(2014, 1, 21, 3, 0, 0));
89+
90+
// When the RTC was stopped and stays connected to the battery, it has
91+
// to be restarted by clearing the STOP bit. Let's do this to ensure
92+
// the RTC is running.
93+
rtc.start();
94+
95+
float drift = 43; // seconds plus or minus over oservation period - set to 0 to cancel previous calibration.
96+
float period_sec = (7 * 86400); // total obsevation period in seconds (86400 = seconds in 1 day: 7 days = (7 * 86400) seconds )
97+
float deviation_ppm = (drift / period_sec * 1000000); // deviation in parts per million (μs)
98+
float drift_unit = 4.34; // use with offset mode PCF8523_TwoHours
99+
// float drift_unit = 4.069; //For corrections every min the drift_unit is 4.069 ppm (use with offset mode PCF8523_OneMinute)
100+
int offset = round(deviation_ppm / drift_unit);
101+
// rtc.calibrate(PCF8523_TwoHours, offset); // Un-comment to perform calibration once drift (seconds) and observation period (seconds) are correct
102+
// rtc.calibrate(PCF8523_TwoHours, 0); // Un-comment to cancel previous calibration
103+
104+
Serial.print("Offset is "); Serial.println(offset); // Print to control offset
105+
106+
// see if the card is present and can be initialized:
107+
if (!SD.begin(_CS)) {
108+
Serial.println("initialization failed!");
109+
return;
110+
}
111+
Serial.println("initialization done.");
112+
}
113+
114+
void loop() {
115+
tempsensor.wake();
116+
DateTime now = rtc.now();
117+
float c = tempsensor.readTempC();
118+
float f = tempsensor.readTempF();
119+
Serial.println("Writing to SD card");
120+
digitalWrite(LED_BUILTIN, HIGH);
121+
122+
// make a string for assembling the data to log:
123+
String dataString = "";
124+
125+
dataString += "The current temp is: ";
126+
dataString += String(c);
127+
dataString += "C, ";
128+
dataString += String(f);
129+
dataString += "F, at ";
130+
dataString += String(now.year(), DEC);
131+
dataString += String('/');
132+
dataString += String(now.month(), DEC);
133+
dataString += String('/');
134+
dataString += String(now.day(), DEC);
135+
dataString += String(" (");
136+
dataString += String(daysOfTheWeek[now.dayOfTheWeek()]);
137+
dataString += String(") ");
138+
dataString += String(now.hour(), DEC);
139+
dataString += String(':');
140+
dataString += String(now.minute(), DEC);
141+
dataString += String(':');
142+
dataString += String(now.second(), DEC);
143+
144+
145+
// open the file. note that only one file can be open at a time,
146+
// so you have to close this one before opening another.
147+
File dataFile = SD.open("datalog.txt", FILE_WRITE);
148+
149+
// if the file is available, write to it:
150+
if (dataFile) {
151+
dataFile.println(dataString);
152+
dataFile.close();
153+
// print to the serial port too:
154+
Serial.println(dataString);
155+
}
156+
// if the file isn't open, pop up an error:
157+
else {
158+
Serial.println("error opening datalog.txt");
159+
}
160+
digitalWrite(LED_BUILTIN, LOW);
161+
162+
delay(5000);
163+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# SPDX-FileCopyrightText: 2023 Liz Clark for Adafruit Industries
2+
#
3+
# SPDX-License-Identifier: MIT
4+
"""CircuitPython PiCowbell Adalogger Example"""
5+
import time
6+
import board
7+
import sdcardio
8+
import busio
9+
import storage
10+
import adafruit_mcp9808
11+
import adafruit_pcf8523
12+
13+
# setup for Pico I2C
14+
i2c = busio.I2C(board.GP5, board.GP4)
15+
# setup for mcp9808 temp monitor
16+
mcp9808 = adafruit_mcp9808.MCP9808(i2c)
17+
# setup for RTC
18+
rtc = adafruit_pcf8523.PCF8523(i2c)
19+
20+
# list of days to print to the text file on boot
21+
days = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
22+
23+
# SPI SD_CS pin
24+
SD_CS = board.GP17
25+
26+
# SPI setup for SD card
27+
spi = busio.SPI(board.GP18, board.GP19, board.GP16)
28+
sdcard = sdcardio.SDCard(spi, SD_CS)
29+
vfs = storage.VfsFat(sdcard)
30+
try:
31+
storage.mount(vfs, "/sd")
32+
print("sd card mounted")
33+
except ValueError:
34+
print("no SD card")
35+
36+
# to update the RTC, change set_clock to True
37+
# otherwise RTC will remain set
38+
# it should only be needed after the initial set
39+
# if you've removed the coincell battery
40+
set_clock = False
41+
42+
if set_clock:
43+
# year, mon, date, hour, min, sec, wday, yday, isdst
44+
t = time.struct_time((2023, 3, 6, 00, 00, 00, 0, -1, -1))
45+
46+
print("Setting time to:", t)
47+
rtc.datetime = t
48+
print()
49+
50+
# variable to hold RTC datetime
51+
t = rtc.datetime
52+
53+
time.sleep(1)
54+
55+
def get_temp(sensor):
56+
temperature_celsius = sensor
57+
temperature_fahrenheit = temperature_celsius * 9 / 5 + 32
58+
return temperature_fahrenheit
59+
60+
# initial write to the SD card on startup
61+
try:
62+
with open("/sd/temp.txt", "a") as f:
63+
# writes the date
64+
f.write('The date is {} {}/{}/{}\n'.format(days[t.tm_wday], t.tm_mon, t.tm_mday, t.tm_year))
65+
# writes the start time
66+
f.write('Start time: {}:{}:{}\n'.format(t.tm_hour, t.tm_min, t.tm_sec))
67+
# headers for data, comma-delimited
68+
f.write('Temp,Time\n')
69+
# debug statement for REPL
70+
print("initial write to SD card complete, starting to log")
71+
except ValueError:
72+
print("initial write to SD card failed - check card")
73+
74+
while True:
75+
try:
76+
# variable for RTC datetime
77+
t = rtc.datetime
78+
# append SD card text file
79+
with open("/sd/temp.txt", "a") as f:
80+
# read temp data from mcp9808
81+
temp = get_temp(mcp9808.temperature)
82+
# write temp data followed by the time, comma-delimited
83+
f.write('{},{}:{}:{}\n'.format(temp, t.tm_hour, t.tm_min, t.tm_sec))
84+
print("data written to sd card")
85+
# repeat every 30 seconds
86+
time.sleep(30)
87+
except ValueError:
88+
print("data error - cannot write to SD card")
89+
time.sleep(10)
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# SPDX-FileCopyrightText: 2017 ladyada for Adafruit Industries
2+
# SPDX-License-Identifier: MIT
3+
4+
import time
5+
import board
6+
import busio
7+
import adafruit_pcf8523
8+
9+
I2C = busio.I2C(board.GP5, board.GP4)
10+
rtc = adafruit_pcf8523.PCF8523(I2C)
11+
12+
days = ("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
13+
14+
set_time = False
15+
16+
if set_time: # change to True if you want to write the time!
17+
# year, mon, date, hour, min, sec, wday, yday, isdst
18+
t = time.struct_time((2023, 3, 6, 10, 55, 00, 1, -1, -1))
19+
# you must set year, mon, date, hour, min, sec and weekday
20+
# yearday is not supported, isdst can be set but we don't do anything with it at this time
21+
22+
print("Setting time to:", t) # uncomment for debugging
23+
rtc.datetime = t
24+
print()
25+
26+
while True:
27+
t = rtc.datetime
28+
#print(t) # uncomment for debugging
29+
30+
print("The date is %s %d/%d/%d" % (days[t.tm_wday], t.tm_mon, t.tm_mday, t.tm_year))
31+
print("The time is %d:%02d:%02d" % (t.tm_hour, t.tm_min, t.tm_sec))
32+
33+
time.sleep(1) # wait a second

0 commit comments

Comments
 (0)