Added Dataflash operational checks and aborts to all projects using the Dataflash...
[pub/lufa.git] / Projects / TempDataLogger / TempDataLogger.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2012.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.lufa-lib.org
7 */
8
9 /*
10 Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
12 Permission to use, copy, modify, distribute, and sell this
13 software and its documentation for any purpose is hereby granted
14 without fee, provided that the above copyright notice appear in
15 all copies and that both that the copyright notice and this
16 permission notice and warranty disclaimer appear in supporting
17 documentation, and that the name of the author not be used in
18 advertising or publicity pertaining to distribution of the
19 software without specific, written prior permission.
20
21 The author disclaim all warranties with regard to this
22 software, including all implied warranties of merchantability
23 and fitness. In no event shall the author be liable for any
24 special, indirect or consequential damages or any damages
25 whatsoever resulting from loss of use, data or profits, whether
26 in an action of contract, negligence or other tortious action,
27 arising out of or in connection with the use or performance of
28 this software.
29 */
30
31 /** \file
32 *
33 * Main source file for the TemperatureDataLogger project. This file contains the main tasks of
34 * the project and is responsible for the initial application hardware configuration.
35 */
36
37 #include "TempDataLogger.h"
38
39 /** LUFA Mass Storage Class driver interface configuration and state information. This structure is
40 * passed to all Mass Storage Class driver functions, so that multiple instances of the same class
41 * within a device can be differentiated from one another.
42 */
43 USB_ClassInfo_MS_Device_t Disk_MS_Interface =
44 {
45 .Config =
46 {
47 .InterfaceNumber = 0,
48
49 .DataINEndpointNumber = MASS_STORAGE_IN_EPNUM,
50 .DataINEndpointSize = MASS_STORAGE_IO_EPSIZE,
51 .DataINEndpointDoubleBank = false,
52
53 .DataOUTEndpointNumber = MASS_STORAGE_OUT_EPNUM,
54 .DataOUTEndpointSize = MASS_STORAGE_IO_EPSIZE,
55 .DataOUTEndpointDoubleBank = false,
56
57 .TotalLUNs = 1,
58 },
59 };
60
61 /** Buffer to hold the previously generated HID report, for comparison purposes inside the HID class driver. */
62 static uint8_t PrevHIDReportBuffer[GENERIC_REPORT_SIZE];
63
64 /** LUFA HID Class driver interface configuration and state information. This structure is
65 * passed to all HID Class driver functions, so that multiple instances of the same class
66 * within a device can be differentiated from one another.
67 */
68 USB_ClassInfo_HID_Device_t Generic_HID_Interface =
69 {
70 .Config =
71 {
72 .InterfaceNumber = 1,
73
74 .ReportINEndpointNumber = GENERIC_IN_EPNUM,
75 .ReportINEndpointSize = GENERIC_EPSIZE,
76 .ReportINEndpointDoubleBank = false,
77
78 .PrevReportINBuffer = PrevHIDReportBuffer,
79 .PrevReportINBufferSize = sizeof(PrevHIDReportBuffer),
80 },
81 };
82
83 /** Non-volatile Logging Interval value in EEPROM, stored as a number of 500ms ticks */
84 static uint8_t EEMEM LoggingInterval500MS_EEPROM = DEFAULT_LOG_INTERVAL;
85
86 /** SRAM Logging Interval value fetched from EEPROM, stored as a number of 500ms ticks */
87 static uint8_t LoggingInterval500MS_SRAM;
88
89 /** Total number of 500ms logging ticks elapsed since the last log value was recorded */
90 static uint16_t CurrentLoggingTicks;
91
92 /** FAT Fs structure to hold the internal state of the FAT driver for the Dataflash contents. */
93 static FATFS DiskFATState;
94
95 /** FAT Fs structure to hold a FAT file handle for the log data write destination. */
96 static FIL TempLogFile;
97
98
99 /** ISR to handle the 500ms ticks for sampling and data logging */
100 ISR(TIMER1_COMPA_vect, ISR_BLOCK)
101 {
102 uint8_t LEDMask = LEDs_GetLEDs();
103
104 /* Check to see if the logging interval has expired */
105 if (++CurrentLoggingTicks < LoggingInterval500MS_SRAM)
106 return;
107
108 /* Reset log tick counter to prepare for next logging interval */
109 CurrentLoggingTicks = 0;
110
111 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
112
113 /* Only log when not connected to a USB host */
114 if (USB_DeviceState == DEVICE_STATE_Unattached)
115 {
116 TimeDate_t CurrentTimeDate;
117 DS1307_GetTimeDate(&CurrentTimeDate);
118
119 char LineBuffer[100];
120 uint16_t BytesWritten;
121
122 BytesWritten = sprintf(LineBuffer, "%02d/%02d/20%02d, %02d:%02d:%02d, %d Degrees\r\n",
123 CurrentTimeDate.Day, CurrentTimeDate.Month, CurrentTimeDate.Year,
124 CurrentTimeDate.Hour, CurrentTimeDate.Minute, CurrentTimeDate.Second,
125 Temperature_GetTemperature());
126
127 f_write(&TempLogFile, LineBuffer, BytesWritten, &BytesWritten);
128 f_sync(&TempLogFile);
129 }
130
131 LEDs_SetAllLEDs(LEDMask);
132 }
133
134 /** Main program entry point. This routine contains the overall program flow, including initial
135 * setup of all components and the main program loop.
136 */
137 int main(void)
138 {
139 SetupHardware();
140
141 /* Fetch logging interval from EEPROM */
142 LoggingInterval500MS_SRAM = eeprom_read_byte(&LoggingInterval500MS_EEPROM);
143
144 /* Check if the logging interval is invalid (0xFF) indicating that the EEPROM is blank */
145 if (LoggingInterval500MS_SRAM == 0xFF)
146 LoggingInterval500MS_SRAM = DEFAULT_LOG_INTERVAL;
147
148 /* Mount and open the log file on the Dataflash FAT partition */
149 OpenLogFile();
150
151 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
152 sei();
153
154 for (;;)
155 {
156 MS_Device_USBTask(&Disk_MS_Interface);
157 HID_Device_USBTask(&Generic_HID_Interface);
158 USB_USBTask();
159 }
160 }
161
162 /** Opens the log file on the Dataflash's FAT formatted partition according to the current date */
163 void OpenLogFile(void)
164 {
165 char LogFileName[12];
166
167 /* Get the current date for the filename as "DDMMYY.csv" */
168 TimeDate_t CurrentTimeDate;
169 DS1307_GetTimeDate(&CurrentTimeDate);
170 sprintf(LogFileName, "%02d%02d%02d.csv", CurrentTimeDate.Day, CurrentTimeDate.Month, CurrentTimeDate.Year);
171
172 /* Mount the storage device, open the file */
173 f_mount(0, &DiskFATState);
174 f_open(&TempLogFile, LogFileName, FA_OPEN_ALWAYS | FA_WRITE);
175 f_lseek(&TempLogFile, TempLogFile.fsize);
176 }
177
178 /** Closes the open data log file on the Dataflash's FAT formatted partition */
179 void CloseLogFile(void)
180 {
181 /* Sync any data waiting to be written, unmount the storage device */
182 f_sync(&TempLogFile);
183 f_close(&TempLogFile);
184 }
185
186 /** Configures the board hardware and chip peripherals for the demo's functionality. */
187 void SetupHardware(void)
188 {
189 /* Disable watchdog if enabled by bootloader/fuses */
190 MCUSR &= ~(1 << WDRF);
191 wdt_disable();
192
193 /* Disable clock division */
194 clock_prescale_set(clock_div_1);
195
196 /* Hardware Initialization */
197 LEDs_Init();
198 SPI_Init(SPI_SPEED_FCPU_DIV_2 | SPI_SCK_LEAD_FALLING | SPI_SAMPLE_TRAILING | SPI_MODE_MASTER);
199 ADC_Init(ADC_FREE_RUNNING | ADC_PRESCALE_128);
200 Temperature_Init();
201 Dataflash_Init();
202 USB_Init();
203 TWI_Init(TWI_BIT_PRESCALE_4, TWI_BITLENGTH_FROM_FREQ(4, 50000));
204
205 /* 500ms logging interval timer configuration */
206 OCR1A = (((F_CPU / 1024) / 2) - 1);
207 TCCR1B = (1 << WGM12) | (1 << CS12) | (1 << CS10);
208 TIMSK1 = (1 << OCIE1A);
209
210 /* Check if the Dataflash is working, abort if not */
211 if (!(DataflashManager_CheckDataflashOperation()))
212 {
213 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
214 for(;;);
215 }
216
217 /* Clear Dataflash sector protections, if enabled */
218 DataflashManager_ResetDataflashProtections();
219 }
220
221 /** Event handler for the library USB Connection event. */
222 void EVENT_USB_Device_Connect(void)
223 {
224 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
225
226 /* Close the log file so that the host has exclusive filesystem access */
227 CloseLogFile();
228 }
229
230 /** Event handler for the library USB Disconnection event. */
231 void EVENT_USB_Device_Disconnect(void)
232 {
233 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
234
235 /* Mount and open the log file on the Dataflash FAT partition */
236 OpenLogFile();
237 }
238
239 /** Event handler for the library USB Configuration Changed event. */
240 void EVENT_USB_Device_ConfigurationChanged(void)
241 {
242 bool ConfigSuccess = true;
243
244 ConfigSuccess &= HID_Device_ConfigureEndpoints(&Generic_HID_Interface);
245 ConfigSuccess &= MS_Device_ConfigureEndpoints(&Disk_MS_Interface);
246
247 LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
248 }
249
250 /** Event handler for the library USB Control Request reception event. */
251 void EVENT_USB_Device_ControlRequest(void)
252 {
253 MS_Device_ProcessControlRequest(&Disk_MS_Interface);
254 HID_Device_ProcessControlRequest(&Generic_HID_Interface);
255 }
256
257 /** Mass Storage class driver callback function the reception of SCSI commands from the host, which must be processed.
258 *
259 * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface configuration structure being referenced
260 */
261 bool CALLBACK_MS_Device_SCSICommandReceived(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
262 {
263 bool CommandSuccess;
264
265 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
266 CommandSuccess = SCSI_DecodeSCSICommand(MSInterfaceInfo);
267 LEDs_SetAllLEDs(LEDMASK_USB_READY);
268
269 return CommandSuccess;
270 }
271
272 /** HID class driver callback function for the creation of HID reports to the host.
273 *
274 * \param[in] HIDInterfaceInfo Pointer to the HID class interface configuration structure being referenced
275 * \param[in,out] ReportID Report ID requested by the host if non-zero, otherwise callback should set to the generated report ID
276 * \param[in] ReportType Type of the report to create, either HID_REPORT_ITEM_In or HID_REPORT_ITEM_Feature
277 * \param[out] ReportData Pointer to a buffer where the created report should be stored
278 * \param[out] ReportSize Number of bytes written in the report (or zero if no report is to be sent)
279 *
280 * \return Boolean true to force the sending of the report, false to let the library determine if it needs to be sent
281 */
282 bool CALLBACK_HID_Device_CreateHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo,
283 uint8_t* const ReportID,
284 const uint8_t ReportType,
285 void* ReportData,
286 uint16_t* const ReportSize)
287 {
288 Device_Report_t* ReportParams = (Device_Report_t*)ReportData;
289
290 DS1307_GetTimeDate(&ReportParams->TimeDate);
291
292 ReportParams->LogInterval500MS = LoggingInterval500MS_SRAM;
293
294 *ReportSize = sizeof(Device_Report_t);
295 return true;
296 }
297
298 /** HID class driver callback function for the processing of HID reports from the host.
299 *
300 * \param[in] HIDInterfaceInfo Pointer to the HID class interface configuration structure being referenced
301 * \param[in] ReportID Report ID of the received report from the host
302 * \param[in] ReportType The type of report that the host has sent, either HID_REPORT_ITEM_Out or HID_REPORT_ITEM_Feature
303 * \param[in] ReportData Pointer to a buffer where the received report has been stored
304 * \param[in] ReportSize Size in bytes of the received HID report
305 */
306 void CALLBACK_HID_Device_ProcessHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo,
307 const uint8_t ReportID,
308 const uint8_t ReportType,
309 const void* ReportData,
310 const uint16_t ReportSize)
311 {
312 Device_Report_t* ReportParams = (Device_Report_t*)ReportData;
313
314 DS1307_SetTimeDate(&ReportParams->TimeDate);
315
316 /* If the logging interval has changed from its current value, write it to EEPROM */
317 if (LoggingInterval500MS_SRAM != ReportParams->LogInterval500MS)
318 {
319 LoggingInterval500MS_SRAM = ReportParams->LogInterval500MS;
320 eeprom_update_byte(&LoggingInterval500MS_EEPROM, LoggingInterval500MS_SRAM);
321 }
322 }
323