3      Copyright (C) Dean Camera, 2012. 
   5   dean [at] fourwalledcubicle [dot] com 
  10   Copyright 2012  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  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. 
  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 
  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. 
  37 #include "TempDataLogger.h" 
  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. 
  43 USB_ClassInfo_MS_Device_t Disk_MS_Interface 
= 
  50                                                 .Address           
= MASS_STORAGE_IN_EPADDR
, 
  51                                                 .Size              
= MASS_STORAGE_IO_EPSIZE
, 
  56                                                 .Address           
= MASS_STORAGE_OUT_EPADDR
, 
  57                                                 .Size              
= MASS_STORAGE_IO_EPSIZE
, 
  64 /** Buffer to hold the previously generated HID report, for comparison purposes inside the HID class driver. */ 
  65 static uint8_t PrevHIDReportBuffer
[GENERIC_REPORT_SIZE
]; 
  67 /** LUFA HID Class driver interface configuration and state information. This structure is 
  68  *  passed to all HID Class driver functions, so that multiple instances of the same class 
  69  *  within a device can be differentiated from one another. 
  71 USB_ClassInfo_HID_Device_t Generic_HID_Interface 
= 
  78                                                 .Address              
= GENERIC_IN_EPADDR
, 
  79                                                 .Size                 
= GENERIC_EPSIZE
, 
  82                                 .PrevReportINBuffer           
= PrevHIDReportBuffer
, 
  83                                 .PrevReportINBufferSize       
= sizeof(PrevHIDReportBuffer
), 
  87 /** Non-volatile Logging Interval value in EEPROM, stored as a number of 500ms ticks */ 
  88 static uint8_t EEMEM LoggingInterval500MS_EEPROM 
= DEFAULT_LOG_INTERVAL
; 
  90 /** SRAM Logging Interval value fetched from EEPROM, stored as a number of 500ms ticks */ 
  91 static uint8_t LoggingInterval500MS_SRAM
; 
  93 /** Total number of 500ms logging ticks elapsed since the last log value was recorded */ 
  94 static uint16_t CurrentLoggingTicks
; 
  96 /** FAT Fs structure to hold the internal state of the FAT driver for the Dataflash contents. */ 
  97 static FATFS DiskFATState
; 
  99 /** FAT Fs structure to hold a FAT file handle for the log data write destination. */ 
 100 static FIL TempLogFile
; 
 103 /** ISR to handle the 500ms ticks for sampling and data logging */ 
 104 ISR(TIMER1_COMPA_vect
, ISR_BLOCK
) 
 106         uint8_t LEDMask 
= LEDs_GetLEDs(); 
 108         /* Check to see if the logging interval has expired */ 
 109         if (++CurrentLoggingTicks 
< LoggingInterval500MS_SRAM
) 
 112         /* Reset log tick counter to prepare for next logging interval */ 
 113         CurrentLoggingTicks 
= 0; 
 115         LEDs_SetAllLEDs(LEDMASK_USB_BUSY
); 
 117         /* Only log when not connected to a USB host */ 
 118         if (USB_DeviceState 
== DEVICE_STATE_Unattached
) 
 120                 TimeDate_t CurrentTimeDate
; 
 121                 DS1307_GetTimeDate(&CurrentTimeDate
); 
 123                 char     LineBuffer
[100]; 
 124                 uint16_t BytesWritten
; 
 126                 BytesWritten 
= sprintf(LineBuffer
, "%02d/%02d/20%02d, %02d:%02d:%02d, %d Degrees\r\n", 
 127                                        CurrentTimeDate
.Day
, CurrentTimeDate
.Month
, CurrentTimeDate
.Year
, 
 128                                        CurrentTimeDate
.Hour
, CurrentTimeDate
.Minute
, CurrentTimeDate
.Second
, 
 129                                        Temperature_GetTemperature()); 
 131                 f_write(&TempLogFile
, LineBuffer
, BytesWritten
, &BytesWritten
); 
 132                 f_sync(&TempLogFile
); 
 135         LEDs_SetAllLEDs(LEDMask
); 
 138 /** Main program entry point. This routine contains the overall program flow, including initial 
 139  *  setup of all components and the main program loop. 
 145         /* Fetch logging interval from EEPROM */ 
 146         LoggingInterval500MS_SRAM 
= eeprom_read_byte(&LoggingInterval500MS_EEPROM
); 
 148         /* Check if the logging interval is invalid (0xFF) indicating that the EEPROM is blank */ 
 149         if (LoggingInterval500MS_SRAM 
== 0xFF) 
 150           LoggingInterval500MS_SRAM 
= DEFAULT_LOG_INTERVAL
; 
 152         /* Mount and open the log file on the Dataflash FAT partition */ 
 155         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 160                 MS_Device_USBTask(&Disk_MS_Interface
); 
 161                 HID_Device_USBTask(&Generic_HID_Interface
); 
 166 /** Opens the log file on the Dataflash's FAT formatted partition according to the current date */ 
 167 void OpenLogFile(void) 
 169         char LogFileName
[12]; 
 171         /* Get the current date for the filename as "DDMMYY.csv" */ 
 172         TimeDate_t CurrentTimeDate
; 
 173         DS1307_GetTimeDate(&CurrentTimeDate
); 
 174         sprintf(LogFileName
, "%02d%02d%02d.csv", CurrentTimeDate
.Day
, CurrentTimeDate
.Month
, CurrentTimeDate
.Year
); 
 176         /* Mount the storage device, open the file */ 
 177         f_mount(0, &DiskFATState
); 
 178         f_open(&TempLogFile
, LogFileName
, FA_OPEN_ALWAYS 
| FA_WRITE
); 
 179         f_lseek(&TempLogFile
, TempLogFile
.fsize
); 
 182 /** Closes the open data log file on the Dataflash's FAT formatted partition */ 
 183 void CloseLogFile(void) 
 185         /* Sync any data waiting to be written, unmount the storage device */ 
 186         f_sync(&TempLogFile
); 
 187         f_close(&TempLogFile
); 
 190 /** Configures the board hardware and chip peripherals for the demo's functionality. */ 
 191 void SetupHardware(void) 
 193         /* Disable watchdog if enabled by bootloader/fuses */ 
 194         MCUSR 
&= ~(1 << WDRF
); 
 197         /* Disable clock division */ 
 198         clock_prescale_set(clock_div_1
); 
 200         /* Hardware Initialization */ 
 202         SPI_Init(SPI_SPEED_FCPU_DIV_2 
| SPI_SCK_LEAD_FALLING 
| SPI_SAMPLE_TRAILING 
| SPI_MODE_MASTER
); 
 203         ADC_Init(ADC_FREE_RUNNING 
| ADC_PRESCALE_128
); 
 207         TWI_Init(TWI_BIT_PRESCALE_4
, TWI_BITLENGTH_FROM_FREQ(4, 50000)); 
 209         /* 500ms logging interval timer configuration */ 
 210         OCR1A   
= (((F_CPU 
/ 1024) / 2) - 1); 
 211         TCCR1B  
= (1 << WGM12
) | (1 << CS12
) | (1 << CS10
); 
 212         TIMSK1  
= (1 << OCIE1A
); 
 214         /* Check if the Dataflash is working, abort if not */ 
 215         if (!(DataflashManager_CheckDataflashOperation())) 
 217                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 221         /* Clear Dataflash sector protections, if enabled */ 
 222         DataflashManager_ResetDataflashProtections(); 
 225 /** Event handler for the library USB Connection event. */ 
 226 void EVENT_USB_Device_Connect(void) 
 228         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
); 
 230         /* Close the log file so that the host has exclusive file system access */ 
 234 /** Event handler for the library USB Disconnection event. */ 
 235 void EVENT_USB_Device_Disconnect(void) 
 237         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 239         /* Mount and open the log file on the Dataflash FAT partition */ 
 243 /** Event handler for the library USB Configuration Changed event. */ 
 244 void EVENT_USB_Device_ConfigurationChanged(void) 
 246         bool ConfigSuccess 
= true; 
 248         ConfigSuccess 
&= HID_Device_ConfigureEndpoints(&Generic_HID_Interface
); 
 249         ConfigSuccess 
&= MS_Device_ConfigureEndpoints(&Disk_MS_Interface
); 
 251         LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY 
: LEDMASK_USB_ERROR
); 
 254 /** Event handler for the library USB Control Request reception event. */ 
 255 void EVENT_USB_Device_ControlRequest(void) 
 257         MS_Device_ProcessControlRequest(&Disk_MS_Interface
); 
 258         HID_Device_ProcessControlRequest(&Generic_HID_Interface
); 
 261 /** Mass Storage class driver callback function the reception of SCSI commands from the host, which must be processed. 
 263  *  \param[in] MSInterfaceInfo  Pointer to the Mass Storage class interface configuration structure being referenced 
 265 bool CALLBACK_MS_Device_SCSICommandReceived(USB_ClassInfo_MS_Device_t
* const MSInterfaceInfo
) 
 269         LEDs_SetAllLEDs(LEDMASK_USB_BUSY
); 
 270         CommandSuccess 
= SCSI_DecodeSCSICommand(MSInterfaceInfo
); 
 271         LEDs_SetAllLEDs(LEDMASK_USB_READY
); 
 273         return CommandSuccess
; 
 276 /** HID class driver callback function for the creation of HID reports to the host. 
 278  *  \param[in]     HIDInterfaceInfo  Pointer to the HID class interface configuration structure being referenced 
 279  *  \param[in,out] ReportID    Report ID requested by the host if non-zero, otherwise callback should set to the generated report ID 
 280  *  \param[in]     ReportType  Type of the report to create, either HID_REPORT_ITEM_In or HID_REPORT_ITEM_Feature 
 281  *  \param[out]    ReportData  Pointer to a buffer where the created report should be stored 
 282  *  \param[out]    ReportSize  Number of bytes written in the report (or zero if no report is to be sent) 
 284  *  \return Boolean true to force the sending of the report, false to let the library determine if it needs to be sent 
 286 bool CALLBACK_HID_Device_CreateHIDReport(USB_ClassInfo_HID_Device_t
* const HIDInterfaceInfo
, 
 287                                          uint8_t* const ReportID
, 
 288                                          const uint8_t ReportType
, 
 290                                          uint16_t* const ReportSize
) 
 292         Device_Report_t
* ReportParams 
= (Device_Report_t
*)ReportData
; 
 294         DS1307_GetTimeDate(&ReportParams
->TimeDate
); 
 296         ReportParams
->LogInterval500MS 
= LoggingInterval500MS_SRAM
; 
 298         *ReportSize 
= sizeof(Device_Report_t
); 
 302 /** HID class driver callback function for the processing of HID reports from the host. 
 304  *  \param[in] HIDInterfaceInfo  Pointer to the HID class interface configuration structure being referenced 
 305  *  \param[in] ReportID    Report ID of the received report from the host 
 306  *  \param[in] ReportType  The type of report that the host has sent, either HID_REPORT_ITEM_Out or HID_REPORT_ITEM_Feature 
 307  *  \param[in] ReportData  Pointer to a buffer where the received report has been stored 
 308  *  \param[in] ReportSize  Size in bytes of the received HID report 
 310 void CALLBACK_HID_Device_ProcessHIDReport(USB_ClassInfo_HID_Device_t
* const HIDInterfaceInfo
, 
 311                                           const uint8_t ReportID
, 
 312                                           const uint8_t ReportType
, 
 313                                           const void* ReportData
, 
 314                                           const uint16_t ReportSize
) 
 316         Device_Report_t
* ReportParams 
= (Device_Report_t
*)ReportData
; 
 318         DS1307_SetTimeDate(&ReportParams
->TimeDate
); 
 320         /* If the logging interval has changed from its current value, write it to EEPROM */ 
 321         if (LoggingInterval500MS_SRAM 
!= ReportParams
->LogInterval500MS
) 
 323                 LoggingInterval500MS_SRAM 
= ReportParams
->LogInterval500MS
; 
 324                 eeprom_update_byte(&LoggingInterval500MS_EEPROM
, LoggingInterval500MS_SRAM
);