int main(void) { setupLEDs(); for(;;){ _delay_ms(500.0); setGreenLED(); clrRedLED(); _delay_ms(500.0); clrGreenLED(); setRedLED(); } }
/**************************************************************************//** * @brief The Heart Rate Monitor loop * It implements the main state machine. *****************************************************************************/ bool HeartRateMonitor_Loop( bool displaySpO2, bool forceStop, bool checkSkinContact ) { static int32_t hrmStatus; int16_t heartRate; int16_t spo2; static HRMSpO2State_t state = HRM_STATE_IDLE; // stores the main state of the state machine HANDLE si114xHandle; int32_t skinDetect = 0; si114xhrm_GetLowLevelHandle(hrmHandle, &si114xHandle); static bool updateDisplay = false; // flag to save when display needs to update if (forceStop && state!=HRM_STATE_IDLE) { // main application sets forceStop to true to force the HRM algo to quit*/ state = HRM_STATE_IDLE; stopHRM (); checkSkinContact = false; } if(state == HRM_STATE_IDLE) { /* * in the idle state we periodically check for skin contact * and if detected start the algorithm */ resetInactiveTimer(); if (checkSkinContact) si114xhrm_DetectSkinContact(hrmHandle, &skinDetect); if (skinDetect) { state = HRM_STATE_NOSIGNAL; #ifdef USB_DEBUG if (USBDebug_IsUSBConfigured()) { configMessage[0] = 0x43; //Configuration message starts with ASCII C USBDebug_ProcessConfigurationMessage(configMessage+1, currentHRMConfig); si114xhrm_OutputDebugMessage(hrmHandle, (int8_t*)configMessage); } #endif // start the algorithm si114xhrm_Run(hrmHandle); } else return false; } // call the main HRM algorithm processing function #ifdef USB_DEBUG if(si114xhrm_Process(hrmHandle, &heartRate, &spo2, &hrmStatus, &hrmData) == SI114xHRM_SUCCESS) { #else if(si114xhrm_Process(hrmHandle, &heartRate, &spo2, &hrmStatus, 0) == SI114xHRM_SUCCESS) { #endif // when STATUS_FRAME_PROCESSED is set new data is available if (hrmStatus&SI114xHRM_STATUS_FRAME_PROCESSED) { hrmStatus &= ~SI114xHRM_STATUS_FRAME_PROCESSED; #ifdef USB_DEBUG debugMessage[0] = 0x44; //Debug message starts with ASCII D sprintf(debugMessage+1, "Fs = %hd, Pi = %hu, Status = %ld, Pulse = %hdbpm, SpO2 = %hd%%", hrmData.Fs, hrmData.spo2IrPerfusionIndex, hrmStatus, heartRate, spo2); si114xhrm_OutputDebugMessage(hrmHandle, (int8_t*)debugMessage); #endif // process error codes heartRateStateMachine(&state,hrmStatus); // if heart rate is valid save the value if (state == HRM_STATE_ACTIVE) displayHeartRateValue = heartRate; // if we want to display SpO2 check the SpO2 status too*/ if (displaySpO2) { spo2StateMachine(&state,hrmStatus); // if spo2 value is valid save the value if (state == HRM_STATE_ACTIVE) displaySpo2Value = spo2; } // if data is invalid start a timeout if (state == HRM_STATE_INVALID) { enableInvalidTimer = true; // when timeout expires clear old data if(invalidTimeout == true) { state = HRM_STATE_IDLE; stopHRM (); resetInvalidTimer(); } } // update the display when we get new data*/ updateDisplay = true; } } if ( (updateDisplay) && (HeartRateMonitor_SamplesPending () == false) ) { HeartRateMonitor_UpdateDisplay(state, displaySpO2); updateDisplay = false; } // this timeout turns off the red led to produce the flash effect if (redLEDTimeout) { redLEDTimeout = false; setRedLED(false); } return ( state!=HRM_STATE_IDLE ); } /**************************************************************************//** * @brief Update the display based on the HRM state *****************************************************************************/ static void HeartRateMonitor_UpdateDisplay(HRMSpO2State_t state, bool displaySpO2) { bool showWait = false; int t; if (displaySpO2) t = displaySpo2Value; else t = displayHeartRateValue; if (bufferOverrunError) { GRAPHICS_DrawError (); } else { switch(state) { case HRM_STATE_IDLE: case HRM_STATE_NOSIGNAL: setRedLED(false); setGreenLED(false); resetInvalidTimer(); break; case HRM_STATE_ACQUIRING: // flash red led setRedLED(true); showWait = true; enableInvalidTimer = true; break; case HRM_STATE_ACTIVE: setGreenLED(true); resetInvalidTimer(); break; case HRM_STATE_INVALID: if (t == 0) { showWait = true; setRedLED(true); setGreenLED(false); } break; } if (displaySpO2) GRAPHICS_ShowSpO2Status(showWait, displaySpo2Value, false); else GRAPHICS_ShowHRMStatus(showWait, displayHeartRateValue, false); } }
int main(void) { motorInit(); // Initialize the motor port to drive the MOSFET low uint8_t watchDogResetFlag = MCUSR & _BV(WDRF); /// Save the watchdog flag MCUSR &= ~ _BV( WDRF ); // Clear the watchdog flag // "In safety level 1, WDE is overridden by WDRF in MCUSR...." // "This means that WDE is always set when WDRF is set." // IF we left this Set, then we could get watchdogged while sleeping wdt_enable( WDTO_8S ); // Give ourselves 8 seconds before forced reboot enableTimer0(); // Initialize the timer that also PWMs the LEDs WHITE_LED_DDR |= _BV(WHITE_LED_BIT); // Pin to output RED_LED_DDR |= _BV(RED_LED_BIT); // Button sense pin setup BUTTON_PORT |= _BV(BUTTON_BIT); // Enable pull-up for button pin // Battery Charger status pin setup EOC_PORT |= _BV(EOC_BIT); // Activate pull-up CIP_PORT |= _BV( CIP_BIT); // Activate pull-up _delay_us(1); // Give the pull-ups a second to work if ( !watchDogResetFlag ) { // Are we coming out of anything except for a WatchDog reset? // Cold boot, run test mode // Blink back and forth to show LEDs work and solicit a button press for(uint8_t i=0;i<100 && !BUTTON_STATE_DOWN(); i++ ) { setRedLED(255); for(uint8_t j=0; j<100 && !BUTTON_STATE_DOWN();j++ ) { _delay_ms(1); } setRedLED(0); setWhiteLED(255); for(uint8_t j=0; j<100 && !BUTTON_STATE_DOWN();j++ ) { _delay_ms(1); } setWhiteLED(0); wdt_reset(); } _delay_ms(BUTTON_DEBOUNCE_TIME_MS); // TODO: Put more code here for some testing and feedback on initial battery connection at the factory. } // Ready to begin normal operation! if (BUTTON_STATE_DOWN()) { // Possible stuck button? // If we get here, either we just finished test mode and the button is Still down, in which case // we are testing to make sure it goes back up // Otherwise we just reset and the button was down when we woke, so likely it is stuck down // and that is what caused the reset. In this case, show the user and then eventually disable the button. // Each pass of this loop takes ~1 sec. for( uint16_t t=0; (t <= BUTTON_TRANSIT_TIMEOUT_S) && BUTTON_STATE_DOWN(); t++ ) { // To indicate that we are in a stuck-button sequence, we will blink the white LED // at 50% brightness, 1Hz, 10% duty cycle. This looks different than other states // and also minimizes battery usage (the LED pulls 10+mA) since we might be doing this // for many minutes // Start with LED off because it looks better when we are coming in from a watchdog // reset because the button was held down for more than 8 secs. Otherwise user // sees an odd blink pattern. setWhiteLED(0); // Leave the white LED off for 900 ms or until the button goes up for( uint8_t l=0; l<90 && BUTTON_STATE_DOWN() ; l++) { _delay_ms(10); } setWhiteLED(BUTTON_FEEDBACK_BRIGHTNESS); // Leave the white LED on for 100 ms or until the button goes up // Could do this as a single _delay_ms(100) but that might feel un-responsive for( uint8_t l=0; l<10 && BUTTON_STATE_DOWN() ; l++) { _delay_ms(10); } wdt_reset(); } // Turn off LED before continuing setWhiteLED(0); // Debounce the possible button up transition _delay_ms(BUTTON_DEBOUNCE_TIME_MS); } if (BUTTON_STATE_DOWN()) { // Do we still have a stuck button? // Indicate we are entering transit mode with a quick double flash of both LEDs setRedLED(255); setWhiteLED(255); _delay_ms(100); setRedLED(0); setWhiteLED(0); _delay_ms(100); setRedLED(255); setWhiteLED(255); _delay_ms(100); setRedLED(0); setWhiteLED(0); BUTTON_PORT &= ~_BV(BUTTON_BIT); // Disable pull up to avoid running the battery down. // Do not enable interrupt on button pin change - we will require a charger state change to wake up // Since the interrupt is not enabled, the pin will be disconnected during sleep so any floating // on it will not waste power. } else { // Leave pull-up enabled PCMSK1 = _BV(BUTTON_INT); // Enable interrupt on button pin so we wake on a press } PCMSK0 = _BV(EOC_INT) | _BV(CIP_INT); // Enable interrupt on change in state-of-charge pin or end-of-charge pin no matter what GIMSK |= _BV(PCIE1) | _BV(PCIE0); // Enable both pin change interrupt vectors (each individual pin was also be enabled above) // Clear pending interrupt flags. This way we will only get an interrupt if something changes // after we read it. There is a race condition where something could change between the flag clear and the // reads below, so code should be able to deal with possible redundant interrupt and worst case // is that we get woken up an extra time and go back to sleep. GIFR = _BV(PCIF1) | _BV(PCIF0); // Clear interrupt flags so we will interrupt on any change after now... if ( !CIP_STATE_ACTIVE() && !EOC_STATE_ACTIVE() ) { // Check if conditions are ALREADY true since we only wake on change.... // Ok, it is bedtime! set_sleep_mode( SLEEP_MODE_PWR_DOWN ); // Go into deep sleep where only a pin change can wake us.. uses only ~0.1uA! // GOOD NIGHT! // This code disables the Watchdog. Note that we can not use the library wdt_disable() becuase it has a bug // that causes intermittent unwanted resets. // Note interrupts are already clear when we get here, otherwise we would need to worry about getting interrupted between the two following lines WDTCSR |= _BV(WDCE) | _BV(WDE); // In the same operation, write a logic one to WDCE and WDE. // Note we use OR to preserve the prescaler WDTCSR = 0; // Within the next four clock cycles, in the same operation, write the WDE and WDP bits // as desired, but with the WDCE bit cleared. sleep_enable(); // "To enter any of the three sleep modes, the SE bit in MCUCR must be written to logic one and a SLEEP instruction must be executed." sei(); // Enable global interrupts. "When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts." sleep_cpu(); // This must come right after the sei() to avoid race condition // GOOD MORNING! // If we get here, then a button push or change in charger status woke s up.... sleep_disable(); // "To avoid the MCU entering the sleep mode unless it is the programmer’s purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up." cli(); // We are awake now, and do don't care about interrupts anymore (out interrupt routines don't do anything anyway) wdt_enable( WDTO_8S ); // Re-enable watchdog on wake Give ourselves 8 seconds before reboot } // Ok, now we are running!!! // Motor speed uint8_t currentSpeedStep = 0; // What motor speed setting are we currently on? while (1) { // This main loop runs for as long as the motor is on. // It can be terminated by battery charger change of state, low battery detection, button press back to 0 speed, or long button press // All these changes terminate the loop in a reboot. if (EOC_STATE_ACTIVE()) { // End of charge? motorOff(); //Turn motor off in case were running before plug went in setWhiteLED(255); // White LED full on _delay_ms( JACK_DEBOUNCE_TIME_MS ); while (EOC_STATE_ACTIVE()); // White LED on for as long as we are charging.... // Note that this will watchdog timeout after 8 seconds and reboot us, // After which we will immediately fall right back to here and continue to show the white LED setWhiteLED(0); // Turn it off now, for instant feedback if unplugged (otherwise it will be on for extra 250ms waiting for watchdog reset) // Charger unplugged, reboot for goo measure REBOOT(); } if (CIP_STATE_ACTIVE()) { // Charging? motorOff(); //Turn motor off in case were running before plug went in uint8_t brightness=0; int8_t direction=1; _delay_ms( JACK_DEBOUNCE_TIME_MS ); while (CIP_STATE_ACTIVE()) { // White LED pulse for as long as we are charging.... setWhiteLED(brightness); if (brightness==255) { direction=-1; } else if (brightness==0) { direction=1; } brightness+=direction; _delay_ms(1); // Slows the speed of the rampping LED wdt_reset(); } setWhiteLED(0); // Turn it off now, for instant feedback if unplugged (otherwise it will be on for extra 250ms waiting for watchdog reset) // All done charing, reboot for good measure REBOOT(); } uint8_t vccx10 = readVccVoltage(); // Capture the current power supply voltage. This takes ~1ms and will be needed multiple times below if ( vccx10 <= LOW_BATTERY_VOLTS_COLDx10) { if ( (currentSpeedStep==0) || ( vccx10 <= LOW_BATTERY_VOLTS_WARMx10) ) { // Motor off, or running and really low? motorOff(); setWhiteLED(0); // Needed becuase both LEDs might be on if we are in the middle of a button press setRedLED(255); _delay_ms(LOW_BATTERY_LED_ONTIME_MS); // Show red LED to user to show low battery while (BUTTON_STATE_DOWN()); // Wait for button to be released if pressed // Will watchdog timeout in 8 seconds if stuff setRedLED(0); REBOOT(); } } uint8_t buttonPressedFlag=0; if (BUTTON_STATE_DOWN()) { // Button pushed? setWhiteLED(BUTTON_FEEDBACK_BRIGHTNESS); _delay_ms(BUTTON_DEBOUNCE_TIME_MS); // debounce going down... if ( currentSpeedStep ==0 ) { // Special case first press turning on instantly updateMotor( pgm_read_word(&speedSteps[1].top) , pgm_read_word(&speedSteps[1].normailzedDuty), vccx10); // Set new motor speed } uint16_t buttonDownCount=0; while (BUTTON_STATE_DOWN()) { // Wait for button to go back up or longpress timeout if (buttonDownCount++ >= BUTTON_LONG_PRESS_MS ) { // Long press? Shut motor off // The reboot would do both of these anyway, but we do them redundantly here so UI feels responsive- // The full reboot cycle takes 100+ ms. motorOff(); setWhiteLED(0); REBOOT(); // If the button is still down once we reboot, we will land in the stuck button detection sequence // which will blink the LED for 1/10th second every second until either the button goes up // or the transit mode button timeout expires } _delay_ms(1); // One loop=~1ms } // Pressed less than a long press buttonPressedFlag=1; // Debounce after setting new motor speed so UI feels responsive currentSpeedStep++; if (currentSpeedStep >= SPEED_STEP_COUNT ) { // Cycled all the Way around? currentSpeedStep=0; } } updateMotor( pgm_read_word(&speedSteps[currentSpeedStep].top) , pgm_read_word(&speedSteps[currentSpeedStep].normailzedDuty), vccx10); // Set new motor speed if (buttonPressedFlag) { // Button released, white LED off again setWhiteLED(0); _delay_ms(BUTTON_DEBOUNCE_TIME_MS); // debounce the button returning back up } if (currentSpeedStep==0) { // Either we stepped though the settings back to off, or we got a spurious wake up REBOOT(); } // If we get to here, then we check for a low battery and had the chance to reboot if we found one, // so ok to postpone reset... wdt_reset(); } }
/**************************************************************************//** * @brief This function enables the 100us timer for HRM. *****************************************************************************/ static void startTimer () { // Enable clock for TIMER module CMU_ClockEnable(CLK_HRM_TIMER1, true); CMU_ClockEnable(CLK_HRM_TIMER2, true); TIMER_Reset(HRM_TIMER1); TIMER_Reset(HRM_TIMER2); // Select TIMER parameters TIMER_Init_TypeDef timerInit1 = { .enable = true, .debugRun = true, .prescale = timerPrescale1, .clkSel = timerClkSelHFPerClk, .fallAction = timerInputActionNone, .riseAction = timerInputActionNone, .mode = timerModeUp, .dmaClrAct = false, .quadModeX4 = false, .oneShot = false, .sync = false, }; TIMER_Init_TypeDef timerInit2 = { .enable = true, .debugRun = true, .prescale = timerPrescale1, .clkSel = timerClkSelCascade, .fallAction = timerInputActionNone, .riseAction = timerInputActionNone, .mode = timerModeUp, .dmaClrAct = false, .quadModeX4 = false, .oneShot = false, .sync = false, }; // Set TIMER Top value TIMER_TopSet(HRM_TIMER1, CMU_ClockFreqGet(cmuClock_HF)/1/10000); /*overflow every 100us*/ TIMER_TopSet(HRM_TIMER2, 0xffff); /*max 16 bits*/ // Configure TIMER TIMER_Init(HRM_TIMER1, &timerInit1); TIMER_Init(HRM_TIMER2, &timerInit2); } /**************************************************************************//** * @brief Initiate the Heart Rate Monitor *****************************************************************************/ void HeartRateMonitor_Init( Si114xPortConfig_t* i2c, HeartRateMonitor_Config_t configSelect ) { // Setup SysTick Timer for 10msec interrupts. if (SysTick_Config(CMU_ClockFreqGet(cmuClock_CORE) / 100)) while (1) ; // Setup Timer as 100 usec counter. The HRM API requires a 100usec timestamp. startTimer (); dataStorage.spo2 = &spo2Data; dataStorage.hrm = &hrmDataStorage; hrmHandle = &dataStorage; si114xhrm_Initialize(i2c, 0, &hrmHandle); if (configSelect == BIOMETRIC_EXP) { si114xhrm_Configure(hrmHandle, &biometricEXPHRMConfig); currentHRMConfig = &biometricEXPHRMConfig; } else if (configSelect == SI1143_PS) { si114xhrm_Configure(hrmHandle, &Si1143PsHRMConfig); currentHRMConfig = &Si1143PsHRMConfig; } else if (configSelect == SI1147_PS) { si114xhrm_Configure(hrmHandle, &Si1147PsHRMConfig); currentHRMConfig = &Si1147PsHRMConfig; } //turn off LEDs setRedLED (false); setGreenLED (false); bufferOverrunError = false; displayHeartRateValue = 0; displaySpo2Value = 0; HeartRateMonitor_UpdateDisplay(HRM_STATE_NOSIGNAL, false); } /**************************************************************************//** * @brief Check for samples in irq queue *****************************************************************************/ bool HeartRateMonitor_SamplesPending () { HANDLE si114xHandle; si114xhrm_GetLowLevelHandle(hrmHandle, &si114xHandle); return (Si114xIrqQueueNumentries(si114xHandle)>0); } /**************************************************************************//** * @brief Reset inactive timer values *****************************************************************************/ static void resetInactiveTimer() { enableInactiveTimer = false; inactiveTimeout = false; inactiveTimerCounter = 0; }
void setLEDsOff() { setRedLED(0); setWhiteLED(0); }