int main(void) { //ewb((uint8_t*)0x80, erb((uint8_t*)0x80)+1); wdt_enable(WDTO_2S); // Avoid an early reboot clock_prescale_set(clock_div_1); // Disable Clock Division:1->8MHz #ifdef HAS_XRAM init_memory_mapped(); // First initialize the RAM #endif // if we had been restarted by watchdog check the REQ BootLoader byte in the // EEPROM if(bit_is_set(MCUSR,WDRF) && erb(EE_REQBL)) { ewb( EE_REQBL, 0 ); // clear flag start_bootloader(); } while(tx_report); // reboot if the bss is not initialized // Setup the timers. Are needed for watchdog-reset OCR0A = 249; // Timer0: 0.008s = 8MHz/256/250 TCCR0B = _BV(CS02); TCCR0A = _BV(WGM01); TIMSK0 = _BV(OCIE0A); TCCR1A = 0; TCCR1B = _BV(CS11) | _BV(WGM12); // Timer1: 1us = 8MHz/8 MCUSR &= ~(1 << WDRF); // Enable the watchdog led_init(); // So we can debug spi_init(); eeprom_init(); USB_Init(); fht_init(); tx_init(); ethernet_init(); #ifdef HAS_FS df_init(&df); fs_init(&fs, df, 0); // needs df_init log_init(); // needs fs_init & rtc_init log_enabled = erb(EE_LOGENABLED); #endif input_handle_func = analyze_ttydata; display_channel = DISPLAY_USB; LED_OFF(); for(;;) { USB_USBTask(); CDC_Task(); RfAnalyze_Task(); Minute_Task(); FastRF_Task(); rf_router_task(); #ifdef HAS_ASKSIN rf_asksin_task(); #endif #ifdef HAS_ETHERNET Ethernet_Task(); #endif } }
int main(void) { watchdog_stop(); TIMER_ID_INPUT = UINT_MAX; node_id = NODE_ID_UNDEFINED; /* protothreads init */ int i; for(i = 0; i < NUM_PT; i++) { PT_INIT(&pt[i]); } /* clock init */ set_mcu_speed_dco_mclk_16MHz_smclk_8MHz(); /* LEDs init */ leds_init(); led_red_on(); led_green_flag = 0; /* timer init */ timerA_init(); timerA_register_cb(&timer_tick_cb); timerA_start_milliseconds(TIMER_PERIOD_MS); /* button init */ button_init(); button_register_cb(button_pressed_cb); antibouncing_flag = 0; button_pressed_flag = 0; /* UART init (serial link) */ uart_init(UART_9600_SMCLK_8MHZ); uart_register_cb(uart_cb); uart_flag = 0; uart_data = 0; /* ADC10 init (temperature) */ adc10_start(); /* radio init */ spi_init(); cc2500_init(); cc2500_rx_register_buffer(radio_tx_buffer, PKTLEN); cc2500_rx_register_cb(radio_cb); cc2500_rx_enter(); radio_rx_flag = 0; /* retrieve node id from flash */ node_id = *((char *) NODE_ID_LOCATION); //printf("node id retrieved from flash: %d\r\n", node_id); button_enable_interrupt(); __enable_interrupt(); /* simple cycle scheduling */ while(1) { /*thread_led_red(&pt[0]); thread_led_green(&pt[1]); thread_uart(&pt[2]); thread_antibouncing(&pt[3]);*/ thread_process_msg(&pt[4]); thread_periodic_send(&pt[5]); /*thread_button(&pt[6]);*/ } }
void update_mrc_cache(void *unused) { printk(BIOS_DEBUG, "Updating fast boot cache data.\n"); struct mrc_data_container *current = cbmem_find(CBMEM_ID_MRCDATA); struct mrc_data_container *cache, *cache_base; u32 cache_size; if (!current) { printk(BIOS_ERR, "No fast boot cache in cbmem. Can't update flash.\n"); return; } if (current->mrc_data_size == -1) { printk(BIOS_ERR, "Fast boot cache data in cbmem invalid.\n"); return; } cache_base = NULL; cache_size = get_mrc_cache_region(&cache_base); if (cache_base == NULL) { printk(BIOS_ERR, "%s: could not find fast boot cache area\n", __func__); return; } /* * we need to: * 0. compare MRC data to last mrc-cache block (exit if same) */ cache = find_current_mrc_cache_local(cache_base, cache_size); if (cache && (cache->mrc_data_size == current->mrc_data_size) && (memcmp(cache, current, cache->mrc_data_size) == 0)) { printk(BIOS_DEBUG, "MRC data in flash is up to date. No update.\n"); return; } /* 1. use spi_flash_probe() to find the flash, then... */ spi_init(); struct spi_flash *flash = spi_flash_probe(0, 0); if (!flash) { printk(BIOS_DEBUG, "Could not find SPI device\n"); return; } /* 2. look up the first unused block */ if (cache) cache = find_next_mrc_cache(cache_base, cache, cache_size); /* * 3. if no such place exists, erase entire mrc-cache range & use * block 0. First time around the erase is not needed, but this is a * small overhead for simpler code. */ if (!cache) { printk(BIOS_DEBUG, "Need to erase the MRC cache region of %d bytes at %p\n", cache_size, cache_base); flash->erase(flash, to_flash_offset(cache_base), cache_size); /* we will start at the beginning again */ cache = cache_base; } /* 4. write mrc data with flash->write() */ printk(BIOS_DEBUG, "Write MRC cache update to flash at %p\n", cache); flash->write(flash, to_flash_offset(cache), current->mrc_data_size + sizeof(*current), current); }
void board_init_f(ulong not_used) { bd_t *bd; init_fnc_t **init_fnc_ptr; gd = (gd_t *)(CONFIG_SYS_SDRAM_BASE + CONFIG_SYS_GBL_DATA_OFFSET); bd = (bd_t *)(CONFIG_SYS_SDRAM_BASE + CONFIG_SYS_GBL_DATA_OFFSET - GENERATED_BD_INFO_SIZE); #if defined(CONFIG_CMD_FLASH) && !defined(CONFIG_SPL_BUILD) ulong flash_size = 0; #endif asm ("nop"); /* FIXME gd is not initialize - wait */ memset((void *)gd, 0, GENERATED_GBL_DATA_SIZE); memset((void *)bd, 0, GENERATED_BD_INFO_SIZE); gd->bd = bd; gd->baudrate = CONFIG_BAUDRATE; bd->bi_baudrate = CONFIG_BAUDRATE; bd->bi_memstart = CONFIG_SYS_SDRAM_BASE; bd->bi_memsize = CONFIG_SYS_SDRAM_SIZE; gd->flags |= GD_FLG_RELOC; /* tell others: relocation done */ monitor_flash_len = __end - __text_start; #ifdef CONFIG_OF_EMBED /* Get a pointer to the FDT */ gd->fdt_blob = _binary_dt_dtb_start; #elif defined CONFIG_OF_SEPARATE /* FDT is at end of image */ gd->fdt_blob = (void *)__end; #endif #ifndef CONFIG_SPL_BUILD /* Allow the early environment to override the fdt address */ gd->fdt_blob = (void *)getenv_ulong("fdtcontroladdr", 16, (uintptr_t)gd->fdt_blob); #endif /* * The Malloc area is immediately below the monitor copy in DRAM * aka CONFIG_SYS_MONITOR_BASE - Note there is no need for reloc_off * as our monitory code is run from SDRAM */ mem_malloc_init(CONFIG_SYS_MALLOC_BASE, CONFIG_SYS_MALLOC_LEN); serial_initialize(); #ifdef CONFIG_XILINX_TB_WATCHDOG hw_watchdog_init(); #endif for (init_fnc_ptr = init_sequence; *init_fnc_ptr; ++init_fnc_ptr) { WATCHDOG_RESET(); if ((*init_fnc_ptr) () != 0) hang(); } #ifndef CONFIG_SPL_BUILD #ifdef CONFIG_OF_CONTROL /* For now, put this check after the console is ready */ if (fdtdec_prepare_fdt()) panic("** No FDT - please see doc/README.fdt-control"); else printf("DTB: 0x%x\n", (u32)gd->fdt_blob); #endif puts("SDRAM :\n"); printf("\t\tIcache:%s\n", icache_status() ? "ON" : "OFF"); printf("\t\tDcache:%s\n", dcache_status() ? "ON" : "OFF"); printf("\tU-Boot Start:0x%08x\n", CONFIG_SYS_TEXT_BASE); #if defined(CONFIG_CMD_FLASH) puts("Flash: "); bd->bi_flashstart = CONFIG_SYS_FLASH_BASE; flash_size = flash_init(); if (bd->bi_flashstart && flash_size > 0) { # ifdef CONFIG_SYS_FLASH_CHECKSUM print_size(flash_size, ""); /* * Compute and print flash CRC if flashchecksum is set to 'y' * * NOTE: Maybe we should add some WATCHDOG_RESET()? XXX */ if (getenv_yesno("flashchecksum") == 1) { printf(" CRC: %08X", crc32(0, (const u8 *)bd->bi_flashstart, flash_size) ); } putc('\n'); # else /* !CONFIG_SYS_FLASH_CHECKSUM */ print_size(flash_size, "\n"); # endif /* CONFIG_SYS_FLASH_CHECKSUM */ bd->bi_flashsize = flash_size; bd->bi_flashoffset = bd->bi_flashstart + flash_size; } else { puts("Flash init FAILED"); bd->bi_flashstart = 0; bd->bi_flashsize = 0; bd->bi_flashoffset = 0; } #endif #ifdef CONFIG_SPI spi_init(); #endif /* relocate environment function pointers etc. */ env_relocate(); /* Initialize stdio devices */ stdio_init(); /* Initialize the jump table for applications */ jumptable_init(); /* Initialize the console (after the relocation and devices init) */ console_init_r(); board_init(); /* Initialize from environment */ load_addr = getenv_ulong("loadaddr", 16, load_addr); #if defined(CONFIG_CMD_NET) printf("Net: "); eth_initialize(gd->bd); uchar enetaddr[6]; eth_getenv_enetaddr("ethaddr", enetaddr); printf("MAC: %pM\n", enetaddr); #endif /* main_loop */ for (;;) { WATCHDOG_RESET(); main_loop(); } #endif /* CONFIG_SPL_BUILD */ }
/* FIXME/Note: * This function assumes nothing else than the ADS is on the spi when the !CS pin of the ADS is * pulled low. If you want to change this, you will have to pull it low each time a command or * data is sent/to be received to/from the ADS. * * This method is run right at the startup of the avr. */ void ads_init_pass1(){ spi_init(); ADS_CS_DDR |= ADS_CS_MASK; }
/** **************************************************************************************** * @brief SPI_439 initialization * * Should only be called once after power reset of 439, do not call this twice. * * @return void **************************************************************************************** */ void spi_439_init() { #if ( DESIGN_0 || DESIGN_1 ) GPIO_SetInactive( GPIO_PORT_2, GPIO_PIN_2 ); // Power on the 439, by setting MUTE_LDO = 0 #elif ( DESIGN_2 || DESIGN_3 ) GPIO_SetInactive( GPIO_PORT_1, GPIO_PIN_3 ); // Power on the 439, by setting MUTE_LDO = 0 #endif SetBits16(SPI_CTRL_REG, SPI_ON, 0); // switch off SPI block SPI_Pad_t spi_cs_pad; #if ( DESIGN_0 || DESIGN_1 ) spi_cs_pad.port = GPIO_PORT_0; spi_cs_pad.pin = GPIO_PIN_3; #elif ( DESIGN_2 || DESIGN_3 ) spi_cs_pad.port = GPIO_PORT_0; spi_cs_pad.pin = GPIO_PIN_2; #endif spi_init(&spi_cs_pad, SPI_MODE_16BIT, SPI_ROLE_MASTER, SPI_CLK_IDLE_POL_LOW, SPI_PHA_MODE_0, SPI_MINT_DISABLE, SPI_XTAL_DIV_14); // SPI_XTAL_DIV_2=8MHZ, SPI_XTAL_DIV_8=2MHZ /* ** First try to read our magic word. It should be 1A30. If so, skip the clock initializations. ** Otherwise, we are coming from cold boot. */ { #ifdef JOH_CLK_SETTINGS /* ** clk=16 Mhz from the 580 => set 439 PLL for Fsys = 46.08 MHz ** This means: ** - SC14439_CLK_CTRL_REG=0,0x12, 0x1A ** - SC14439_PLL_DIV_REG = 0x2A19, so VD/VX=(72/25)*16Mhz = 46.08 Mhz Fsys clock ** - SC14439_CLK_CTRL_REG , turn on PLL ** - SC14439_PER_DIV_REG = 4 ** - SC14439_CODEC_DIV_REG = 20, so ClodecClk=46.08/20=2.304 Mhz */ SetWord439(SC14439_CLK_CTRL_REG, 0); SetWord439(SC14439_PLL_DIV_REG, 0x2A19); /* VD/XD=(72/25)*16MHz = 46.08 Mhz Fsys. VD=72=6x12=01.0101; XD=25=00.11001, total = 0010.1010.0001.1001 */ SetWord439(SC14439_CLK_CTRL_REG, 0x12); SetWord439(SC14439_PER_DIV_REG, 4); /* see calculation in DS SC14439, per_div<4 */ #else /* ** clk=16 Mhz from the 580 => set 439 PLL for Fsys = 39.183 MHz ** This means: ** - SC14439_CLK_CTRL_REG=0,0x12, 0x1A ** - SC14439_PLL_DIV_REG = 0x2A19, so VD/VX=(120/49)*16Mhz = 39.183 Mhz Fsys clock ** - SC14439_CLK_CTRL_REG , turn on PLL ** - SC14439_PER_DIV_REG = 4 ** - SC14439_CODEC_DIV_REG = 20, so ClodecClk=46.08/20=2.304 Mhz */ SetWord439(SC14439_CLK_CTRL_REG, 0); SetWord439(SC14439_PLL_DIV_REG, 0x3631); /* VD/XD=(120/49)*16MHz = 39.183 Mhz Fsys. VD=120=10x12=01.1011; XD=49=01.10001 */ SetWord439(SC14439_CLK_CTRL_REG, 0x12); SetWord439(SC14439_PER_DIV_REG, 4); /* see calculation in DS SC14439, per_div<4 */ #endif SetWord439(SC14439_BAT_CTRL_REG, 2); /* VDDIO 2.25..2.75V gr: ok up to 3.45 V Not required - default value is valid */ SetWord439(SC14439_CODEC_VREF_REG, 0x0000); //make VREF settle faster TODO CHECK SetWord439(SC14439_CODEC_ADDA_REG, 0x040e); #if ( DESIGN_0 || DESIGN_1 ) SetWord439(SC14439_CODEC_MIC_REG, 0x1081); /* Amplifier Active*/ #elif ( DESIGN_2 || DESIGN_3 ) SetWord439(SC14439_CODEC_MIC_REG, 0x1041); /* Amplifier Active - Less Gain */ #endif #if ( DESIGN_0 || DESIGN_1 ) spi439_delay(1500); //wait for PLL to settle SetWord439(SC14439_CLK_CTRL_REG, 0x1A); spi439_delay(100); //wait 16 spi cycles #elif ( DESIGN_2 || DESIGN_3 ) spi439_delay(2000); //wait for PLL to settle SetWord439(SC14439_CLK_CTRL_REG, 0x1A); spi439_delay(100); //wait 16 spi cycles #endif } /* ** 439 Codec initialization ** */ #ifdef JOH_CLK_SETTINGS SetWord439(SC14439_CODEC_DIV_REG, 0x14); /* codec clk divider 46.08/20 = 2.304 MHz */ #else SetWord439(SC14439_CODEC_DIV_REG, 0x11); /* codec clk divider Fsys/17 = 2.304 MHz */ #endif spi439_delay(100); //wait a while SetWord439(SC14439_CODEC_ADDA_REG, 0x0006); SetWord439(SC14439_CODEC_VREF_REG, 0x0000); /* ** Setup DMA on 439 ** DMA will collect 80 samples from CODEC and put them in Shared RAM at address 0x0CD8, in circular buffer ** and continue indefenitely. ** ** The DMA buffer on the 439 is set to 80 samples = 160 bytes (Note hat DMA0_LEN is in bytes) ** Start address is 0xCD8. Second part of buffer starts at 0xD28 ** */ SetWord439(SC14439_DMA0_LEN_REG,SC14439_DMA_LEN); SetWord439(SC14439_DMA0_A_STARTL_REG,SC14439_DMA_DST_ADDR); SetWord439(SC14439_DMA0_A_IDX_REG,0); SetWord439(SC14439_DMA0_B_STARTL_REG,SC14439_CODEC_IN_OUT_REG); SetWord439(SC14439_DMA0_B_IDX_REG,0); SetWord439(SC14439_DMA0_CTRL_REG,0x062D); // SYNC_SEL=0, DREQ_LEVEL=0,CIRUCLAR=1., AINC=10,BINC=00 DREQ_MODE=1, RSRV, IND=1, DIR=1, RSRVD, DMA_ON=1 = 0000.0110.0010.1101 NVIC_SetPriority(SPI_IRQn,1); NVIC_EnableIRQ(SPI_IRQn); }
int main(void) { clk_init(); gpio_init(); #ifdef SERIAL serial_init(); #endif i2c_init(); spi_init(); pwm_init(); pwm_set(MOTOR_FL, 0); // FL pwm_set(MOTOR_FR, 0); pwm_set(MOTOR_BL, 0); // BL pwm_set(MOTOR_BR, 0); // FR time_init(); if (RCC_GetCK_SYSSource() == 8) { } else { failloop(5); } sixaxis_init(); if (sixaxis_check()) { #ifdef SERIAL printf(" MPU found \n"); #endif } else { #ifdef SERIAL printf("ERROR: MPU NOT FOUND \n"); #endif failloop(4); } adc_init(); rx_init(); int count = 0; vbattfilt = 0.0; while (count < 64) { vbattfilt += adc_read(1); count++; } // for randomising MAC adddress of ble app - this will make the int = raw float value random_seed = *(int *)&vbattfilt ; random_seed = random_seed&0xff; vbattfilt = vbattfilt / 64; #ifdef SERIAL printf("Vbatt %2.2f \n", vbattfilt); #ifdef NOMOTORS printf("NO MOTORS\n"); #warning "NO MOTORS" #endif #endif #ifdef STOP_LOWBATTERY // infinite loop if (vbattfilt < STOP_LOWBATTERY_TRESH) failloop(2); #endif // loads acc calibration and gyro dafaults loadcal(); gyro_cal(); rgb_init(); imu_init(); extern unsigned int liberror; if (liberror) { #ifdef SERIAL printf("ERROR: I2C \n"); #endif failloop(7); } lastlooptime = gettime(); extern int rxmode; extern int failsafe; float thrfilt; // // // MAIN LOOP // // checkrx(); while (1) { // gettime() needs to be called at least once per second maintime = gettime(); looptime = ((uint32_t) (maintime - lastlooptime)); if (looptime <= 0) looptime = 1; looptime = looptime * 1e-6f; if (looptime > 0.02f) // max loop 20ms { failloop(3); //endless loop } lastlooptime = maintime; if (liberror > 20) { failloop(8); // endless loop } sixaxis_read(); control(); // battery low logic float hyst; float battadc = adc_read(1); vbatt = battadc; // average of all 4 motor thrusts // should be proportional with battery current extern float thrsum; // from control.c // filter motorpwm so it has the same delay as the filtered voltage // ( or they can use a single filter) lpf ( &thrfilt , thrsum , 0.9968f); // 0.5 sec at 1.6ms loop time lpf ( &vbattfilt , battadc , 0.9968f); #ifdef AUTO_VDROP_FACTOR static float lastout[12]; static float lastin[12]; static float vcomp[12]; static float score[12]; static int current_index = 0; int minindex = 0; float min = score[0]; { int i = current_index; vcomp[i] = vbattfilt + (float) i *0.1f * thrfilt; if ( lastin[i] < 0.1f ) lastin[i] = vcomp[i]; float temp; // y(n) = x(n) - x(n-1) + R * y(n-1) // out = in - lastin + coeff*lastout // hpf temp = vcomp[i] - lastin[i] + FILTERCALC( 1000*12 , 1000e3) *lastout[i]; lastin[i] = vcomp[i]; lastout[i] = temp; lpf ( &score[i] , fabsf(temp) , FILTERCALC( 1000*12 , 10e6 ) ); } current_index++; if ( current_index >= 12 ) current_index = 0; for ( int i = 0 ; i < 12; i++ ) { if ( score[i] < min ) { min = score[i]; minindex = i; } } #undef VDROP_FACTOR #define VDROP_FACTOR minindex * 0.1f #endif if ( lowbatt ) hyst = HYST; else hyst = 0.0f; vbatt_comp = vbattfilt + (float) VDROP_FACTOR * thrfilt; if ( vbatt_comp <(float) VBATTLOW + hyst ) lowbatt = 1; else lowbatt = 0; // led flash logic if (rxmode != RX_MODE_BIND) { // non bind if (failsafe) { if (lowbatt) ledflash(500000, 8); else ledflash(500000, 15); } else { if (lowbatt) ledflash(500000, 8); else { if (ledcommand) { if (!ledcommandtime) ledcommandtime = gettime(); if (gettime() - ledcommandtime > 500000) { ledcommand = 0; ledcommandtime = 0; } ledflash(100000, 8); } else { if ( aux[LEDS_ON] ) ledon( 255); else ledoff( 255); } } } } else { // bind mode ledflash(100000 + 500000 * (lowbatt), 12); } // rgb strip logic #if (RGB_LED_NUMBER > 0) extern void rgb_led_lvc( void); rgb_led_lvc( ); #endif #ifdef BUZZER_ENABLE buzzer(); #endif #ifdef FPV_ON static int fpv_init = 0; if ( rxmode == RX_MODE_NORMAL && ! fpv_init ) { fpv_init = gpio_init_fpv(); } if ( fpv_init ) { if ( failsafe ) { GPIO_WriteBit( FPV_PIN_PORT, FPV_PIN, Bit_RESET ); } else { GPIO_WriteBit( FPV_PIN_PORT, FPV_PIN, aux[ FPV_ON ] ? Bit_SET : Bit_RESET ); } } #endif checkrx(); // loop time 1ms while ((gettime() - maintime) < (1000 - 22) ) delay(10); } // end loop }
int main( void ) { wdt_disable(); jtag_disable(); rs232_init( 9600, 0 ); spi_init( SPI_HALFSPEED | SPI_EIGHTHSPEED ); spi_idetrol_slave_init( &player ); irmp_init(); timer1_init(); timer2_init(); stdin = stdout = &rs232inout; sei(); printf_P( PSTR("\nCDTrol "__DATE__"\n") ); if( !ata_init() ) { printf_P( PSTR("ATA Initialization failed\n") ); _delay_ms(1000); return 1; } if( !atapi_init() ) { printf_P( PSTR("ATAPI Initialization failed\n") ); _delay_ms(1000); return 1; } if( !atapiplayer_init( &player ) ) { printf_P( PSTR("ATAPIPlayer Initialization failed\n") ); _delay_ms(1000); return 1; } while( true ) { spi_idetrol_slave_update(); if( updateFlag ) { atapiplayer_update( &player ); updateFlag = 0; } if( irmp_get_data( &irmp_data ) ) { if( ! (irmp_data.flags & IRMP_FLAG_REPETITION) ) { printf_P( PSTR("\nIRMP: protocol \"%S\", address %d, command %d\n"), (PGM_P)pgm_read_word(&(irmp_protocol_strings[irmp_data.protocol])), irmp_data.address, irmp_data.command ); switch( irmp_data.command ) { case 53: printf_P( PSTR("\nPlay\n") ); atapiplayer_play( &player ); break; case 48: printf_P( PSTR("\nPause\n") ); atapiplayer_pause( &player ); break; case 54: printf_P( PSTR("\nStop\n") ); atapiplayer_stop( &player ); break; case 36: printf_P( PSTR("\nPrevious\n") ); atapiplayer_previous( &player ); break; case 30: printf_P( PSTR("\nNext\n") ); atapiplayer_next( &player ); break; case 55: printf_P( PSTR("\nLoad/Eject\n") ); atapiplayer_loadEject( &player ); break; } } switch( irmp_data.command ) { case 52: printf_P( PSTR("\nFastForward\n") ); atapiplayer_forward( &player ); break; case 50: printf_P( PSTR("\nFastRewind\n") ); atapiplayer_rewind( &player ); break; case 59: atapi_printError(); break; } } } return 0; }
/** * @brief Initialize the whole system * * All functions that need to be called before the first mainloop iteration * should be placed here. */ void main_init_generic(void) { // Reset to safe values global_data_reset(); // Load default eeprom parameters as fallback global_data_reset_param_defaults(); // LOWLEVEL INIT, ONLY VERY BASIC SYSTEM FUNCTIONS hw_init(); enableIRQ(); led_init(); led_on(LED_GREEN); buzzer_init(); sys_time_init(); sys_time_periodic_init(); sys_time_clock_init(); ppm_init(); pwm_init(); // Lowlevel periphel support init adc_init(); // FIXME SDCARD // MMC_IO_Init(); spi_init(); i2c_init(); // Sensor init sensors_init(); debug_message_buffer("Sensor initialized"); // Shutter init shutter_init(); shutter_control(0); // Debug output init debug_message_init(); debug_message_buffer("Text message buffer initialized"); // MEDIUM LEVEL INIT, INITIALIZE I2C, EEPROM, WAIT FOR MOTOR CONTROLLERS // Try to reach the EEPROM eeprom_check_start(); // WAIT FOR 2 SECONDS FOR THE USER TO NOT TOUCH THE UNIT while (sys_time_clock_get_time_usec() < 2000000) { } // Do the auto-gyro calibration for 1 second // Get current temperature led_on(LED_RED); gyro_init(); // uint8_t timeout = 3; // // Check for SD card // while (sys_time_clock_get_time_usec() < 2000000) // { // while (GetDriveInformation() != F_OK && timeout--) // { // debug_message_buffer("MMC/SD-Card not found ! retrying.."); // } // } // // if (GetDriveInformation() == F_OK) // { // debug_message_buffer("MMC/SD-Card SUCCESS: FOUND"); // } // else // { // debug_message_buffer("MMC/SD-Card FAILURE: NOT FOUND"); // } //FIXME redo init because of SD driver decreasing speed //spi_init(); led_off(LED_RED); // Stop trying to reach the EEPROM - if it has not been found by now, assume // there is no EEPROM mounted if (eeprom_check_ok()) { param_read_all(); debug_message_buffer("EEPROM detected - reading parameters from EEPROM"); for (int i = 0; i < ONBOARD_PARAM_COUNT * 2 + 20; i++) { param_handler(); //sleep 1 ms sys_time_wait(1000); } } else { debug_message_buffer("NO EEPROM - reading onboard parameters from FLASH"); } // Set mavlink system mavlink_system.compid = MAV_COMP_ID_IMU; mavlink_system.sysid = global_data.param[PARAM_SYSTEM_ID]; //Magnet sensor hmc5843_init(); acc_init(); // Comm parameter init mavlink_system.sysid = global_data.param[PARAM_SYSTEM_ID]; // System ID, 1-255 mavlink_system.compid = global_data.param[PARAM_COMPONENT_ID]; // Component/Subsystem ID, 1-255 // Comm init has to be // AFTER PARAM INIT comm_init(MAVLINK_COMM_0); comm_init(MAVLINK_COMM_1); // UART initialized, now initialize COMM peripherals communication_init(); gps_init(); us_run_init(); servos_init(); //position_kalman3_init(); // Calibration starts (this can take a few seconds) // led_on(LED_GREEN); // led_on(LED_RED); // Read out first time battery global_data.battery_voltage = battery_get_value(); global_data.state.mav_mode = MAV_MODE_PREFLIGHT; global_data.state.status = MAV_STATE_CALIBRATING; send_system_state(); float_vect3 init_state_accel; init_state_accel.x = 0.0f; init_state_accel.y = 0.0f; init_state_accel.z = -1000.0f; float_vect3 init_state_magnet; init_state_magnet.x = 1.0f; init_state_magnet.y = 0.0f; init_state_magnet.z = 0.0f; //auto_calibration(); attitude_observer_init(init_state_accel, init_state_magnet); debug_message_buffer("Attitude Filter initialized"); led_on(LED_RED); send_system_state(); debug_message_buffer("System is initialized"); // Calibration stopped led_off(LED_RED); global_data.state.mav_mode = MAV_MODE_FLAG_MANUAL_INPUT_ENABLED; global_data.state.status = MAV_STATE_STANDBY; send_system_state(); debug_message_buffer("Checking if remote control is switched on:"); // Initialize remote control status remote_control(); remote_control(); if (radio_control_status() == RADIO_CONTROL_ON && global_data.state.remote_ok) { global_data.state.mav_mode = MAV_MODE_FLAG_MANUAL_INPUT_ENABLED | MAV_MODE_FLAG_TEST_ENABLED; debug_message_buffer("RESULT: remote control switched ON"); debug_message_buffer("Now in MAV_MODE_TEST2 position hold tobi_laurens"); led_on(LED_GREEN); } else { global_data.state.mav_mode = MAV_MODE_FLAG_MANUAL_INPUT_ENABLED; debug_message_buffer("RESULT: remote control switched OFF"); led_off(LED_GREEN); } }
void read_config (void) { char line[80]; char *pToken; char *pLine; unsigned j; // first set defaults for (j=0; j < NUM_TOKENS; j++) { switch (config_lookup[j].type) { case TYPE_INT: { int32_t *pVal = config_lookup[j].pValue; *pVal = config_lookup[j].val_i; break; } case TYPE_DOUBLE: { double *pVal = config_lookup[j].pValue; *pVal = config_lookup[j].val_d; break; } } } /* initialize SPI for SDCard */ spi_init(); /* access to "config.txt" file on SDCard */ FATFS fs; /* Work area (file system object) for logical drive */ FIL file; /* file object */ FRESULT res; /* FatFs function common result code */ /* Register a work area for logical drive 0 */ res = f_mount(0, &fs); if(res) debug("Err mount fs\n"); /* Open config.txt file */ res = f_open(&file, "config.txt", FA_OPEN_EXISTING | FA_READ); if (res) debug("File config.txt not found\n"); else { bool found; pLine = f_gets(line, sizeof(line), &file); /* read one line */ while (pLine) { pToken = get_token (pLine); if (pToken && *pToken != '#') { found = false; for (j=0; (j < NUM_TOKENS) && !found; j++) { if (stricmp (pToken, config_lookup[j].name) == 0) { found = true; pToken = get_token (NULL); if (pToken && (*pToken == '=')) { // get value pToken = get_token (NULL); if (pToken) { switch (config_lookup[j].type) { case TYPE_INT: { int32_t *pVal = config_lookup[j].pValue; *pVal = atoi (pToken); break; } case TYPE_DOUBLE: { double *pVal = config_lookup[j].pValue; *pVal = atod(pToken); break; } } // debug //sersendf ("Found: %s = %d\r\n", config_lookup[j].name, *config_lookup[j].pValue); } else sersendf ("Missing value for %s\r\n", config_lookup[j].name); } else sersendf ("Expected '='%s\r\n", line); } } if (!found) sersendf ("Unknown config: %s\r\n", pToken); } pLine = f_gets(line, sizeof(line), &file); /* read next line */ } /* Close config.txt file */ res = f_close(&file); if (res) debug("Error closing config.txt\n"); } // //read_gcode_file ("autoexec.g"); res = f_open(&file, "autoexec.g", FA_OPEN_EXISTING | FA_READ); if (res == FR_OK) { tLineBuffer line_buf; pLine = f_gets(line_buf.data, sizeof(line_buf.data), &file); /* read one line */ while (pLine) { line_buf.len = strlen(pLine); gcode_parse_line (&line_buf); pLine = f_gets(line_buf.data, sizeof(line_buf.data), &file); /* read next line */ } /* Close file */ res = f_close(&file); if (res) debug("Error closing autoexec.g\n"); } // /* Initialize using values read from "config.txt" file */ gcode_parse_init(); }
void spi1_dma_master_spi0_slave(void) { SIM_SCGC6 |= SIM_SCGC6_DMAMUX_MASK; //DMAMUX Clock Gate Control: 1, clock enable--- SIM_SCGC7 |= SIM_SCGC7_DMA_MASK; //DMA Clock Gate control: 1, clock enable---- m_tdata8[0] = 0xF0; m_tdata8[1] = 0x11; m_tdata8[2] = 0x22; m_tdata8[3] = 0x33; m_tdata8[4] = 0x44; m_tdata8[5] = 0x66; m_tdata8[6] = 0x77; m_tdata8[7] = 0x88; for (k=0; k<8; k++) m_rdata8[k] = 0; s_tdata8[0] = 0x01; s_tdata8[1] = 0x23; s_tdata8[2] = 0x45; s_tdata8[3] = 0x67; s_tdata8[4] = 0x89; s_tdata8[5] = 0xAB; s_tdata8[6] = 0xCD; s_tdata8[7] = 0xEF; for (k=0; k<8; k++) s_rdata8[k] = 0; #ifdef CMSIS disable_irq(DMA0_IRQn); //DMA channel 0 transfer complete and error interrupt disable_irq(DMA1_IRQn); //DMA channel 1 transfer complete and error interrupt disable_irq(DMA2_IRQn); //DMA channel 2 transfer complete and error interrupt disable_irq(DMA3_IRQn); //DMA channel 3 transfer complete and error interrupt #else disable_irq(0); //DMA channel 0 transfer complete and error interrupt disable_irq(1); //DMA channel 1 transfer complete and error interrupt disable_irq(2); //DMA channel 2 transfer complete and error interrupt disable_irq(3); //DMA channel 3 transfer complete and error interrupt #endif SIM_CLKDIV1 = ( 0 | SIM_CLKDIV1_OUTDIV1(0x1) | SIM_CLKDIV1_OUTDIV4(0) ); // disable DMA channel DMAMUX0_CHCFG0 = 0; DMAMUX0_CHCFG1 = 0; DMAMUX0_CHCFG2 = 0; DMAMUX0_CHCFG3 = 0; // //SPI0 receive dma source number is 16; SPI0 transmint dma source number is 17 //*****channel 0--->TX, channel 1----->RX************ DMAMUX0_CHCFG0 |= DMAMUX_CHCFG_ENBL_MASK & (~DMAMUX_CHCFG_TRIG_MASK); DMAMUX0_CHCFG0 |= DMAMUX_CHCFG_SOURCE(17); //TX---DMA channel 0-SPI0 source number--ENBL=1--TRIG=0--- DMAMUX0_CHCFG1 |= DMAMUX_CHCFG_ENBL_MASK & (~DMAMUX_CHCFG_TRIG_MASK); DMAMUX0_CHCFG1 |= DMAMUX_CHCFG_SOURCE(16); //RX---DMA channel 1-SPI0 source number--ENBL=1--TRIG=0--- //*****channel 2--->TX, channel 3----->RX************ DMAMUX0_CHCFG2 |= DMAMUX_CHCFG_ENBL_MASK & (~DMAMUX_CHCFG_TRIG_MASK); DMAMUX0_CHCFG2 |= DMAMUX_CHCFG_SOURCE(19); //TX---DMA channel 2-SPI1 source number--ENBL=1--TRIG=0--- DMAMUX0_CHCFG3 |= DMAMUX_CHCFG_ENBL_MASK & (~DMAMUX_CHCFG_TRIG_MASK); DMAMUX0_CHCFG3 |= DMAMUX_CHCFG_SOURCE(18); //RX---DMA channel 3-SPI1 source number--ENBL=1--TRIG=0--- //************channel request number ???????***************** DMA_SAR0 = (uint32_t)(&(s_tdata8)); DMA_DAR0 = (uint32_t)(&(SPI0_D)); DMA_DSR_BCR0 |= DMA_DSR_BCR_BCR(8); //BCR contains the number of bytes yet to be transferred for a given block DMA_DCR0 = DMA_DCR_ERQ_MASK|DMA_DCR_EINT_MASK|DMA_DCR_D_REQ_MASK|DMA_DCR_CS_MASK |DMA_DCR_DSIZE(1)|DMA_DCR_SSIZE(1)|DMA_DCR_SINC_MASK; //|DMA_DCR_CS_MASK DMA_SAR1 = (uint32_t)(&(SPI0_D)); DMA_DAR1 = (uint32_t)(&(s_rdata8)); DMA_DSR_BCR1 |= DMA_DSR_BCR_BCR(8); //BCR contains the number of bytes yet to be transferred for a given block DMA_DCR1 = DMA_DCR_ERQ_MASK|DMA_DCR_EINT_MASK|DMA_DCR_D_REQ_MASK|DMA_DCR_CS_MASK |DMA_DCR_DSIZE(1)|DMA_DCR_SSIZE(1)|DMA_DCR_DINC_MASK; //|DMA_DCR_CS_MASK DMA_SAR2 = (uint32_t)(&(m_tdata8)); //----tx----- DMA_DAR2 = (uint32_t)(&(SPI1_D)); DMA_DSR_BCR2 |= DMA_DSR_BCR_BCR(8); //BCR contains the number of bytes yet to be transferred for a given block DMA_DCR2 = DMA_DCR_ERQ_MASK|DMA_DCR_EINT_MASK|DMA_DCR_D_REQ_MASK|DMA_DCR_CS_MASK |DMA_DCR_DSIZE(1)|DMA_DCR_SSIZE(1)|DMA_DCR_SINC_MASK; //|DMA_DCR_CS_MASK DMA_SAR3 = (uint32_t)(&(SPI1_D)); //----rx----- DMA_DAR3 = (uint32_t)(&(m_rdata8)); DMA_DSR_BCR3 |= DMA_DSR_BCR_BCR(8); //BCR contains the number of bytes yet to be transferred for a given block DMA_DCR3 = DMA_DCR_ERQ_MASK|DMA_DCR_EINT_MASK|DMA_DCR_D_REQ_MASK|DMA_DCR_CS_MASK |DMA_DCR_DSIZE(1)|DMA_DCR_SSIZE(1)|DMA_DCR_DINC_MASK; //|DMA_DCR_CS_MASK #ifdef CMSIS enable_irq(DMA0_IRQn); enable_irq(DMA1_IRQn); enable_irq(DMA2_IRQn); enable_irq(DMA3_IRQn); #else enable_irq(0); enable_irq(1); enable_irq(2); enable_irq(3); #endif dma_int_cnt = 0; //this variable is used to indicates the count of transmission interrupt extend_cnt = 0; m_DMA0_IntFlag = 0; m_DMA1_IntFlag = 0; m_DMA2_IntFlag = 0; m_DMA3_IntFlag = 0; printf("Initializing SPI module!\n\r"); spi_init(); while(!m_DMA0_IntFlag); while(!m_DMA3_IntFlag); for(k=0; k<8 ; k++) { if(s_tdata8[k] != m_rdata8[k]) { printf("k = 0x%01x\n\r",k); printf("m_tdata8 = 0x%02x\n\r",m_rdata8[k]); printf("s_rdata8 = 0x%02x\n\r",s_tdata8[k]); // error_count++; printf("Transmit failure!\n\r"); } else { printf("m_tdata8 = 0x%02x\n\r",m_rdata8[k]); printf("s_rdata8 = 0x%02x\n\r",s_tdata8[k]); printf("Transmit successful!\n\r"); } } }
int main(void) { led_init(); #ifdef LED_RGB led_off(LED_CHANNEL_GREEN); led_off(LED_CHANNEL_RED); led_off(LED_CHANNEL_BLUE); #else LED_ON(); #endif spi_init(); OCR0A = 249; // Timer0: 0.008s = 8MHz/256/250 == 125Hz TCCR0B = _BV(CS02); TCCR0A = _BV(WGM01); TIMSK0 = _BV(OCIE0A); TCCR1A = 0; TCCR1B = _BV(CS11) | _BV(WGM12); // Timer1: 1us = 8MHz/8 clock_prescale_set(clock_div_1); MCUSR &= ~(1 << WDRF); // Enable the watchdog uart_init( UART_BAUD_SELECT_DOUBLE_SPEED(UART_BAUD_RATE,F_CPU) ); input_handle_func = analyze_ttydata; display_channel = DISPLAY_USB; #ifdef LED_RGB my_delay_ms(200); led_on(LED_CHANNEL_RED); my_delay_ms(200); led_off(LED_CHANNEL_RED); led_on(LED_CHANNEL_GREEN); my_delay_ms(200); led_off(LED_CHANNEL_GREEN); led_on(LED_CHANNEL_BLUE); my_delay_ms(200); led_off(LED_CHANNEL_BLUE); #else LED_OFF(); #endif sei(); /* start moritz function */ moritz_func("Zr\n"); for(;;) { led_process(ticks); uart_task(); Minute_Task(); rf_asksin_task(); rf_moritz_task(); if (rf_moritz_data_available()) { DC('Z'); uint8_t *rf_data = (uint8_t*) &max_data; for (uint8_t i=0; i<=*rf_data; i++) { DH2( *rf_data++ ); } DNL(); DS("length: "); DU(max_data.length, 2); DNL(); DS("msg count: "); DU(max_data.message_count, 2); DNL(); DS("msg type: "); DU(max_data.message_type, 2); DNL(); } } }
int main(void) { wdt_disable(); #ifdef CSMV4 LED_ON_DDR |= _BV( LED_ON_PIN ); LED_ON_PORT |= _BV( LED_ON_PIN ); #endif led_init(); LED_ON(); spi_init(); // eeprom_factory_reset("xx"); eeprom_init(); // led_mode = 2; // if we had been restarted by watchdog check the REQ BootLoader byte in the // EEPROM ... // if(bit_is_set(MCUSR,WDRF) && eeprom_read_byte(EE_REQBL)) { // eeprom_write_byte( EE_REQBL, 0 ); // clear flag // start_bootloader(); // } // Setup the timers. Are needed for watchdog-reset #ifdef HAS_IRRX ir_init(); // IR uses highspeed TIMER0 for sampling OCR0A = 1; // Timer0: 0.008s = 8MHz/256/2 == 15625Hz #else OCR0A = 249; // Timer0: 0.008s = 8MHz/256/250 == 125Hz #endif TCCR0B = _BV(CS02); TCCR0A = _BV(WGM01); TIMSK0 = _BV(OCIE0A); TCCR1A = 0; TCCR1B = _BV(CS11) | _BV(WGM12); // Timer1: 1us = 8MHz/8 clock_prescale_set(clock_div_1); MCUSR &= ~(1 << WDRF); // Enable the watchdog wdt_enable(WDTO_2S); uart_init( UART_BAUD_SELECT_DOUBLE_SPEED(UART_BAUD_RATE,F_CPU) ); #ifdef HAS_DOGM dogm_init(); #endif fht_init(); tx_init(); input_handle_func = analyze_ttydata; display_channel = DISPLAY_USB; #ifdef HAS_RF_ROUTER rf_router_init(); display_channel |= DISPLAY_RFROUTER; #endif #ifdef HAS_DOGM display_channel |= DISPLAY_DOGM; #endif LED_OFF(); sei(); for(;;) { uart_task(); RfAnalyze_Task(); Minute_Task(); #ifdef HAS_FASTRF FastRF_Task(); #endif #ifdef HAS_RF_ROUTER rf_router_task(); #endif #ifdef HAS_ASKSIN rf_asksin_task(); #endif #ifdef HAS_MORITZ rf_moritz_task(); #endif #ifdef HAS_IRRX ir_task(); #endif #ifdef HAS_MBUS rf_mbus_task(); #endif } }
void nRF905_init() { #ifdef ARDUINO pinMode(TRX_EN, OUTPUT); pinMode(PWR_MODE, OUTPUT); pinMode(TX_EN, OUTPUT); #if NRF905_COLLISION_AVOID pinMode(CD, INPUT); #endif #if AM_IS_USED_HW pinMode(AM, INPUT); #endif #if !NRF905_DR_SW pinMode(DR, INPUT); #endif digitalWrite(CSN, HIGH); pinMode(CSN, OUTPUT); SPI.begin(); SPI.setClockDivider(SPI_CLOCK_DIV2); #else TRX_EN_DDR |= _BV(TRX_EN_BIT); PWR_MODE_DDR |= _BV(PWR_MODE_BIT); TX_EN_DDR |= _BV(TX_EN_BIT); #if NRF905_COLLISION_AVOID CD_DDR &= ~_BV(CD_BIT); #endif #if AM_IS_USED_HW AM_DDR &= ~_BV(AM_BIT); #endif #if !NRF905_DR_SW DR_DDR &= ~_BV(DR_BIT); #endif spiDeselect(); CSN_DDR |= _BV(CSN_BIT); spi_init(); #endif radio.state = NRF905_RADIO_STATE_IDLE; // Startup enableStandbyMode(); receiveMode(); nRF905_powerDown(); _delay_ms(3); defaultConfig(); #if NRF905_INTERRUPTS // Set interrupts REG_EXTERNAL_INT_CTL |= BIT_EXTERNAL_INT_CTL; nRF905_interrupt_on(); #endif nRF905_powerUp(); }
int main(void) { clk_init(); gpio_init(); #ifdef SERIAL serial_init(); #endif i2c_init(); spi_init(); pwm_init(); pwm_set(MOTOR_FL, 0); // FL pwm_set(MOTOR_FR, 0); pwm_set(MOTOR_BL, 0); // BL pwm_set(MOTOR_BR, 0); // FR time_init(); #ifdef SERIAL printf("\n clock source:"); #endif if (RCC_GetCK_SYSSource() == 8) { #ifdef SERIAL printf(" PLL \n"); #endif } else { #ifdef SERIAL if (RCC_GetCK_SYSSource() == 0) printf(" HSI \n"); else printf(" OTHER \n"); #endif failloop(5); } sixaxis_init(); if (sixaxis_check()) { #ifdef SERIAL printf(" MPU found \n"); #endif } else { #ifdef SERIAL printf("ERROR: MPU NOT FOUND \n"); #endif failloop(4); } adc_init(); rx_init(); int count = 0; float vbattfilt = 0.0; while (count < 64) { vbattfilt += adc_read(1); count++; } vbattfilt = vbattfilt / 64; #ifdef SERIAL printf("Vbatt %2.2f \n", vbattfilt); #ifdef NOMOTORS printf("NO MOTORS\n"); #warning "NO MOTORS" #endif #endif #ifdef STOP_LOWBATTERY // infinite loop if (vbattfilt < STOP_LOWBATTERY_TRESH) failloop(2); #endif // loads acc calibration and gyro dafaults loadcal(); gyro_cal(); imu_init(); extern unsigned int liberror; if (liberror) { #ifdef SERIAL printf("ERROR: I2C \n"); #endif failloop(7); } lastlooptime = gettime(); extern int rxmode; extern int failsafe; float thrfilt; // // // MAIN LOOP // // checkrx(); while (1) { // gettime() needs to be called at least once per second maintime = gettime(); looptime = ((uint32_t) (maintime - lastlooptime)); if (looptime <= 0) looptime = 1; looptime = looptime * 1e-6f; if (looptime > 0.02f) // max loop 20ms { failloop(3); //endless loop } lastlooptime = maintime; if (liberror > 20) { failloop(8); // endless loop } sixaxis_read(); control(); // battery low logic float battadc = adc_read(1); // average of all 4 motor thrusts // should be proportional with battery current extern float thrsum; // from control.c // filter motorpwm so it has the same delay as the filtered voltage // ( or they can use a single filter) lpf(&thrfilt, thrsum, 0.9968); // 0.5 sec at 1.6ms loop time lpf(&vbattfilt, battadc, 0.9968); if (vbattfilt + VDROP_FACTOR * thrfilt < VBATTLOW) lowbatt = 1; else lowbatt = 0; // led flash logic if (rxmode != RX_MODE_BIND) { // non bind if (failsafe) { if (lowbatt) ledflash(500000, 8); else ledflash(500000, 15); } else { if (lowbatt) ledflash(500000, 8); else { if (ledcommand) { if (!ledcommandtime) ledcommandtime = gettime(); if (gettime() - ledcommandtime > 500000) { ledcommand = 0; ledcommandtime = 0; } ledflash(100000, 8); } else ledon(255); } } } else { // bind mode ledflash(100000 + 500000 * (lowbatt), 12); } checkrx(); #ifdef DEBUG elapsedtime = gettime() - maintime; #endif // loop time 1ms while ((gettime() - maintime) < 1000) delay(10); } // end loop }
/** **************************************************************************************** * @brief Setup the microcontroller system. * * Initialize the system clock and pins. ***************************************************************************************** */ void SystemInit(void) { /* ************************** * Sub module clock setting ************************** */ // Disable all peripheral clock, will be enabled in the driver initilization. timer_clock_off(QN_TIMER0); timer_clock_off(QN_TIMER1); timer_clock_off(QN_TIMER2); timer_clock_off(QN_TIMER3); uart_clock_off(QN_UART0); uart_clock_off(QN_UART1); spi_clock_off(QN_SPI0); usart_reset((uint32_t) QN_SPI1); spi_clock_off(QN_SPI1); flash_clock_off(); gpio_clock_off(); adc_clock_off(); dma_clock_off(); pwm_clock_off(); // Configure sytem clock. syscon_set_sysclk_src(CLK_XTAL, __XTAL); syscon_set_ahb_clk(__AHB_CLK); syscon_set_ble_clk(__BLE_CLK); syscon_set_apb_clk(__APB_CLK); syscon_set_timer_clk(__TIMER_CLK); syscon_set_usart_clk((uint32_t)QN_UART0, __USART_CLK); syscon_set_usart_clk((uint32_t)QN_UART1, __USART_CLK); clk32k_enable(__32K_TYPE); /* ************************** * IO configuration ************************** */ SystemIOCfg(); /* ************************** * Peripheral setting ************************** */ // GPIO initialization for led, button & test control pin. gpio_init(gpio_interrupt_callback); // LED led_init(); // Test controll pin is input to check work mode #if (defined(QN_TEST_CTRL_PIN)) gpio_pull_set(QN_TEST_CTRL_PIN, GPIO_PULL_UP); gpio_set_direction_field(QN_TEST_CTRL_PIN, (uint32_t)GPIO_INPUT); #if (defined(CFG_HCI_UART)) // Initialize HCI UART port uart_init(QN_HCI_PORT, USARTx_CLK(0), UART_9600); uart_tx_enable(QN_HCI_PORT, MASK_ENABLE); uart_rx_enable(QN_HCI_PORT, MASK_ENABLE); #elif (defined(CFG_HCI_SPI)) // Initialize HCI SPI port spi_init(QN_HCI_PORT, SPI_BITRATE(1000000), SPI_8BIT, SPI_SLAVE_MOD); gpio_set_direction_field(CFG_HCI_SPI_WR_CTRL_PIN, (uint32_t)GPIO_OUTPUT); gpio_write_pin(CFG_HCI_SPI_WR_CTRL_PIN, GPIO_HIGH); #endif #endif // Button button_init(); // Accelerometer accel_gpio_init(); #if (QN_DBG_PRINT) uart_init(QN_DEBUG_UART, USARTx_CLK(0), UART_115200); uart_tx_enable(QN_DEBUG_UART, MASK_ENABLE); uart_rx_enable(QN_DEBUG_UART, MASK_ENABLE); #endif }
// Initialise board void board_init (void) { #ifndef SIMULATE io_init(); // Init GPIOs uart_init(BAUD_RATE); stderr = &uartio; printf(str_boot_uart,BAUD_RATE); printf(str_boot_start); #else printf("Skipping UART initialization...\n"); #endif #ifndef SIMULATE digital_init(); #endif encoder_init(); #ifndef SIMULATE spi_init(); motor_init(); servo_init(); #ifdef LCD_DEBUG lcd_init(); //consider wrapping this in an #ifdef LCD_DEBUG tag? stdout = &lcdout; #else stdout = &uartio; stdin = &uartio; #endif adc_init(); isr_init(); memory_init(); #endif // load config, or fail if invalid if (!board_load_config()) board_fail("Bad Config"); printf(str_boot_conf); printf(str_boot_board, board_config.version>>8, board_config.version&0xFF); printf(str_boot_id, board_config.id); // print boot text to screen printf(str_boot_message, board_config.version>>8, board_config.version&0xFF); // check battery, fail if <7.5V printf(str_boot_batt,read_battery()); #ifdef CHECK_BATTERY if (!(read_battery()>=7200)) { // NOTE: in the current 2-battery version of the HappyBoard, the // battery voltage is the motor battery (P+). Holding GO overrides // the check so you can run the HappyBoard without a motor battery. if (go_press()) printf("WARNING: LOW BATTERY\n"); else board_fail("Low battery"); } else { printf("Battery OK\n"); } #endif #ifndef SIMULATE // initialise FPGA if (!fpga_init(FPGA_CONFIG_ADDRESS, board_config.fpga_len)) board_fail("FPGA failure"); printf(str_boot_fpga, fpga_get_version_major(), fpga_get_version_minor()); #else printf("Skipping FPGA initialization...\n"); #endif // all ok #ifndef SIMULATE #ifdef LCD_DEBUG lcd_set_pos(31); lcd_print_char('\1', NULL); #else printf("Board init complete.\n"); #endif #else printf("Board init complete.\n"); #endif #ifndef SIMULATE LED_COMM(0); #endif }
int main(int argc, char *argv[]) { //Initialize GTK gtk_init(&argc, &argv); builder = gtk_builder_new(); gtk_builder_add_from_file (builder, "main.glade", NULL); window = GTK_WIDGET (gtk_builder_get_object(builder, "window")); lblColdLegTemp = GTK_WIDGET (gtk_builder_get_object(builder, "lblColdLegTemp")); lblHotLegTemp = GTK_WIDGET (gtk_builder_get_object(builder, "lblHotLegTemp")); lblHeatingElementDC = GTK_WIDGET (gtk_builder_get_object(builder, "lblHeatingElementDC")); lblTpv = GTK_WIDGET (gtk_builder_get_object(builder, "lblTpv")); lblAlarm = GTK_WIDGET (gtk_builder_get_object(builder, "lblAlarm")); lblError = GTK_WIDGET (gtk_builder_get_object(builder, "lblError")); rbDependentGains = GTK_WIDGET (gtk_builder_get_object(builder, "rbDependentGains")); rbIndependentGains = GTK_WIDGET (gtk_builder_get_object(builder, "rbIndependentGains")); txtKc = GTK_WIDGET (gtk_builder_get_object(builder, "txtKc")); txtTi = GTK_WIDGET (gtk_builder_get_object(builder, "txtTi")); txtTd = GTK_WIDGET (gtk_builder_get_object(builder, "txtTd")); txtKp = GTK_WIDGET (gtk_builder_get_object(builder, "txtKp")); txtKi = GTK_WIDGET (gtk_builder_get_object(builder, "txtKi")); txtKd = GTK_WIDGET (gtk_builder_get_object(builder, "txtKd")); txtTsp = GTK_WIDGET (gtk_builder_get_object(builder, "txtTsp")); txtTdev = GTK_WIDGET (gtk_builder_get_object(builder, "txtTdev")); txtTbias = GTK_WIDGET (gtk_builder_get_object(builder, "txtTbias")); txtWcold = GTK_WIDGET (gtk_builder_get_object(builder, "txtWcold")); txtWhot = GTK_WIDGET (gtk_builder_get_object(builder, "txtWhot")); txtCVlow = GTK_WIDGET (gtk_builder_get_object(builder, "txtCVlow")); txtCVhigh = GTK_WIDGET (gtk_builder_get_object(builder, "txtCVhigh")); //Default Parameter Set (load from file or default if they don't exist) LoadDefaultParameters(¶meter_set, "parameters.csv"); //Update Parameter Text Boxes to Reflect Defaults sprintf(buffer, "%f", parameter_set.Kc); gtk_entry_set_text ((GtkEntry*) txtKc, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Ti); gtk_entry_set_text ((GtkEntry*) txtTi, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Td); gtk_entry_set_text ((GtkEntry*) txtTd, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Kp); gtk_entry_set_text ((GtkEntry*) txtKp, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Ki); gtk_entry_set_text ((GtkEntry*) txtKi, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Kd); gtk_entry_set_text ((GtkEntry*) txtKd, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Tsp); gtk_entry_set_text ((GtkEntry*) txtTsp, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Tdev); gtk_entry_set_text ((GtkEntry*) txtTdev, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Tbias); gtk_entry_set_text ((GtkEntry*) txtTbias, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Wcold); gtk_entry_set_text ((GtkEntry*) txtWcold, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.Whot); gtk_entry_set_text ((GtkEntry*) txtWhot, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.CVlow); gtk_entry_set_text ((GtkEntry*) txtCVlow, (gchar *) buffer); sprintf(buffer, "%f", parameter_set.CVhigh); gtk_entry_set_text ((GtkEntry*) txtCVhigh, (gchar *) buffer); btnUpdateParameters = GTK_WIDGET (gtk_builder_get_object(builder, "btnUpdateParameters")); g_signal_connect (btnUpdateParameters, "clicked", G_CALLBACK(btnUpdateParametersOnClick), NULL); btnControllerActive = GTK_WIDGET (gtk_builder_get_object(builder, "btnControllerActive")); g_signal_connect (btnControllerActive, "clicked", G_CALLBACK(btnControllerActiveOnClick), NULL); btnRTDInit = GTK_WIDGET (gtk_builder_get_object(builder, "btnRTDInit")); g_signal_connect (btnRTDInit, "clicked", G_CALLBACK(btnRTDInitOnClick), NULL); btnStepResponse = GTK_WIDGET (gtk_builder_get_object(builder, "btnStepResponse")); g_signal_connect (btnStepResponse, "clicked", G_CALLBACK(btnStepResponseOnClick), NULL); //Update Controller Active Button Label to Default gtk_button_set_label(GTK_BUTTON(btnControllerActive), "Controller Inactive"); gtk_toggle_button_set_active((GtkToggleButton*) btnControllerActive, 0); gtk_toggle_button_set_active((GtkToggleButton*) btnStepResponse, 0); ctrl.StepResponseMode = 0; lastStepResponseMode = 1; gtk_builder_connect_signals(builder, NULL); g_object_unref(G_OBJECT(builder)); g_signal_connect(window, "delete-event", G_CALLBACK(delete_event), NULL); g_signal_connect(window, "destroy", G_CALLBACK(destroy), NULL); //Update Controller every 20ms and PWM every 1ms g_timeout_add(20, (GSourceFunc) update_event, (gpointer) window); g_timeout_add(1, (GSourceFunc) pwm_timer_event, (gpointer) window); gtk_widget_show (window); btnUpdateParametersOnClick(NULL, NULL); //Initialize WiringPi if(wiringPiSetupGpio() < 0) { return -1; } //Configure SPI Bus spi_init(); //Configure MAX31865 pinMode(MAX31865_DR0_PIN, INPUT); pinMode(MAX31865_DR1_PIN, INPUT); pinMode(MAX31865_CS0_PIN, OUTPUT); pinMode(MAX31865_CS1_PIN, OUTPUT); btnRTDInitOnClick(NULL, NULL); //Initialize PWM pwm.pin = HeatingElement_PIN; pinMode(pwm.pin, OUTPUT); digitalWrite(pwm.pin, HIGH); pwm.state = 1; pwm.dc = 0.0f; pwm.period = 0.020f; //20 ms pwm.lastUpdate = getDoubleTime(); //Run GTK Loop gtk_main(); return 0; }
int main (void) { #ifdef BOOTLOADER_SUPPORT _IVREG = _BV (IVCE); /* prepare ivec change */ _IVREG = _BV (IVSEL); /* change ivec to bootloader */ #endif /* Default DDR Config */ #if IO_HARD_PORTS >= 4 && DDR_MASK_A != 0 DDRA = DDR_MASK_A; #endif #if DDR_MASK_B != 0 DDRB = DDR_MASK_B; #endif #if DDR_MASK_C != 0 DDRC = DDR_MASK_C; #endif #if DDR_MASK_D != 0 DDRD = DDR_MASK_D; #endif #if IO_HARD_PORTS >= 6 #if DDR_MASK_E != 0 DDRE = DDR_MASK_E; #endif #if DDR_MASK_F != 0 DDRF = DDR_MASK_F; #endif #endif #if IO_HARD_PORTS >= 7 #if DDR_MASK_G != 0 DDRG = DDR_MASK_G; #endif #endif #ifdef STATUSLED_POWER_SUPPORT PIN_SET(STATUSLED_POWER); #endif //FIXME: zum ethersex meta system hinzufügen, aber vor allem anderem initalisieren debug_init(); debug_printf("ethersex " VERSION_STRING_LONG " (Debug mode)\n"); #ifdef DEBUG_RESET_REASON if (bit_is_set (mcusr_mirror, BORF)) debug_printf("reset: Brown-out\n"); else if (bit_is_set (mcusr_mirror, PORF)) debug_printf("reset: Power on\n"); else if (bit_is_set (mcusr_mirror, WDRF)) debug_printf("reset: Watchdog\n"); else if (bit_is_set (mcusr_mirror, EXTRF)) debug_printf("reset: Extern\n"); else debug_printf("reset: Unknown\n"); #endif #ifdef BOOTLOADER_SUPPORT /* disable interrupts */ cli (); wdt_disable(); #endif //BOOTLOADER_SUPPORT /* enable interrupts */ sei (); #ifdef USE_WATCHDOG debug_printf("enabling watchdog\n"); #ifdef DEBUG /* for debugging, test reset cause and jump to bootloader */ if (MCU_STATUS_REGISTER & _BV (WDRF)) { debug_printf("bootloader...\n"); jump_to_bootloader(); } #endif /* set watchdog to 2 seconds */ wdt_enable(WDTO_2S); wdt_kick(); #else //USE_WATCHDOG debug_printf("disabling watchdog\n"); wdt_disable(); #endif //USE_WATCHDOG #if defined(RFM12_SUPPORT) || defined(ENC28J60_SUPPORT) \ || defined(DATAFLASH_SUPPORT) spi_init(); #endif ethersex_meta_init(); /* must be called AFTER all other initialization */ #ifdef PORTIO_SUPPORT portio_init(); #elif defined(NAMED_PIN_SUPPORT) np_simple_init(); #endif #ifdef ENC28J60_SUPPORT debug_printf ("enc28j60 revision 0x%x\n", read_control_register (REG_EREVID)); debug_printf ("mac: %02x:%02x:%02x:%02x:%02x:%02x\n", uip_ethaddr.addr[0], uip_ethaddr.addr[1], uip_ethaddr.addr[2], uip_ethaddr.addr[3], uip_ethaddr.addr[4], uip_ethaddr.addr[5]); #endif #ifdef STATUSLED_BOOTED_SUPPORT PIN_SET(STATUSLED_BOOTED); #endif ethersex_meta_startup(); /* main loop */ while (1) { wdt_kick(); ethersex_meta_mainloop(); #ifdef SD_READER_SUPPORT if (sd_active_partition == NULL) { if (!sd_try_init()) { #ifdef VFS_SD_SUPPORT vfs_sd_try_open_rootnode(); #endif } wdt_kick(); } #endif #ifdef BOOTLOADER_JUMP if (status.request_bootloader) { #ifdef MBR_SUPPORT mbr_config.bootloader = 1; write_mbr(); #endif #ifdef CLOCK_CRYSTAL_SUPPORT TC2_INT_OVERFLOW_OFF; #endif #ifdef DCF77_SUPPORT ACSR &= ~_BV (ACIE); #endif cli(); jump_to_bootloader(); } #endif #ifndef TEENSY_SUPPORT if (status.request_wdreset) { cli(); wdt_enable(WDTO_15MS); for (;;); } #endif if (status.request_reset) { cli(); void (*reset) (void) = NULL; reset(); } } }
STATIC_PREFIX int fw_load_intl(unsigned por_cfg,unsigned target,unsigned size) { int rc=0; unsigned temp_addr; #if CONFIG_UCL temp_addr=target-0x800000; #else temp_addr=target; #endif unsigned * mem; switch(POR_GET_1ST_CFG(por_cfg)) { case POR_1ST_NAND: case POR_1ST_NAND_RB: rc=nf_read(temp_addr,size); break; case POR_1ST_SPI : case POR_1ST_SPI_RESERVED : mem=(unsigned *)(NOR_START_ADDR+READ_SIZE); spi_init(); #if CONFIG_UCL==0 if((rc=check_sum(target,0,0))!=0) { return rc; } #endif serial_puts("Boot From SPI\n"); memcpy((unsigned*)temp_addr,mem,size); break; case POR_1ST_SDIO_C: serial_puts("Boot From SDIO C\n"); rc=sdio_read(temp_addr,size,POR_2ND_SDIO_C<<3); break; case POR_1ST_SDIO_B: rc=sdio_read(temp_addr,size,POR_2ND_SDIO_B<<3);break; case POR_1ST_SDIO_A: rc=sdio_read(temp_addr,size,POR_2ND_SDIO_A<<3);break; break; default: return 1; } #if defined(CONFIG_AML_SECU_BOOT_V2) if(aml_sec_boot_check((unsigned char *)temp_addr)) { AML_WATCH_DOG_START(); } #endif //CONFIG_AML_SECU_BOOT_V2 #if CONFIG_UCL #ifndef CONFIG_IMPROVE_UCL_DEC unsigned len; if(rc==0){ serial_puts("ucl decompress..."); rc=uclDecompress((char*)target,&len,(char*)temp_addr); serial_puts(rc?"fail\n":"pass\n"); } #endif #endif #ifndef CONFIG_IMPROVE_UCL_DEC if(rc==0) rc=check_sum((unsigned*)target,magic_info->crc[1],size); #else if(rc==0) rc=check_sum((unsigned*)temp_addr,magic_info->crc[1],size); #endif return rc; }
/* Act on incomming packet. Comand in msg_buf, seqnum needed for reply */ void programcmd(unsigned char seqnum) { unsigned char tmp,tmp2,addressing_is_word,ci,cj,cstatus; unsigned int answerlen; unsigned long poll_address=0; unsigned int i,nbytes; // distingush addressing CMD_READ_EEPROM_ISP (8bit) and CMD_READ_FLASH_ISP (16bit) addressing_is_word=1; // 16 bit is default switch(msg_buf[0]){ case CMD_SIGN_ON: // prepare answer: msg_buf[0] = CMD_SIGN_ON; // 0x01 msg_buf[1] = STATUS_CMD_OK; // 0x00 msg_buf[2] = 8; //len //strcpy((char *)&(msg_buf[3]),"AVRISP_2"); // note: this copied also the null termination msg_buf[3] = 'S'; msg_buf[4] = 'T'; msg_buf[5] = 'K'; msg_buf[6] = '5'; msg_buf[7] = '0'; msg_buf[8] = '0'; msg_buf[9] = '_'; msg_buf[10] = '2'; answerlen=11; break; case CMD_SET_PARAMETER: // not implemented: // PARAM_VTARGET // PARAM_VADJUST // PARAM_OSC_PSCALE // PARAM_OSC_CMATCH if (msg_buf[1]==PARAM_SCK_DURATION){ spi_set_sck_duration(msg_buf[2]); }else if(msg_buf[1]==PARAM_RESET_POLARITY){ param_reset_polarity=msg_buf[2]; }else if(msg_buf[1]==PARAM_CONTROLLER_INIT){ param_controller_init=msg_buf[2]; } answerlen = 2; //msg_buf[0] = CMD_SET_PARAMETER; msg_buf[1] = STATUS_CMD_OK; break; case CMD_GET_PARAMETER: tmp=0xff; switch(msg_buf[1]) { case PARAM_BUILD_NUMBER_LOW: tmp = CONFIG_PARAM_BUILD_NUMBER_LOW; break; case PARAM_BUILD_NUMBER_HIGH: tmp = CONFIG_PARAM_BUILD_NUMBER_HIGH; break; case PARAM_HW_VER: tmp = CONFIG_PARAM_HW_VER; break; case PARAM_SW_MAJOR: tmp = CONFIG_PARAM_SW_MAJOR; break; case PARAM_SW_MINOR: tmp = CONFIG_PARAM_SW_MINOR; break; case PARAM_VTARGET: tmp = CONFIG_PARAM_VTARGET; break; case PARAM_VADJUST: tmp = CONFIG_PARAM_VADJUST; break; case PARAM_SCK_DURATION: tmp = spi_get_sck_duration(); break; case PARAM_RESET_POLARITY: // is actually write only, list anyhow tmp = param_reset_polarity; break; case PARAM_CONTROLLER_INIT: tmp = param_controller_init; break; case PARAM_OSC_PSCALE: tmp = CONFIG_PARAM_OSC_PSCALE; break; case PARAM_OSC_CMATCH: tmp = CONFIG_PARAM_OSC_CMATCH; break; case PARAM_TOPCARD_DETECT: // stk500 only tmp = 0x8c; // no card ?? break; case PARAM_DATA: // stk500 only tmp = 0; break; default: break; } if (tmp ==0xff){ // command not understood answerlen = 2; //msg_buf[0] = CMD_GET_PARAMETER; msg_buf[1] = STATUS_CMD_UNKNOWN; }else{ answerlen = 3; //msg_buf[0] = CMD_GET_PARAMETER; msg_buf[1] = STATUS_CMD_OK; msg_buf[2] = tmp; } break; case CMD_LOAD_ADDRESS: address = ((unsigned long)msg_buf[1])<<24; address |= ((unsigned long)msg_buf[2])<<16; address |= ((unsigned long)msg_buf[3])<<8; address |= ((unsigned long)msg_buf[4]); // atmega2561/atmega2560 //If bit 31 is set, this indicates that the following read/write operation //will be performed on a memory that is larger than 64KBytes. This is an //indication to STK500 that a load extended address must be executed. See //datasheet for devices with memories larger than 64KBytes. // if (msg_buf[1] >= 0x80) { larger_than_64k = 1; }else{ larger_than_64k = 0; } extended_address = msg_buf[2]; new_address = 1; answerlen = 2; //msg_buf[0] = CMD_LOAD_ADDRESS; msg_buf[1] = STATUS_CMD_OK; break; case CMD_FIRMWARE_UPGRADE: // firmare upgrade is not supported this way answerlen = 2; //msg_buf[0] = CMD_FIRMWARE_UPGRADE; msg_buf[1] = STATUS_CMD_FAILED; break; case CMD_ENTER_PROGMODE_ISP: // 0x10 // The syntax of this command is as follows: // 0: Command ID 1 byte, CMD_ENTER_ PROGMODE_ISP // 1: timeout 1 byte, Command time-out (in ms) // 2: stabDelay 1 byte, Delay (in ms) used for pin stabilization // 3: cmdexeDelay 1 byte, Delay (in ms) in connection with the EnterProgMode command execution // 4: synchLoops 1 byte, Number of synchronization loops // 5: byteDelay 1 byte, Delay (in ms) between each byte in the EnterProgMode command. // 6: pollValue 1 byte, Poll value: 0x53 for AVR, 0x69 for AT89xx // 7: pollIndex 1 byte, Start address, received byte: 0 = no polling, 3 = AVR, 4 = AT89xx // cmd1 1 byte // cmd2 1 byte // cmd3 1 byte // cmd4 1 byte LED_ON; spi_init(); delay_ms(msg_buf[2]); // stabDelay answerlen=2; //msg_buf[0] = CMD_ENTER_PROGMODE_ISP; // set default to failed: msg_buf[1] = STATUS_CMD_FAILED; //connect to the target i=0; // limit the loops: if (msg_buf[4]> 48){ msg_buf[4]=48; } if (msg_buf[5] < 1){ // minimum byteDelay msg_buf[5]=1; } while(i<msg_buf[4]){//synchLoops wd_kick(); LED_ON; // blink during init delay_ms(msg_buf[3]); //cmdexeDelay i++; spi_mastertransmit(msg_buf[8]);//cmd1 delay_ms(msg_buf[5]); //byteDelay spi_mastertransmit(msg_buf[9]); //cmd2 delay_ms(msg_buf[5]); //byteDelay LED_OFF; // blink during init tmp=spi_mastertransmit(msg_buf[10]);//cmd3 delay_ms(msg_buf[5]); //byteDelay tmp2=spi_mastertransmit(msg_buf[11]);//cmd4 // //7=pollIndex, 6=pollValue if(msg_buf[7]==3 && tmp==msg_buf[6]) { msg_buf[1] = STATUS_CMD_OK; } //7=pollIndex, 6=pollValue if(msg_buf[7]!=3 && tmp2==msg_buf[6]) { msg_buf[1] = STATUS_CMD_OK; } if(msg_buf[7]==0) { //pollIndex msg_buf[1] = STATUS_CMD_OK; } if(msg_buf[1] == STATUS_CMD_OK ) { LED_ON; i=msg_buf[4];// end loop }else{ // new try, see e.g chapeter "Serial download" in // data sheet. // in atmega8 it says: give positive reset pulse // and try again // in at90s2313 it says: give positive sck pulse // and try again // One of those datasheets must be wrong!? // Guido thinks that spi_sck_pulse is correct // and will also work for atmega8 given that // the number of synchLoops is at least 32. //spi_reset_pulse(); spi_sck_pulse(); delay_ms(20); } } break; case CMD_LEAVE_PROGMODE_ISP: spi_disable(); LED_OFF; answerlen = 2; //msg_buf[0] = CMD_LEAVE_PROGMODE_ISP; msg_buf[1] = STATUS_CMD_OK; break; case CMD_CHIP_ERASE_ISP: spi_mastertransmit(msg_buf[3]); spi_mastertransmit(msg_buf[4]); spi_mastertransmit(msg_buf[5]); spi_mastertransmit(msg_buf[6]); if(msg_buf[2]==0) { // pollMethod use delay delay_ms(msg_buf[1]); // eraseDelay } else { // pollMethod RDY/BSY cmd ci=150; // timeout while((spi_mastertransmit_32(0xF0000000)&1)&&ci){ ci--; } } answerlen = 2; //msg_buf[0] = CMD_CHIP_ERASE_ISP; msg_buf[1] = STATUS_CMD_OK; break; case CMD_PROGRAM_EEPROM_ISP: addressing_is_word=0; // address each byte case CMD_PROGRAM_FLASH_ISP: // msg_buf[0] CMD_PROGRAM_FLASH_ISP = 0x13 // msg_buf[1] NumBytes H // msg_buf[2] NumBytes L // msg_buf[3] mode // msg_buf[4] delay // msg_buf[5] cmd1 (Load Page, Write Program Memory) // msg_buf[6] cmd2 (Write Program Memory Page) // msg_buf[7] cmd3 (Read Program Memory) // msg_buf[8] poll1 (value to poll) // msg_buf[9] poll2 // msg_buf[n+10] Data poll_address=0; ci=150; // set a minimum timed delay if (msg_buf[4] < 4){ msg_buf[4]=4; } // set a max delay if (msg_buf[4] > 32){ msg_buf[4]=32; } saddress=address&0xFFFF; // previous address, start address nbytes = ((unsigned int)msg_buf[1])<<8; nbytes |= msg_buf[2]; if (nbytes> 280){ // corrupted message answerlen = 2; msg_buf[1] = STATUS_CMD_FAILED; break; } wd_kick(); // store the original mode: tmp2=msg_buf[3]; // result code cstatus=STATUS_CMD_OK; // msg_buf[3] test Word/Page Mode bit: if ((msg_buf[3]&1)==0){ // word mode for(i=0;i<nbytes;i++) { // The Low/High byte selection bit is // bit number 3. Set high byte for uneven bytes if(addressing_is_word && i&1) { // high byte spi_mastertransmit(msg_buf[5]|(1<<3)); } else { // low byte spi_mastertransmit(msg_buf[5]); } spi_mastertransmit_16(address&0xFFFF); spi_mastertransmit(msg_buf[i+10]); // if the data byte is not same as poll value // in that case we can do polling: if(msg_buf[8]!=msg_buf[i+10]) { poll_address = address&0xFFFF; // restore the possibly modifed mode: msg_buf[3]=tmp2; } else { //switch the mode to timed delay (waiting), for this word msg_buf[3]= 0x02; } // wd_kick(); if (!addressing_is_word){ // eeprom writing, eeprom needs more time delay_ms(2); } //check the different polling mode methods if(msg_buf[3]& 0x04) { //data value polling tmp=msg_buf[8]; ci=150; // timeout while(tmp==msg_buf[8] && ci ){ // The Low/High byte selection bit is // bit number 3. Set high byte for uneven bytes // Read data: if(addressing_is_word && i&1) { spi_mastertransmit(msg_buf[7]|(1<<3)); } else { spi_mastertransmit(msg_buf[7]); } spi_mastertransmit_16(poll_address); tmp=spi_mastertransmit(0x00); ci--; } } else if(msg_buf[3]&0x08){ //RDY/BSY polling ci=150; // timeout while((spi_mastertransmit_32(0xF0000000)&1)&&ci){ ci--; } }else{ //timed delay (waiting) delay_ms(msg_buf[4]); } if (addressing_is_word){ //increment word address only when we have an uneven byte if(i&1) address++; }else{ //increment address address++; } if (ci==0){ cstatus=STATUS_CMD_TOUT; } } }else{ //page mode, all modern chips for(i=0;i<nbytes;i++) { wd_kick(); // In commands PROGRAM_FLASH and READ_FLASH "Load Extended Address" // command is executed before every operation if we are programming // processor with Flash memory bigger than 64k words and 64k words boundary // is just crossed or new address was just loaded. if (larger_than_64k && ((address&0xFFFF)==0 || new_address)){ // load extended addr byte 0x4d spi_mastertransmit(0x4d); spi_mastertransmit(0x00); spi_mastertransmit(extended_address); spi_mastertransmit(0x00); new_address = 0; } // The Low/High byte selection bit is // bit number 3. Set high byte for uneven bytes if(addressing_is_word && i&1) { spi_mastertransmit(msg_buf[5]|(1<<3)); } else { spi_mastertransmit(msg_buf[5]); } spi_mastertransmit_16(address&0xFFFF); spi_mastertransmit(msg_buf[i+10]); // that the data byte is not same as poll value // in that case we can do polling: if(msg_buf[8]!=msg_buf[i+10]) { poll_address = address&0xFFFF; } else { //switch the mode to timed delay (waiting) //we must preserve bit 0x80 msg_buf[3]= (msg_buf[3]&0x80)|0x10; } if (addressing_is_word){ //increment word address only when we have an uneven byte if(i&1) { address++; if((address&0xFFFF)==0xFFFF){ extended_address++; } } }else{ address++; } } wd_kick(); //page mode check result: // // stk sets the Write page bit (7) if the page is complete // and we should write it. if(msg_buf[3]&0x80) { spi_mastertransmit(msg_buf[6]); spi_mastertransmit_16(saddress); spi_mastertransmit(0); // if (!addressing_is_word){ // eeprom writing, eeprom needs more time delay_ms(1); } //check the different polling mode methods ci=150; // timeout if(msg_buf[3]&0x20 && poll_address) { //Data value polling tmp=msg_buf[8]; while(tmp==msg_buf[8] && ci){ // The Low/High byte selection bit is // bit number 3. Set high byte for uneven bytes // Read data: if(poll_address&1) { spi_mastertransmit(msg_buf[7]|(1<<3)); } else { spi_mastertransmit(msg_buf[7]); } spi_mastertransmit_16(poll_address); tmp=spi_mastertransmit(0x00); ci--; } if (ci==0){ cstatus=STATUS_CMD_TOUT; } } else if(msg_buf[3]& 0x40){ //RDY/BSY polling while((spi_mastertransmit_32(0xF0000000)&1)&&ci){ ci--; } if (ci==0){ cstatus=STATUS_RDY_BSY_TOUT; } }else{ // simple waiting delay_ms(msg_buf[4]); } } } answerlen = 2; //msg_buf[0] = CMD_PROGRAM_FLASH_ISP; or CMD_PROGRAM_EEPROM_ISP msg_buf[1] = cstatus; break; case CMD_READ_EEPROM_ISP: addressing_is_word=0; // address each byte case CMD_READ_FLASH_ISP: // msg_buf[1] and msg_buf[2] NumBytes // msg_buf[3] cmd nbytes = ((unsigned int)msg_buf[1])<<8; nbytes |= msg_buf[2]; tmp = msg_buf[3]; // limit answer len, prevent overflow: if (nbytes> 280){ nbytes=280; } // for(i=0;i<nbytes;i++){ wd_kick(); // In commands PROGRAM_FLASH and READ_FLASH "Load Extended Address" // command is executed before every operation if we are programming // processor with Flash memory bigger than 64k words and 64k words boundary // is just crossed or new address was just loaded. if (larger_than_64k && ((address&0xFFFF)==0 || new_address)){ // load extended addr byte 0x4d spi_mastertransmit(0x4d); spi_mastertransmit(0x00); spi_mastertransmit(extended_address); spi_mastertransmit(0x00); new_address = 0; } //Select Low or High-Byte if(addressing_is_word && i&1) { spi_mastertransmit(tmp|(1<<3)); } else { spi_mastertransmit(tmp); } spi_mastertransmit_16(address&0xFFFF); msg_buf[i+2] = spi_mastertransmit(0); if (addressing_is_word){ //increment word address only when we have an uneven byte if(i&1) { address++; if((address&0xFFFF)==0xFFFF){ extended_address++; } } }else{ address++; } } answerlen = nbytes+3; //msg_buf[0] = CMD_READ_FLASH_ISP; or CMD_READ_EEPROM_ISP msg_buf[1] = STATUS_CMD_OK; msg_buf[nbytes+2] = STATUS_CMD_OK; break; case CMD_PROGRAM_LOCK_ISP: case CMD_PROGRAM_FUSE_ISP: spi_mastertransmit(msg_buf[1]); spi_mastertransmit(msg_buf[2]); spi_mastertransmit(msg_buf[3]); spi_mastertransmit(msg_buf[4]); answerlen =3; // msg_buf[0] = CMD_PROGRAM_FUSE_ISP; or CMD_PROGRAM_LOCK_ISP msg_buf[1] = STATUS_CMD_OK; msg_buf[2] = STATUS_CMD_OK; break; case CMD_READ_OSCCAL_ISP: case CMD_READ_SIGNATURE_ISP: case CMD_READ_LOCK_ISP: case CMD_READ_FUSE_ISP: for(ci=0;ci<4;ci++){ tmp = spi_mastertransmit(msg_buf[ci+2]); if (msg_buf[1] == (ci + 1)){ msg_buf[2] = tmp; } delay_ms(5); } answerlen = 4; // msg_buf[0] = CMD_READ_FUSE_ISP; or CMD_READ_LOCK_ISP or ... msg_buf[1] = STATUS_CMD_OK; // msg_buf[2] is the data (fuse byte) msg_buf[3] = STATUS_CMD_OK; break; case CMD_SPI_MULTI: // 0: CMD_SPI_MULTI // 1: NumTx // 2: NumRx // 3: RxStartAddr counting from zero // 4+: TxData (len in NumTx) // example: 0x1d 0x04 0x04 0x00 0x30 0x00 0x00 0x00 tmp=msg_buf[2]; tmp2=msg_buf[3]; cj=0; ci=0; for (cj=0; cj<msg_buf[1]; cj++) { delay_ms(5); if (cj >= tmp2 && ci <tmp){ // store answer starting from msg_buf[2] msg_buf[ci+2]=spi_mastertransmit(msg_buf[cj+4]); ci++; }else{ spi_mastertransmit(msg_buf[cj+4]); } } // padd with zero: while(ci<tmp){ msg_buf[ci+2]=0; ci++; } answerlen = ci+3; // msg_buf[0] = CMD_SPI_MULTI msg_buf[1] = STATUS_CMD_OK; // msg_buf[2...ci+1] is the data msg_buf[ci+2] = STATUS_CMD_OK; break; default: // we should not come here answerlen = 2; msg_buf[1] = STATUS_CMD_UNKNOWN; break; } transmit_answer(seqnum,answerlen); }
int main() { DDRC &= ~(1<<PC0); //input for DPDT switch increase_day_count_eeprom(); //some more initialization of EEPROM /*** Students list ***/ /** These are the bytes that are read from the RFID tags of the students**/ uint8_t person_byte[MAX_PEOPLE][5] = { {0x23, 0x6D, 0xD6, 0x00, 0x98} , {0xF9, 0x46, 0x1D, 0x00, 0xA2}, {0xA3, 0x7E, 0x30, 0x02, 0xEF} }; //Some tags that we used to experiment //{0xF9, 0x46, 0x1D, 0x00, 0xA2} //{0x23, 0x6D, 0xD6, 0x00, 0x98} - recognized1 //{0xF9, 0x46, 0x1D, 0x00, 0xA2} - recognized2 (change any bit in any of these 2 to see effect of unrecognized person entering) //{0xA3, 0x7E, 0x30, 0x02, 0xEF} - Nimi - white //{0x5B, 0xA8, 0x2C, 0x00, 0xDF} - Adnan - blue // person name list .. these used to control people names etc int detected_person; int person_entry_list[MAX_PEOPLE] = {0, 0, 0}; char *person_name[MAX_LEN] = { (char *)"Sibat", (char *)"Ripon" , (char *)"Nimi" }; char *entered_msg = (char *)" entered"; char *left_msg = (char *)" left"; char msg_to_show[100]; int person_count = 0; // iterator and byte array to use later uint8_t byte, i; uint8_t str[MAX_LEN]; _delay_ms(50); // initialize the LCD LCDInit(LS_BLINK); LCDWriteStringXY(2,0,"RFID Reader"); // spi initialization spi_init(); _delay_ms(1000); LCDClear(); //init reader mfrc522_init(); // poll until reader is found while(1) { byte = mfrc522_read(VersionReg); if(byte == 0x92) { LCDClear(); LCDWriteStringXY(2,0,"Detected"); _delay_ms(1000); break; } else { LCDClear(); LCDWriteStringXY(0,0,"No reader found"); _delay_ms(800); LCDClear(); LCDWriteStringXY(0, 0, "Connect reader"); _delay_ms(1000); } } // ready to run _delay_ms(1500); LCDClear(); // initializing the RGB LEDs DDRA = 0xFF; PORTA = 0xFE; //Interrupt INT2 DDRB |= (1<<PB2); // Set PB2 as input (Using for interrupt INT2) PORTB |= (1<<PB2); // Enable PB2 pull-up resistor // setting up the timer codes // setting up the LED animation initials // TODO timer code ... START HERE ... TCCR1A = 0x00; TCCR1B = 0x01; TIMSK = 0x04; min = 0; sec = 0; hour = 0; sec_counter = 0; LED_animation_status = 0; LED_animation_on = 1; program_status_2_first_time = 1; program_status_3_first_time = 1; program_status_4_first_time = 1; // TODO timer code ... ENDS HERE ... // The loop starts here // program status : 1 means entrance period // : 2 means session period // : 3 means session ended program_status = 1; //Using interrupt 2 for reading history mode GICR &= ~(1<<INT2); // Disable INT2 MCUCSR |= (1<<ISC2); // Trigger INT2 on 1 = rising edge , 0 falling edge GIFR |= (1<<INTF2); // clear INTF2 GICR |= (1<<INT2); // Enable INT2 sei(); while(1) { spi_init(); mfrc522_init(); byte = mfrc522_read(ComIEnReg); mfrc522_write(ComIEnReg,byte|0x20); byte = mfrc522_read(DivIEnReg); mfrc522_write(DivIEnReg,byte|0x80); if(program_status == 1) { LCDClear(); LCDWriteStringXY(0, 0, "Show your card."); LCDWriteStringXY(0, 1, "#students:"); LCDWriteIntXY(12,1, person_count ,2 ); byte = mfrc522_request(PICC_REQALL,str); if(byte == CARD_FOUND) { byte = mfrc522_get_card_serial(str); if(byte == CARD_FOUND) { LED_animation_on = 0; // check for person 1 detected_person = -1; for(i = 0; i < MAX_PEOPLE; i++) { for(byte = 0; byte < 5; byte++) { /***The following piece of code was written to test and read the bytes off the tags and print them***/ //LCDClear(); //LCDWriteIntXY(0,0,byte,2); //LCDWriteIntXY(0,1,str[byte],14); //_delay_ms(3000); if(str[byte] != person_byte[i][byte]) { break; } } if(byte == 5) { detected_person = i; break; } } if(i == MAX_PEOPLE) { detected_person = -1; } // showing message on LCD upon decision of the person LCDClear(); if(detected_person == -1) { PORTA = 0x7E; LCDClear(); LCDWriteStringXY(0, 0, "Access denied!"); _delay_ms(2000); PORTA = 0xFE; LCDClear(); LCDWriteStringXY(0, 0, "Unrecognized!"); } else { PORTA = 0xFD; LCDClear(); LCDWriteStringXY(0, 0, "Access granted!"); _delay_ms(2000); if(person_entry_list[i] == 0) { person_entry_list[i] = 1; } else { person_entry_list[i] = 0; } strcpy(msg_to_show, person_name[detected_person]); if(person_entry_list[i] == 0) { /** Code to sound buzzer when a student is leaving **/ PORTA = 0x7D; _delay_ms(200); PORTA = 0xFD; // end of buzzer code //EEPROM WRITE if(write_enable_eeprom == 1){ eeprom_update_byte ((uint8_t*) (&NonVolatileIsPresent[curr_day][i]), 0); } person_count--; strcat(msg_to_show, left_msg); } else { /** Code to sound buzzer when a student is entering **/ PORTA = 0x7D; _delay_ms(200); PORTA = 0xFD; _delay_ms(100); PORTA = 0x7D; _delay_ms(200); PORTA = 0xFD; // end of buzzer code //EEPROM WRITE if(write_enable_eeprom == 1) { eeprom_write_byte ((uint8_t*) (&NonVolatileIsPresent[curr_day][i]), 1); eeprom_update_byte ((uint8_t*) (&NonVolatileHour[curr_day][i]), hour); eeprom_update_byte ((uint8_t*) (&NonVolatileMinute[curr_day][i]), min); eeprom_update_byte ((uint8_t*) (&NonVolatileSecond[curr_day][i]), sec); } person_count++; strcat(msg_to_show, entered_msg); } LCDClear(); LCDWriteStringXY(0, 0, msg_to_show); } _delay_ms(3000); PORTA = 0xFE; LCDClear(); LED_animation_on = 1; } else { LCDClear(); LCDWriteStringXY(0,1,"Error"); } } _delay_ms(200); } else if(program_status == 2) { LCDClear(); LCDWriteStringXY(0, 0, "In session now!"); LCDWriteStringXY(0, 1, "#students:"); LCDWriteIntXY(12,1, person_count ,2 ); byte = mfrc522_request(PICC_REQALL,str); if(byte == CARD_FOUND) { LED_animation_on = 0; PORTA = 0x7E; LCDClear(); LCDWriteStringXY(0, 0, "Warning!!"); _delay_ms(2000); LCDClear(); LCDWriteStringXY(0, 0, "Session running."); _delay_ms(2000); PORTA = 0xFE; LCDClear(); LCDWriteStringXY(0, 0, "Can't go out/in."); _delay_ms(2000); LCDClear(); PORTA = 0xFB; LED_animation_on = 1; } _delay_ms(200); } else if(program_status == 3) { LCDClear(); LCDWriteStringXY(0, 0, "Session ended!"); LCDWriteStringXY(0, 1, "#students:"); LCDWriteIntXY(12,1, person_count ,2 ); byte = mfrc522_request(PICC_REQALL,str); if(byte == CARD_FOUND) { byte = mfrc522_get_card_serial(str); if(byte == CARD_FOUND) { LED_animation_on = 0; // check for person 1 detected_person = -1; for(i = 0; i < MAX_PEOPLE; i++) { for(byte = 0; byte < 5; byte++) { if(str[byte] != person_byte[i][byte]) { break; } } if(byte == 5) { detected_person = i; break; } } // showing message on LCD upon decision of the person if(detected_person == -1) { PORTA = 0x7E; LCDClear(); LCDWriteStringXY(0, 0, "Unrecognized!"); _delay_ms(2000); PORTA = 0xFE; } else { PORTA = 0xFB; if(person_entry_list[detected_person] != 0){ LCDClear(); strcpy(msg_to_show, "Take care "); strcat(msg_to_show, person_name[detected_person]); LCDWriteStringXY(0, 0, msg_to_show); _delay_ms(1000); LCDClear(); strcpy(msg_to_show, person_name[detected_person]); strcat(msg_to_show, left_msg); LCDWriteStringXY(0, 0, msg_to_show); person_entry_list[detected_person] = 0; person_count--; //unnecessary sanity check if(person_count == 0) { break; } } } _delay_ms(3000); PORTA = 0xFD; LCDClear(); LED_animation_on = 1; } else { PORTA = 0x7E; LCDClear(); LCDWriteStringXY(0,1,"Error"); _delay_ms(2000); PORTA = 0xFE; LCDClear(); PORTA = 0xFD; } } _delay_ms(200); } else { /***This is the warning phase. When leaving period has ended, but some students were still stuck in the classroom, the buzzer buzzes off continuously suspecting that some students might be sick or in trouble. ***/ if(person_count != 0) { LED_animation_on = 0; PORTA = 0x7E; LCDClear(); LCDWriteIntXY(0,0, person_count ,2 ); LCDWriteStringXY(3, 0, "student could"); LCDWriteStringXY(0, 1, "not get out"); _delay_ms(1500); LCDClear(); LCDWriteStringXY(0, 0, "Take caution!"); _delay_ms(1500); PORTA = 0xFE; _delay_ms(400); } else { /**When all students have left, nothing to do. **/ LCDClear(); break; } } } LED_animation_on = 1; PORTA = 0xFB; temp_PORTA = PORTA; LCDClear(); LCDWriteStringXY(0, 0, "Everyone left."); while(1) { ; } cli(); }
int main(int argc, char ** argv){ int randptr, i; spi_init(); wishbone_read((unsigned char *)buffer, 2, 0x0000); if (buffer[1] != 0xde || buffer[0] != 0xad) { fprintf(stderr, "Invalid ID: 0x%02x%02x. Did you load the FPGA?\n", buffer[1], buffer[0]); spi_close(); exit(1); } /* // Reset buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); // Address buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0002); buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0003); // Data buffer[1] = 0xBE; buffer[0] = 0xEF; wishbone_write((unsigned char *)buffer, 2, 0x0001); // Write buffer[1] = 0; buffer[0] = 3; wishbone_write((unsigned char *)buffer, 2, 0x0004); // Reset buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); // Address buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0002); buffer[1] = 0; buffer[0] = 3; wishbone_write((unsigned char *)buffer, 2, 0x0003); // Data buffer[1] = 0xF0; buffer[0] = 0x0D; wishbone_write((unsigned char *)buffer, 2, 0x0001); // Write buffer[1] = 0; buffer[0] = 3; wishbone_write((unsigned char *)buffer, 2, 0x0004); */ for (i = 0; i < 256; i++) { // Reset buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); // Address buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0002); buffer[1] = 0; buffer[0] = i; wishbone_write((unsigned char *)buffer, 2, 0x0003); // Read buffer[1] = 0; buffer[0] = 1; wishbone_write((unsigned char *)buffer, 2, 0x0004); usleep(10); // Reset buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); wishbone_read((unsigned char *)buffer, 2, 0x0001); fprintf(stderr, "0x%02x: 0x%02x%02x\n", i, buffer[1], buffer[0]); } // Reset buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); // Address buffer[1] = 0; buffer[0] = 1; wishbone_write((unsigned char *)buffer, 2, 0x0002); buffer[1] = 0; buffer[0] = 1; wishbone_write((unsigned char *)buffer, 2, 0x0003); // Read buffer[1] = 0; buffer[0] = 1; wishbone_write((unsigned char *)buffer, 2, 0x0004); usleep(10); // Reset buffer[1] = 0; buffer[0] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); wishbone_read((unsigned char *)buffer, 2, 0x0001); fprintf(stderr, "Read data 0x%02x%02x\n", buffer[0], buffer[1]); /* // Address buffer[0] = 0; buffer[1] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0003); // Read buffer[0] = 1; buffer[1] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); sleep(1); // Reset buffer[0] = 0; buffer[1] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); // Data wishbone_read((unsigned char *)buffer, 2, 0x0001); fprintf(stderr, "Read data 0x%02x%02x\n", buffer[0], buffer[1]); // Address buffer[0] = 0; buffer[1] = 10; wishbone_write((unsigned char *)buffer, 2, 0x0003); // Read buffer[0] = 1; buffer[1] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); sleep(1); // Reset buffer[0] = 0; buffer[1] = 0; wishbone_write((unsigned char *)buffer, 2, 0x0004); // Data wishbone_read((unsigned char *)buffer, 2, 0x0001); fprintf(stderr, "Read data 0x%02x%02x\n", buffer[0], buffer[1]); */ spi_close(); return 0; }
/* * Routine: board_init * Description: Early hardware init. */ int board_init(void) { __maybe_unused int err; /* Do clocks and UART first so that printf() works */ clock_init(); clock_verify(); #ifdef CONFIG_FDT_SPI pin_mux_spi(); spi_init(); #endif #ifdef CONFIG_PWM_TEGRA if (pwm_init(gd->fdt_blob)) debug("%s: Failed to init pwm\n", __func__); #endif #ifdef CONFIG_LCD pin_mux_display(); tegra_lcd_check_next_stage(gd->fdt_blob, 0); #endif /* boot param addr */ gd->bd->bi_boot_params = (NV_PA_SDRAM_BASE + 0x100); power_det_init(); #ifdef CONFIG_SYS_I2C_TEGRA #ifndef CONFIG_SYS_I2C_INIT_BOARD #error "You must define CONFIG_SYS_I2C_INIT_BOARD to use i2c on Nvidia boards" #endif i2c_init_board(); # ifdef CONFIG_TEGRA_PMU if (pmu_set_nominal()) debug("Failed to select nominal voltages\n"); # ifdef CONFIG_TEGRA_CLOCK_SCALING err = board_emc_init(); if (err) debug("Memory controller init failed: %d\n", err); # endif # endif /* CONFIG_TEGRA_PMU */ #endif /* CONFIG_SYS_I2C_TEGRA */ #ifdef CONFIG_USB_EHCI_TEGRA pin_mux_usb(); usb_process_devicetree(gd->fdt_blob); #endif #ifdef CONFIG_LCD tegra_lcd_check_next_stage(gd->fdt_blob, 0); #endif #ifdef CONFIG_TEGRA_NAND pin_mux_nand(); #endif #ifdef CONFIG_TEGRA_LP0 /* save Sdram params to PMC 2, 4, and 24 for WB0 */ warmboot_save_sdram_params(); /* prepare the WB code to LP0 location */ warmboot_prepare_code(TEGRA_LP0_ADDR, TEGRA_LP0_SIZE); #endif return 0; }
/** * \brief Init the radio * \return Returns success/fail * \retval 0 Success */ int rf233_init(void) { volatile uint8_t regtemp; volatile uint8_t radio_state; /* don't optimize this away, it's important */ PRINTF("RF233: init.\n"); /* init SPI and GPIOs, wake up from sleep/power up. */ spi_init(); // RF233 expects line low for CS, this is default SAM4L behavior //spi_set_chip_select(3); // POL = 0 means idle is low spi_set_chip_select(3); spi_set_polarity(0); // PHASE = 0 means sample leading edge spi_set_phase(0); spi_set_rate(400000); /* reset will put us into TRX_OFF state */ /* reset the radio core */ gpio_enable_output(RST_PIN); gpio_enable_output(SLP_PIN); gpio_clear(RST_PIN); delay_ms(1); gpio_set(RST_PIN); gpio_clear(SLP_PIN); /* be awake from sleep*/ /* Read the PART_NUM register to verify that the radio is * working/responding. Could check in software, I just look at * the bus. If this is working, the first write should be 0x9C x00 * and the return bytes should be 0x00 0x0B. - pal*/ regtemp = trx_reg_read(RF233_REG_PART_NUM); /* before enabling interrupts, make sure we have cleared IRQ status */ regtemp = trx_reg_read(RF233_REG_IRQ_STATUS); PRINTF("RF233: After wake from sleep\n"); radio_state = rf233_status(); PRINTF("RF233: Radio state 0x%04x\n", radio_state); calibrate_filters(); if (radio_state == STATE_P_ON) { trx_reg_write(RF233_REG_TRX_STATE, TRXCMD_TRX_OFF); } /* Assign regtemp to regtemp to avoid compiler warnings */ regtemp = regtemp; // Set up interrupts gpio_interrupt_callback(interrupt_callback, NULL); gpio_enable_input(RADIO_IRQ, PullNone); gpio_clear(RADIO_IRQ); gpio_enable_interrupt(RADIO_IRQ, PullNone, RisingEdge); /* Configure the radio using the default values except these. */ trx_reg_write(RF233_REG_TRX_CTRL_1, RF233_REG_TRX_CTRL_1_CONF); trx_reg_write(RF233_REG_PHY_CC_CCA, RF233_REG_PHY_CC_CCA_CONF); trx_reg_write(RF233_REG_PHY_TX_PWR, RF233_REG_PHY_TX_PWR_CONF); trx_reg_write(RF233_REG_TRX_CTRL_2, RF233_REG_TRX_CTRL_2_CONF); trx_reg_write(RF233_REG_IRQ_MASK, RF233_REG_IRQ_MASK_CONF); trx_reg_write(RF233_REG_XAH_CTRL_1, 0x02); trx_bit_write(SR_MAX_FRAME_RETRIES, 0); trx_bit_write(SR_MAX_CSMA_RETRIES, 0); PRINTF("RF233: Configured transciever.\n"); { uint8_t addr[8]; addr[0] = 0x22; addr[1] = 0x22; addr[2] = 0x22; addr[3] = 0x22; addr[4] = 0x22; addr[5] = 0x22; addr[6] = 0x22; addr[7] = 0x22; SetPanId(IEEE802154_CONF_PANID); SetIEEEAddr(addr); SetShortAddr(0x2222); } rf_generate_random_seed(); for (uint8_t i = 0; i < 8; i++) { regtemp = trx_reg_read(0x24 + i); } /* 11_09_rel */ trx_reg_write(RF233_REG_TRX_RPC, 0xFF); /* Enable RPC feature by default */ PRINTF("RF233: Installed addresses. Turning on radio."); rf233_on(); return 0; }
const mp_obj_module_t *py_spi_init() { /* Init spi */ spi_init(); return &py_spi_module; }
void board_init_r(gd_t *id, ulong dest_addr) { #ifndef CONFIG_SYS_NO_FLASH ulong size; #endif bd_t *bd; gd = id; gd->flags |= GD_FLG_RELOC; /* tell others: relocation done */ debug("Now running in RAM - U-Boot at: %08lx\n", dest_addr); gd->reloc_off = dest_addr - CONFIG_SYS_MONITOR_BASE; monitor_flash_len = image_copy_end() - dest_addr; serial_initialize(); bd = gd->bd; /* The Malloc area is immediately below the monitor copy in DRAM */ mem_malloc_init(CONFIG_SYS_MONITOR_BASE + gd->reloc_off - TOTAL_MALLOC_LEN, TOTAL_MALLOC_LEN); #if defined(CONFIG_STATUS_LED) && defined(STATUS_LED_BOOT) status_led_set(STATUS_LED_BOOT, STATUS_LED_STATE); #endif #ifndef CONFIG_SYS_NO_FLASH /* configure available FLASH banks */ size = flash_init(); display_flash_config(size); bd->bi_flashstart = CONFIG_SYS_FLASH_BASE; bd->bi_flashsize = size; #if CONFIG_SYS_MONITOR_BASE == CONFIG_SYS_FLASH_BASE bd->bi_flashoffset = monitor_flash_len; /* reserved area for U-Boot */ #else bd->bi_flashoffset = 0; #endif #else bd->bi_flashstart = 0; bd->bi_flashsize = 0; bd->bi_flashoffset = 0; #endif #ifdef CONFIG_CMD_NAND puts("NAND: "); nand_init(); /* go init the NAND */ #endif #if defined(CONFIG_CMD_ONENAND) onenand_init(); #endif #ifdef CONFIG_GENERIC_MMC puts("MMC: "); mmc_initialize(gd->bd); #endif /* relocate environment function pointers etc. */ env_relocate(); #if defined(CONFIG_PCI) /* * Do pci configuration */ pci_init(); #endif /** leave this here (after malloc(), environment and PCI are working) **/ /* Initialize stdio devices */ stdio_init(); jumptable_init(); /* Initialize the console (after the relocation and devices init) */ console_init_r(); /** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **/ /* Initialize from environment */ load_addr = getenv_ulong("loadaddr", 16, load_addr); #ifdef CONFIG_CMD_SPI puts("SPI: "); spi_init(); /* go init the SPI */ puts("ready\n"); #endif #if defined(CONFIG_MISC_INIT_R) /* miscellaneous platform dependent initialisations */ misc_init_r(); #endif #ifdef CONFIG_BITBANGMII bb_miiphy_init(); #endif #if defined(CONFIG_CMD_NET) puts("Net: "); eth_initialize(gd->bd); #endif /* main_loop() can return to retry autoboot, if so just run it again. */ for (;;) main_loop(); /* NOTREACHED - no way out of command loop except booting */ }
int wishbone_init(void){ if(fd == 0){ spi_init(); } return 0 ; }
void board_init() { uint16_t i,j; //enable all port clocks. SIM_SCGC5 |= (SIM_SCGC5_PORTA_MASK | SIM_SCGC5_PORTB_MASK | SIM_SCGC5_PORTC_MASK | SIM_SCGC5_PORTD_MASK | SIM_SCGC5_PORTE_MASK ); //init all pins for the radio //SLPTR #ifdef TOWER_K20 PORTB_PCR3 = PORT_PCR_MUX(1);// -- PTB3 used as gpio for slptr GPIOB_PDDR |= RADIO_SLPTR_MASK; //set as output //RADIO RST -- TODO in the TWR change it to another pin! this is one of the leds. PORTC_PCR9 = PORT_PCR_MUX(1);// -- PTC9 used as gpio for radio rst GPIOC_PDDR |= RADIO_RST_MASK; //set as output #elif OPENMOTE_K20 PORTD_PCR4 = PORT_PCR_MUX(1);// -- PTD4 used as gpio for slptr GPIOD_PDDR |= RADIO_SLPTR_MASK; //set as output //RADIO RST PORTD_PCR5 = PORT_PCR_MUX(1);// -- PTD5 used as gpio for radio rst GPIOD_PDDR |= RADIO_RST_MASK; //set as output #endif PORT_PIN_RADIO_RESET_LOW();//activate the radio. PORT_PIN_RADIO_SLP_TR_CNTL_LOW(); //ptc5 .. ptc5 is pin 62, irq A enable_irq(RADIO_EXTERNAL_PORT_IRQ_NUM);//enable the irq. The function is mapped to the vector at position 105 (see manual page 69). The vector is in isr.h //external port radio_isr. PORTC_PCR5 = PORT_PCR_MUX(1);// -- PTC5 used as gpio for radio isr through llwu GPIOC_PDDR &= ~1<<RADIO_ISR_PIN; //set as input ==0 PORTC_PCR5 |= PORT_PCR_IRQC(0x09); //9 interrupt on raising edge. page 249 of the manual. PORTC_PCR5 |= PORT_PCR_ISF_MASK; //clear any pending interrupt. llwu_init();//low leakage unit init - to recover from deep sleep debugpins_init(); leds_init(); bsp_timer_init(); uart_init(); radiotimer_init(); spi_init(); radio_init(); leds_all_off(); leds_sync_on(); leds_radio_on(); leds_debug_on(); leds_error_on(); leds_all_off(); debugpins_fsm_clr(); }
int main(int argc,char **argv) { int i; HW_VGA(FRAMEBUFFERPTR)=0x00000; puts("Initializing SD card\n"); if(spi_init()) { puts("Hunting for partition\n"); FindDrive(); if(LoadFile("MANIFESTMST",Manifest)) { unsigned char *buffer=Manifest; int ptr; puts("Parsing manifest\n"); while(1) { unsigned char c=0; ptr=0; // Parse address while((c=*buffer++)!=' ') { HW_UART(REG_UART)=c; if(c=='#') // Comment line? break; if(c=='G') _boot(); if(c=='\n') _break(); // Halt CPU if(c=='L') buffer=Manifest; c=(c&~32)-('0'-32); // Convert to upper case if(c>='9') c-='A'-'0'; ptr<<=4; ptr|=c; } // Parse filename if(c!='#') { int i; while((c=*buffer++)==' ') ; --buffer; // c-1 is now the filename pointer // printf("Loading file %s to %d\n",fn,(long)ptr); // buffer[11]=0; LoadFile(buffer,(unsigned char *)ptr); HW_VGA(FRAMEBUFFERPTR)=ptr; } // Hunt for newline character while((c=*buffer++)!='\n') ; } } else { puts("Loading manifest failed\n"); } } puts("Returning\n"); return(0); }