Enhance TemperatureDatalogger project -- add RTC capabilities so that data is logged...
[pub/lufa.git] / Projects / TemperatureDataLogger / TempDataLogger.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2010.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2010 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 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 uint8_t EEMEM LoggingInterval500MS_EEPROM;
85
86 /** SRAM Logging Interval value fetched from EEPROM, stored as a number of 500ms ticks */
87 uint8_t LoggingInterval500MS_SRAM;
88
89 /** Total number of 500ms logging ticks elapsed since the last log value was recorded */
90 uint16_t CurrentLoggingTicks;
91
92 /** FAT Fs structure to hold the internal state of the FAT driver for the dataflash contents. */
93 FATFS DiskFATState;
94
95 /** FAT Fs structure to hold a FAT file handle for the log data write destination. */
96 FIL TempLogFile;
97
98
99 ISR(TIMER1_COMPA_vect, ISR_BLOCK)
100 {
101 uint8_t LEDMask = LEDs_GetLEDs();
102
103 /* Check to see if the logging interval has expired */
104 if (CurrentLoggingTicks++ < LoggingInterval500MS_SRAM)
105 return;
106
107 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
108
109 /* Reset log tick counter to prepare for next logging interval */
110 CurrentLoggingTicks = 0;
111
112 if (USB_DeviceState == DEVICE_STATE_Unattached)
113 {
114 uint8_t Day, Month, Year;
115 uint8_t Hour, Minute, Second;
116
117 DS1307_GetDate(&Day, &Month, &Year);
118 DS1307_GetTime(&Hour, &Minute, &Second);
119
120 char LineBuffer[100];
121 uint16_t BytesWritten;
122
123 BytesWritten = sprintf(LineBuffer, "%02d/%02d/20%04d, %02d:%02d:%02d, %d Degrees\r\n",
124 Day, Month, Year, Hour, Minute, Second, Temperature_GetTemperature());
125
126 f_write(&TempLogFile, LineBuffer, BytesWritten, &BytesWritten);
127 f_sync(&TempLogFile);
128 }
129
130 LEDs_SetAllLEDs(LEDMask);
131 }
132
133 /** Main program entry point. This routine contains the overall program flow, including initial
134 * setup of all components and the main program loop.
135 */
136 int main(void)
137 {
138 /* Fetch logging interval from EEPROM */
139 LoggingInterval500MS_SRAM = eeprom_read_byte(&LoggingInterval500MS_EEPROM);
140
141 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
142
143 SetupHardware();
144
145 /* Mount and open the log file on the dataflash FAT partition */
146 OpenLogFile();
147
148 /* Discard the first sample from the temperature sensor, as it is generally incorrect */
149 uint8_t Dummy = Temperature_GetTemperature();
150 (void)Dummy;
151
152 for (;;)
153 {
154 MS_Device_USBTask(&Disk_MS_Interface);
155 HID_Device_USBTask(&Generic_HID_Interface);
156 USB_USBTask();
157 }
158 }
159
160 void OpenLogFile(void)
161 {
162 char LogFileName[12];
163
164 /* Get the current date for the filename as "DDMMYY.csv" */
165 uint8_t Day, Month, Year;
166 DS1307_GetDate(&Day, &Month, &Year);
167 sprintf(LogFileName, "%02d%02d%02d.csv", Day, Month, Year);
168
169 /* Mount the storage device, open the file */
170 f_mount(0, &DiskFATState);
171 f_open(&TempLogFile, LogFileName, FA_OPEN_ALWAYS | FA_WRITE);
172 f_lseek(&TempLogFile, TempLogFile.fsize);
173 }
174
175 void CloseLogFile(void)
176 {
177 /* Sync any data waiting to be written, unmount the storage device */
178 f_sync(&TempLogFile);
179 f_close(&TempLogFile);
180 }
181
182 /** Configures the board hardware and chip peripherals for the demo's functionality. */
183 void SetupHardware(void)
184 {
185 /* Disable watchdog if enabled by bootloader/fuses */
186 MCUSR &= ~(1 << WDRF);
187 wdt_disable();
188
189 /* Disable clock division */
190 clock_prescale_set(clock_div_1);
191
192 /* Hardware Initialization */
193 LEDs_Init();
194 SPI_Init(SPI_SPEED_FCPU_DIV_2 | SPI_SCK_LEAD_FALLING | SPI_SAMPLE_TRAILING | SPI_MODE_MASTER);
195 ADC_Init(ADC_REFERENCE_AVCC | ADC_FREE_RUNNING | ADC_PRESCALE_128);
196 Temperature_Init();
197 Dataflash_Init();
198 USB_Init();
199
200 /* 500ms logging interval timer configuration */
201 OCR1A = ((F_CPU / 1024) / 2);
202 TCCR1B = (1 << WGM12) | (1 << CS12) | (1 << CS10);
203 TIMSK1 = (1 << OCIE1A);
204
205 /* Clear Dataflash sector protections, if enabled */
206 DataflashManager_ResetDataflashProtections();
207 }
208
209 /** Event handler for the library USB Connection event. */
210 void EVENT_USB_Device_Connect(void)
211 {
212 LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
213
214 /* Close the log file so that the host has exclusive filesystem access */
215 CloseLogFile();
216 }
217
218 /** Event handler for the library USB Disconnection event. */
219 void EVENT_USB_Device_Disconnect(void)
220 {
221 LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
222
223 /* Mount and open the log file on the dataflash FAT partition */
224 OpenLogFile();
225 }
226
227 /** Event handler for the library USB Configuration Changed event. */
228 void EVENT_USB_Device_ConfigurationChanged(void)
229 {
230 LEDs_SetAllLEDs(LEDMASK_USB_READY);
231
232 if (!(MS_Device_ConfigureEndpoints(&Disk_MS_Interface)))
233 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
234
235 if (!(HID_Device_ConfigureEndpoints(&Generic_HID_Interface)))
236 LEDs_SetAllLEDs(LEDMASK_USB_ERROR);
237 }
238
239 /** Event handler for the library USB Unhandled Control Request event. */
240 void EVENT_USB_Device_UnhandledControlRequest(void)
241 {
242 MS_Device_ProcessControlRequest(&Disk_MS_Interface);
243 HID_Device_ProcessControlRequest(&Generic_HID_Interface);
244 }
245
246 /** Mass Storage class driver callback function the reception of SCSI commands from the host, which must be processed.
247 *
248 * \param[in] MSInterfaceInfo Pointer to the Mass Storage class interface configuration structure being referenced
249 */
250 bool CALLBACK_MS_Device_SCSICommandReceived(USB_ClassInfo_MS_Device_t* MSInterfaceInfo)
251 {
252 bool CommandSuccess;
253
254 LEDs_SetAllLEDs(LEDMASK_USB_BUSY);
255 CommandSuccess = SCSI_DecodeSCSICommand(MSInterfaceInfo);
256 LEDs_SetAllLEDs(LEDMASK_USB_READY);
257
258 return CommandSuccess;
259 }
260
261 /** HID class driver callback function for the creation of HID reports to the host.
262 *
263 * \param[in] HIDInterfaceInfo Pointer to the HID class interface configuration structure being referenced
264 * \param[in,out] ReportID Report ID requested by the host if non-zero, otherwise callback should set to the generated report ID
265 * \param[in] ReportType Type of the report to create, either REPORT_ITEM_TYPE_In or REPORT_ITEM_TYPE_Feature
266 * \param[out] ReportData Pointer to a buffer where the created report should be stored
267 * \param[out] ReportSize Number of bytes written in the report (or zero if no report is to be sent
268 *
269 * \return Boolean true to force the sending of the report, false to let the library determine if it needs to be sent
270 */
271 bool CALLBACK_HID_Device_CreateHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo, uint8_t* const ReportID,
272 const uint8_t ReportType, void* ReportData, uint16_t* ReportSize)
273 {
274 Device_Report_t* ReportParams = (Device_Report_t*)ReportData;
275
276 DS1307_GetDate(&ReportParams->Day, &ReportParams->Month, &ReportParams->Year);
277 DS1307_GetTime(&ReportParams->Hour, &ReportParams->Minute, &ReportParams->Second);
278
279 ReportParams->LogInterval500MS = LoggingInterval500MS_SRAM;
280
281 *ReportSize = sizeof(Device_Report_t);
282 return true;
283 }
284
285 /** HID class driver callback function for the processing of HID reports from the host.
286 *
287 * \param[in] HIDInterfaceInfo Pointer to the HID class interface configuration structure being referenced
288 * \param[in] ReportID Report ID of the received report from the host
289 * \param[in] ReportData Pointer to a buffer where the created report has been stored
290 * \param[in] ReportSize Size in bytes of the received HID report
291 */
292 void CALLBACK_HID_Device_ProcessHIDReport(USB_ClassInfo_HID_Device_t* const HIDInterfaceInfo, const uint8_t ReportID,
293 const void* ReportData, const uint16_t ReportSize)
294 {
295 Device_Report_t* ReportParams = (Device_Report_t*)ReportData;
296
297 GPIOR0 = ReportParams->Day;
298 GPIOR1 = ReportParams->Month;
299 GPIOR2 = ReportParams->Year;
300
301 DS1307_SetDate(ReportParams->Day, ReportParams->Month, ReportParams->Year);
302 DS1307_SetTime(ReportParams->Hour, ReportParams->Minute, ReportParams->Second);
303
304 if (LoggingInterval500MS_SRAM != ReportParams->LogInterval500MS)
305 {
306 LoggingInterval500MS_SRAM = ReportParams->LogInterval500MS;
307 eeprom_write_byte(&LoggingInterval500MS_EEPROM, LoggingInterval500MS_SRAM);
308 }
309 }