-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSD_example_data_logger.spin2
More file actions
207 lines (170 loc) · 7.91 KB
/
Copy pathSD_example_data_logger.spin2
File metadata and controls
207 lines (170 loc) · 7.91 KB
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
{Spin2_v45}
'' =========================================================================================
''
'' File....... SD_example_data_logger.spin2
'' Purpose.... Data logging example with append and sync for power-fail safety
'' Author..... Stephen M Moraco
'' E-mail..... stephen@ironsheep.biz
'' Started.... 25 FEB 2026
'' Updated.... 12 AUG 2026
''
'' =========================================================================================
{ Description:
This example demonstrates a data logging pattern:
1. Mount the card and create a LOGS directory
2. Open an existing log file for append (or create a new one)
3. Write log entries with periodic sync for power-fail safety
4. Close and unmount cleanly
Key concepts shown:
- openFileWrite() positions at end of file (append mode)
- syncHandle() flushes data to card without closing the file
- Directory creation with existence check
}
CON
_CLKFREQ = 350_000_000
SD_BASE = 56
SD_SCK = SD_BASE + 5
SD_CS = SD_BASE + 4
SD_MOSI = SD_BASE + 3
SD_MISO = SD_BASE + 2
MAX_ENTRIES = 20 ' Number of log entries to write
SYNC_INTERVAL = 5 ' Sync every N entries
CSV_HEADER_LEN = 11 ' Length of "Entry,Value"
CHAR_CR = 13 ' Carriage Return
CHAR_LF = 10 ' Line Feed
SENSOR_RANGE_MASK = $3FF ' 10-bit sensor mask (0-1023)
MAX_DECIMAL_DIVISOR = 1_000_000_000 ' Largest power of 10 for 32-bit formatting
DEBUG_DISABLE = 0
OBJ
sd : "micro_sd_fat32_fs"
VAR
byte msg[80]
PUB go() | handle, idx, result, entries_written
'' Main entry point -- creates a LOGS directory and writes MAX_ENTRIES CSV log entries with periodic sync.
' @local handle - File handle for the log file
' @local idx - Loop index for writing log entries
debug("=== SD Data Logger Example ===")
if sd.mount(SD_CS, SD_MOSI, SD_MISO, SD_SCK) >= 0
' Set timestamp for file creation
sd.setDate(2026, 2, 25, 12, 0, 0)
' Create LOGS directory (ignore error if it already exists)
if sd.changeDirectory(@"LOGS") < 0
sd.newDirectory(@"LOGS")
sd.changeDirectory(@"LOGS")
' Open existing log for append, or create new
handle := sd.openFileWrite(@"DATALOG.CSV")
if handle < 0
' File doesn't exist yet -- create it with a header
handle := sd.createFileNew(@"DATALOG.CSV")
if handle >= 0
sd.writeHandle(handle, @"Entry,Value", CSV_HEADER_LEN)
sd.writeHandle(handle, @CRLF, 2)
if handle >= 0
debug("Log file open, writing ", udec(MAX_ENTRIES), " entries...")
' Write log entries
entries_written := 0
repeat idx from 1 to MAX_ENTRIES
' Format a simple CSV line: "N,reading"
result := writeLogEntry(handle, idx, getReading())
if result < 0
debug(" Write FAILED at entry ", udec(idx), ", error: ", sdec(result))
quit
entries_written++
' Periodic sync -- ensures data survives power loss
if idx // SYNC_INTERVAL == 0
result := sd.syncHandle(handle)
if result < 0
debug(" Sync FAILED at entry ", udec(idx), ", error: ", sdec(result))
quit
debug(" Synced at entry ", udec(idx))
' A long-running logger should also watch the BACKGROUND flush.
' The driver flushes a dirty handle on its own during idle windows,
' and if one of those writes fails there is no call for it to
' return through -- lastFlushError() is where that outcome lands.
' Polling it is what turns a silent card failure into a noticed one.
result := sd.lastFlushError()
if result < 0
debug(" Background flush FAILED before entry ", udec(idx), ", error: ", sdec(result))
quit
' closeFileHandle() flushes; its status says whether the tail landed.
result := sd.closeFileHandle(handle)
if result < 0
debug("Close FAILED, error: ", sdec(result), " -- final entries may not be on the card")
else
debug("Log file closed -- ", udec(entries_written), " entries on the card")
else
debug("Cannot create log file, error: ", sdec(handle))
' Return to root before unmount
sd.changeDirectory(@"/")
sd.unmount()
debug("=== Done -- ", udec(MAX_ENTRIES), " entries logged ===")
else
debug("Mount FAILED")
PRI writeLogEntry(handle, entry_num, value) : status | len
' Format one CSV line "entry_num,value\r\n" and write it to the log file.
' @param handle - File handle for the open log file
' @param entry_num - Entry sequence number to write
' @param value - Sensor reading value to log
' @returns status - bytes written, or a negative error code from writeHandle()
' @local len - Running byte count for the formatted message
len := 0
len += formatDec(@msg + len, entry_num)
msg[len++] := ","
len += formatDec(@msg + len, value)
msg[len++] := CHAR_CR
msg[len++] := CHAR_LF
status := sd.writeHandle(handle, @msg, len)
if status <> len
debug(" short write: ", sdec(status), " of ", udec(len), " bytes")
PRI getReading() : value
' Simulate a sensor reading -- returns a random value 0-1023.
' @returns value - Simulated sensor reading (0-1023)
value := getrnd() & SENSOR_RANGE_MASK ' Random 0-1023
PRI formatDec(p_buf, val) : len | digit, started, divisor
' Format an integer as decimal ASCII into a buffer and return the character count.
' @param p_buf - Pointer to destination byte buffer
' @param val - Integer value to format (handles negative values)
' @returns len - Number of characters written to the buffer
' @local digit - Current digit value (0-9) during formatting
' @local started - Flag indicating leading zeros have been passed
' @local divisor - Current power of 10 being extracted
len := 0
if val < 0
byte[p_buf] := "-"
p_buf++
len++
val := -val
started := false
divisor := MAX_DECIMAL_DIVISOR
repeat 10
digit := val / divisor
val //= divisor
divisor /= 10
if digit > 0 or started or divisor == 0
byte[p_buf] := "0" + digit
p_buf++
len++
started := true
DAT
CRLF byte 13, 10
con { license }
{{
=================================================================================================
Terms of Use: MIT License
Copyright (c) 2026 Iron Sheep Productions, LLC
Permission is hereby granted, free of charge, to any person obtaining a copy of this
software and associated documentation files (the "Software"), to deal in the Software
without restriction, including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be included in all copies
or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
=================================================================================================
}}