Example #1
0
obj fn_wait_for_event (obj args)
{
  (void) args;
  sleep_enable ();
  set_sleep_mode (SLEEP_MODE_IDLE);
  for (;;)
  {
    noInterrupts ();
    if (isReady ())
      break;
    interrupts ();
    sleep_cpu ();
  }
  interrupts ();
  return (obj_NIL);
}
Example #2
0
void go_sleep()
{
  cbi(ADCSRA,ADEN);  // switch Analog to Digitalconverter OFF
	set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        cli();
	sleep_enable();	
	sleep_bod_disable();
	sei();
	sleep_cpu();
	//sleep_mode();
	/* wake up here */
	sleep_disable();
        sbi(ADCSRA,ADEN);                    // switch Analog to Digitalconverter ON
        initvars();
        setup();
}
Example #3
0
int main(void)
{
	uint8_t i, 
		led;		/* port D LEDs */

	DDRD = 0xFF;		/* set port D as output */
	DDRE &= ~(_BV(PORTE4));	/* set PE4 as input */
	PORTE |= _BV(PORTE4);	/* enable PE4 pull up resistor */

	cli();			/* global interrupt disable */
	EIMSK = 0x00;		/* disable all external interrupts */
	EICRB = 0x00;		/* 0 0 The low level of INT4 generates an interrupt request. */
	EIFR = 0x00;		/* clear all interrupt flags */
	EIMSK = _BV(INT4);	/* enable external interrupts */
	sei();			/* global interrupt enable */

	/*
	 * SLEEP_MODE_IDLE          ... Idle
	 * SLEEP_MODE_ADC           ... ADC Noise Reduction
	 * SLEEP_MODE_PWR_DOWN      ... Power-down
	 * SLEEP_MODE_PWR_SAVE      ... Power-save
	 * SLEEP_MODE_STANDBY       ... Standby
	 * SLEEP_MODE_EXT_STANDBY   ... Extended Standby
	 */

	set_sleep_mode(SLEEP_MODE_IDLE); /* set sleep mode */

	while(1) 
	{
		led = 1;	/* indicate we are ready */
		PORTD = ~led;

		sleep_enable();		/* set Sleep Enable bit */
		sleep_cpu();		/* sleep - waiting for INT4 */
		sleep_disable();	/* clear Sleep Enable bit */

		while (led)	/* action after wake-up */
		{
			led <<= 1;	/* walking LED */
			PORTD = ~led;	

			for (i = 0; i < 100; i++)	/* delay 1s */
				_delay_ms(10);
		}
	}
}
Example #4
0
File: clk.c Project: kuwatay/AVR
int main(void) {
  // setup t10 internal clock speed
  CCP = 0xD8;
  CLKMSR = 0x00;  // internal 8MHz
  CCP = 0xD8;
  CLKPSR = 0x03;  // 1/8 prescaler -> 1MHz

  si5351_init();

  CLOCK_DISABLE();  // Power down all output drivers

  SETUP_XTAL_CAP(CAP_10PF);  // Set the load capacitance for the XTAL

  PLL_SOURCE_XTAL();  // input source of PLAA PLLB to xtal

  // PLLA
  // VCO Frequency (MHz) =  696.204000000
  SETUP_PLLA(26UL, 5051UL, 6500UL);  // Input Frequency (MHz) = 26.000000000, Feedback Divider = 26  5051/6500

  // PLLB
  // VCO Frequency (MHz) =  832.000000000
  SETUP_PLLB(32UL, 0UL, 1UL);  // Input Frequency (MHz) = 26.000000000, Feedback Divider = 32

  // Channel 0
  // Output Frequency (MHz) = 4.194000000
  SETUP_DIV0(166UL, 0UL, 1UL, OD_PARAM(1));   // Multisynth Output Frequency (MHz) = 4.194000000,  Multisynth Divider = 166,  R Divider = 1
  CLOCK0_CONTROL(SOURCE_PLLA, MODE_INT);   // PLL source = PLLA

  // Channel 1
  // Output Frequency (MHz) = 12.80000000
  SETUP_DIV1(65UL, 0UL, 1UL, OD_PARAM(1));  // Multisynth Output Frequency (MHz) = 12.800000000, Multisynth Divider = 65,  R Divider = 1
  CLOCK1_CONTROL(SOURCE_PLLB, MODE_INT);   // PLL source = PLLB

  // Channel 2
  // Output Frequency (MHz) = 0.010000000
  SETUP_DIV2(1300UL, 0UL, 1UL, OD_PARAM(64));   // Multisynth Output Frequency (MHz) = 0.640000000, Multisynth Divider = 1300, R Divider = 64
  CLOCK2_CONTROL(SOURCE_PLLB, MODE_INT);   // PLL source = PLLB

  PLL_SOFTRESET();  // Apply PLLA and PLLB soft reset

  ENABLE_OUTPUT();  // Enable all outputs

  while(1) {
    sleep_cpu();
  }
}
int main()
{
  stdout = &mystdout;

  // read the eeprom value
  uint32_t c = eeprom_read_dword((void*)&value);
  printf("Read from eeprom 0x%08lx -- should be 0xdeadbeef\n", c);
  // change the eeprom
  eeprom_write_dword((void*)&value, 0xcafef00d);
  // re-read it
  c = eeprom_read_dword((void*)&value);
  printf("Read from eeprom 0x%08lx -- should be 0xcafef00d\n", c);

  // this quits the simulator, since interupts are off
  // this is a "feature" that allows running tests cases and exit
  sleep_cpu();
}
Example #6
0
void standbyTimerDone(uint32_t avgInputVolt) {	
	if (avgInputVolt > 768) { // high level means NO bat. loading!  now we can really go to sleep
		// shut down everything
		led_fader_disable();
		DIGIWRITE_L(PORTB, PIN_LED);
        DIGIWRITE_L(PORTB, PIN_AUDIO_TRIGGER);  // stop giving signal to audio playback
		DIGIWRITE_L(PORTB, ACCEL_PIN_X);
		
		// prepare going to sleep
		GIMSK |= (1 << INT0);	// enable external interrupt on PB2
		
		// NOTE: only LOW level will wake the MCU up again!
		// this does not work somehow:
//		MCUCR |= (1 << ISC01) | (1 << ISC00);	// The rising edge of INT0 generates an interrupt request.
//		MCUCR |= (1 << ISC00);	// Any logical change on INT0 generates an interrupt request.
//		wdt_disable();
				
		// go to sleep
		sleep_enable();
		sei();
		sleep_bod_disable();
        sleep_cpu();
        
		// woken up!
		cli();
        sleep_disable();
		
		GIMSK &= ~(1 << INT0);	// disable external interrupt on PB2
		
		// test LEDs. 2 times blinking means "woken up"
		blinkLED(&PORTB, PIN_LED, 50);
		long_delay_ms(50);
		blinkLED(&PORTB, PIN_LED, 50);

		// start LED fading again
		startLEDDefaultMode();
		shakeEnded();		// reset states
		
		// wake up watch dog
//		wdt_enable(WTD_TIME);
	} else {
		standby_timer_reset();		// try it again
	}
	
	// standby_timer_enable();
}
Example #7
0
//---------------------------------------------------------------------------
static void IdleMain( void *unused )
{
    while(1)
    {
#if 1
        // LPM code;
        set_sleep_mode(SLEEP_MODE_IDLE);
        cli();
        sleep_enable();
        sei();
        sleep_cpu();
        sleep_disable();
        sei();
#endif        
    }
    return 0;
}
/// @see http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html
void Sleepy::powerDown() {
	byte adcsraSave = ADCSRA;
	ADCSRA &= ~bit(ADEN); // disable the ADC
	set_sleep_mode(SLEEP_MODE_PWR_DOWN);
	ATOMIC_BLOCK(ATOMIC_FORCEON) {
		sleep_enable();
		// sleep_bod_disable(); // can't use this - not in my avr-libc version!
#ifdef BODSE
		MCUCR = MCUCR | bit(BODSE) | bit(BODS); // timed sequence
		MCUCR = (MCUCR & ~bit(BODSE)) | bit(BODS);
#endif
	}
	sleep_cpu();
	sleep_disable();
	// re-enable what we disabled
	ADCSRA = adcsraSave;
}
Example #9
0
void osx_tlsche_execute( TiOsxTimeLineScheduler * sche )
{
	rtc_setinterval( sche->timer, 0, 2, 0x01); //定时周期为一秒 
	hal_enable_interrupts();
	rtc_start( sche->timer );

    while (1)
    {
        osx_tlsche_evolve( sche, NULL );
	
        set_sleep_mode(SLEEP_MODE_IDLE);
	    sleep_enable();
	    sleep_cpu();
	    sleep_disable();
    }

    // rtc_stop( sche->rtc );
}
Example #10
0
int main(void)
{
    DDRB = (1 << PB0);

    // Watchdog signal will be active low
    //PORTB |= (1 << PB0);

    // Setup the power reduction register
    PRR = (1 << PRTIM1) | (1 << PRTIM0) | (1 << PRUSI) | (1 << PRADC);

    sei();
    
    while (1)
    {
        // Disable the watchdog
    
        WDTCR |= (1 << WDCE) | (1 << WDE);
        WDTCR &= ~(1 << WDE);
        
        // Enable the watchdog. It will fire every 4 seconds.
        
        WDTCR = (1 << WDIE) | (1 << WDE) | (1 << WDP3);

        // Sleep in power down mode. We will be woken up by the watchdog interrupt

        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_enable();
        sleep_cpu();

        // When we wake up the watchdog interrupt has fired, chck if we have done enough
        // iterations for an hour. If so, pulse PB0 low.

        if (counter >= (60 / 60))
        {
            counter = 0;

            PINB |= (1 << PB0);
            _delay_us(4);
            PINB &= ~(1 << PB0);
        }
    }

    return 0;
}
Example #11
0
//------------------------------------End of Setup-------------------------------------------------//
 //Main Loop//
 void loop () 
 {   
  flash ();                        //HeartBeat Flash//
  AwakeTimer();                    //Awake Timer// 
    if ( ATimer == SleepTime)
    { 
      BattRead();
      DataTX();
    } // End of Main loop if timer was reached

//----------------------------------- End of Actual executing code---------------------------//
  //Preparing to go to sleep//
  
  digitalWrite(DataRadioSwitch,LOW);               //Switch Data Radio off

  byte old_ADCSRA = ADCSRA;                        // disable ADC //
  ADCSRA = 0;                                      // disable ADC //

  byte old_PRR = PRR;                              // disable Internal modules//
  PRR = 0xFF;                                      // disable Internal modules//

  MCUSR = 0;                                       // clear various "reset" flags// 

  // Watchdog Timer Parameters//
  WDTCSR = bit (WDCE) | bit (WDE);                 // allow changes, disable reset
  WDTCSR = bit (WDIE) | bit (WDP3) | bit (WDP0);   // set WDIE, and 8 seconds delay
  wdt_reset();                                     // pat the dog once program has executed.

  // Sleep Activation //
  set_sleep_mode (SLEEP_MODE_PWR_DOWN);            //Sleep mode Selection//
  sleep_enable();                                  //Sleep Now//

  // turn off brown-out enable in software//
  MCUCR = bit (BODS) | bit (BODSE);                //Brown out settings
  MCUCR = bit (BODS);                              //Brown out set.
  sleep_cpu ();                                    //CPU is now sleeping

  //--------------------------------------End of sleep Preperation-------------------------------//
  // Once awake code executes from this point//
  // Once CPU wakes up do the follwoing to restore full operations//
  sleep_disable();
  PRR = old_PRR;
  ADCSRA = old_ADCSRA;
}
Example #12
0
int main(void)
{
  sys_init();                                   // Initialize system
  canInit(CAN_BAUDRATE);         		// Initialize the CANopen bus
  initTimer();                                 	// Start timer for the CANopen stack
  nodeID = read_bcd();				// Read node ID first
  setNodeId (&ObjDict_Data, nodeID);
  setState(&ObjDict_Data, Initialisation);	// Init the state

  for(;;)		                        // forever loop
  {
    if (sys_timer)	                        // Cycle timer, invoke action on every time slice
    {
      reset_sys_timer();	                // Reset timer
      digital_input[0] = get_inputs();
      digital_input_handler(&ObjDict_Data, digital_input, sizeof(digital_input));
      digital_output_handler(&ObjDict_Data, digital_output, sizeof(digital_output));
      set_outputs(digital_output[0]);

      // Check if CAN address has been changed
      if(!( nodeID == read_bcd()))
      {
        nodeID = read_bcd();                    // Save the new CAN adress
        setState(&ObjDict_Data, Stopped);         // Stop the node, to change the node ID
        setNodeId(&ObjDict_Data, nodeID);         // Now the CAN adress is changed
        setState(&ObjDict_Data, Pre_operational); // Set to Pre_operational, master must boot it again
      }
    }

    // a message was received pass it to the CANstack
    if (canReceive(&m))			// a message reveived
      canDispatch(&ObjDict_Data, &m);         // process it
    else
    {
      // Enter sleep mode
      #ifdef WD_SLEEP		// Watchdog and Sleep
      wdt_reset();
      sleep_enable();
      sleep_cpu();
      #endif				// Watchdog and Sleep
    }
  }
}
Example #13
0
static void
serial_puts(char *str)
{
    output.str = str;
    output.printing = 1;

    serial_interrupt_dre_enable();

again:
    cli();
    if (output.printing) {
        sleep_enable();
        sei();
        sleep_cpu();
        sleep_disable();
        goto again;
    }
    sei();
}
Example #14
0
int uart1_putchar(char ch, FILE* fp) {
    // End-of-line expansion
    if (ch == '\n') {
        uart1_putchar('\r', fp);
    }

    // This must be done atomically with respect to the transmit interrupt.
    clear_bit(UCSR1B, TXCIE1);

    if (ser_tx_write_pos == ser_tx_read_pos && bit_is_set(UCSR1A, UDRE1)) {
        // Send immediately.
        UDR1 = ch;
    } else {
        // Something is being sent now, so add this character to the ring buffer

        uint8_t next_write_pos;
        while (1) {
            next_write_pos = ser_tx_write_pos + 1;
            if (next_write_pos == SER_TX_SIZE) {
                next_write_pos = 0;
            }

            if (next_write_pos == ser_tx_read_pos) {
                // The ring buffer is full.
                // Sleep until something happens and check again.
                set_bit(UCSR1B, TXCIE1);
                sleep_cpu();
                clear_bit(UCSR1B, TXCIE1);
            } else {
                break;
            }
        }

        ser_tx_buf[ser_tx_write_pos++] = ch;
        if (ser_tx_write_pos == SER_TX_SIZE) {
            ser_tx_write_pos = 0;
        }
    }

    set_bit(UCSR1B, TXCIE1);

    return 0;
}
Example #15
0
/// @see http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html
void powerDown () {
    byte adcsraSave = ADCSRA;
    ADCSRA &= ~ bit(ADEN); // disable the ADC
    // switch off analog comparator - not in Jeelabs' code
    ACSR = ACSR & 0x7F; // note if using it then we need to switch this back on when we wake.
    set_sleep_mode(SLEEP_MODE_PWR_DOWN);
    ATOMIC_BLOCK(ATOMIC_FORCEON) {
        sleep_enable();
        // sleep_bod_disable(); // can't use this - not in my avr-libc version!
#ifdef BODSE
        MCUCR = MCUCR | bit(BODSE) | bit(BODS); // timed sequence
        MCUCR = (MCUCR & ~ bit(BODSE)) | bit(BODS);
#endif
    }
    sleep_cpu();
    sleep_disable();
    // re-enable what we disabled
    ADCSRA = adcsraSave;
}
uint8_t analog_read_p(uint8_t index){
	//Set up which pin to read
	ADMUX = (ADMUX & 0xF0) | index;

	set_sleep_mode(SLEEP_MODE_ADC);
	sleep_enable();

	//Ensure interrupts are enabled, or else CPU will hang until hard reset
	sei();

	//Go to sleep to start ADC
	sleep_cpu();
	
	//Once we are done, disable sleep mode
	sleep_disable();

	//Return conversion result
	return ADCH;
}
Example #17
0
void yackpower(byte n)
/*! 
 @brief     Manages the power saving mode
 
 This is called in yackbeat intervals with either a TRUE or FALSE as parameter. Whenever the
 parameter is TRUE a beat counter is advanced until the timeout level is reached. When timeout
 is reached, the chip shuts down and will only wake up again when issued a level change interrupt on
 either of the input pins.
 
 When the parameter is FALSE, the counter is reset.
 
 @param n   TRUE: OK to sleep, FALSE: Can not sleep now
 
*/

{
    static uint32_t shdntimer=0;
    
    if (n) // True = we could go to sleep
    {
        if(shdntimer++ == YACKSECS(PSTIME))
        {
            shdntimer=0; // So we do not go to sleep right after waking up..

            set_sleep_mode(SLEEP_MODE_PWR_DOWN);
            sleep_bod_disable();
            sleep_enable();
            sei();
            sleep_cpu();
            cli();
            
            // There is no technical reason to CLI here but it avoids hitting the ISR every time
            // the paddles are touched. If the remaining code needs the interrupts this is OK to remove.
            
        }
        
    }
    else // Passed parameter is FALSE
    {
        shdntimer=0;
    }

}
Example #18
0
int main(void)
{
	ADC_init();
	powermgmt(); 
	uint8_t i;
	DDRB |= (1 << PB5)|(1 << PB4);       							//Set DDR of PORTB of LED 1 & LED 2-High(output)		
	while(1)										 
	{ 
		sleep_cpu();
 		for(i=0; i<=1; i++)
		{	
 			if(i==0)
 			{
 				ADC_converted = read_ADC(0);                 //Read one ADC channel 
 				sleep_disable();
 				if(ADC_converted < 50)
 				{
 					PORTB |= (1<<PB5);    //If ADC value is Below "10"(i.e darkness) turn led on
 				}
 				else
 				{
 					PORTB &= ~(1<<PB5);    //Else turn led off
 				}
 			}
 			else if(i==1)
 			{
 				ADC_converted = read_ADC(1);                 //Read one ADC channel
 				sleep_disable();
 				if(ADC_converted > 120)
 				{
 					PORTB |= (1<<PB4);    //If ADC value is Above 121(i.e temperature higher than room temperature) turn led on
 				}
 				else if(ADC_converted < 120)
 				{
 					PORTB &= ~(1<<PB4);    //Else turn led off
 				}
 			}
 			_delay_ms(400);					 //0.4 second switching between LDR and NTC
 		}
	}
	return 0;
}
Example #19
0
void hwPowerDown(const uint8_t wdto)
{
	// Let serial prints finish (debug, log etc)
#ifndef MY_DISABLED_SERIAL
	MY_SERIALDEVICE.flush();
#endif

	// disable ADC for power saving
	ADCSRA &= ~(1 << ADEN);
	// save WDT settings
	const uint8_t WDTsave = WDTCSR;
	if (wdto != WDTO_SLEEP_FOREVER) {
		wdt_enable(wdto);
		// enable WDT interrupt before system reset
		WDTCSR |= (1 << WDCE) | (1 << WDIE);
	} else {
		// if sleeping forever, disable WDT
		wdt_disable();
	}
	set_sleep_mode(SLEEP_MODE_PWR_DOWN);
	cli();
	sleep_enable();
#if defined(__AVR_ATmega328P__)
	sleep_bod_disable();
#endif
	// Enable interrupts & sleep until WDT or ext. interrupt
	sei();
	// Directly sleep CPU, to prevent race conditions!
	// Ref: chapter 7.7 of ATMega328P datasheet
	sleep_cpu();
	sleep_disable();
	// restore previous WDT settings
	cli();
	wdt_reset();
	// enable WDT changes
	WDTCSR |= (1 << WDCE) | (1 << WDE);
	// restore saved WDT settings
	WDTCSR = WDTsave;
	sei();
	// enable ADC
	ADCSRA |= (1 << ADEN);
}
Example #20
0
// Sleep until the timer match interrupt fired. If interruptible is
// true, this can return before if some other interrupt wakes us up
// from sleep. If this happens, true is returned.
bool SleepHandler::sleepUntilMatch(bool interruptible) {
  // When the timer is in asynchronous mode, it takes up to two
  // 32kHz clock cycles for register writes to take effect. Wait
  // until that's done before sleeping.
  while (ASSR & ASSR_BUSY_MASK) /* wait */;

  while (true) {
    #ifdef sleep_bod_disable
    // On 256rfr2, BOD is automatically disabled in deep sleep, but
    // some other MCUs need explicit disabling. This should happen shortly
    // before actually sleeping. It's always automatically re-enabled.
    sleep_bod_disable();
    #endif
    sei();
    // AVR guarantees that the instruction after sei is executed, so
    // there is no race condition here
    sleep_cpu();
    // Immediately disable interrupts again, to ensure that
    // exactly one interrupt routine runs after wakeup, so
    // we prevent race conditions and can properly detect if
    // another interrupt than overflow occurred.
    cli();
    if (!timer_match && interruptible) {
      // We were woken up, but the overflow interrupt
      // didn't run, so another interrupt must have
      // triggered. Note that if the overflow
      // interrupt did run, but also another (lower
      // priority) interrupt occured, its flag will
      // remain set and it will immediately wake us up
      // on the next sleep attempt.
      return false;
    }
    // See if overflow happened. Also check the TOV2 flag,
    // for the case where the overflow happens together with
    // another (higher priority) interrupt.
    if (timer_match || TIFR2 & (1 << TOV2)) {
      TIFR2 = (1 << TOV2);
      timer_match = false;
      return true;
    }
  }
}
void Sleep(byte interval)
{ 
    noInterrupts ();   // timed sequence below
    
    MCUSR = 0;                          // reset various flags
    WDTCSR |= 0b00011000;               // see docs, set WDCE, WDE
    WDTCSR =  0b01000000 | interval;    // set WDIE, and appropriate delay
    wdt_reset();
    
    byte adcsra_save = ADCSRA;
    ADCSRA = 0;  // disable ADC
    set_sleep_mode (SLEEP_MODE_PWR_DOWN);   // sleep mode is set here
    sleep_enable();
    
    interrupts ();
    sleep_cpu ();            // now goes to Sleep and waits for the interrupt
   
    ADCSRA = adcsra_save;  // stop power reduction(Enable ADC)
  
}
Example #22
0
//#START_FUNCTION_HEADER//////////////////////////////////////////////////////
//#	
//# Description: 	Puts the unit into sleep while enabling proper interrupts to 
//#					exit sleep mode.  In normal mode, we want to sleep in between
//#					data ready aquisitions to maximize power.  When no motion is present,
//#					we only want to be woken up by BLE or movement again, not data
//#					ready.
//#
//# Parameters:		still --> 	true = disable acc data interrupts
//#								false = enable acc data interrupts
//#
//# Returns: 		Nothing
//#
//#//END_FUNCTION_HEADER////////////////////////////////////////////////////////
	void sleep_handler(bool still)
	{
		got_slp_wake = false;
		got_data_acc = false;
		got_int_ble = false;
		factory_sleep = false;

		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_enable();
		cli();
		sleep_bod_disable();
		enable_int(PCIE0);
		enable_int(PCIE1);
		still ? disable_int(PCIE2) : enable_int(PCIE2);	//if we want to sleep in between data reads AND when no motion occurs
		clear_acc_ints();
		sei();
		sleep_cpu();
		sleep_disable();
		enable_int(PCIE2);
	}
Example #23
0
void    setSleep(void) {
	//dbg << ',';																// some debug
	//_delay_ms(10);															// delay is necessary to get it printed on the console before device sleeps
	//_delay_ms(100);

	// some power savings by switching off some CPU functionality
	ADCSRA = 0;																	// disable ADC
	backupPwrRegs();															// save content of power reduction register and set it to all off

	sleep_enable();																// enable sleep
	offBrownOut();																// turn off brown out detection

	sleep_cpu();																// goto sleep
	// sleeping now
	// --------------------------------------------------------------------------------------------------------------------
	// wakeup will be here
	sleep_disable();															// first thing after waking from sleep, disable sleep...
	recoverPwrRegs();															// recover the power reduction register settings
	//dbg << '.';																// some debug
}
Example #24
0
int main(void)
{
	initialize();

	trt_uart_init();

	/* Print a statement to the serial communication terminal when the system is reset. */
	stdout = stdin = stderr = &uart_str;
	fprintf(stdout,"TinyRealTime: 2/9/09\n\r");

	/* Sets up the kernel data structures.
	 * The parameter is the desired starck size of the idle task.
	 * For a null idle task, a stack size of 80 should be sufficient. */
	trtInitKernel(80);

	/* Creates semaphores with identifer semnumber and initial values initval. */
	trtCreateSemaphore(SEM_RX_ISR_SIGNAL, 0);
	trtCreateSemaphore(SEM_STRING_DONE  , 0);
	trtCreateSemaphore(SEM_S            , 1);
	trtCreateSemaphore(SEM_P            , 1);
	trtCreateSemaphore(SEM_I            , 1);
	trtCreateSemaphore(SEM_D            , 1);

	/* Identifies the three functions to the kernel as threads.
	 * The parameters specify pointers to the functions, the
	 * desired stack size, the initial release time, the initial deadline time,
	 * and an abitrary data input structure */
	trtCreateTask(serialTask  , 200, SECONDS2TICKS(0.1), SECONDS2TICKS(0.2 ), &(args[0]));
	trtCreateTask(motorTask   , 200, SECONDS2TICKS(0.3), SECONDS2TICKS(0.32), &(args[1]));

	/* Choose our preferred sleep mode */
	set_sleep_mode(SLEEP_MODE_IDLE);
	/* Set sleep enable (SE) bit */
	sleep_enable();

	/* Sleep the CPU when a task isn't running. */
	while (1) {
		sleep_cpu();
	}

}
Example #25
0
int main(void)
{
OSCCAL=eeprom_read_byte(0x00);        // Настройка генератора.
PRR=0x0b;           // выключаем лишние устройства.
DDRB=0b00000111;    //  настраиваем порт в
PORTB=0b00000000;   // сбрасываем в ноль
DDRA= 0b10011000;    // настраиваем порт А
PORTA=0b00010000;   // выключаем приемопередатчик
DIDR0=0b00000110;   // отключаем цифровые входы от компаратора
// сторожевой таймер
WDTCSR=0x18;        // настраиваем сторожевой таймер
WDTCSR=0x29;        // сторожевой таймер сброс через 8 секунд.
// настройка переменных
flag=0;
set_sleep_mode(SLEEP_MODE_IDLE);
sleep_enable();
id_yd=0;
while (1)
      {  
		 ClsBit(PORTA,pwr_up); // выключаем приемник
		 flag=0;
		 delay_ms(20);
		 ACSR=0b00011011; // включаем компаратор.
		 delay_ms(10);
		 sei(); // разрешаем прерывания 
         while(!flag)  	sleep_cpu();  //ждем удара и усыпляем контролер 
		 // удар произошел передаем данные
		 // 
		 cli(); // запрещаем прерывания.
		 SetBit(PORTA,pwr_up);  // включаем приемник
		 delay_ms(10);       	// задержка 10 ms.
		 LoadConf();         	// загружаем конфигурацию.  
		 // передаем пакет.      
         PutChar(0xe7);
         PutChar(adr);  
         PutChar(id_yd);      
		 ce0; // активизируем передачу    
         delay_ms(9); // делаем выдержку по времени 1 ms.
		 wdr(); // сбрасываем сторожевой таймер.
      }
}
Example #26
0
void os_sleep_cpu(void *user_data, SleepCheck sleep_check)
{
    do
    {
	cli();

	if (sleep_check(user_data))
	{
	    if (_inhibit_deep_sleep) set_sleep_mode(SLEEP_MODE_IDLE);
	    else                     set_sleep_mode(SLEEP_MODE_PWR_SAVE);

	    sleep_enable();
	    sei();
	    sleep_cpu();
	    sleep_disable();
	}

	sei();
    }
    while (sleep_check(user_data));
}
Example #27
0
/**
 ** Handler for USB suspend state. Switch to poewr save mode.
 ** XXX interrupt handler for INT0
 **/
void d12_suspend_handler(void) {
  cli();
  if (!(d12_flags & D12_FLAG_SUSPEND))
    goto end;
  
  if (!d12_is_suspend())
    goto end;
  sei();
  _delay_ms(1);
  if (!d12_is_suspend())
    goto end;

  set_power_save();
  sleep_cpu();

  cli();

 end:
  sei();
  return;
}
Example #28
0
int main(void)
{
	// set for 1 MHz clock
	CPU_PRESCALE(4);

	// set all pins as inputs with pullup resistors
	#if defined(PORTA)
	DDRF = 0;
	PORTF = 0xFF;
	#endif
	DDRB = 0;
	PORTB = 0xFF;
	DDRC = 0;
	PORTC = 0xFF;
	DDRD = 0;
	PORTD = 0xFF;
	#if defined(PORTE)
	DDRE = 0;
	PORTE = 0xFF;
	#endif
	#if defined(PORTF)
	DDRF = 0;
	PORTF = 0xFF;
	#endif

	// initialize USB
	usb_init();

	// do nothing (USB code handles reboot message)
	while (1) {
		_delay_ms(1);
		// put the CPU into low power idle mode
		set_sleep_mode(SLEEP_MODE_IDLE);
		cli();
		sleep_enable();
		sei();
		sleep_cpu();
		sleep_disable();
	}
}
Example #29
0
static void shine_leds(uint16_t dur, uint8_t cur_vals[]) {
  for (TCNT1 = 0; TCNT1 < dur; /*nothing*/) {
    for (uint8_t t = 0; t < BIT_SCHED_LEN; t++) {
      for (uint8_t i = 0; i < NUM_LEDS; i++) {
        uint8_t tmp_port = ALL_GND_PULL_OFF, tmp_ddr = ALL_INPUT;
        if (lookup_on_off(cur_vals[i], t)) {
          turn_led_on(&tmp_ddr, &tmp_port, i);
        }
        DDRA = tmp_ddr;
        PORTA = tmp_port;
      }
      DDRA = ALL_INPUT;
      PORTA = ALL_POS_PULL_ON;
      DDRB = ALL_INPUT;
      PORTB = ALL_POS_PULL_ON;

      if (go_to_sleep) {
        _delay_ms(2000);

        cli();
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_enable();
        // don't wake up via mode button
        GIMSK &=  ~_BV(PCIE0);
        sei();

        sleep_cpu();

        sleep_disable();
        GIMSK |=  _BV(PCIE0);
        _delay_ms(1000);
        go_to_sleep = 0;
      }

      if (next_animation || TCNT1 > dur) break;
    }

    if (next_animation) break;
  }
}
Example #30
0
int main() {

	delay_us(0xFFFF); //brief delay at startup
  	DDRB = 0xFF; //set pins to output, ideally should be more granular

	//Play "Happy Birthday" one time
	play_tone(D5, DUR8D); 
	play_tone(D5, DUR16);
	play_tone(E5, DUR4);
	play_tone(D5, DUR4);
	play_tone(G5, DUR4);
	play_tone(Fsh5, DUR2);
	play_tone(D5, DUR8D);
	play_tone(D5, DUR16);
	play_tone(E5, DUR4);
	play_tone(D5, DUR4);
	play_tone(A5, DUR4);
	play_tone(G5, DUR2);
	play_tone(D5, DUR8D); 
	play_tone(D5, DUR16);
	play_tone(D6, DUR4);
	play_tone(B5, DUR4);
	play_tone(G5, DUR4);
	play_tone(Fsh5, DUR4);
	play_tone(E5, DUR2);
	play_tone(C6, DUR8D); 
	play_tone(C6, DUR16);
	play_tone(B5, DUR4);
	play_tone(G5, DUR4);
	play_tone(A5, DUR4);
	play_tone(G5, DUR2);

	PORTB=0x00; //all pins GND
	DDRB=0xFF; //all pin states Input
        MCUCR = _BV(SM1) |  _BV(SE); //configure sleep mode 
        sleep_cpu(); //sleep until button pressed again  

  	return 0;

}