Esempio n. 1
0
void ASYNCHRONOUS_DNS_CACHE()
{
    rtos::Semaphore semaphore;
    dns_application_data data;
    data.semaphore = &semaphore;

    Ticker ticker;
    ticker.attach_us(&test_dns_query_ticker, 100);

    for (unsigned int i = 0; i < 5; i++) {
        int started_us = ticker_us;

        nsapi_error_t err = get_interface()->gethostbyname_async(dns_test_hosts[0],
                                                                 mbed::Callback<void(nsapi_error_t, SocketAddress *)>(hostbyname_cb, (void *) &data));
        TEST_ASSERT(err >= 0);

        semaphore.wait();

        TEST_ASSERT_EQUAL(NSAPI_ERROR_OK, data.result);
        TEST_ASSERT(strlen(data.addr.get_ip_address()) > 1);

        int delay_ms = (ticker_us - started_us) / 1000;

        static int delay_first = delay_ms / 2;
        printf("Delays: first: %i, delay_ms: %i\n", delay_first, delay_ms);
        // Check that cached accesses are at least twice as fast as the first one
        TEST_ASSERT_TRUE(i == 0 || delay_ms <= delay_first);

        printf("DNS: query \"%s\" => \"%s\", time %i ms\n",
               dns_test_hosts[0], data.addr.get_ip_address(), delay_ms);
    }
}
/*******************************************************************************
 * Sets up the serial port for communication and PWM for the lights, and
 * initializes the device.
 ******************************************************************************/
void setup() {
    
    pc.baud(BAUD);
    pc.attach(&serialInterrupt);
    
    // Setup the spi for 8 bit data, high steady state clock,
    // second edge capture, with a 1MHz clock rate
    cs = 1;
    spi.format(8,3);
    spi.frequency(1000000);
    
    // set up the lights on this mBed
    // light initialization on slave mBed handled by its own setup code
    lights[0] = new PwmOut(p26);
    lights[1] = new PwmOut(p25);
    lights[2] = new PwmOut(p24);
    lights[3] = new PwmOut(p23);
    lights[4] = new PwmOut(p22);
    lights[5] = new PwmOut(p21);
    
    for (int i = 0; i < 6; i++) {
        lights[i]->period_us(333); // 3 kHz
        lights[i]->write(0.5);   // 50% duty cycle
    }
    
    row = 0;
    setRowMux(row);
   led3.write(0);
   while(start==0);
    
   adcRead.attach_us(&readAdcs, ADC_DELAY);
    
    
}
Esempio n. 3
0
BOOL
xMBPortSerialInit( UCHAR ucPORT, ULONG ulBaudRate, UCHAR ucDataBits, eMBParity eParity )
{
    simISR.attach_us(&prvvUARTISR,1000);    // Cam - attach prvvUARTISR to a 1mS ticker to simulate serial interrupt behaviour
                                            // 1mS is just short of a character time at 9600 bps, so quick enough to pick
                                            // up status on a character by character basis.
    return TRUE;
}
Esempio n. 4
0
void app_start(int, char*[])
{
    MBED_HOSTTEST_TIMEOUT(15);
    MBED_HOSTTEST_SELECT(wait_us_auto);
    MBED_HOSTTEST_DESCRIPTION(Ticker Int us);
    MBED_HOSTTEST_START("MBED_23");

    tick.attach_us(togglePin, 1000);
}
Esempio n. 5
0
File: lib.c Progetto: guillep19/frob
void lib_init(){
    timer.start();
    ticker.attach_us(handleTick, 1000);
    fader.period_ms(10);
    fader.pulsewidth_ms(5);
    spi.format(8,0);
    spi.frequency(250000);
    pin20 = 1;
}
void app_start(int, char **)
{

#ifndef MBED_CONF_RTOS_PRESENT
    // set the baud rate for output printing
    pc.baud(YOTTA_CFG_K64F_BORDER_ROUTER_BAUD);
    // set heap size and memory error handler for this application
    ns_dyn_mem_init(app_stack_heap, APP_DEFINED_HEAP_SIZE, app_heap_error_handler, 0);

#else
    pc.baud(MBED_CONF_APP_TRACE_BAUD_RATE);
    ns_hal_init(app_stack_heap, APP_DEFINED_HEAP_SIZE, app_heap_error_handler, 0);
#endif

    trace_init(); // set up the tracing library
    set_trace_print_function(trace_printer);
    set_trace_config(TRACE_MODE_COLOR | APP_TRACE_LEVEL | TRACE_CARRIAGE_RETURN);

    const char *mac_src;

#ifndef MBED_CONF_RTOS_PRESENT
    mac_src = STR(YOTTA_CFG_K64F_BORDER_ROUTER_BACKHAUL_MAC_SRC);
#else
    mac_src = STR(MBED_CONF_APP_BACKHAUL_MAC_SRC);
#endif

    if (strcmp(mac_src, "BOARD") == 0) {
        /* Setting the MAC Address from UID (A yotta function)
         * Takes UID Mid low and UID low and shuffles them around. */
        mbed_mac_address((char *)mac);
    } else if (strcmp(mac_src, "CONFIG") == 0) {
        /* MAC is defined by the user through yotta configuration */
#ifndef MBED_CONF_RTOS_PRESENT
        const uint8_t mac48[] = YOTTA_CFG_K64F_BORDER_ROUTER_BACKHAUL_MAC;
#else
        const uint8_t mac48[] = MBED_CONF_APP_BACKHAUL_MAC;
#endif

        for (uint32_t i = 0; i < sizeof(mac); ++i) {
            mac[i] = mac48[i];
        }
    }

#ifndef MBED_CONF_RTOS_PRESENT
    // run LED toggler in the Minar scheduler
    minar::Scheduler::postCallback(mbed::util::FunctionPointer0<void>
                                  (toggle_led1).bind()).period(minar::milliseconds(500));
#else
    led_ticker.attach_us(toggle_led1, 500000);
#endif
    tr_info("Starting K64F border router...");
    border_router_start();
}
Esempio n. 7
0
int main()
{
    
    rightMotor.setPwm(1.0);
    leftMotor.setPwm(1.0);
    
    Systicker.attach_us(&systick,1000);
    
    //loop();
   // pc.printf("test\n");
    
    
    return 0;
}
Esempio n. 8
0
static void equeue_tick_init() {
    MBED_STATIC_ASSERT(sizeof(equeue_timer) >= sizeof(Timer),
            "The equeue_timer buffer must fit the class Timer");
    MBED_STATIC_ASSERT(sizeof(equeue_ticker) >= sizeof(Ticker),
            "The equeue_ticker buffer must fit the class Ticker");
    Timer *timer = new (equeue_timer) Timer;
    Ticker *ticker = new (equeue_ticker) Ticker;

    equeue_minutes = 0;
    timer->start();
    ticker->attach_us(equeue_tick_update, 1000 << 16);

    equeue_tick_inited = true;
}
 void do_blink() {
     for (;;) {
         // blink the LED
         red_led = !red_led;
         // up the position, if we reached the end of the vector
         if (blink_args->position >= blink_args->blink_pattern.size()) {
             // send delayed response after blink is done
             M2MObjectInstance* inst = led_object->object_instance();
             M2MResource* led_res = inst->resource("5850");
             led_res->send_delayed_post_response();
             red_led = LED_OFF;
             status_ticker.attach_us(blinky, 250000);
             return;
         }
         // Wait requested time, then continue prosessing the blink pattern from next position.
         Thread::wait(blink_args->blink_pattern.at(blink_args->position));
         blink_args->position++;
     }
 }
Esempio n. 10
0
int main()
{
    ticker_motor_ctrl.attach_us(&tickerInterrupt, MOTOR_CTRL_TICKER_PERIOD);
    
    //pc.attach(&ComPC, &USBSerialCom::serialCallback);
    ComPC.setAsser(&asser);
    t_com.start();

    //TODO: Enable a WatchDog !!!

    int count = 0;
    while (1) 
    {   
        if (t_com.read_ms() > 20)
        {
            ComPC.processSerialPort();
            
            if(ComPC.checkTimeOut())  ComPC.sendHeartBeat(88288);
            
            asser.UpdateCmd();
            asser.DataAvailable();
          
            asser.ComputeOdometry();
            asser.Compute();
            
            /*pc.printf("X%ld!",long(asser.getODO_X()*100));
            pc.printf("Y%ld!",long(asser.getODO_Y()*100));
            pc.printf("A%ld!",long(asser.getODO_Theta()*100));
            
            pc.printf("L%ld!",asser.getWheelL());
            pc.printf("R%ld!",asser.getWheelR()); 
            
            if (count > 0) { pc.printf("D:To!"); }
            count = 0;*/
            ComPC.printOdo();
               
            t_com.reset();        
        }
        
    }
}
Esempio n. 11
0
int main() {
    controls.setPC(comm.getPC());
    controls.setup();
//    comm.printPosition();
    comm.printGains();

    controlsInterrupt.attach_us(&controls, &Controls::loop, 1000);

    while(1) {
        controls.updateIMUS();
        comm.check();
        
        
        if (serialCounter++>100) {
//            comm.printPosition();
//            comm.getPC()->printf("%f\n", controls.getTheta1());
//            comm.getPC()->printf("%f", controls.motor.getPWM());
            serialCounter = 0;
           // float z[4] = {1,2,0,0};
//            comm.getPC()->printf("%f\n",controls.target.getTheta2ForTarget(z));
        }
    }
}
Esempio n. 12
0
int main()
{  
    PC.baud(115200);
    TFC_TickerObj.attach_us(&TFC_TickerUpdate,2000); // update ticker array every 2mS (2000 uS)
    TFC_Init();
    TFC_HBRIDGE_ENABLE;
    InterruptIn button(PTA17);//Interrupção no pino
    button.rise(&flip);  // attach the address of the flip function to the rising edge
    TFC_Ticker[0] = 0;
    update();
    while(1)
    {      
        //PC.printf("Hello World!\n");
        
       //button.rise(NULL);      // Disable interruptions
       comm(&commands[0]);    //Pass commands as a parameter of comm  
       //update();
        
        
        //TFC_Task must be called in your main loop.  This keeps certain processing happy (I.E. Serial port queue check)
         //   TFC_Task();
    }    
 
}
Esempio n. 13
0
int main()
{
    input_button_t button;
    input_button_t last_button = W_IDLE;

#if defined(TARGET_LPC1114) && defined(SERIAL_DEBUG)
    int i;
    for (i = 0; i <= NUM_WHEEL_BUTTONS-1; i++)
        dprintf("Threshold %d: 0x%04X\r\n", i, WHEEL_BUTTON_THRESHOLD[i]);
#endif
#if defined(TARGET_LPC1768) && defined(SERIAL_DEBUG)
    dbg_serial.baud(115200);
#endif

    dprintf("\r\n\r\n############## MBED MAZDA ##############\r\n");
#ifdef ENABLE_RN52
    bluetooth.init();
    dprintf("Bluetooth init done\r\n");
    bluetooth.set_user_defaults();
    dprintf("Bluetooth defaults done\r\n");
#endif

    dprintf("Entering main loop\r\n");
    loop_ticker.attach_us(&loop_ticker_isr, LOOP_TIME_US);
    for (;;)
    {
        if (!main_loop_continue)
            goto _main_sleep;

#ifdef ENABLE_RN52
        if (bluetooth.status_update)
        {
            bluetooth.check_status();
#ifdef TARGET_LPC1768
            led1 = bluetooth.is_connected;
#endif
        }
#endif

        button = read_input_button();
        if (button != last_button)
        {
            dprintf("Switched to button %s\r\n", INPUT_BUTTON_STR[button]);

#ifdef ENABLE_RN52
            if (bluetooth.is_connected)
            {
                // button mapping when bluetooth is connected
                switch (button)
                {
                case W_VOLUP:
                    PIONEER_HOLD(P_VOLUP);
                    break;
                case W_VOLDOWN:
                    PIONEER_HOLD(P_VOLDOWN);
                    break;
                case W_NEXT:
                    bluetooth.next_track();
                    break;
                case W_PREV:
                    bluetooth.prev_track();
                    break;
                case W_MODE:
                    bluetooth.voice_command();
                    break;
                case W_MUTE:
                    bluetooth.play_pause();
                    break;
#ifdef TARGET_LPC1768
                case W_STATUSCHECK:
                    bluetooth.check_status();
                    led1 = bluetooth.is_connected;
                    break;
#endif
                case W_IDLE:
                default:
                    PIONEER_RELEASE();
                    break;
                }
            }
            else
#endif
            {
                switch (button)
                {
                // button mapping when bluetooth isn't connected
                case W_VOLUP:
                    PIONEER_HOLD(P_VOLUP);
                    break;
                case W_VOLDOWN:
                    PIONEER_HOLD(P_VOLDOWN);
                    break;
                case W_NEXT:
                    PIONEER_HOLD(P_NEXT);
                    break;
                case W_PREV:
                    PIONEER_HOLD(P_PREV);
                    break;
                case W_MODE:
                    PIONEER_HOLD(P_SOURCE);
                    break;
                case W_MUTE:
                    PIONEER_HOLD(P_MUTE);
                    break;
#ifdef TARGET_LPC1768
                case W_STATUSCHECK:
                    bluetooth.check_status();
                    led1 = bluetooth.is_connected;
                    break;
#endif
                case W_IDLE:
                default:
                    PIONEER_RELEASE();
                    break;
                }
            }

            last_button = button;
        }
        main_loop_continue = false; // Ticker ISR will reset this
_main_sleep:
        sleep();
    }
}
Esempio n. 14
0
File: main.cpp Progetto: AsamQi/mbed
int main()
{
    tick.attach_us(togglePin, 1000);
    while (1);
}
Esempio n. 15
0
control_t test_case_ticker() {
    tick.attach_us(togglePin, 1000);
    return CaseTimeout(15 * 1000);
}
Esempio n. 16
0
/**
 * Main application entry point.
 */
int main( void )

{

#if( OVER_THE_AIR_ACTIVATION != 0 )
    uint8_t sendFrameStatus = 0;
#endif
    bool trySendingFrameAgain = false;
 //   float tempLightValue = 0;   
    
//    LightMode = 0;      // 0: manual,   1: automatic
    buzzer = 0;         // 0: OFF,      1: ON
    bar.setLevel(0);
    debug( "\n\n\r    LoRaWAN Class A Demo code  \n\n\r" );
    
    BoardInitMcu( );
    BoardInitPeriph( );

    // Initialize LoRaMac device unique ID
     BoardGetUniqueId( DevEui );
    
    LoRaMacEvents.MacEvent = OnMacEvent;
    LoRaMacInit( &LoRaMacEvents );

    IsNetworkJoined = false;

#if( OVER_THE_AIR_ACTIVATION == 0 )
    // Random seed initialization
    srand( RAND_SEED );
    // Choose a random device address
    // NwkID = 0
    // NwkAddr rand [0, 33554431]
    if( ( DevAddr == 0 ) || ( DevAddr == 0xFFFFFFFF ) )
    {
        // Generate random DevAddr if it does not exist
        debug("Generate random DevAddr\n\r");
        DevAddr = randr( 0, 0x01FFFFFF );
    }
    debug( "- DevAddr = 0x%x\n\r" , DevAddr);    
    LoRaMacInitNwkIds( 0x000000, DevAddr, NwkSKey, AppSKey );
    IsNetworkJoined = true;
#endif

    TxNextPacket = true;

    LoRaMacSetAdrOn( false );    
    LoRaMacSetDutyCycleOn( false );   
    

     
while( 1 )
    {
        while( IsNetworkJoined == false )
        {
#if( OVER_THE_AIR_ACTIVATION != 0 )
            if( TxNextPacket == true )
            {
                TxNextPacket = false;
                
                sendFrameStatus = LoRaMacJoinReq( DevEui, AppEui, AppKey );
                debug("Req Sent\n\r");
                switch( sendFrameStatus )
                {
                case 1: // BUSY
                    break;
                case 0: // OK
                case 2: // NO_NETWORK_JOINED
                case 3: // LENGTH_PORT_ERROR
                case 4: // MAC_CMD_ERROR
                case 6: // DEVICE_OFF
                default:
                    // Relaunch timer for next trial
                    JoinReqTimer.attach_us( &OnJoinReqTimerEvent, OVER_THE_AIR_ACTIVATION_DUTYCYCLE );
                    break;
                }
            }
//            TimerLowPowerHandler( );
#endif
        }

        if( TxDone == true )
        {
            
            TxDone = false;
            
            debug( "TxDone \n\n\r" );
            // Schedule next packet transmission
            TxDutyCycleTime = APP_TX_DUTYCYCLE + randr( -APP_TX_DUTYCYCLE_RND, APP_TX_DUTYCYCLE_RND );
            TxNextPacketTimer.attach_us( &OnTxNextPacketTimerEvent, TxDutyCycleTime );
        }

        if( trySendingFrameAgain == true )
        {
            trySendingFrameAgain = SendFrame( );
        }
        
        if( TxNextPacket == true )
        {       
            TxNextPacketTimer.detach( );
            
            TxNextPacket = false;
        
            PrepareTxFrame( AppPort );
            
            trySendingFrameAgain = SendFrame( );
        }




        /* Read light sensor
        tempLightValue = LightSens.read( ) * 1.65;
        
        LightValue = ( 1 - tempLightValue );
        
        // Set automatic RGB from light sensor
        if( LightMode == 0 )
        {
            color_led.setColorRGB( 0, ( uint8_t )( 255 * LightValue ), ( uint8_t )( 255 * LightValue ), ( uint8_t )( 255 * LightValue ) );
        }*/
//        TimerLowPowerHandler( );
    }
}
Esempio n. 17
0
static void ProcessRxFrame( LoRaMacEventFlags_t *flags, LoRaMacEventInfo_t *info )
{
    debug( "[Rx] Port=%d\n\r" , info->RxPort);
    switch( info->RxPort ) 
    {
        case 10: 
             display.write( 0, info->RxBuffer[0] );
             display.write( 1, info->RxBuffer[1] );
             display.write( 2, info->RxBuffer[2] );
             display.write( 3, info->RxBuffer[3] ); 
           break;
            
        /*case 20:
             LightMode = info->RxBuffer[0];
             debug( "[Rx] LightMode=%x - R G B= 0x%x 0x%x 0x%x\n\r" , LightMode, info->RxBuffer[1], info->RxBuffer[2], info->RxBuffer[3]);
             if( LightMode )
             {
                 color_led.setColorRGB(0, info->RxBuffer[1], info->RxBuffer[2], info->RxBuffer[3] );
             }
            break;*/
            
        case 30:
            BuzTimer.attach_us( &OnBuzTimerEvent, 500000 );
            buzzer = 1;
         break;
            
        case 40:
       relay = 0;
        int i=10;
        for (i=10; i>=0; i--) {
            bar.setLevel(i);
            wait(0.1);
        }
        bar.setLevel(0);       
      break;
      
       case 41:
       relay = 1;
          i=1;
             for (i=0; i<=10; i++) {
                  bar.setLevel(i);
             wait(0.02);         } 
            bar.setLevel(10);
      break;
      
      case 44:
        relay = 1;
          i=1;
             for (i=0; i<=10; i++) {
                  bar.setLevel(i);
             wait(0.02);         }                      
        wait(5); 
          relay = 0;
         i=10;
        for (i=10; i>=0; i--) {
            bar.setLevel(i);
            wait(0.1);
        }
        bar.setLevel(0);
        break;
        
   case 50:
    i=int(info->RxBuffer[0]);
     bar.setLevel(i);
     break;
            
        default:
            break;
            
            
            
           

    }
}
Esempio n. 18
0
int main(void)
{
    blue  = LED_ON;
    green = LED_OFF;

#if BUTTON_DOWN
    button.mode(PullDown);
    button.rise(button_wakeup);
#else
    button.mode(PullUp);
    button.fall(button_wakeup);
#endif

    DEBUG("Initialising the nRF51822\n\r");
    ble.init();
    ble.onConnection(connectionCallback);
    ble.onDisconnection(disconnectionCallback);
    ble.onDataWritten(onDataWritten);

    /* setup advertising */
    ble.accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE);
    ble.setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED);
    ble.accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME,
                                    (const uint8_t *)BLE_NAME, sizeof(BLE_NAME));

    ble.setAdvertisingInterval(160); /* 100ms; in multiples of 0.625ms. */
    ble.startAdvertising();

    /* Enable over-the-air firmware updates. Instantiating DFUSservice introduces a
     * control characteristic which can be used to trigger the application to
     * handover control to a resident bootloader. */
    DFUService dfu(ble);

    UARTService uartService(ble);
    uartServicePtr = &uartService;

    blue_led_time_to_off = 3000 / TICK_PERIOD_MS;

    Ticker ticker;
    ticker.attach_us(tick, TICK_PERIOD_MS * 1000);

    while (true) {
        if (button_event) {
            int click;

            blue = LED_ON;
            click = button_detect();
            blue = LED_OFF;
            DEBUG("click type: %d\n\r", click);

            button_event = false;

            if (1 == click) {
                single_click_input = current_input;
            } else if (2 == click) {
                double_click_input = current_input;
                green = LED_ON;
                green_led_time_to_off = 1000 / TICK_PERIOD_MS;
            } else if (-1 == click) {
                while (BUTTON_DOWN == button.read()) {

                }
                nrf_delay_us(3000);

                power_down();
            } else {
                continue;
            }

            DEBUG("typical input: %f, %f\n\r", single_click_input, double_click_input);

            threshold_update = 1;
        } else {
            ble.waitForEvent();
        }
    }
}
Esempio n. 19
0
int main() {
	//host.baud(115200);
	xbee.baud(115200);

	Ticker heartbeat_tkr;
	heartbeat_tkr.attach_us(&beat, HEARTBEAT_UPDATE_RATE * 1000);
	autopilotRemote.rise(&autopilot_ISR);
	//i2c.frequency(400);

	// Initialise PIDs
	speedOverGroundPid.setInputLimits(0.0, SPEED_IN_KNOTS_LIMIT); // Assuming speed is in knots -- check this!
	speedOverGroundPid.setOutputLimits(1, THROTTLE_LIMIT);
	speedOverGroundPid.setMode(AUTO_MODE);

	headingPid.setInputLimits(-180,180);
	headingPid.setOutputLimits(0.0, THROTTLE_LIMIT);
	headingPid.setMode(AUTO_MODE);

	speedOverGroundPid.setSetPoint(2.5);
	headingPid.setSetPoint(0);

	DEBUG_OUTPUT("     _              _   _                 _   \r\n"
				 "    | |            | | | |               | |  \r\n"
				 " ___| |__   ___  __| | | |__   ___   __ _| |_ \r\n"
				 "/ __| '_ \\ / _ \\/ _` | | '_ \\ / _ \\ / _` | __|\r\n"
				 "\\__ \\ | | |  __/ (_| | | |_) | (_) | (_| | |_ \r\n"
				 "|___/_| |_|\\___|\\__,_| |_.__/ \\___/ \\__,_|\\__|\r\n"
				 "                   ______                     \r\n"
				 "                  |______|\r\n"
				 "\r\n\n");

	NMEA::init();

	compass.init();

	// Parkwood: 51.298997, 1.056683
	// Chestfield: 51.349215, 1.066184
	// Initialise Motors (Arming Sequence) -- If a value is not sent periodicially, then the motors WILL disarm!
	leftMotor.set(0);
	rightMotor.set(0);
	wait(1);

	setup_waypoints();
	// Initialise Scheduler
	Ticker gpsTelemetryUpdateTkr;
	Ticker systemTelemetryUpdateTkr;
	Ticker debugTelemetryUpdateTkr;

	Ticker trackandSpeedUpdateTkr;
	Ticker motorUpdateTkr;
	gpsTelemetryUpdateTkr.attach_us(&gps_telemetry_update_ISR, GPS_TELEMETRY_UPDATE_RATE * 1000);
	systemTelemetryUpdateTkr.attach_us(&system_telemetry_update_ISR, SYSTEM_TELEMETRY_UPDATE_RATE * 1000);
	debugTelemetryUpdateTkr.attach_us(&debug_telemetry_update_ISR, DEBUG_TELEMETRY_UPDATE_RATE * 1000);

	trackandSpeedUpdateTkr.attach_us(&track_and_speed_update_ISR, TRACK_UPDATE_RATE * 1000);
	motorUpdateTkr.attach_us(&motor_update_ISR, MOTOR_UPDATE_RATE * 1000);

	while(1) {
		if(updateTrackAndSpeed && autopilotEngaged){
			update_speed_and_heading();
			updateTrackAndSpeed = false;
		}
		if(updateMotor && autopilotEngaged){
			update_motors();
			updateMotor = false;
		}
		if(updateGPSTelemetry){
			gps_satellite_telemetry();
			updateGPSTelemetry = false;
		}
		if(updateSystemTelemetry){
			send_system_telemetry();
			updateSystemTelemetry = false;
		}
		if(updateDebugTelemetry){
			send_debug_telemetry();
			updateDebugTelemetry = false;
		}
	}
}
// Entry point to the program
int main() {

    unsigned int seed;
    size_t len;

#ifdef MBEDTLS_ENTROPY_HARDWARE_ALT
    // Used to randomize source port
    mbedtls_hardware_poll(NULL, (unsigned char *) &seed, sizeof seed, &len);

#elif defined MBEDTLS_TEST_NULL_ENTROPY

#warning "mbedTLS security feature is disabled. Connection will not be secure !! Implement proper hardware entropy for your selected hardware."
    // Used to randomize source port
    mbedtls_null_entropy_poll( NULL,(unsigned char *) &seed, sizeof seed, &len);

#else

#error "This hardware does not have entropy, endpoint will not register to Connector.\
You need to enable NULL ENTROPY for your application, but if this configuration change is made then no security is offered by mbed TLS.\
Add MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES and MBEDTLS_TEST_NULL_ENTROPY in mbed_app.json macros to register your endpoint."

#endif

    srand(seed);
    red_led = LED_OFF;
    blue_led = LED_OFF;

    status_ticker.attach_us(blinky, 250000);
    // Keep track of the main thread
    mainThread = osThreadGetId();

    printf("\nStarting mbed Client example in ");
#if defined (MESH) || (MBED_CONF_LWIP_IPV6_ENABLED==true)
    printf("IPv6 mode\n");
#else
    printf("IPv4 mode\n");
#endif

    mbed_trace_init();

    NetworkInterface* network = easy_connect(true);
    if(network == NULL) {
        printf("\nConnection to Network Failed - exiting application...\n");
        return -1;
    }

    // we create our button and LED resources
    ButtonResource button_resource;
    LedResource led_resource;
    BigPayloadResource big_payload_resource;

#ifdef TARGET_K64F
    // On press of SW3 button on K64F board, example application
    // will call unregister API towards mbed Device Connector
    //unreg_button.fall(&mbed_client,&MbedClient::test_unregister);
    unreg_button.fall(&unregister);

    // Observation Button (SW2) press will send update of endpoint resource values to connector
    obs_button.fall(&button_clicked);
#else
    // Send update of endpoint resource values to connector every 15 seconds periodically
    timer.attach(&button_clicked, 15.0);
#endif

    // Create endpoint interface to manage register and unregister
    mbed_client.create_interface(MBED_SERVER_ADDRESS, network);

    // Create Objects of varying types, see simpleclient.h for more details on implementation.
    M2MSecurity* register_object = mbed_client.create_register_object(); // server object specifying connector info
    M2MDevice*   device_object   = mbed_client.create_device_object();   // device resources object

    // Create list of Objects to register
    M2MObjectList object_list;

    // Add objects to list
    object_list.push_back(device_object);
    object_list.push_back(button_resource.get_object());
    object_list.push_back(led_resource.get_object());
    object_list.push_back(big_payload_resource.get_object());

    // Set endpoint registration object
    mbed_client.set_register_object(register_object);

    // Register with mbed Device Connector
    mbed_client.test_register(register_object, object_list);
    registered = true;

    while (true) {
        updates.wait(25000);
        if(registered) {
            if(!clicked) {
                mbed_client.test_update_register();
            }
        }else {
            break;
        }
        if(clicked) {
            clicked = false;
            button_resource.handle_button_click();
        }
    }

    mbed_client.test_unregister();
    status_ticker.detach();
}
Esempio n. 21
0
/* Program entry */
int main(void){
/* Init */
	// reset flags
	LPC_SYSCON->SYSRSTSTAT = 0x1F;
	// Motor Control IO config
	SMC_init();
	// aux init
	aux = 0;
	// LED
	led = 0;
	// USB Initialize	
	static USBHID hid_object(64, 64);
	hid = &hid_object;
	send_report.length = 64;
	// UART initialize
	uart.format(8, Serial::None, 1);
	uart.baud(115200);
	uart.attach(serialHandler);
	xifo_init(&uartbuf,sizeof(uartbufpool),uartbufpool);
	xifo_clear(&uartbuf);
	Ticker_BufferAging.attach_us(&serialBufferAgingHandler, Ticker_BufferAging_interval);
	// remap uart interrupt so we can add stuff
	/*
	Original_UART_IRQn_Address = NVIC_GetVector(UART_IRQn);
	NVIC_SetVector(UART_IRQn, (uint32_t)&UART_IRQ_Custom);
	LPC_USART->IER |= (1<<2); // enable line status interrupt
	*/
	// button config
	Ticker_button.attach_us(&Ticker_button_handler, 20000);	
	
	// Ready
	while(1){
		uint8_t UART_PacketParsed = 0;
		// insert idle time, since we cant be running USB stuff all the time
		wait_us(5000);
		
		if(button_history < 0xFFFFFFFF){
			SMC_step(1600, 1, 30000, 1);
			while(!SMC_idle());
			continue;
		}
			
		
	/* First read from UART, since UART uses the same command structures as USB
	 * Commands from UART are loaded into USB recv_report	to reduce code size 
	 * and decrease required UART development time 
	 */
		
	// try to read a msg form UART	
		if( serialPacketReady ){
			serialPacketReady--;
			// Load UART buffer into recv_report (FIFO MODE)
			{
				empty_report(&recv_report);
				recv_report.length = 64;
				uint8_t *p = recv_report.data;
				while( xifo_get_used(&uartbuf) ){
						*p++ = xifo_pop_lr(&uartbuf);
				}
				xifo_init(&uartbuf,sizeof(uartbufpool),uartbufpool);
				xifo_clear(&uartbuf);
			}
			// Data packet received, start parsing
			int irx=0;
			int itx=0;
			send_report.data[itx++] = recv_report.data[0];
			// Include large switch case module
			{
				#include "USB_SwitchCase.c"
			}
			// Return command + optional new args
			{
				uint8_t *p = send_report.data;
				uint32_t i;
				send_report.length = 32;
				i = send_report.length;
				while(i--) while(uart.writeable()) uart.putc(*p);
			}
			// 0xFF unused bytes
			empty_report(&recv_report);			
			empty_report(&send_report);
			// Set flag to skip USB packet parsing
			UART_PacketParsed++;
		}	// if uart readable
		
	//try to read a msg from USB
		if( hid->readNB(&recv_report) && !UART_PacketParsed ){
			// Data packet received, start parsing
			int irx=0;
			int itx=0;
			send_report.data[itx++] = recv_report.data[0];
			// Include large switch case module
			{
				#include "USB_SwitchCase.c"
			}
			// Return command + optional new args
			hid->send(&send_report);
			// 0xFF unused bytes
			empty_report(&recv_report);			
			empty_report(&send_report);
		}	// if packet
		
	} // While
} // Main
Esempio n. 22
0
void nbprint_setup() {
  serial.printf("Setting up non-blocking print...\r\n");
  nb_printer.attach_us(&print_fn, NBPRINT_US);
  nbprint("Non-blocking print setup complete!\r\n");
}
Esempio n. 23
0
//***************** You can start coding here *****************//
int main (void)
{   

    // MRF SPI Init
    uint8_t channel = 12;
    print_adxl_timer.start();
    mrf.SetChannel(channel); //Set the Channel. 0 is default, 15 is max
    // ///////////

    // M2 SPI Init
    ss = 1;
    spi.format(8, 0);
    //spi.format(16, 0);
    spi.frequency(SPI_FREQ);
    spi_start_ticker.attach_us(&SPI_start_handler, SPI_PRD*1000);
    read_adxl = false;
    // ///////////

    // IMU I2C Init
    i2c.frequency(400000); // 400KHz
    setup_imu();
    // ///////////

    //Start the timer
    timer.start();
    debounce.start();
    strcpy(testString, "0,2,0.2,1,0.6,0.7,0.7,0.4,0");
    err();
    testcheck = 1;
    button.rise(debounce_handler);
    training_mode = false;
    
    // Initial Lights
    recMode = 0;
    
    // Timer initiate
    for (int i = 0; i < 7; i++) {
        //timerarray[i].start();   
        timerarray[i].stop();   
    }
    
    // Digital Pin Pwms
    for (int i = 0; i < 7; i++) {
        pwm_duty_cycles[i] = 0.0;
    }
    ticker_30Hz.attach_us(&ticker_30Hz_handler, THIRTYHZ*1000);

    
    pc.printf("Starting...\n");
    while(1) {
        greenlightact();

        if (training_mode) {
            if (read_adxl) read_adxl_from_m2();
    
            if (print_adxl_timer.read_ms() > PRINT_PRD) {
              print_adxl_timer.reset();
              pc.printf("dx: ");
              for (int i = 0; i < NUM_ADXL; i++)
                pc.printf("%d\t", adxl[i]);
              pc.printf("\tdtheta: ");
              for (int i = 0; i < NUM_IMU; i++)
                pc.printf("%d\t", imu[i]);
              pc.printf("\t");
              for (int i = 0; i < 7; i++) 
                pc.printf("%d\t", vhit[i]);
              pc.printf("\n");
            }
            
            // GUI controlled
            //TODO TODO TODO
            if (pc.readable()) {
                pc.gets(gui_input_buf, 16);
                sscanf(gui_input_buf, "%d,%d,%d,%d,%d,%d,%d,%d", &recMode,green,green+1,green+2,green+3,green+4,green+5,green+6);
                pc.printf("DEBUG: %d,%d,%d,%d,%d,%d,%d,%d\n", recMode,green[0],green[1],green[2],green[3],green[4],green[5],green[6]);
                //pc.printf("DEBUG: %d,%d,%d,%d,%d,%d,%d,%d\r\n", *recMode,green[0],green[1],green[2],green[3],green[4],green[5],green[6]);
                if (recMode > 0) {
                    trigger(recMode);
                }
            }
            pc.printf("DEBUG: %d,%d,%d,%d,%d,%d,%d,%d\n", recMode,green[0],green[1],green[2],green[3],green[4],green[5],green[6]);
        }
        
        else {
            //Try to receive some data
            rxLen = rf_receive(rxBuffer, 128);
            if(rxLen > 0) {
                pc.printf("%s \r\n", rxBuffer );
                token = strtok(rxBuffer, " ,");
                player = atoi(token);
                if (player == LINKED_PLAYER) {
                    token = strtok(NULL, " ,");
                    inputs = atoi(token);
                    for (int i = 0; i < inputs; i++) {
                        token = strtok(NULL, ",");
                        float temp = atof(token);
                        //float temp = ((float) atoi(token))/MAX_ACCEL_VAL;
                        temp = 1.0  - temp;
                        pwm_duty_cycles[i] = temp;
                        if (temp > 0.2) {
                            green[i] = 0;
                        }
                        else {
                            green[i] = 1;
                        }
                    }
                }
            }
        }
    }
}
Esempio n. 24
0
File: main.cpp Progetto: logxen/mbed
int main() {
    tick.attach_us(togglePin, 1000);
    while (true) {
        wait(1);
    }
}