Beispiel #1
0
int clock_main()
{
    sys_init();
    gpio_init();
    timer0_init();
    lcd_init();

    ds1623_init();

    lcd_fill_rect(0, 0, 240, 320, 0x0000);
    int i = 0;
    for(;;)
    {
        ms_delay(1000);
        update_clock();
        update_temp();
    }
    return 0;
}
int main(void)
{
    wdt_disable();
    /* Clear WDRF in MCUSR */
    MCUSR &= ~(1<<WDRF);
    /* Write logical one to WDCE and WDE */
    /* Keep old prescaler setting to prevent unintentional time-out */
    WDTCSR |= (1<<WDCE) | (1<<WDE);
    /* Turn off WDT */
    WDTCSR = 0x00;
    //DDRA |= 0x07;
    //PORTA &= ~7;
    //DDRC |= 0x07;
    //DDRC |= 0xC0;

    eeprom_read_block(&state, &state_ee, sizeof(state));
    aes_handler_init();
    bus_handler_init();
    serial_init();
    bus_init();
    cmd_init();
    buttons_init();
    leds_init();
    timer0_init();
    sei();
    
    leds_set(0,LED_SHORT_FLASH);

    while( 1 ){
        if( timer0_timebase ){
            timer0_timebase--;
            bus_tick();
            serial_tick();
            buttons_tick();
            leds_tick();
        }
        bus_process();
        serial_process();

        //aes128_enc(data, &ctx); /* encrypting the data block */
    }

}
int main(void)
{
    // connect led to pin PC0
    DDRC |= (1 << 0);

    // initialize timer
    timer0_init(); 

    // loop forever 
    while(1) 
    { 
        // check if the timer count reaches 191 
        if (TCNT0 >= 191)
        {
            PORTC ^= (1 << 0);    // toggles the led
            TCNT0 = 0;            // reset counter
        }
    }
}
Beispiel #4
0
void main()
{

		buzzer_off();
		pcf_8591_init();
		timer0_init();
		timer1_init();
		while(1)
		{
				switch(mod)
				{
						case 1:
									re =  pcf_8591_rd();
									delay(20);
									l3 = weight(re,l3);
									break;
						case 2:
									TR0 = 0;
									if(leixing == 1)
									{
										display(mod,ht1,0);
											Delay1000ms(ht1);
											ht1--;
											if(ht1 == 0)
												mod = 1;
										}
									else
									{	
										display(mod,ht2,0);
											Delay1000ms(ht2);
											ht2--;
										if(ht2 == 0)
												mod = 1;
									}
								
									
									break;
						case 3:
									break;
				}
		}
}
int main(void)
{
    wdt_disable();
    /* Clear WDRF in MCUSR */
    MCUSR &= ~(1<<WDRF);
    /* Write logical one to WDCE and WDE */
    /* Keep old prescaler setting to prevent unintentional time-out */
    WDTCSR |= (1<<WDCE) | (1<<WDE);
    /* Turn off WDT */
    WDTCSR = 0x00;
    DDRC |= 0xC0;

    eeprom_read_block(&state, &state_ee, sizeof(state));
    
    leds_init();
    buttons_init();
    adc_init();
    power_init();
    door_init();
    aes_handler_init();
    bus_handler_init();
    bus_init();
    cmd_init();
    timer0_init();
    sei();
    
    while( 1 ){
        if( timer0_timebase ){
            timer0_timebase--;
            bus_tick();
            door_tick();
            power_tick();
            cmd_tick();
            buttons_tick();
            leds_tick();
        }
        bus_process();
        door_process();
        power_process();
    }

}
void main_init(void) {
    OSCCON = 0x70; //intosc 8MHz
    // adc:RA 0,1,2, OUTPUT:RB 2,5,7, SW(shield):RB 0,3,6, SW(button):RA4,5, LED:RA 3,6,7, SCL:RB4, SDA:RB1
    TRISA = 0x37; //0011,0111
    TRISB = 0x5B; //0101,1011
    ANSELA = 0x07; //Use AN0,1,2
    ANSELB = 0x00; //all digital
    WPUA = 0x30;
    WPUB = 0x5B;
    OPTION_REGbits.nWPUEN = 0;

    adc_init(FVR);
    timer0_init(4);
    timer1_init(2);

    I2C_init();
    LCD_init();

    INTCONbits.PEIE = 1;
}
//call this routine to initialize all peripherals
void init_devices(void)
{
    //stop errant interrupts until set up
    cli(); //disable all interrupts


    DDRD = 0x30;   //port 4 & 5 as outputs

    timer0_init();
    
    MCUCR = 0x00;
    EICRA = 0x00; //extended ext ints
    EIMSK = 0x00;
    
    TIMSK0 = 0x02; //timer 0 interrupt sources
    
    PRR = 0x00; //power controller
    sei(); //re-enable interrupts
    //all peripherals are now initialized
}
Beispiel #8
0
void block_detect()
{
			stop();	
			ssss =SREG;
			cli();
			timer0_init();
			TIMSK |= (1 << OCIE0) | (1 << TOIE0); // timer 0 compare match and overflow interrupt enable 
			sei();
			SREG = ssss;
			drop_down();
			_delay_ms(2000);
			pickup();
			//drop_down();
			
			ssss =SREG;
			cli();
			timer2_init();
			sei();
			ssss = SREG;
			forward();	
}
//************************Main関数****************************
int main(void)
{
	//初期化
	timer_pwm_init();
	io_init();
	timer0_init();
	
	//I2CSlaveの初期化
	I2CSlave_init(SLAVE_ADDRESS,INTERRUPT_OFF);
	I2CSlave_setInitEvent(*initHandler);
	I2CSlave_setSendEvent(*sendHandler);
	I2CSlave_setReceiveEvent(*recieveHandler);
	I2CSlave_setStopEvent(*stopHandler);
	
	//割り込み許可
	sei();
	
	while(1){
		//I2C通信
		I2CSlave_com();
		setTergetSpeed(chengeSignalToSpeed(signals[0]),chengeSignalToSpeed(signals[1]));
	}
}
Beispiel #10
0
int main(void) {
    uint16_t adc_data = 0;
    
    sei(); // Enable interrupts
    fosc_cal(); // Set calibrated 1MHz system clock
    portb_init(); // Set up port B
    usart_init(); // Set up the USART
    timer2_init();  // Set up, stop, and reset timer2
    timer0_init();
    usart_puts("Initialize ADC\r\n");
    adc_init();
    usart_puts("Initialize LCD\r\n");
    lcd_init(); // From LDC_driver
    usart_puts("Start main loop\r\n");
    lcd_puts("Hello",0); // From LCD_functions
    timer2_start(); // Start stimulus
    adc_mux(1); // Switch to the voltage reader at J407
    for(;;) {
        adc_read(&adc_data);
        adc_report(adc_data);
        OCR0A = (uint8_t)(adc_data);
    }// end main for loop
} // end main
Beispiel #11
0
int main()
{
  uint8_t i = 0;

  do_calibration();

  rtc_init();
  timer0_init();

  uart_init( UART_BAUD_SELECT(38400,F_CPU) );
  uart_putc(OSCCAL);  
  uart_putc('\n'); 

  DDRC |= (1<<PC4) | (1<<PC5);  // both pins output

  sei(); // turn on interrupt handler

  while(1)
  {
    delay_ms(100);
    // while ((ASSR & (1<<OCR2BUB)) != 0) {} 
  }
}
Beispiel #12
0
/* SUMMARY:
 * Main function
 * INFO:
 * [1] Start by init the watchdog, see wdt.h for macro options. 
 * [2] Init the current state to the entry state and the collection of return 
 * codes. 
 * [3] Setup the function pointer for the diffrent states. 
 * [4] Init the serial communication and enable global interrupts and 
 * init timer0. 
 * [5] Redirect the stdout and the stdin for serial streams through uart.
 * MAIN LOOP:
 * [1] Assign the function pointer a current state
 * [2] Call the pointed function, and collect it's return code
 * [3] Reset the watchdog
 * [4] Check if the current state is exit and break(This will terminate)
 * [5] If not, then move to the next state, declared in the transition table.
 * [6] Repeat
 */
int
main(void) 
{
    enum state_codes cur_state = ENTRY_STATE;
    enum ret_codes rc;
    uint8_t (* state_fun)(void);

    UART0Init();
    sei();
    timer0_init();

    stdin = stdout = &uart0_str;
    
    for (;;) {
        state_fun = state[cur_state];
        rc = state_fun();
        
        if (EXIT_STATE == cur_state)
            break;
        cur_state = lookup_transitions(cur_state, rc);
    }
    return 0;
}
Beispiel #13
0
/*********************************************************** 
***** 
***** 主函数 
***** 
***********************************************************/  
void main( void )  
{  
    timer0_init();  
    time_set(5, 0);  //设置5小时倒计时  
    while(1)  
    {  
        time_display();  //显示时间  
        if(countTime <= 10)  
        {  
            dpFlag = 0;           
        }  
        else  
        if(countTime <= 20)  
        {  
            dpFlag = 1;   
        }  
        else  
        {  
            countTime = 0;  
            time_judge();   
        }  
    }  
}  
Beispiel #14
0
int main(void)
{
    // connect led to pin PC0
    DDRC |= (1 << 0);

    // initialize timer
     timer0_init();

    // loop forever
    while(1)
    {
        // check if no. of overflows = 12
        if (tot_overflow >= 4)  // NOTE: '>=' is used
        {
            // check if the timer count reaches 53
            if (TCNT0 >= 53)
            {
                PORTC ^= (1 << 0);    // toggles the led
                TCNT0 = 0;            // reset counter
                tot_overflow = 0;     // reset overflow counter
            }
        }
    }
}
Beispiel #15
0
void hw_init(void)
{
   u08 t = md_InhibitPortPullUp;  // see md.h

#ifdef _AVR_IOM2561_H_     
    PRR0 = 0x00;           // turn off power reduction registers on Mega2561
    PRR1 = 0x00;
#endif

    /* setup all ports as pulled up inputs */

    DDRA  = 0x00;   // PortA
    if ((t&1)==0) PORTA = 0xFF;

    DDRB  = 0x00;   // PortB
    if ((t&2)==0) PORTB = 0xFF;

    DDRC  = 0x00;   // PortC
    if ((t&4)==0) PORTC = 0xFF;

    DDRD  = 0x00;   // PortD
    if ((t&8)==0) PORTD = 0xFF;

    DDRE  = 0x00;   // PortE
    if ((t&0x10)==0) PORTE = 0xFF;

    DDRF  = 0x00;   // PortF ADC Port all Input
    if ((t&0x20)==0) PORTF = 0xFF;

    DDRG  = 0x00;   // PortG
    if ((t&0x40)==0) PORTG = 0xFF;

    DDRA = 0x03;    //  PA0 PA1 output
    DDRB |= 0x10;   //  (1<<4);  // PB4 output  Speaker
    DDRC |= 0x04;   //   

    // Watchdog Enabled, Prescaler: OSC/16k
    //  wdt_enable(WDTO_15MS);


    led_set(0, LED_OFF); // turn off all 4 leds

#ifdef TIMER_CODE
    time_not_set = 1;
    timer0_init();
#endif

#ifdef UART0
    uart0_init(9600L, 8, 'N', 1, 0);
    #ifdef MDT_CODE
       if(MDT_COM_PORT == 0) uart0_init(MDT_BAUD_RATE, 8, 'N', 1, 0);
    #endif 
#endif

#ifdef UART1
    uart1_init(9600L, 8, 'N', 1, 0);
    #ifdef MDT_CODE
       if(MDT_COM_PORT == 1) uart1_init(MDT_BAUD_RATE, 8, 'N', 1, 0);
    #endif 
#endif

#ifdef TWI_CODE
//    twi_init();
#endif

#ifdef ADC_CODE
    ACSR = 0x80;       // Analog Comparator Disabled
    adc_init(8);       // start up continuous cycle of ADC capture, channels 0..7
#endif                 // including touch screen digitize
}                      // now relies on timer0 call at 10 KHz
Beispiel #16
0
int main(void)
{

    // for 74HC595 port setting for LCD
    SoftSPI_Init();
    
    // for 74HC595 port setting for LED array
    SoftSPI_LED_Init();
    
    // Initialize LCD
	lcd_init();
	
    // Timer for PWM driver initialize
    timer0_init();
    
    // TachoMeter counter initialize
    timer1_init();

    // delay counter initialize
    timer2_init();
    
    // PWM output port definition
    DDRD |= (1<<PD6);
    
	// USART initialize
	USARTinit(UBRR);
	
	// Ext. Interupt setting
	ExtInterrupt_init();
    
    // TicToc initialize
    tictoc_init(FOSC, Ndiv1);
    
    // Tacho Meter Initialize
    TachoMeter_init(FOSC,Ndiv1);
    
    // Bar-Meter Initialize
    BarMeter_init();
    
    // Facemark character Initialize
    FaceMark_init();
    
    // Set Initial Target IDs
    set_initial_t_id();
    
	// Declarations
	unsigned char*   opening_message0 = "Multi-Function Meter";
    unsigned char*   opening_message1 = "     Timer Test     ";
    unsigned char*   opening_message2 = "   Firmware Rev.6   ";
    
	uint8_t         n, m;					// 'for' loop variables
    
	uint8_t         index = 0;				// LCD displaying data index
	
	uint16_t		maxv = 2352;			// maximum decimal angle data value from 'Defi Link Unit II'
    
	uint8_t         id;						// ID index for processing
    
	uint8_t         valid_packet[Ndata];	// Validtity indicator
	
	uint8_t			low4bits[4];			// Extracted lower 4 bits from byte data
	uint16_t        dec_ang;				// Angle data (decimal)
	float           dec_nrm;				// Angle data (decimal)
	float			value[Ndata];			// Decoded value
    uint16_t        mult_factor[3];		// Multiplying factor for hexadecimal to decimal decoding
    
	uint8_t         digits_int[5];			// Digits integer data
	unsigned char	digits_char[5];			// Digits character data for display
    
	float           div_factor;				// Dividing factor for integer
	uint8_t         digits_valid;			// Indicate digits in integer are valid or invalid
    
    // value = eq_grad * dec_nrm + eq_intercept
    // Gradient-term of decoding equation
	uint16_t eq_grad[] = {
        3,	// Turbo
        9000,	// Tacho
        10,	// Oil pres.
        6,	// Fuel pres.
        900,	// Ext. Temp.
        100,	// Oil Temp.
        100	// Water Temp.
    };
    
    // Intercept-term of decoding equation
    int16_t eq_intercept[] = {
        -1,	// Turbo
        0,	// Tacho
        0,	// Oil pres.
        0,	// Fuel pres.
        200,	// Ext. Temp.
        50,	// Oil Temp.
        20	// Water Temp.
    };
    
    // Definition of number of significant figure
	uint8_t   Nsig[] = {				// Number of significant figures
        3,	// Turbo
        4,	// Tacho
        3,	// Oil pres.
        3,	// Fuel pres.
        4,	// Ext. Temp.
        3,	// Oil Temp.
        3	// Water Temp.
    };
    
    // Deifinition of number of integer figure
	uint8_t	Nint[] = {				// Number of integr digits
        1,	// Turbo
        4,	// Tacho
        2,	// Oil pres.
        1,	// Fuel pres.
        4,	// Ext. Temp.
        3,	// Oil Temp.
        3	// Water Temp.
    };
    
    uint8_t	SIGN[] = {				// Show +/-, enable showing is '1'
        1,	// Turbo
        0,	// Tacho
        0,	// Oil pres.
        0,	// Fuel pres.
        0,	// Ext. Temp.
        0,	// Oil Temp.
        0	// Water Temp.
    };
    
	uint8_t	Nspace[7];				// Number of space between character and digits
    float   Resolution[7];


    RxName[0]		=   "BOOST";
    RxName[1]		=   "TACHO";
    RxName[2]		=   "OIL.P";
    RxName[3]		=   "FUEL.P";
    RxName[4]		=   "EXT.T";
    RxName[5]		=   "OIL.T";
    RxName[6]		=   "WATER.T";

/*
	RxName[0]		=   "Boost";
	RxName[1]		=   "Tacho";
	RxName[2]		=   "Oil.P";
	RxName[3]		=   "Fuel.P";
	RxName[4]		=   "ExTmp";
	RxName[5]		=   "Oil.T";
	RxName[6]		=   "Water.T";
*/
    
/*
	RxName[0]	=   "BS";
	RxName[1]	=   "TC";
	RxName[2]	=   "OP";
	RxName[3]	=   "FP";
	RxName[4]	=   "ET";
	RxName[5]	=   "OT";
	RxName[6]	=   "WT";
*/
    
/*
	RxName[0]	=   "Boost";
	RxName[1]	=   "Tacho";
	RxName[2]	=   "Oil press";
	RxName[3]	=   "Fuel press";
	RxName[4]	=   "Ext. Temp.";
	RxName[5]	=   "Oil Temp.";
	RxName[6]	=   "Water Temp.";
*/
    
    // Definition of Resolution for processing and number of space for display
    for(n=0;n<7;n++){
        Resolution[n] = 1;
        for(m=0;m<Nsig[n]-Nint[n];m++){
            Resolution[n] = Resolution[n] / 10;
        }
        RxNameLength[n] = StrLength(RxName[n]);
        Nspace[n]       = DISP_W - RxNameLength[n] - ( Nsig[n] + (Nsig[n]!=Nint[n]) + SIGN[n] );
    }
    
    
	mult_factor[0] = 1;
	mult_factor[1] = 16;
	mult_factor[2] = 256;
    
    
//    delay_cnt = (unsigned long int)( ( WAIT*1.0 ) * ( (1.0*FOSC)/(1.0*Ndiv2) ) / 256.0 / 1000.0 );
    delay_cnt = (unsigned long int)( ( WAIT*1.0 ) * ( (1.0*FOSC)/1000.0/(1.0*Ndiv2) ) / 256.0 );
    
/*
    // opening @ LED array
    for(n=0;n<=8;n++){
        send_bits_595_LED(0x01 << n);
        _delay_ms(60);
    }

    // opening @ LCD
	_delay_ms(50);
	lcd_locate(1,0);
	for(n=0;n<LCD_W;n++){
		lcd_set_char(opening_message0[n]);
		_delay_ms(20);
	}
    lcd_locate(2,0);
    for(n=0;n<LCD_W;n++){
        lcd_set_char(opening_message1[n]);
        _delay_ms(20);
    }
    lcd_locate(3,0);
    for(n=0;n<LCD_W;n++){
        lcd_set_char(opening_message2[n]);
        _delay_ms(20);
    }
    
    // opening @ LED array
    for(n=0;n<=8;n++){
        send_bits_595_LED(~( 0xff << n ));
        _delay_ms(30);
    }
    _delay_ms(250);
    for(n=0;n<=8;n++){
        send_bits_595_LED( 0xff >> n );
        _delay_ms(30);
    }
    _delay_ms(50);
    for(n=0;n<2;n++){
        send_bits_595_LED(0xff);
        _delay_ms(75);
        send_bits_595_LED(0x00);
        _delay_ms(75);
    }
    
    // Clear Opening
	for(m=0;m<4;m++){
		lcd_locate(m,0);
		for(n=0;n<LCD_W;n++){
			lcd_set_char(0x20);
			_delay_ms(15);
		}
	}
*/
    
    // Initialize data display for Defi Link Tap
    for ( index = 0; index < Ndata; index++ ){
        data_updated[index] = 1;
    }
    
    // Enable Interrupt
    sei();

    // Timer Test
    DDRC = 0b00000001;
    PORTC = 0b00000001;
    // Timer Test
    
	////// Main Process start //////
	while(1){
        
        if(lcd_update){
            DisplayItemInfo();
            lcd_locate((chg_index&0x03)>>1,8-(1-chg_index%2));
            lcd_update = 0;
		}

        ////// Measure Process //////
        
        //// Defi Link Tap ////
		for ( index = 0; index < Ndata; index++ ){
			
            if( data_updated[index] == 1 ){
                data_updated[index] = 0;
                
                // Rx data read
                id = t_id[index];
                
                // Judge data validity
                for( n = 1; n < 4; n++ ){
                    if( ( ( (data[index][n] >= '0') & (data[index][n] <= '9') )
                         |( (data[index][n] >= 'A') & (data[index][n] <= 'F') ) ) ){
                        valid_packet[index] = 1;
                    }else{
                        valid_packet[index] = 0;
                        break;
                    }
                }
                // end of judge
                
                if ( valid_packet[index] == 1 ) {
                    // Change char to angle-dec
                    dec_ang = 0;
                    for( n = 1; n < 4; n++){ // data[0] is neglected because of it is control data
                        if  ( (data[index][n] & 0xf0) == 0x30 ){
                            low4bits[n] = (unsigned int)(data[index][n] & 0x0f);
                        }else if ( (data[index][n] & 0xf0) == 0x40 ){
                            low4bits[n] = (unsigned int)(data[index][n] & 0x0f) + 9;
                        }else{
                            break;
                        }
                        dec_ang = dec_ang + low4bits[n] * mult_factor[3-n];
                    }
                    // end of Change char to angle-dec
                    
                    // Change angle-dec to normlized-dec
                    dec_nrm = (float)dec_ang / (float)maxv;
                    // end of Change angle-dec to normlized-dec
                    
                    // Change dec to ISO
                    value[index] = dec_nrm * eq_grad[id] + eq_intercept[id];
                    // end of change dec to ISO
                }

            }
		}
        
        rpm = TachoMeter();
        
/*
        //debug
        if( rpm > 8000 ){
            rpm = 0;
        }else{
            rpm = rpm + 10;
        }
        //debug
*/
        
        // Fuel Pump Driver
        OCR0A = FuelPumpDriver(rpm, value[2],value[3]);
        // value[2] ... Fuel Pressure
        // value[3] ... Boost

        
        ////// Display Process //////
        if(    ( ( (0xffff - timer2_cnt_last) > delay_cnt ) && ( (timer2_cnt - timer2_cnt_last)             > delay_cnt ) )
            || ( ( (0xffff - timer2_cnt_last) < delay_cnt ) && ( (timer2_cnt + (0xffff - timer2_cnt_last))  > delay_cnt ) ) ){

            timer2_cnt_last = timer2_cnt;

            // Timer Test
            PORTC = ~PORTC;
            // Timer Test
            

            //// Defi Link Tap ////
            for ( index = 0; index < Ndata; index++ ){
                
                // Rx data read
                id = t_id[index];

                // clear value area of LCD
                lcd_locate(index,RxNameLength[id]);
                for (n=0;n<=(DISP_W-RxNameLength[id])-1;n++) {
                    lcd_set_char(' ');
                }
                // end of clear value area
                
                // pad blank area of LCD
                lcd_locate(index,RxNameLength[id]);
                for (n=0;n<Nspace[id];n++){
                    lcd_set_char(' ');
                }
                // end of pad blank area of LCD
                
                // display value
                if ( valid_packet[index] == 1 ) {
                    lcd_set_numeric(value[index],Nint[id],Nsig[id]-Nint[id],SIGN[id]);
                }else if( valid_packet[index] == 0 ){
                    for(n=0;n<(Nsig[id]!=Nint[id])+SIGN[id];n++){
                        lcd_set_char(' ');
                    }
                    for(n=0;n<Nsig[id];n++){
                        lcd_set_char('*');
                    }
                }
                // end of display value

            }
            

            // Display Facemark
            lcd_locate(2,13);
            if((unsigned int)rpm < 3000){
                shobon();
            }else if((unsigned int)rpm < 5000){
                shakin();
            }else{
                kuwa();
                lcd_set_str("  ");
            }

 
            // Update Indicator
            lcd_locate(2,12);
            lcd_set_char(0xff);
 
            
        }else{

            // Clear Update Indicator
            lcd_locate(2,12);
            lcd_set_char(' ');
            
        }
        
        //// Real-Time Update items
        

        // Display RPM
        lcd_locate(0,12);
        lcd_set_numeric((unsigned int)rpm,5,0,0);
        lcd_set_str("RPM");
        
        // Display RPM @ Bar Meter
        lcd_locate(3,12);
        BarMeter_disp((unsigned int)rpm);

        
	}

    return 0;
}
int main(void)
{
	int i;
	int count = 0;
	
	DDRB = 0;
	DDRC = 0;
	DDRE = 0;
	
	// Enable the pullup on RESET pin.
	#if defined(__AVR_AT90PWM316__)
	PORTE = (1<<PINE0);
	PORTE &= ~(1<<PINE0);
	#elif defined(__AVR_ATmega328__) || defined(__AVR_ATmega328P__)
	PORTC = (1<<PINC6);
	PORTC &= ~(1<<PINC6);
	#else
	#warning "Didn't enable reset pin pullup"
	#endif
	
	// Setup all of port C as inputs, except for pin C5
	SETUP_DEBUG_PINS();
	
	// Set up the ADC single conversion pin.
	DDRC  &= ~(1<<PINC6);
	PORTC &= ~(1<<PINC6);
	
	// Disable all the ADC digital inputs.
	DIDR1 = 0xFF;
	DIDR0 = 0xFF & ~(1<<ADC1D);
	
	// populate the buffer with known values
	ringBuffer_initialize(&txbuffer,txbuffer_storage,TXBUFFER_LEN);
	ringBuffer_initialize(&adcbuffer,adcbuffer_storage,BUFFER_LEN);
	ringBuffer_initialize(&rxbuffer,rxbuffer_storage,RXBUFFER_LEN);
	
	// Populate the ADC read schedule with the mux indices that you want.
	adc_mux_schedule[0] = 2;
	adc_mux_schedule[1] = 10;
	adc_mux_schedule[2] = 6;
	adc_mux_schedule[3] = 3;
	
	
	uart_init( UART_BAUD_SELECT_DOUBLE_SPEED(UART_BAUD_RATE,F_CPU), &rxbuffer, &txbuffer);
	//uart_config_default_stdio();
	// Translate those indices and the mask specifying which MUXes to turn on,
	// to an encoded mux schedule that the ADC understands.
	adc_encode_muxSchedule(adc_mux_schedule, SCHEDULE_LEN);
	
	
	adc_init(ADC_MODE_MANUAL, &adcbuffer, adc_mux_schedule, SCHEDULE_LEN);
	timer0_init();
	sei();
	uart_puts_P("\f\r\n\r\nADC and UART Demo. Commands:\n"
				"b      Begin 4 channel read bursts at CLK/16K\n"
				"e      End reading.\n"
				"s      Single conversion.\n");
	
	DEBUG_PIN1_OFF();
	while(1)
	{
		do
		{
			i = uart_getc();
		} while (i == UART_NO_DATA);
		DEBUG_PIN1_ON();
		if(i == 'b'){
			uart_puts_P("Begin.\n");
			start_timer0();
		}
		else if(i == 'e'){
			stop_timer0();
			_delay_us(100);
			uart_puts_P("End.\n");
		}
		else if(i == 's'){
			uart_puts_P("ADC");
			uart_put_hex8(count);
			uart_puts_P(": ");
			i = adc_single_conversion(count);
			uart_put_hex8((i >> 8) & 0xFF);
			uart_put_hex8(i & 0xFF);
			uart_putc('\n');
			count = (count + 1) & 0xF;
			if(count == 11)
			{
				count = 13;
			}
		}
		else{
Beispiel #18
0
int main(void)
{
	PCMSK0 = _BV(PCINT6);	//	PCINT on pa6
	PCMSK1 = _BV(PCINT14);	//	PCINT on pb6
	GIMSK  = _BV(PCIE1);	//	enable PCINT

	PRR =		(0 << 7)		|
				(0 << 6)		|	// reserved
				(0 << 5)		|
				(0 << 4)		|
				(0 << PRTIM1)	|	// timer1
				(0 << PRTIM0)	|	// timer0
				(0 << PRUSI)	|	// usi
				(0 << PRADC);		// adc / analog comperator

	uint8_t slot;

	DDRA = 0;
	DDRB = 0;

	for(slot = 0; slot < OUTPUT_PORTS; slot++)
		*output_ports[slot].ddr |= _BV(output_ports[slot].bit);

	for(slot = 0; slot < PWM_PORTS; slot++)
		*pwm_ports[slot].ddr |= _BV(pwm_ports[slot].bit);

	for(slot = 0; slot < OUTPUT_PORTS; slot++)
	{
		softpwm_meta[slot].duty		= 0;
		softpwm_meta[slot].pwm_mode	= pwm_mode_none;
	}

	for(slot = 0; slot < PWM_PORTS; slot++)
		pwm_meta[slot].pwm_mode	= pwm_mode_none;

	for(slot = 0; slot < COUNTER_PORTS; slot++)
		counters_meta[slot].counter = 0;

	for(slot = 0; slot < OUTPUT_PORTS; slot++)
	{
		ioport = &output_ports[slot];
		*ioport->port |= _BV(ioport->bit);
		_delay_ms(50);
	}

	for(slot = 0; slot < OUTPUT_PORTS; slot++)
	{
		ioport = &output_ports[slot];
		*ioport->port &= ~_BV(ioport->bit);
		_delay_ms(50);
	}

	for(slot = 0; slot < PWM_PORTS; slot++)
	{
		pwmport = &pwm_ports[slot];
		*pwmport->port |= _BV(pwmport->bit);
		_delay_ms(50);
	}

	for(slot = 0; slot < PWM_PORTS; slot++)
	{
		pwmport = &pwm_ports[slot];
		*pwmport->port &= ~_BV(pwmport->bit);
		_delay_ms(50);
	}

	adc_init();

	// 8 mhz / 256 / 256 = 122 Hz
	timer0_init(TIMER0_PRESCALER_256);
	timer0_set_max(0xff);

	// 8 mhz / 32 / 1024 = 244 Hz
	pwm_timer1_init(PWM_TIMER1_PRESCALER_32);
	pwm_timer1_set_max(0x3ff);
	pwm_timer1_start();

	watchdog_setup(WATCHDOG_PRESCALER);
	watchdog_start();

	usi_twi_slave(0x02, 1, twi_callback, 0);

	return(0);
}
Beispiel #19
0
// ----------------------------------------------------------------------------------------------
//  M A I N
// ----------------------------------------------------------------------------------------------
void main(void)
{   
    
   port_init(); 
    timer0_init();
   timer0_Delay(1000);
   SPI_masterInit(); 
   LED_RUN_ON;
   LED_ERROR_ON;
  
   CAN_Init(CAN_PARAMS,  CAN_BAUD_500);  
   CAN_setAcceptFilter(CAN_PARAMS, 2, 0x200);
   LED_ERROR_OFF;
   timer0_Delay(1000);
   
  can_msg_out.ID = 0x100;


  can_msg_out.DLEN = 2;

  //рабочий цикл
  while(1)
  { 
  //-------------------------------------
  // собираем пакет
  packages();
  
  //------------------------------------------------------
   //Посылаем пакет
   if ( (timer0_getCounter() - hbit) > 200) { CAN_Msg_Send(CAN_PARAMS,&can_msg_out); hbit = timer0_getCounter(); LED_RUN_SWITCH; }
   
   //Получаем КАН сообщение
   if (CAN_msg_Read(CAN_PARAMS, &can_msg_in)) 
    { 
	 //Обнуляем флаг ошибки
	 if (err_flag) {LED_ERROR_OFF; err_flag = 0;}
	 //Обрабатываем
	 Process_data(); 
	 //Запоминаем, когда последний раз получили	  
	 timestamp1 =  timer0_getCounter();
	}
 
   //если не получили, проверяем тайм аут
   if ( (timer0_getCounter() - timestamp1) > MAX_timeout )
   {
       err_flag = 1;
	
	   //смотрим, горит ли error
	   //если не горит - включаем и запоминаем когда включили
		
		if ( (timer0_getCounter() - timestamp2) > timeout) 
		  if ( (PORTD & BIT(6)) )
		   {
		    LED_ERROR_ON; 
			B1LED_ON;
			B2LED_ON;
		    timestamp2 = timer0_getCounter();
		    if (!kolvo) {timeout = 600;}
			 else 
			  {timeout = 500; }
		   }
		   else
		   {
		    LED_ERROR_OFF;
			B1LED_OFF;
			B2LED_OFF; 
			timestamp2 = timer0_getCounter();
		    if (kolvo) {timeout = 600;kolvo=0;}
			 else 
			  {timeout = 500;kolvo=1; }
		   }
		   
		   
	  } 
 }
}
Beispiel #20
0
int main(void)
{

    // for 74HC595 port setting for LCD
    SoftSPI_Init();
    
    // for 74HC595 port setting for LED array
    SoftSPI_LED_Init();
    
    // Initialize LCD
	lcd_init();
	
    // Interval Measure
    timer1_init();

    // PWM putput port definition
    DDRD |= (1<<PD6);
    
    // PWM counter init
    timer0_init();
    
	// USART initialize
	USARTinit(UBRR);
	
	// Ext. Interupt setting
	ExtInterrupt_init();
    
    // Bar-Meter Initialize
    BarMeter_init();
    
    // Facemark character Initialize
    FaceMark_init();
    
    // Set Initial Target IDs
    set_initial_t_id();

	// Declarations
	unsigned char*   opening_message0 = "Multi-Function Meter";
    unsigned char*   opening_message1 = " w/ FuelPump Driver ";
    unsigned char*   opening_message2 = "  Firmware  Rev.3   ";
    
	uint8_t         n, m;					// 'for' loop variables
    
    uint8_t        FPDcomp = 0xff;
    
	uint8_t         index = 0;				// LCD displaying data index
	
	uint16_t		maxv = 2352;			// maximum decimal angle data value from 'Defi Link Unit II'
    
	uint8_t         id;						// ID index for processing
    
	uint8_t         valid_packet[Ndata];	// Validtity indicator
	
	uint8_t			low4bits[4];			// Extracted lower 4 bits from byte data
	uint16_t        dec_ang;				// Angle data (decimal)
	float           dec_nrm;				// Angle data (decimal)
	float			value[Ndata];			// Decoded value
	uint8_t         digits_int[5];			// Digits integer data
	unsigned char	digits_char[5];			// Digits character data for display
    
	uint16_t        mult_factor[3];		// Multiplying factor for hexadecimal to decimal decoding
	float           div_factor;				// Dividing factor for integer
	uint8_t         digits_valid;			// Indicate digits in integer are valid or invalid
    
    // value = eq_grad * dec_nrm + eq_intercept
    // Gradient-term of decoding equation
	uint16_t eq_grad[] = {
        3,	// Turbo
        9000,	// Tacho
        10,	// Oil pres.
        6,	// Fuel pres.
        900,	// Ext. Temp.
        100,	// Oil Temp.
        100	// Water Temp.
    };
    
    // Intercept-term of decoding equation
    int16_t eq_intercept[] = {
        -1,	// Turbo
        0,	// Tacho
        0,	// Oil pres.
        0,	// Fuel pres.
        200,	// Ext. Temp.
        50,	// Oil Temp.
        20	// Water Temp.
    };
    
    // Definition of number of significant figure
	uint8_t   Nsig[] = {				// Number of significant figures
        3,	// Turbo
        4,	// Tacho
        3,	// Oil pres.
        3,	// Fuel pres.
        4,	// Ext. Temp.
        3,	// Oil Temp.
        3	// Water Temp.
    };
    
    // Deifinition of number of integer figure
	uint8_t	Nint[] = {				// Number of integr digits
        1,	// Turbo
        4,	// Tacho
        2,	// Oil pres.
        1,	// Fuel pres.
        4,	// Ext. Temp.
        3,	// Oil Temp.
        3	// Water Temp.
    };
    
    uint8_t	SIGN[] = {				// Show +/-, enable showing is '1'
        1,	// Turbo
        0,	// Tacho
        0,	// Oil pres.
        0,	// Fuel pres.
        0,	// Ext. Temp.
        0,	// Oil Temp.
        0	// Water Temp.
    };
    
	uint8_t	Nspace[7];				// Number of space between character and digits
    float   Resolution[7];
    
    RxName[0]		=   "BOOST";
    RxName[1]		=   "TACHO";
    RxName[2]		=   "OIL.P";
    RxName[3]		=   "FUEL.P";
    RxName[4]		=   "EXT.T";
    RxName[5]		=   "OIL.T";
    RxName[6]		=   "WATER.T";

/*
	RxName[0]		=   "Boost";
	RxName[1]		=   "Tacho";
	RxName[2]		=   "Oil.P";
	RxName[3]		=   "Fuel.P";
	RxName[4]		=   "ExTmp";
	RxName[5]		=   "Oil.T";
	RxName[6]		=   "Water.T";
*/
    
/*
	RxName[0]	=   "BS";
	RxName[1]	=   "TC";
	RxName[2]	=   "OP";
	RxName[3]	=   "FP";
	RxName[4]	=   "ET";
	RxName[5]	=   "OT";
	RxName[6]	=   "WT";
*/
    
/*
	RxName[0]	=   "Boost";
	RxName[1]	=   "Tacho";
	RxName[2]	=   "Oil press";
	RxName[3]	=   "Fuel press";
	RxName[4]	=   "Ext. Temp.";
	RxName[5]	=   "Oil Temp.";
	RxName[6]	=   "Water Temp.";
*/
    
    // Definition of Resolution for processing and number of space for display
    for(n=0;n<7;n++){
        Resolution[n] = 1;
        for(m=0;m<Nsig[n]-Nint[n];m++){
            Resolution[n] = Resolution[n] / 10;
        }
        RxNameLength[n] = StrLength(RxName[n]);
        Nspace[n]       = DISP_W - RxNameLength[n] - ( Nsig[n] + (Nsig[n]!=Nint[n]) + SIGN[n] );
    }
    
	mult_factor[0] = 1;
	mult_factor[1] = 16;
	mult_factor[2] = 256;
    for(m=0;m<3;m++){
        for(n=0;n<=m;n++){
            
        }
    }
    
    
    // opening @ LED array
    for(n=0;n<=8;n++){
        send_bits_595_LED(0x01 << n);
        _delay_ms(50);
    }

    // opening @ LCD
	_delay_ms(50);
	lcd_locate(1,0);
	for(n=0;n<LCD_W;n++){
		lcd_set_char(opening_message0[n]);
		_delay_ms(20);
	}
    lcd_locate(2,0);
    for(n=0;n<LCD_W;n++){
        lcd_set_char(opening_message1[n]);
        _delay_ms(20);
    }
    lcd_locate(3,0);
    for(n=0;n<LCD_W;n++){
        lcd_set_char(opening_message2[n]);
        _delay_ms(20);
    }
    
    // opening @ LED array
    for(n=0;n<=8;n++){
        send_bits_595_LED(~( 0xff << n ));
        _delay_ms(30);
    }
    _delay_ms(250);
    for(n=0;n<=8;n++){
        send_bits_595_LED( 0xff >> n );
        _delay_ms(30);
    }
    _delay_ms(50);
    for(n=0;n<2;n++){
        send_bits_595_LED(0xff);
        _delay_ms(75);
        send_bits_595_LED(0x00);
        _delay_ms(75);
    }
    
    // Clear Opening
	for(m=0;m<4;m++){
		lcd_locate(m,0);
		for(n=0;n<LCD_W;n++){
			lcd_set_char(0x20);
			_delay_ms(15);
		}
	}
    
    // Enable Interrupt
    sei();

	// Main function start this
	while(1){

        if(lcd_update){
            DisplayItemInfo();
            lcd_locate((chg_index&0x03)>>1,8-(1-chg_index%2));
            lcd_update = 0;
		}

        
        ////// Measure Sequence //////
        
        //// Defi Link Tap ////
		for ( index = 0; index < Ndata; index++ ){
			
			// Rx data read
			id = t_id[index];
            
			// Judge data validity
			for( n = 1; n < 4; n++ ){
                if( ( ( (data[index][n] >= '0') & (data[index][n] <= '9') )
                     |( (data[index][n] >= 'A') & (data[index][n] <= 'F') ) ) ){
					valid_packet[index] = 1;
				}else{
				 	valid_packet[index] = 0;
		 			break;
				}
			}
			// end of judge
            
			if ( valid_packet[index] == 1 ) {
				// Change char to angle-dec
                dec_ang = 0;
				for( n = 1; n < 4; n++){ // data[0] is neglected because of it is control data
					if  ( (data[index][n] & 0xf0) == 0x30 ){
						low4bits[n] = (unsigned int)(data[index][n] & 0x0f);
					}else if ( (data[index][n] & 0xf0) == 0x40 ){
						low4bits[n] = (unsigned int)(data[index][n] & 0x0f) + 9;
					}else{
						break;
					}
					dec_ang = dec_ang + low4bits[n] * mult_factor[3-n];
				}
				// end of Change char to angle-dec
                
                // Change angle-dec to normlized-dec
                dec_nrm = (float)dec_ang / maxv;
                // end of Change angle-dec to normlized-dec
                
				// Change dec to ISO
				value[index] = dec_nrm * eq_grad[id] + eq_intercept[id];
                // end of change
				
            }
		}
        
        
        // Tacho Meter
            //Median Filter
            for(n=0;n<Nmed;n++){
                proc_array[n] = meas_array[n];
            }
            BubbleSort();
        
            // Calculate frequency
            if(meas_array[tacho_n] >= 0xffff){          // Too Long Gap Pulse
                freq = 0;
            }else{                                      // Last Pulse
                freq = FOSC / Ndiv1 / meas_array[tacho_n];
            }
        
            // Decide measured frequency is valid or invalid
            if( ( freq - freq_cur ) < RPM_DIFF/60.0 ){  // Tracking
                freq_cur = freq;
            }else{                                      // Force Track
                
                // add 2014/11/9
                // 小さいヒゲの分だけ回転数が上がってしまうので、小さいヒゲのカウントをマージ
                cnt = proc_array[Nmed-1];
                for(n=0;n<Nmed-1;n++){
//                    if( proc_array[n] < proc_array[Nmed-1]/20 ){ //3500rpm以上が表示されない
                    if( proc_array[n] < 100 ){
                        cnt = cnt +proc_array[n];
                    }else{
                        break;
                    }
                }
                
//                freq_cur = FOSC / Ndiv1 / proc_array[Nmed>>1]; //debug
                //メディアンフィルタで中央値を取るとノイズを拾う。。。
                
                freq_cur = FOSC / Ndiv1 / cnt;
            }
//        freq_cur = freq;
        
            // Calcurate RPM
            rpm = (unsigned long int)( 60.0 * freq_cur / Npulse );

        
        // Fuel Pump Driver
        if( rpm > 5000 ) FPDcomp = 0xff;
        else FPDcomp = rpm / 5000.0 * 0xff + 0x48;
        OCR0A = FPDcomp;

        
        
        ////// Display sequence //////
        
        //// Defi Link Tap ////
        for ( index = 0; index < Ndata; index++ ){
            
            // Rx data read
            id = t_id[index];

            // clear value area of LCD
            lcd_locate(index,RxNameLength[id]);
            for (n=0;n<=(DISP_W-RxNameLength[id])-1;n++) {
                lcd_set_char(' ');
            }
            // end of clear value
            
            // pad blank area of LCD
            lcd_locate(index,RxNameLength[id]);
            for (n=0;n<Nspace[id];n++){
                lcd_set_char(' ');
            }
            // end of pad blank area of LCD
            
            if ( valid_packet[index] == 1 ) {
                lcd_set_numeric(value[index],Nint[id],Nsig[id]-Nint[id],SIGN[id]);
            }else if( valid_packet[index] == 0 ){
                for(n=0;n<(Nsig[id]!=Nint[id])+SIGN[id];n++){
                    lcd_set_char(' ');
                }
                for(n=0;n<Nsig[id];n++){
                    lcd_set_char('*');
                }
            }

        }
        
        // Display RPM
        lcd_locate(0,12);
        lcd_set_numeric((unsigned int)rpm,5,0,0);
        lcd_set_str("RPM");
        
        // Display Freq
        lcd_locate(1,12);
        if((unsigned int)rpm < 3000){
            shobon();
        }else if((unsigned int)rpm < 5000){
            shakin();
        }else{
            kuwa();
            lcd_set_str("  ");
        }

/*
        // Display Freq
        lcd_locate(1,12);
        lcd_set_numeric((unsigned int)freq,5,0,0);
        lcd_set_str("Hz");
*/
        
/*
        // Display FuelPump Duty
        lcd_locate(2,12);
        lcd_set_str("DUTY ");
        lcd_set_numeric((unsigned int)(FPDcomp*1.0/0xff*100),3,0,0);
*/
        
        //debug
        lcd_locate(2,12);
        lcd_set_str("L");
        lcd_set_numeric((unsigned int)TCNT_LIM,7,0,0);
        
        // Display Bar Meter RPM
        lcd_locate(3,12);
        BarMeter_disp((unsigned int)rpm);

        /*
        // Display Bar Meter FuelPump Duty
        lcd_locate(3,12);
        BarMeter_disp((unsigned int)(FPDcomp*1.0/0xff*100));
        */
        
        LEDarray((unsigned int)rpm);

        // カウントデータデバグ用
/*
        lcd_locate(1,0);
        for(n=0;n<3;n++){
            lcd_set_numeric(proc_array[n+0],4,0,0);
        }
        lcd_locate(2,0);
        for(n=0;n<3;n++){
            lcd_set_numeric(proc_array[n+3],4,0,0);
        }
        lcd_locate(3,0);
        for(n=0;n<3;n++){
            lcd_set_numeric(proc_array[n+6],4,0,0);
        }
*/
        _delay_ms(WAIT);
        
	}

    return 0;
}
Beispiel #21
0
void board_init(void)
{
	timer0_init();
	timer2_init();
	interrupt_init();
}
Beispiel #22
0
/** 
 *  @brief   The main task for the autoshifter      */
int main(void)
{   
    timer0_init();
    timer1_init();
    io_init();
   
    //Create and initialize gears
    Gear g1,g2,g3,g4,g5;
    //Gear_Const(Gear *this, uint8_t num, uint8_t lower, uint8_t upper,
    //           Gear *p, Gear* n)
    
    Gear_Construct(&g1,1,0,100,50,0,&g2);
    uint16_t inc1[MAX_GEARS] = {20,30,40,100,200};
    uint16_t dec1[MAX_GEARS] = {200,100,30,20,10};
    Gear_IncreaseLevels(&g1,inc1);
    Gear_DecreaseLevels(&g1,dec1);

    Gear_Construct(&g2,2,20,200,150,&g1,&g3);
    uint16_t inc2[MAX_GEARS] = {20,40,60,90,160};
    uint16_t dec2[MAX_GEARS] = {400,90,40,20,10};
    Gear_IncreaseLevels(&g2,inc2);
    Gear_DecreaseLevels(&g2,dec2);
   
    Gear_Construct(&g3,3,120,300,250,&g2,&g4);
    uint16_t inc3[MAX_GEARS] = {40,60,80,100,120};
    uint16_t dec3[MAX_GEARS] = {140,80,50,30,10};
    Gear_IncreaseLevels(&g3,inc3);
    Gear_DecreaseLevels(&g3,dec3);
    
    Gear_Construct(&g4,4,200,400,350,&g3,&g5);
    uint16_t inc4[MAX_GEARS] = {20,40,60,80,100};
    uint16_t dec4[MAX_GEARS] = {100,60,40,20,10};
    Gear_IncreaseLevels(&g4,inc4);
    Gear_DecreaseLevels(&g4,dec4);
    
    Gear_Construct(&g5,5,300,500,450,&g4,0);
    uint16_t inc5[MAX_GEARS] = {20,30,40,50,60};
    uint16_t dec5[MAX_GEARS] = {50,40,30,20,10};
    Gear_IncreaseLevels(&g5,inc5);
    Gear_DecreaseLevels(&g5,dec5);
    
    gear_ = &g1;

#ifdef DEBUG
    puts("DEBUG is on.\r\n");
#endif

#ifdef SIMULATE
    puts("SIMULATE is on.\r\n");
#endif
    printf("\rStarting main task...\r\r");
    delay_ms(200);
    ADCSRA |= _BV(ADSC);     //Start ADC Conversion
    //sei();

    //Main task
    for(;;)
    {
        switch(mode)
        {
            case manual:         //Manual
                //If up_shift is pressed and released...
                if(onRelease(&up_shift))
                {
                    if(gear_->next != 0)
                    {
                        shift(SOLEN_UP);
                        gear_ = gear_->next;
                    }
                }

                //If dn_shift is pressed and released...
                if(onRelease(&dn_shift))
                {
                    if(gear_->prev != 0 && tach.rpms < gear_upper())
                    {
                        shift(SOLEN_DN);
                        gear_ = gear_->prev;
                    }
                }
                break;
            case semi_man:
                // Upshift 
                if(tach.rpms >= gear_upper())
                {
                    if(gear_->next != 0)
                    {
                        shift(SOLEN_UP);
                        gear_ = gear_->next;
                    }
                }
                // Downshift
                if(onRelease(&dn_shift))
                {
                    if(gear_->prev != 0 && tach.ave < gear_upper())
                    {
                        shift(SOLEN_DN);
                        gear_ = gear_->prev;
                    }
                }
                break;
            case automated:
                // Upshift
                if(tach.rpms >= gear_upper())
                {
                    if(gear_->next != 0)
                    {
                        shift(SOLEN_UP);
                        gear_ = gear_->next;
                    }
                }
                // Downshift
                else if(tach.rpms < gear_lower())
                {
                    if(gear_->prev != 0)
                    {
                        shift(SOLEN_DN);
                        gear_ = gear_->prev;
                    }
                }
                break;
            default:
                //Should not get here...
                break;
        }
        
        update_ave_rpms();

//#ifdef DEBUG
        if(canPrint)
        {
            //printf("cur pos = %d\n\r",throttle_pos);
            //printf("current ADC = %d\n\r",cur_adc);
            printf("Current mode = %d\n\r", mode);
            printf("Current gear = %d\n\r", gear_num());
            printf("Current rpms = %d\n\r",cur_rpms());
            //printf("Ave rpms = %d\r\r",average_rpms());

            canPrint = 0;
        }
//#endif
       //Give'em a break.
        delay_ms(1);
    }
    // Should never get here
    return 0;
}
Beispiel #23
0
/*
 * Turn on RX carrier sweep. This test uses timer0 to restart the RX carrier above at different channels.
 */
static void radio_rx_sweep_start(uint8_t channel_start, uint8_t delayms)
{
  channel_  = channel_start;
  sweep_tx_ = false;
  timer0_init(delayms);
}
Beispiel #24
0
//* ************************************************************************************************
/// @fn			init_application(void)
/// @brief		Init the watch's program
/// @return		none
//* ************************************************************************************************
void init_application(void)
{
	volatile unsigned char *ptr;
	
	// ---------------------------------------------------------------------
	// Enable watchdog
	
	// Watchdog triggers after 16 seconds when not cleared
#ifdef USE_WATCHDOG
	WDTCTL = WDTPW + WDTIS__512K + WDTSSEL__ACLK;
#else
	WDTCTL = WDTPW + WDTHOLD;
#endif
	
	// ---------------------------------------------------------------------
	// Configure PMM
	
	SetVCore(3);
	
	// Set global high power request enable
	PMMCTL0_H  = 0xA5;
	PMMCTL0_L |= PMMHPMRE;
	PMMCTL0_H  = 0x00;
	
	// ---------------------------------------------------------------------
	// Enable 32kHz ACLK
	
	P5SEL |= 0x03;				// Select XIN, XOUT on P5.0 and P5.1
	UCSCTL6 &= ~XT1OFF;			// XT1 On, Highest drive strength
	UCSCTL6 |= XCAP_3;			// Internal load cap
	
	UCSCTL3 = SELA__XT1CLK;		// Select XT1 as FLL reference
	UCSCTL4 = SELA__XT1CLK | SELS__DCOCLKDIV | SELM__DCOCLKDIV;
	
	// ---------------------------------------------------------------------
	// Configure CPU clock for 12MHz
	
	_BIS_SR(SCG0);				// Disable the FLL control loop
	UCSCTL0 = 0x0000;			// Set lowest possible DCOx, MODx
	UCSCTL1 = DCORSEL_5;		// Select suitable range
	UCSCTL2 = FLLD_1 + 0x16E;	// Set DCO Multiplier
	_BIC_SR(SCG0);				// Enable the FLL control loop
	
	// Worst-case settling time for the DCO when the DCO range bits have been
	// changed is n x 32 x 32 x f_MCLK / f_FLL_reference. See UCS chapter in 5xx
	// UG for optimization.
	// 32 x 32 x 8 MHz / 32,768 Hz = 250000 = MCLK cycles for DCO to settle
	
#if __GNUC_MINOR__ > 5 || __GNUC_PATCHLEVEL__ > 8
	
	__delay_cycles(250000);
	
#else
	
	__delay_cycles(62500);
	__delay_cycles(62500);
	__delay_cycles(62500);
	__delay_cycles(62500);
	
#endif
	
	// Loop until XT1 & DCO stabilizes, use do-while to insure that 
	// body is executed at least once
	do
	{
		UCSCTL7 &= ~(XT2OFFG + XT1LFOFFG + XT1HFOFFG + DCOFFG);
		SFRIFG1 &= ~OFIFG;		// Clear fault flags
	}
	while ((SFRIFG1 & OFIFG));
	
	// ---------------------------------------------------------------------
	// Configure port mapping
	
	// Disable all interrupts
	__disable_interrupt();
	// Get write-access to port mapping registers:
	PMAPPWD = 0x02D52;
	// Allow reconfiguration during runtime:
	PMAPCTL = PMAPRECFG;
	
	// P2.7 = TA0CCR1A or TA1CCR0A output (buzzer output)
	ptr  = &P2MAP0;
	*(ptr + 7) = PM_TA1CCR0A;
	P2OUT &= ~BIT7;
	P2DIR |= BIT7;
	
	// P1.5 = SPI MISO input
	ptr  = &P1MAP0;
	*(ptr + 5) = PM_UCA0SOMI;
	// P1.6 = SPI MOSI output
	*(ptr + 6) = PM_UCA0SIMO;
	// P1.7 = SPI CLK output
	*(ptr + 7) = PM_UCA0CLK;
	
	// Disable write-access to port mapping registers:
	PMAPPWD = 0;
	// Re-enable all interrupts
	__enable_interrupt();
	
	// Init the hardwre real time clock (RTC_A)
	rtca_init();
	
	// ---------------------------------------------------------------------
	// Configure ports
	
	// ---------------------------------------------------------------------
	// Reset radio core
	
	radio_reset();
	radio_powerdown();
	
	// ---------------------------------------------------------------------
	// Init acceleration sensor
	
#ifdef CONFIG_MOD_ACCELEROMETER
	as_init();
#else
	as_disconnect();
#endif
	
	// ---------------------------------------------------------------------
	// Init LCD
	
	lcd_init();
	
	// ---------------------------------------------------------------------
	// Init buttons

	init_buttons();
	
	// ---------------------------------------------------------------------
	// Configure Timer0 for use by the clock and delay functions
	
	timer0_init();
	
	// Init buzzer
	buzzer_init();
	
	// ---------------------------------------------------------------------
	// Init pressure sensor
	
#ifdef CONFIG_PRESSURE_SENSOR
	ps_init();
#endif
	
	// ---------------------------------------------------------------------
	// Init other sensors
	
	// From: "driver/battery"
	battery_init();
	
	// From: "drivers/temperature"
	temperature_init();
	
	/// @todo What is this ?
#ifdef CONFIG_INFOMEM
	
	if (infomem_ready() == -2)
		infomem_init(INFOMEM_C, INFOMEM_C + 2 * INFOMEM_SEGMENT_SIZE);
	
#endif

}
Beispiel #25
0
int main(void)
{
        struct rtc_time_var rtc;
        uint8_t timer0_prev_sec;
        char buf[256];

#ifdef APP_ADC_EEPROM
        uint8_t adc_curr = 0;
        uint8_t adc_prev = 0;
        int adc_diff;

        uint16_t eeprom_index = 0;
        uint8_t eeprom_nbr_chars = 0;
#endif
        /* Initialize UART0, serial printing over USB on Arduino Mega */
        uart0_init();

        /* Initialize blinking LED */
        led_init();

        /* Initialize I2C */
        i2c_init();

        /* Initialize Timer0 */
        timer0_init();

        /* Initialize INT4 button */
        button_init();

        /* Initialize ADC */
        adc0_init();

        /* Enable global interrupts (used in I2C) */
        sei();

        /* Added startup delay after IRQ-enable and followed by a boot print */
        _delay_ms(1000);
        printf("\n\nTiny RTC firmware successfully started!\n\n");
        printf("RTC DS1307 I2C-addr:0x%x\n", DS1307);
        printf("EEPROM AT24C32 I2C-addr:0x%x\n\n", AT24C32);

        rtc_init();

        /* Write dummy data to the RTC RAM */
        rtc_set_ram_buf((uint8_t *)Dummy_RTC_RAM, strlen(Dummy_RTC_RAM));

        /* Write dummy data to the EEPROM */
        eeprom_set_data(0, (uint8_t *)Dummy_EEPROM, strlen(Dummy_EEPROM));

        _delay_ms(1000);

        /* Read and print dummy data from RTC RAM  */
        memset(buf, 0, sizeof(buf));
        rtc_get_ram_buf((uint8_t *)buf, strlen(Dummy_RTC_RAM));
        printf("RTC RAM read result:%s\n", buf);

        /* Read and print dummy data from EEPROM  */
        memset(buf, 0, sizeof(buf));
        eeprom_get_data(0, (uint8_t *)buf, strlen(Dummy_EEPROM));
        printf("EEPROM read result:%s\n\n", buf);

        timer0_prev_sec = g_tmr0_sec;
        /* Main loop */
        while (1) {
                if (g_print) {
                        g_print = 0;
#ifdef APP_ADC_EEPROM
                        /* Read out stored EEPROM data upon button-press */
                        eeprom_get_data(0, (uint8_t *)buf, eeprom_index);
                        printf("Stored data[%d]:\n%s\n", eeprom_index, buf);
#else
                        /* Dummy print upon button-press */
                        printf("Button pressed\n");
#endif
                }

                if (timer0_prev_sec == g_tmr0_sec)
                        continue;
                timer0_prev_sec = g_tmr0_sec;
                led_toggle();
                rtc_get_time_var(&rtc);

#ifdef APP_ADC_EEPROM
                /* Poll the current ADC value to see if there is a +/-10%
                 * deviation since the last sample.
                 */
                adc_curr = adc0_get_val_percentage();
                adc_diff = adc_curr - adc_prev;
                adc_prev = adc_curr;
                if (adc_diff > -10 && adc_diff < 10)
                        continue;

                /* Create a char-array containing the RTC-time and the ADC
                 * percentage value and store it in the EEPROM.
                 */
                eeprom_nbr_chars = snprintf(buf, 16, "%d%d:%d%d - %d%%\n",
                                rtc.min_10, rtc.min_1, rtc.sec_10, rtc.sec_1,
                                adc0_get_val_percentage());
                printf("eeprom_index:%d eeprom_nbr_chars:%d %s\n",
                                eeprom_index, eeprom_nbr_chars, buf);
                eeprom_set_data(eeprom_index, (uint8_t *)buf, eeprom_nbr_chars);
                eeprom_index += eeprom_nbr_chars;
#else
                /* Print out the ADC value and the RTC time every second */
                printf("Elapsed RTC time - min:%d%d sec:%d%d\n",
                                rtc.min_10, rtc.min_1, rtc.sec_10, rtc.sec_1);
                printf("Current adc_val:%d %d%%\n\n",
                                adc0_get_val(), adc0_get_val_percentage());
#endif
        }
}
Beispiel #26
0
uint8_t init(void)
{
	uint8_t result;
	
	uart_init();
#if DEBUG
	uart_puts_p(PSTR("INIT Started! \n\n"));
	uart_puts_p(PSTR("uart_init() Completed! \n"));
#endif	
		
	LED_init();
#if DEBUG	
	uart_puts_p(PSTR("LED_init() Completed! \n"));
#endif

	key_init();
#if DEBUG	
	uart_puts_p(PSTR("key_init() Completed! \n"));
#endif
		
	LCD_Init();
#if DEBUG	
	uart_puts_p(PSTR("LCD_Init() Completed! \n"));
#endif	
	set_screen(BOOT_SCN);
	_delay_ms(100);

	set_screen(BOOT_SCN);
	_delay_ms(100);
	set_screen(BOOT_SCN);
	_delay_ms(100);
	set_screen(BOOT_SCN);
	_delay_ms(100);

	gps_init();
#if DEBUG	
	uart_puts_p(PSTR("gps_init() Completed! \n"));
#endif	
	set_screen(BOOT_SCN);
	_delay_ms(100);
	
	timer0_init();
#if DEBUG	
	uart_puts_p(PSTR("timer0_Init() Completed! \n"));
#endif	
	set_screen(BOOT_SCN);
	_delay_ms(100);

	timer1_init();
#if DEBUG	
	uart_puts_p(PSTR("timer1_Init() Completed! \n"));
#endif
	set_screen(BOOT_SCN);
	_delay_ms(100);
	
	result = sdreader_init();
	if(result)
	{
#if DEBUG		
		uart_puts_p(PSTR("ERROR : sdreader_init()"));
		uart_putc_hex(result);
		uart_puts_p(PSTR("\n\r"));
#endif	
		return result;
	}
#if DEBUG	
	else
		uart_puts_p(PSTR("sdreader_init() copmleted! \n\r"));
#endif
	set_screen(BOOT_SCN);
	_delay_ms(100);
	
	sei();
	set_screen(BOOT_SCN);
	_delay_ms(500);
	
	return 0;
}
Beispiel #27
0
int main(void)
{
	uint16_t send_status_timeout = 25;
	uint32_t station_packetcounter;
	uint32_t pos;
	uint8_t button_state = 0;
	uint8_t manual_dim_direction = 0;

	// delay 1s to avoid further communication with uart or RFM12 when my programmer resets the MC after 500ms...
	_delay_ms(1000);

	util_init();
	check_eeprom_compatibility(DEVICE_TYPE_DIMMER);

	osccal_init();
	
	// read packetcounter, increase by cycle and write back
	packetcounter = eeprom_read_dword((uint32_t*)EEPROM_POS_PACKET_COUNTER) + PACKET_COUNTER_WRITE_CYCLE;
	eeprom_write_dword((uint32_t*)EEPROM_POS_PACKET_COUNTER, packetcounter);

	// read device id and write to send buffer
	device_id = eeprom_read_byte((uint8_t*)EEPROM_POS_DEVICE_ID);	
	use_pwm_translation = 1; //eeprom_read_byte((uint8_t*)EEPROM_POS_USE_PWM_TRANSLATION);	
	
	// TODO: read (saved) dimmer state from before the eventual powerloss
	/*for (i = 0; i < SWITCH_COUNT; i++)
	{
		uint16_t u16 = eeprom_read_word((uint16_t*)EEPROM_POS_SWITCH_STATE + i * 2);
		switch_state[i] = (uint8_t)(u16 & 0b1);
		switch_timeout[i] = u16 >> 1;
	}*/
	
	// read last received station packetcounter
	station_packetcounter = eeprom_read_dword((uint32_t*)EEPROM_POS_STATION_PACKET_COUNTER);

	led_blink(200, 200, 5);

#ifdef UART_DEBUG
	uart_init(false);
	UART_PUTS ("\r\n");
	UART_PUTS ("smarthomatic Dimmer V1.0 (c) 2013 Uwe Freese, www.smarthomatic.org\r\n");
	osccal_info();
	UART_PUTF ("Device ID: %u\r\n", device_id);
	UART_PUTF ("Packet counter: %lu\r\n", packetcounter);
	UART_PUTF ("Use PWM translation table: %u\r\n", use_pwm_translation);
	UART_PUTF ("Last received station packet counter: %u\r\n\r\n", station_packetcounter);
#endif

	// init AES key
	eeprom_read_block (aes_key, (uint8_t *)EEPROM_POS_AES_KEY, 32);

	rfm12_init();
	PWM_init();
	io_init();
	setPWMDutyCycle(0);
	timer0_init();

	// DEMO to measure the voltages of different PWM settings to calculate the pwm_lookup table
	/*while (42)
	{
		uint16_t i;
		
		for (i = 0; i <= 1024; i = i + 100)
		{
			UART_PUTF ("PWM value OCR1A: %u\r\n", i);
			OCR1A = i;
			led_blink(500, 6500, 1);
		}
	}*/
	
	// DEMO 0..100..0%, using the pwm_lookup table and the translation table in EEPROM.
	/*while (42)
	{
		float i;
		
		for (i = 0; i <= 100; i = i + 0.05)
		{
			led_blink(10, 10, 1);
			setPWMDutyCycle(i);
		}
		
		for (i = 99.95; i > 0; i = i - 0.05)
		{
			led_blink(10, 10, 1);
			setPWMDutyCycle(i);
		}
	}*/

	// set initial switch state
	/*for (i = 0; i < SWITCH_COUNT; i++)
	{
		switchRelais(i, switch_state[i]);
	}*/

	sei();

	// DEMO 30s
	/*animation_length = 30;
	animation_length = (uint32_t)((float)animation_length * 1000 / ANIMATION_CYCLE_MS);
	start_brightness = 0;
	end_brightness = 255;
	animation_position = 0;*/
	
	while (42)
	{
		if (rfm12_rx_status() == STATUS_COMPLETE)
		{
			uint8_t len = rfm12_rx_len();
			
			if ((len == 0) || (len % 16 != 0))
			{
				UART_PUTF("Received garbage (%u bytes not multiple of 16): ", len);
				printbytearray(bufx, len);
			}
			else // try to decrypt with all keys stored in EEPROM
			{
				memcpy(bufx, rfm12_rx_buffer(), len);
				
				//UART_PUTS("Before decryption: ");
				//printbytearray(bufx, len);
					
				aes256_decrypt_cbc(bufx, len);

				//UART_PUTS("Decrypted bytes: ");
				//printbytearray(bufx, len);

				uint32_t assumed_crc = getBuf32(len - 4);
				uint32_t actual_crc = crc32(bufx, len - 4);
				
				//UART_PUTF("Received CRC32 would be %lx\r\n", assumed_crc);
				//UART_PUTF("Re-calculated CRC32 is  %lx\r\n", actual_crc);
				
				if (assumed_crc != actual_crc)
				{
					UART_PUTS("Received garbage (CRC wrong after decryption).\r\n");
				}
				else
				{
					//UART_PUTS("CRC correct, AES key found!\r\n");
					UART_PUTS("         Received: ");
					printbytearray(bufx, len - 4);
					
					// decode command and react
					uint8_t sender = bufx[0];
					
					UART_PUTF("           Sender: %u\r\n", sender);
					
					if (sender != 0)
					{
						UART_PUTF("Packet not from base station. Ignoring (Sender ID was: %u).\r\n", sender);
					}
					else
					{
						uint32_t packcnt = getBuf32(1);

						UART_PUTF("   Packet Counter: %lu\r\n", packcnt);

						// check received counter
						if (0) //packcnt <= station_packetcounter)
						{
							UART_PUTF2("Received packet counter %lu is lower than last received counter %lu. Ignoring packet.\r\n", packcnt, station_packetcounter);
						}
						else
						{
							// write received counter
							station_packetcounter = packcnt;
							eeprom_write_dword((uint32_t*)EEPROM_POS_STATION_PACKET_COUNTER, station_packetcounter);
							
							// check command ID
							uint8_t cmd = bufx[5];

							UART_PUTF("       Command ID: %u\r\n", cmd);
							
							if (cmd != 141) // ID 141 == Dimmer Request
							{
								UART_PUTF("Received unknown command ID %u. Ignoring packet.\r\n", cmd);
							}
							else
							{
								// check device id
								uint8_t rcv_id = bufx[6];

								UART_PUTF("      Receiver ID: %u\r\n", rcv_id);
								
								if (rcv_id != device_id)
								{
									UART_PUTF("Device ID %u does not match. Ignoring packet.\r\n", rcv_id);
								}
								else
								{
									// read animation mode and parameters
									uint8_t animation_mode = bufx[7] >> 5;
									
									// TODO: Implement support for multiple dimmers (e.g. RGB)
									// uint8_t dimmer_bitmask = bufx[7] & 0b111;
									
									animation_length = getBuf16(8);
									start_brightness = bufx[10];
									end_brightness = bufx[11];

									UART_PUTF("   Animation Mode: %u\r\n", animation_mode); // TODO: Set binary mode like 00010110
									//UART_PUTF("   Dimmer Bitmask: %u\r\n", dimmer_bitmask);
									UART_PUTF("   Animation Time: %us\r\n", animation_length);
									UART_PUTF(" Start Brightness: %u\r\n", start_brightness);
									UART_PUTF("   End Brightness: %u\r\n", end_brightness);
									
									animation_length = (uint32_t)((float)animation_length * 1000 / ANIMATION_CYCLE_MS);
									animation_position = 0;
									
									/* TODO: Write to EEPROM (?)
									// write back switch state to EEPROM
									switch_state[i] = req_state;
									switch_timeout[i] = req_timeout;
									
									eeprom_write_word((uint16_t*)EEPROM_POS_SWITCH_STATE + i * 2, u16);
									
									*/
									
									// send acknowledge
									UART_PUTS("Sending ACK:\r\n");

									// set device ID (base station has ID 0 by definition)
									bufx[0] = device_id;
									
									// update packet counter
									packetcounter++;
									
									if (packetcounter % PACKET_COUNTER_WRITE_CYCLE == 0)
									{
										eeprom_write_dword((uint32_t*)0, packetcounter);
									}

									setBuf32(1, packetcounter);

									// set command ID "Generic Acknowledge"
									bufx[5] = 1;
									
									// set sender ID of request
									bufx[6] = sender;
									
									// set Packet counter of request
									setBuf32(7, station_packetcounter);

									// zero unused bytes
									bufx[11] = 0;
									
									// set CRC32
									uint32_t crc = crc32(bufx, 12);
									setBuf32(12, crc);

									// show info
									UART_PUTF("            CRC32: %lx\r\n", crc);
									uart_putstr("      Unencrypted: ");
									printbytearray(bufx, 16);

									rfm12_sendbuf();
									
									UART_PUTS("   Send encrypted: ");
									printbytearray(bufx, 16);
									UART_PUTS("\r\n");
								
									rfm12_tick();
									
									led_blink(200, 0, 1);
									
									send_status_timeout = 25;
								}
							}
						}
					}
				}
				
			}

			// tell the implementation that the buffer can be reused for the next data.
			rfm12_rx_clear();
		}

		_delay_ms(ANIMATION_UPDATE_MS);
		
		// React on button press.
		// - abort animation
		// - switch off, when brightness > 0
		// - switch on otherwise
		if (!(BUTTON_PORT & (1 << BUTTON_PIN))) // button press
		{
			if (button_state == 0)
			{
				UART_PUTS("Button pressed\r\n");
				animation_length = 0;
				animation_position = 0;
			}
			
			if (button_state < 5)
			{
				button_state++;
			}
			else // manual dimming
			{
				if (manual_dim_direction) // UP
				{
					if (current_brightness < 100)
					{
						current_brightness = (uint8_t)current_brightness / 2 * 2 + 2;
						setPWMDutyCycle(current_brightness);
					}
					else
					{
						UART_PUTS("manual dimming DOWN\r\n");
						manual_dim_direction = 0;
					}
				}
				else // DOWN
				{
					if (current_brightness > 0)
					{
						current_brightness = (((uint8_t)current_brightness - 1) / 2) * 2;
						setPWMDutyCycle(current_brightness);
					}
					else
					{
						UART_PUTS("manual dimming UP\r\n");
						manual_dim_direction = 1;
					}
				}
				
			}
		}
		else if (button_state && (BUTTON_PORT & (1 << BUTTON_PIN))) // button release
		{
			UART_PUTS("Button released\r\n");
			
			if (button_state < 5) // short button press
			{
				if (current_brightness > 0)
				{
					UART_PUTS(" -> 0%\r\n");
					setPWMDutyCycle(0);
				}
				else
				{
					UART_PUTS(" -> 100%\r\n");
					setPWMDutyCycle(100);
				}
			}
			else
			{
				// reverse dim direction
				manual_dim_direction = !manual_dim_direction;
			}
			
			button_state = 0;
		}
				
		// update brightness according animation_position, updated by timer0
		if (animation_length > 0)
		{
			pos = animation_position; // copy value to avoid that it changes in between by timer interrupt
			UART_PUTF2("%lu/%lu, ", pos, animation_length);
			
			if (pos == animation_length)
			{
				UART_PUTF("END Brightness %u%%, ", end_brightness * 100 / 255);
				setPWMDutyCycle((float)end_brightness * 100 / 255);
				animation_length = 0;
				animation_position = 0;
			}
			else
			{			
				float brightness = (start_brightness + ((float)end_brightness - start_brightness) * pos / animation_length) * 100 / 255;
				UART_PUTF("Br.%u%%, ", (uint32_t)(brightness));
				setPWMDutyCycle(brightness);
			}
		}			
		
		// send status from time to time
		if (send_status_timeout == 0)
		{
			send_status_timeout = SEND_STATUS_EVERY_SEC * (1000 / ANIMATION_UPDATE_MS);
			send_dimmer_status();
			led_blink(200, 0, 1);
		}

		rfm12_tick();
		send_status_timeout--;
		checkSwitchOff();
	}
Beispiel #28
0
int main(int argc, char *argv[])
{
int i=0;
int h=0;
int bupi=0;


cli();
memset(command,'$',58);
init();
timer0_init();
timer1_init();
timer3_init();
timer4_init();
timer5_init();
//lcd_init();
//lcd_string("Welcome");
//lcd_move(0,1);
//lcdconfig();
//lcd_string("Give me a code:");
//lcd_move(0,2);
UART_init();
//adc_init();
//lcdsenddata('F');
//lcd_num(123456);
_delay_ms(1500);
sei();

	while(1)
	{
//-------------------------------------------------scan for input	
		while(mode==0)
		{
			while(1)//scan line
			{				

				if(command[comm]=USART_Receive())
				{
					if((command[comm]==13||command[comm]=='\n'||command[comm]==59)&&(comm<59))
					{
					break;
					}

					if(echo==1)
					{
					//USART_Transmit('[');
				//	USART_Transmit(comm+48);
				//	USART_Transmit(']');
					USART_Transmit(command[comm]);
					}

					comm++;

				}
				else
				{
				}

			
			}
			mode=1;
		
			if(echo==1)
			{
			USART_String_Transmit("\nTransition to parsing.");
			}
		
		}
		


//-------------------------------------------------parse commands
		while(mode==1)//parse commands
		{
			for(i=0;i<comm;i++)//cycling i till \n-1
			{

				if(command[i]=='N'&&command[i+1]>47&&command[i+1]<58)//GET LINE NUMBER
				{
					if(echo)
					{
					USART_String_Transmit("\n Getting line number.");
					}

					temp_line_number=fetchlong(command,i,'N');
				}				

				if(command[i]=='M'&&command[i+1]=='1'&&command[i+2]=='0'&&command[i+3]=='5')//GET EXTRUDER TEMP
				{

				}
				

				
				if(command[i]=='M'&&command[i+1]=='1'&&command[i+2]=='0'&&command[i+3]=='4')//SET EXTRUDER TEMP FAST SXXX
				{
	
				}					

				
				
				if(command[i]=='M'&&command[i+1]=='1'&&command[i+2]=='0'&&command[i+3]=='9')//SET EXTRUDER TEMP AND WAIT RXXX
				{
				
				}

				
				
				if(command[i]=='M'&&command[i+1]=='1'&&command[i+2]=='4'&&command[i+3]=='0')//SET BED TEMP FAST SXXX
				{
				
				}
				

				
				if(command[i]=='M'&&command[i+1]=='1'&&command[i+2]=='9'&&command[i+3]=='0')//WAIT FOR BED TEMP TO HIT RXXX
				{
				
				}

				
				
				if(command[i]=='M'&&command[i+1]=='1'&&command[i+2]=='0'&&command[i+3]=='7')//FAN OFF
				{
				
				}
				
				
				
				if(command[i]=='M'&&command[i+1]=='1'&&command[i+2]=='0'&&command[i+3]=='6')//FAN ON WITH FAN SPEED S255MAX
				{
				
				}

				
				

				if(command[i]=='M'&&command[i+1]=='8'&&command[i+2]=='2'&&command[i+3]==' ')//EXTRUDER TO ABSOLUTE MODE
				{
				
				}
				

				
				if(command[i]=='G'&&command[i+1]=='2'&&command[i+2]=='1'&&command[i+3]==' ')//METRIC VALUES
				{
				
				}

				
				
				if(command[i]=='G'&&command[i+1]=='9'&&command[i+2]=='0'&&command[i+3]==' ')//ABSOLUTE POSITIONING
				{
				
				}

				
				
				if(command[i]=='G'&&command[i+1]=='9'&&command[i+2]=='2'&&command[i+3]==' ')//ZERO EXTRUDED LENGTH WITH E0 otherwise set origin?
				{
				
				}

				
				
				if(command[i]=='G'&&command[i+1]=='0'&&command[i+2]==' ')//MOVE WITHOUT EXTUSION
				{
				if(echo)
				{
				USART_String_Transmit("\nG0 command.");
				}
				line_engine(double_scan_x,double_scan_y,double_scan_z,double_scan_e,i);
				if((echo==1)&&(xroll==1)&&(yroll=1))
				{
				USART_String_Transmit("\n Xroll=1");
				USART_String_Transmit("\n Yroll=1");
				}
				mode==2;
				
				}

				
				
				if(command[i]=='G'&&command[i+1]=='1'&&command[i+2]==' ')//MOVE WITH EXTRUSION
				{



				}

				
				
				if(command[i]=='Q'&&command[i+1]=='1')//MOTOR TEST					{
				{
					if(echo)
					{
					USART_String_Transmit("\n Motor test on.");
					//xroll=1;
					yroll=1;
					//testval=(threefetchdouble(command,i,'E')/0.01)*16;
					}
				}

				
				
				if(command[i]=='Q'&&command[i+1]=='0')//MOTOR TEST
				{
					if(echo)
					{
					USART_String_Transmit("\n Motor test off.");
					}
					//xroll=0;
					yroll=0;
				}
				

				
			}
			mode=2;
				if(echo)
				{
				USART_String_Transmit("\nTransition to set outputs.");
				}
			


		}	



//-------------------------------------------------setting outputs
		while(mode==2)
		{
			while(zroll==1||eroll==1||xroll==1||yroll==1)
			{
				if(USART_Receive()=='.')
				{
				zroll=0;
				eroll=0;
				xroll=0;
				yroll=0;
				
				USART_String_Transmit("\nSW Emergency stopped, please reset!");
			//	PINK|=0b00000001;
			//	PINA|=0b00000100;
			//	PINF|=0b00000100;
			//	PIND|=0b10000000;

				}
			}

			if(zroll==0&&eroll==0&&xroll==0&&yroll==0)
			{
				if(echo)
				{
				USART_String_Transmit("\nTransition to mode 3, reseting parameters.");
				}

				mode=3;
			}


		}



//-------------------------------------------------clear things
		while(mode==3)
		{
		cli();

		memset(command,'$',58);
		comm=0;
		i=0;
		double_scan_x=-1.0;
		double_scan_y=-1.0;
		double_scan_z=-1.0;
		double_scan_e=-1.0;
		
			if(echo)
			{
			USART_String_Transmit("\nParameters reseted returning to scanning mode");
			}

		USART_String_Transmit("\n\rok");
		
		sei();

		mode=0;
		}



		
//-------------------------------------------------
		while(mode==4)
		{

		}		

	}



return 0;
}
Beispiel #29
0
// Main loop of the program
int main(void)
{
    //
    // Set the clocking to run directly from the crystal. 8Mhz
    //
    SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN |
                   SYSCTL_XTAL_8MHZ);
    delay(500);
    LED_init();
    delay(500);
    ADC_init(); //init the adc
    delay(500);
    timer0_init(); //init the first timer
    delay(500);
    timer1_init(); //second timer
    delay(500);
    key_init(); //keypad
    display_init();
    CPUcpsie(); //turn on cpu inttrupts

    //init all prices and indexes
    int upDownIndex = 0; 
    int currDollars = 0;
    int currCents = 0;
    int leftRightIndex = 0;
    display_on(1,1); 
    print_welcome(); //print initial welcome menu
 
     /*
    handles key inputs
    User can toggle through display menus (welcome menu, food menu,...) 
    using LEFT and RIGHT
    While on the food menu, user can toggle through food options using UP 
    and DOWN and select food items using SELECT.
    */
    while(1)
    {
      int currentKey = keymaster();
      if (!readKey) { //if we have not read the key since it has been updated
        switch (currentKey) //main control flow loop
        {
          case UP:
            if (upDownIndex) {
              upDownIndex--; //de-inc the vertical index
              print_menu(upDownIndex, currDollars, currCents);
            }
            break;
          case DOWN:
            if (upDownIndex < maxUpDownIndex) {
              upDownIndex++; //inc the vertical index
              print_menu(upDownIndex, currDollars, currCents);
            }
            break;
          case RIGHT:
            if (leftRightIndex < maxLeftRightIndex) {
              leftRightIndex++; //inc the left right index
              select_menu(&leftRightIndex, upDownIndex, currDollars, currCents);
            }
            break;
          case LEFT:
            if (leftRightIndex) {
              leftRightIndex--; //de-inc the left right index
              select_menu(&leftRightIndex, upDownIndex, currDollars, currCents);
            }
            break;
          case SELECT:
            currDollars += dollars[upDownIndex]; //update the total costs
            currCents += cents[upDownIndex];
            if (currCents >= 100) {
              currDollars += 1;
              currCents -= 100;
            }
            print_menu(upDownIndex, currDollars, currCents);
            break;
        }
      }
      readKey = 1; //tell timer 0 we have read the key
      //Reset the totals for the costs
      if (leftRightIndex == 0) {
        currDollars = 0;
        currCents = 0;
      }
    }

}
Beispiel #30
0
int main(void)
{
	uint16_t send_status_timeout = 25;
	uint32_t pos;
	uint8_t button_state = 0;
	uint8_t manual_dim_direction = 0;

	// delay 1s to avoid further communication with uart or RFM12 when my programmer resets the MC after 500ms...
	_delay_ms(1000);

	util_init();
	
	check_eeprom_compatibility(DEVICETYPE_DIMMER);
	
	// read packetcounter, increase by cycle and write back
	packetcounter = e2p_generic_get_packetcounter() + PACKET_COUNTER_WRITE_CYCLE;
	e2p_generic_set_packetcounter(packetcounter);

	// read device id
	device_id = e2p_generic_get_deviceid();

	// pwm translation table is not used if first byte is 0xFF
	use_pwm_translation = (0xFF != eeprom_read_UIntValue8(EEPROM_BRIGHTNESSTRANSLATIONTABLE_BYTE,
		EEPROM_BRIGHTNESSTRANSLATIONTABLE_BIT, 8, 0, 0xFF));
	
	// TODO: read (saved) dimmer state from before the eventual powerloss
	/*for (i = 0; i < SWITCH_COUNT; i++)
	{
		uint16_t u16 = eeprom_read_word((uint16_t*)EEPROM_POS_SWITCH_STATE + i * 2);
		switch_state[i] = (uint8_t)(u16 & 0b1);
		switch_timeout[i] = u16 >> 1;
	}*/
	
	// read last received station packetcounter
	station_packetcounter = e2p_dimmer_get_basestationpacketcounter();
	
	led_blink(500, 500, 3);

	osccal_init();

	uart_init();
	UART_PUTS ("\r\n");
	UART_PUTF4("smarthomatic Dimmer v%u.%u.%u (%08lx)\r\n", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_HASH);
	UART_PUTS("(c) 2013..2014 Uwe Freese, www.smarthomatic.org\r\n");
	osccal_info();
	UART_PUTF ("DeviceID: %u\r\n", device_id);
	UART_PUTF ("PacketCounter: %lu\r\n", packetcounter);
	UART_PUTF ("Use PWM translation table: %u\r\n", use_pwm_translation);
	UART_PUTF ("Last received base station PacketCounter: %u\r\n\r\n", station_packetcounter);

	// init AES key
	eeprom_read_block (aes_key, (uint8_t *)EEPROM_AESKEY_BYTE, 32);

	rfm12_init();
	PWM_init();
	io_init();
	setPWMDutyCyclePercent(0);
	timer0_init();

	// DEMO to measure the voltages of different PWM settings to calculate the pwm_lookup table
	/*while (42)
	{
		uint16_t i;
		
		for (i = 0; i <= 1024; i = i + 100)
		{
			UART_PUTF ("PWM value OCR1A: %u\r\n", i);
			OCR1A = i;
			led_blink(500, 6500, 1);
		}
	}*/
	
	// DEMO 0..100..0%, using the pwm_lookup table and the translation table in EEPROM.
	/*while (42)
	{
		float i;
		
		for (i = 0; i <= 100; i = i + 0.05)
		{
			led_blink(10, 10, 1);
			setPWMDutyCycle(i);
		}
		
		for (i = 99.95; i > 0; i = i - 0.05)
		{
			led_blink(10, 10, 1);
			setPWMDutyCycle(i);
		}
	}*/

	// set initial switch state
	/*for (i = 0; i < SWITCH_COUNT; i++)
	{
		switchRelais(i, switch_state[i]);
	}*/

	sei();

	// DEMO 30s
	/*animation_length = 30;
	animation_length = (uint32_t)((float)animation_length * 1000 / ANIMATION_CYCLE_MS);
	start_brightness = 0;
	end_brightness = 255;
	animation_position = 0;*/
	
	while (42)
	{
		if (rfm12_rx_status() == STATUS_COMPLETE)
		{
			uint8_t len = rfm12_rx_len();
			
			if ((len == 0) || (len % 16 != 0))
			{
				UART_PUTF("Received garbage (%u bytes not multiple of 16): ", len);
				print_bytearray(bufx, len);
			}
			else // try to decrypt with all keys stored in EEPROM
			{
				memcpy(bufx, rfm12_rx_buffer(), len);
				
				UART_PUTS("Before decryption: ");
				print_bytearray(bufx, len);
					
				aes256_decrypt_cbc(bufx, len);

				UART_PUTS("Decrypted bytes: ");
				print_bytearray(bufx, len);
				
				if (!pkg_header_check_crc32(len))
				{
					UART_PUTS("Received garbage (CRC wrong after decryption).\r\n");
				}
				else
				{
					process_packet(len);
				}		
			}

			// tell the implementation that the buffer can be reused for the next data.
			rfm12_rx_clear();
		}

		_delay_ms(ANIMATION_UPDATE_MS);
		
		// React on button press.
		// - abort animation
		// - switch off, when brightness > 0
		// - switch on otherwise
		if (!(BUTTON_PORT & (1 << BUTTON_PIN))) // button press
		{
			if (button_state == 0)
			{
				UART_PUTS("Button pressed\r\n");
				animation_length = 0;
				animation_position = 0;
			}
			
			if (button_state < 5)
			{
				button_state++;
			}
			else // manual dimming
			{
				if (manual_dim_direction) // UP
				{
					if (current_brightness < 100)
					{
						current_brightness = (uint8_t)current_brightness / 2 * 2 + 2;
						setPWMDutyCyclePercent(current_brightness);
					}
					else
					{
						UART_PUTS("manual dimming DOWN\r\n");
						manual_dim_direction = 0;
					}
				}
				else // DOWN
				{
					if (current_brightness > 0)
					{
						current_brightness = (((uint8_t)current_brightness - 1) / 2) * 2;
						setPWMDutyCyclePercent(current_brightness);
					}
					else
					{
						UART_PUTS("manual dimming UP\r\n");
						manual_dim_direction = 1;
					}
				}
				
			}
		}
		else if (button_state && (BUTTON_PORT & (1 << BUTTON_PIN))) // button release
		{
			UART_PUTS("Button released\r\n");
			
			if (button_state < 5) // short button press
			{
				if (current_brightness > 0)
				{
					UART_PUTS(" -> 0%\r\n");
					setPWMDutyCyclePercent(0);
				}
				else
				{
					UART_PUTS(" -> 100%\r\n");
					setPWMDutyCyclePercent(100);
				}
			}
			else
			{
				// reverse dim direction
				manual_dim_direction = !manual_dim_direction;
			}
			
			button_state = 0;
		}
				
		// update brightness according animation_position, updated by timer0
		if (animation_length > 0)
		{
			pos = animation_position; // copy value to avoid that it changes in between by timer interrupt
			UART_PUTF2("%lu/%lu, ", pos, animation_length);
			
			if (pos == animation_length)
			{
				UART_PUTF("END Brightness %u%%, ", end_brightness);
				setPWMDutyCyclePercent((float)end_brightness);
				animation_length = 0;
				animation_position = 0;
			}
			else
			{			
				float brightness = (start_brightness + ((float)end_brightness - start_brightness) * pos / animation_length);
				UART_PUTF("Br.%u%%, ", (uint32_t)(brightness));
				setPWMDutyCyclePercent(brightness);
			}
		}			
		
		// send status from time to time
		if (send_status_timeout == 0)
		{
			send_status_timeout = SEND_STATUS_EVERY_SEC * (1000 / ANIMATION_UPDATE_MS);
			send_dimmer_status();
			led_blink(200, 0, 1);
		}
		else if (version_status_cycle >= SEND_VERSION_STATUS_CYCLE)
		{
			version_status_cycle = 0;
			send_version_status();
			led_blink(200, 0, 1);
		}

		rfm12_tick();
		send_status_timeout--;
		checkSwitchOff();
	}
	
	// never called
	// aes256_done(&aes_ctx);
}