Esempio n. 1
0
/** 
 * @brief emulate instruction 
 * @return returns false if something goes wrong (e.g. illegal instruction)
 *
 * Current limitations:
 * 
 * - Illegal instructions are not implemented
 * - Excess cycles due to page boundary crossing are not calculated
 * - Some known architectural bugs are not emulated
 */
bool Cpu::emulate()
{
  /* fetch instruction */
  uint8_t insn = fetch_op();
  bool retval = true;
  /* emulate instruction */
  switch(insn)
  {
  /* BRK */
  case 0x0: brk(); break;
  /* ORA (nn,X) */
  case 0x1: ora(load_byte(addr_indx()),6); break;
  /* ORA nn */
  case 0x5: ora(load_byte(addr_zero()),3); break;
  /* ASL nn */
  case 0x6: asl_mem(addr_zero(),5); break;
  /* PHP */
  case 0x8: php(); break;
  /* ORA #nn */
  case 0x9: ora(fetch_op(),2); break;
  /* ASL A */
  case 0xA: asl_a(); break;
  /* ORA nnnn */
  case 0xD: ora(load_byte(addr_abs()),4); break;
  /* ASL nnnn */
  case 0xE: asl_mem(addr_abs(),6); break; 
  /* BPL nn */
  case 0x10: bpl(); break;
  /* ORA (nn,Y) */
  case 0x11: ora(load_byte(addr_indy()),5); break;
  /* ORA nn,X */
  case 0x15: ora(load_byte(addr_zerox()),4); break;
  /* ASL nn,X */
  case 0x16: asl_mem(addr_zerox(),6); break;
  /* CLC */
  case 0x18: clc(); break;
  /* ORA nnnn,Y */
  case 0x19: ora(load_byte(addr_absy()),4); break;
  /* ORA nnnn,X */
  case 0x1D: ora(load_byte(addr_absx()),4); break;
  /* ASL nnnn,X */
  case 0x1E: asl_mem(addr_absx(),7); break;
  /* JSR */
  case 0x20: jsr(); break;
  /* AND (nn,X) */
  case 0x21: _and(load_byte(addr_indx()),6); break;
  /* BIT nn */
  case 0x24: bit(addr_zero(),3); break;
  /* AND nn */
  case 0x25: _and(load_byte(addr_zero()),3); break;
  /* ROL nn */
  case 0x26: rol_mem(addr_zero(),5); break;
  /* PLP */
  case 0x28: plp(); break;
  /* AND #nn */
  case 0x29: _and(fetch_op(),2); break;
  /* ROL A */
  case 0x2A: rol_a(); break;
  /* BIT nnnn */
  case 0x2C: bit(addr_abs(),4); break;
  /* AND nnnn */
  case 0x2D: _and(load_byte(addr_abs()),4); break;
  /* ROL nnnn */
  case 0x2E: rol_mem(addr_abs(),6); break;
  /* BMI nn */
  case 0x30: bmi(); break;
  /* AND (nn,Y) */
  case 0x31: _and(load_byte(addr_indy()),5); break;               
  /* AND nn,X */
  case 0x35: _and(load_byte(addr_zerox()),4); break;
  /* ROL nn,X */
  case 0x36: rol_mem(addr_zerox(),6); break;
  /* SEC */
  case 0x38: sec(); break;
  /* AND nnnn,Y */
  case 0x39: _and(load_byte(addr_absy()),4); break;
  /* AND nnnn,X */
  case 0x3D: _and(load_byte(addr_absx()),4); break;
  /* ROL nnnn,X */
  case 0x3E: rol_mem(addr_absx(),7); break;
  /* RTI */
  case 0x40: rti(); break;
  /* EOR (nn,X) */
  case 0x41: eor(load_byte(addr_indx()),6); break;
  /* EOR nn */
  case 0x45: eor(load_byte(addr_zero()),3); break;
  /* LSR nn */
  case 0x46: lsr_mem(addr_zero(),5); break;
  /* PHA */
  case 0x48: pha(); break;
  /* EOR #nn */
  case 0x49: eor(fetch_op(),2); break;
  /* BVC */
  case 0x50: bvc(); break;
  /* JMP nnnn */
  case 0x4C: jmp(); break;
  /* EOR nnnn */
  case 0x4D: eor(load_byte(addr_abs()),4); break;
  /* LSR A */
  case 0x4A: lsr_a(); break;
  /* LSR nnnn */
  case 0x4E: lsr_mem(addr_abs(),6); break;
  /* EOR (nn,Y) */
  case 0x51: eor(load_byte(addr_indy()),5); break;
  /* EOR nn,X */
  case 0x55: eor(load_byte(addr_zerox()),4); break;
  /* LSR nn,X */
  case 0x56: lsr_mem(addr_zerox(),6); break;
  /* CLI */
  case 0x58: cli(); break;
  /* EOR nnnn,Y */
  case 0x59: eor(load_byte(addr_absy()),4); break;
  /* EOR nnnn,X */
  case 0x5D: eor(load_byte(addr_absx()),4); break;
  /* LSR nnnn,X */
  case 0x5E: lsr_mem(addr_absx(),7); break;
  /* RTS */
  case 0x60: rts(); break;
  /* ADC (nn,X) */
  case 0x61: adc(load_byte(addr_indx()),6); break;
  /* ADC nn */
  case 0x65: adc(load_byte(addr_zero()),3); break;
  /* ROR nn */
  case 0x66: ror_mem(addr_zero(),5); break;
  /* PLA */
  case 0x68: pla(); break;
  /* ADC #nn */
  case 0x69: adc(fetch_op(),2); break;
  /* ROR A */
  case 0x6A: ror_a(); break;
  /* JMP (nnnn) */
  case 0x6C: jmp_ind(); break;
  /* ADC nnnn */
  case 0x6D: adc(load_byte(addr_abs()),4); break;
  /* ROR nnnn */
  case 0x6E: ror_mem(addr_abs(),6); break;
  /* BVS */
  case 0x70: bvs(); break;
  /* ADC (nn,Y) */
  case 0x71: adc(load_byte(addr_indy()),5); break;
  /* ADC nn,X */
  case 0x75: adc(load_byte(addr_zerox()),4); break;
  /* ROR nn,X */
  case 0x76: ror_mem(addr_zerox(),6); break;
  /* SEI */
  case 0x78: sei(); break;
  /* ADC nnnn,Y */
  case 0x79: adc(load_byte(addr_absy()),4); break;
  /* ADC nnnn,X */
  case 0x7D: adc(load_byte(addr_absx()),4); break;
  /* ROR nnnn,X */
  case 0x7E: ror_mem(addr_absx(),7); break;
  /* STA (nn,X) */
  case 0x81: sta(addr_indx(),6); break;
  /* STY nn */
  case 0x84: sty(addr_zero(),3); break;
  /* STA nn */
  case 0x85: sta(addr_zero(),3); break;
  /* STX nn */
  case 0x86: stx(addr_zero(),3); break;
  /* DEY */
  case 0x88: dey(); break;
  /* TXA */
  case 0x8A: txa(); break;
  /* STY nnnn */
  case 0x8C: sty(addr_abs(),4); break;
  /* STA nnnn */
  case 0x8D: sta(addr_abs(),4); break;
  /* STX nnnn */
  case 0x8E: stx(addr_abs(),4); break;
  /* BCC nn */
  case 0x90: bcc(); break;
  /* STA (nn,Y) */
  case 0x91: sta(addr_indy(),6); break;
  /* STY nn,X */
  case 0x94: sty(addr_zerox(),4); break;
  /* STA nn,X */
  case 0x95: sta(addr_zerox(),4); break;
  /* STX nn,Y */
  case 0x96: stx(addr_zeroy(),4); break;
  /* TYA */
  case 0x98: tya(); break;
  /* STA nnnn,Y */
  case 0x99: sta(addr_absy(),5); break;
  /* TXS */
  case 0x9A: txs(); break;
  /* STA nnnn,X */
  case 0x9D: sta(addr_absx(),5); break;
  /* LDY #nn */
  case 0xA0: ldy(fetch_op(),2); break; 
  /* LDA (nn,X) */
  case 0xA1: lda(load_byte(addr_indx()),6); break;
  /* LDX #nn */
  case 0xA2: ldx(fetch_op(),2); break;
  /* LDY nn */
  case 0xA4: ldy(load_byte(addr_zero()),3); break;
  /* LDA nn */
  case 0xA5: lda(load_byte(addr_zero()),3); break;
  /* LDX nn */
  case 0xA6: ldx(load_byte(addr_zero()),3); break;
  /* TAY */
  case 0xA8: tay(); break;
  /* LDA #nn */
  case 0xA9: lda(fetch_op(),2); break;
  /* TAX */
  case 0xAA: tax(); break;
  /* LDY nnnn */
  case 0xAC: ldy(load_byte(addr_abs()),4); break;
  /* LDA nnnn */
  case 0xAD: lda(load_byte(addr_abs()),4); break;
  /* LDX nnnn */
  case 0xAE: ldx(load_byte(addr_abs()),4); break;
  /* BCS nn */
  case 0xB0: bcs(); break;
  /* LDA (nn,Y) */
  case 0xB1: lda(load_byte(addr_indy()),5); break;
  /* LDY nn,X */
  case 0xB4: ldy(load_byte(addr_zerox()),3); break;
  /* LDA nn,X */
  case 0xB5: lda(load_byte(addr_zerox()),3); break;
  /* LDX nn,Y */
  case 0xB6: ldx(load_byte(addr_zeroy()),3); break;
  /* CLV */
  case 0xB8: clv(); break;
  /* LDA nnnn,Y */
  case 0xB9: lda(load_byte(addr_absy()),4); break;
  /* TSX */
  case 0xBA: tsx(); break;
  /* LDY nnnn,X */
  case 0xBC: ldy(load_byte(addr_absx()),4); break;
  /* LDA nnnn,X */
  case 0xBD: lda(load_byte(addr_absx()),4); break;
  /* LDX nnnn,Y */
  case 0xBE: ldx(load_byte(addr_absy()),4); break;
  /* CPY #nn */
  case 0xC0: cpy(fetch_op(),2); break;
  /* CMP (nn,X) */
  case 0xC1: cmp(load_byte(addr_indx()),6); break;
  /* CPY nn */
  case 0xC4: cpy(load_byte(addr_zero()),3); break;
  /* CMP nn */
  case 0xC5: cmp(load_byte(addr_zero()),3); break;
  /* DEC nn */
  case 0xC6: dec(addr_zero(),5); break;
  /* INY */
  case 0xC8: iny(); break;
  /* CMP #nn */
  case 0xC9: cmp(fetch_op(),2); break;
  /* DEX */
  case 0xCA: dex(); break;
  /* CPY nnnn */
  case 0xCC: cpy(load_byte(addr_abs()),4); break;
  /* CMP nnnn */
  case 0xCD: cmp(load_byte(addr_abs()),4); break;
  /* DEC nnnn */
  case 0xCE: dec(addr_abs(),6); break;
  /* BNE nn */
  case 0xD0: bne(); break;
  /* CMP (nn,Y) */
  case 0xD1: cmp(load_byte(addr_indy()),5); break;
  /* CMP nn,X */
  case 0xD5: cmp(load_byte(addr_zerox()),4); break;
  /* DEC nn,X */
  case 0xD6: dec(addr_zerox(),6); break;
  /* CLD */
  case 0xD8: cld(); break;
  /* CMP nnnn,Y */
  case 0xD9: cmp(load_byte(addr_absy()),4); break;
  /* CMP nnnn,X */
  case 0xDD: cmp(load_byte(addr_absx()),4); break;
  /* DEC nnnn,X */
  case 0xDE: dec(addr_absx(),7); break;
  /* CPX #nn */
  case 0xE0: cpx(fetch_op(),2); break;
  /* SBC (nn,X) */
  case 0xE1: sbc(load_byte(addr_indx()),6); break;
  /* CPX nn */
  case 0xE4: cpx(load_byte(addr_zero()),3); break;
  /* SBC nn */
  case 0xE5: sbc(load_byte(addr_zero()),3); break;
  /* INC nn */
  case 0xE6: inc(addr_zero(),5); break;
  /* INX */
  case 0xE8: inx(); break;
  /* SBC #nn */
  case 0xE9: sbc(fetch_op(),2); break;
  /* NOP */
  case 0xEA: nop(); break;
  /* CPX nnnn */
  case 0xEC: cpx(load_byte(addr_abs()),4); break;
  /* SBC nnnn */
  case 0xED: sbc(load_byte(addr_abs()),4); break;
  /* INC nnnn */
  case 0xEE: inc(addr_abs(),6); break;
  /* BEQ nn */
  case 0xF0: beq(); break;
  /* SBC (nn,Y) */
  case 0xF1: sbc(load_byte(addr_indy()),5); break;
  /* SBC nn,X */
  case 0xF5: sbc(load_byte(addr_zerox()),4); break;
  /* INC nn,X */
  case 0xF6: inc(addr_zerox(),6); break;
  /* SED */
  case 0xF8: sed(); break;
  /* SBC nnnn,Y */
  case 0xF9: sbc(load_byte(addr_absy()),4); break;
  /* SBC nnnn,X */
  case 0xFD: sbc(load_byte(addr_absx()),4); break;
  /* INC nnnn,X */
  case 0xFE: inc(addr_absx(),7); break;
  /* Unknown or illegal instruction */
  default:
    D("Unknown instruction: %X at %04x\n", insn,pc());
    retval = false;
  }
  return retval;
}
Esempio n. 2
0
int main(void)
{	
	char remotePrev = 0;
	signed char remoteValue;
	unsigned int cowDelay = 0;
	unsigned char cowDirection = FORWARD;
	unsigned char count = 0;
	unsigned int motorb_current = 0;
	char motorb_safety = ON;

	char name[15];

	timer0_prescale(TMR0_PRE1024);
//	set_bit(TIMSK0, TOIE0);

	twiMasterInit(100000);
	sei();
	hcmmod_rc(DISABLE);
	iomod_text(FIRST_LINE, "Darla Rules");
	//darla_relay(0x00);
	
//	while (1);

	while (TRUE) {
		if (masterCounter > cowDelay) {
			clear_bit(TIMSK0, TOIE0);
			masterCounter = 0;
			if (cowDirection == FORWARD)
				hcmd_drive_limit(MOTORB, +40, 1);
			else if (cowDirection == REVERSE)
				hcmd_drive_limit(MOTORB, -40, 2);
		}
		remoteValue = iomod_remote();	
		if (remoteValue != -1) 
			iomod_decimal(FIRST_LINE, remoteValue, 4);
		//if (remoteValue == 1) {
		if ((remoteValue == 1) && (remotePrev != 1)) {
			masterCounter = 0;
			cowDirection = FORWARD;
			cowDelay = 2400;
			set_bit(TIMSK0, TOIE0);
			darla_send_set(darlaSet1, 7);
			mp3mod_play_file("o1NEWMC.mp3");
			/* Need to avoid multiple calls from remote, which seemed to be the
			 * cause of problems with the MP3 not working. */
			//delay_ms(1000);
			remotePrev = 1;
		}
		//else if (remoteValue == 2) {
		else if ((remoteValue == 2) && (remotePrev != 2)) {
			masterCounter = 0;
			cowDirection = REVERSE;
			cowDelay = 50;
			set_bit(TIMSK0, TOIE0);
			darla_send_set(darlaSet2, 3);
			mp3mod_play_file("i2MTC.mp3");
			remotePrev = 2;
			//delay_ms(1000);
		}
		else if (remoteValue == 4)
			hcmd_drive_limit(MOTORB, +40, 1);
		else if (remoteValue == 6)
			hcmd_drive_limit(MOTORB, -40, 2);
		else if (remoteValue == 5)
			hcmd_stop_motor(MOTORB, BRAKE);
		else if (remoteValue == 7) 
			darla_relay(OFF);
		else if (remoteValue == 8)
			darla_relay(MM);
		else if (remoteValue == 9) 
			darla_relay(UC);
	//		darla_send_set(darlaSetT, 2);
		/* Prevent Darla from moving if current draw is too high */
		iomod_decimal(SECOND_LINE, hcmmod_current(MOTORB), 6);
		motorb_current = hcmmod_current(MOTORB);	
		if ((motorb_current > 200) && (motorb_safety == ON))
			hcmd_stop_motor(MOTORB, BRAKE);

	}
}
Esempio n. 3
0
void INT0_vect ( void )
{
  cli ();
  printf ("I am in an interrupt----------->\n");
  sei ();
}
Esempio n. 4
0
int main( void )
{
	// Enable interrupts as early as possible
	sei();
	
	Timer_Init();

	// Set as outputs and stop rotor
	DDRD |= (1 << PD1)|(1 << PD2);
	PORTD &= ~((1 << PD1)|(1 << PD2));
	
	// Setup ADC
	initAdcFeedback();
	
	Can_Message_t txMsg;
	txMsg.Id = (CAN_NMT_APP_START << CAN_SHIFT_NMT_TYPE) | (NODE_ID << CAN_SHIFT_NMT_SID);
	txMsg.DataLength = 4;
	txMsg.RemoteFlag = 0;
	txMsg.ExtendedFlag = 1;
	txMsg.Data.words[0] = APP_TYPE;
	txMsg.Data.words[1] = APP_VERSION;
	
	// Set up callback for CAN reception
	BIOS_CanCallback = &can_receive;
	// Send CAN_NMT_APP_START
	BIOS_CanSend(&txMsg);
	
	// Read calibration value from eeprom
	azimuthCalibration = eeprom_read_word( CALIBRATE_AZIMUTH );
	
	// Timer for reading position feedback
	Timer_SetTimeout(0, 100, TimerTypeFreeRunning, 0);
	Timer_SetTimeout(1, 1000, TimerTypeFreeRunning, 0);

	sendStatus( STATUS );

	while (1) {
		if (Timer_Expired(0)) {
			// Periodicly read antennas position
			readFeedback();
		}
		if (Timer_Expired(1)) {
			sendStatus(STATUS);
		}
		
		if (rxMsgFull) {
			switch (rxMsg.Id){
				case MSG_CAL_SET: // Set calibration value
					if( 2 == rxMsg.DataLength ){
						calibration( SET, rxMsg.Data.words[0] );
					}
					break;
					
				case MSG_CAL_GET: // Get calibration value
					if( 0 == rxMsg.DataLength ){
						txMsg.Id = MSG_CAL_RET; 
						txMsg.DataLength = 2;
						txMsg.Data.words[0] = calibration( GET, 0 );
						BIOS_CanSend(&txMsg);
					}
					break;
					
				case MSG_ABS: // Start turning to absolute position
					if( 2 == rxMsg.DataLength ){
						
					}
					break;
					
				case MSG_REL: // Start turning to relative position
					if( 2 == rxMsg.DataLength ){
						
					}
					break;
					
				case MSG_START: // Start turning
					if( 1 == rxMsg.DataLength ){
						// First data byte decides direction
						controlRelay( rxMsg.Data.bytes[0] );
					}
					break;
					
				case MSG_STOP: // Stop turning
					//if( 1 == rxMsg.DataLength ){
						controlRelay( ROTATE_STOP );
					//}
					break;
				case MSG_STATUS: // Get position
					if( 0 == rxMsg.DataLength ){
						sendStatus(STATUS);
					}
					break;
					
				default:
					break;
			}

    			rxMsgFull = 0; //  
		}
	}
	
	return 0;
}
Esempio n. 5
0
int main(void)
{
	SetSystemClockPrescaler(0);
	init();
	sei();

	led_blink(3);

     while (1)
     {
    	if(SW_ACTIVE())
    	{
    		// SW pressed
    		uint8_t pressCnt = 100;

    		// wait until released
    		do
    		{
				// long term press detected?
    			if(pressCnt>0 && --pressCnt==0)
    				LED_ON();

    			_delay_ms(10);
    		} while(SW_ACTIVE());


    		// SW released
    		LED_OFF();
    		if(pressCnt>0)
    			handleSensor(1); // force transmit
    		else
    		{
    			// program mode
        		LED_ON();
        		fs20_resetbuffer();
        		fs20_rxon();
        		fstelegram_t t;
        		t.type = 'U'; // undefined
        		pressCnt = 100;

        		// wait for next telegram
        		// exit if button pressed or timeout occured
        		while(!fs20_readFS20Telegram(&t) && --pressCnt>0 && !SW_ACTIVE())
        			_delay_ms(100);

        		fs20_idle();
        		LED_OFF();

        		// save the result
        		if(t.type=='F')
        		{
        			saveConfig(t.housecode, t.button);
        			led_blink(2); // confirm save of config
        			handleSensor(1); // force transmit
        		}

        		// wait until sw releases
        		while(SW_ACTIVE());
    		}
    	}

		// check long term timer
		if(longTimerCnt >= LONGTIMER_VAL)
			handleSensor(1);

		// finaly check if sensor value changed
		// this will only be the case if the current sensor value haven't been sent
		// during this cycle
		handleSensor(0);

		// sleep well
		LED_OFF();
		SENS_ACTIVATE(0);
		set_sleep_mode(SLEEP_MODE_PWR_DOWN);
		sleep_mode();
     }
}
Esempio n. 6
0
void set_time(bool timeType){
	int *hou = &hour;
	int *min = &minute;
	update_timeXPos(hour, minute);
	if (timeType == ALARM_TYPE){
		hou = &alarm_hour;
		min = &alarm_minute;
		update_timeXPos(alarm_hour, alarm_minute);
	}
	int item = 0;
	int old_selectedItem = 1;
	cli();
	btn_drehenc_pushed = false;
	sei();
	clear_pixelMatrix();
	print_time(timeType);
	
	print_symbol(16,17, hakenSymb,108,46);
	print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+get_timeWidth(alarm_hour)/2-4, 2);
	update_LCD();
	while(item != 2){
		while(!btn_drehenc_pushed){
			if(rotary != 0){
				item += rotary;
				cli();
				rotary = 0;
				sei();
				item = item % 3;
				if(item<0){
					item += 3;
				}
				
				switch (old_selectedItem){
					case 0: for(int x = 0; x<128; x++){
								for(int y = 2; y<10; y++)
									reset_pixel(x,y);
							} break;
					case 1: for(int x = 0; x<128; x++){
								for(int y = 2; y<10; y++)
								reset_pixel(x,y);
							}break;
					case 2: for(int x = 92; x<102; x++){
								for(int y = 2+3*15+5; y<2+3*15+8+5; y++)
									reset_pixel(x,y);
							}break;
				}
				switch (item) {
					case 0: print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+hourWidth/2-4, 2); break;
					case 1: print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+hourWidth+2*SPACE_TO_DOTS+ TIMEDOT_WIDTH + minuteWidth/2-4, 2); break;
					case 2: print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb, 92, 2+3*15+5);break;
				}
				old_selectedItem = item;
				update_LCD();
			}
			goodNight();
			check_light();
		}
		cli();
		btn_drehenc_pushed = false;
		sei();
		switch (item) {
			case 0: {
				print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinOffenSymb,timeXPos+hourWidth/2-4, 2); 
				update_LCD(); 
				set_timeParameter(hou, 24, timeType); 
				print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+hourWidth/2-4, 2);
				break;
			}
			
			case 1: {
				print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinOffenSymb,timeXPos+hourWidth+2*SPACE_TO_DOTS+ TIMEDOT_WIDTH + minuteWidth/2-4, 2); 
				update_LCD(); 
				set_timeParameter(min, 60, timeType); 
				print_symbol(8,HERZ_KLEIN_WIDTH,herzKleinSymb,timeXPos+hourWidth+2*SPACE_TO_DOTS+ TIMEDOT_WIDTH + minuteWidth/2-4, 2);
				break;
			}
			case 2: {	seconds = 0;
						cli();
						TCNT2 = 0;
						timeAdvance = 0;
						timeUpdate = 0;
						sei();
						break;
			}
		}
		update_LCD();
	}
}
Esempio n. 7
0
int
door_main(void)
{
	serial_init(9600, 8e2);

	pin13_mode_output();

	pin_mode_input(PIN_CLK);         /* clk             */
	pin_mode_input(PIN_DATA);        /* data            */
	pin_mode_output(PIN_GREEN_LED);  /* green led lock  */
	pin_mode_output(PIN_YELLOW_LED); /* yellow led lock */
	pin_mode_output(PIN_OPEN_LOCK);  /* open            */
	pin_mode_output(PIN_DAYMODE);    /* stay open       */
	pin_mode_output(PIN_STATUS_LED); /* yellow status   */

	pin_high(PIN_OPEN_LOCK);
	pin_high(PIN_DAYMODE);
	pin_high(PIN_GREEN_LED);
	pin_high(PIN_YELLOW_LED);

	/* trigger pin2 interrupt when the clock
	 * signal goes high */
	pin2_interrupt_mode_rising();
	pin2_interrupt_enable();

	data_reset();

	/* setup timer1 to trigger interrupt a 4 times a second */
	timer1_mode_ctc();
	timer1_compare_a_set(62499);
	timer1_clock_d64();
	timer1_interrupt_a_enable();

        softserial_init();
	pin_mode_output(PIN_RFID_ENABLE);
	pin_low(PIN_RFID_ENABLE);

	sleep_mode_idle();

	while (1) {
		/*
		 * sleep if no new events need to be handled
		 * while avoiding race conditions. see
		 * http://www.nongnu.org/avr-libc/user-manual/group__avr__sleep.html
		 */
		cli();
		if (events == EV_NONE && !ev_softserial) {
			sleep_enable();
			sei();
			sleep_cpu();
			sleep_disable();
			continue;
		}
		sei();

		if (events & EV_SERIAL) {
			handle_serial_input();
			continue;
		}

		if (ev_softserial) {
			handle_rfid_input();
		}

		events &= ~EV_DATA;
		if (cnt > 0 && data[cnt - 1] == 0xB4) {
			if (cnt >= 10) {
				struct sha1_context ctx;
				char digest[SHA1_DIGEST_LENGTH];

				sha1_init(&ctx);
				sha1_update(&ctx, (char *)data, 256);
				sha1_final(&ctx, digest);
				serial_print("HASH+");
				serial_hexdump(digest, SHA1_DIGEST_LENGTH);
				serial_print("\n");
			}
			data_reset();
			continue;
		}

		events &= ~EV_TIME;
		if (second > 10*4) {
			serial_print("ALIVE\n");
			second = 0;
			data_reset();
			continue;
		}
	}
}
Esempio n. 8
0
/*---------------------------------------------------------------------------*/
int main(void)
{
    uint8_t rv;
    uint8_t i = 0;
    uint8_t mcp3421_addr;
    uint8_t mcp9800_addr;
    uint8_t tmpReadout[4];

    /* Variables for cold junction moving average filter */
    int16_t movAvg_read;
    int8_t movAvg_ind = 0;
    int32_t movAvg_sum = 0;
    uint8_t movAvg_stabil = 0;
    int16_t movAvg_mem[8] = {0,0,0,0,0,0,0,0};    

    gainSetting = 0;
    timer0_counter = 0;

    initSerialNumber();
    usb_init();  
    I2C_Init();  
    timer_init();

    pinMode(B,1,OUTPUT);

    /*-----------------------------------------------------------------------*/
    /* Search for viable MCP3421 address options */
    /*-----------------------------------------------------------------------*/
    for(i=0x68;i<0x70;i++)
    {
        I2C_Start();
        rv = I2C_Write(write_address(i));
        I2C_Stop();

        if(rv == 0)
        {
            mcp3421_addr = i;
        }
    }

    /*-----------------------------------------------------------------------*/
    /* Search for viable MCP9800 address options */
    /*-----------------------------------------------------------------------*/
    I2C_Start();
    rv = I2C_Write(write_address(0x48));
    I2C_Stop();

    if(rv == 0)
    {
        mcp9800_addr = 0x48;
    }
    else
    {
        mcp9800_addr = 0x4D;
    }

    /*-----------------------------------------------------------------------*/
    /* Set MCP9800 to 12 bit resolution */
    /*-----------------------------------------------------------------------*/
    I2C_Start();
    I2C_Write(write_address(mcp9800_addr));    
    I2C_Write(0x01);
    I2C_Write((1<<7)|(1<<6)|(1<<5));
    I2C_Stop();

    /*-----------------------------------------------------------------------*/
    /* Set MCP9800 Register Pointer to Ambient Temperature */
    /*-----------------------------------------------------------------------*/
    I2C_Start();
    I2C_Write(write_address(mcp9800_addr));
    I2C_Write(0x00);
    I2C_Stop();
    
    while(1)
    {                
        /*-------------------------------------------------------------------*/
        /* MCP9800: Cold junction channel */
        /*-------------------------------------------------------------------*/
        usbPoll();
        I2C_Start();
        debug[0] = I2C_Write(read_address(mcp9800_addr));
        tmpReadout[0] = I2C_Read(ACK);
        tmpReadout[1] = I2C_Read(NO_ACK);        
        I2C_Stop();

        movAvg_read = ((int16_t)tmpReadout[0] << 8) + ((int16_t)tmpReadout[1]);                
        movAvg_sum -= movAvg_mem[movAvg_ind];
        movAvg_sum += movAvg_read;        
        movAvg_mem[movAvg_ind] = movAvg_read;
        
        if(movAvg_ind == 7)
        {
            movAvg_ind = 0;
            movAvg_stabil = 1;
        }
        else
        {
            movAvg_ind++;
        }

        if(movAvg_stabil == 1)
        {
            movAvg_read = movAvg_sum >> 3;    
        }        

        usbPoll();
        cli();                                
            coldJunctionReadout[0] = movAvg_read >> 8;            
            coldJunctionReadout[1] = movAvg_read & 0xFF;          
        sei();

        /*-------------------------------------------------------------------*/
        /* MCP3421: 3.75 SPS + 18 Bits + Initiate new conversion
        /*-------------------------------------------------------------------*/
        usbPoll();
        I2C_Start();
        I2C_Write(write_address(mcp3421_addr));
        I2C_Write((1<<7)|(1<<3)|(1<<2)|gainSetting);
        I2C_Stop();

        /*-------------------------------------------------------------------*/
        /* Small delay ...
        /*-------------------------------------------------------------------*/
        timer0_counter = 250;
        while(timer0_counter)
        {
            usbPoll();            
        }

        /*-------------------------------------------------------------------*/
        /* MCP3421
        /*-------------------------------------------------------------------*/
        usbPoll();
        I2C_Start();
        I2C_Write(read_address(mcp3421_addr));
        tmpReadout[0] = I2C_Read(ACK);
        tmpReadout[1] = I2C_Read(ACK);
        tmpReadout[2] = I2C_Read(ACK);
        tmpReadout[3] = I2C_Read(NO_ACK);
        I2C_Stop();

        usbPoll();
        cli();
            thermocoupleReadout[0] = tmpReadout[0];
            thermocoupleReadout[1] = tmpReadout[1];
            thermocoupleReadout[2] = tmpReadout[2];
            thermocoupleReadout[3] = tmpReadout[3];
        sei();
    }
Esempio n. 9
0
int main(void)
{
    { // Set up timers, sleep and such
        cli();
        set_sleep_mode(SLEEP_MODE_IDLE);
        PRR = ((1 << PRTIM1) | (1 << PRUSI) | (1 << PRADC));
        // TIMER0
        TCCR0A = (1 << WGM01);
        TCCR0B = ((1 << CS01) | (1 << CS00));
        OCR0A = 61;
        OCR0B = 0;
        TIMSK = (1 << OCIE0A);
        // INT0
        MCUCR |= (1 << ISC01);
        GIMSK = (1 << INT0);
        PORTB = PORTB_NULL;
        counter = leds = 0;
        counter_max = MAXIMUM;
        piezo = 0;
        stopped = 1;
        sei();
    }
    { // Set up the counter and start
        while (stopped < 3)
        {
            leds = counter_max;
            sleep_mode();
        }
        leds = LED_ON;
    }
    { // Prepare for the timer
        cli();
        GIMSK = 0; // Stop INT0
        stopped = 0;
        TCNT0 = 0; // Clear TIMER0
        sei();
    }
    { // Display the timer while it's running
        while (counter < counter_max)
        {
            leds = counter | LED_ON;
            sleep_mode();
        }
        stopped = 4;
        leds = counter;
    }
    { // Yell!
        cli();
        GIMSK = (1 << INT0); // Start INT0
        sei();
        while (stopped == 4) // Sleep!
            sleep_mode();
        GIMSK = 0; // Stop INT0
        TCCR0A &= ~((1 << COM0B1) | (1 << COM0B0)); // Stop yelling!
    }
    { // Timer finished, sleep forever!
        cli();
        TIMSK = 0;
        PORTB = 0; // Everything off
        set_sleep_mode(SLEEP_MODE_PWR_DOWN);
        sleep_mode();
    }
    return 0;
}
Esempio n. 10
0
/**
 * Entry point 
 */
int main(void) {

  /* Misc variables */
  DCPU_registers reg; // CPU registers states (at boot)

  /* Hardware initialisation */
  cli();
  led_setup();
  spi_setup(SPI_PRESCALER, SPI_MODE, SPI_BITS_ORDER);
  uart_setup(UART_BAUDRATE);
  DEBUG_STR("Main init", "UART ready");
  button_setup();
  buzzer_setup(BUZZER_FREQUENCY, BUZZER_DURATION);
  ram_setup();
  rom_setup();
  microvga_setup();
  microvga_enable();
  dcpu_register_init(&reg);
  DEBUG_STR("Main init", "done");
  sei();
  
  /* MicroVGA initialisation */
  _delay_ms(1000);         // MicroVGA boot time
  microvga_clear_screen(); // Clear screen and goto (0, 0)
  microvga_goto_cursor(0, 0);
  uart_puts_PSTR(PSTR("SkyWodd DCPU-16 hardware emulator")); // Screen test
  buzzer_beep();
  DEBUG_STR("Main init", "MicroVGA ready");
  
  /* Hardware self-test */
  DEBUG_STR("Main init", "self-test run");
  led_run_write(1); // Led test
  _delay_ms(250);
  led_run_write(0);
  led_cpu_write(1);
  _delay_ms(250);
  led_cpu_write(0);
  led_rom_write(1);
  _delay_ms(250);
  led_rom_write(0);
  led_ram_write(1);
  _delay_ms(250);
  led_ram_write(0);
  DEBUG_STR("Main init", "self-test done");
  
  /* Keyboard & MicroVGA api test */
  DEBUG_STR("Main init", "waiting for keypress");
  microvga_goto_cursor(0, 1);
  uart_puts_PSTR(PSTR("Press any key to boot ..."));
  keyboard_wait();
  uart_puts_PSTR(PSTR("Loading please wait ..."));
  dcpu_setup(reg);
  buzzer_beep();
  microvga_clear_screen();
  microvga_goto_cursor(0, 0);
  DEBUG_STR("Main init", "ready to run");
  
  /* Infinite loop */
  for(;;) {
  
    /* Handle pause */
    while(!button_get_state()); 
	
#ifdef SERIAL_DEBUG_SUPPORT
	/* Debug */
	dcpu_registers_dump();
#endif
	
	/* Fetch opcode from ROM */
    dcpu_step(); 
  }
  
}
Esempio n. 11
0
static void bluetooth_parse_command(uint8_t len)
{
	uint8_t response = RESPONSE_OK;

	sei();

	if (len == 0) {
		response = RESPONSE_NO_RESPONSE;
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_HELP, len) == 0) {
		uint8_t i = 0;

		for (i = 1; i < sizeof(commands) / sizeof(commands[0]); i ++) {
			uart_puts(commands[i]);

			if ((i % 3) == 0) {
				uart_puts("\r\n");
			} else {
				uint8_t padding = 0, j = 0;
				padding = 26 - strlen(commands[i]);
				for (j = 0; j < padding; j++) {
					uart_putc(' ');
				}
			}
		}

		if (((i - 1) % 3) != 0) {
			uart_puts("\r\n");
		}

		response = RESPONSE_NO_RESPONSE;
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_BATTERY, len) == 0) {
		uint8_t capacity = 0;
		char resp[16];

		capacity = battery_get_capacity();
		itoa(capacity, resp, 10);

		uart_puts(BLUETOOTH_CMD_BATTERY);
		uart_puts(": ");
		uart_puts(resp);
		uart_puts("%\r\n");

		response = RESPONSE_NO_RESPONSE;
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_ECHO, len) == 0) {
		echo = TRUE;
		uart_puts("\r\n");
		response = RESPONSE_NO_RESPONSE;
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_EYES, strlen(BLUETOOTH_CMD_EYES)) == 0) {
		char *param = rxbuff + strlen(BLUETOOTH_CMD_EYES) + 1;

		if (len == strlen(BLUETOOTH_CMD_EYES) + strlen(BLUETOOTH_PARAM_ON) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_ON, strlen(BLUETOOTH_PARAM_ON)) == 0) {
				power_on(EYES);
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_EYES) + strlen(BLUETOOTH_PARAM_OFF) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_OFF, strlen(BLUETOOTH_PARAM_OFF)) == 0) {
				power_off(EYES);
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_EYES)) {
			uint8_t state = power_state(EYES);

			uart_puts(BLUETOOTH_CMD_EYES);
			uart_puts(": ");

			if (state == POWER_ON) {
				uart_puts(BLUETOOTH_PARAM_ON);
			} else {
				uart_puts(BLUETOOTH_PARAM_OFF);
			}
			uart_puts("\r\n");

			response = RESPONSE_NO_RESPONSE;
		} else {
			response = RESPONSE_ERROR;
		}
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_HELMET, strlen(BLUETOOTH_CMD_HELMET)) == 0) {
		char *param = rxbuff + strlen(BLUETOOTH_CMD_HELMET) + 1;

		if (len == strlen(BLUETOOTH_CMD_HELMET) + strlen(BLUETOOTH_PARAM_OPEN) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_OPEN, strlen(BLUETOOTH_PARAM_OPEN)) == 0) {
				helmet_open();
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_HELMET) + strlen(BLUETOOTH_PARAM_CLOSE) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_CLOSE, strlen(BLUETOOTH_PARAM_CLOSE)) == 0) {
				helmet_close();
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_HELMET)) {
			uint8_t state = helmet_state();

			uart_puts(BLUETOOTH_CMD_HELMET);
			uart_puts(": ");

			if (state == HELMET_OPEN) {
				uart_puts(BLUETOOTH_PARAM_OPEN);
			} else {
				uart_puts(BLUETOOTH_PARAM_CLOSE);
			}
			uart_puts("\r\n");

			response = RESPONSE_NO_RESPONSE;
		} else {
			response = RESPONSE_ERROR;
		}
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_INTENSITY, strlen(BLUETOOTH_CMD_INTENSITY)) == 0) {
		uint8_t device = 0;
		char *param = rxbuff + strlen(BLUETOOTH_CMD_INTENSITY) + 1;

		if (strncmp(param, BLUETOOTH_CMD_EYES, strlen(BLUETOOTH_CMD_EYES)) == 0) {
			if (len == strlen(BLUETOOTH_CMD_INTENSITY) + strlen(BLUETOOTH_CMD_EYES) + 3) {
				device = EYES;
			} else if (len == strlen(BLUETOOTH_CMD_INTENSITY) + strlen(BLUETOOTH_CMD_EYES) + 1) {
				device = EYES;
				response = RESPONSE_NO_RESPONSE;
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (strncmp(param, BLUETOOTH_CMD_REPULSORS, strlen(BLUETOOTH_CMD_REPULSORS)) == 0) {
			if (len == strlen(BLUETOOTH_CMD_INTENSITY) + strlen(BLUETOOTH_CMD_REPULSORS) + 3) {
				device = REPULSORS_POWER;
			} else if (len == strlen(BLUETOOTH_CMD_INTENSITY) + strlen(BLUETOOTH_CMD_REPULSORS) + 1) {
				device = REPULSORS_POWER;
				response = RESPONSE_NO_RESPONSE;
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (strncmp(param, BLUETOOTH_CMD_UNIBEAM, strlen(BLUETOOTH_CMD_UNIBEAM)) == 0) {
			if (len == strlen(BLUETOOTH_CMD_INTENSITY) + strlen(BLUETOOTH_CMD_UNIBEAM) + 3) {
				device = UNIBEAM;
			} else if (len == strlen(BLUETOOTH_CMD_INTENSITY) + strlen(BLUETOOTH_CMD_UNIBEAM) + 1) {
				device = UNIBEAM;
				response = RESPONSE_NO_RESPONSE;
			} else {
				response = RESPONSE_ERROR;
			}
		} else {
			response = RESPONSE_ERROR;
		}

		if (response == RESPONSE_OK) {
			// convert number in ascii to integer
			uint8_t intensity = rxbuff[len - 1] - '0';

			if ((intensity >= 0) && (intensity <= 9)) {
				power_set_intensity(device, intensity);
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (response == RESPONSE_NO_RESPONSE) {
			int8_t intensity = power_get_intensity(device);

			uart_puts(BLUETOOTH_CMD_INTENSITY);
			uart_puts(": ");
			uart_putc('0' + intensity);
			uart_puts("\r\n");
		}
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_QUOTE, len) == 0) {
		if (voice_is_playing()) {
			voice_stop_playback();
		} else {
			voice_play_quote();
		}
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_REBOOT, len) == 0) {
		response = RESPONSE_NO_RESPONSE;

		// stop reporting of battery status
		battery_reporting_stop();

		voice_play_sound(SOUND_SLEEP_0);
		_delay_ms(1000);
		voice_play_sound(SOUND_SLEEP_2);
		voice_play_sound_no_wait(SOUND_POWER_DOWN);

		// turn off all devices
		power_off(ALL);

		// restart mcu
		wdt_reboot();
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_REPULSORS, strlen(BLUETOOTH_CMD_REPULSORS)) == 0) {
		char *param = rxbuff + strlen(BLUETOOTH_CMD_REPULSORS) + 1;

		if (len == strlen(BLUETOOTH_CMD_REPULSORS) + strlen(BLUETOOTH_PARAM_ON) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_ON, strlen(BLUETOOTH_PARAM_ON)) == 0) {
				power_on(REPULSORS_POWER);
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_REPULSORS) + strlen(BLUETOOTH_PARAM_OFF) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_OFF, strlen(BLUETOOTH_PARAM_OFF)) == 0) {
				power_off(REPULSORS_POWER);
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_REPULSORS)) {
			uint8_t state = power_state(REPULSORS_POWER);

			uart_puts(BLUETOOTH_CMD_REPULSORS);
			uart_puts(": ");

			if (state == POWER_ON) {
				uart_puts(BLUETOOTH_PARAM_ON);
			} else {
				uart_puts(BLUETOOTH_PARAM_OFF);
			}
			uart_puts("\r\n");

			response = RESPONSE_NO_RESPONSE;
		} else {
			response = RESPONSE_ERROR;
		}
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_REPULSOR, strlen(BLUETOOTH_CMD_REPULSOR)) == 0) {
		char *param = rxbuff + strlen(BLUETOOTH_CMD_REPULSOR) + 1;

		if (len == strlen(BLUETOOTH_CMD_REPULSOR) + strlen(BLUETOOTH_PARAM_LEFT) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_LEFT, strlen(BLUETOOTH_PARAM_LEFT)) == 0) {
				power_blast(REPULSOR_LEFT);
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_REPULSOR) + strlen(BLUETOOTH_PARAM_RIGHT) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_RIGHT, strlen(BLUETOOTH_PARAM_RIGHT)) == 0) {
				power_blast(REPULSOR_RIGHT);
			} else {
				response = RESPONSE_ERROR;
			}
		} else {
			response = RESPONSE_ERROR;
		}
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_UNIBEAM, strlen(BLUETOOTH_CMD_UNIBEAM)) == 0) {
		char *param = rxbuff + strlen(BLUETOOTH_CMD_UNIBEAM) + 1;

		if (len == strlen(BLUETOOTH_CMD_UNIBEAM) + strlen(BLUETOOTH_PARAM_ON) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_ON, strlen(BLUETOOTH_PARAM_ON)) == 0) {
				power_on(UNIBEAM);
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_UNIBEAM) + strlen(BLUETOOTH_PARAM_OFF) + 1) {
			if (strncmp(param, BLUETOOTH_PARAM_OFF, strlen(BLUETOOTH_PARAM_OFF)) == 0) {
				power_off(UNIBEAM);
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_UNIBEAM)) {
			uint8_t state = power_state(UNIBEAM);

			uart_puts(BLUETOOTH_CMD_UNIBEAM);
			uart_puts(": ");

			if (state == POWER_ON) {
				uart_puts(BLUETOOTH_PARAM_ON);
			} else {
				uart_puts(BLUETOOTH_PARAM_OFF);
			}
			uart_puts("\r\n");

			response = RESPONSE_NO_RESPONSE;
		} else {
			response = RESPONSE_ERROR;
		}
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_VERSION, len) == 0) {
		uart_puts(BLUETOOTH_RESPONSE_VERSION);
		uart_puts("\r\n");
		response = RESPONSE_NO_RESPONSE;
	} else if (strncmp(rxbuff, BLUETOOTH_CMD_VOLUME, strlen(BLUETOOTH_CMD_VOLUME)) == 0) {
		if (len == strlen(BLUETOOTH_CMD_VOLUME) + 2) {
			// convert number in ascii to integer
			uint8_t volume = rxbuff[len - 1] - '0';

			if ((volume >= 0) && (volume <= 7)) {
				voice_set_volume(SOUND_VOLUME_0 + volume);
			} else {
				response = RESPONSE_ERROR;
			}
		} else if (len == strlen(BLUETOOTH_CMD_VOLUME)) {
			uint8_t volume = voice_get_volume() - SOUND_VOLUME_0;

			uart_puts(BLUETOOTH_CMD_VOLUME);
			uart_puts(": ");
			uart_putc('0' + volume);
			uart_puts("\r\n");

			response = RESPONSE_NO_RESPONSE;
		} else {
			response = RESPONSE_ERROR;
		}
	} else {
		response = RESPONSE_ERROR;
	}

	if (response == RESPONSE_OK) {
		uart_puts(BLUETOOTH_RESPONSE_OK);
		uart_puts("\r\n");
	} else if (response == RESPONSE_ERROR) {
		uart_puts(BLUETOOTH_RESPONSE_ERROR);
		uart_puts("\r\n");
	}

	if (echo) {
		uart_puts(BLUETOOTH_PROMPT);
	}
}
Esempio n. 12
0
/*
 *      //~ uart_puts_P("G21\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G90\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G94\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G17\n");
        //~ get_grbl_response();
        //~ uart_puts_P("M3 S1000\n");
        //~ get_grbl_response();
        //~ uart_puts_P("F800.00\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G0 Z1.00\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G0 X15 Y15\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G1 Z-1\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G2 X25 Y25 I10\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G0 Z1\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G0 X35 Y15\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G1 Z-1\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G2 X25 Y5 I-10\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G0 Z1\n");
        //~ get_grbl_response();
        //~ uart_puts_P("G0 X15 Y15\n");
        //~ get_grbl_response();
        //~ uart_puts_P("M5\n");
        //~ get_grbl_response();
        //~ uart_puts_P("M30\n");
*/
int main(void)
{
  stdout = &mystdout;
  //uart_init(UART_BAUD_SELECT_DOUBLE_SPEED(UART_BAUD_RATE,F_CPU));
  uart_init(UART_BAUD_SELECT(UART_BAUD_RATE,F_CPU));
  lcd_init(LCD_DISP_ON_CURSOR);
  lcd_clrscr();
  lcd_gotoxy(0,0);
  lcd_puts_P("Needler v0.7\n");
  lcd_gotoxy(0,1);
  lcd_puts_P(__DATE__" aw");

  //Delay for Splash
  for(uint8_t i=0;i<160;++i)
    _delay_ms(15);

  //PD2: IN : Z_DIR
  //PD3: IN : Enable/FEED HOLD. 0=betätigt
  //PD6: OUT: Relais Pneumatikventil. 1=EIN
  DDRD  |= _BV(PD6);
  PORTD |= _BV(PD2) | _BV(PD3) | _BV(PD4) | _BV(PD5) | _BV(PD7);

  //PB1: IN: Z_STEP
  PORTB |= _BV(PB1);

  lcd_clrscr();
  clr_text_buffer();
  strncpy(font_name,"rowmans",10);

  /*** TIMER0 ***/
  OCR0=250;
  //CTC = Clear Timer on Compare match S.80
  //Normal port operation, OC0 disconnected
  //Prescaler=64 -> clk=250kHz
  TCCR0 = _BV(WGM01) | _BV(CS01) | _BV(CS00);
  //On Compare match Interrupt Enable for timer 0
  TIMSK |= _BV(OCIE0);

  /** TIMER1 **/
  //PWM Phase correct 10bit
  //Set OC1A+OC1B on match when upcounting (page 108)
  //TCCR1A = _BV(COM1A1) | _BV(COM1B1) | _BV(COM1A0) | _BV(COM1B0) | _BV(WGM11) | _BV(WGM10);
  //Prescaler = 1 (page 110)
  //TCCR1B = _BV(CS10);

  /** TIMER1 **/
  //External clock source on T1 pin. Clock on rising edge.
  TCCR1B = _BV(CS12) | _BV(CS11) | _BV(CS10);
  //OCR1x=5;

  /** External Interrupt INT0 PD2 **/
  //Any logical change on INT0 generates an interrupt request.
  MCUCR = _BV(ISC00);
  GICR = _BV (INT0);

  //enable global interrupts
  sei();
  uint8_t debounce_key=0, last_key=0;
  uint8_t key, event=0;
  for (;;)    /* main event loop */
    {
      key=key_get();
      if(key==last_key)
        debounce_key++;
      else
        debounce_key=0;
      if(debounce_key>50)
      {
        event=process_menu(key);
        debounce_key=0;
      }
      last_key=key;

      if(do_update_lcd || event)
      {
        update_lcd();
        do_update_lcd=0;
      }

      if (bit_is_clear(PIND,3) && !running)
      {
        grbl_num_err=0;
        grbl_num_ok=0;
        //empty read
        while(uart_getc()!=UART_NO_DATA);
        running=1;
        update_status_lcd();
        uart_puts_P("$X\n");
        get_grbl_response();
        strncpy(grbl_error_msg, "$H:Referenzfahrt",17);
        update_status_lcd();
        uart_puts_P("$H\n");
        get_grbl_response();
        strncpy(grbl_error_msg, "Gravur laeuft...",17);
        update_status_lcd();

       //int init_get_gcode_line ( char *font, char *text, double X0, double Y0, double Z_up, double Z_down, double yinc, double scale,
       //double feed, int precision, char verbose, char align, char use_inch);

        //int r = init_get_gcode_line("rowmans", "Hello world!", 1, 1, 1, -1, 7, 0.3, 1100, 3, 0, 'l', 0);
        uint8_t line_nr;
        double scale=font_size*0.047619;
        double x0, y0;
        char line[BUFFER_WIDTH];
        for(line_nr=0; line_nr<BUFFER_HEIGHT; line_nr++)
        {
          strncpy(line, get_text_buffer(line_nr), BUFFER_WIDTH);
          //Leerzeichen am Ende mit 0 füllen
          int8_t len = BUFFER_WIDTH-1;
          while(len>=0 && line[len]==' ') line[len--]=0;

          //Positionsberechnung
          //Die Alukärtchen haben 85x54mm
          x0 = 7; //10mm vorerst fix, wie einstellbar?
          y0 = 50 - (line_nr+1) * (font_size*1.7);  //70% der Zeichenhöhe als Zeilenabstand

          //~ uart_puts_P("-");
          //~ uart_puts(line);
          //~ uart_puts_P("-");
          //~ char xtemp[5];
          //~ itoa(len,xtemp,10);
          //~ uart_puts(xtemp);
          //~ uart_puts_P("----");

          if(len>=0)
          {
            init_get_gcode_line(font_name, line, x0, y0, 1, -1, 0, scale, 1300, 2, 0, 'l', 0);
            char buf[200];
            while((g_line = get_gcode_line (buf, 200))!=-1)
            {
              uart_puts(buf);
              uart_putc('\n');
              get_grbl_response();
            }
          }
        }
        strncpy(grbl_error_msg, "*** BEENDET  ***",17);
        update_status_lcd();
        PORTD &= (uint8_t) ~_BV(PD6);
        uart_puts_P("G0X1Y1\n");
        uart_puts_P("M30\n");
        //empty read
        while(uart_getc()!=UART_NO_DATA);
        //BEENDET etwas stehen lassen
        for(uint8_t i=0;i<200;++i)
          _delay_ms(10);
        grbl_error_msg[0]=0;
        do_update_lcd=1;
        running=0;
      }
    }
    return 0;
}
Esempio n. 13
0
void HardwareSerial::flush()
{
  cli();
  _rxfifo->idx_r = _rxfifo->idx_w = 0;
  sei();
}
/*
 * Do all the startup-time peripheral initializations.
 */
static void
ioinit(void)
{
  uint16_t pwm_from_eeprom;

  /*
   * Set up the 16-bit timer 1.
   *
   * Timer 1 will be set up as a 10-bit phase-correct PWM (WGM10 and
   * WGM11 bits), with OC1A used as PWM output.  OC1A will be set when
   * up-counting, and cleared when down-counting (COM1A1|COM1A0), this
   * matches the behaviour needed by the STK500's low-active LEDs.
   * The timer will runn on full MCU clock (1 MHz, CS10 in TCCR1B).
   */
  TCCR1A = _BV(WGM10) | _BV(WGM11) | _BV(COM1A1) | _BV(COM1A0);
  TCCR1B = _BV(CS10);

  OCR1A = 0;			/* set PWM value to 0 */

  /* enable pull-ups for pushbuttons */
  CONTROL_PORT = _BV(TRIGGER_DOWN) | _BV(TRIGGER_UP) | _BV(TRIGGER_ADC);

  /*
   * Enable Port D outputs: PD6 for the clock output, PD7 for the LED
   * flasher.  PD1 is UART TxD but not DDRD setting is provided for
   * that, as enabling the UART transmitter will automatically turn
   * this pin into an output.
   */
  CONTROL_DDR = _BV(CLOCKOUT) | _BV(FLASH);

  /*
   * As the location of OC1A differs between supported MCU types, we
   * enable that output separately here.  Note that the DDRx register
   * *might* be the same as CONTROL_DDR above, so make sure to not
   * clobber it.
   */
  PWMDDR |= _BV(PWMOUT);

  UCSRA = _BV(U2X);		/* improves baud rate error @ F_CPU = 1 MHz */
  UCSRB = _BV(TXEN)|_BV(RXEN)|_BV(RXCIE); /* tx/rx enable, rx complete intr */
  UBRRL = (F_CPU / (8 * 9600UL)) - 1;  /* 9600 Bd */

  /*
   * enable ADC, select ADC clock = F_CPU / 8 (i.e. 125 kHz)
   */
  ADCSRA = _BV(ADEN) | _BV(ADPS1) | _BV(ADPS0);

  TIMSK = _BV(TOIE1);
  sei();			/* enable interrupts */

  /*
   * Enable the watchdog with the largest prescaler.  Will cause a
   * watchdog reset after approximately 2 s @ Vcc = 5 V
   */
  wdt_enable(WDTO_2S);

  /*
   * Read the value from EEPROM.  If it is not 0xffff (erased cells),
   * use it as the starting value for the PWM.
   */
  if ((pwm_from_eeprom = eeprom_read_word(&ee_pwm)) != 0xffff)
    OCR1A = (pwm = pwm_from_eeprom);
}
Esempio n. 15
0
int main( )
{
	uint8_t frame;
	static uint8_t i;
	static uint16_t adcT = 0;  //ADC Temp
	static uint16_t adcP = 0;  //ADC Pin
	static uint8_t last_timercycle = 0;
	cli();

	setup_clock();

	//1st let's see how fast we can clock the pin.
	et_init( MyMAC );

	i = 0;


	//Assumed setup:
	//
	// PB2: Disconnect this (I don't know if you can use it at all)
	// PB1: TX (From this device, out) Put a 47nF capcaitor in series.

	//Enable ADC.  (For reading in pin ADC2)
	PORTB &= ~_BV(4);
	PORTB |= _BV(4);
	ADCSRA = _BV(ADEN) | _BV(ADPS1) | _BV(ADPS0) | _BV(ADSC) | _BV(ADATE);

	//Enable port B for the WS2812B.
	WSDDR |= WSPIN;
	WSPORT &= ~WSPIN;

	//The burden of configuring the tick timer is on you, the user.
	//#188 Creates a clock with period ~4ms. ~3.2ms at 31MHz, ~4.8ms at 20 MHz.
	//Making it lower seems to help.
	TCCR1 = _BV(CTC1) | _BV(CS13) | _BV(CS12); //HS Clock/2048
	OCR1C = 255; 
	OCR1A = 1;
	TIMSK = _BV(OCIE1A);

	//Enable Pin Change Interrupt.
	//(For if we have some RX data)
	PCMSK |= _BV(PCINT0);
	GIMSK |= _BV(PCIE);

	sei();

	OSCCAL = OSCHIGH;
	PORTB |= _BV(0);

	while(1)
	{
		if( last_timercycle != timercycle )
		{
			last_timercycle = timercycle;
			//i++;
			i = timercycle & 0x0f;

			if( i == 0 )
			{
				ADMUX = 2;
			}

			if( i == 1 )
			{
				adcP = ADC;
				ADMUX = _BV(REFS1) | 0x0f;
			}

			if( i == 2 )
			{
				adcT = ADC;
			}

			if( i == 14 )
			{

				frame++;
				//How to send a UDP Packet.
				cli();
				OSCCAL = OSC20;
				et_stopop();
				et_startsend( 0 );
				memset( macfrom, 0xff, 6 );
				send_etherlink_header( 0x0800 );
				send_ip_header( 0, (unsigned char*)"\xff\xff\xff\xff", 17 ); //UDP Packet to 255.255.255.255
				et_push16( 13313  ); //to port
				et_push16( 13312 ); //from port
				et_push16( 0 ); //length for later
				et_push16( 0 ); //csum for later
				et_pushpgmstr( PSTR( "TPIN" ) ); //csum for later
				et_push16( adcT ); 
				et_push16( adcP ); 
				et_push16( icmp_out ); 
				et_push16( hict ); 
				et_push16( lowct );
				util_finish_udp_packet();
				OSCCAL = OSCHIGH;
				sei();
				i = 0;

			}

		}
	}



	return 0;
} 
Esempio n. 16
0
/******************************************************************************
* File:              main.c
* Author:            Kevin Day
* Date:              February, 2005
* Description:       
*                    Main program for audi radio interface
*                    
* Copyright (c) 2005 Kevin Day
* 
*     This program is free software: you can redistribute it and/or modify
*     it under the terms of the GNU General Public License as published by
*     the Free Software Foundation, either version 3 of the License, or
*     (at your option) any later version.
*
*     This program is distributed in the hope that it will be useful,
*     but WITHOUT ANY WARRANTY; without even the implied warranty of
*     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*     GNU General Public License for more details.
*
*     You should have received a copy of the GNU General Public License
*     along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*******************************************************************************/


#include <avr/interrupt.h>
#include <avr/pgmspace.h>
#include <avr/io.h>
#include <avr/wdt.h>

#include "types.h"
#include "tasks.h"
#include "comms_generic.h"
#include "timers.h"
#include "adc.h"
#include "persist.h"
#include "hcms.h"
#include "gpsavr.h"
#include "hud.h"
#include "spimaster.h"
#include "avrcan.h"
#include "avrms2.h"
#include "swuart.h"
#include "hwi2c.h"
#include "adcgauges.h"
#include "miscgpio.h"
#include "sensors.h"

#define LED_PORT PORTG
#define LED_DIR  DDRG
#define LED_PIN  PING
#define LED_BIT  0

#define ANT_PORT PORTB
#define ANT_DIR  DDRB
#define ANT_PIN  PINB
#define ANT_BIT  2

void debug_led(u8 val);
static inline void start_blink_timer();

void bufferpool_init();
task_t* comms_task_create();
task_t *radio_input_task_create();


#define STACK_CANARY 0xC5
void StackPaint(void) __attribute__ ((naked)) __attribute__ ((section (".init1")));

void StackPaint(void)
{
#if 0
    uint8_t *p = &_end;

    while(p <= &__stack)
    {
        *p = STACK_CANARY;
        p++;
    }
#else
    __asm volatile ("    ldi r30,lo8(_end)\n"
                    "    ldi r31,hi8(_end)\n"
                    "    ldi r24,lo8(0xc5)\n" /* STACK_CANARY = 0xc5 */
                    "    ldi r25,hi8(__stack)\n"
                    "    rjmp .cmp\n"
                    ".loop:\n"
                    "    st Z+,r24\n"
                    ".cmp:\n"
                    "    cpi r30,lo8(__stack)\n"
                    "    cpc r31,r25\n"
                    "    brlo .loop\n"
                    "    breq .loop"::);
#endif
} 

extern uint8_t __heap_start; /* not _end because of .bufferpool */
extern uint8_t __stack; 

uint16_t StackCount(void)
{
    const uint8_t *p = &__heap_start;
    uint16_t       c = 0;

    while(*p == STACK_CANARY && p <= &__stack)
    {
        p++;
        c++;
    }

    return c;
} 




#define ADC_CONTEXTS 8
adc_context_t adc_context[ADC_CONTEXTS];
u8 num_adc;
u16 stack_high;

#define DISPAVR_RESET_PIN 4 /* on port B */
int main()
{    
    u8 mcusr_rst = MCUSR;
    MCUSR = 0;
    wdt_disable();
    wdt_enable(WDTO_2S);

    /* Disable JTAG so the ADC pins are available.
     * Don't do this if the JTAG reset flag is set -- 
     * presumably the jtag pod is connected in that
     * case. */
    if (! (mcusr_rst & (1<<JTRF)))
    {
        MCUCR |= (1<<JTD);
    }

    /* Assert remote AVR reset */
    PORTB &= ~(1<<DISPAVR_RESET_PIN);
    DDRB  |= (1<<DISPAVR_RESET_PIN);

    bufferpool_init();
    
    init_persist_data();
    
    systimer_init();

    //fuel_gauge_init(&adc_context[num_adc++]);

    num_adc = sensors_init(&adc_context[num_adc], num_adc);

    adc_init_adc(ADC_DIV128, num_adc, adc_context);

    /* Deassert remote AVR reset */
    PORTB |= (1<<DISPAVR_RESET_PIN);
    

    spimaster_init();

    init_avrms2(); 

//    swuart_init();

    /* Enable interrupts */
    sei();

    /* Populate the tasklist in priority order */    
    tasklist[num_tasks++] = comms_task_create();
    tasklist[num_tasks++] = gps_task_create();
    tasklist[num_tasks++] = can_task_create();
    tasklist[num_tasks++] = hud_task_create(); 
//    tasklist[num_tasks++] = i2c_task_create(); 
    tasklist[num_tasks++] = gpio_task_create();
    //
    start_blink_timer();

    /* non-preemptive static priority scheduler */    
    while(1)
    {
        wdt_reset();

        u8 taskidx;
	u8 r;
        for(taskidx=0; taskidx<num_tasks; taskidx++)
        {
            r = tasklist[taskidx]->taskfunc();
            if (r)
                break;
        }
        if (r == 0)
        {
            stack_high = StackCount(); /* only run this after all tasks run */
        }
    }
}
Esempio n. 17
0
int main (void) {

    // disable unused functions for powersaving
    PRR = (1<<PRUSI) | (1<<PRUSART);

    DDRA = 0xff;

    change_clock_prescale( 0x01 );  // full speed 4MHz

    led_init_port();

    // brownout @1.8V if device is started with insuficcient bats.
    if ( mcusr_mirror == (1<<BORF) ) {
        blink_red_powersave();
        sleep_powerdown();        
    }
    uint8_t i=0;    // selected pattern;
    uint8_t pwrhyst = 0;

    // switch on stepup, change frequency after short delay
    POWER_DDR |= (1<<POWER_PIN);
    POWER_PORT |= (1<<POWER_PIN);

    // bat comparator
    ACSR = (1<<ACBG);
    DIDR |= (1<<AIN1D);

    // init pwm counter
    led_init_timer();
    key_init_timer_port();

    // alive signal 
    pled_on( (1<<PLED_RED) | (1<<PLED_GREEN) );
    led_set_mode_r( 0x11, 0x11, 0 );
    _delay_ms(50);
    led_set_mode_r( 0x00, 0x00, 0 );
    _delay_ms(500);
    pled_off( (1<<PLED_RED) );

    // check initial bat state for undervolt
    if ( (ACSR & (1<<ACO)) ) pwrhyst = 0xFF;
    sei();

    for(;;) {

        for(uint8_t r=0; r< (*light_patterns[i]).rotate; r++) {
            // if there is a change to measure with leds off, then here
            // => check bat voltage
            if ( ACSR & (1<<ACO) ) {
                if ( pwrhyst == 0x0f ) { 
                    pled_on( 1<<PLED_RED);
                    pled_off(1<<PLED_GREEN);
                } else {
                    pwrhyst++;
                }
            } else {
                if ( pwrhyst == 0x00 ) {
                    pled_on(1<<PLED_GREEN);
                    pled_off( 1<<PLED_RED);
                } else {
                    pwrhyst--;
                }
            } 
            for(uint8_t p=0; p<(*light_patterns[i]).nr_elements; p++) {
                if ( key_press & ALL_KEYS ) {
                    pwrhyst = 0;
                    led_set_mode_r(0x00,0x00,0);
                    if( get_key_short( 1<<KEY0 )) {
                        r = 0;
                        p = 0;
                        i++;
                        if ( i >= sizeof(light_patterns)/sizeof(light_patterns[0]) )
                            i = 0;
                    }
                    if( get_key_long( 1<<KEY0 )) {
                        pled_off( (1<<PLED_RED) | (1<<PLED_GREEN) );
                        // wait for key release (with pullup=>1)
                        loop_until_bit_is_set( KEY_PIN, KEY0 );
                        sleep_powerdown();
                    }
                } else {
                    led_set_mode_r(
                        (*light_patterns[i]->lp_elements)[p]->l12,
                        (*light_patterns[i]->lp_elements)[p]->l34,
                        r);
                    key_wait_times_5ms(
                        (*light_patterns[i]->lp_elements)[p]->duration 
                    );
                }
            }
        }
    }
}
Esempio n. 18
0
int main(void)
{
	char c;

	unsigned short cnt = 0;
#if (F_CPU > 4000000UL)
#define CNTHALLO (unsigned int)(0xFFFF)
#else 
#define CNTHALLO (unsigned int)(0xFFFF/3)
#endif
	unsigned short mycnt=0;
	  CLKPR=_BV(CLKPCE);
  	CLKPR=0;
	pir=0;

	DDRA |= 0xe2;
	PORTA |= 0x81;
	adc_init();
	softuart_init();
	TCCR1A=_BV(COM0B1)|_BV(WGM00);
	TCCR1B=_BV(CS00);


	softuart_turn_rx_on(); /* redundant - on by default */
	
	sei();
	
	

#if WITH_STDIO_DEMO
		stdio_demo_func();
#endif
OCR1A=0x10;
OCR1B=0xf0;

	
	for (;;) {
	           if((PINB&4)==4 ) pir=1;
	
		if ( softuart_kbhit() ) {
			c = softuart_getchar();
			//softuart_putchar( '[' );
			//softuart_putchar( c );
			//softuart_putchar( ']' );
			if(c=='g')
			  {
			    c=softuart_getchar();
			    if(c==C_ID(ID))
			      {
				softuart_putchar(3);
				softuart_putchar(2);
				send();
			pir=0;
			      }
			  }
			else if( c=='s') 
			  {
			   unsigned int pwm;
			  c=softuart_getchar();
                            if(c==C_ID(ID))
                              {
			      sprintf(line,"made it");
	//		       char line[32];
				for(cnt=0;cnt<=31;cnt++)
				 {
				  c=softuart_getchar();
				  if(c=='\n') {line[cnt]=0; break;}
				  else line[cnt]=c;
				 }
				int ret=sscanf_P(&line[0],PSTR("inTopic/pwm/"STD_ID(ID)" %d"),&pwm);
				sprintf_P(dbg,PSTR("%dpwm:%d"),ret,pwm);
				OCR1B=pwm;	
			
			  }

			 }
			}
		
		
	}
	
	return 0; /* never reached */
}
Esempio n. 19
0
void set_date(){
	clear_pixelMatrix();
	print_date(POS_DATE_SET);
	print_year();
	print_symbol(16,17, hakenSymb,108,46);
	print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() / 2 - 4, POS_DATE_SET - 10);
	update_LCD();
	int old_selectedItem = 0;
	int item = 0;
	
	while (item != 3){
		cli();
		btn_drehenc_pushed = false;
		sei();
		while(!btn_drehenc_pushed){
			if(rotary != 0){
				item += rotary;
				cli();
				rotary = 0;
				sei();
				item = item % 4;
				if(item<0){
					item += 4;
				}
			
				switch (old_selectedItem){
					case 0: for(int x = 0; x<128; x++){
						for(int y = 0; y<10; y++)
						reset_pixel(x,y);
					} break;
					case 1: for(int x = 0; x<128; x++){
						for(int y = 0; y<10; y++)
						reset_pixel(x,y);
					}break;
					case 2: for(int x = 0; x<128; x++){
						for(int y = 30; y<40; y++)
						reset_pixel(x,y);
					}break;
					case 3: for(int x = 94; x<104; x++){
						for(int y = 2+3*15+5; y<2+3*15+5+8; y++)
						reset_pixel(x,y);
					}break;
				}
				switch (item) {
					case 0: print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() / 2 - 4, POS_DATE_SET - 10); break; //-4 = halbe Länge Herz
					case 1: print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() + get_monthWidth() / 2 - 4, POS_DATE_SET - 10); break;
					case 2: print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_yearXPos() + get_yearWidth() / 2 - 4, YPOS_YEAR - 10);break;
					case 3: print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, 94, 2+3*15+5);break;
				}
				old_selectedItem = item;
				update_LCD();
			}
			goodNight();
			check_light();
		}
		cli();
		btn_drehenc_pushed = false;
		sei();
		switch (item) {
			case 0: {
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinOffenSymb, get_dateXPos() + get_dayWidth() / 2 - 4, POS_DATE_SET - 10);
				update_LCD();
				set_day();
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() / 2 - 4, POS_DATE_SET - 10);
				break;
			}
			case 1:{
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinOffenSymb, get_dateXPos() + get_dayWidth() + get_monthWidth() / 2 - 4, POS_DATE_SET - 10);
				update_LCD();
				set_month();
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb, get_dateXPos() + get_dayWidth() + get_monthWidth() / 2 - 4, POS_DATE_SET - 10);
				break;
			}
			case 2: {
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinOffenSymb,  get_yearXPos() + get_yearWidth() / 2 - 4, YPOS_YEAR - 10);
				update_LCD();
				set_year();
				print_symbol(8, HERZ_KLEIN_WIDTH, herzKleinSymb,  get_yearXPos() + get_yearWidth() / 2 - 4, YPOS_YEAR - 10);
				break;
			}
			default: break;
		}
		update_LCD();
	}
}
Esempio n. 20
0
int main(void)
{
#ifndef HOST_VERSION
	/* brake */
	BRAKE_DDR();
	BRAKE_OFF();

	/* CPLD reset on PG3 */
	DDRG |= 1<<3;
	PORTG &= ~(1<<3); /* implicit */

	/* LEDS */
	DDRJ |= 0x0c;
	DDRL = 0xc0;
	LED1_OFF();
	LED2_OFF();
	LED3_OFF();
	LED4_OFF();
#endif

	memset(&gen, 0, sizeof(gen));
	memset(&mainboard, 0, sizeof(mainboard));
	mainboard.flags = DO_ENCODERS | DO_CS | DO_RS |
		DO_POS | DO_POWER | DO_BD | DO_ERRBLOCKING;
	ballboard.lcob = I2C_COB_NONE;
	ballboard.rcob = I2C_COB_NONE;

	/* UART */
	uart_init();
	uart_register_rx_event(CMDLINE_UART, emergency);
#ifndef HOST_VERSION
#if CMDLINE_UART == 3
 	fdevopen(uart3_dev_send, uart3_dev_recv);
#elif CMDLINE_UART == 1
 	fdevopen(uart1_dev_send, uart1_dev_recv);
#endif

	/* check eeprom to avoid to run the bad program */
	if (eeprom_read_byte(EEPROM_MAGIC_ADDRESS) !=
	    EEPROM_MAGIC_MAINBOARD) {
		int c;
		sei();
		printf_P(PSTR("Bad eeprom value ('f' to force)\r\n"));
		c = uart_recv(CMDLINE_UART);
		if (c == 'f')
			eeprom_write_byte(EEPROM_MAGIC_ADDRESS, EEPROM_MAGIC_MAINBOARD);
		wait_ms(100);
		bootloader();
	}
#endif /* ! HOST_VERSION */

	/* LOGS */
	error_register_emerg(mylog);
	error_register_error(mylog);
	error_register_warning(mylog);
	error_register_notice(mylog);
	error_register_debug(mylog);

#ifndef HOST_VERSION
	/* SPI + ENCODERS */
	encoders_spi_init(); /* this will also init spi hardware */

	/* I2C */
	i2c_init(I2C_MODE_MASTER, I2C_MAINBOARD_ADDR);
	i2c_protocol_init();
	i2c_register_recv_event(i2c_recvevent);
	i2c_register_send_event(i2c_sendevent);

	/* TIMER */
	timer_init();
	timer0_register_OV_intr(main_timer_interrupt);

	/* PWM */
	PWM_NG_TIMER_16BITS_INIT(1, TIMER_16_MODE_PWM_10,
				 TIMER1_PRESCALER_DIV_1);
	PWM_NG_TIMER_16BITS_INIT(4, TIMER_16_MODE_PWM_10,
				 TIMER4_PRESCALER_DIV_1);

	PWM_NG_INIT16(&gen.pwm1_4A, 4, A, 10, PWM_NG_MODE_SIGNED,
		      &PORTD, 4);
	PWM_NG_INIT16(&gen.pwm2_4B, 4, B, 10, PWM_NG_MODE_SIGNED |
		      PWM_NG_MODE_SIGN_INVERTED, &PORTD, 5);
	PWM_NG_INIT16(&gen.pwm3_1A, 1, A, 10, PWM_NG_MODE_SIGNED,
		      &PORTD, 6);
	PWM_NG_INIT16(&gen.pwm4_1B, 1, B, 10, PWM_NG_MODE_SIGNED,
		      &PORTD, 7);


	/* servos */
	PWM_NG_TIMER_16BITS_INIT(3, TIMER_16_MODE_PWM_10,
				 TIMER1_PRESCALER_DIV_256);
	PWM_NG_INIT16(&gen.servo1, 3, C, 10, PWM_NG_MODE_NORMAL,
		      NULL, 0);
	PWM_NG_TIMER_16BITS_INIT(5, TIMER_16_MODE_PWM_10,
				 TIMER1_PRESCALER_DIV_256);
	PWM_NG_INIT16(&gen.servo2, 5, A, 10, PWM_NG_MODE_NORMAL,
		      NULL, 0);
	PWM_NG_INIT16(&gen.servo3, 5, B, 10, PWM_NG_MODE_NORMAL,
		      NULL, 0);
	PWM_NG_INIT16(&gen.servo4, 5, C, 10, PWM_NG_MODE_NORMAL,
		      NULL, 0);
	support_balls_deploy(); /* init pwm for servos */
#endif /* !HOST_VERSION */

	/* SCHEDULER */
	scheduler_init();
#ifdef HOST_VERSION
	hostsim_init();
	robotsim_init();
#endif

#ifndef HOST_VERSION
	scheduler_add_periodical_event_priority(do_led_blink, NULL,
						100000L / SCHEDULER_UNIT,
						LED_PRIO);
#endif /* !HOST_VERSION */

	/* all cs management */
	microb_cs_init();

	/* TIME */
	time_init(TIME_PRIO);

	/* sensors, will also init hardware adc */
	sensor_init();

#ifndef HOST_VERSION
	/* start i2c slave polling */
	scheduler_add_periodical_event_priority(i2c_poll_slaves, NULL,
						8000L / SCHEDULER_UNIT, I2C_POLL_PRIO);
#endif /* !HOST_VERSION */

	/* strat */
 	gen.logs[0] = E_USER_STRAT;
 	gen.log_level = 5;

	/* strat-related event */
	scheduler_add_periodical_event_priority(strat_event, NULL,
						25000L / SCHEDULER_UNIT,
						STRAT_PRIO);

#ifndef HOST_VERSION
	/* eeprom time monitor */
	scheduler_add_periodical_event_priority(do_time_monitor, NULL,
						1000000L / SCHEDULER_UNIT,
						EEPROM_TIME_PRIO);
#endif /* !HOST_VERSION */

	sei();

	strat_db_init();

	printf_P(PSTR("\r\n"));
	printf_P(PSTR("Respect et robustesse.\r\n"));
#ifndef HOST_VERSION
	{
		uint16_t seconds;
		seconds = eeprom_read_word(EEPROM_TIME_ADDRESS);
		printf_P(PSTR("Running since %d mn %d\r\n"), seconds/60, seconds%60);
	}
#endif

#ifdef HOST_VERSION
	strat_reset_pos(400, COLOR_Y(400), COLOR_A(-90));
#endif

	cmdline_interact();

	return 0;
}
Esempio n. 21
0
int main(void)
{
	uint8_t i1, i2, i3, i4, i5;
	int16_t x, y, z;
	uint8_t rx_count, rx_length, rx_type, rx_timeout, rx_starve;
	uint8_t addr;
	uint8_t rx[80];	// usb input buffer
	uint8_t d[80];
	uint8_t awake;
	uint8_t found_sub[4] = {0,0,0,0};
	uint8_t offset_x[4] = {0,8,0,8};
	uint8_t offset_y[4] = {0,0,8,8};
	uint8_t lookup_sub[2][2] = { {100,102} , {104,106} };
	uint8_t size_x, size_y;
	
	char id[32];
	
	uint8_t output_buffer[OUTPUT_BUFFER_LENGTH];
	uint8_t output_write;
	uint8_t output_read;
	uint8_t input_buffer[INPUT_BUFFER_LENGTH];

	i1 = i2 = i3 = i4 = 0;
	rx_count = rx_type = rx_timeout = 0;
	rx_length = 1;
	input_check = 0;
	awake = 1;

	output_read = output_write = 0;

	DDRB = 0;
	DDRC = C3_WR | C2_RD;
	DDRD = 0;

	TCCR0A = 0;
	TCCR0B = (1<<CS02) | (1<<CS00);
	TIMSK0 = (1 << OCIE0A);
	OCR0A = GATHER_RATE;

	// TCCR1A = 0;
	// TCCR1B = (1<<CS10) | (1<<CS12);
	// TIMSK1 = (1<<TOIE1);

	sei();

	twi_init();
	//twi_setAddress(0);
	// twi_attachSlaveRxEvent(processRx);

	//// scan i2c bus //////////////////////////////////////////////////////
	
	// for(i1=0;i1<4;i1++) {
	// 	addr = 100 + (i1*2);
	// 	d[0] = _LED_ALL1;
	// 	twi_writeTo(addr, d, 1, 1);
	// }
	
	/*
	
	_delay_ms(50);	

	for(i1=0;i1<4;i1++) {
		addr = 100 + (i1*2);
		d[0] = _QUERY;
		i2 = twi_writeTo(addr, d, 1, 1);
		if(!i2) {
			found_sub[i1] = addr;
			// lookup_sub[offset_x[i1]>>8][offset_y[i1>>8]] = addr;
			//d[0] = _LED_ALL0;
			//twi_writeTo(addr, d, 1, 1);
		}
	}
	
	*/
	
	for(i1=0;i1<32;i1++) id[i1]=0;

	i1 = 0;
	for(i2=0;i2<4;i2++) {
		if(found_sub[i2]) i1++;
	}
	
	size_x = 0; size_y = 0;
	
	if(i1==0) {
		strcpy(id,"monome");
	} else if(i1==1) {
		size_x = 8; size_y = 8;
		strcpy(id,"monome 64");
	} else if(i1==2) {
		size_x = 16; size_y = 8;
		strcpy(id,"monome 128");
	} else if(i1==4) {
		size_x = 16; size_y = 16;
		strcpy(id,"monome 256");
	}


	// tilt setup
	
	addr = 0x53;

	d[0] = 0x2D; 	// write to power ctl
	d[1] = (1<<3);	// set measure bit on d3

	twi_writeTo(addr, d, 2, 1);
	
	
	/*

	// startup animation
	
	addr = 100;
	
	d[0] = _LED_COL;
	d[1] = 0;
	d[2] = 6;
	twi_writeTo(addr, d, 3, 1);
	_delay_ms(50);

	d[0] = _LED_COL;	
	d[2] = 9;
	twi_writeTo(addr, d, 3, 1);
	d[1] = 1;
	d[2] = 6;
	twi_writeTo(addr, d, 3, 1);
	d[0] = _LED_INT;
	d[1] = 12;
	twi_writeTo(addr, d, 2, 1);
	_delay_ms(50);

	d[0] = _LED_COL;
	d[1] = 0;
	d[2] = 16;
	twi_writeTo(addr, d, 3, 1);
	d[1] = 1;
	d[2] = 9;
	twi_writeTo(addr, d, 3, 1);
	d[1] = 2;
	d[2] = 6;
	twi_writeTo(addr, d, 3, 1);
	d[0] = _LED_INT;
	d[1] = 7;
	twi_writeTo(addr, d, 2, 1);
	_delay_ms(50);

	d[0] = _LED_COL;
	d[1] = 1;
	d[2] = 16;
	twi_writeTo(addr, d, 3, 1);
	d[1] = 2;
	d[2] = 9;
	twi_writeTo(addr, d, 3, 1);
	d[1] = 3;
	d[2] = 6;
	twi_writeTo(addr, d, 3, 1);
	d[0] = _LED_INT;
	d[1] = 2;
	twi_writeTo(addr, d, 2, 1);
	_delay_ms(50);
	
	d[0] = _LED_ALL0;
	twi_writeTo(addr, d, 1, 1);
	d[0] = _LED_INT;
	d[1] = 15;
	twi_writeTo(addr, d, 2, 1);

	*/


	//// main loop /////////////////////////////////////////////////////////
	while(1)
	{
		i1 = (PINB & B0_PWREN);
		if(i1 != awake) {
			if(i1) {
				addr = 100;
				d[0] = _SLEEP;
				twi_writeTo(addr, d, 1, 1);
			} else {
				addr = 100;
				d[0] = _WAKE;
				twi_writeTo(addr, d, 1, 1);
			}

			awake = i1;
		}

		// ====================== check/read incoming serial
		PORTD = 0;                  // setup PORTD for input
		DDRD = 0;                   // input w/ tristate

		if(rx_timeout > 40 ) {
			rx_count = 0;
		}
		else rx_timeout++;

		rx_starve = 0;

		while((PINC & C1_RXF) == 0 && rx_starve < RX_STARVE_THRESH) {
			rx_starve++;			// make sure we process keypad data...
									// if we process more input bytes than RX_STARVE
									// we'll jump to sending out waiting keypad bytes
									// and then continue
			PORTC &= ~(C2_RD);
			_delay_us(1);			// wait for valid data
			rx[rx_count] = PIND;
			PORTC |= C2_RD;

			if(rx_count == 0) {		// get packet length if reading first byte
				rx_type = rx[0];
				rx_length = usb_packet_length[rx_type];
				rx_count++;
				rx_timeout = 0;
			}
			else rx_count++;

			if(rx_count == rx_length) {
				rx_count = 0;
				
				if(rx_type == _SYS_QUERY) {
					i1 = 0;
					for(i2=0;i2<4;i2++) {
						if(found_sub[i2]) i1++;
					}
					
					output_buffer[output_write] = _SYS_QUERY_RESPONSE;
					output_write++;
					output_buffer[output_write] = 1;
					output_write++;
					output_buffer[output_write] = i1;
					output_write++;
					
					output_buffer[output_write] = _SYS_QUERY_RESPONSE;
					output_write++;
					output_buffer[output_write] = 2;
					output_write++;
					output_buffer[output_write] = i1;
					output_write++;
				}
				else if(rx_type == _SYS_QUERY_ID) {
					output_buffer[output_write] = _SYS_ID;
					output_write++;
					
					for(i1=0;i1<32;i1++) {
						output_buffer[output_write] = id[i1];
						output_write++;
					}
				}
				else if(rx_type == _SYS_WRITE_ID) {
				}
				else if(rx_type == _SYS_GET_GRID_OFFSET) {
				}
				else if(rx_type == _SYS_SET_GRID_OFFSET) {
				}
				else if(rx_type == _SYS_GET_GRID_SIZE) {
					output_buffer[output_write] = _SYS_REPORT_GRID_SIZE;
					output_write++;
					output_buffer[output_write] = size_x;
					output_write++;
					output_buffer[output_write] = size_y;
					output_write++;
				}
				else if(rx_type == _SYS_SET_GRID_SIZE) {
				}
				else if(rx_type == _SYS_SCAN_ADDR) {
				}
				else if(rx_type == _SYS_SET_ADDR) {
				}
				else if(rx_type == _SYS_QUERY_VERSION) {
					output_buffer[output_write] = _SYS_REPORT_VERSION;
					output_write++;
					output_buffer[output_write] = FIRMWARE_VERSION;
					output_write++;
				}
				
				else if(rx_type == _LED_SET0) {
					// _LED_SET0 //////////////////////////////////////////////
					i1 = rx[1] >> 3;
					i2 = rx[2] >> 3;
					i3 = rx[1] & 0x07;
					i4 = rx[2] & 0x07;
					
					addr = lookup_sub[i2][i1];

					d[0] = _LED_SET0;
					d[1] = (i3 << 4) + i4;
					twi_writeTo(addr, d, 2, 1);
				}
				else if(rx_type == _LED_SET1) {
					// _LED_SET1 //////////////////////////////////////////////
					i1 = rx[1] >> 3;
					i2 = rx[2] >> 3;
					i3 = rx[1] & 0x07;
					i4 = rx[2] & 0x07;
					
					addr = lookup_sub[i2][i1];

					d[0] = _LED_SET1;
					d[1] = (i3 << 4) + i4;					
					twi_writeTo(addr, d, 2, 1);
				}
Esempio n. 22
0
void processor_idle() {
	sleep_enable();
	set_sleep_mode(SLEEP_MODE_IDLE);
	sei(); // Just in case, if this is called form an ISR
	sleep_cpu();
}
Esempio n. 23
0
int main( void )
{
  uint32_t val = 0;
  char textbuf [ (2*16) + 1 ]; // lcd

  /* setup
   */

  // LCD
  lcd_init();

  // Timer: enable a timer so we can measure passage of time
  //
  // Given: 20MHz clock
  // --> if we want resolution of ms (1/1000th second) .. actually, we want us (1/10th of a ms) so we can measure partial ms
  // --> and we have 1/20000000 clock resolution
  // -----> 2000 ticks will get us there (20,000 will get us ms)
  //
  // Goal: Use CTC interupt mode (CTC -> Clear on Timer Compare)
  // So a compare matches, it clears to zero and triggers interupt
  TCCR1B |= (1 << WGM12); // Configure timer 1 for CTC mode 
  OCR1A = 2000; // number to compare against
  TIMSK1 |= (1 << OCIE1A); // Enable CTC interrupt 
  TCCR1B |= (1 << CS10); // Set up timer , with no prescaler (works at full MHz of clock)

  // Receiver setup - set up pin change interupt
#if 1
  EICRA &= ~ ( (1 << ISC01) | (1 << ISC01) ); // clear ISC01+ISC00
  EICRA |= ( (1 << ISC00) ); // 00 set and 01 unset means any edge will make event
  PCMSK0 |= ( (1 << PCINT0) | (1 << PCINT1) ); // Pins to monitor: PA0 and PA1
  PCICR |= (1 << PCIE0); // PA is monitored
#endif

  // Serial - setup (for motor controller)
  mc_setup();

  // TWI - set up
  unsigned char twibuf [ TWI_BUFFER_SIZE ];
  unsigned char TWI_slaveAddress; 
  TWI_slaveAddress = 0x10; // our TWI address
  TWI_Slave_Initialise( (unsigned char)((TWI_slaveAddress<<TWI_ADR_BITS) | (TRUE<<TWI_GEN_BIT) )); // Initialise TWI module as slave; include addr+general
  unsigned char twi_heartbeat_counter = 0;

  // setup done - kick up interupts
  sei();

  // lets burn the first couple of seconds, so the receiver can get some signal
  // before we start blasting stuff into the motor controllers
  {
    unsigned int start_sec = g_time_s;
    while ( g_time_s - start_sec < 3 ) {
      nop();
    }
  }

  // Start the TWI transceiver to enable reseption of the first command from the TWI Master.
  TWI_Start_Transceiver();

#if 1 // timer test .. show per-second counter update on lcd
  if ( 1 ) {
    unsigned int last_sec = g_time_s;
    unsigned int last_us = _g_time_us_tick;

    unsigned char sent_l = 0, sent_r = 0;
    char message [ 17 ];

    while(1) {
      unsigned int ch1 = g_ch1_duration;
      unsigned int ch2 = g_ch2_duration;

      // 100ms has past?
      if ( _g_time_us_tick - last_us > 1000 ) {

        if ( g_control_twi ) {
          // we're on TWI control, but if nothing comes in.. revert back to RC
          if ( g_time_s - g_control_last_s > 2 ) {
            g_control_twi = 0;
          }
        } else {
          mc_set_by_receiver ( ch1, ch2, &sent_l, &sent_r, message );
        }

        last_us = _g_time_us_tick;
      } // .1sec tick

      // one second has past? update lcd
      if ( g_time_s != last_sec ) {
        //sprintf ( textbuf, "recv %2d %2d     ", g_ch1_duration, g_ch2_duration );
        sprintf ( textbuf, "m %2d %2d th %2d %2d #", sent_l, sent_r, ch1, ch2 );
        lcd_xy ( 0, 0 );
        lcd_puts( textbuf ); // display number right adjusted

        //sprintf ( textbuf, "t%2d #", g_time_s );
        sprintf ( textbuf, "t%2d # %s", g_time_s, message );
        lcd_xy ( 0, 1 );
        lcd_puts( textbuf ); // display number right adjusted

        last_sec = g_time_s;
      } // 1 sec tick

      // TWI/I2C stuff, talk to r-pi
      //

      // Check if the TWI Transceiver has completed an operation.
      if ( ! TWI_Transceiver_Busy() ) {

        // Check if the last operation was successful
        if ( TWI_statusReg.lastTransOK ) {

          // Check if the last operation was a reception
          if ( TWI_statusReg.RxDataInBuf ) {
            TWI_Get_Data_From_Transceiver ( twibuf, 3 );

            // Check if the last operation was a reception as General Call        
            if ( TWI_statusReg.genAddressCall ) {
              // don't care

            } else { // Ends up here if the last operation was a reception as Slave Address Match   
              // Example of how to interpret a command and respond.

#if 0            
              // TWI_CMD_MASTER_WRITE stores the data to PORTB
              if (twibuf[0] == TWI_CMD_MASTER_WRITE) {
                PORTB = twibuf[1];                            
              }
#endif

              // TWI_CMD_MASTER_READ prepares the data from PINB in the transceiver buffer for the TWI master to fetch.
              if ( twibuf[0] == tc_heartbeat ) {
                twibuf [ 0 ] = 1;
                twibuf [ 1 ] = twi_heartbeat_counter++;
                TWI_Start_Transceiver_With_Data ( twibuf, TWI_BUFFER_SIZE );

              } else if ( twibuf[0] == tc_gethello ) {
                sprintf ( twibuf + 1, "hello" );
                twibuf [ 0 ] = strlen ( twibuf + 1 ); // len
                TWI_Start_Transceiver_With_Data ( twibuf, TWI_BUFFER_SIZE );

              } else if ( twibuf[0] == tc_setmotors ) {
                g_control_last_s = g_time_s;
                mc_speed ( mcm_left, twibuf [ 1 ] );
                mc_speed ( mcm_right, twibuf [ 2 ] );

              } else if ( twibuf[0] == tc_takeover ) {
                g_control_last_s = g_time_s;
                g_control_twi = 1;

              } else if ( twibuf[0] == tc_release ) {
                g_control_twi = 0;

              } else {
                twibuf [ 0 ] = 1;
                twibuf [ 1 ] = 0xde;
                twibuf [ 2 ] = 0xad;
                twibuf [ 3 ] = 0xbe;
                twibuf [ 4 ] = 0xef;
                TWI_Start_Transceiver_With_Data ( twibuf, TWI_BUFFER_SIZE );
              }

            }

          } else { // Ends up here if the last operation was a transmission  
            // don't care
          }

          // Check if the TWI Transceiver has already been started.
          // If not then restart it to prepare it for new receptions.             
          if ( ! TWI_Transceiver_Busy() ) {
            TWI_Start_Transceiver();
          }

        } else { // Ends up here if the last operation completed unsuccessfully
          TWI_Act_On_Failure_In_Last_Transmission ( TWI_Get_State_Info() );
        } // success/fail

      } // TWI busy?

      // spin
      _delay_ms ( 20 );

    } // while forever

  } // if 1
#endif

  /* churn forever
   */
  while(1);

  return ( 0 );
}
Esempio n. 24
0
/**
 *   \brief This is main...
*/
int
main(void)
{
    lcd_init();

    key_init();

    uart_init();

    eeprom_init();

    temp_init();

    timer_init();

    sei();

    lcd_symbol_set(LCD_SYMBOL_RAVEN);
    lcd_symbol_set(LCD_SYMBOL_IP);

    /* Start with main menu */
    read_menu(0);
    /* and draw it */
    lcd_puts_P(menu.text);

    timer_start();

    for (;;){
        /* Make sure interrupts are always on */
        sei();

        /* The one second timer has fired. */
        if(timer_flag){
            timer_flag = false;
            /* Check if main menu needs toggled. */
            check_main_menu();
            /* Update LCD with temp data. */
            if(temp_flag){
                menu_display_temp();
            }
            /* Auto send temp data to 1284p. */
            if(auto_temp){
                menu_send_temp();
            }
            /* If ping mode, send 4 ping requests and then stop. */
            if(ping_mode){
                if((PING_ATTEMPTS == count) && !timeout_flag){
                    count = 0;
                    timeout_count = 0;
                    menu_stop_ping();
                }
                else if(timeout_flag){
                    timeout_flag = false;
                    timeout_count++;
                    /* Display timeout message if all PING_ATTEMPTS were not successful. */
                    if(PING_ATTEMPTS == timeout_count){
                        lcd_puts_P(PSTR("PINGS FAILED"));
                    }
                }
                else{
                    count = menu_send_ping();
                }
            }
        }

        /* Check for button press and deal with it */
        if (is_button()){
            /* Dispatch the button pressed */
            switch (get_button()){
                case KEY_UP:
                    read_menu(menu.up);
                    lcd_puts_P(menu.text);
                    break;
                case KEY_DOWN:
                    read_menu(menu.down);
                    lcd_puts_P(menu.text);
                    break;
                case KEY_LEFT:
                    read_menu(menu.left);
                    lcd_puts_P(menu.text);
                    break;
                case KEY_RIGHT:
                    /*
                     * Check to see if we should show another menu or
                     * run a function
                     */
                    if (!menu.enter_func){
                        /* Just another menu to display */
                        read_menu(menu.right);
                        lcd_puts_P(menu.text);
                        break;
                    }
                    /* Drop through here */
                case KEY_ENTER:
                    /* Call the menu function on right or enter buttons */
                    if (menu.enter_func){
                        menu.enter_func(menu.state);
                        if (menu.state){
                            /*
                             * We just called a selection menu (not a test),
                             * so re-display the text for this menu level
                             */
                            lcd_puts_P(menu.text);
                        }
                        /* After enter key, check the right button menu and display. */
                        read_menu(menu.right);
                        lcd_puts_P(menu.text);
                    }
                    break;
                default:
                    break;
            }
            /* After button press, check for menus... */
            check_menu();
        }
        /* Process any progress frames */
        uart_serial_rcv_frame(false);
    } /* end for(). */
} /* end main(). */
Esempio n. 25
0
void main(void)
{

//adc_init();//initialize the LDR input

DDRB |= _BV(PB0);
DDRB |= _BV(PB1);
DDRB |= _BV(PB2);
//DDRB |= _BV(PB4);
DDRB |= _BV(PB3);

//CONTROL_DDR = 0xFF;  // Set the Control DDR (i.e. DDRB) to be all outputs

int i;  // initialize for loop variables

//int j;  // Loop variable for OPTION 2 - If you use OPTION 1 you should comment this out or you will get a warning upon compiling

//reset_SR();  // Toggle the Reset Pin on the 595 to clear out SR

Set_Enable;  // Set the Output Enable Pin on the 595 (PB1 in this case) LOW to allow data to show on the outputs upon being latched

 /* interrup setup */
  // call ISR(TIM0_COMPA_vect) every 103us (for 9600 bauds)
  // set CTC mode : clear timer on comapre match
  // -> reset TCNTO (timer 0) when TCNTO == OCR0A
  sbi(TCCR0A, WGM01);
  // prescaler : clk/8 (1 tic = 1us for 8MHz clock)
  sbi(TCCR0B, CS01);
  // compare register A at 103 us
  OCR0A = 103;
  // interrupt on compare match OCROA == TCNT0
  sbi(TIMSK, OCIE0A);
  // Enable global interrupts
  sei();


old_millis = millis() + 500;

int numberOfTimes = rng(2, 5);
for (int j=0; j<numberOfTimes; j++) 
	myCircleLoop();

while(1)  // infinite loop
{

//idea is to have flashes now and then, and then now and the the whole circle
 
//int an4 = adc_read(2);

if (   old_millis < millis())
 {
		//myCircleLoop();
		if ( dir == 0 ) dir = 1; else dir = 0;
		old_millis = millis() + 500*rng(1, 5);



		int myChoice = rng(0, 15);

		if ( myChoice == 0 ) myCircleLoop();
		if ( (myChoice > 0) && (myChoice < 8) ) {
			int numberOfTimes = rng(2, 10);
			for (int j=0; j<numberOfTimes; j++) {
				resetOutputArray(myChoice);
				doLoopThing(4);
				for (int j2=40; j2<(40 + rng(0,10)); j2++) 
					delay(10);
				resetOutputArray(10);//all zero's
				doLoopThing(4);

				for (int j2=20; j2<(20 + rng(0,10)); j2++) 
					delay(10);
			}
		}
		resetOutputArray(10);//all zero's

}




//oldVal = an4;


}  // end while





}	// end main
Esempio n. 26
0
int
main (void)
{
#ifdef BOOTLOADER_SUPPORT
  _IVREG = _BV (IVCE);    /* prepare ivec change */
  _IVREG = _BV (IVSEL);   /* change ivec to bootloader */
#endif

  /* Default DDR Config */
#if IO_HARD_PORTS >= 4 && DDR_MASK_A != 0
  DDRA = DDR_MASK_A;
#endif
#if DDR_MASK_B != 0
  DDRB = DDR_MASK_B;
#endif
#if DDR_MASK_C != 0
  DDRC = DDR_MASK_C;
#endif
#if DDR_MASK_D != 0
  DDRD = DDR_MASK_D;
#endif
#if IO_HARD_PORTS >= 6
#if DDR_MASK_E != 0
  DDRE = DDR_MASK_E;
#endif
#if DDR_MASK_F != 0
  DDRF = DDR_MASK_F;
#endif
#endif
#if IO_HARD_PORTS >= 7
#if DDR_MASK_G != 0
  DDRG = DDR_MASK_G;
#endif
#endif


#ifdef STATUSLED_POWER_SUPPORT
  PIN_SET(STATUSLED_POWER);
#endif

  //FIXME: zum ethersex meta system hinzufügen, aber vor allem anderem initalisieren
  debug_init();
  debug_printf("ethersex " VERSION_STRING_LONG " (Debug mode)\n");

#ifdef DEBUG_RESET_REASON
  if (bit_is_set (mcusr_mirror, BORF))
    debug_printf("reset: Brown-out\n");
  else if (bit_is_set (mcusr_mirror, PORF))
    debug_printf("reset: Power on\n");
  else if (bit_is_set (mcusr_mirror, WDRF))
    debug_printf("reset: Watchdog\n");
  else if (bit_is_set (mcusr_mirror, EXTRF))
    debug_printf("reset: Extern\n");
  else
    debug_printf("reset: Unknown\n");
#endif

#ifdef BOOTLOADER_SUPPORT
  /* disable interrupts */
  cli ();
  wdt_disable();
#endif //BOOTLOADER_SUPPORT
  /* enable interrupts */
  sei ();

#ifdef USE_WATCHDOG
  debug_printf("enabling watchdog\n");
#ifdef DEBUG
  /* for debugging, test reset cause and jump to bootloader */
  if (MCU_STATUS_REGISTER & _BV (WDRF))
  {
    debug_printf("bootloader...\n");
    jump_to_bootloader();
  }
#endif
  /* set watchdog to 2 seconds */
  wdt_enable(WDTO_2S);
  wdt_kick();
#else //USE_WATCHDOG
  debug_printf("disabling watchdog\n");
  wdt_disable();
#endif //USE_WATCHDOG

#if defined(RFM12_SUPPORT) || defined(ENC28J60_SUPPORT) \
	|| defined(DATAFLASH_SUPPORT)
  spi_init();
#endif

  ethersex_meta_init();

  /* must be called AFTER all other initialization */
#ifdef PORTIO_SUPPORT
  portio_init();
#elif defined(NAMED_PIN_SUPPORT)
  np_simple_init();
#endif

#ifdef ENC28J60_SUPPORT
  debug_printf ("enc28j60 revision 0x%x\n",
  read_control_register (REG_EREVID));
  debug_printf ("mac: %02x:%02x:%02x:%02x:%02x:%02x\n",
	  uip_ethaddr.addr[0], uip_ethaddr.addr[1], uip_ethaddr.addr[2],
	  uip_ethaddr.addr[3], uip_ethaddr.addr[4], uip_ethaddr.addr[5]);
#endif

#ifdef STATUSLED_BOOTED_SUPPORT
  PIN_SET(STATUSLED_BOOTED);
#endif

  ethersex_meta_startup();
  /* main loop */
  while (1)
  {
    wdt_kick();
    ethersex_meta_mainloop();

#ifdef SD_READER_SUPPORT
    if (sd_active_partition == NULL)
    {
      if (!sd_try_init())
      {
#ifdef VFS_SD_SUPPORT
        vfs_sd_try_open_rootnode();
#endif
      }
      wdt_kick();
    }
#endif

#ifdef BOOTLOADER_JUMP
    if (status.request_bootloader)
    {
#ifdef MBR_SUPPORT
      mbr_config.bootloader = 1;
      write_mbr();
#endif
#ifdef CLOCK_CRYSTAL_SUPPORT
      TC2_INT_OVERFLOW_OFF;
#endif
#ifdef DCF77_SUPPORT
      ACSR &= ~_BV (ACIE);
#endif
      cli();
      jump_to_bootloader();
    }
#endif

#ifndef TEENSY_SUPPORT
    if (status.request_wdreset)
    {
      cli();
      wdt_enable(WDTO_15MS);
      for (;;);
    }
#endif

    if (status.request_reset)
    {
      cli();
      void (*reset) (void) = NULL;
      reset();
    }
  }
}
Esempio n. 27
0
int main (void)
{	
	int tmp,i,res;
	CLKPR = 0x80;  CLKPR = 0x00;  // Clock prescaler Reset

/*-----------------------------------------------------------------*
 *------------------------- Gear buttoms setup---------------------*
 *-----------------------------------------------------------------*/
	DDRC&=~(1<<PC7); // Neutral
	PORTC |= (1<<PC7); // Neutral pull-up
	DDRE&=~(1<<PE6); // Knap1 
	DDRE&=~(1<<PE7); // Knap2

	/* Buttoms interrupt */
	EICRB |= (1<<ISC71|1<<ISC70|1<<ISC61|1<<ISC60); /* Rising edge */
	EIMSK |= (1<<INT7 | 1<<INT6);


	uint8_t test_rx[8];

	int8_t data;
	char streng[10];

	// Recieve buffer
	st_cmd_t msg;

//  Init CAN, UART, I/O
	init();
	uartinit();
	sendtekst("UART initialized\n\r");
	TWI_init();
	sendtekst("TWI initialized\n\r");

	sei();		/* Interrupt enable */
	sendtekst("Interrupt enabled\n\r");
/*-----------------------------------------------------------------*
 *----------------------------Display setup -----------------------*
 *-----------------------------------------------------------------*/

	/* Set blink rates */
	set_blink_rate(LED0_7_ADDR, LED_BLINK1, 20, 100);
	set_blink_rate(LED0_7_ADDR, LED_BLINK2, 0, RPM_LED_DUTYCYCLE*2.56);

	set_blink_rate(LED8_15_ADDR, LED_BLINK1, (1.0/RPM16_RATE)*252, RPM16_DUTYCYCLE*2.56);
	set_blink_rate(LED8_15_ADDR, LED_BLINK2, 0, RPM_LED_DUTYCYCLE*2.56);

	set_blink_rate(SEG_ADDR, LED_BLINK1, 20, 100);
	set_blink_rate(SEG_ADDR, LED_BLINK2, 0, SEG_DUTYCYCLE*2.56);

	set_blink_rate(LED_BUTTONS_ADDR, LED_BLINK1, 20, 100);
	set_blink_rate(LED_BUTTONS_ADDR, LED_BLINK2, 0, SEG_DUTYCYCLE*2.56);


/*-----------------------------------------------------------------*
 *----------------------------CAN interrupt setup -----------------*
 *-----------------------------------------------------------------*/
	Can_sei();		/* Enable general can interrupt */
	Can_set_tx_int();	/* Enable can tx interrupt */
	Can_set_rx_int();	/* Enable can rx interrupt */

	/*
	 *	Kode til hurtig test af can 
	 */
	sendtekst("Config 3 mailboxes for rpm_msgid...\n\r");
	msg.id.std = rpm_msgid;
	msg.dlc = 8;
	res = can_config_rx_mailbox(&msg, 3);
	if (res == CAN_CMD_ACCEPTED) {
		sendtekst("SUCCESS\n\r");
	} else {
		sendtekst("FAIL\n\r");
	}	
    	// --- Init variables

	/* Init user led 0 & 1 */
	DDRB |= (1<<PB6 | 1<<PB5);
	PORTB |= (1<<PB6 | 1<<PB5);

	sendtekst("Beep\n\r");
	display_test();
    
    params.GearEst = 0;

	char dataout[] = {gear,0};

	while (1) {
		_delay_ms(20);

		/* Display selected parameter */
		if (mode == RPM_MODE) {		
			set_rpm(params.rpm, LED_ON);
		} else if (mode == VOLTAGE_MODE) {
			set_voltage(params.batteryV, LED_ON);
		} else if (mode == WATER_TEMP_MODE) {
			set_water_temp(params.waterTemp, LED_ON);
		}

		// Geat buttons to CAN
		dataout[1] = 0;
		/* Format buttom states for sending */ 
		dataout[1] |= (params.GearButDown*GEARDOWNBUT | 
					GEARUPBUT*params.GearButUp | 
					params.GearButNeutral*GEARNEUBUT);

		/* Send buttom states */
		if(dataout[1] != 0) {
			// Hack, sender gearskiftesignal et par gange, sådan at det går igennem
			// Symptombehandling, sygdommen skal kureres...
			if (dataout[1] & (GEARDOWNBUT) == GEARDOWNBUT)
				indi_leds_state |= (LED_BLINK2<<LED_BUTTON_1);
			if (dataout[1] & (GEARUPBUT) == GEARUPBUT)
				indi_leds_state |= (LED_BLINK2<<LED_BUTTON_1);
		

			set_leds(LED_BUTTONS_ADDR, indi_leds_state);
			for(j=0;j<1;j++){
				can_send_non_blocking(gear_msgid, dataout, 2);
				_delay_ms(5);
			}
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_2);
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_1);
			set_leds(LED_BUTTONS_ADDR, indi_leds_state);

		}
		/* Clear buttom states */
		params.GearButDown = 0;
		params.GearButUp = 0;
		params.GearButNeutral = 0;

		/* Display bottons code */
		buttons_state = get_buttons(LED_BUTTONS_ADDR) & (BUTTON1 | BUTTON2);
		if (buttons_state == 2) {
			indi_leds_state |= (LED_BLINK2<<LED_BUTTON_1);
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_2);
			mode = VOLTAGE_MODE;
		} else if (buttons_state == 1) {
			indi_leds_state |= (LED_BLINK2<<LED_BUTTON_2);
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_1);
			mode = WATER_TEMP_MODE;
		} else if (buttons_state == 0) {
			indi_leds_state |= (LED_BLINK2<<LED_BUTTON_1 | LED_BLINK2<<LED_BUTTON_2);
		} else {
			indi_leds_state &= ~(LED_BLINK2<<LED_BUTTON_1 | LED_BLINK2<<LED_BUTTON_2);
			mode = RPM_MODE;
		}

		/* Indicator for water temp */
		if (params.waterTemp <= WATER_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI1);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI4);
		} else if (params.waterTemp > WATER_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI4);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI1);
		}

		/* Indicator for batt ok */
		if (params.batteryV <= VOLTAGE_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI2);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI5);
		} else if (params.batteryV > VOLTAGE_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI5);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI2);
		}
		
		/* Indicator for oil pressure ok */
		if (params.oilPressure <= OILPRESS_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI3);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI6);
		} else if (params.oilPressure > OILPRESS_OK) {
			indi_leds_state |= (LED_BLINK2<<LED_INDI6);
			indi_leds_state &= ~(LED_BLINK2<<LED_INDI3);
		}

		/* Indicator for Gear */
		if (params.GearNeutral < 0) {
			SEG_N(LED_ON);
		} else {
			if (params.GearEst > 6) {
				SEG_OFF();
			} else {
				switch (params.GearEst) {
                    case 0:
						SEG_N(LED_ON);
						break;
					case 1:
						SEG_1(LED_ON);
						break;
					case 2:
						SEG_2(LED_ON);
						break;
					case 3:
						SEG_3(LED_ON);
						break;
					case 4:
						SEG_4(LED_ON);
						break;
					case 5:
						SEG_5(LED_ON);
						break;
					case 6:
						SEG_6(LED_ON);
						break;
					default:
						break;

				}
			}
		}


/*		if (params.GearNeutral == 0) {
			SEG_OFF();
		} else if (params.GearNeutral > 0) {
			SEG_N(LED_BLINK2);
		}
*/

		/* Set indicator leds */
		set_leds(LED_BUTTONS_ADDR, indi_leds_state);
			
/*		itoa(params.batteryV, streng, 10);*/
/*		sendtekst(streng);*/
/*		sendtekst("\n\r");		*/
		PORTB ^= (1<<PB6);
	}
	return 0;
}
Esempio n. 28
0
int main(void){

        
        uint16_t plen;
        uint16_t dat_p;
        //uint8_t cmd_pos=0;
        int8_t cmd;
        //uint8_t payloadlen=0;
        //char str[20];
        //char cmdval;

        //char req[16];
        //char i;
        
        DATA_DAIKIN daikin;

        // set the clock speed to "no pre-scaler" (8MHz with internal osc or 
        // full external speed)
        // set the clock prescaler. First write CLKPCE to enable setting 
        // of clock the next four instructions.
        // Note that the CKDIV8 Fuse determines the initial
        // value of the CKKPS bits.
        CLKPR=(1<<CLKPCE); // change enable
        CLKPR=0; // "no pre-scaler"
        _delay_loop_1(0); // 60us

        /*initialize enc28j60*/
        enc28j60Init(mymac);
        //enc28j60clkout(2); // change clkout from 6.25MHz to 12.5MHz
        _delay_loop_1(0); // 60us
        
        /* Magjack leds configuration, see enc28j60 datasheet, page 11 */
        // LEDB=yellow LEDA=green
        //
        // 0x476 is PHLCON LEDA=links status, LEDB=receive/transmit
        // enc28j60PhyWrite(PHLCON,0b0000 0100 0111 01 10);
        enc28j60PhyWrite(PHLCON,0x476);
        
        //DDRB|= (1<<DDB1); // enable PB1, LED as output 
        // the transistor on PD7:
        //DDRD|= (1<<DDD7);
        //PORTD &= ~(1<<PORTD7);// transistor off

        //PORTB = 0xff;
        //DDRB = 0xff;

        init_power_settings();
        uart_init();
        init_ir();
        init_airController(&daikin);
        sei();

        xfunc_out = (void (*)(char))uart_put;
        xputs(PSTR("AVR-Ethernet test monitor\n"));
        xprintf(PSTR("ENC28J60 Rev.%d\n"), enc28j60getrev());
xprintf(PSTR("PRR=%02X\n"),PRR);
        //init the web server ethernet/ip layer:
        init_ip_arp_udp_tcp(mymac,myip,MYWWWPORT);

        while(1){

                // handle ping and wait for a tcp packet
                plen=enc28j60PacketReceive(BUFFER_SIZE, buf);
                buf[BUFFER_SIZE]='\0';
                dat_p=packetloop_icmp_tcp(buf,plen);

                if(dat_p==0){
                        // check if udp otherwise continue
                        goto UDP;
                }
                // send data everytime we get a http request        
                xprintf(PSTR("get http request\n"));


                if (strncmp("GET ",(char *)&(buf[dat_p]),4)!=0){
                        xprintf(PSTR("'GET \n'"));
                        // head, post and other methods:
                        //
                        // for possible status codes see:
                        // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
                        plen=http200ok();
                        plen=fill_tcp_data_p(buf,plen,PSTR("<h1>200 OK</h1>"));
                        goto SENDTCP;
                }
                if (strncmp("/ ",(char *)&(buf[dat_p+4]),2)==0){
                        plen=http200ok();
                        plen=fill_tcp_data_p(buf,plen,PSTR("<p>Usage: http://host_or_ip/pc or m</p>\n"));
                        goto SENDTCP;
                }
                if ((strncmp("/pc ",(char *)&(buf[dat_p+4]),4)==0)
                     || (strncmp("/pc/ ",(char *)&(buf[dat_p+4]),5)==0)){
                        plen=http200ok();
                        plen=fill_tcp_data_p(buf,plen,pc_html);
                        goto SENDTCP;
                }
                if ((strncmp("/m ",(char *)&(buf[dat_p+4]),3)==0)
                     || (strncmp("/m/ ",(char *)&(buf[dat_p+4]),4)==0)){
                        plen=http200ok();
                        plen=fill_tcp_data_p(buf,plen,mobile_html);
                        goto SENDTCP;
                }
                // GET /ir?power=on&temp=28
                if (strncmp("/ir?",(char *)&(buf[dat_p+4]),4)==0){
                        if(find_key_val(
                                (char *)&(buf[dat_p+8]),
                                gStrbuf,
                                5,
                                "power"
                                )
                        ) {
                                xprintf(PSTR("power=%s\n"),gStrbuf);
                                if(strncmp("on", gStrbuf, 2) == 0){
                                        airController_on(&daikin);
                                        setData(DAIKIN, daikin.buf, 35*8);
                                }else if(strncmp("off", gStrbuf, 3) == 0){
                                        airController_off(&daikin);
                                        setData(DAIKIN, daikin.buf, 35*8);
                                }
                        }
                        if(find_key_val(
                                (char *)&(buf[dat_p+8]),
                                gStrbuf,
                                4,
                                "temp"
                                )
                        ) {
                                xprintf(PSTR("temp=%s\n"),gStrbuf);
                                airController_setTemp(&daikin, atoi(gStrbuf));
                                setData(DAIKIN, daikin.buf, 35*8);
                        }
                        plen=http200ok();
                        plen=fill_tcp_data_p(buf,plen,PSTR("Done\n"));
                        goto SENDTCP;
                }

                cmd=analyse_get_url((char *)&(buf[dat_p+4]));
                // for possible status codes see:
                // http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
                if (cmd==-1){
                        plen=fill_tcp_data_p(buf,0,PSTR("HTTP/1.0 401 Unauthorized\r\nContent-Type: text/html\r\n\r\n<h1>401 Unauthorized</h1>"));
                        goto SENDTCP;
                }
                if (cmd==1){
                        //PORTD|= (1<<PORTD7);// transistor on
                }
                if (cmd==0){
                        //PORTD &= ~(1<<PORTD7);// transistor off
                }
                if (cmd==2){
                        // favicon:
                        //plen=moved_perm(buf,0);
                        goto SENDTCP;
                }
                if (cmd==-2){
                        // redirect to the right base url (e.g add a trailing slash):
                        plen=moved_perm(buf,1);
                        goto SENDTCP;
                }
                // if (cmd==-2) or any other value
                // just display the status:
                //plen=print_webpage(buf,/*(PORTD & (1<<PORTD7))*/0);
                //
SENDTCP:
                www_server_reply(buf,plen); // send data
                continue;

                // tcp port www end
                // -------------------------------
                // udp start, we listen on udp port 1200=0x4B0
UDP:
//                xprintf(PSTR("here is UDP:\n"));
                // check if ip packets are for us:
                if(eth_type_is_ip_and_my_ip(buf,plen)==0){
  //                      xprintf(PSTR("here is eth_type_is_ip_andd_my_ip\n"));
                        continue;
                }
                /*if (buf[IP_PROTO_P]==IP_PROTO_UDP_V&&buf[UDP_DST_PORT_H_P]==(MYUDPPORT>>8)&&buf[UDP_DST_PORT_L_P]==(MYUDPPORT&0xff)){
                        payloadlen=buf[UDP_LEN_L_P]-UDP_HEADER_LEN;
                        // you must sent a string starting with v
                        // e.g udpcom version 10.0.0.24
                        if (verify_password((char *)&(buf[UDP_DATA_P]))){
                                // find the first comma which indicates 
                                // the start of a command:
                                cmd_pos=0;
                                while(cmd_pos<payloadlen){
                                        cmd_pos++;
                                        if (buf[UDP_DATA_P+cmd_pos]==','){
                                                cmd_pos++; // put on start of cmd
                                                break;
                                        }
                                }
                                // a command is one char and a value. At
                                // least 3 characters long. It has an '=' on
                                // position 2:
                                if (cmd_pos<2 || cmd_pos>payloadlen-3 || buf[UDP_DATA_P+cmd_pos+1]!='='){
                                        strcpy(str,"e=no_cmd");
                                        goto ANSWER;
                                }
                                // supported commands are
                                // t=1 t=0 t=?
                                if (buf[UDP_DATA_P+cmd_pos]=='t'){
                                        cmdval=buf[UDP_DATA_P+cmd_pos+2];
                                        if(cmdval=='1'){
                                                PORTD|= (1<<PORTD7);// transistor on
                                                strcpy(str,"t=1");
                                                goto ANSWER;
                                        }else if(cmdval=='0'){
                                                PORTD &= ~(1<<PORTD7);// transistor off
                                                strcpy(str,"t=0");
                                                goto ANSWER;
                                        }else if(cmdval=='?'){
                                                if (PORTD & (1<<PORTD7)){
                                                        strcpy(str,"t=1");
                                                        goto ANSWER;
                                                }
                                                strcpy(str,"t=0");
                                                goto ANSWER;
                                        }
                                }
                                strcpy(str,"e=inv_cmd");
                                goto ANSWER;
                        }
                        strcpy(str,"e=inv_pw");
ANSWER:
                        make_udp_reply_from_request(buf,str,strlen(str),MYUDPPORT);
                }*/
        }
        return (0);
}
Esempio n. 29
0
int main(void)
{
    DDRC = 0xFF;
    OUTPUT = 0x00;

    serialInit(SPEED9600);
    setupTimer();
    sei();

/*
    byte buf[3];
    uint16_t num;
    while(1)
    {
        if(serialAvailable() >= 2)
        {
            serialRead(buf,2);
            memcpy((void*)&num,buf,2);
            setAngle(num);
            serialClearBuffer();
        }
    }
*/
/*
    uint16_t num;
    while(1)
    {
        serialWaitUntil('\r');
        num = serialParseInt();
        serialClearBuffer();
        setElectricalAngle(num);
    }

*/

/*
    serialWrite("hello max!1 - f, 2 - b, 3 ++,4 --\n");
    while(1)
    {
        if(serialAvailable()>0)
        {
            uint8_t c = serialReadChar();

            switch(c)
            {
            case '1':
                if(direction)
                    direction = 1;
                break;
            case '2':
                if(direction)
                    direction = 2;
                break;
            case '3':
                if(userSpeed > 1)
                    userSpeed--;
                    serialWrite("userSpeed:");
                    serialPrintIntLn(userSpeed);
                break;
            case '4':
                if(userSpeed<255)
                    userSpeed++;
                    serialWrite("userSpeed:");
                    serialPrintIntLn(userSpeed);
                break;

            }
        }

    }

*/

    uint16_t i=0;
    while(1)
    {

        for(i=0;;i+=5)
        {
            setElectricalAngle(i);
            _delay_ms(2);
        }
    }

    serialEnd();


    return 0;
}
Esempio n. 30
0
int main( void )
{
	int32_t tmp = 0x0;
//	uint8_t tmp8;

	cli();

	SetupInterruptPins();

	y_pos = 0;
	x_pos = 0;

//	DDRC = _BV(PC6); //output pin
	SetupDriverPins();

	setup_clock();
	setup_timers();
	SetupPrintf();

	USB_ZeroPrescaler();
	USB_Init();

	sei();

	printf("hello world");

//	motorflags |= 0x01;
//	set_motor_pwm(PWM_MAX);
//	forward();
//	while(1);

//AutoSlop();

/*
AutoSlop();
while(1);
*/

//		dec_backward();
//		set_dec_pwm(0x1fff);
//		ra_forward();
//		set_ra_pwm(0x3fff);

	while(1)
	{
		cli();
//		tmp8 = usbHasEvent;
		//add accumulated radial encoder output
		y_pos += y_tmp;
		y_tmp = 0;

		x_pos += x_tmp;
		x_tmp = 0;
		sei();

		if (usbHasEvent) ProcessUSB();

		if (jog_value_dec == 0) {
			tmp = ComputeOffset(&y_pos,&y_dest); //pid error value
			slew_dec(&tmp);
		}

		if (jog_value_ra == 0) {
			tmp = ComputeOffset(&x_pos,&x_dest); //pid error value
			slew_ra(&tmp);
		}

	}
	return 0;
}