bool PHPROBE_init(void){ struct usart_config usart_conf; usart_get_config_defaults(&usart_conf); usart_conf.mux_setting = USART_RX_3_TX_2_XCK_3; usart_conf.pinmux_pad0 = PINMUX_UNUSED; usart_conf.pinmux_pad1 = PINMUX_UNUSED; usart_conf.pinmux_pad2 = PINMUX_PA10C_SERCOM0_PAD2; usart_conf.pinmux_pad3 = PINMUX_PA11C_SERCOM0_PAD3; usart_conf.baudrate = 9600; while (usart_init(&PHPROBE_uart, SERCOM0, &usart_conf) != STATUS_OK ) { //add a timeout if blocked here } usart_register_callback(&PHPROBE_uart, PHPROBE_buffer_received , USART_CALLBACK_BUFFER_RECEIVED); usart_enable_callback(&PHPROBE_uart, USART_CALLBACK_BUFFER_RECEIVED); usart_enable(&PHPROBE_uart); usart_read_job(&PHPROBE_uart , &get_char_buffer); return true; }
/** Inicjalizacja urządzeń wejścia / wyjścia. */ void ioinit(void) { uint8_t i; hd44780_init(); hd44780_outcmd(HD44780_CLR); hd44780_wait_ready(); hd44780_outcmd(HD44780_ENTMODE(1, 0)); hd44780_wait_ready(); hd44780_outcmd(HD44780_DISPCTL(1, 1, 1)); hd44780_wait_ready(); hd44780_outcmd(HD44780_CGADDR(0)); for(i=0; i<64; i++) { hd44780_outdata(pgm_read_byte(&extraChar[i])); } TCCR1B = _BV(WGM12) | _BV(CS11); // licznik / 8 - wyzerwoanie na porownanie TIMSK = _BV(OCIE1A); // przerwanie na porownanie wartosci OCR1A = TAU1; // warto licznika porownania usart_init(UBRR_VALUE); onewire_init(); twi_init(); outputs_init(); top_off_init(); qbuttons_init(); ui_init(); BUZZER_DDR |= _BV(BUZZER_SWITCH); buzzer_off(); wdt_enable(WDTO_2S); }
int main(void) { timer_init(); usart_init(BAUDRATE); /** * get function codes of all configured pins * - disable uart if pin is used */ getFuncCode(); I2C_MAIN_INFO("\n\rSystem_Ready\n\r"); I2C_MAIN_INFO("Compiliert_am_"__DATE__"_um_"__TIME__"\r\n"); I2C_MAIN_INFO("Compiliert_mit_GCC_Version_"__VERSION__"\r\n"); init(); printIOsstruct(); while (1) { // RoBue: // Uhrzeit bestimmen hh = (time/3600)%24; mm = (time/60)%60; ss = time%60; //get new pulse time from eeprom pulse_time = eeprom_read_byte(EEPROM_PULSE_TIME) << 8; pulse_time |= eeprom_read_byte(EEPROM_PULSE_TIME+1); update_tx(); handle_vio(); _delay_ms(1000); } //end.while while (1) ;; } //end.main
void init(void) { setupFlash(); setupClocks(); setupNVIC(); systick_init(SYSTICK_RELOAD_VAL); gpio_init_all(); afio_init(); setupADC(); setupTimers(); setupUSB(); boardInit(); //for debug gpio_set_mode(GPIOA, 2, GPIO_AF_OUTPUT_PP); gpio_set_mode(GPIOA, 3, GPIO_INPUT_FLOATING); usart_init(USART2); usart_set_baud_rate(USART2, STM32_PCLK1, 57600); usart_enable(USART2); /*delay(1000); TxDString("hello pandora\r\n");*/ }
int main(void) { uint16_t adc_data = 0; sei(); // Enable interrupts fosc_cal(); // Set calibrated 1MHz system clock portb_init(); // Set up port B usart_init(); // Set up the USART timer2_init(); // Set up, stop, and reset timer2 timer0_init(); usart_puts("Initialize ADC\r\n"); adc_init(); usart_puts("Initialize LCD\r\n"); lcd_init(); // From LDC_driver usart_puts("Start main loop\r\n"); lcd_puts("Hello",0); // From LCD_functions timer2_start(); // Start stimulus adc_mux(1); // Switch to the voltage reader at J407 for(;;) { adc_read(&adc_data); adc_report(adc_data); OCR0A = (uint8_t)(adc_data); }// end main for loop } // end main
void zbus_core_init(void) { /* Initialize the usart module */ usart_init(); /* Enable RX/TX Swtich as Output */ DDR_CONFIG_OUT(ZBUS_RXTX_PIN); #ifdef HAVE_ZBUS_RX_PIN DDR_CONFIG_OUT(ZBUS_RX_PIN); #endif #ifdef HAVE_ZBUS_TX_PIN DDR_CONFIG_OUT(ZBUS_TX_PIN); #endif /* clear the buffers */ zbus_txlen = 0; zbus_rxlen = 0; zbus_index = 0; zbus_rxstart (); }
/** * @brief Low level serial driver configuration and (re)start. * * @param[in] sdp pointer to a @p SerialDriver object * @param[in] config the architecture-dependent serial driver configuration. * If this parameter is set to @p NULL then a default * configuration is used. * * @notapi */ void sd_lld_start(SerialDriver *sdp, const SerialConfig *config) { if (config == NULL) config = &default_config; if (sdp->state == SD_STOP) { #if USE_SAM7_USART0 if (&SD1 == sdp) { /* Starts the clock and clears possible sources of immediate interrupts.*/ AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_US0); /* Enables associated interrupt vector.*/ AIC_EnableIT(AT91C_ID_US0); } #endif #if USE_SAM7_USART1 if (&SD2 == sdp) { /* Starts the clock and clears possible sources of immediate interrupts.*/ AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_US1); /* Enables associated interrupt vector.*/ AIC_EnableIT(AT91C_ID_US1); } #endif #if (SAM7_PLATFORM == SAM7A3) #if USE_SAM7_USART2 if (&SD3 == sdp) { /* Starts the clock and clears possible sources of immediate interrupts.*/ AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_US2); /* Enables associated interrupt vector.*/ AIC_EnableIT(AT91C_ID_US2); } #endif #endif /* (SAM7_PLATFORM == SAM7A3) */ /* Note - no explicit start for SD3 (DBGU_UART) since it's not included in the AIC or PMC.*/ } usart_init(sdp, config); }
int main(void) { uint8_t i, j; /*-----------------------------------------------------------------------*/ SBI(DDRB, 0); SBI(DDRC, 5); SBI(PORTC, 5); /*-----------------------------------------------------------------------*/ usart_init(9600, 1, 0); /*-----------------------------------------------------------------------*/ /*Any logical change on INT0 triggers an interrupt*/ MCUCR |= (0 << ISC01) | (1 << ISC00); GICR |= (1 << INT0); /*-----------------------------------------------------------------------*/ /*CTC on ICR1 compare*/ TCCR1A |= (0 << WGM10) | (0 << WGM11); TCCR1B |= (1 << WGM13) | (1 << WGM12); TIMSK |= (1 << TICIE1); /*-----------------------------------------------------------------------*/ c_count = 0; pin_state = 0; TCNT1 = 0; ICR1 = ICR1_RP; /*-----------------------------------------------------------------------*/ for(i = 0; i < NUM_PULSES; i++){ ir_codes[i][0] = eeprom_read_byte(ir_code_eeprom_start + i * PULSE_DATA_LEN); if(ir_codes[i][0] > PULSE_DATA_LEN) ir_codes[i][0] = 1; for(j = 1; j < ir_codes[i][0]; j++) ir_codes[i][j] = eeprom_read_byte(ir_code_eeprom_start + i * PULSE_DATA_LEN + j); } /*-----------------------------------------------------------------------*/ sei(); while(1); }
void init_drivers( ) { usart_init(USART_SET_THIS_BAUDRATE); gpio_init_pin(PIN_2T0, GPIO_OUTPUT, GPIO_LOW); gpio_init_pin(PIN_2T1, GPIO_OUTPUT, GPIO_LOW); gpio_init_pin(PIN_2T2, GPIO_OUTPUT, GPIO_LOW); gpio_init_pin(PIN_2T3, GPIO_OUTPUT, GPIO_LOW); gpio_init_pin(PIN_5T0, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T1, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T2, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T3, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T4, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T5, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T6, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T7, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T8, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T9, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T10, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin(PIN_5T11, GPIO_INPUT, GPIO_NO_PULL_UP); gpio_init_pin_as_adc(PIN_7T0_ADC0); gpio_init_pin_as_adc(PIN_7T0_ADC1); }
int main(void) { char *str1 = "Shell", *str2 = "Fib_task", *str3 = "Print_task"; usart_init(); if (thread_create(shell,str1, (void *) str1,10) == -1) print_str("Shell creation failed\r\n"); if (thread_create(test_fib,str2, (void *) str2,5) == -1) print_str("Fib_task creation failed\r\n"); if (thread_create(Print_task,str3, (void *) str3,9) == -1) print_str("Print_task creation failed\r\n"); /* SysTick configuration */ *SYSTICK_LOAD = (CPU_CLOCK_HZ / TICK_RATE_HZ) - 1UL; *SYSTICK_VAL = 0; *SYSTICK_CTRL = 0x07; thread_start(); return 0; }
void main () { char buf[20]; int i; int buflen; ADCON1= 0x20; // CONFIGURE ADC --- AN2 TRISA = 0xFF; // MAKE PORTA AS INPUT usart_init(2400); // initialize the usart do { depth=pressure(); itoa(buf, depth); buflen=strlen(buf); for(i=buflen-1; i>=0; i--) { Usart_Write(buf[i]); // write the data } Usart_Write(0x0D); Usart_Write(0x0A) ; } while(1); }
/** * @brief Main program. * @param None * @retval : None */ int main(void) { int i; stopwatch_reset(&stopwatch); /* * Enable peripherals */ rcc_init(); gpio_init(); nvic_init(); usart_init(); tim_init(); delay_ms(1000); iprintf(ANSI_CLRSCR ANSI_BOLD("STM32 Stopwatch") " rev %s, built on %s.\r\n", build_git_description, build_git_time); iprintf("(c) Sami Kujala, 2012. https://github.com/skujala/stm32-stopwatch\r\n"); iprintf("Initialization complete.\r\n"); LED_GPIO->BSRR = (1 << BLUE_LED_PIN); while (1) { if (stopwatch.counter == COUNTER_STOPPED){ for (i = 0; i < 10; i++) { LED_GPIO->ODR ^= (1 << BLUE_LED_PIN); delay_ms(50); } iprintf("Elapsed time: " ANSI_BOLD("%d") " ms.\r\n", TIMER_COUNTS_IN_MS(stopwatch.counts_elapsed)); stopwatch_reset(&stopwatch); } } return 0; }
int main() { /* * used by rotary encoder int rot_a = 0; int rot_b = 0; int prev_val = 0; */ /* Initialize Clock Rate */ usart_init(47); shift_init(); DDRD &= (1 << PD5); // Set PORTD bit 5 for input, take in rotary bit A DDRD &= (1 << PD6); // Set PORTD bit 6 for input, take in rotary bit B PORTD |= (1 << PD5); // Activate pull-ups in PORTD pi PORTD |= (1 << PD6); // Activate pull-ups in PORTD pi /* main loop * every cycle, read at the beginning, write at the end * */ uint8_t zone_reg = 0; while (1) { int temperature = get_temperature(); int moisture = get_moisture(); char zone_char = usart_in(); usart_putchar('\n'); char temp_write_buf[36]; snprintf(temp_write_buf, 36, "Temp: %ld F, Moisture: %d, ", CtoF(temperature), moisture); usart_out(temp_write_buf); _delay_ms(200); /** * Rotary Encoder - Deprecated * Read inputs rot_a = (PIND & (1 << PD5)); // Read value on PD5 rot_b = (PIND & (1 << PD6)); // Read value on PD6 if ((prev_val == 0) && (rot_a == 32)) { if (rot_b == 64) { zone_char--; } else { zone_char++; } } prev_val = rot_a; */ /* we only accept zones 1 through 8, 0 to turn off */ char zone_write_buf[17]; if (zone_char >= '0' && zone_char <= '8') { snprintf(zone_write_buf, 17, "Current Zone: %c\r\n", zone_char); usart_out(zone_write_buf); _delay_ms(200); if (zone_char > '0') { uint8_t zone_onehot = (uint8_t) (1 << (zone_char - '1')); shift_write(zone_onehot); zone_reg = (uint8_t) (zone_char - '0'); } else { if (zone_char == '0') { zone_reg = 0; } shift_write(0); } } else { snprintf(zone_write_buf, 17, "Current Zone: %c\r\n", (char) (zone_reg + '0')); usart_out(zone_write_buf); _delay_ms(200); } } return 0; }
void USARTSerial::begin(const uint32_t baud) { usart_init(&port, port.USARTx, pinrx, pintx, baud); }
int main(void) { /* disable interrupts */ cli(); /* input for IR and rest, no pull up resistor */ DDRB = 0x00; PORTB &= ~_BV(PORTB0); /* LED output pin, off */ DDRD |= _BV(LED_PIN); LED_PORT &= ~_BV(LED_PIN); /* initialize USART */ usart_init(BAUD_PRESCALE); /* configure 16bit timer 1 for 1uS @ 8MHz using clk/8 prescaler */ TCCR1B |= (1 << CS11); /* flash LED to confirm initialization complete */ LED_PORT |= _BV(LED_PIN); _delay_ms(500); LED_PORT &= ~_BV(LED_PIN); int in_phase = 0; while(1) { /* if we are not in phase and the IR pin is high, we are now in phase, * so we reset the timer and start recording how long this phase length is */ if(in_phase == 0 && (PINB & _BV(IR_PIN))) { in_phase = 1; TCNT1 = 0; continue; } /* if we are in phase and the IR pin goes low, we cut off the timer and measure the * phase length. if it's greater than the length of our IR start bit, we assume * the data bits will follow */ if(in_phase == 1 && !(PINB & _BV(IR_PIN))) { int phase_len = TCNT1; in_phase = 0; if(phase_len >= IR_BIT_START && phase_len < (IR_BIT_START * 2)) { /* LED pin high to indicate a signal */ LED_PORT |= _BV(LED_PIN); uint32_t value = 0; int x; for(x = 0; x < IR_BITS; x++) { /* wait for a new phase to start. once one does, we reset our timer * and wait for it to end */ while(!(PINB & _BV(IR_PIN))); TCNT1 = 0; while((PINB & _BV(IR_PIN))); phase_len = TCNT1; /* translate the phase length to bit value and shift into our final value */ if(phase_len >= IR_BIT_1) { value |= (1 << (IR_BITS - x)); } else if(phase_len >= IR_BIT_0) { /* nothing needed for this bit to remain 0 */ } else { /* for now if it doesn't match up with any of our phase lengths, we mark the value * as an error and we will ignore it */ value = -1; break; } } /* if we successfully received the IR data we transmit through usart*/ if(value != -1) { char v_str[50] = {0}; ultoa(value, v_str, 10); int x; for(x = 0; x < strlen(v_str); x++) { usart_tx(v_str[x]); } usart_tx('\n'); } LED_PORT &= ~_BV(LED_PIN); } } } }
//******************************************************************************* //* This is where we get the chunks of data //* to program to the dataflash //******************************************************************************* void image_interface_begin(void) { unsigned int page_count = 0; unsigned char command = 0; unsigned char *buff; unsigned int page_num = 0; boolean keepGoing; #ifdef _TOUCH_STEALTH_ COLOR black = {0,0,0}; COLOR white = {255,255,255}; #endif /* order of operations: 1.) purge usart buffers 2.) recv mode byte 3.) if mode == STORE, recv page_count recv all pages else mode == READ send page_count send pages */ #ifdef _USE_DBBUG_RECT_STATUS_ DebugRectPrintText("image_interface_begin()"); #endif arduinoReset(); usart_init(115200); // usart_init(57600); #ifdef _USE_DBBUG_RECT_STATUS_ DebugRectPrintText("usart_init 115200"); #endif #ifdef _USE_DBBUG_RECT_STATUS_ DebugRectPrintText("arduino in reset"); #endif cli(); buff = usart_getBuff_ptr(); //enough setup, lets begin keepGoing = TRUE; while(keepGoing) { usart_read_bytes(1); // Wait for us to read a byte command = buff[0]; // store or read command #ifdef _TOUCH_STEALTH_ if (command == IMAGE_INTERFACE_ERASE) { dispPutS("Erasing",0,0,white,black); dataflash_erase(); usart_putc(IMAGE_INTERFACE_PAGE_DONE); //ok dispPutS("Erasing Done",0,10,white,black); } else #endif if (command == IMAGE_INTERFACE_STORE) { unsigned int x; unsigned int ii,wait,wait2; unsigned char out_data[DATAFLASH_PAGESIZE],in_data[DATAFLASH_PAGESIZE]; #ifdef _USE_DBBUG_RECT_STATUS_ DebugRectPrintText("IMAGE_INTERFACE_STORE"); #endif buff = usart_getBuff_ptr(); dataflash_erase(); usart_putc(IMAGE_INTERFACE_PAGE_DONE); //done erasing #ifdef _USE_DBBUG_RECT_STATUS_ DebugRectPrintText("done erasing "); #endif //give us the number of pages you're sending usart_read_bytes(2); page_count = (buff[0] << 8) + buff[1]; //number of pages for (ii=0; ii< page_count; ii++) { unsigned int buffer_count = 0; #ifdef _USE_DBBUG_RECT_STATUS_ // DebugRectPrintText("Page"); #endif usart_read_bytes(DATAFLASH_PAGESIZE); //read the whole page buffer_count = usart_getBuff_size(); //program the whole page for(x=0;x<DATAFLASH_PAGESIZE;x++) { out_data[x] = buff[x]; } dataflash_program_page(&out_data[0], ii); //program the page for(x=0;x<DATAFLASH_PAGESIZE;x++) in_data[x] = 0x00; dataflash_cont_read(&in_data[0], ii, DATAFLASH_PAGESIZE); for (x=0;x<DATAFLASH_PAGESIZE;x++) { if (x==256) { for (wait = 0; wait < 254; wait++) { for (wait2 = 0; wait2 < 254; wait2++) { asm("nop"); } } } usart_putc(in_data[x]); asm("nop"); } } } else if (command == IMAGE_INTERFACE_READ) { unsigned int x; unsigned char out[DATAFLASH_PAGESIZE]; #ifdef _USE_DBBUG_RECT_STATUS_ DebugRectPrintText("IMAGE_INTERFACE_READ"); #endif page_num=0; //give us the number of pages you're sending usart_read_bytes(2); page_num = (buff[0] << 8) + buff[1]; //number of pages dataflash_cont_read(&out[0], page_num, DATAFLASH_PAGESIZE); for (x=0; x<DATAFLASH_PAGESIZE; x++) { usart_putc(out[x]); } asm("nop"); } else if (command == IMAGE_INTERFACE_INFO) { short ii; char validImage; short bmpWidth; short bmpHeight; char displayLine[64]; usart_puts("\nTouch Shield | ver 002\n"); usart_putc(0); ii = 0; validImage = TRUE; while (validImage && (ii < BMP_MAXBMP_COUNT)) { bmp_get_entryname(ii, displayLine, &bmpWidth, &bmpHeight); usart_puts(displayLine); usart_puts("\n"); ii++; } } else if (command == IMAGE_INTERFACE_EXIT) { usart_puts("Exit Command\n"); sei(); //enable interrupts bmp_init(); usart_putc(IMAGE_INTERFACE_PAGE_DONE); //ok arduinoRun(); keepGoing = FALSE; // break; } }//end while } //end function
int main(void) { char tmp[256]; const char message[] = "This royal throne of kings, this scepter'd isle, \n" "This earth of majesty, this seat of Mars, \n" /* "This other Eden, demi-paradise, \n" "This fortress built by Nature for herself\n" "Against infection and the hand of war, \n" "This happy breed of men, this little world,\n" "This precious stone set in the silver sea, \n" "Which serves it in the office of a wall, \n" "Or as a moat defensive to a house, \n" "Against the envy of less happier lands, \n" "This blessed plot, this earth, this realm, this England,"*/ ; const uint16 messlen = strlen(message); cmcore_init(); usart_init(&Serial6, USART6, PC7, PC6); usart_begin(&Serial6, 57600); spi_init(&spi1, SPI1, PA5, PA6, PA7, PA4); spi_begin(&spi1); usart_print(&Serial6, "Basic initialization has been finished.\n"); RCC_ClocksTypeDef RCC_Clocks; RCC_GetClocksFreq(&RCC_Clocks); usart_print(&Serial6, message); usart_print(&Serial6, "\r\n\r\n"); usart_flush(&Serial6); sprintf(tmp, "Clock frequencies: SYSCLK = %dl, HCLK = %dl, PCLK1 = %dl\r\n", RCC_Clocks.SYSCLK_Frequency, RCC_Clocks.HCLK_Frequency, RCC_Clocks.PCLK1_Frequency); usart_print(&Serial6, tmp); GPIOMode(PinPort(LED1), (PinBit(LED1) | PinBit(LED2) | PinBit(LED3) | PinBit(LED4)), OUTPUT, FASTSPEED, PUSHPULL, NOPULL); nokiaLCD.init(); nokiaLCD.clear(); nokiaLCD.drawBitmap(PCD8544::SFEFlame); delay(1000); uint16 shift = 0; nokiaLCD.selectFont(PCD8544::CHICAGO10); while (1) { nokiaLCD.clear(); nokiaLCD.cursor(shift); nokiaLCD.drawString("Nuke is absolutely safe!"); // nokiaLCD.drawFont(Nokia5110::Chicago10x15, 'A'); // nokiaLCD.drawFont(Nokia5110::Chicago10x15, 'W'); shift++; shift %= 252; delay(250); /* if ( millis() / 125 != shift ) { shift = millis()/ 125; nokiaLCD.clear(); nokiaLCD.gotoXY(7- shift%7,0); strncpy(tmp, message+((shift/7) % messlen), 48); tmp[48] = 0; nokiaLCD.drawString(tmp); // usart_print(&Serial6, tmp); // usart_print(&Serial6, "\r\n"); } */ } }
/** Initialize the debug UART. */ void debug_uart_init(void) { usart_init(DEBUG_UART, 115200); usart_enable(DEBUG_UART); }
int main(void) { uint16_t counter; char c; uint8_t stop = TRUE; usart_init(); sonar_init(); rtc_setup(); counter = 0; usart_resume(0); strcpy_P(usart->tx0_buffer, PSTR("\nTsunami Simulator ")); strcat_P(usart->tx0_buffer, PSTR(GITREL)); strcat_P(usart->tx0_buffer, PSTR("\n\nConnected!\n")); usart_printstr(0, NULL); rtc_start(); while (1) { /* Restart the counter */ rtc_clear(); c = usart_getchar(0, FALSE); switch (c) { case '0': stop = TRUE; break; case '1': stop = FALSE; break; default: break; } if (stop) { /* stop the code */ while(usart_getchar(0, FALSE) != '1'); stop = FALSE; rtc_clear(); } /* send the trigger */ sonar_trigger(); /* clear all the data */ sonar_clear(); /* * Wait 40mS maximum and collect all the * data during the period. */ while (rtc_us < 4000) sonar_set(); /* * speed = ((i * SCALEuS)/1000000) * 340 / 2 * where: * i * SCALEuS is the duration in uS of the signal. * (i * SCALEuS)/1000000 is the same in seconds. * 340 is the speed of the sound and * /2 we need only half of the way. * The simplyfied formula in cm. * 340 mm/msec = 34cm/msec = 0.029 msec/cm = 29 uS/cm * dist (cm) = T (uS) / 29 /2. */ usart->tx0_buffer = utoa(counter, usart->tx0_buffer, 10); usart_printstr(0, NULL); usart_printstr(0, " "); counter++; sonar_print(); /* if the counter has already reach 50mS, * then this cycle takes too long. */ if (rtc_us > 5000) usart_printstr(0, "Warning! Time overrun.\n"); /* Wait up to 50mS before restart */ while (rtc_us < 5000); } return(0); }
//! @brief This function initializes the hardware/software resources required for ushell task. //! void ushell_task_init(uint32_t pba_hz) { uint8_t u8_i; //** Initialize the USART used by uShell with the configured parameters static const gpio_map_t SHL_USART_GPIO_MAP = { {SHL_USART_RX_PIN, SHL_USART_RX_FUNCTION}, {SHL_USART_TX_PIN, SHL_USART_TX_FUNCTION} }; #if (defined __GNUC__) set_usart_base((void *)SHL_USART); gpio_enable_module(SHL_USART_GPIO_MAP, sizeof(SHL_USART_GPIO_MAP) / sizeof(SHL_USART_GPIO_MAP[0])); usart_init(SHL_USART_BAUDRATE); #elif (defined __ICCAVR32__) static const usart_options_t SHL_USART_OPTIONS = { .baudrate = SHL_USART_BAUDRATE, .charlength = 8, .paritytype = USART_NO_PARITY, .stopbits = USART_1_STOPBIT, .channelmode = USART_NORMAL_CHMODE }; extern volatile avr32_usart_t *volatile stdio_usart_base; stdio_usart_base = SHL_USART; gpio_enable_module(SHL_USART_GPIO_MAP, sizeof(SHL_USART_GPIO_MAP) / sizeof(SHL_USART_GPIO_MAP[0])); usart_init_rs232(SHL_USART, &SHL_USART_OPTIONS, pba_hz); #endif //** Configure standard I/O streams as unbuffered. #if (defined __GNUC__) setbuf(stdin, NULL); #endif setbuf(stdout, NULL); // Set default state of ushell g_b_ushell_task_run = false; for( u8_i=0; u8_i<USHELL_HISTORY; u8_i++ ) { g_s_cmd_his[u8_i][0] = 0; // Set end of line for all cmd line history } fputs(MSG_EXIT, stdout ); g_u32_ushell_pba_hz = pba_hz; // Save value to manage a time counter during perform command #ifdef FREERTOS_USED xTaskCreate(ushell_task, configTSK_USHELL_NAME, configTSK_USHELL_STACK_SIZE, NULL, configTSK_USHELL_PRIORITY, NULL); #endif // FREERTOS_USED } #ifdef FREERTOS_USED /*! \brief Entry point of the explorer task management. * * This function performs uShell decoding to access file-system functions. * * \param pvParameters Unused. */ void ushell_task(void *pvParameters) #else /*! \brief Entry point of the explorer task management. * * This function performs uShell decoding to access file-system functions. */ void ushell_task(void) #endif { #ifdef FREERTOS_USED //** Inifinite loop for RTOS because it is a RTOS task portTickType xLastWakeTime; xLastWakeTime = xTaskGetTickCount(); while (true) { vTaskDelayUntil(&xLastWakeTime, configTSK_USHELL_PERIOD); #else //** No loop with the basic scheduler { #endif // FREERTOS_USED //** Check the USB mode and authorize/unauthorize ushell if(!g_b_ushell_task_run) { if( Is_usb_id_device() ) #ifdef FREERTOS_USED continue; // Continue in the RTOS task #else return; // Exit of the task scheduled #endif g_b_ushell_task_run = true; // Display shell startup fputs(MSG_WELCOME, stdout); ushell_cmd_nb_drive(); fputs(MSG_PROMPT, stdout); // Reset the embedded FS on ushell navigator and on first drive nav_reset(); nav_select( FS_NAV_ID_USHELL_CMD ); nav_drive_set( 0 ); }else{ if( Is_usb_id_device() ) { g_b_ushell_task_run = false; fputs(MSG_EXIT, stdout ); nav_exit(); #ifdef FREERTOS_USED continue; // Continue in the RTOS task #else return; // Exit of the task scheduled #endif } } //** Scan shell command if( !ushell_cmd_scan() ) #ifdef FREERTOS_USED continue; // Continue in the RTOS task #else return; // Exit of the task scheduled #endif //** Command ready then decode and execute this one switch( ushell_cmd_decode() ) { // Displays number of drives case CMD_NB_DRIVE: ushell_cmd_nb_drive(); break; // Displays free space information for all connected drives case CMD_DF: ushell_cmd_free_space(); break; // Formats disk case CMD_FORMAT: ushell_cmd_format(); break; // Mounts a drive (e.g. "b:") case CMD_MOUNT: ushell_cmd_mount(); break; // Displays the space information for current drive case CMD_SPACE: ushell_cmd_space(); break; // Lists the files present in current directory (e.g. "ls") case CMD_LS: ushell_cmd_ls(false); break; case CMD_LS_MORE: ushell_cmd_ls(true); break; // Enters in a directory (e.g. "cd folder_toto") case CMD_CD: ushell_cmd_cd(); break; // Enters in parent directory ("cd..") case CMD_UP: ushell_cmd_gotoparent(); break; // Displays a text file case CMD_CAT: ushell_cmd_cat(false); break; case CMD_CAT_MORE: ushell_cmd_cat(true); break; // Displays the help case CMD_HELP: ushell_cmd_help(); break; // Creates directory case CMD_MKDIR: ushell_cmd_mkdir(); break; // Creates file case CMD_TOUCH: ushell_cmd_touch(); break; // Deletes files or directories case CMD_RM: ushell_cmd_rm(); break; // Appends char to selected file case CMD_APPEND: ushell_cmd_append_file(); break; // Index routines (= specific shortcut from ATMEL FileSystem) case CMD_SET_ID: g_mark_index = nav_getindex(); break; case CMD_GOTO_ID: nav_gotoindex( &g_mark_index ); break; // Copies file to other location case CMD_CP: ushell_cmd_copy(); break; // Renames file case CMD_MV: ushell_cmd_rename(); break; // Synchronize folders case CMD_SYNC: ushell_cmd_sync(); break; case CMD_PERFORM: ushell_cmd_perform(); break; // USB commands #if USB_HOST_FEATURE == true case CMD_LS_USB: ushell_cmdusb_ls(); break; case CMD_USB_SUSPEND: ushell_cmdusb_suspend(); break; case CMD_USB_RESUME: ushell_cmdusb_resume(); break; #endif case CMD_NONE: break; // Unknown command default: fputs(MSG_ER_CMD_NOT_FOUND, stdout); break; } fputs(MSG_PROMPT, stdout); } } //! @brief Get the full command line to be interpreted. //! //! @return true, if a command is ready //! bool ushell_cmd_scan(void) { int c_key; // Something new of the UART ? if (usart_read_char(SHL_USART, &c_key) != USART_SUCCESS) { usart_reset_status(SHL_USART); return false; } if( 0 != g_u8_escape_sequence ) { //** Decode escape sequence if( 1 == g_u8_escape_sequence ) { if( 0x5B != c_key ) { g_u8_escape_sequence=0; return false; // Escape sequence cancel } g_u8_escape_sequence=2; } else { // Decode value of the sequence switch (c_key) { /* Note: OVERRUN error on USART with an RTOS and USART without interrupt management If you want support "Escape sequence", then you have to implement USART interrupt management case 0x41: // UP command ushell_clean_cmd_line(); ushell_history_up(); ushell_history_display(); break; case 0x42: // DOWN command ushell_clean_cmd_line(); ushell_history_down(); ushell_history_display(); break; */ default: // Ignore other command break; } g_u8_escape_sequence=0; // End of Escape sequence } return false; } //** Normal sequence switch (c_key) { //** Command validation case ASCII_CR: putchar(ASCII_CR); // Echo putchar(ASCII_LF); // Add new line flag g_s_cmd_his[g_u8_history_pos][g_u8_cmd_size]=0; // Add NULL terminator at the end of command line return true; //** Enter in escape sequence case ASCII_ESCAPE: g_u8_escape_sequence=1; break; //** backspace case ASCII_BKSPACE: if(g_u8_cmd_size>0) // Beginning of line ? { // Remove the last character on terminal putchar(ASCII_BKSPACE); // Send a backspace to go in previous character putchar(' '); // Send a space to erase previous character putchar(ASCII_BKSPACE); // Send a backspace to go in new end position (=previous character position) // Remove the last character on cmd line buffer g_u8_cmd_size--; } break; // History management case '!': ushell_clean_cmd_line(); ushell_history_up(); ushell_history_display(); break; case '$': ushell_clean_cmd_line(); ushell_history_down(); ushell_history_display(); break; //** Other char default: if( (0x1F<c_key) && (c_key<0x7F) && (USHELL_SIZE_CMD_LINE!=g_u8_cmd_size) ) { // Accept char putchar(c_key); // Echo g_s_cmd_his[g_u8_history_pos][g_u8_cmd_size++] = c_key; // append to cmd line } break; } return false; }
void serial_line_log_init (void) { /* Initialize the usart module */ usart_init (); }
void yport_init(void) { usart_init(); }
int main( void ){ uint8_t error; Packet packet; Queue* packets; packets = Packets_getQueue(); // initialize pwm pwm_init(); pwm_set_scalar(1); pwm_set(PWM_CHAN_A, 127); // initialize Time time_init(); TimeResult tr, rpm_tr; uint32_t previous = 0; rpm_tr.previous = 0; // enable external interrupt for INT0 //setbit(MCUCR, BIT(ISC01) | BIT(ISC00)); setbit(MCUCR,BIT(ISC00)); setbit(GICR, BIT(INT0)); // initialize rpm counter InterruptCounterResult icr; icr.previous = 0; float rpm = 0, prev_rpm = 0, time_ms = 0, rpm_delta = 0; uint16_t* rpm_target_p; float pwm_power = 0; float pwm_acc = 0; float rpm_target = 0; rpm_target_p = get_rpm_handle(); *rpm_target_p = 1000; // initialize usart usart_init(); // enable interrupts sei(); // set initial value pwm_set_scalar(3); pwm_set(1,256); // loop forever while(1){ error = Packets_getError(); if (error){ Packets_sendError(ERROR_PACKETS, error); continue; } if (packets->count > 0){ error = 0x00; packet = Packets_getNext(); error = Queue_getError(packets); if (error){ Packets_sendError(ERROR_QUEUE, error); continue; } handle_packet(packet); } tr = time_get_time_delta(previous); // every 20ms, calculate rpm if (get_time_in_ms(tr.delta) > 20){ previous = tr.previous; // calculate RPM rpm_tr = time_get_time_delta(rpm_tr.previous); icr = interrupt_counter_delta(icr.previous); time_ms = get_time_in_ms(rpm_tr.delta); rpm = (double) icr.delta /(double) 32 / (double) time_ms * (double) 1000 * (double) 60; rpm_target_p = get_rpm_handle(); rpm_target = (float) *rpm_target_p; rpm_delta = rpm_delta * 0.65 + (rpm - prev_rpm) * 0.35; //pwm_acc = (rpm_target - rpm) * 0.01 - rpm_delta * 0.05; pwm_acc = (rpm_target - rpm) * 0.015 - rpm_delta * 0.15; if (pwm_acc < - pwm_power) pwm_power = 0; else if (pwm_acc + pwm_power > 1023) pwm_power = 1023; else{ pwm_power = pwm_power + pwm_acc; } if (rpm_target == 0) pwm_power = 0; pwm_set(1,floor(pwm_power)); prev_rpm = rpm; cmd_send_debug16( 'r', (uint16_t) rpm); } } }
/** * @brief Main function. */ int main(void) { /* load settings and parameters */ global_data_reset_param_defaults(); global_data_reset(); /* init led */ LEDInit(LED_ACT); LEDInit(LED_COM); LEDInit(LED_ERR); LEDOff(LED_ACT); LEDOff(LED_COM); LEDOff(LED_ERR); /* enable FPU on Cortex-M4F core */ SCB_CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); /* set CP10 Full Access and set CP11 Full Access */ /* init clock */ if (SysTick_Config(SystemCoreClock / 1000)) { /* capture clock error */ LEDOn(LED_ERR); while (1); } /* init usb */ USBD_Init( &USB_OTG_dev, USB_OTG_FS_CORE_ID, &USR_desc, &USBD_CDC_cb, &USR_cb); /* init mavlink */ communication_init(); /* enable image capturing */ enable_image_capture(); /* gyro config */ gyro_config(); /* init and clear fast image buffers */ for (int i = 0; i < global_data.param[PARAM_IMAGE_WIDTH] * global_data.param[PARAM_IMAGE_HEIGHT]; i++) { image_buffer_8bit_1[i] = 0; image_buffer_8bit_2[i] = 0; } uint8_t * current_image = image_buffer_8bit_1; uint8_t * previous_image = image_buffer_8bit_2; /* usart config*/ usart_init(); /* i2c config*/ i2c_init(); /* sonar config*/ float sonar_distance_filtered = 0.0f; // distance in meter float sonar_distance_raw = 0.0f; // distance in meter bool distance_valid = false; sonar_config(); /* reset/start timers */ timer[TIMER_SONAR] = SONAR_TIMER_COUNT; timer[TIMER_SYSTEM_STATE] = SYSTEM_STATE_COUNT; timer[TIMER_RECEIVE] = SYSTEM_STATE_COUNT / 2; timer[TIMER_PARAMS] = PARAMS_COUNT; timer[TIMER_IMAGE] = global_data.param[PARAM_VIDEO_RATE]; /* variables */ uint32_t counter = 0; uint8_t qual = 0; /* bottom flow variables */ float pixel_flow_x = 0.0f; float pixel_flow_y = 0.0f; float pixel_flow_x_sum = 0.0f; float pixel_flow_y_sum = 0.0f; float velocity_x_sum = 0.0f; float velocity_y_sum = 0.0f; float velocity_x_lp = 0.0f; float velocity_y_lp = 0.0f; int valid_frame_count = 0; int pixel_flow_count = 0; /* main loop */ while (1) { /* reset flow buffers if needed */ if(buffer_reset_needed) { buffer_reset_needed = 0; for (int i = 0; i < global_data.param[PARAM_IMAGE_WIDTH] * global_data.param[PARAM_IMAGE_HEIGHT]; i++) { image_buffer_8bit_1[i] = 0; image_buffer_8bit_2[i] = 0; } delay(500); continue; } /* calibration routine */ if(global_data.param[PARAM_CALIBRATION_ON]) { while(global_data.param[PARAM_CALIBRATION_ON]) { dcmi_restart_calibration_routine(); /* waiting for first quarter of image */ while(get_frame_counter() < 2){} dma_copy_image_buffers(¤t_image, &previous_image, FULL_IMAGE_SIZE, 1); /* waiting for second quarter of image */ while(get_frame_counter() < 3){} dma_copy_image_buffers(¤t_image, &previous_image, FULL_IMAGE_SIZE, 1); /* waiting for all image parts */ while(get_frame_counter() < 4){} send_calibration_image(&previous_image, ¤t_image); if (global_data.param[PARAM_SYSTEM_SEND_STATE]) communication_system_state_send(); communication_receive_usb(); debug_message_send_one(); communication_parameter_send(); LEDToggle(LED_COM); } dcmi_restart_calibration_routine(); LEDOff(LED_COM); } uint16_t image_size = global_data.param[PARAM_IMAGE_WIDTH] * global_data.param[PARAM_IMAGE_HEIGHT]; /* new gyroscope data */ float x_rate_sensor, y_rate_sensor, z_rate_sensor; gyro_read(&x_rate_sensor, &y_rate_sensor, &z_rate_sensor); /* gyroscope coordinate transformation */ float x_rate = y_rate_sensor; // change x and y rates float y_rate = - x_rate_sensor; float z_rate = z_rate_sensor; // z is correct /* calculate focal_length in pixel */ const float focal_length_px = (global_data.param[PARAM_FOCAL_LENGTH_MM]) / (4.0f * 6.0f) * 1000.0f; //original focal lenght: 12mm pixelsize: 6um, binning 4 enabled /* debug */ float x_rate_pixel = x_rate * (get_time_between_images() / 1000.0f) * focal_length_px; float y_rate_pixel = y_rate * (get_time_between_images() / 1000.0f) * focal_length_px; //FIXME for the old sensor PX4FLOW v1.2 uncomment this!!!! // x_rate = x_rate_raw_sensor; // change x and y rates // y_rate = y_rate_raw_sensor; /* get sonar data */ sonar_read(&sonar_distance_filtered, &sonar_distance_raw); /* compute optical flow */ if(global_data.param[PARAM_SENSOR_POSITION] == BOTTOM) { /* copy recent image to faster ram */ dma_copy_image_buffers(¤t_image, &previous_image, image_size, 1); /* compute optical flow */ qual = compute_flow(previous_image, current_image, x_rate, y_rate, z_rate, &pixel_flow_x, &pixel_flow_y); if (sonar_distance_filtered > 5.0f || sonar_distance_filtered == 0.0f) { /* distances above 5m are considered invalid */ sonar_distance_filtered = 0.0f; distance_valid = false; } else { distance_valid = true; } /* * real point P (X,Y,Z), image plane projection p (x,y,z), focal-length f, distance-to-scene Z * x / f = X / Z * y / f = Y / Z */ float flow_compx = pixel_flow_x / focal_length_px / (get_time_between_images() / 1000.0f); float flow_compy = pixel_flow_y / focal_length_px / (get_time_between_images() / 1000.0f); /* integrate velocity and output values only if distance is valid */ if (distance_valid) { /* calc velocity (negative of flow values scaled with distance) */ float new_velocity_x = - flow_compx * sonar_distance_filtered; float new_velocity_y = - flow_compy * sonar_distance_filtered; if (qual > 0) { velocity_x_sum += new_velocity_x; velocity_y_sum += new_velocity_y; valid_frame_count++; /* lowpass velocity output */ velocity_x_lp = global_data.param[PARAM_BOTTOM_FLOW_WEIGHT_NEW] * new_velocity_x + (1.0f - global_data.param[PARAM_BOTTOM_FLOW_WEIGHT_NEW]) * velocity_x_lp; velocity_y_lp = global_data.param[PARAM_BOTTOM_FLOW_WEIGHT_NEW] * new_velocity_y + (1.0f - global_data.param[PARAM_BOTTOM_FLOW_WEIGHT_NEW]) * velocity_y_lp; } else { /* taking flow as zero */ velocity_x_lp = (1.0f - global_data.param[PARAM_BOTTOM_FLOW_WEIGHT_NEW]) * velocity_x_lp; velocity_y_lp = (1.0f - global_data.param[PARAM_BOTTOM_FLOW_WEIGHT_NEW]) * velocity_y_lp; } } else { /* taking flow as zero */ velocity_x_lp = (1.0f - global_data.param[PARAM_BOTTOM_FLOW_WEIGHT_NEW]) * velocity_x_lp; velocity_y_lp = (1.0f - global_data.param[PARAM_BOTTOM_FLOW_WEIGHT_NEW]) * velocity_y_lp; } pixel_flow_x_sum += pixel_flow_x; pixel_flow_y_sum += pixel_flow_y; pixel_flow_count++; } counter++; /* TODO for debugging */ //mavlink_msg_named_value_float_send(MAVLINK_COMM_2, boot_time_ms, "blabla", blabla); if(global_data.param[PARAM_SENSOR_POSITION] == BOTTOM) { /* send bottom flow if activated */ if (counter % 2 == 0) { float flow_comp_m_x = 0.0f; float flow_comp_m_y = 0.0f; float ground_distance = 0.0f; if(global_data.param[PARAM_BOTTOM_FLOW_LP_FILTERED]) { flow_comp_m_x = velocity_x_lp; flow_comp_m_y = velocity_y_lp; } else { flow_comp_m_x = velocity_x_sum/valid_frame_count; flow_comp_m_y = velocity_y_sum/valid_frame_count; } if(global_data.param[PARAM_SONAR_FILTERED]) ground_distance = sonar_distance_filtered; else ground_distance = sonar_distance_raw; if (valid_frame_count > 0) { // send flow mavlink_msg_optical_flow_send(MAVLINK_COMM_0, get_boot_time_ms() * 1000, global_data.param[PARAM_SENSOR_ID], pixel_flow_x_sum * 10.0f, pixel_flow_y_sum * 10.0f, flow_comp_m_x, flow_comp_m_y, qual, ground_distance); if (global_data.param[PARAM_USB_SEND_FLOW]) mavlink_msg_optical_flow_send(MAVLINK_COMM_2, get_boot_time_ms() * 1000, global_data.param[PARAM_SENSOR_ID], pixel_flow_x_sum * 10.0f, pixel_flow_y_sum * 10.0f, flow_comp_m_x, flow_comp_m_y, qual, ground_distance); update_TX_buffer(pixel_flow_x_sum * 10.0f, pixel_flow_y_sum * 10.0f, flow_comp_m_x, flow_comp_m_y, qual, ground_distance, x_rate, y_rate, z_rate); } else { // send distance mavlink_msg_optical_flow_send(MAVLINK_COMM_0, get_boot_time_ms() * 1000, global_data.param[PARAM_SENSOR_ID], pixel_flow_x_sum * 10.0f, pixel_flow_y_sum * 10.0f, 0.0f, 0.0f, 0, ground_distance); if (global_data.param[PARAM_USB_SEND_FLOW]) mavlink_msg_optical_flow_send(MAVLINK_COMM_2, get_boot_time_ms() * 1000, global_data.param[PARAM_SENSOR_ID], pixel_flow_x_sum * 10.0f, pixel_flow_y_sum * 10.0f, 0.0f, 0.0f, 0, ground_distance); update_TX_buffer(pixel_flow_x_sum * 10.0f, pixel_flow_y_sum * 10.0f, 0.0f, 0.0f, 0, ground_distance, x_rate, y_rate, z_rate); } if(global_data.param[PARAM_USB_SEND_GYRO]) { mavlink_msg_debug_vect_send(MAVLINK_COMM_2, "GYRO", get_boot_time_ms() * 1000, x_rate, y_rate, z_rate); } velocity_x_sum = 0.0f; velocity_y_sum = 0.0f; pixel_flow_x_sum = 0.0f; pixel_flow_y_sum = 0.0f; valid_frame_count = 0; pixel_flow_count = 0; } } /* forward flow from other sensors */ if (counter % 2) { communication_receive_forward(); } /* send system state, receive commands */ if (send_system_state_now) { /* every second */ if (global_data.param[PARAM_SYSTEM_SEND_STATE]) { communication_system_state_send(); } send_system_state_now = false; } /* receive commands */ if (receive_now) { /* test every second */ communication_receive(); communication_receive_usb(); receive_now = false; } /* sending debug msgs and requested parameters */ if (send_params_now) { debug_message_send_one(); communication_parameter_send(); send_params_now = false; } /* transmit raw 8-bit image */ if (global_data.param[PARAM_USB_SEND_VIDEO] && send_image_now) { /* get size of image to send */ uint16_t image_size_send; uint16_t image_width_send; uint16_t image_height_send; image_size_send = image_size; image_width_send = global_data.param[PARAM_IMAGE_WIDTH]; image_height_send = global_data.param[PARAM_IMAGE_HEIGHT]; if (global_data.param[PARAM_VIDEO_USB_MODE] == CAM_VIDEO) { mavlink_msg_data_transmission_handshake_send( MAVLINK_COMM_2, MAVLINK_DATA_STREAM_IMG_RAW8U, image_size_send, image_width_send, image_height_send, image_size_send / 253 + 1, 253, 100); LEDToggle(LED_COM); uint16_t frame; for (frame = 0; frame < image_size_send / 253 + 1; frame++) { mavlink_msg_encapsulated_data_send(MAVLINK_COMM_2, frame, &((uint8_t *) current_image)[frame * 253]); } } else if (global_data.param[PARAM_VIDEO_USB_MODE] == FLOW_VIDEO) { mavlink_msg_data_transmission_handshake_send( MAVLINK_COMM_2, MAVLINK_DATA_STREAM_IMG_RAW8U, image_size_send, image_width_send, image_height_send, image_size_send / 253 + 1, 253, 100); LEDToggle(LED_COM); uint16_t frame; for (frame = 0; frame < image_size / 253 + 1; frame++) { mavlink_msg_encapsulated_data_send(MAVLINK_COMM_2, frame, &((uint8_t *) previous_image)[frame * 253]); } } send_image_now = false; } else if (!global_data.param[PARAM_USB_SEND_VIDEO]) { LEDOff(LED_COM); } } }
/*-----------------------------------------------------------------vSerialTask() * * Handle (usb/serial) from console and monitored device. * The idea here is to handle the incoming characters as quickly as possible. * All data coming from the console or the datalogger * is delimited by <CR><LF>. Finding an end of line "gives" a semaphore. * * eventually this should be moved down to the */ static void vSerialTask(void* pvParameters) { portTickType xLastWakeTime = xTaskGetTickCount(); const portTickType xWakePeriod = 50; usart_init(USART1); usart_set_baud_rate(USART1, USART_USE_PCLK, 9600); usart_enable(USART1); deviceComm.len=0; deviceComm.gotline=false; vSemaphoreCreateBinary( deviceComm.xGotLineSemaphore ); //if( deviceComm.xGotLineSemaphore == NULL ) //{ // FREAK OUT!!! //} consoleComm.len=0; consoleComm.gotline=false; vSemaphoreCreateBinary( consoleComm.xGotLineSemaphore ); //if( consoleComm.xGotLineSemaphore == NULL ) //{ // FREAK THE HELL OUT!!! //} // usart_init(USART2); // usart_set_baud_rate(USART2, USART_USE_PCLK, 9600); // usart_enable(USART2); while (true) { togglePin(YEL_LED); uint32_t rc=0; unsigned char ch; #if 0 if (!deviceComm.gotline) { //rc=usart_data_available(USART1); while (usart_data_available(USART1) && deviceComm.len<(MAX_COMMAND_LINE_LENGTH-1)) { ch=usart_getc(USART1); if (ch=='\r') { deviceComm.gotline=true; deviceComm.line[deviceComm.len]='\0'; //xSemaphoreGive(deviceComm.xGotLineSemaphore); break; } else if (ch!='\n') { deviceComm.line[deviceComm.len++]=ch; } } } #endif if (!consoleComm.gotline) { while(SerialUSB.isConnected() && SerialUSB.available() && consoleComm.len<(MAX_COMMAND_LINE_LENGTH-1)) { ch=SerialUSB.read(); SerialUSB.write(ch); if (ch=='\r') { consoleComm.gotline=true; consoleComm.line[consoleComm.len]='\0'; //xSemaphoreGive(consoleComm.xGotLineSemaphore); break; } else if ((ch==ASCII_DELETE) || (ch==ASCII_BACKSPACE)) { if (consoleComm.len) consoleComm.len--; } else if (ch!='\n') { consoleComm.line[consoleComm.len++]=ch; } } } vTaskDelayUntil(&xLastWakeTime, xWakePeriod); } }
void ctrl_send_state(char state) { usart_init(); usart_transmit(state); }
static void initialize_dbgu(void) { at91_dbgu_hw_init(); usart_init(BAUDRATE(MASTER_CLOCK, 115200)); }
void _start(void) { /* copy data from rom */ if (&__data_start != &__data_start_rom) { unsigned int *src = &__data_start_rom; unsigned int *dest = &__data_start; while (dest != &__data_end) *dest++ = *src++; } /* zero out bss */ unsigned int *bss = &__bss_start; while (bss != &__bss_end) *bss++ = 0; USART_TypeDef *debug_usart; #if TARGET_STM3210E /* configure the usart1 pins */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); GPIO_PinRemapConfig(GPIO_Remap_USART1, DISABLE); GPIO_InitTypeDef init; init.GPIO_Pin = GPIO_Pin_9; init.GPIO_Speed = GPIO_Speed_50MHz; init.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOA, &init); init.GPIO_Pin = GPIO_Pin_10; init.GPIO_Speed = GPIO_Speed_50MHz; init.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOA, &init); debug_usart = USART1; #endif #if TARGET_STM32_P107 /* configure the usart3 pins */ RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); GPIO_PinRemapConfig(GPIO_FullRemap_USART3, ENABLE); GPIO_InitTypeDef init; init.GPIO_Pin = GPIO_Pin_8; init.GPIO_Speed = GPIO_Speed_50MHz; init.GPIO_Mode = GPIO_Mode_AF_PP; GPIO_Init(GPIOD, &init); init.GPIO_Pin = GPIO_Pin_9; init.GPIO_Speed = GPIO_Speed_50MHz; init.GPIO_Mode = GPIO_Mode_IN_FLOATING; GPIO_Init(GPIOD, &init); debug_usart = USART3; #endif init_leds(); usart_init(debug_usart); printf("how are you gentlemen\n"); printf("devid 0x%x\n", DBGMCU_GetDEVID()); dump_clocks(); // bring up te HSE printf("enabling external crystal\n"); RCC_HSEConfig(RCC_HSE_ON); RCC_WaitForHSEStartUp(); printf("external crystal up\n"); // try to program up the pll printf("enabling pll\n"); #if STM32F10X_CL RCC_PLLConfig(RCC_PLLSource_PREDIV1, RCC_PLLMul_4); #else RCC_PLLConfig(RCC_PLLSource_HSE_Div1, RCC_PLLMul_9); #endif RCC_PLLCmd(ENABLE); while (RCC_GetFlagStatus(RCC_FLAG_PLLRDY) == RESET) ; printf("pll latched\n"); printf("setting up clocks\n"); FLASH_SetLatency(FLASH_Latency_2); RCC_HCLKConfig(RCC_SYSCLK_Div1); RCC_PCLK1Config(RCC_HCLK_Div2); RCC_PCLK2Config(RCC_HCLK_Div1); #if STM32F10X_CL RCC_SYSCLKConfig(RCC_SYSCLKSource_HSE); #else RCC_SYSCLKConfig(RCC_SYSCLKSource_PLLCLK); #endif usart_init(debug_usart); set_led(3, 0); set_led(3, 1); printf("after new sysclk\n"); dump_clocks(); printf("done!\n"); /* try to fire the systick */ // __set_BASEPRI(8 << __NVIC_PRIO_BITS); /* start the systick timer */ NVIC_SetVectorTable(0, 0); NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4); uint32_t pri = NVIC_EncodePriority(3, 0, 0); NVIC_SetPriority(SysTick_IRQn, pri); SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK); SysTick_Config(systick_counter); #if 0 uint32_t last = 0; for (;;) { uint32_t now = current_time(); if (now - last >= 1000000) { printf("time %d\n", now); last = now; } } #endif #if 0 uint32_t val; for (val = 0; ; val++) { set_led(0, val & 0x1); set_led(1, val & 0x2); set_led(2, val & 0x4); set_led(3, val & 0x8); } #endif /* write the boot sequence */ led_panel_command_write(0b100000000010, 12); // SYS_EN led_panel_command_write(0b100000000110, 12); // LED_ON led_panel_command_write(0b100000010000, 12); // BLINK_OFF led_panel_command_write(0b100000110000, 12); // INT_RC led_panel_command_write(0b100001001000, 12); // n-mos open drain, 16 com led_panel_command_write(0b100101011110, 12); // PWM_CTRL | 0xf for(uint j = 0; ; j++) { GPIO_ResetBits(GPIOF, LED_CS); led_panel_write(0b1010000000, 10); // start write at address 0 for (int i = 0; i < 96; i++) { led_panel_write(((j % 96) > i) ? 0b1111: 0, 4); } GPIO_SetBits(GPIOF, LED_CS); spin(10000); } for(;;) ; }
/*! \brief Initializes STDIO. */ static void init_stdio(void) { #if (defined __GNUC__) && (defined __AVR32__) static const gpio_map_t STDIO_USART_GPIO_MAP = { {STDIO_USART_RX_PIN, STDIO_USART_RX_FUNCTION}, {STDIO_USART_TX_PIN, STDIO_USART_TX_FUNCTION} }; // Initialize the USART used for STDIO. set_usart_base((void *)STDIO_USART); gpio_enable_module(STDIO_USART_GPIO_MAP, sizeof(STDIO_USART_GPIO_MAP) / sizeof(STDIO_USART_GPIO_MAP[0])); usart_init(STDIO_USART_BAUDRATE); #elif (defined __ICCAVR32__) static const gpio_map_t STDIO_USART_GPIO_MAP = { {STDIO_USART_RX_PIN, STDIO_USART_RX_FUNCTION}, {STDIO_USART_TX_PIN, STDIO_USART_TX_FUNCTION} }; static const usart_options_t STDIO_USART_OPTIONS = { .baudrate = STDIO_USART_BAUDRATE, .charlength = 8, .paritytype = USART_NO_PARITY, .stopbits = USART_1_STOPBIT, .channelmode = USART_NORMAL_CHMODE }; // Initialize the USART used for STDIO. extern volatile avr32_usart_t *volatile stdio_usart_base; stdio_usart_base = STDIO_USART; gpio_enable_module(STDIO_USART_GPIO_MAP, sizeof(STDIO_USART_GPIO_MAP) / sizeof(STDIO_USART_GPIO_MAP[0])); usart_init_rs232(STDIO_USART, &STDIO_USART_OPTIONS, FPBA_HZ); #endif } #if (defined __GNUC__) /*! \brief Low-level initialization routine called during startup, before the * main function. * * This version comes in replacement to the default one provided by the Newlib * add-ons library. * Newlib add-ons' _init_startup only calls init_exceptions, but Newlib add-ons' * exception and interrupt vectors are defined in the same section and Newlib * add-ons' interrupt vectors are not compatible with the interrupt management * of the INTC module. * More low-level initializations are besides added here. */ int _init_startup(void) { // Import the Exception Vector Base Address. extern void _evba; // Load the Exception Vector Base Address in the corresponding system register. Set_system_register(AVR32_EVBA, (int)&_evba); // Enable exceptions. Enable_global_exception(); // Initialize interrupt handling. irq_initialize_vectors(); cpu_irq_enable(); init_stdio(); // Don't-care value for GCC. return 1; } #elif (defined __ICCAVR32__) /*! \brief Low-level initialization routine called during startup, before the * main function. */ int __low_level_init(void) { // Enable exceptions. Enable_global_exception(); // Initialize interrupt handling. irq_initialize_vectors(); cpu_irq_enable(); init_stdio(); // Request initialization of data segments. return 1; }
int main(void) { #warning change clock hse_value to 25m SYSTIM_Init(); LEDInit(LED_ACT); LEDInit(LED_COM); LEDInit(LED_ERR); LEDOn(LED_ACT); LEDOff(LED_COM); LEDOff(LED_ERR); SYSTIM_DelayTms(1000); LEDOff(LED_ACT); // USBD_Init(&USB_OTG_dev, // USB_OTG_FS_CORE_ID, // &USR_desc, // &USBD_CDC_cb, // &USR_cb); usart_init(); UART_DMAInit(); if (!CheckXCLK()) { XCLK_ON(); SYSTIM_DelayTms(100); } #ifdef USE_MT9V034 MT9V034_Init(); #endif #ifdef USE_MT9D111 MT9D111_Init(); #endif #warning already enable i2c when init camera //mpu6050_enable(); memset(Cam_Capture,'1',FULL_IMAGE_SIZE); Cam_Capture[FULL_IMAGE_SIZE] = 's'; Cam_Capture[FULL_IMAGE_SIZE + 1] = 't'; Cam_Capture[FULL_IMAGE_SIZE + 2] = 'p'; DCMI_CaptureCmd(ENABLE); while(1) { int i=0; #ifdef TEST_MPU6050 bool res; res = I2C_ReadBytes(I2C2,data,MPU_ADDR, MPU_DATA, 14); if (!res) { LEDOn(LED_ERR); } ax = (double)(data[1] + (data[0]<<8)); ay = (double)(data[3] + (data[2]<<8)); az = (double)(data[5] + (data[4]<<8)); wx = (double)(data[9] + (data[8]<<8)); wy = (double)(data[11] + (data[10]<<8)); wz = (double)(data[13] + (data[12]<<8)); SYSTIM_DelayTms(100); #endif if (DCMI_Flag) { DCMI_Flag = 0; LEDToggle(LED_ACT); // SendImageDMA((uint32_t*)&Cam_Capture[0], FULL_IMAGE_SIZE); // for (i=0;i<FULL_IMAGE_SIZE;i++) // { // Cam_Buffer[i] = Cam_Capture[i]; // } VCP_DataTx(Cam_Capture,FULL_IMAGE_SIZE+3); SYSTIM_DelayTms(5000); DCMI_CaptureCmd(ENABLE); } } }