-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnopeusmittari.c
398 lines (347 loc) · 10.5 KB
/
nopeusmittari.c
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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
#include <stdio.h>
#include <string.h>
#include <math.h>
#include "pico/stdlib.h"
#include "hardware/i2c.h"
#include "pico/binary_info.h"
#include "rgb_lcd.h"
#include "DHT20.h"
// SD
#include "f_util.h"
#include "ff.h"
#include "pico/stdlib.h"
#include "rtc.h"
//
#include "hw_config.h"
#ifndef OPTOENCODER_GPIO_PIN
#define OPTOENCODER_GPIO_PIN 22
#endif
// Rim length in millimeters, distance traveled with single rotation
// defaults to 700x28c/28-622 = (635 + 28 + 28) * 3.14159 ≈ 2170
// Define to length per rotation
#ifndef LENGTH_PER_ROTATION
#define LENGTH_PER_ROTATION 2170
#endif
// Pulses per rotation, for different types of encoding disks
#ifndef PULSES_PER_ROTATION
#define PULSES_PER_ROTATION 1
#endif
// Use alt pins 8, 9 for i2c, since that's what the grove shield uses
#define I2C0_SDA 8
#define I2C0_SCL 9
/*
Static entries for str data. Stored in program memory.
*/
static const char __in_flash() startmsg_line_1[12] = "Speedometer";
static const char __in_flash() startmsg_line_2[12] = "starting...";
static const char __in_flash() speedmsg[8] = "Speed: ";
static const char __in_flash() kmh[5] = "km/h";
static const char __in_flash() celsius[3] = "c ";
static const char __in_flash() perrh[4] = "RH%";
/*
Using global variables for calculation information to allow using just
callbacks for looping.
*/
char curspd_format_buf[6] = "0.000"; // Current speed string
char curtemp_format_buf[6] = "0.000"; // Current temperature string
char curhumid_format_buf[6] = "0.000"; // Current humidity string
float speed_ms = 0.00; // Current speed value
bool opto_status = 0; // optoencoder status
bool opto_status_last_tick = 0; // optoencoder status in previous tick
uint32_t time_of_last_edge = 0; // elapsed time since last accepted falling edge
repeating_timer_t timerinfo;
Displaystate *disp = NULL;
DHT20 sensStruct;
DHT20 *sens = &sensStruct;
/*
Initialize the csv file.
*/
void init_sd_card_file() {
char full_print_string[30] = "Speed,Temperature,Humidity\n";
sd_card_t *pSD = sd_get_by_num(0);
FRESULT fr = f_mount(&pSD->fatfs, pSD->pcName, 1);
if (FR_OK != fr) {
panic("f_mount error: %s (%d)\n", FRESULT_str(fr), fr);
}
FIL fil;
const char filename[16] = "sensor_data.csv";
fr = f_open(&fil, filename, FA_WRITE);
if (FR_OK != fr && FR_EXIST != fr)
panic("f_open(%s) error: %s (%d)\n", filename, FRESULT_str(fr), fr);
if (f_printf(&fil,full_print_string) < 0) {
printf("f_printf failed\n");
}
fr = f_close(&fil);
if (FR_OK != fr) {
printf("f_close error: %s (%d)\n", FRESULT_str(fr), fr);
}
f_unmount(pSD->pcName);
}
/*
Dump latest records to sd card.
*/
void write_to_sd_card() {
char full_print_string[30] = "";
sprintf(
full_print_string,
"%3.2f,%3.2f,%3.2f\n",
speed_ms,
getTemperature(sens),
getHumidity(sens)
);
// printf("Writing following string to SD Card: %s", full_print_string);
// printf("The amount of SD cards on list is: %s\n", sd_get_num());
printf("Opening sdcard 0.\n");
sd_card_t *pSD = sd_get_by_num(0);
printf("Got sdcard 0.\n");
FRESULT fr = f_mount(&pSD->fatfs, pSD->pcName, 1);
printf("Mounted sdcard 0.\n");
if (FR_OK != fr) {
panic("f_mount error: %s (%d)\n", FRESULT_str(fr), fr);
}
FIL fil;
const char filename[16] = "sensor_data.csv";
fr = f_open(&fil, filename, FA_OPEN_APPEND | FA_WRITE);
printf("Opened file %s.\n", filename);
if (FR_OK != fr && FR_EXIST != fr)
panic("f_open(%s) error: %s (%d)\n", filename, FRESULT_str(fr), fr);
if (f_printf(&fil,full_print_string) < 0) {
printf("f_printf failed\n");
}
fr = f_close(&fil);
printf("Closed the file.");
if (FR_OK != fr) {
printf("f_close error: %s (%d)\n", FRESULT_str(fr), fr);
}
f_unmount(pSD->pcName);
printf("Unmounted the file.");
}
/*
Handle interrupts generated by optoencoder input pin.
*/
void opto_interrupt_callback(uint gpio, uint32_t event_mask) {
uint32_t tick_duration = to_ms_since_boot(get_absolute_time()) - time_of_last_edge;
// Tick under 100ms would amount to 80 kmh, this shouldn't happen
// in normal operation. Thus, we'll use this as ceiling for operational
// calculations to easily ignore possible noise in edges.
if (tick_duration < 100) {
return;
}
printf("Flagging a falling edge from speed sensor with duration of %dms.\n", tick_duration);
speed_ms = ((float)LENGTH_PER_ROTATION / (float)PULSES_PER_ROTATION / (float)tick_duration) * 3.6;
// handle weird edge cases with elapsed time of zero, shouldn't happen
// in current implementation using internal clock.
if (isinf(speed_ms)) {
printf("Ignoring infinite speed from 0 elapsed time.");
speed_ms = 0.0;
}
time_of_last_edge = to_ms_since_boot(get_absolute_time());
}
/*
Callback for screen refresh, meant to run on 250ms intervals.
Repeating.
*/
bool screen_callback(repeating_timer_t *rt)
{
// Refresh buffers
sprintf(curspd_format_buf, "%3.2f", speed_ms);
sprintf(curtemp_format_buf, "%3.2f", getTemperature(sens));
sprintf(curhumid_format_buf, "%3.2f", getHumidity(sens));
// Update displayed speed
setCursor(disp, 7, 0);
for (uint32_t c = 0; c < 4; c++)
{
write(disp, curspd_format_buf[c]);
}
// Update displayed temperature and humidity
setCursor(disp, 0, 1);
for (uint32_t c = 0; c < 5; c++)
{
write(disp, curtemp_format_buf[c]);
}
setCursor(disp, 7, 1);
for (uint32_t c = 0; c < 5; c++) {
write(disp, curhumid_format_buf[c]);
}
return true;
}
// Pre-declare retrieval since retrieval and refresh call each other
int64_t temperature_retrieval_callback(alarm_id_t, void *);
/*
Callback for temperature refresh, meant to run on 2000ms intervals.
Sets alarm for temperature measurement retrieval.
*/
int64_t temperature_refresh_callback(alarm_id_t id, void *user_data)
{
startMeasurement(sens);
add_alarm_in_ms(
60,
temperature_retrieval_callback,
NULL,
true
);
return 0;
}
/*
Callback for temperature retrieval, meant to run on 2000ms intervals.
Sets alarm for temperature measurement refresh.
*/
int64_t temperature_retrieval_callback(alarm_id_t id, void *user_data)
{
if (readMeasurement(sens) == DHT20_ERROR_BUSY)
{
printf("Temperature measurement failed.\n");
printf("Trying again after 10ms.\n");
add_alarm_in_ms(
10,
temperature_retrieval_callback,
NULL,
true
);
}
else
{
convert(sens);
add_alarm_in_ms(
2000,
temperature_refresh_callback,
NULL,
true
);
}
return 0;
}
/*
Setup relevant RP2040 features and display boot messages.
*/
int setup()
{
// Set up stdio
stdio_init_all();
time_init();
sleep_ms(500);
printf("Running controller setup.\n");
#ifndef PICO_DEFAULT_LED_PIN
#warning blink example requires a board with a regular LED
#else
// set internal led as debug output for pulse
printf("Adding default led pin as pulse flag.\n");
gpio_init(PICO_DEFAULT_LED_PIN);
gpio_set_dir(PICO_DEFAULT_LED_PIN, GPIO_OUT);
gpio_put(PICO_DEFAULT_LED_PIN, false);
printf("Added default led pin as pulse flag.\n");
#endif
printf("Initializing optoencoder input pin.\n");
// set GP22 as input for optoencoder pulse
gpio_init(OPTOENCODER_GPIO_PIN);
gpio_set_dir(OPTOENCODER_GPIO_PIN, GPIO_IN);
gpio_set_pulls(OPTOENCODER_GPIO_PIN, true, false);
printf("Enabling optoencoder pin input hysteresis.\n");
gpio_set_input_hysteresis_enabled(OPTOENCODER_GPIO_PIN, true);
printf("Initialized optoencoder input pin.\n");
printf("Adding optoencoder interrupt handler.\n");
gpio_set_irq_enabled_with_callback(
OPTOENCODER_GPIO_PIN,
GPIO_IRQ_EDGE_FALL,
true,
opto_interrupt_callback
);
printf("Setting up i2c\n");
// setup i2c
i2c_init(i2c0, 100 * 1000);
gpio_set_function(I2C0_SDA, GPIO_FUNC_I2C);
gpio_set_function(I2C0_SCL, GPIO_FUNC_I2C);
gpio_pull_up(I2C0_SDA);
gpio_pull_up(I2C0_SCL);
// Make the I2C pins available to picotool
bi_decl(bi_2pins_with_func(I2C0_SDA, I2C0_SCL, GPIO_FUNC_I2C));
printf("Set up i2c.\n");
// Setup Grove LCD monitor
printf("Create grove lcd display struct.\n");
disp = rgb_lcd();
printf("Initialize grove lcd display struct.\n");
begin(disp, 16, 2);
// Set up temp and humid sensor
printf("Initialize DHT20.\n");
DHT20_init(sens);
printf("Initialized DHT20.\n");
// Write initialization message
printf("Initialize cursor to start.\n");
setCursor(disp, 0, 0);
printf("Blink display.\n");
noDisplay(disp);
sleep_ms(1000);
display(disp);
printf("Blinked display.\n");
printf("Setting up scrolling.\n");
leftToRight(disp);
noAutoscroll(disp);
printf("Set up scrolling.\n");
printf("Writing startup message.\n");
for (uint32_t c = 0; c < 11; c++)
{
write(disp, startmsg_line_1[c]);
sleep_ms(100);
}
setCursor(disp, 0, 1);
for (uint32_t c = 0; c < 11; c++)
{
write(disp, startmsg_line_2[c]);
sleep_ms(100);
}
sleep_ms(2000);
// LCD is infuriatingly slow to update -> write static messages on screen
// and only update the changing information
// Pre-write speed information
clear(disp);
setCursor(disp, 0, 0);
for (uint32_t c = 0; c < 7; c++)
{
write(disp, speedmsg[c]);
}
setCursor(disp, 12, 0);
for (uint32_t c = 0; c < 4; c++)
{
write(disp, kmh[c]);
}
// Pre-write temp and humidity units
setCursor(disp, 5, 1);
for (uint32_t c = 0; c < 2; c++) {
write(disp, celsius[c]);
}
setCursor(disp, 12, 1);
for (uint32_t c = 0; c < 3; c++) {
write(disp, perrh[c]);
}
setCursor(disp, 0, 0);
printf("Speedometer initialization successful.\n");
init_sd_card_file();
return 0;
}
/*
Main starts the timers and sleeps indefenetly.
*/
int main()
{
int ret;
ret = setup();
// In case we add failure conditions after setup, handle them after
// label "failover"
if (ret)
goto failover;
// start timer loops
temperature_refresh_callback(0, NULL);
add_repeating_timer_ms(
500,
screen_callback,
NULL,
&timerinfo
);
for (;;) {
sleep_ms(1000);
write_to_sd_card();
}
return 0;
failover:
return ret;
}