int main(int argc, char* argv[]) {
	// Initialize
	SharedVariable v;

	if (wiringPiSetup() == -1) {
		printf("Failed to setup wiringPi.");
		return 1; 
	}

	init_shared_variable(&v);
	init_sensors(&v);

	pthread_t t_ultrasound, t_irled, t_linefollow,t_keypress,t_socket;
			  
		// Create sensing threads
		thread_create(ultrasound);
		thread_create(irled);
		thread_create(linefollow);
		thread_create(keypress);		
		thread_create(socket);		
		// Wait until all threads finish
		thread_join(socket);
		thread_join(ultrasound);
		thread_join(irled);
		thread_join(linefollow);	
		thread_join(keypress);

	return 0;
}
Example #2
0
/* main function */
int main(void)
{
    /* ============================== */
    /* initialization =============== */
    /* ============================== */
    
    WDT_EnableAndSetTimeout(WDT_PER_512CLK_gc);

    /* set up LED pins */
    init_leds();

    /* set up I2C as slave */
    init_twi();

    /* set up our clocks */
    init_clock();
    
    /* set up sensors */
    init_sensors();

    /* set up motors */
    init_motors();

    /* set up crude digital outputs */
    init_digout();

    /* Flash all the LEDs for two and a half seconds to make sure
     * they're hooked up */
    led_orders->behavior = LED_BEHAVIOR_TIMED;
    led_orders->time = 4000;
    led_error1->behavior = LED_BEHAVIOR_TIMED;
    led_error1->time = 6000;
    led_error2->behavior = LED_BEHAVIOR_TIMED;
    led_error2->time = 8000;
    led_mota->behavior = LED_BEHAVIOR_TIMED;
    led_mota->time = 10000;
    led_motb->behavior = LED_BEHAVIOR_TIMED;
    led_motb->time = 12000;

    /* motA.duty = 4000; */
    /* motA.direction = 1; */
    /* motB.duty = 16000; */
    /* motB.direction = 1; */

    /* enable interrupts - things start ticking now */
    sei();


    /* ============================== */
    /* main loop ==================== */
    /* ============================== */
    for(;;)
    {
        _delay_us(10);
        WDT_Reset();
    }
}
int main(int argc, char* argv[]) {
	SharedVariable v;

	int runningTimeInSec = 10;
	if (argc == 2) {
		runningTimeInSec = atoi(argv[1]);
	}

	if (wiringPiSetup() == -1) {
		printf("Failed to setup wiringPi.");
		return 1; 
	}

	printf("start");
	// Initialize for the interfaces provided
	signal(SIGINT, signal_handler);
	init_deferred_buffer(1024*1024); // 1MB
	init_userspace_governor();
	init_workload();
	printf("stop");

	// Initializers that you need to implement
	init_shared_variable(&v);
	init_sensors(&v);
	learn_workloads(&v);

	printf("Init scheduler start");
	// Init scheduler
	int aliveTasks[NUM_TASKS];
	init_scheduler(runningTimeInSec);
	set_by_max_freq(); // reset to the max freq

	printf("Init scheduler stop");
	printDBG("Start Scheduling with %d threads\n", NUM_TASKS);
	TaskSelection sel;
	long long idleTime;
	while (v.bProgramExit != 1) {
		// 1. Prepare tasks
		idleTime = prepare_tasks(aliveTasks, &v);
		if (idleTime < 0)
			break;

		// 2. Select a process: You need to implement.
		sel = select_task(&v, aliveTasks, idleTime); 
		if (sel.task < 0)
			break;

		// 3. Run the selected task
		execute_task(sel);
	}

	finish_workload();
	release_buffer(fileno(stdout));
	printf("Scheduler program finished.\n");

	return 0;
}
Example #4
0
/* Initialisation */
void rcx_init (void) {
    init_timer(&async, &dispatch[0]);
    init_power();
    systime_init();
    init_sensors();
    //init_motors
    init_buttons(); // Buttons & display pins
    init_serial(0, 0, 1, 1);
}
Example #5
0
 SensorSimulator(rng_t *rng):
         rng(rng),
         filter(new KalmanFilter<real_t>(KINSTATE_SIZE, 
                                         MAX_READINGS,
                                         new KinematicPredictor<real_t>(
                                                 ACCEL_PROCESS_VARIANCE, 
                                                 OMEGA_PROCESS_VARIANCE))), 
         t(0) {
     init_sensors();
     init_state();
 }
Example #6
0
int main(void) {
    WDTCTL = WDTPW | WDTHOLD;	// Stop watchdog timer

    BCSCTL1 = CALBC1_8MHZ;    // 8Mhz calibration for clock
    DCOCTL  = CALDCO_8MHZ;

    init_sensors();
    init_wdt();
    init_motors();
    init_lastData();

    _bis_SR_register(GIE+LPM0_bits);	//enable general interrupts and power down CPU
}
Example #7
0
 SensorSimulator():
         // random number gen for fake sensor noise
         rng(new rng_t(11937294775LL)),
         // new kalman filter
         filter(new KalmanFilter<real_t>(KINSTATE_SIZE, 
                                         MAX_READINGS,
                                         // Predictor for advancing state:
                                         new KinematicPredictor<real_t>(
                                                 ACCEL_PROCESS_VARIANCE, 
                                                 OMEGA_PROCESS_VARIANCE))), 
         t(0) {
     init_sensors();
     init_state();
 }
int main(int argc, char* argv[]) {
    // Initialize
    SharedVariable v;

    if (wiringPiSetup() == -1) {
        printf("Failed to setup wiringPi.");
        return 1;
    }

    init_shared_variable(&v);
    init_sensors(&v);

    pthread_t t_button,
              t_twocolor,
              t_temp,
              t_track,
              t_shock,
              t_rgbcolor,
              t_aled,
              t_buzzer;

    while (v.bProgramExit != 1) {
        // Create sensing threads
        thread_create(button);
        thread_create(twocolor);
        thread_create(temp);
        thread_create(track);
        thread_create(shock);
        thread_create(rgbcolor);
        thread_create(aled);
        thread_create(buzzer);

        // Wait until all threads finish
        thread_join(button);
        thread_join(twocolor);
        thread_join(temp);
        thread_join(track);
        thread_join(shock);
        thread_join(rgbcolor);
        thread_join(aled);
        thread_join(buzzer);

        delay(1);
    }

    printf("Program finished.\n");

    return 0;
}
Example #9
0
/***************************************************************************
 * int main
 * Parses command line. Format is:
 *	argv[0] [-v] bin_file
 *
 * options:
 *	-v	Verbose mode. Prints text output rather than raw output.
 *
 *--------------------------------------------------------------------------
 * To go into man page:
 * Name:	emu-lejosrun - Emulate lejos RCX code in Unix
 *
 * Synosis:	emu-lejosrun [-v] bin_file
 *
 * Description:	Executes a binary file created by the lejos compiler within
 *		Unix rather than in the RCX environment. The Java byte-codes
 *		are executed here, and their actions are listed rather than
 *		executed as they would be on the real RCX device.
 *
 * Options:	-v	Verbose mode. Normally the output is printed in raw
 *			mode. The actual hex values are printed. Using this
 *			option displays more user-friendly output.
 *--------------------------------------------------------------------------
 ***************************************************************************/
int main (int argc, char *argv[])
{
	int	c;
	char	*file = argv[argc - 1];

	/* Process any options. */
	while(--argc > 0 && (*++argv)[0] == '-')
		while((c = *++argv[0]) != 0)
			switch (c) {
			case 'v':
				verbose = 1;
				break;
			default:
				printf("%s: unknown option %c\n",
					argv[0], c);
				exit(1);
			}
	if (argc != 1)
	{
		printf ("%s runs a binary dumped by the linker.\n", argv[0]);
		printf ("Use: %s [-v] binary_file\n", argv[0]);
		exit (1);
	}
#if DEBUG_STARTUP
	printf ("Reading binary %s\n", file);
#endif
	readBinary (file);
	if (gettimeofday(&gStart, NULL)) 
		perror("main: gettimeofday");
	timer_handler (SIGALRM);
	if (setitimer(ITIMER_REAL, &itimer, null) < 0)
	{
	  printf ("Failed to set interval timer\n");
	  exit(1);
	}

        init_sensors ();
        last_ad_time = get_sys_time();

	run();
	itimer.it_value.tv_usec = 0;
	setitimer(ITIMER_REAL, &itimer, null);
	signal(SIGALRM, SIG_DFL);
	exit(0);
} 
Example #10
0
int main() {
  openlog("smadom_auto_bl", LOG_PID | LOG_CONS, LOG_USER);
  syslog(LOG_INFO, "smadom_auto_bl server starting");
  printf("smadom_auto_bl starting....\n");
  init_sensors();
  printf("Initialed sensor's interfaces\n");
  init_equipments() ;
  printf("Initialed equipmen's interfaces\n");
  run_in_daemon();
  
  TIMES_LIGHT = 15;
  DELAY_LIGHT = 20;
  
  TIMES_BED_LIGHT_PERSON = 15;
  DELAY_BED_LIGHT_PERSON = 20;
  KEEP_BED_LIGHT = 3;
  void *arg;
  thread_auto_bed_light(arg);
}
void bios(void) {
    uart_start();
    pwm_setup(2);
    adc_start(1);
    twi_start();

    //Start sensors from robot.h
    init_sensors();

    //button code
    init_buttons();

    //set the CPU_POW led pin to high to show we have power
    DDRD |= (1<<CPU_POW);
    PORTD |= (1<<CPU_POW);

    //set the status leds as outputs
    DDRD |= (1<<stat_led1);
    DDRD |= (1<<stat_led2);

    //if this is my dev board, pull them low because the leds are cathode
    #if DEV
        PORTD &= ~(1<<stat_led1)
              & ~(1<<stat_led2);
    #endif

    #if DEBUG
        uart_sendint(BIOS_KEY);
        #if DEBUG_BEG
            uart_sendstr("0x01 - Hardware setup successful...");
            uart_sendstr("Bios complete...");
            uart_sendstr("Starting main code...");
        #endif
    #endif
    return;
}
Example #12
0
int main() {
  openlog("smadom_auto_tl", LOG_PID | LOG_CONS, LOG_USER);
  syslog(LOG_INFO, "smadom_auto_tl server starting");
  printf("smadom_auto_tl starting....\n");
  init_sensors();
  printf("Initialed sensor's interfaces\n");
  init_equipments() ;
  printf("Initialed equipmen's interfaces\n");
  run_in_daemon();
  
  TIMES_LIGHT = 15;
  DELAY_LIGHT = 20;
  
  TIMES_SEAT_PERSON = 15;
  DELAY_SEAT_PERSON = 20;
  KEEP_TABLE_LIGHT= 10;
  void *arg;
  thread_auto_table_light(arg);
//   auto_table_light();
//   while (tmp_running) {
//     sleep (1);
//     printf("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
//   }
}
Example #13
0
int main()
{
	init_sensors();

	int SET_POINT_VALUE = get_int_from_user("SetPnt=?", 20, 5);
	int END_POINT_VALUE = get_int_from_user("EndPnt=?", 145, 1);

	wait_with_message("Press B");
	count_down(2);

	
	int front = 0;
	int left = 0;
	int right = 0;
	int balance = 0;

	int left_speed = 0;
	int right_speed = 0;

	int set_point = 0;

	while(1)
	{
		left = analog_read(6);
		right = analog_read(5);
		front = analog_read(7);
		
		balance = 0;
		if (left > 20 || right > 20)
		{
			balance = right - left - 20;
		}

		if(front < SET_POINT_VALUE)
		{
			left_speed = 110 - (1.0 * 0.54838709677419354838709677419355 * front);
			right_speed = 110 - (1.0 * 0.54838709677419354838709677419355 * front);
		}
		else
		{
			while(left_speed > 25 || right_speed > 25)
			{
				left_speed--;
				right_speed--;
				set_motors(left_speed + balance,right_speed - balance);
				play_frequency(200, 50, 14);
			}

		}

		if (set_point == 0 && front > END_POINT_VALUE)
		{
			set_point = 1;
			set_motors(25,25);
			
		}
		else
		{
			set_motors(left_speed + balance,right_speed - balance);
		}

		if (set_point == 1 && front < END_POINT_VALUE)
		{
			break;
		}


	}


	halt();

	clear();
	print("f=");
	print_long(front);

	// end
	while(1);
}
Example #14
0
/*****************************************************************************
*  Main Control Loop
*
*  
*****************************************************************************/
int main(void)
{
  unsigned char i;
  unsigned char arptimer=0;

	// PORTB PB5 als Ausgang (in use LED)
	DDRB=(1<<PB5);
	PORTB=(1<<PB5);

	init_sensors();

  // init NIC device driver
  nic_init();

  // init uIP
  uip_init();

  // init app
  example1_init();

  // init ARP cache
  uip_arp_init();

  // init periodic timer
  initTimer();
  
  sei();

	// initialisierendes lesen der Temperatur(en)
	read_temp_sensors();

  while(1)
  {

	if(minInt==1){
		minInt=0;
		read_temp_sensors();
	}
    // look for a packet
    uip_len = nic_poll();
    if(uip_len == 0)
    {
      // if timed out, call periodic function for each connection
      //if(timerCounter > TIMERCOUNTER_PERIODIC_TIMEOUT)
	  if(tInt)
      {
        
		tInt = 0;
		//timerCounter = 0;
        
        for(i = 0; i < UIP_CONNS; i++)
        {
          uip_periodic(i);
		
          // transmit a packet, if one is ready
          if(uip_len > 0)
          {
            uip_arp_out();
            nic_send();
          }
        }

        /* Call the ARP timer function every 10 seconds. */
        if(++arptimer == 20)
        {	
          uip_arp_timer();
          arptimer = 0;
        }
      }
    }
    else  // packet received
    {
      // process an IP packet
      if(BUF->type == htons(UIP_ETHTYPE_IP))
      {
        // add the source to the ARP cache
        // also correctly set the ethernet packet length before processing
        uip_arp_ipin();
        uip_input();

        // transmit a packet, if one is ready
        if(uip_len > 0)
        {
          uip_arp_out();
          nic_send();
        }
      }
      // process an ARP packet
      else if(BUF->type == htons(UIP_ETHTYPE_ARP))
      {
        uip_arp_arpin();

        // transmit a packet, if one is ready
        if(uip_len > 0)
          nic_send();
      }
    }
  }

  return 1;
}
Example #15
0
File: moo.c Project: aelog/umichmoo
int main(void)
{
  //*******************************Timer setup**********************************
  WDTCTL = WDTPW + WDTHOLD;            // Stop Watchdog Timer

  P1SEL = 0;
  P2SEL = 0;

  P1IE = 0;
  P1IFG = 0;
  P2IFG = 0;

  DRIVE_ALL_PINS // set pin directions correctly and outputs to low.

  // Check power on bootup, decide to receive or sleep.
  if(!is_power_good())
    sleep();

  RECEIVE_CLOCK;

#if DEBUG_PINS_ENABLED
#if USE_2618
  DEBUG_PIN5_LOW;
#endif
#endif

#if ENABLE_SLOTS
  // setup int epc
  epc = ackReply[2]<<8;
  epc |= ackReply[3];

  // calculate RN16_1 table
  for (Q = 0; Q < 16; Q++)
  {
    rn16 = epc^Q;
    lfsr();

    if (Q > 8)
    {
      RN16[(Q<<1)-9] = __swap_bytes(rn16);
      RN16[(Q<<1)-8] = rn16;
    }
    else
    {
      RN16[Q] = rn16;
    }
  }
#endif

  TACTL = 0;

  asm("MOV #0000h, R9");
  // dest = destorig;

#if READ_SENSOR
	init_sensors();
#endif

#if !(ENABLE_SLOTS)
  queryReplyCRC = crc16_ccitt(&queryReply[0],2);
  queryReply[3] = (unsigned char)queryReplyCRC;
  queryReply[2] = (unsigned char)__swap_bytes(queryReplyCRC);
#endif

#if SENSOR_DATA_IN_ID
  // this branch is for sensor data in the id
  state = STATE_READ_SENSOR;
  timeToSample++;
#else
  ackReplyCRC = crc16_ccitt(&ackReply[0], 14);
  ackReply[15] = (unsigned char)ackReplyCRC;
  ackReply[14] = (unsigned char)__swap_bytes(ackReplyCRC);
#endif

#if ENABLE_SESSIONS
  initialize_sessions();
#endif

  state = STATE_READY;

  setup_to_receive();

  while (1)
  {

    // TIMEOUT!  reset timer
    if (TAR > 0x256 || delimiterNotFound)   // was 0x1000
    {
      if(!is_power_good()) {
        sleep();
      }

#if SENSOR_DATA_IN_ID
    // this branch is for sensor data in the id
      if ( timeToSample++ == 10 ) {
        state = STATE_READ_SENSOR;
        timeToSample = 0;
      }
#elif SENSOR_DATA_IN_READ_COMMAND
      if ( timeToSample++ == 10 ) {
        state = STATE_READ_SENSOR;
        timeToSample = 0;
      }
#else
#if !(ENABLE_READS)
    if(!is_power_good())
        sleep();
#endif
    inInventoryRound = 0;
    state = STATE_READY;

#endif

#if ENABLE_SESSIONS
    handle_session_timeout();
#endif

#if ENABLE_SLOTS
    if (shift < 4)
        shift += 1;
    else
        shift = 0;
#endif

      setup_to_receive();
    }

    switch (state)
    {
      case STATE_READY:
      {
        inInventoryRound = 0;
        //////////////////////////////////////////////////////////////////////
        // process the QUERY command
        //////////////////////////////////////////////////////////////////////
        if ( bits == NUM_QUERY_BITS  && ( ( cmd[0] & 0xF0 ) == 0x80 ) )
        {
          handle_query(STATE_REPLY);
          setup_to_receive();
        }
        //////////////////////////////////////////////////////////////////////
        // process the SELECT command
        //////////////////////////////////////////////////////////////////////
        // @ short distance has slight impact on performance
        else if ( bits >= 44  && ( ( cmd[0] & 0xF0 ) == 0xA0 ) )
        {
          handle_select(STATE_READY);
          delimiterNotFound = 1;
        } // select command
        //////////////////////////////////////////////////////////////////////
        // got >= 22 bits, and it's not the beginning of a select. just reset.
        //////////////////////////////////////////////////////////////////////
        else if ( bits >= MAX_NUM_QUERY_BITS && ( ( cmd[0] & 0xF0 ) != 0xA0 ) )
        {
          do_nothing();
          state = STATE_READY;
          delimiterNotFound = 1;
        }
        break;
      }
      case STATE_ARBITRATE:
      {
        //////////////////////////////////////////////////////////////////////
        // process the QUERY command
        //////////////////////////////////////////////////////////////////////
        if ( bits == NUM_QUERY_BITS  && ( ( cmd[0] & 0xF0 ) == 0x80 ) )
        {
          handle_query(STATE_REPLY);
          setup_to_receive();
        }
        //////////////////////////////////////////////////////////////////////
        // got >= 22 bits, and it's not the beginning of a select. just reset.
        //////////////////////////////////////////////////////////////////////
        //else if ( bits >= NUM_QUERY_BITS )
        else if ( bits >= MAX_NUM_QUERY_BITS && ( ( cmd[0] & 0xF0 ) != 0xA0 ) )
        {
          do_nothing();
          state = STATE_READY;
          delimiterNotFound = 1;
        }
        // this state handles query, queryrep, queryadjust, and select commands.
        //////////////////////////////////////////////////////////////////////
        // process the QUERYREP command
        //////////////////////////////////////////////////////////////////////
        else if ( bits == NUM_QUERYREP_BITS && ( ( cmd[0] & 0x06 ) == 0x00 ) )
        {
          handle_queryrep(STATE_REPLY);
          delimiterNotFound = 1;
        } // queryrep command
        //////////////////////////////////////////////////////////////////////
        // process the QUERYADJUST command
        //////////////////////////////////////////////////////////////////////
        else if ( bits == NUM_QUERYADJ_BITS  && ( ( cmd[0] & 0xF8 ) == 0x48 ) )
        {
          handle_queryadjust(STATE_REPLY);
          setup_to_receive();
        } // queryadjust command
        //////////////////////////////////////////////////////////////////////
        // process the SELECT command
        //////////////////////////////////////////////////////////////////////
        // @ short distance has slight impact on performance
        else if ( bits >= 44  && ( ( cmd[0] & 0xF0 ) == 0xA0 ) )
        {
          handle_select(STATE_READY);
          delimiterNotFound = 1;
        } // select command

      break;
      }

      case STATE_REPLY:
      {
        // this state handles query, query adjust, ack, and select commands
        ///////////////////////////////////////////////////////////////////////
        // process the ACK command
        ///////////////////////////////////////////////////////////////////////
        if ( bits == NUM_ACK_BITS  && ( ( cmd[0] & 0xC0 ) == 0x40 ) )
        {
#if ENABLE_READS
          handle_ack(STATE_ACKNOWLEDGED);
          setup_to_receive();
#elif SENSOR_DATA_IN_ID
          handle_ack(STATE_ACKNOWLEDGED);
          delimiterNotFound = 1; // reset
#else
          // this branch for hardcoded query/acks
          handle_ack(STATE_ACKNOWLEDGED);
          //delimiterNotFound = 1; // reset
          setup_to_receive();
#endif
        }
        //////////////////////////////////////////////////////////////////////
        // process the QUERY command
        //////////////////////////////////////////////////////////////////////
        if ( bits == NUM_QUERY_BITS  && ( ( cmd[0] & 0xF0 ) == 0x80 ) )
        {
          // i'm supposed to stay in state_reply when I get this, but if I'm
          // running close to 1.8v then I really need to reset and get in the
          // sleep, which puts me back into state_arbitrate. this is complete
          // a violation of the protocol, but it sure does make everything
          // work better. - polly 8/9/2008
          handle_query(STATE_REPLY);
          setup_to_receive();
        }
        //////////////////////////////////////////////////////////////////////
        // process the QUERYREP command
        //////////////////////////////////////////////////////////////////////
        else if ( bits == NUM_QUERYREP_BITS && ( ( cmd[0] & 0x06 ) == 0x00 ) )
        {
			do_nothing();
			state = STATE_ARBITRATE;
			setup_to_receive();
        } // queryrep command
        //////////////////////////////////////////////////////////////////////
        // process the QUERYADJUST command
        //////////////////////////////////////////////////////////////////////
        else if ( bits == NUM_QUERYADJ_BITS  && ( ( cmd[0] & 0xF8 ) == 0x48 ) )
        {
          handle_queryadjust(STATE_REPLY);
          delimiterNotFound = 1;
        } // queryadjust command
        //////////////////////////////////////////////////////////////////////
        // process the SELECT command
        //////////////////////////////////////////////////////////////////////
        else if ( bits >= 44  && ( ( cmd[0] & 0xF0 ) == 0xA0 ) )
        {
          handle_select(STATE_READY);
          delimiterNotFound = 1;
        } // select command
        else if ( bits >= MAX_NUM_QUERY_BITS && ( ( cmd[0] & 0xF0 ) != 0xA0 ) &&
                ( ( cmd[0] & 0xF0 ) != 0x80 ) )
        {
          do_nothing();
          state = STATE_READY;
          delimiterNotFound = 1;
        }
        break;
      }
      case STATE_ACKNOWLEDGED:
      {
        // responds to query, ack, request_rn cmds
        // takes action on queryrep, queryadjust, and select cmds
        /////////////////////////////////////////////////////////////////////
        // process the REQUEST_RN command
        //////////////////////////////////////////////////////////////////////
        if ( bits >= NUM_REQRN_BITS && ( cmd[0] == 0xC1 ) )
        {
#if 1
          handle_request_rn(STATE_OPEN);
          setup_to_receive();
#else
          handle_request_rn(STATE_READY);
          delimiterNotFound = 1;
#endif
        }

#if 1
        //////////////////////////////////////////////////////////////////////
        // process the QUERY command
        //////////////////////////////////////////////////////////////////////
        if ( bits == NUM_QUERY_BITS  && ( ( cmd[0] & 0xF0 ) == 0x80 ) )
        {
          handle_query(STATE_REPLY);
          delimiterNotFound = 1;
        }
        ///////////////////////////////////////////////////////////////////////
        // process the ACK command
        ///////////////////////////////////////////////////////////////////////
        // this code doesn't seem to get exercised in the real world. if i ever
        // ran into a reader that generated an ack in an acknowledged state,
        // this code might need some work.
        //else if ( bits == 20  && ( ( cmd[0] & 0xC0 ) == 0x40 ) )
        else if ( bits == NUM_ACK_BITS  && ( ( cmd[0] & 0xC0 ) == 0x40 ) )
        {
          handle_ack(STATE_ACKNOWLEDGED);
          setup_to_receive();
        }
        //////////////////////////////////////////////////////////////////////
        // process the QUERYREP command
        //////////////////////////////////////////////////////////////////////
        else if ( bits == NUM_QUERYREP_BITS && ( ( cmd[0] & 0x06 ) == 0x00 ) )
        {
          // in the acknowledged state, rfid chips don't respond to queryrep
          // commands
          do_nothing();
          state = STATE_READY;
          delimiterNotFound = 1;
        } // queryrep command

        //////////////////////////////////////////////////////////////////////
        // process the QUERYADJUST command
        //////////////////////////////////////////////////////////////////////
        else if ( bits == NUM_QUERYADJ_BITS  && ( ( cmd[0] & 0xF8 ) == 0x48 ) )
        {
          do_nothing();
          state = STATE_READY;
          delimiterNotFound = 1;
        } // queryadjust command
        //////////////////////////////////////////////////////////////////////
        // process the SELECT command
        //////////////////////////////////////////////////////////////////////
        else if ( bits >= 44  && ( ( cmd[0] & 0xF0 ) == 0xA0 ) )
        {
          handle_select(STATE_READY);
          delimiterNotFound = 1;
        } // select command
        //////////////////////////////////////////////////////////////////////
        // process the NAK command
        //////////////////////////////////////////////////////////////////////
        else if ( bits >= 10 && ( cmd[0] == 0xC0 ) )
        {
          do_nothing();
          state = STATE_ARBITRATE;
          delimiterNotFound = 1;
        }
        //////////////////////////////////////////////////////////////////////
        // process the READ command
        //////////////////////////////////////////////////////////////////////
        // warning: won't work for read addrs > 127d
        if ( bits == NUM_READ_BITS && ( cmd[0] == 0xC2 ) )
        {
          handle_read(STATE_ARBITRATE);
          state = STATE_ARBITRATE;
          delimiterNotFound = 1 ;
        }
        // FIXME: need write, kill, lock, blockwrite, blockerase
        //////////////////////////////////////////////////////////////////////
        // process the ACCESS command
        //////////////////////////////////////////////////////////////////////
        if ( bits >= 56  && ( cmd[0] == 0xC6 ) )
        {
          do_nothing();
          state = STATE_ARBITRATE;
          delimiterNotFound = 1 ;
        }
#endif
        else if ( bits >= MAX_NUM_READ_BITS )
        {
          state = STATE_ARBITRATE;
          delimiterNotFound = 1 ;
        }

#if 0
        // kills performance ...
        else if ( bits >= 44 )
        {
          do_nothing();
          state = STATE_ARBITRATE;
          delimiterNotFound = 1;
        }
#endif
        break;
      }
      case STATE_OPEN:
      {
        // responds to query, ack, req_rn, read, write, kill, access,
        // blockwrite, and blockerase cmds
        // processes queryrep, queryadjust, select cmds
        //////////////////////////////////////////////////////////////////////
        // process the READ command
        //////////////////////////////////////////////////////////////////////
        // warning: won't work for read addrs > 127d
        if ( bits == NUM_READ_BITS  && ( cmd[0] == 0xC2 ) )
        {
          handle_read(STATE_OPEN);
          // note: setup_to_receive() et al handled in handle_read
        }
        //////////////////////////////////////////////////////////////////////
        // process the REQUEST_RN command
        //////////////////////////////////////////////////////////////////////
        else if ( bits >= NUM_REQRN_BITS  && ( cmd[0] == 0xC1 ) )
        {
          handle_request_rn(STATE_OPEN);
          setup_to_receive();
         }
        //////////////////////////////////////////////////////////////////////
        // process the QUERY command
        //////////////////////////////////////////////////////////////////////
        if ( bits == NUM_QUERY_BITS  && ( ( cmd[0] & 0xF0 ) == 0x80 ) )
        {
          handle_query(STATE_REPLY);
          delimiterNotFound = 1;
        }
        //////////////////////////////////////////////////////////////////////
        // process the QUERYREP command
        //////////////////////////////////////////////////////////////////////
        else if ( bits == NUM_QUERYREP_BITS && ( ( cmd[0] & 0x06 ) == 0x00 ) )
        {
          do_nothing();
          state = STATE_READY;
          setup_to_receive();
        } // queryrep command
        //////////////////////////////////////////////////////////////////////
        // process the QUERYADJUST command
        //////////////////////////////////////////////////////////////////////
          else if ( bits == 9  && ( ( cmd[0] & 0xF8 ) == 0x48 ) )
        {
          do_nothing();
          state = STATE_READY;
          delimiterNotFound = 1;
        } // queryadjust command
        ///////////////////////////////////////////////////////////////////////
        // process the ACK command
        ///////////////////////////////////////////////////////////////////////
        else if ( bits == NUM_ACK_BITS  && ( ( cmd[0] & 0xC0 ) == 0x40 ) )
        {
          handle_ack(STATE_OPEN);
          delimiterNotFound = 1;
        }
        //////////////////////////////////////////////////////////////////////
        // process the SELECT command
        //////////////////////////////////////////////////////////////////////
        else if ( bits >= 44  && ( ( cmd[0] & 0xF0 ) == 0xA0 ) )
        {
          handle_select(STATE_READY);
          delimiterNotFound = 1;
        } // select command
        //////////////////////////////////////////////////////////////////////
        // process the NAK command
        //////////////////////////////////////////////////////////////////////
        else if ( bits >= 10 && ( cmd[0] == 0xC0 ) )
        {
          handle_nak(STATE_ARBITRATE);
          delimiterNotFound = 1;
        }

        break;
      }

    case STATE_READ_SENSOR:
      {
#if SENSOR_DATA_IN_READ_COMMAND
        read_sensor(&readReply[0], 8, null);
        // crc is computed in the read state
        RECEIVE_CLOCK;
        state = STATE_READY;
        delimiterNotFound = 1; // reset
#elif SENSOR_DATA_IN_ID
		uint8_t id;
		read_sensor(&ackReply[3], 8, &id);
		ackReply[2] = id;
        RECEIVE_CLOCK;
        ackReplyCRC = crc16_ccitt(&ackReply[0], 14);
        ackReply[15] = (unsigned char)ackReplyCRC;
        ackReply[14] = (unsigned char)__swap_bytes(ackReplyCRC);
        state = STATE_READY;
        delimiterNotFound = 1; // reset
#endif

        break;
      } // end case
    } // end switch

  } // while loop
}
Example #16
0
/**  This is where it all starts ++++++++++++++++++++++++++++++++++++++++++ 
 main is entered as a result of one of SEVERAL events:
  - Normal startup from press of reset button.
  - Battery inserted.
  - After DFU (Device Firmware Upgrade) at manufacturing Quality Assurance or user DFU.
  - WatchDogTimer expiration and its interrupt handler didn't feed new value.
  - Some error occured and
  - Spontenous unknown reset.
 All subsystems are initalized and any failures are noted and available later in init_status
 Since some events occur after tag is deployed and no one can see the LEDs the system continues operating.

 After initalizition (including setting up interrupts)
    we loop here calling app_sched_execute and sd_app_evt_wait 
*/
int main(void)
{
   // LEDs first (they're easy and cannot fail)  drivers/init/init.c
  init_leds();
  RED_LED_ON;

  if( init_log() ) { init_status |=LOG_FAILED_INIT; }
  else { NRF_LOG_INFO("LOG initalized \r\n"); } // subsequent initalizations assume log is working

  // start watchdog now in case program hangs up.
  // watchdog_default_handler logs error and resets the tag.
  init_watchdog(NULL);

  // Battery voltage initialization cannot fail under any reasonable circumstance.
  battery_voltage_init(); 
  vbat = getBattery();

  if( vbat < BATTERY_MIN_V ) { init_status |=BATTERY_FAILED_INIT; }
  else NRF_LOG_INFO("BATTERY initalized \r\n"); 

  if(init_sensors() == NRF_SUCCESS )
  {
    model_plus = true;
    NRF_LOG_INFO("Sensors initialized \r\n");  
  }

  // Init NFC ASAP in case we're waking from deep sleep via NFC (todo)
  // outputs ID:DEVICEID ,MAC:DEVICEADDR, SW:REVision
  set_nfc_callback(app_nfc_callback);
  if( init_nfc() ) { init_status |= NFC_FAILED_INIT; } 
  else { NRF_LOG_INFO("NFC init \r\n"); }

  pin_interrupt_init(); 

  if( pin_interrupt_enable(BSP_BUTTON_0, NRF_GPIOTE_POLARITY_TOGGLE, NRF_GPIO_PIN_PULLUP, button_press_handler) ) 
  {
    init_status |= BUTTON_FAILED_INIT;
  }

  // Initialize BLE Stack. Starts LFCLK required for timer operation.
  if( init_ble() ) { init_status |= BLE_FAILED_INIT; }
  bluetooth_configure_advertisement_type(STARTUP_ADVERTISEMENT_TYPE);
  bluetooth_tx_power_set(BLE_TX_POWER);
  bluetooth_configure_advertising_interval(ADVERTISING_INTERVAL_STARTUP);
  advertisement_delay = NRF_FICR->DEVICEID[0]&0x0F;

  // Priorities 2 and 3 are after SD timing critical events. 
  // 6, 7 after SD non-critical events.
  // Triggers ADC, so use 3. 
  ble_radio_notification_init(3,
                              NRF_RADIO_NOTIFICATION_DISTANCE_800US,
                              on_radio_evt);

  // If GATT is enabled BLE init inits peer manager which uses flash.
  // BLE init should handle insufficient space gracefully (i.e. erase flash and proceed). 
  // Flash must be initialized after softdevice. 
  if(flash_init())
  {
    NRF_LOG_ERROR("Failed to init flash \r\n");
  }
  size_t flash_space_remaining = 0;
  flash_free_size_get(&flash_space_remaining);
  NRF_LOG_INFO("Largest continuous space remaining %d bytes\r\n", flash_space_remaining);
  if(4000 > flash_space_remaining)
  {
    NRF_LOG_INFO("Flash space is almost used, running gc\r\n")
    flash_gc_run();
    flash_free_size_get(&flash_space_remaining);
    NRF_LOG_INFO("Continuous space remaining after gc %d bytes\r\n", flash_space_remaining);
  }
  else if (flash_record_get(FDS_FILE_ID, FDS_RECORD_ID, sizeof(tag_mode), &tag_mode))
  {
   NRF_LOG_INFO("Did not find mode in flash, is this first boot? \r\n");
  }
  else 
  {
    NRF_LOG_INFO("Loaded mode %d from flash\r\n", tag_mode);
  }

  if( init_rtc() ) { init_status |= RTC_FAILED_INIT; }
  else { NRF_LOG_INFO("RTC initialized \r\n"); }

  // Initialize lis2dh12 and BME280 - TODO: Differentiate LIS2DH12 and BME280 
  if (model_plus)    
  {
    lis2dh12_reset(); // Clear memory.
    
    // Enable Low-To-Hi rising edge trigger interrupt on nRF52 to detect acceleration events.
    if (pin_interrupt_enable(INT_ACC2_PIN, NRF_GPIOTE_POLARITY_LOTOHI, NRF_GPIO_PIN_NOPULL, lis2dh12_int2_handler) )
    {
      init_status |= ACC_INT_FAILED_INIT;
    }
    
    nrf_delay_ms(10); // Wait for LIS reboot.
    // Enable XYZ axes.
    lis2dh12_enable();
    lis2dh12_set_scale(LIS2DH12_SCALE);
    lis2dh12_set_sample_rate(LIS2DH12_SAMPLERATE_RAWv1);
    lis2dh12_set_resolution(LIS2DH12_RESOLUTION);

    lis2dh12_set_activity_interrupt_pin_2(LIS2DH12_ACTIVITY_THRESHOLD);
    NRF_LOG_INFO("Accelerometer configuration done \r\n");

    // oversampling must be set for each used sensor.
    bme280_set_oversampling_hum  (BME280_HUMIDITY_OVERSAMPLING);
    bme280_set_oversampling_temp (BME280_TEMPERATURE_OVERSAMPLING);
    bme280_set_oversampling_press(BME280_PRESSURE_OVERSAMPLING);
    bme280_set_iir(BME280_IIR);
    bme280_set_interval(BME280_DELAY);
    bme280_set_mode(BME280_MODE_NORMAL);
    NRF_LOG_INFO("BME280 configuration done \r\n");
  }

  // Enter stored mode after boot - or default mode if store mode was not found
  app_sched_event_put (&tag_mode, sizeof(&tag_mode), change_mode);
  
  // Initialize repeated timer for sensor read and single-shot timer for button reset
  if( init_timer(main_timer_id, APP_TIMER_MODE_REPEATED, MAIN_LOOP_INTERVAL_RAW, main_timer_handler) )
  {
    init_status |= TIMER_FAILED_INIT;
  }
  
  if( init_timer(reset_timer_id, APP_TIMER_MODE_SINGLE_SHOT, BUTTON_RESET_TIME, reboot) )
  {
    init_status |= TIMER_FAILED_INIT;
  }
  // Init starts timers, stop the reset
  app_timer_stop(reset_timer_id);

  // Log errors, add a note to NFC, blink RED to visually indicate the problem
  if (init_status)
  { 
    snprintf((char* )NFC_message, NFC_message_length, "Error: %X", init_status);
    NRF_LOG_WARNING (" -- Initalization error :  %X \r\n", init_status);
    for ( int16_t i=0; i<13; i++)
    { 
      RED_LED_ON;
      nrf_delay_ms(500u);
      RED_LED_OFF;
      nrf_delay_ms(500u); 
    }
  }
  
  // Turn green led on if model+ with no errors.
  // Power manage turns led off
  if (model_plus & !init_status)
  {
    GREEN_LED_ON;
  }

  // Turn off red led, leave green on to signal model+ without errors
  RED_LED_OFF;

  // Wait for sensors to take first sample
  nrf_delay_ms(1000);
  // Get first sample from sensors
  app_sched_event_put (NULL, 0, main_sensor_task);
  app_sched_execute();

  // Start advertising 
  bluetooth_advertising_start(); 
  NRF_LOG_INFO("Advertising started\r\n");

  // Enter main loop. Executes tasks scheduled by timers and interrupts.
  for (;;)
  {
    app_sched_execute();
    // Sleep until next event.
    power_manage();
  }
}
int main(int argc, char **argv)
{
    if (1 == argc) {
        utlog(LOG_ERR, "No configuration file was specified\n\n");
        print_help(EXIT_FAILURE);
    }

    int c;
    int foreground = 0;
    char *config_file = "";

    while (1) {

        static struct option long_options[] = {
            {"help",       no_argument,       0, 'h'},
            {"version",    no_argument,       0, 'v'},
            {"config",     required_argument, 0, 'c'},
            {"foreground", no_argument,       0, 'f'},
            {0, 0, 0, 0}
        };

        // getopt_long stores the option index here.
        int option_index = 0;

        c = getopt_long(argc, argv, "hvfc:",
                long_options, &option_index);

        // Detect the end of the options.
        if (c == -1) {
            break;
        }

        switch (c) {
            case 'h':
                print_help(EXIT_SUCCESS);
                break;

            case 'v':
                print_version(EXIT_SUCCESS);
                break;

            case 'c':
                config_file = optarg;
                break;

            case 'f':
                foreground = 1;
                break;

            case '?':
                // getopt_long already printed an error message.
                utlog(LOG_INFO, "\n");
                print_help(EXIT_FAILURE);
                break;

            default:
                break;
        }
    }

    pid_t pid;

    if (0 != (pid = pidfile_check(pidfile))) {
        utlog(LOG_ERR, "A instance of avm-motion-triggerd (%d) is already running\n",
                pid);
        exit(EXIT_FAILURE);
    }

    conf = get_config(config_file);
    validate_config(&conf);

    // Run as daemon if we should
    if (0 == foreground) {
        daemonize();
        utlog_mode(LOG_BACKGROUND);
        utlog_pri_mode(LOG_PRI_DISABLE);
    } else {
        utlog_mode(LOG_FOREGROUND);
        utlog_pri_mode(LOG_PRI_ENABLE);
    }

    // Write a pidfile for the current daemon process
    if (0 == pidfile_write(pidfile)) {
        exit(EXIT_FAILURE);
    }

    // Bind the signal handler
    signal(SIGINT, handle_signal);
    signal(SIGTERM, handle_signal);

    // Initialize the sensors
    init_sensors(&conf);

    // Call the business logic loop
    detect_motions(&conf);

    return EXIT_SUCCESS;
}
Example #18
0
// Main関数
void android_main(struct android_app* state) {
    struct engine engine;

    // glueが削除されないように
    app_dummy();

    memset(&engine, 0, sizeof(engine));
    // ユーザーデータの配置
    state->userData = &engine;
    // アプリケーションコマンド処理関数の設定
    state->onAppCmd = engine_handle_cmd;

    // 入力イベント処理関数の設定
    state->onInputEvent = engine_handle_input;
    engine.app = state;

    // センサーの初期化を行う
    init_sensors(&engine, state);

    if (state->savedState != NULL) {
        // 以前の状態に戻す
        engine.state = *(struct saved_state*) state->savedState;
    }

    // Configurationを表示
    displayConfiguration(&engine);


    engine.animating = 1;
    while (1) {

        int ident;
        int events;
        struct android_poll_source* source;

        // アプリケーションの状態にあわせてセンサー情報の処理を行う
        while ((ident = ALooper_pollAll(engine.animating ? 0 : -1, NULL, &events,
                                        (void**) &source)) >= 0) { /////-----(1)
            // 内部イベントを処理する
            if (source != NULL) {
                source->process(state, source);
            }

            // センサー情報取得キューのデータを処理する
            if (ident == LOOPER_ID_USER) {/////-----(2)
                ASensorEvent event[1];
                int count, i, j;
                while ((count = ASensorEventQueue_getEvents(engine.sensorEventQueue,
                                event, 1)) > 0) {
                    for (i = 0; i < count; i++) {
                        for (j = 0; j < SENSOR_MAX; j++) {
                            if ((engine.sensors[j].sensor != NULL)
                                    && (engine.sensors[j].type == event[i].type)) {
                                engine.sensors[j].value = event[i].vector; /////-----(3)
                            }
                        }
                    }
                }
            }
            // EGL情報を破棄する
            if (state->destroyRequested != 0) {
                engine_term_display(&engine);
                return;
            }
        }
        // 画面の描画
        engine_draw_frame(&engine);
    }

}
int main()
{
	
	init();
	float kp=1.5; 
	float kd=2.5;
	
	
	int error=0, prev_error=0, rate=0, pwm_duty, integ=0;
	
	int v1=0, v2=0, v3=0, s1, s2,a,b;
	
	while(bit_is_set(PIND,3));
	init_sensors();
	

		
	while(1)
	
	{	
		a=1;
		b=1;
		v1=adc_start(1);
		v2=adc_start(2);
		v3=adc_start(3);
		
		v1=(v1-l1);
		v2=(v2-l2);
		v3=(v3-l3);

		error=-((u1-v1)-(u3-v3));
		rate=error-prev_error;
		prev_error=error;
		integ+=0.001*error;
		
		if (error>0)
			PORTB = (1<<0) | (0<<1);
		else if (error<0)
			PORTB = (1<<1) | (0<<0);
		pwm_duty=error/kp+rate/kd+integ;
		
		s1=240+pwm_duty;
		s2=240-pwm_duty;

		if (s1>255)
		{
			s2=s2-(s1-255);
			s1=255;
		}
		if (s2>255)
		{	
			s1=s1-(s2-255);
			s2=255;
		}
		if (s1<0)
		{
			s1=0;
			
		}
		if (s2<0)
		{
			s2=0;
		}
		if (v1<45 && v2<45 && v3<45)	
		{
			s1=180;
			s2=180;
			a=2;
			Drive_Motor(0,0);
			break;
		}
		OCR1B=s1;
		OCR1A=s2;
		Drive_Motor(a,b);

	}
	return 0;
}