summaryrefslogtreecommitdiffstats
path: root/src/main.cpp
blob: 319c024b6d5eb0a3ba88c8a41dad5e01de6b4f77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// simple data logger
//
// using Arduino Leonardo and an Adafruit Logger Shield
//
// uses Adafruit's RTClib
//
// Based on https://github.com/cnvogelg/ardu/blob/master/datalog/datalog/datalog.ino

#include <Arduino.h>
#include <Wire.h>
#include <SD.h>
#include <RTClib.h>
#include <DallasTemperature.h>
#include <stdlib.h>

#include "Bounce.h"

// Pin setup
const int ledGreenPin = 8;
const int ledRedPin = 4;
const int buttonPin = 6;
const int oneWirePin = 7;
const int chipSelect = 10;

#define DEBOUNCE 10
#define BUFSIZE 32

// ----- GLOBALS -----
RTC_DS1307 RTC;
OneWire oneWire(oneWirePin);
DallasTemperature sensors(&oneWire);

uint16_t   delta = 10; // measurement delta in seconds
uint32_t   next_ts;

static uint16_t year;
static uint8_t month, day, hour, minute, second;

Bounce logToggleButton;

File file;

// offsets:    0123456789012
byte name[] = "yymmdd_x.log";

// ----- FUNCTIONS -----
static void led(int pin, int on)
{
	digitalWrite(pin, on ? HIGH : LOW);
}

// fatal error - blink led and wait for reset
static void fail() {
	while(1) {
		led(ledRedPin, 1);
		delay(200);
		led(ledRedPin, 0);
		delay(200);
	}
}

static int sd_init()
{
	pinMode(chipSelect, OUTPUT);
	//if (!SD.begin(chipSelect)) {
	if (!SD.begin(10,11,12,13)) {
		Serial.println("SD init failed");
		fail();
	}
}

static void rtc_init()
{
	Wire.begin();
	RTC.begin();

	if (! RTC.isrunning()) {
		Serial.println("RTC is NOT running!");
	}

	// get value for first measurement
	next_ts = RTC.now().unixtime();
}

static uint16_t parse_dec(byte *buf, byte num)
{
	uint16_t val = 0;
	for(byte i=0;i<num;i++) {
		val = val * 10;
		if ((buf[i] >= '0')&&(buf[i] <= '9')) {
			byte v = buf[i] - '0';
			val += v;
		} else {
			return 0xffff;
		}
	}
	return val;
}

static void to_dec(uint16_t val, byte *buf, byte num)
{
	byte *ptr = buf + num - 1;
	for(byte i=0;i<num;i++) {
		byte r = val % 10;
		val = val / 10;
		*(ptr--) = '0' + r;
	}
}

static void store_name()
{
	DateTime now = RTC.now();
	to_dec(now.year(),name,2);
	to_dec(now.month(),name+2,2);
	to_dec(now.day(),name+4,2);
}

static byte log_find_name()
{
	store_name();
	for(int i=0;i<26;i++) {
		name[7] = 'a' + i;
		if (!SD.exists((char *)name)) {
			return 1;
		}
	}
	return 0;
}

static byte log_open()
{
	// log already open!
	if (file) {
		return 1;
	}
	// try to find name
	if (!log_find_name()) {
		return 2;
	}
	file = SD.open((char *)name, FILE_WRITE);
	if (!file) {
		return 3;
	}

	Serial.print("O: ");
	Serial.println((char *)name);
	return 0;
}

static byte log_close()
{
	// log is not open!
	if (!file) {
		return 1;
	}
	file.close();

	Serial.print("C: ");
	Serial.println((char *)name);
	return 0;
}

static void store_byte_val(byte v, byte cmd)
{
	switch (cmd) {
		case 'm': month = v; break;
		case 'd': day = v; break;
		case 'H': hour = v; break;
		case 'M': minute = v; break;
		case 'S': second = v; break;
	}
}

static void store_word_val(uint16_t v, byte cmd)
{
	switch (cmd) {
		case 'y': year = v; break;
		case 'D': delta = v; break;
	}
}

static void adjust_clock()
{
	DateTime set(year,month,day,hour,minute,second);
	RTC.adjust(set);

	// check new time
	uint32_t ts = RTC.now().unixtime();

	// update next time
	next_ts = ts + delta;
}

static void print_time()
{
	DateTime now = RTC.now();
	Serial.print(now.year(), DEC);
	Serial.print('/');
	Serial.print(now.month(), DEC);
	Serial.print('/');
	Serial.print(now.day(), DEC);
	Serial.print(' ');
	Serial.print(now.hour(), DEC);
	Serial.print(':');
	Serial.print(now.minute(), DEC);
	Serial.print(':');
	Serial.print(now.second(), DEC);
	Serial.println(" UTC");
}

const byte ERR_CMD = 9;
const byte ERR_SYNTAX = 8;
const byte OK = 0;

static byte handle_command(char *buf, int len)
{
	uint16_t v;
	switch (buf[0]) {
		case 'y': // set year
		case 'D': // set delta
			if (len==5) {
				v = parse_dec((byte*) buf+1,4);
				if (v==0xffff) {
					return ERR_SYNTAX;
				}
				Serial.write(buf[0]);
				Serial.println(v);
				store_word_val(v,buf[0]);
			} else {
				return ERR_SYNTAX;
			}
			break;
		case 'm': // set month
		case 'd': // set day
		case 'H': // set HOUR
		case 'M': // set MINUTE
		case 'S': // set SECOND
			if (len==3) {
				v = parse_dec((byte*) buf+1,2);
				if (v==0xffff) {
					return ERR_SYNTAX;
				}
				Serial.write(buf[0]);
				Serial.println(v);
				store_byte_val((byte)v,buf[0]);
			} else {
				return ERR_SYNTAX;
			}
			break;
		case 'a': // adjust clock
			adjust_clock();
			break;
		case 'o': // open log
			return log_open();
		case 'c': // close log
			return log_close();
		case 'r': // read clock
			print_time();
			break;
		default:
			return ERR_CMD;
	}
	return OK;
}

static void serial_in()
{
	// read serial
	if (Serial.available()) {
		char buf[BUFSIZE];
		int len = Serial.readBytesUntil('\n', buf, sizeof(buf));
		byte err = handle_command(buf, len);
		if (err == 0) {
			Serial.println("OK");
		} else {
			Serial.print("ERR");
			Serial.print(err);
			Serial.println();
		}
	}
}

static void handle_button(void)
{
	if (file) {
		log_close();
	} else {
		log_open();
	}
}

// ----- MAIN -----
void setup () {
	Serial.begin(9600);

	//while (!Serial) {
		//; // wait for serial port to connect. Needed for Leonardo only
	//}

	Serial.println("Starting up");

	pinMode(buttonPin, INPUT_PULLUP);
	logToggleButton = Bounce(buttonPin, DEBOUNCE);

	pinMode(ledRedPin, OUTPUT);
	pinMode(ledGreenPin, OUTPUT);

	rtc_init();
	sd_init();
}

void loop () {
	led(ledRedPin, file ? 1 : 0);

	serial_in();

	logToggleButton.update();
	if (logToggleButton.fallingEdge()) {
		handle_button();
	}

	uint32_t ts = RTC.now().unixtime();

	if (ts >= next_ts) {
		led(ledGreenPin, 1);
		next_ts += delta;
		// do measurement
		sensors.requestTemperatures();
		float t = sensors.getTempCByIndex(0);
		char temp[BUFSIZE];

		// format: <timestamp> t:1=<temp>
		String line = "";
		line += ts;

		line += " t:1=";
		dtostrf(t, 5, 2, temp);
		line += temp;

		Serial.println(line);
		if (file) {
			file.println(line);
			file.flush();
		}
		led(ledGreenPin, 0);
	}
}