예제 #1
0
bool app_openuart(void){
	//Open a uart
	uart_init(uart);
	uart_setdevice(uart,"/dev/ttyS41");
	if (!uart_configure(uart,B9600,false)){
		//Failed to open.
		printf_clr(CLR_YELLOW,"Try a different tty:?\n");
		uint8_t newname[64];
		fgets(newname,64,stdin);
		//Remove \n
		int len = strlen(newname);	
		newname[len-1] = 0;		

		uart_setdevice(uart,newname);
		if (!uart_configure(uart,B9600,false)){
			printf_clr(CLR_RED,"Nope.\n");
			return false;
		}
	}

	//Setup everything:
	fifo_init(&txfifo,txbuffer,UART_BUFFER_SIZE);
	fifo_init(&rxfifo,rxbuffer,UART_BUFFER_SIZE);
	//Attach fifo's to uart.
	uart->rxfifo = &rxfifo;
	uart->txfifo = &txfifo;

	printf("Attatching funcions to stream\n");
	stream_init(stream,uart);
	stream->write_start = &stream_writestart;
	stream->write_stop = &stream_writestop;

	bus_init(bus);
}
예제 #2
0
int main(void)
{

    bus_init(BUS_ADDRESS_CHASSIS);
    _delay_ms(100);
    engine_init();
    regulator_init();

    carrying_rfid = 0;
    handled_count = 0;
    manual_control = 0;
    scan_count = 0;
    lap_finished = 0;
    number_of_stations = 0;
    station_count = 0;

    // bus_register_receive(1, receive_line_data);
    bus_register_receive(2, arm_is_done);
    bus_register_receive(3, control_line_following);
    bus_register_receive(4, RFID_done);
    bus_register_receive(8, engine_control_command);
    bus_register_receive(11, engine_set_kp);
    bus_register_receive(12, engine_set_kd);

    sei();
    start_button_init();
    timer_interrupt_init();

    while(1)
    {

    }
}
예제 #3
0
파일: bus_handler.c 프로젝트: lwid/openasc
void bus_handler_init() {
    /* Read the external address of the device */
  bus_set_address(BUS_BASE_ADDR + read_ext_addr());

    /* This delay is simply so that if you have the devices connected to the same power supply
     * all units should not send their status messages at the same time. Therefor we insert a delay
     * that is based on the external address of the device */
  for (unsigned char i = 0; i < bus_get_address(); i++) {
    delay_ms(DEFAULT_STARTUP_DELAY);
  }

    /* Initialize the communication bus */
  bus_init();
  bus_ping_init();

  if ((BUS_BASE_ADDR + read_ext_addr()) == 0x01) {
    bus_set_is_master(1, DEF_NR_DEVICES);
  }
  else {
    bus_set_is_master(0, 0);
  }

    /* Timer used for the communication bus. The interrupt is caught in bus.c */
  bsp_init_timer_2();
}
예제 #4
0
파일: main.c 프로젝트: cillian64/thegrid
int main(void)
{
    halInit();
    chSysInit();

    chBSemObjectInit(&frame_thread_sem, false);

    bus_init();
    power_init();

    sduObjectInit(&SDU1);
    sduStart(&SDU1, &serusbcfg);

    usbDisconnectBus(serusbcfg.usbp);
    chThdSleepMilliseconds(1500);
    usbStart(serusbcfg.usbp, &usbcfg);
    usbConnectBus(serusbcfg.usbp);

    chThdCreateStatic(frame_thread_wa, sizeof(frame_thread_wa),
        NORMALPRIO, frame_thread, NULL);

    while(true) {
        usb_rx(streamGet(&SDU1));
    }
}
예제 #5
0
파일: main.c 프로젝트: Paolo-Maffei/nxstack
int main( void )
{
	LED_INIT();
	if (bus_init() == pdFALSE)
	{
	}	
	LED1_ON();
	xTaskCreate( vbeacon_rfd, "Client", configMINIMAL_STACK_SIZE + 200, NULL, (tskIDLE_PRIORITY + 2 ), NULL );
	vTaskStartScheduler();

	return 0;
}
예제 #6
0
파일: app.c 프로젝트: Pingue/uk-transport
static void init(void) {
  bitmaps_init();

  mqueue_init();
  tube_init();
  bus_init();
  train_init();

  settings_restore();
  win_main_menu_create();
  win_main_menu_show(true);

  analytics_track_event("app.start", " ");
  time_started = time(NULL);
}
예제 #7
0
파일: ninja.c 프로젝트: pfalcon/bus-ninja
int main(void)
{
    /* Bring up processor */
	cpu_init();
    watchdog_init();

#ifdef CONFIG_HW_LED_ALIVE_CHECK
    /* Bring up low level LED */
    hw_led_init();
#endif
#ifdef CONFIG_HW_UART
    /* Bring up low level hardware UART */
    hw_uart_init();
#endif
    /* Setup timer for tick counting */
    tick_init();

    /* Bring up high level LED */
    led_init();

    /* Bring up console */
    console_init();

#ifdef CONFIG_DEBUG_RESET_REASON
    /* Report reason for last reset */
    console_puts_P(PSTR("Reset cause:"));
    console_puthex8(MCUSR);
    console_newline();
#endif

    /* Set default LED pattern */
    led_set_seq(LED_SEQ_SINE);

#ifdef CONFIG_USBDEV
    usbdev_init(USBMODE_DEFAULT);
#endif

    /* HiZ bus mode selected by default */
    bus_init(&bus_hiz);

    /* Enable interrupts */
    cpu_enable_int();

    while(1)
	{
        driver_tick();
	}
}
예제 #8
0
파일: main.c 프로젝트: bruggers/NES-2012
int main(void)
{
		//initialize_memory();
        DEBUG_INIT();
#if ! defined(USE_SCHEDULE)
	bus_init();
	ifs_init();
#endif /* USE_SCHEDULE */
	ttpa_setstate(TTPA_STATE_UNSYNC);
        while(1) {
#if defined(USE_SCHEDULE)
		schedule();
#endif
        }
    return 0;
}
int board_init(void)
{
	init_sc520();
	bus_init();
	irq_init();

	/* max drive current on SDRAM */
	sc520_mmcr->dsctl = 0x0100;

	/* enter debug mode after next reset (only if jumper is also set) */
	sc520_mmcr->rescfg = 0x08;
	/* configure the software timer to 33.333MHz */
	sc520_mmcr->swtmrcfg = 0;
	gd->bus_clk = 33333000;

	return 0;
}
예제 #10
0
static int
cmd_initbus_run( chain_t *chain, char *params[] )
{
	int i;

	if (cmd_params( params ) < 2)
		return -1;

	if (!cmd_test_cable( chain ))
		return 1;

	if (!chain->parts) {
		printf( _("Run \"detect\" first.\n") );
		return 1;
	}

	if (chain->active_part >= chain->parts->len || chain->active_part < 0) {
		printf( _("%s: no active part\n"), "initbus" );
		return 1;
	}

	for (i = 0; bus_drivers[i] != NULL; i++) {
		if (strcasecmp( bus_drivers[i]->name, params[1] ) == 0) {
			bus_t *abus = bus_drivers[i]->new_bus( chain, bus_drivers[i], params );
			if (abus == NULL) {
				printf( _("bus alloc/attach failed!\n") );
				return 1;
			}
			buses_add( abus );
			if (bus_init( abus ) != URJTAG_STATUS_OK)
				printf( _("bus initialization failed!\n") );

			for (i = 0; i < buses.len; i++)
				if (buses.buses[i] == bus)
					break;
			if (i != buses.len - 1)
				printf( _("Initialized bus %d, active bus %d\n"), buses.len - 1, i );

			return 1;
		}
	}

	printf( _("Unknown bus: %s\n"), params[1] );

	return 1;
}
예제 #11
0
int main(void)
{
    wdt_disable();
    /* Clear WDRF in MCUSR */
    MCUSR &= ~(1<<WDRF);
    /* Write logical one to WDCE and WDE */
    /* Keep old prescaler setting to prevent unintentional time-out */
    WDTCSR |= (1<<WDCE) | (1<<WDE);
    /* Turn off WDT */
    WDTCSR = 0x00;
    //DDRA |= 0x07;
    //PORTA &= ~7;
    //DDRC |= 0x07;
    //DDRC |= 0xC0;

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

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

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

}
예제 #12
0
파일: main.c 프로젝트: Paolo-Maffei/nxstack
int main( void )
{
	LED_INIT();
	if (bus_init() == pdFALSE)
	{
		for (;;)
		{
			LED1_ON();
			LED2_OFF();
			LED1_OFF();
			LED2_ON();
		}
	}	
	
	xTaskCreate( vSensorTask, "Sens", configMINIMAL_STACK_SIZE + 100, NULL, (tskIDLE_PRIORITY + 2 ), NULL );
	vTaskStartScheduler();

	return 0;
}
예제 #13
0
int main(void)
{
    wdt_disable();
    /* Clear WDRF in MCUSR */
    MCUSR &= ~(1<<WDRF);
    /* Write logical one to WDCE and WDE */
    /* Keep old prescaler setting to prevent unintentional time-out */
    WDTCSR |= (1<<WDCE) | (1<<WDE);
    /* Turn off WDT */
    WDTCSR = 0x00;
    DDRC |= 0xC0;

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

}
예제 #14
0
/* Main task, initialize hardware and start the FreeRTOS scheduler */
int main( void )
{
	/* Initialize the Nano hardware */
	bus_init();
	LED_INIT();
	N710_SENSOR_INIT();
	/* Start the debug UART at 115k */
	debug_init(115200);
	stack_init();
	button_events = xQueueCreate( 4, 1 /*message size one byte*/ );
	/* Setup the application task and start the scheduler */
	xTaskCreate( vAppTask, "App", configMAXIMUM_STACK_SIZE, NULL, (tskIDLE_PRIORITY + 1 ), ( xTaskHandle * )NULL );
	xTaskCreate( vButtonTask, "Button", configMAXIMUM_STACK_SIZE, NULL, (tskIDLE_PRIORITY + 2 ), ( xTaskHandle * )NULL );

	vTaskStartScheduler();
	
	/* Scheduler has taken control, next vAppTask starts executing. */

	return 0;
}
예제 #15
0
파일: 5370.c 프로젝트: jks-prv/5370_proc
// only done once per app run
void sim_init()
{
	// try and improve our performance a bit
    setpriority(PRIO_PROCESS, 0, -20);
	scall("mlockall", mlockall(MCL_CURRENT | MCL_FUTURE));

	// check that new polarity scheme didn't break anything
	assert(WREG_O3_RST == WREG_O3_RST_GOOD);
	assert(WREG_O2_IDLE == WREG_O2_IDLE_GOOD);
	assert(WREG_O2_ENA == WREG_O2_ENA_GOOD);
	assert(WREG_O2_ARM == WREG_O2_ARM_GOOD);

	bus_init();
	pru_start();
	bus_pru_gpio_init();

	if (!background_mode) {
		tty = open("/dev/tty", O_RDONLY | O_NONBLOCK);
		if (tty < 0) sys_panic("open tty");
	}
}
/*---------------------------------------------------------------------------*/
int
main(void)
{

  /* Hardware initialization */
  bus_init();

  leds_init();
  fade(LEDS_GREEN);

  uart1_init(115200);
  uart1_set_input(serial_line_input_byte);

  /* initialize process manager. */
  process_init();

  serial_line_init();

  printf("\n" CONTIKI_VERSION_STRING " started\n");
  printf("model: " SENSINODE_MODEL "\n\n");

  /* initialize the radio driver */

  cc2430_rf_init();
  rime_init(sicslowmac_init(&cc2430_rf_driver));
  set_rime_addr();

  /* start services */
  process_start(&etimer_process, NULL);

  fade(LEDS_RED);

  autostart_start(autostart_processes);

  while(1) {
    process_run();
    etimer_request_poll();
  }
}
예제 #17
0
파일: device.c 프로젝트: futurepr0n/cen64
// Creates and initializes a device.
struct cen64_device *device_create(struct cen64_device *device,
  const struct rom_file *ddipl, const struct rom_file *ddrom,
  const struct rom_file *pifrom, const struct rom_file *cart,
  const struct save_file *eeprom, const struct save_file *sram,
  const struct save_file *flashram, const struct controller *controller,
  bool no_audio, bool no_video) {

  // Initialize the bus.
  device->bus.ai = &device->ai;
  device->bus.dd = &device->dd;
  device->bus.pi = &device->pi;
  device->bus.ri = &device->ri;
  device->bus.si = &device->si;
  device->bus.vi = &device->vi;

  device->bus.rdp = &device->rdp;
  device->bus.rsp = &device->rsp;
  device->bus.vr4300 = &device->vr4300;

  // Initialize the bus.
  if (bus_init(&device->bus)) {
    debug("create_device: Failed to initialize the bus.\n");
    return NULL;
  }

  // Initialize the AI.
  if (ai_init(&device->ai, &device->bus, no_audio)) {
    debug("create_device: Failed to initialize the AI.\n");
    return NULL;
  }

  // Initialize the DD.
  if (dd_init(&device->dd, &device->bus,
    ddipl->ptr, ddrom->ptr, ddrom->size)) {
    debug("create_device: Failed to initialize the DD.\n");
    return NULL;
  }

  // Initialize the PI.
  if (pi_init(&device->pi, &device->bus, cart->ptr, cart->size, sram, flashram)) {
    debug("create_device: Failed to initialize the PI.\n");
    return NULL;
  }

  // Initialize the RI.
  if (ri_init(&device->ri, &device->bus)) {
    debug("create_device: Failed to initialize the RI.\n");
    return NULL;
  }

  // Initialize the SI.
  if (si_init(&device->si, &device->bus, pifrom->ptr,
    cart->ptr, ddipl->ptr != NULL, eeprom->ptr, eeprom->size,
    controller)) {
    debug("create_device: Failed to initialize the SI.\n");
    return NULL;
  }

  // Initialize the VI.
  if (vi_init(&device->vi, &device->bus, no_video)) {
    debug("create_device: Failed to initialize the VI.\n");
    return NULL;
  }

  // Initialize the RDP.
  if (rdp_init(&device->rdp, &device->bus)) {
    debug("create_device: Failed to initialize the RDP.\n");
    return NULL;
  }

  // Initialize the RSP.
  if (rsp_init(&device->rsp, &device->bus)) {
    debug("create_device: Failed to initialize the RSP.\n");
    return NULL;
  }

  // Initialize the VR4300.
  if (vr4300_init(&device->vr4300, &device->bus)) {
    debug("create_device: Failed to initialize the VR4300.\n");
    return NULL;
  }

  return device;
}
예제 #18
0
파일: main.c 프로젝트: cbmeeks/sd2iec
int main(void) {
  /* Early system initialisation */
  board_init();
  system_init_early();
  leds_init();

  set_busy_led(1);
  set_dirty_led(0);

  /* Due to an erratum in the LPC17xx chips anything that may change */
  /* peripheral clock scalers must come before system_init_late()    */
  uart_init();
#ifndef SPI_LATE_INIT
  spi_init(SPI_SPEED_SLOW);
#endif
  timer_init();
  bus_interface_init();
  i2c_init();

  /* Second part of system initialisation, switches to full speed on ARM */
  system_init_late();
  enable_interrupts();

  /* Internal-only initialisation, called here because it's faster */
  buffers_init();
  buttons_init();

  /* Anything that does something which needs the system clock */
  /* should be placed after system_init_late() */
  bus_init();    // needs delay
  rtc_init();    // accesses I2C
  disk_init();   // accesses card
  read_configuration();

  fatops_init(0);
  change_init();

  uart_puts_P(PSTR("\r\nsd2iec " VERSION " #"));
  uart_puthex(device_address);
  uart_putcrlf();

#ifdef CONFIG_REMOTE_DISPLAY
  /* at this point all buffers should be free, */
  /* so just use the data area of the first to build the string */
  uint8_t *strbuf = buffers[0].data;
  ustrcpy_P(strbuf, versionstr);
  ustrcpy_P(strbuf+ustrlen(strbuf), longverstr);
  if (display_init(ustrlen(strbuf), strbuf)) {
    display_address(device_address);
    display_current_part(0);
  }
#endif

  set_busy_led(0);

#if defined(HAVE_SD) && BUTTON_PREV != 0
  /* card switch diagnostic aid - hold down PREV button to use */
  if (!(buttons_read() & BUTTON_PREV)) {
    while (buttons_read() & BUTTON_NEXT) {
      set_dirty_led(sdcard_detect());
# ifndef SINGLE_LED
      set_busy_led(sdcard_wp());
# endif
    }
    reset_key(0xff);
  }
#endif

  bus_mainloop();

  while (1);
}
예제 #19
0
int main(void){
	clock_switch32M();
	
	uart_init();	
	bus_init(&bus);	

	
	PORTC.DIR = 0xFF;
		
	//Setup a timer, just for counting. Used for bus message and timeouts.
	TCC1_CTRLA = TC_CLKSEL_DIV1024_gc;

	//Set the interrupts we want to listen to.
	PMIC.CTRL = PMIC_MEDLVLEN_bm |PMIC_HILVLEN_bm | PMIC_RREN_bm;
		
	//Make sure to move the reset vectors to application flash.
	CCP = CCP_IOREG_gc;
	PMIC.CTRL &= ~PMIC_IVSEL_bm;
	
	//Enable interrupts.
	sei();
	
	//Read temperature calibration:
	read_calibration();
		
	uint8_t cnt_tm = 0;		//Used by TCC1
	uint8_t poll_cnt = 0;	//Used for polling the display.	
	//uint16_t pwm_lim = 0;	//PWM limit may change at higher speed.
	
	while(1){
		continue;
		get_measurements();
		if (get_throttle()){
			motor.throttle = throttle;
		}else{
			motor.throttle = 0;
		}
		
		if (display.online == false){
			motor.mode = 0;
		}
			
		//Set display data	
		display.voltage = motor.voltage;
		display.current = motor.current;
		//display.power = power_av;
		display.throttle = throttle;
		display.error = status | motor.status;
		/*if (motor.status){
			display.error = motor.status;	
		}*/
		//display.speed = speed% 1000; //999 max
		
		if (TCC1.CNT > 500){
			cnt_tm++;
			TCC1.CNT = 0;
		
			
			//Last character in message
			if (wait_for_last_char){
				wait_for_last_char = false;
			}else{
				bus_endmessage(&bus);
			}				
			
			//Send timer tick
			bus_tick(&bus);
			
			if (bus_check_for_message()){
				
				green_led_on();
			}else{
				green_led_off();
				//Increase offline count.
				display.offline_cnt++;
				if (display.offline_cnt > 10){
					uart_rate_find();
					PORTC.OUTSET = PIN6_bm;
				}else{
					PORTC.OUTCLR = PIN6_bm;
				}
				
				//If offline too long:
				if (display.offline_cnt > 50){
					//You need to make it unsafe again.
					display.road_legal = true;
					display.online = false;
					throttle_cruise = false;					
					throttle = 0;
					use_brake = false;
					brake = 0;
				}
				if (motor.offline_cnt > 20){
					motor.online = false;
				}
				
				
				poll_cnt++;				
				if (poll_cnt == 2){					
					bus_display_poll(&bus);	
				}else if (poll_cnt == 4){
					bus_display_update(&bus);
				}else if (poll_cnt == 6){					
					bus_motor_poll(&bus);
					motor.offline_cnt++;					
				}else if (poll_cnt == 8){
					poll_cnt = 0;
				}
			}
		}		
	}
}
예제 #20
0
/*
void read_calibration(void){	
	//Get the factory temperature value, at 85 Deg. C.		
	ad_temp_ref = SP_ReadCalibrationByte(PRODSIGNATURES_ADCACAL0) ;
	ad_temp_ref |= SP_ReadCalibrationByte(PRODSIGNATURES_ADCACAL1) <<8;
}
*/
int main(void){
	clock_switch32M();
	
	init_pwm();
	uart_init();	
	bus_init(&bus);	
	
	
	
	//Clear the AD settings.
	PORTA.DIR = 0;
	PORTA.OUT = 0;
	ADCA.CTRLA  = ADC_FLUSH_bm;
	ADCA.CTRLB  = 0;
	ADCA.REFCTRL  = 0;
	ADCA.EVCTRL  = 0;
	ADCA.PRESCALER  = 0;	

	//Set PORTB as AD input
	PORTB.DIR = 0;
	PORTB.OUT = 0;
		
	//Setup a timer, just for counting. Used for bus message and timeouts.
	TCC1_CTRLA = TC_CLKSEL_DIV1024_gc;
	
	//Set up the RTC for speed timing.
	CLK.RTCCTRL = CLK_RTCSRC_RCOSC32_gc | CLK_RTCEN_bm;	
	RTC.CTRL = RTC_PRESCALER_DIV1_gc;
	RTC.COMP = 32768;
	
	//A counter for 100% PWM timing.
	TCD0.CTRLA = TC_CLKSEL_DIV1024_gc;
	TCD0.PER = 320;
	TCD0.INTCTRLA = TC_OVFINTLVL_HI_gc;
	
	
	//Make sure to move the reset vectors to application flash.
	//Set the interrupts we want to listen to.
	CCP = CCP_IOREG_gc;
	PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm |PMIC_HILVLEN_bm | PMIC_RREN_bm;
	
	//Enable interrupts.
	sei();
	
	//Set defaults:
	eepsettings.straincal = 200;
	
	eemem_read_block(EEMEM_MAGIC_HEADER_SETTINGS,(uint8_t*)&eepsettings, sizeof(eepsettings), EEBLOCK_SETTINGS1);
	
	
	//Apply settings...
	strain_threshhold = eepsettings.straincal;

	//Startup hall state.
	hall_state = 0x04;
	get_hall();

	//Startup PWM value.
	pwm = PWM_SET_MIN;
	
	uint8_t cnt_tm = 0;		//Used by TCC1
	uint8_t poll_cnt = 0;	//Used for polling the display.	
	uint16_t pwm_lim = 0;	//PWM limit may change at higher speed.
	
	display.strain_th = strain_threshhold;	
	
	//Two flags that can only be set.
	bool should_freewheel = true;
	bool force_commute = false;
	while(1){		
		
		
		//Double check the PWM hasn't gone crazy:
		if (pwm < pwm_set_min){
			pwm = pwm_set_min;
		}
		if (pwm > pwm_set_max){
			pwm = pwm_set_max;
		}
		
		//Testing
		if (testvalue > pwm_set_max){
			testvalue = pwm_set_max;
		}		
		if (testvalue < pwm_set_min){
			testvalue = pwm_set_min;
		}

		//Apply PWM settings.
		TCC0.CCA = pwm;
		TCC0.CCB = pwm;
		TCC0.CCC = pwm;
		
		//Get halls sensors.		
		if (!get_hall()){
			should_freewheel = true;			
			status_set(STAT_HALL_FAULT);
		}		
				
		//Commute or freewheel:
		if (should_freewheel){
			pwm_freewheel();
		}else if (force_commute){			
			if (direction == FORWARD){				
				commute_forward();
			}else{
				commute_backward();
			}	
			
		}else if (flag_hall_changed){
			if (direction == FORWARD){
				commute_forward();
			}else{
				commute_backward();
			}
		}else{			
			//pwm_freewheel();
		}
				
		//Remeber...
		pwm_prev = pwm;
		
		
		//Reset 
		should_freewheel = false;
		//force_commute = false;
				
		if (startup == 10){ //Just started
			//Setup PWM
			commute_start();
			pwm = estimate_pwm_byspeed();
			//Apply PWM settings.
			TCC0.CCA = pwm;
			TCC0.CCB = pwm;
			TCC0.CCC = pwm;
		}
		
		if (display.online == false){
			should_freewheel = true;			
		}		
		if (motor.mode == 0){
			should_freewheel = true;
		}
		
		//Get voltage/current.
		get_measurements();
		
		//Hard under and over voltage.
		if (ad_voltage > 3700){ //3900
			//Freewheel as fast as possible.
			pwm_freewheel();
			should_freewheel = true;
			status_set(STAT_OVER_VOLTAGE);
		}else if (ad_voltage < 1800){ //About 19 volts.
			//Freewheel as fast as possible.
			pwm_freewheel();
			should_freewheel = true;
			status_set(STAT_UNDER_VOLTAGE);
			pwm_inc(200);pwm_inc(200);
		}

		//Regenning too hard:
		if (ad_current_regav < -1300){
			//Freewheel as fast as possible.
			//pwm_freewheel();
			//should_freewheel = true;
			//status_set(STAT_REGEN_HIGH);
			//startup = 3;
		}
		
		#if (HARDWARE_HAS_THROTTLE)
		if (use_throttle){
			//This gas pedal is low on disconnect.					
			if (!get_throttle()){
				status_set(STAT_THROTTLE_FAULT);
				should_freewheel = true;
			}
			
			//Use the brake too:
			if (get_brake()){
				if (use_brake){
					throttle_cruise = false;
					throttle_tick = 0;
				}else{
					if (throttle == 0){ //< 5
						should_freewheel = true;
					}
				}
			}else{
				status_set(STAT_BRAKE_FAULT);				
				should_freewheel = true;
			}
		}
		#endif
		
		if (usehall){
			//Timer:
			if (flag_hall_changed){
				//Toggle blue led:
				PORTC.OUTTGL = PIN7_bm;			
			
				//compute time:
				time_now = RTC.CNT;			
				time_comm = time_now;
				//Running average.			
				time_comm_av += time_comm;
				time_comm_av >>= 1;
				
				commtime_sum+= time_comm;
				commtime_cnt++;				
				cnt_commutations++;				
			
				//Reset timer.
				RTC.CNT = 0;

				//Computer average current in this time:
				if (ad_current_regcnt > 0){
					ad_current_regav = ad_current_regsum / (int32_t)ad_current_regcnt;
				}else{
					ad_current_regav = ad_current;
				}

				//Values reset in next if-statement.
			}
			
			//Allowed to go faster if the commutation time is guaranteed to switch fast enough.
			//TCD0 is used in case the motor suddenly stops. Capacitors are 100uF/16V
			if (time_comm_av < 250){
				//Round REV0 does not support 100% duty cycle.
				pwm_set_min = 0;
			}
			
			//Limit for braking
			pwm_lim = pwm_set_max -  (display.function_val3 * 10);
			if (pwm_lim < pwm_set_min){
				pwm_lim = pwm_set_min;
			}else if (pwm_lim > pwm_set_max){
				pwm_lim = pwm_set_max;
			}
			
			//That's really slow.
			if (RTC.CNT> 5000){			
				speed = 0;
			}
		
			//Minimum response time
			if (flag_hall_changed) {
					

				//Clear current sum:
				ad_current_regcnt = 0;
				ad_current_regsum = 0;				
				
				RTC.CNT = 0;	
			}							
			
			//Control loop
			if ((flag_hall_changed) || (TCC1.CNT > 450)){
				//Clear hall flag if it was set.
				flag_hall_changed = false;
				if (!off){
					//If brake is enabled:
					if (use_brake){
						if (brake > 5){
							//Regenning is a bit harder. The amount of strength decreases if PWM is too high.
							//Brake is current limited.
							//At low speed, ovverride PWM settings
							if (speed < 150){
								pwm_lim = pwm_set_max;
							}
																
							if ((ad_current_regav + 169) > (((int16_t)brake)*-12)){  //100 * 10 -> current of about -8 Amp
								//More power: inc PWM
									
								//Use the speed average as a voltage estimate for the motor.
								//24V will give an unloaded speed of 350 (35.0kmh)
								//If we're doing 10km/h, the motor is at 7V approx, 30% duty cycle.
									
								if (pwm < pwm_lim){
									pwm_inc(slope_brake);
								}									
									
							}else{
								//Back off
								pwm_dec(slope_brake);
							}
							//Voltage limits
							if (ad_voltage > 3600){
								pwm_dec(slope_brake/2);
							}
							if (ad_voltage > 3700){
								pwm_dec(slope_brake/2);
							}
						}
					}
					if (use_throttle){
						//Undo brake :
						if (flag_brake_lowrpm){
							off = false;
							tie = false;
							status_clear();
							flag_brake_lowrpm = false;
						}


						if (throttle > 5){
							/*
							//Throttle is current limited.
							if ((ad_current_regav + 169) < (((int16_t)throttle)*8)){
								//More power
								pwm_dec(slope_throttle*2);
							}else if ((ad_current_regav + 169) < (((int16_t)throttle)*16)){  //100 * 16 -> current of about 12 Amp									
								//More power
								pwm_dec(slope_throttle);
							}else{
								//Back off
								pwm_inc(slope_throttle);
							}*/
							
							//Voltage limits
							if (ad_voltage < 1950){
								pwm_inc(slope_throttle*2);
							}	
							if (ad_voltage < 1900){
								pwm_inc(slope_throttle*2);
							}
							
							//Cal current reg:
							//Current calibration:
							#if(HARDWARE_VER == HW_CTRL_REV0)
							int32_t regualtion = ad_current_regav; 
							regualtion += 1749;
							regualtion *= 1000;
							regualtion /= 286;
							regualtion -= 34;
							#endif
							
							//Current regulation
							if (speed){
								if (regualtion < ((int16_t)throttle*(int16_t)motor.mode)){ //200 * 0-5
									//More power
									pwm_dec(slope_throttle*2);
								}else if (regualtion < ((int16_t)throttle*(int16_t)motor.mode)){ 
									//More power
									pwm_dec(slope_throttle);
								}else{
									//Back off
									pwm_inc(slope_throttle);
								}
							}							
						}
					}
					
					if (use_pedalassist) {						
						if (ad_strain_av > highestforce){
							highestforce  = ad_strain_av;
						}					
						
						if (ad_strain_av > strain_threshhold){
							strain_cnt = 75UL + (2UL*speed);
							if (ad_strain_av-strain_threshhold < 100){
								pedal_signal = ad_strain_av-strain_threshhold;
							}else{
								pedal_signal = 100;
							}							
							
						}
						
						if (strain_cnt){
							strain_cnt--;
						}else{
							pedal_signal = 0;
						}
						
						if (pedal_signal && strain_cnt){
							//Same control loop as in throttle:
						
							
							//Voltage limits
							if (ad_voltage < 1950){
								pwm_inc(slope_throttle*2);
							}	
							if (ad_voltage < 1900){
								pwm_inc(slope_throttle*2);
							}
							
							//Cal current reg:
							//Current calibration:
							#if(HARDWARE_VER == HW_CTRL_REV0)
							int32_t regualtion = ad_current_regav; 
							regualtion += 1749;
							regualtion *= 1000;
							regualtion /= 286;
							regualtion -= 34;
							#endif
							
							//Current regulation
							if (speed){
								if (regualtion < ((int16_t)pedal_signal*2*(int16_t)motor.mode)){ //200 * 0-5
									//More power
									pwm_dec(slope_throttle*2);
								}else if (regualtion < ((int16_t)pedal_signal*2*(int16_t)motor.mode)){ 
									//More power
									pwm_dec(slope_throttle);
								}else{
									//Back off
									pwm_inc(slope_throttle);
								}
							}			
						}
						
					}
					
					

				}else{ //if (off)
					//Undo braking at low RPM
					if (flag_brake_lowrpm){
						off = false;
						tie = false;
						status_clear();
						flag_brake_lowrpm = false;
					}
					
					
				}
			}			
		}else{ //Hall hasn't changed.
			//Don't use hall.
			if (RTC.CNT > time_comm_av_last){
				//Reset timer.
				RTC.CNT = 0;				
				
			}					
		}		
		
		//Act on a fault?
		if (isfaultset()){
			if (tie){	
				tie_ground();
			}else{			
				should_freewheel = true;
			}			
		}
		
		if (use_pedalassist && (!use_throttle)){
			if (!pedal_signal){
				should_freewheel = true;
			}
		}else if ((!use_pedalassist) && (use_throttle && (throttle < 5))){
			should_freewheel = true;
		}else if ((use_throttle)&& (use_pedalassist)){
			if ((throttle < 5) && (!pedal_signal)){
				should_freewheel = true;
			}
		}
		
		//Current min/max
		if (ad_current < ad_currentmin){
			ad_currentmin = ad_current;
		}
		if (ad_current > ad_currentmax){
			ad_currentmax = ad_current;
		}
		
		if (flag_keep_pwm){
			pwm = pwm_prev;
		}

		cnt_rotations = cnt_commutations / 48;
		
		
				
		//Set display data	
		display.voltage = ad_voltage_av;
		display.current = ad_current_av;
		display.power = power_av;
		display.error = status;
		display.speed = speed% 1000; //999 max
		motor.status = status;
		//display.speed = pwm;
		//display.current = pwm_lim;
		if (use_brake){
			display.throttle = brake;	
		}else{
			if (use_pedalassist){
				if (pedal_signal > throttle){
					display.throttle = pedal_signal;
				}else{
					display.throttle = throttle;
				}
			}else{
				display.throttle = throttle;
			}
			
		}
		display.cruise = throttle_cruise;
		
		//Throttle test
		//display.speed = pwm;
		//display.current = status;
		
		if (TCC1.CNT > 450){
			cnt_tm++;
			TCC1.CNT = 0;
			
			//Testing
			/*
			if (display.button_state & BUTT_MASK_FRONT){
				if (testvalue < (PWM_SET_MAX -5)){
					testvalue+=5;
				}
			}else if (display.button_state & BUTT_MASK_TOP){
				if (testvalue > (PWM_SET_MIN+5)){
					testvalue-=5;
				}
			}*/
			
			//Apply speed limit:
			pwm_set_max = (display.function_val2 +1) * 50;
			if (pwm_set_max > PWM_SET_MAX){
				pwm_set_max = PWM_SET_MAX;
			}
			
			
			//Startup from standstill
			uint8_t throttle_was = throttle;
			throttle = motor.throttle;
			if ((throttle_was == 0) && throttle && (speed == 0)){
				force_commute = true;
				pwm_inc(20);
			}else{
				force_commute = false;
			}
			
			
			if (!motor.mode){
				pwm_inc(200);
			}
			//Testing 
			
					
			
			
			//Last character in message
			if (wait_for_last_char){
				wait_for_last_char = false;
			}else{
				bus_endmessage(&bus);
			}
			
			
			
			//Estimate speed  /pwm. Only when there is no throttle signal or brake.
			if (!use_brake){
				if ((use_throttle && (throttle < 5)) && ((use_pedalassist)&&(!pedal_signal))){
					pwm = estimate_pwm_byspeed();					
				}
			}			
			
			//Send timer tick
			bus_tick(&bus);
			
			if (bus_check_for_message()){
				green_led_on();				
			}else{
				green_led_off();
				//Increase offline count.
				display.offline_cnt++;
				if (display.offline_cnt > 10){
					uart_rate_find();
					PORTC.OUTSET = PIN6_bm;
				}else{
					PORTC.OUTCLR = PIN6_bm;
				}					
				
				//If offline too long:
				if (display.offline_cnt > 50){
					//You need to make it unsafe again.
					display.road_legal = true;
					display.online = false;
					throttle_cruise = false;
					should_freewheel = true;
					throttle = 0;
					use_brake = false;
					brake = 0;
					pedal_signal = 0;
					strain_cnt = 0;
					motor.mode = 0;
				}
				
				poll_cnt++;				
				if (poll_cnt == 2){
					#if (OPT_DISPLAY== FW_DISPLAY_MASTER)
					bus_display_poll(&bus);
					#endif
				}else if (poll_cnt == 4){
					//Update the display, and it's variables:
					
					//Speed is now the amount of commutations per seconds.
					if (commtime_sum){
						speed = (commtime_cnt * 32768UL) / commtime_sum;
						//With a 26" wheel:
						speed = (speed * 10000UL) / 6487UL;
					}else{
						speed=0;
					}						
					
					commtime_sum = 0;
					commtime_cnt = 0 ;
						
					//Disaplay average voltage:
					ad_voltage_av = ad_voltage_sum / meas_cnt;
					ad_voltage_sum = 0;
						
					//And current.
					ad_current_av = ad_current_sum / meas_cnt;
					ad_current_sum = 0;

					//Strain, if we have it:
					#ifdef HARDWARE_HAS_STRAIN
					//Running average:
					int32_t strain_val = ad_strain_sum / meas_cnt;
					strain_val /= 100;
					
					ad_strain_av += strain_val;
					ad_strain_av /= 2;
					
					//ad_strain_av = meas_cnt;
					ad_strain_sum = 0;
					
					//Strain calibration in Menu F8/F3:
					if ((display.func == 8) && (display.menu_downcnt > 100)){	
						strain_threshhold = 200;
						display.strain_th = strain_threshhold;
					}						
					if ((display.func == 3) && (display.menu_downcnt > 100)){						
						if (ad_strain_av > strain_threshhold){
							strain_threshhold++;
						}
						display.strain_th = strain_threshhold;
						flagsave = true;
					}
					
					if (display.menu_timeout == 0){
						if (flagsave){
							flagsave = false;
							//Save
							eepsettings.straincal = strain_threshhold;
							eemem_write_block(EEMEM_MAGIC_HEADER_SETTINGS,(uint8_t*)&eepsettings, sizeof(eepsettings), EEBLOCK_SETTINGS1);
							
						}
						
					}
					
					
					//Set test value
					//uint16_t s; 
					//adc_init_single_ended(REF_3V3,ADC_CH_MUXPOS_PIN8_gc); //Strain Sensor.
					//s = adc_getsample();
					
					//2180 average, over if you help.
					/*
					if (s > 2183){
						display.value1 = 200;
						testvalue+=1;
					}else if (s < 2177){
						display.value1 = 000;
						testvalue-=1;
					}else{
						display.value1 = 100;
					}*/
					
					
					
					
					//motor.current = ad_strain_av;
					display.value1 = ad_strain_av;// ad_strain_av - 2000;
					display.value2 = highestforce;// ad_strain_av - 2000;
					display.value3 = pwm;
					
					display.value4 = should_freewheel;
					#endif
					
					//Temperature
					ad_temp_av = ad_temp_sum / meas_cnt;
					ad_temp_sum = 0;
					
					//Set test value
					//display.value2 = ad_temp_av / 2;
					
					//Temperature about 20 Deg.C is 1866 counts. CKDIV16 2020 CKDIV512
					
										
					//Counts per kelvin.
					/*
					uint32_t cpk = ad_temp_ref*10 / 358;					
					ad_temp_av  = (ad_temp_av * 10) / cpk - 273;
					ad_temp_av = ad_temp_ref;
					*/
												
					meas_cnt = 0;
						
					//Calibration:
					ad_voltage_av -= 175;
					ad_voltage_av *= 1000;
					ad_voltage_av /= 886;
					
					//Current calibration:	
					#if(HARDWARE_VER == HW_CTRL_REV0)
					ad_current_av += 1749;
					ad_current_av *= 1000;
					ad_current_av /= 286;
					ad_current_av -= 34;
					#else					
					ad_current_av += 169;
					ad_current_av *= 100;
					ad_current_av /= 75;					
					#endif
					
					power_av = (ad_current_av * ad_voltage_av) / 10000;
									
					poll_cnt = 0;
					#if(OPT_DISPLAY == FW_DISPLAY_MASTER)
					bus_display_update(&bus);
					#endif
					//motor.mode = 1;
				}
			}
		}
	
		//Counter from TCC1
		if (cnt_tm > 15){
			cnt_tm = 0;
			
			//Increase throttle tick, for cruise control.
			if ((use_throttle)&& (!use_brake)){
				if ((display.online)&&(throttle > 10)){
					if (throttle_tick < 20){
						throttle_tick++;
					}else{
						throttle_cruise = true;
					}
				}				
			}
			
			//test
			//pwm_dec(5);
			testvalue-=5;
			
			ad_currentmin = 9999;
			ad_currentmax = -9999;
			
			
			
			
			if (startup){
				startup--;
				
				if (startup == 0){
					//Clear any status flag:
					//status_clear();
					//Give it a nudge.
					//commute_allowed = true;
				}
			}else{
				status_clear();
			}
			
		}
		
		//Set fault flags:
		if (off){
			status_set(STAT_STOPPED);
		}
		
		if (use_throttle){
			//status_set(STAT_USETHROTTLE);
		}		
	}
예제 #21
0
int main(void) {
  /* Early system initialisation */
  early_board_init();
  system_init_early();
  leds_init();

  set_busy_led(1);
  set_dirty_led(0);

  /* Due to an erratum in the LPC17xx chips anything that may change */
  /* peripheral clock scalers must come before system_init_late()    */
  uart_init();
#ifndef SPI_LATE_INIT
  spi_init(SPI_SPEED_SLOW);
#endif
  timer_init();
  i2c_init();

  /* Second part of system initialisation, switches to full speed on ARM */
  system_init_late();
  enable_interrupts();

  /* Prompt software name and version string */
  uart_puts_P(PSTR("\r\nNODISKEMU " VERSION "\r\n"));

  /* Internal-only initialisation, called here because it's faster */
  buffers_init();
  buttons_init();

  /* Anything that does something which needs the system clock */
  /* should be placed after system_init_late() */
  rtc_init();    // accesses I2C
  disk_init();   // accesses card
  read_configuration(); // restores configuration, may change device address

  filesystem_init(0);
  // FIXME: change_init();

#ifdef CONFIG_REMOTE_DISPLAY
  /* at this point all buffers should be free, */
  /* so just use the data area of the first to build the string */
  uint8_t *strbuf = buffers[0].data;
  ustrcpy_P(strbuf, versionstr);
  ustrcpy_P(strbuf+ustrlen(strbuf), longverstr);
  if (display_init(ustrlen(strbuf), strbuf)) {
    display_address(device_address);
    display_current_part(0);
  }
#endif

  set_busy_led(0);

#if defined(HAVE_SD)
  /* card switch diagnostic aid - hold down PREV button to use */
  if (menu_system_enabled && get_key_press(KEY_PREV))
    board_diagnose();
#endif

  if (menu_system_enabled)
    lcd_splashscreen();

  bus_interface_init();
  bus_init();
  read_configuration();
  late_board_init();

  for (;;) {
    if (menu_system_enabled)
      lcd_refresh();
    else {
      lcd_clear();
      lcd_printf("#%d", device_address);
    }
    /* Unit number may depend on hardware and stored settings */
    /* so present it here at last */
    printf("#%02d\r\n", device_address);
    bus_mainloop();
    bus_interface_init();
    bus_init();    // needs delay, inits device address with HW settings
  }
}
예제 #22
0
파일: main.c 프로젝트: fachat/XD2031
/////////////////////////////////////////////////////////////////////////////
// Main-Funktion
/////////////////////////////////////////////////////////////////////////////
int main(int argc, const char *argv[])
{

	// Initializations
	//
	// first some basic hardware infrastructure
	
	timer_init();			// Timer Interrupt initialisieren
	led_init();

	provider_init();		// needs to be in the beginning, as other
					// modules like serial register here

	term_init();			// does not need endpoint/provider yet
					// but can take up to a buffer of text


#ifdef __AVR__
	stdout = &term_stdout;          // redirect stdout
#else
	device_setup(argc, argv);
#endif

	// server communication
	uarthw_init();			// first hardware
	provider_t *serial = serial_init();	// then logic layer

	// now prepare for terminal etc
	// (note: in the future the assign parameter could be used
	// to distinguish different UARTs for example)
	void *epdata = serial->prov_assign(NAMEINFO_UNUSED_DRIVE, NULL);
	term_endpoint.provider = serial;
	term_endpoint.provdata = epdata;

	// and set as default
	provider_set_default(serial, epdata);

	// debug output via "terminal"
	term_set_endpoint(&term_endpoint);

	// init file handling (active open calls)
	file_init();
	// buffer structures
	buffer_init();
	// direct buffer handling
	direct_init();
	// relfile handling
	relfile_init();
	// init main channel handling
	channel_init();

	// before we init any busses, we init the runtime config code
	// note it gets the provider to register a listener for X command line params
	rtconfig_init(&term_endpoint);

	// bus init	
	// first the general bus (with bus counter)
	bus_init();		

	// this call initializes the device-specific hardware
	// e.g. IEEE488 and IEC busses on xs1541, plus SD card on petSD and so on
	// it also handles the interrupt initialization if necessary
	device_init();

#ifdef HAS_EEPROM
	// read bus-independent settings from non volatile memory
	nv_restore_common_config();
#endif

	// enable interrupts
	enable_interrupts();

	// sync with the server
	serial_sync();		

	// pull in command line config options from server
	// also send directory charset
	rtconfig_pullconfig(argc, argv);

#ifdef USE_FAT
	// register fat provider
	provider_register("FAT", &fat_provider);
	//provider_assign(0, "FAT", "/");		// might be overwritten when fetching X-commands
	//provider_assign(1, "FAT", "/");		// from the server, but useful for standalone-mode
#endif

	// show our version...
  	ListVersion();
	// ... and some system info
	term_printf((" %u Bytes free"), BytesFree());
	term_printf((", %d kHz"), FreqKHz());
#ifdef __AVR__
	fuse_info();
#endif
	term_putcrlf();
	term_putcrlf();


	while (1)  			// Mainloop-Begin
	{
		// keep data flowing on the serial line
		main_delay();

		if (!is_locked) 
			device_loop();

		// send out log messages
		term_flush();
	}
}
예제 #23
0
파일: main.c 프로젝트: Karlinde/Lagerrobot
int main(void) {
	// Disable watchdog reset timer to prevent continious resets
	wdt_disable();
	MCUSR = 0;
	can_start = 0;
	
	uint8_t status;
	arm_coordinate current_position;

	servo_init();
	bus_init(BUS_ADDRESS_ARM);

	bus_register_receive(0, emergency_handler);

	bus_register_receive(1, control_claw);

	bus_register_receive(2, object_pickup);
	bus_register_receive(3, object_pickup);
	bus_register_receive(4, object_pickup);
	bus_register_receive(5, object_pickup);

	bus_register_receive(6, manual_target);
	bus_register_receive(7, manual_target);
	bus_register_receive(8, manual_target);
	bus_register_receive(9, manual_target);
	bus_register_receive(10, manual_target);

	bus_register_receive(11, update_manual_control);

	bus_register_receive(12, object_return);
	bus_register_receive(13, predefined_positions);

	

	// Wait for communication unit to say we can continue initialising
	/*while (!can_start) {
		// Delay is needed when looping flags such as this
		_delay_us(1);
	}*/
	
	// Wait for servos to power on before setting initial parameters
	_delay_ms(100);
	arm_init();

	_delay_ms(1000);

	// Make sure claw is open and arm is in a well defined state
	arm_claw_open();
	arm_resting_position();

	// XXX: Trick system into thinking we have reached a pickup station
	//while (bus_transmit(BUS_ADDRESS_SENSOR, 9, 1));
	//object_side = LEFT;

	for (;;) {
		if (object_grab) {
			status = arm_move_to_coordinate(object_position);

			switch (status) {
				case 0:
					// Save position for when dropping off object
					last_object_position = object_position;

					// Perform movement to coordinate
					arm_move_perform_block();

					// Wait for arm to stabilize
					_delay_ms(500);

					// Grip object and return to resting position
					if (arm_claw_close()) {
						display(0, "Picked object");
						arm_resting_position();

						has_object = 1;

						// Send command that arm picked up object to chassis
						while (bus_transmit(BUS_ADDRESS_CHASSIS, 2, 0));
					} else {
						display(0, "Failed pickup");
						arm_resting_position();
						arm_claw_open();

						has_object = 0;

						// Send command that no object was picked up object to chassis
						while (bus_transmit(BUS_ADDRESS_CHASSIS, 2, 2));
					}
					break;
				case 1:
					display(0, "Invalid coordinate");
					break;
				case 2:
					display(0, "No P found");
					break;
				default:
					display(0, "Error %u", status);
			}
			object_grab = 0;
		} else if (object_drop_off) {
			// Move to the position where object was picked up
			status = arm_move_to_coordinate(last_object_position);

			switch (status) {
				case 0:
					// Perform movement to coordinate
					arm_move_perform_block();

					// Wait for arm to stabilize
					_delay_ms(500);

					// Leave object and return to resting position
					if (arm_claw_open()) {
						display(0, "Left object");
						arm_resting_position();
						has_object = 0;
					} else {
						display(0, "Left no object");
						arm_resting_position();
						has_object = 1;
					}

					// Send command that arm is done to chassis
					while (bus_transmit(BUS_ADDRESS_CHASSIS, 2, 1));
					break;
				case 1:
					display(0, "Invalid coordinate");
					break;
				case 2:
					display(0, "No P found");
					break;
				default:
					display(0, "Error %u", status);
			}
			object_drop_off = 0;
		} else if (has_manual_target) {
			display(1, "%d,%d,%d",
				manual_target_position.x,
				manual_target_position.y,
				(uint16_t)(manual_target_position.angle * 1000));

			status = arm_move_to_coordinate(manual_target_position);

			if (status) {
				display(0, "Error %u", status);
			} else {
				arm_move_perform_block();
			}

			has_manual_target = 0;
		} else if (manual_control_state) {
			// Update reference position when we start manual movement
			if (manual_control_state == 2) {
				arm_position(&manual_control_reference);
				manual_control_state = 1;
			}

			manual_control_reference.x += manual_control_change.x;
			manual_control_reference.y += manual_control_change.y;
			manual_control_reference.angle += manual_control_change.angle;

			if (!arm_move_to_coordinate(manual_control_reference)) {
				//arm_move_perform_block();
				arm_move_perform();
				_delay_ms(100);
			}
		} else if (manual_control_claw) {
			if (manual_control_claw == 1) {
				display(0, "Claw close");
				arm_claw_close();
			} else {
				display(0, "Claw open");
				arm_claw_open();
			}
			manual_control_claw = 0;
		} else if (predefined_position_move) {
			switch (predefined_position_move) {
				case 1:
					arm_resting_position();
					break;
			}
			predefined_position_move = 0;
		}
	}
}
/*---------------------------------------------------------------------------*/
int
main(void)
{

  /* Hardware initialization */
  bus_init();//ʱÖÓ³õʼ»¯
  rtimer_init();//¼ÆʱÆ÷³õʼ»¯

  /* model-specific h/w init. */
  io_port_init();

  /* Init LEDs here */
  leds_init();//LED³õʼ»¯
  /*LEDS_GREEN indicate LEDs Init finished*/
  fade(LEDS_GREEN);

  /* initialize process manager. */
  process_init();//½ø³Ì¹ÜÀí³õʼ»¯

  /* Init UART0
   * Based on the EJOY MCU CC2430 Circuit Design
   *  */
  uart0_init();//UART0´®¿Ú³õʼ»¯

#if DMA_ON
  dma_init();//DMA³õʼ»¯
#endif

#if SLIP_ARCH_CONF_ENABLE
  /* On cc2430, the argument is not used */
  slip_arch_init(0);//SLIP³õʼ»¯
#else
  uart1_set_input(serial_line_input_byte);
  serial_line_init();
#endif

  PUTSTRING("##########################################\n");
  putstring(CONTIKI_VERSION_STRING "\n");
//  putstring(SENSINODE_MODEL " (CC24");
  puthex(((CHIPID >> 3) | 0x20));
  putstring("-" FLASH_SIZE ")\n");

#if STARTUP_VERBOSE
#ifdef HAVE_SDCC_BANKING
  PUTSTRING("  With Banking.\n");
#endif /* HAVE_SDCC_BANKING */
#ifdef SDCC_MODEL_LARGE
  PUTSTRING("  --model-large\n");
#endif /* SDCC_MODEL_LARGE */
#ifdef SDCC_MODEL_HUGE
  PUTSTRING("  --model-huge\n");
#endif /* SDCC_MODEL_HUGE */
#ifdef SDCC_STACK_AUTO
  PUTSTRING("  --stack-auto\n");
#endif /* SDCC_STACK_AUTO */

  PUTCHAR('\n');

  PUTSTRING(" Net: ");
  PUTSTRING(NETSTACK_NETWORK.name);
  PUTCHAR('\n');
  PUTSTRING(" MAC: ");
  PUTSTRING(NETSTACK_MAC.name);
  PUTCHAR('\n');
  PUTSTRING(" RDC: ");
  PUTSTRING(NETSTACK_RDC.name);
  PUTCHAR('\n');

  PUTSTRING("##########################################\n");
#endif

  watchdog_init();//¿´ÃŹ·³õʼ»¯

  /* Initialise the cc2430 RNG engine. */
  random_init(0);//Ëæ»úÊýÉú³ÉÆ÷³õʼ»¯

  /* start services */
  process_start(&etimer_process, NULL);//
  ctimer_init();//ctimer³õʼ»¯

  /* initialize the netstack */
  netstack_init();//ÍøÂçµ×²ãÕ»³õʼ»¯
  set_rime_addr();//rimeµØÖ·ÉèÖÃ

//there is no sensor for us maintenance
#if BUTTON_SENSOR_ON || ADC_SENSOR_ON
  process_start(&sensors_process, NULL);
  sensinode_sensors_activate();
#endif

//IPV6,YES!
#if UIP_CONF_IPV6
  memcpy(&uip_lladdr.addr, &rimeaddr_node_addr, sizeof(uip_lladdr.addr));
  queuebuf_init();
  process_start(&tcpip_process, NULL);
//DISCO
#if DISCO_ENABLED
  process_start(&disco_process, NULL);
#endif /* DISCO_ENABLED */
//VIZTOOL
#if VIZTOOL_CONF_ON
  process_start(&viztool_process, NULL);
#endif

#if (!UIP_CONF_IPV6_RPL)
  {
    uip_ipaddr_t ipaddr;
    uip_ip6addr(&ipaddr, 0x2001, 0x630, 0x301, 0x6453, 0, 0, 0, 0);
    uip_ds6_set_addr_iid(&ipaddr, &uip_lladdr);
    uip_ds6_addr_add(&ipaddr, 0, ADDR_TENTATIVE);
  }
#endif /* UIP_CONF_IPV6_RPL */
#endif /* UIP_CONF_IPV6 */

  /*
   * Acknowledge the UART1 RX interrupt
   * now that we're sure we are ready to process it
   *
   * We don't need it. by MW
   */
//  model_uart_intr_en();

  energest_init();
  ENERGEST_ON(ENERGEST_TYPE_CPU);

  fade(LEDS_RED);

#if BATMON_CONF_ON
  process_start(&batmon_process, NULL);
#endif

  autostart_start(autostart_processes);

  watchdog_start();

  while(1) {
    do {
      /* Reset watchdog and handle polls and events */
      watchdog_periodic();

      /**/
#if !CLOCK_CONF_ACCURATE
      if(sleep_flag) {
        if(etimer_pending() &&
            (etimer_next_expiration_time() - count - 1) > MAX_TICKS) { /*core/sys/etimer.c*/
          etimer_request_poll();
        }
        sleep_flag = 0;
      }
#endif
      r = process_run();
    } while(r > 0);
#if SHORTCUTS_CONF_NETSTACK
    len = NETSTACK_RADIO.pending_packet();
    if(len) {
      packetbuf_clear();
      len = NETSTACK_RADIO.read(packetbuf_dataptr(), PACKETBUF_SIZE);
      if(len > 0) {
        packetbuf_set_datalen(len);
        NETSTACK_RDC.input();
      }
    }
#endif

#if LPM_MODE
#if (LPM_MODE==LPM_MODE_PM2)
    SLEEP &= ~OSC_PD;            /* Make sure both HS OSCs are on */
    while(!(SLEEP & HFRC_STB));  /* Wait for RCOSC to be stable */
    CLKCON |= OSC;               /* Switch to the RCOSC */
    while(!(CLKCON & OSC));      /* Wait till it's happened */
    SLEEP |= OSC_PD;             /* Turn the other one off */
#endif /* LPM_MODE==LPM_MODE_PM2 */

    /*
     * Set MCU IDLE or Drop to PM1. Any interrupt will take us out of LPM
     * Sleep Timer will wake us up in no more than 7.8ms (max idle interval)
     */
    SLEEP = (SLEEP & 0xFC) | (LPM_MODE - 1);

#if (LPM_MODE==LPM_MODE_PM2)
    /*
     * Wait 3 NOPs. Either an interrupt occurred and SLEEP.MODE was cleared or
     * no interrupt occurred and we can safely power down
     */
    __asm
      nop
      nop
      nop
    __endasm;

    if (SLEEP & SLEEP_MODE0) {
#endif /* LPM_MODE==LPM_MODE_PM2 */

      ENERGEST_OFF(ENERGEST_TYPE_CPU);
      ENERGEST_ON(ENERGEST_TYPE_LPM);

      /* We are only interested in IRQ energest while idle or in LPM */
      ENERGEST_IRQ_RESTORE(irq_energest);

      /* Go IDLE or Enter PM1 */
      PCON |= IDLE;

      /* First instruction upon exiting PM1 must be a NOP */
      __asm
        nop
      __endasm;

      /* Remember energest IRQ for next pass */
      ENERGEST_IRQ_SAVE(irq_energest);

      ENERGEST_ON(ENERGEST_TYPE_CPU);
      ENERGEST_OFF(ENERGEST_TYPE_LPM);

#if (LPM_MODE==LPM_MODE_PM2)
      SLEEP &= ~OSC_PD;            /* Make sure both HS OSCs are on */
      while(!(SLEEP & XOSC_STB));  /* Wait for XOSC to be stable */
      CLKCON &= ~OSC;              /* Switch to the XOSC */
      /*
       * On occasion the XOSC is reported stable when in reality it's not.
       * We need to wait for a safeguard of 64us or more before selecting it
       */
      clock_delay(10);
      while(CLKCON & OSC);         /* Wait till it's happened */
    }
#endif /* LPM_MODE==LPM_MODE_PM2 */
#endif /* LPM_MODE */
  }
}