TempDataLogger.c 11 KB

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