int main() { // when working with the watchdog timer, it is important that your // program's first action is to clear the MCUSR register // (this is accomplished by calling clear_reset_flags()) and disable // the watchdog timer. If the watchdog timer ever resets your program, // the watchdog timer defaults to enabled with the shortest possible // period (15 ms), which can lead to repeated resets if your program // does not initially clear MCUSR and disable the watchdog timer. unsigned char rf = get_reset_flags(); clear_reset_flags(); wdt_disable(); clear(); print("boot"); unsigned char i; for (i = 0; i < 4; i++) { delay_ms(150); print("."); } delay_ms(300); wdt_enable(WDTO_2S); // enable watchdog timer with 2 sec period while (1) { clear(); // clear LCD // display last reset source on the LCD if (rf & WATCHDOG_RESET) print("WATCHDOG"); else if (rf & BROWNOUT_RESET) print("BROWNOUT"); else if (rf & EXTERNAL_RESET) print("EXTERNAL"); else if (rf & POWERON_RESET) print("POWER-ON "); else print("none"); while (1) { lcd_goto_xy(0, 1); // go to start of second LCD row print(" BUTTON "); wdt_reset(); // reset the watchdog timer unsigned long time = get_ms(); while (button_is_pressed(ANY_BUTTON)) { // We loop here while button is held down and DO NOT // reset the watchdog timer. // Display a four-second countdown until WDT resets us. int wdt_ms = 2000 - (int)(get_ms() - time); lcd_goto_xy(0, 1); // go to start of second LCD row print("WD "); if (wdt_ms < 0) print("0.00s"); else { print_long(wdt_ms / 1000); // seconds print("."); print_long((wdt_ms/100)%10); // tenths of seconds print_long((wdt_ms/10)%10); // hundredths of seconds print("s"); } } } } }
/*************************************************************************** Declaration : int main(void) Function : Main Loop ***************************************************************************/ int main(void) { init_mcu(); init_rf(); init_buffer(); init_protocol(); init_freq(); #ifdef TEST_TX_CW test_rf_transmitter(78); #endif #ifdef TEST_TX_MOD test_rf_modulator(81); #endif #ifdef TEST_RX test_rf_receiver(78); #endif /* Main Background loop */ call_state = CALL_IDLE; while(1) { /* Call States */ switch (call_state) { case CALL_IDLE: #ifdef DONGLE sleep(WDT_TIMEOUT_60MS,STANDBY_MODE); call_status = CALL_NO_ACTIVITY; #ifdef USB SET_VOLUME_DOWN; SET_VOLUME_UP; SET_MUTE_PLAY; SET_MUTE_REC; if(CALL_ACTIVITY_PIN) call_status = CALL_ACTIVITY; #else if(!CALL_SETUP_KEY) call_status = CALL_ACTIVITY; #endif if(call_status == CALL_ACTIVITY) call_state = CALL_SETUP; #endif #ifdef HEADSET sleep(WDT_TIMEOUT_1S,POWER_DOWN_MODE); call_state = CALL_SETUP; #endif break; case CALL_SETUP: #ifdef DONGLE LED_ON; call_status = call_setup(&setup_freq[0],N_FREQ_SETUP); LED_OFF; if(call_status != CALL_SETUP_FAILURE) { init_buffer(); init_rf(); init_protocol(); init_codec(); start_codec(); #ifdef USB // Enable watchdog to handle USB Suspend Mode wdt_enable(WDT_TIMEOUT_15MS); #else start_timer1(0,FRAME_PERIOD, DIV1); #endif call_state = CALL_CONNECTED; } else call_state = CALL_IDLE; #endif #ifdef HEADSET LED_ON; call_status = call_detect(&setup_freq[0],N_FREQ_SETUP,N_REP_SETUP); LED_OFF; if(call_status != CALL_SETUP_FAILURE) { init_buffer(); init_rf(); init_protocol(); init_codec(); call_status &= ~MASTER_SYNC; start_timer1(0,FRAME_PERIOD, DIV1); call_state = CALL_CONNECTED; } else call_state = CALL_IDLE; #endif break; case CALL_CONNECTED: #ifdef DONGLE while(1) { // USB Dongle clears watchdog handling USB Suspend Mode #ifdef USB wdt_reset(); #endif // Send and receive audio packet audio_transfer(); // Handle key code from HEADSET key_code = (signal_in[1] & 0x1F); if(key_code != 0) LED_ON; else LED_OFF; #ifdef USB if(key_code & VOLUME_DOWN) CLEAR_VOLUME_DOWN; else SET_VOLUME_DOWN; if(key_code & VOLUME_UP) CLEAR_VOLUME_UP; else SET_VOLUME_UP; if(key_code & MUTE_PLAY) CLEAR_MUTE_PLAY; else SET_MUTE_PLAY; if(key_code & MUTE_REC) CLEAR_MUTE_REC; else SET_MUTE_REC; #endif // Check if call is to be cleared #ifdef USB if(!CALL_ACTIVITY_PIN) { call_activity_timer += 1; if(call_activity_timer >= TIMEOUT_CALL_ACTIVITY) call_status = CALL_CLEAR; } else call_activity_timer = 0; #else if(!CALL_CLEAR_KEY) call_status = CALL_CLEAR; #endif // Call clearing by HEADSET or DONGLE if((key_code == CALL_CLEARING) || (call_status == CALL_CLEAR)) { signal_out[0] |= SIGNAL_CALL_CLEAR; call_timer += 1; if(call_timer >= TIMEOUT_CALL_CLEAR_MASTER) { call_state = CALL_IDLE; stop_codec(); init_buffer(); init_rf(); init_protocol(); init_codec(); eeprom_write(freq[0],EEPROM_ADR_FREQ0); eeprom_write(freq[1],EEPROM_ADR_FREQ1); LED_OFF; #ifdef USB // Disable watchdog used to handle USB Suspend Mode wdt_disable(); #endif break; } } else signal_out[0] &= ~SIGNAL_CALL_CLEAR; // Call clearing due to Frame Loss if(frame_loss >= TIMEOUT_FRAME_LOSS) { #ifdef USB call_state = CALL_RECONNECT; init_rf(); init_protocol(); // Disable watchdog used to handle USB Suspend Mode wdt_disable(); #else call_state = CALL_RECONNECT; stop_codec(); init_buffer(); init_rf(); init_protocol(); init_codec(); #endif break; } } #endif #ifdef HEADSET while(1) { if(call_status & MASTER_SYNC) { audio_transfer(); } else { call_status = get_sync(); if(call_status & MASTER_SYNC) start_codec(); else frame_loss += 10; } // Read and handle keys key_code = read_key(); signal_out[1] &= 0xE0; signal_out[1] |= key_code; // Call cleared by DONGLE if(signal_in[0] & SIGNAL_CALL_CLEAR) { call_timer += 1; if(call_timer >= TIMEOUT_CALL_CLEAR_SLAVE) { call_state = CALL_IDLE; stop_codec(); init_buffer(); init_rf(); init_protocol(); init_codec(); break; } } else call_timer = 0; // Call clearing due to Frame Loss if(frame_loss >= TIMEOUT_FRAME_LOSS) { call_state = CALL_RECONNECT; stop_codec(); init_buffer(); init_rf(); init_protocol(); init_codec(); break; } } #endif break; case CALL_RECONNECT: #ifdef DONGLE LED_ON; call_status = call_setup(&setup_freq[0],N_FREQ_SETUP); LED_OFF; if(call_status != CALL_SETUP_FAILURE) { #ifdef USB init_rf(); init_protocol(); reset_codec(); call_state = CALL_CONNECTED; #else init_buffer(); init_rf(); init_protocol(); init_codec(); start_codec(); start_timer1(0,FRAME_PERIOD, DIV1); call_state = CALL_CONNECTED; #endif } else { stop_codec(); init_buffer(); init_rf(); init_protocol(); init_codec(); call_state = CALL_IDLE; } #endif #ifdef HEADSET LED_ON; call_status = call_detect(&setup_freq[0],N_FREQ_SETUP,N_REP_RECONNECT); LED_OFF; if(call_status != CALL_SETUP_FAILURE) { init_buffer(); init_rf(); init_protocol(); init_codec(); call_status &= ~MASTER_SYNC; start_timer1(0,FRAME_PERIOD, DIV1); call_state = CALL_CONNECTED; } else call_state = CALL_IDLE; #endif break; default: break; } } }
void reset_system() { cli(); wdt_enable(WDTO_1S); while(1); }
_start(void) { /* * Make sure interrupts are disabled. */ __disable_irq(); /* * Depending on the config parameter, enable or disable the WDT. */ #if !defined(CONFIG_HW_WATCHDOG) #if !defined(CONFIG_SYS_M2S) wdt_disable(); #endif #else wdt_enable(); #endif #ifdef CONFIG_LPC18XX_NORFLASH_BOOTSTRAP_WORKAROUND /* * Reload the whole U-Boot image from SPIFI. * *** The Boot ROM on LPC4350 parts cannot load more than 32KBytes * from NOR flash when booting.*** * * Boot from SPIFI only */ // lpc18xx_bootstrap_from_spifi(); #endif /* CONFIG_LPC18XX_NORFLASH_BOOTSTRAP_WORKAROUND */ // // Copy sections from Flash // unsigned int LoadAddr, ExeAddr, SectionLen, loop; unsigned int *SectionTableAddr; // Load base address of Global Section Table SectionTableAddr = &__section_table_start; // Copy the text,image_top and data sections from flash to SRAM and RAM. while (SectionTableAddr < &__section_table_end) { LoadAddr = *SectionTableAddr++; ExeAddr = *SectionTableAddr++; SectionLen = *SectionTableAddr++; unsigned int *pulDest = (unsigned int*) ExeAddr; unsigned int *pulSrc = (unsigned int*) LoadAddr; for (loop = 0; loop < SectionLen; loop = loop + 4) *pulDest++ = *pulSrc++; } unsigned int *pulDest = (unsigned int*) &_bss_start; for (loop = 0; loop < (&_bss_end - &_bss_start); loop = loop + 4) *pulDest++ = 0; /* * In U-boot (armboot) lingvo, "go to the C code" - * in fact, with M3, we are at the C code from the very beginning. * In actuality, this is the jump to the ARM generic start code. * ... * Note initialization of _armboot_start below. The ARM generic * code expects that this variable is set to the upper boundary of * the malloc pool area. * For Cortex-M3, where we do not relocate the code to RAM, I set * the malloc pool right behind the stack. See how armboot_start * is defined in the CPU specific .lds file. */ // Clear all pending interrupts in the NVIC volatile unsigned int *NVIC_ICPR = (unsigned int *) 0xE000E280; unsigned int irqpendloop; for (irqpendloop = 0; irqpendloop < 8; irqpendloop++) { *(NVIC_ICPR+irqpendloop)= 0xFFFFFFFF; } #ifdef CONFIG_LPC18XX_USB // Reenable interrupts __enable_irq(); #endif // ****************************** // Check to see if we are running the code from a non-zero // address (eg RAM, external flash), in which case we need // to modify the VTOR register to tell the CPU that the // vector table is located at a non-0x0 address. unsigned int * pSCB_VTOR = (unsigned int *) 0xE000ED08; if ((unsigned int *)vectors!=(unsigned int *) 0x00000000) { // CMSIS : SCB->VTOR = <address of vector table> *pSCB_VTOR = (unsigned int)vectors; } _armboot_start = (unsigned long)&_mem_stack_base; start_armboot(); }
/** Master V2 Protocol packet handler, for received V2 Protocol packets from a connected host. * This routine decodes the issued command and passes off the handling of the command to the * appropriate function. */ void V2Protocol_ProcessCommand(void) { uint8_t V2Command = Endpoint_Read_8(); /* Start the watchdog with timeout interrupt enabled to manage the timeout */ TimeoutExpired = false; wdt_enable(WDTO_1S); WDTCSR |= (1 << WDIE); switch (V2Command) { case CMD_SIGN_ON: V2Protocol_SignOn(); break; case CMD_SET_PARAMETER: case CMD_GET_PARAMETER: V2Protocol_GetSetParam(V2Command); break; case CMD_LOAD_ADDRESS: V2Protocol_LoadAddress(); break; case CMD_RESET_PROTECTION: V2Protocol_ResetProtection(); break; #if defined(ENABLE_ISP_PROTOCOL) case CMD_ENTER_PROGMODE_ISP: ISPProtocol_EnterISPMode(); break; case CMD_LEAVE_PROGMODE_ISP: ISPProtocol_LeaveISPMode(); break; case CMD_PROGRAM_FLASH_ISP: case CMD_PROGRAM_EEPROM_ISP: ISPProtocol_ProgramMemory(V2Command); break; case CMD_READ_FLASH_ISP: case CMD_READ_EEPROM_ISP: ISPProtocol_ReadMemory(V2Command); break; case CMD_CHIP_ERASE_ISP: ISPProtocol_ChipErase(); break; case CMD_READ_FUSE_ISP: case CMD_READ_LOCK_ISP: case CMD_READ_SIGNATURE_ISP: case CMD_READ_OSCCAL_ISP: ISPProtocol_ReadFuseLockSigOSCCAL(V2Command); break; case CMD_PROGRAM_FUSE_ISP: case CMD_PROGRAM_LOCK_ISP: ISPProtocol_WriteFuseLock(V2Command); break; case CMD_SPI_MULTI: ISPProtocol_SPIMulti(); break; #endif #if defined(ENABLE_XPROG_PROTOCOL) case CMD_XPROG_SETMODE: XPROGProtocol_SetMode(); break; case CMD_XPROG: XPROGProtocol_Command(); break; #endif default: V2Protocol_UnknownCommand(V2Command); break; } /* Disable the timeout management watchdog timer */ wdt_disable(); Endpoint_WaitUntilReady(); Endpoint_SelectEndpoint(AVRISP_DATA_OUT_EPNUM); Endpoint_SetEndpointDirection(ENDPOINT_DIR_OUT); }
void forceReset() { StatusBlink(3); wdt_enable(WDTO_15MS); for(;;) ; }
void WDT_init(uint8_t val){ wdt_enable(val); }
/* * Setup */ void setup() { wdt_enable(WDTO_8S); wdt_reset(); //Setup Ports Serial.begin(115200); //Start Debug Serial 0 Serial1.begin(9600); //Start GPS Serial 1 Serial2.begin(9600); pinMode(PIN_LED_GREEN, OUTPUT); //Blue GREEN pinMode(PIN_LED_RED, OUTPUT); //Blue RED pinMode(PIN_LED_BLUE, OUTPUT); //Blue LED pinMode(PIN_SPI_CS,OUTPUT); //Chip Select Pin for the SD Card pinMode(10, OUTPUT); //SDcard library expect 10 to set set as output. // Initialise the GPS wdt_disable(); gps.init(); gps.configureUbloxSettings(); // Configure Ublox for MY_HIGH altitude mode wdt_enable(WDTO_8S); // join I2C bus //start I2C transfer to the Module/Transmitter Wire.begin(); //Set up the two EasyTransfer methods ETI2Cout.begin(details(mD.i2cOut), &Wire); //setup the data structure to transfer out ETSerialIn.begin(details(vals), &Serial2); //Start up the LGgyro if (LGgyro.init()) { #ifdef DEBUG_ON Serial.println("LGgyro OK"); #endif LGgyro.enableDefault(); } else { #ifdef DEBUG_ON Serial.println("LGgyro not working"); #endif SET_LED_Status(SET_LED_WHITE,500); //White LED SET_LED_Status(SET_LED_RED,1000); //Red LED } //Start up the accelerometer accel = ADXL345(); // Create an instance of the accelerometer if(accel.EnsureConnected()) { // Check that the accelerometer is connected. #ifdef DEBUG_ON Serial.println("Connected to ADXL345."); #endif accel.SetRange(2, true); // Set the range of the accelerometer to a maximum of 2G. accel.EnableMeasurements(); // Tell the accelerometer to start taking measurements. } else{ #ifdef DEBUG_ON Serial.println("Could not connect to ADXL345."); #endif SET_LED_Status(SET_LED_WHITE,500); //White LED SET_LED_Status(SET_LED_RED,2000); //Red LED } //Start up the compass compass = HMC5883L(); // Construct a new HMC5883 compass. #ifdef DEBUG_ON if(compass.EnsureConnected() == 1) { Serial.println("Connected to HMC5883L."); } else { Serial.println("Not Connected to HMC5883L."); } #endif error = compass.SetScale(1.3); // Set the scale of the compass. #ifdef DEBUG_ON if(error != 0) { // If there is an error, print it out. Serial.println("Compass Error 1"); Serial.println(compass.GetErrorText(error)); } else { Serial.println("Compass Ok 1"); } #endif error = compass.SetMeasurementMode(Measurement_Continuous); // Set the measurement mode to Continuous #ifdef DEBUG_ON if(error != 0) { // If there is an error, print it out. Serial.println("Compass error 2"); Serial.println(compass.GetErrorText(error)); } else { Serial.println("Compass Ok 2"); } #endif //Start up the Pressure Sensor dps = BMP085(); dps.init(); #ifdef DEBUG_ON Serial.print("BMP Mode "); Serial.println(dps.getMode()); #endif wdt_reset(); // Start up the OneWire Sensors library and turn off blocking takes too long! sensors.begin(); sensors.setWaitForConversion(false); sensors.requestTemperaturesByAddress(outsideThermometer); // Send the command to get temperature //Initialise all of the record values mD.vals.tCount = 0; mD.vals.uslCount = 0; mD.vals.year = 0; mD.vals.month = 0; mD.vals.day = 0; mD.vals.hour = 0; mD.vals.minute = 0; mD.vals.second = 0; mD.vals.hundredths = 0; mD.vals.iLat = 0; mD.vals.iLong = 0; mD.vals.iAlt = 0; mD.vals.bSats = 0; mD.vals.iAngle = 0; mD.vals.iHspeed = 0; mD.vals.iVspeed = 0; mD.vals.age = 0; mD.vals.ihdop = 0; mD.vals.AcXPayload = 0; mD.vals.AcYPayload = 0; mD.vals.AcZPayload = 0; mD.vals.GyXPayload = 0; mD.vals.GyYPayload = 0; mD.vals.GyZPayload = 0; mD.vals.MgXPayload = 0; mD.vals.MgYPayload = 0; mD.vals.MgZPayload = 0; mD.vals.TmpPayload = 0; //Connect to the SD Card if(!SD.begin(PIN_SPI_CS, SPI_HALF_SPEED)) { #ifdef DEBUG_ON Serial.println("SD not working!!"); #endif SET_LED_Status(SET_LED_WHITE,500); //White LED SET_LED_Status(SET_LED_RED,3000); //Red LED } else { #ifdef DEBUG_ON Serial.println("SD OK"); #endif dataFile.open(SD_LOG_FILE, O_CREAT | O_WRITE | O_APPEND); //Open Logfile if (!dataFile.isOpen()) { #ifdef DEBUG_ON Serial.println("SD Data File Not Opened"); #endif SET_LED_Status(SET_LED_WHITE,500); SET_LED_Status(SET_LED_RED,3000); } } //Cycle lights SET_LED_Status(SET_LED_OFF,0); SET_LED_Status(SET_LED_RED,500); SET_LED_Status(SET_LED_GREEN,500); SET_LED_Status(SET_LED_BLUE,500); SET_LED_Status(SET_LED_OFF,0); elapseSIM900 = millis(); //Elapse counter for data to SIM900 elapseNTXB = millis(); //Elapse counter for data to NTXB NEWGPSDATA = false; wdt_enable(WDTO_2S); wdt_reset(); }
/*----------------------------------------------------------------------------- * Verarbeitung der Bustelegramme */ static void ProcessBus(UINT8 ret) { TBusMsgType msgType; UINT16 *pData; UINT16 wordAddr; BOOL rc; if ((ret == BUS_MSG_OK) && (spRxBusMsg->msg.devBus.receiverAddr == MY_ADDR)) { msgType = spRxBusMsg->type; if (msgType == eBusDevReqReboot) { /* Über Watchdog Reset auslösen */ /* Watchdogtimeout auf kurzeste Zeit (14 ms) stellen */ cli(); wdt_enable(WDTO_15MS); /* warten auf Reset */ while (1); } else { switch (sFwuState) { case WAIT_FOR_UPD_ENTER_TIMEOUT: case WAIT_FOR_UPD_ENTER: if (msgType == eBusDevReqUpdEnter) { /* Applicationbereich des Flash löschen */ FlashErase(); /* Antwort senden */ SetMsg(eBusDevRespUpdEnter, spRxBusMsg->senderAddr); BusSend(&sTxBusMsg); sFwuState = WAIT_FOR_UPD_DATA; } break; case WAIT_FOR_UPD_DATA: if (msgType == eBusDevReqUpdData) { wordAddr = spRxBusMsg->msg.devBus.x.devReq.updData.wordAddr; pData = spRxBusMsg->msg.devBus.x.devReq.updData.data; /* Flash programmieren */ rc = FlashProgram(wordAddr, pData, sizeof(spRxBusMsg->msg.devBus.x.devReq.updData.data) / 2); /* Antwort senden */ SetMsg(eBusDevRespUpdData, spRxBusMsg->senderAddr); if (rc == TRUE) { /* Falls Programmierung des Block OK: empfangene wordAddr zurücksenden */ sTxBusMsg.msg.devBus.x.devResp.updData.wordAddr = wordAddr; } else { /* Problem bei Programmierung: -1 als wordAddr zurücksenden */ sTxBusMsg.msg.devBus.x.devResp.updData.wordAddr = -1; } BusSend(&sTxBusMsg); } else if (msgType == eBusDevReqUpdTerm) { /* programmiervorgang im Flash abschließen (falls erforderlich) */ rc = FlashProgramTerminate(); /* Antwort senden */ SetMsg(eBusDevRespUpdTerm, spRxBusMsg->senderAddr); if (rc == TRUE) { /* Falls Programmierung OK: success auf 1 setzen */ sTxBusMsg.msg.devBus.x.devResp.updTerm.success = 1; } else { /* Problem bei Programmierung: -1 als wordAddr zurücksenden */ sTxBusMsg.msg.devBus.x.devResp.updTerm.success = 0; } BusSend(&sTxBusMsg); } break; default: break; } } } }
static int __devinit hisik3_wdt_probe(struct platform_device *pdev) { int ret = 0; struct resource *res; res = platform_get_resource(pdev, IORESOURCE_MEM, 0); if (!res) { ret = -ENOENT; dev_warn(&pdev->dev, "WDT memory resource not defined\n"); goto err; } if (!request_mem_region(res->start, resource_size(res), pdev->name)) { dev_warn(&pdev->dev, "WDT failed to get memory region resource\n"); ret = -ENOENT; goto err; } wdt = kzalloc(sizeof(*wdt), GFP_KERNEL); if (!wdt) { dev_warn(&pdev->dev, "WDT kzalloc failed\n"); ret = -ENOMEM; goto err_kzalloc; } wdt->clk = clk_get(NULL,"clk_wd"); if (IS_ERR(wdt->clk)) { dev_warn(&pdev->dev, "WDT clock not found\n"); ret = PTR_ERR(wdt->clk); goto err_clk_get; } wdt->base = ioremap(res->start, resource_size(res)); if (!wdt->base) { ret = -ENOMEM; dev_warn(&pdev->dev, "WDT ioremap fail\n"); goto err_ioremap; } spin_lock_init(&wdt->lock); /* This checks if system booted after watchdog reset or not */ ret = clk_enable(wdt->clk); if (ret) { dev_warn(&pdev->dev, "clock enable fail"); goto err_clk_enable; } wdt->pdev = pdev; wdt_default_init(DEFAULT_TIMEOUT); wdt_default_config(); INIT_DELAYED_WORK(&wdt->k3_wdt_delayed_work, wdt_mond); schedule_delayed_work(&wdt->k3_wdt_delayed_work, 0); ret = misc_register(&hisik3_wdt_miscdev); if (ret < 0) { dev_warn(&pdev->dev, "WDT cannot register misc device\n"); goto err_misc_register; } wdt_enable(); dev_warn(&pdev->dev,"WDT probing has been finished\n"); return 0; err_misc_register: clk_disable(wdt->clk); err_clk_enable: iounmap(wdt->base); err_ioremap: clk_put(wdt->clk); err_clk_get: kfree(wdt); wdt = NULL; err_kzalloc: release_mem_region(res->start, resource_size(res)); err: dev_warn(&pdev->dev, "WDT probe failed!!!\n"); return ret; }
int main (void) { En_RC32M(); PORT_init(); TimerD0_init(); PMIC_CTRL |=PMIC_LOLVLEN_bm|PMIC_MEDLVLEN_bm; wdt_enable(); USART_R_init(); USART_L_init(); USARTD0_init(); NRF24L01_L_CE_LOW; //disable transceiver modes NRF24L01_R_CE_LOW; ///////////////////////////////////////////////////////////////////////////////////////////spi se spi_xmega_set_baud_div(&NRF24L01_L_SPI,8000000UL,F_CPU); spi_enable_master_mode(&NRF24L01_L_SPI); spi_enable(&NRF24L01_L_SPI); spi_xmega_set_baud_div(&NRF24L01_R_SPI,8000000UL,F_CPU); spi_enable_master_mode(&NRF24L01_R_SPI); spi_enable(&NRF24L01_R_SPI); sei(); ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// _delay_us(10); _delay_ms(100); //power on reset delay needs 100ms NRF24L01_L_Clear_Interrupts(); NRF24L01_R_Clear_Interrupts(); NRF24L01_L_Flush_TX(); NRF24L01_R_Flush_TX(); NRF24L01_L_Flush_RX(); NRF24L01_R_Flush_RX(); NRF24L01_L_CE_LOW; NRF24L01_L_Init_milad(_RX_MODE, _CH_L, _2Mbps, Address, _Address_Width, _Buffer_Size, RF_PWR_MAX); NRF24L01_L_WriteReg(W_REGISTER | DYNPD,0x07);//0x07 NRF24L01_L_WriteReg(W_REGISTER | FEATURE,0x06);//0x06 NRF24L01_L_CE_HIGH; NRF24L01_R_CE_LOW; NRF24L01_R_Init_milad(_RX_MODE, _CH_R, _2Mbps, Address, _Address_Width, _Buffer_Size, RF_PWR_MAX); NRF24L01_R_WriteReg(W_REGISTER | DYNPD,0x07); NRF24L01_R_WriteReg(W_REGISTER | FEATURE,0x06); NRF24L01_R_CE_HIGH; _delay_us(130); for (uint8_t i=0;i<Max_Robot;i++) { Robot_D_tmp[i].RID=12; } while (1) { //Buf_Tx_R[7][7] = 0xFF; //Buf_Tx_R[7][8] = 0X01; for(uint8_t i=0;i<12;i++) { Buf_Tx_R[i][11] = Menu_Num; Buf_Tx_R[i][12] = (int)(kp*100); Buf_Tx_R[i][13] = (int)(ki*100); Buf_Tx_R[i][14] = (int)(kd*100); } _delay_us(1); } }
void resetArduino() { wdt_enable(WDTO_15MS); while(1); }
int main(void) { //uchar i; unsigned int i; uchar calibrationValue; calibrationValue = eeprom_read_byte(0); /* calibration value from last time */ if(calibrationValue != 0xff){ OSCCAL = calibrationValue; } //odDebugInit(); //Production Test Routine - Turn on both LEDs and an LED on the SparkFun Pogo Test Bed. DDRB |= 1 << WHITE_LED | 1 << YELLOW_LED | 1<<4; /* output for LED */ sbi(PORTB, WHITE_LED); for(i=0;i<20;i++){ /* 300 ms disconnect */ _delay_ms(15); } cbi(PORTB, WHITE_LED); sbi(PORTB, YELLOW_LED); for(i=0;i<20;i++){ /* 300 ms disconnect */ _delay_ms(15); } cbi(PORTB, YELLOW_LED); sbi(PORTB, 4); for(i=0;i<20;i++){ /* 300 ms disconnect */ _delay_ms(15); } cbi(PORTB, 4); DDRB &= ~(1<<4); //Initialize the USB Connection with the host computer. usbDeviceDisconnect(); for(i=0;i<20;i++){ /* 300 ms disconnect */ _delay_ms(15); } usbDeviceConnect(); wdt_enable(WDTO_1S); timerInit(); //Create a timer that will trigger a flag at a ~60hz rate adcInit(); //Setup the ADC conversions usbInit(); //Initialize USB comm. sei(); for(;;){ /* main event loop */ wdt_reset(); usbPoll(); //Check to see if it's time to send a USB packet if(usbInterruptIsReady() && nextDigit != NULL){ /* we can send another key */ buildReport(); //Get the next 'key press' to send to the host. usbSetInterrupt(reportBuffer, sizeof(reportBuffer)); if(*++nextDigit == 0xff) /* this was terminator character */ nextDigit = NULL; } timerPoll(); //Check timer to see if it's time to start another ADC conversion. adcPoll(); //If an ADC conversion was started, get the value and switch to the other ADC channel for the next conversion. } return 0; }
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 } }
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(); } } }
/** * Polls the serial communications (via coms_Poll) and takes * the apropriate action in response. * * @param runData The runData state of the program. This is * required so the record and livedata flags can be switched. */ void coms_Handle(RunData *runData) { ComsMsg msg = coms_Poll(); bool valid = true; int i; switch (msg.type) { case BAD: case NONE: //Ignore bad coms break; case OVERFLOW: //ignore - stub for debug break; case VERIFY: runData->record = false; runData->liveData = false; usart_Write(SERIAL, COMS_VERIFY_OUT); usart_Write(SERIAL, COMS_VERIFY_MAJOR_VERSION); usart_Write(SERIAL, COMS_VERIFY_MINOR_VERSION); break; case READ_FLASH: ; uint32_t addr = ((uint32_t)msg.msg[0] << 16) + ((uint32_t)msg.msg[1] << 8) + msg.msg[2]; uint32_t size = ((uint32_t)msg.msg[3] << 16) + ((uint32_t)msg.msg[4] << 8) + msg.msg[5]; runData->record = false; runData->liveData = false; sst_Read_To_Coms((char*)&addr, size); break; case WRITE_TIME: ; Time t; runData->record = false; runData->liveData = false; t.seconds = msg.msg[0]; t.minutes = msg.msg[1]; t.hours = msg.msg[2]; t.dow = msg.msg[3]; t.date = msg.msg[4]; t.month = msg.msg[5]; t.year = msg.msg[6]; rtc_Set_Time(&t); usart_Write(SERIAL, COMS_WRITE_TIME_OUT); break; case READ_CONFIG: runData->record = false; runData->liveData = false; usart_Write(SERIAL, data_Read_EEPROM((msg.msg[0] << 8) + msg.msg[1])); break; case WRITE_CONFIG: runData->record = false; runData->liveData = false; data_Write_EEPROM((msg.msg[0] << 8) + msg.msg[1], msg.msg[2]); usart_Write(SERIAL, COMS_WRITE_CONFIG_OUT); break; case LIVE_DATA: runData->record = false; runData->liveData = true; usart_Write(SERIAL, COMS_LIVE_DATA_OUT); break; case HEADER_REQ: ; uint32_t header = data_Cur_Addr(); usart_Write(SERIAL, ((char*)(&header))[2]); usart_Write(SERIAL, ((char*)(&header))[1]); usart_Write(SERIAL, ((char*)(&header))[0]); usart_Write(SERIAL, sizeof(DataPoint)); break; case RESET_REQ: for (i = 0; i < COMS_RESET_REQ_SIZE; i++) { if (msg.msg[i] != resetConfirmation[i]) { valid = false; } } if (valid) { wdt_enable(WDTO_120MS); } break; case ERASE_REQ: for (i = 0; i < COMS_RESET_REQ_SIZE; i++) { if (msg.msg[i] != resetConfirmation[i]) { valid = false; } } if (valid) { data_Clear(); } usart_Write(SERIAL, COMS_ERASE_REQ_OUT); break; case START_REQ: for (i = 0; i < COMS_RESET_REQ_SIZE; i++) { if (msg.msg[i] != resetConfirmation[i]) { valid = false; } } if (valid) { runData->record = true; runData->liveData = false; } usart_Write(SERIAL, COMS_START_REQ_OUT); break; } }
int main(void) { POWER_ON(); // Turn the regulator ON PWRMODE_SETUP(); // Setup PWRMODE jumper input lcd_init(); // init LCD uint8_t tmp; ADCSRA = (1<<ADEN) | (1<<ADPS1) | (1<<ADPS0); // Enable ADC, set Prescale to 8 unsigned int rhval = eeprom_read_word(&R_H_VAL); // R_H unsigned int rlval = eeprom_read_word(&R_L_VAL); // R_L ctmode = eeprom_read_byte(&CapTestMode); // Compile time choice of test modes (0x22) cp1 = (ctmode & 12) >> 2; // Capacitor pin 1, DEFAULT 0 cp2 = ctmode & 3; // Capacitor pin 2, DEFAULT 2 ctmode = (ctmode & 48) >> 4; // Capacitor test mode, DEFAULT is 0x02 for all 6 cap tests. wdt_disable(); // Disable watch dog timer. if(MCU_STATUS_REG & (1<<WDRF)) { // Examine for Watchdog RESETs That enters, if the Watchdog 2s were not put back Can occur, lcd_clear(); // if the program in a continuous loop " itself; tangled" has. lcd_eep_string(TestTimedOut); // Message - "Timeout!" _delay_ms(3000); // Wait 3 sec wdt_enable(WDTO_2S); // Wait two seconds; if on power it will reset; on battery it will turn itself off while(1) { POWER_OFF(); // Power down in BAT mode or RESET in PWR mode } } LCDLoadCustomChar(); // Custom indication Diode symbol into LCD load lcd_eep_string(DiodeIcon); // Message - diode icon Line1(); // jump to start of first line start: // re-entry point, if button is re-pressed #ifdef WDT_enabled wdt_enable(WDTO_2S); // Watchdog Timer on, 2 seconds? #endif PartFound = PART_NONE; // Default all results tmpPartFound = PART_NONE; // " " NumOfDiodes = 0; // || PartReady = 0; // || PartMode = 0; // || ca = 0; // || cb = 0; // \/ // -> // Startup Message //////////////////////////////////////// lcd_clear(); // lcd_eep_string(StartupMessage); // LCD: ACT v#.# [XXX] // -> // Power selection and Battery Testing //////////////////// if(PWRMODE_GET()) { // Get the PWRMODE jumper logic PowerMode = PWR_9V; // Set powermode to PWR_9V _delay_us(250); ReadADC(5 | (1<<REFS1)); // Measure the 9V battery Supply ( - diode drop) hfe[0] = ReadADC(5 | (1<<REFS1)); // if in battery mode. lcd_eep_string(BatMode); // Tell user device in BAT mode Line2(); if (hfe[0] < BAT_WEAK) { // Compare 9v reading with BAT_WEAK variable if(hfe[0] < BAT_DEAD) { // If the batter is considered dead then lcd_eep_string(Bat); lcd_eep_string(BatEmpty); // Tell the user battery is DEAD _delay_ms(3000); // Wait a bit. while(1) { // Forever loop POWER_OFF(); // keep trying to kill the power forever. } } lcd_clear(); lcd_eep_string(Bat); // Battery isnt dead; its just weak lcd_eep_string(BatWeak); // tell the user; but keep testing... Line2(); // Start second line } } else { PowerMode = PWR_5V; // Power mode is constent v5, skip battery check. lcd_eep_string(PwrMode); // Tell user we are running in PWR mode. Line2(); } // -> // Begin testing sequince. /////////////////////////////// lcd_eep_string(TestRunning); // Tell user the testing has begun... UpdateProgress("00%"); // Progress at 00% and Testing CheckPins(TP1, TP2, TP3); // || UpdateProgress("16%"); // \/ CheckPins(TP1, TP3, TP2); // TESTING... UpdateProgress("33%"); // CheckPins(TP2, TP1, TP3); // || UpdateProgress("50%"); // \/ CheckPins(TP2, TP3, TP1); // TESTING... UpdateProgress("66%"); // CheckPins(TP3, TP2, TP1); // || UpdateProgress("83%"); // \/ CheckPins(TP3, TP1, TP2); // Almost there! UpdateProgress("99%"); // Testing Completed or 99% //---------------------------------------------CAPACITOR--------------------------------------- // Separate measurement to the test on condenser if(((PartFound == PART_NONE) || (PartFound == PART_RESISTOR) || (PartFound == PART_DIODE)) && (ctmode > 0)) { // Condenser unload; otherwise possibly no measurement is possible R_PORT = 0; R_DDR = (1<<(TP1 * 2)) | (1<<(TP2 * 2)) | (1<<(TP3 * 2)); _delay_ms(10); R_DDR = 0; if(ctmode == NORMAL_CAP_TESTS) { // see if we want to do all 6 Cap Tests ReadCapacity(cp1, cp2); // No - just read the pins both ways. ReadCapacity(cp2, cp1); } else { // DEFAULT ctmode == 0x02 to do all tests Line2(); lcd_eep_string(TestCapV); UpdateProgress("00%"); ReadCapacity(TP3, TP1); UpdateProgress("16%"); ReadCapacity(TP3, TP2); UpdateProgress("33%"); ReadCapacity(TP2, TP3); UpdateProgress("50%"); ReadCapacity(TP2, TP1); UpdateProgress("66%"); ReadCapacity(TP1, TP3); UpdateProgress("83%"); ReadCapacity(TP1, TP2); UpdateProgress("99%"); } } lcd_clear(); // Finished, now evaluate, the results //---------------------------------------------DIODE------------------------------------------------ if(PartFound == PART_DIODE) { if(NumOfDiodes == 1) { // Standard-Diode lcd_eep_string(Diode); // Message - "Diode: " lcd_eep_string(Anode); // Message - "A=" lcd_data(GetPinAlias(diodes[0].Anode + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(NextK); // Message - ";C=" lcd_data(GetPinAlias(diodes[0].Cathode + ASCII_1)); // Display 1, 2, or 3 Line2(); // Start second line lcd_eep_string(Uf); // Message - "Uf=" lcd_string(itoa(diodes[0].Voltage, outval, 10)); lcd_eep_string(mV); // Message - "mV" goto end; } else if(NumOfDiodes == 2) { // dual diode if(diodes[0].Anode == diodes[1].Anode) { // Common Anode lcd_eep_string(DualDiode); // Message - "Double diode €" lcd_eep_string(CA); // Message - "CA" Line2(); // Start second line lcd_eep_string(Anode); // Message - "A=" lcd_data(GetPinAlias(diodes[0].Anode + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(K1); // Message - ";C1=" lcd_data(GetPinAlias(diodes[0].Cathode + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(K2); // Message - ";C2=" lcd_data(GetPinAlias(diodes[1].Cathode + ASCII_1)); // Display 1, 2, or 3 goto end; } else if(diodes[0].Cathode == diodes[1].Cathode) { // Common Cathode lcd_eep_string(DualDiode); // Message - "Double diode €" lcd_eep_string(CC); // Message - "CC" Line2(); // Start second line lcd_eep_string(K); // Message - "C=" lcd_data(GetPinAlias(diodes[0].Cathode + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(A1); // Message - ";A1=" lcd_data(GetPinAlias(diodes[0].Anode + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(A2); // Message - ";A2=" lcd_data(GetPinAlias(diodes[1].Anode + ASCII_1)); // Display 1, 2, or 3 goto end; } else if ((diodes[0].Cathode == diodes[1].Anode) && \ (diodes[1].Cathode == diodes[0].Anode)) { // Antiparallel lcd_eep_string(TwoDiodes); // Message - "2 diodes" Line2(); // Start second line lcd_eep_string(Antiparallel); // Message - "anti-parallel" goto end; } } else if(NumOfDiodes == 3) { // Series connection from 2 diodes; as 3 diodes one recognizes b = 3; c = 3; // Check to see if it is series connection of 2 diodes. // But 2 cathodes, and 2 anodes must agree. // Then the 2 diodes are a single dual-diode. if((diodes[0].Anode == diodes[1].Anode) || (diodes[0].Anode == diodes[2].Anode)) b = diodes[0].Anode; if(diodes[1].Anode == diodes[2].Anode) b = diodes[1].Anode; if((diodes[0].Cathode == diodes[1].Cathode) || (diodes[0].Cathode == diodes[2].Cathode)) c = diodes[0].Cathode; if(diodes[1].Cathode == diodes[2].Cathode) c = diodes[1].Cathode; if((b<3) && (c<3)) { lcd_eep_string(TwoDiodes); // Message - "2 diodes" Line2(); // Start second line lcd_eep_string(InSeries); // Message - "serial A=€€" lcd_data(GetPinAlias(b + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(NextK); // Message - ";C=" lcd_data(GetPinAlias(c + ASCII_1)); // Display 1, 2, or 3 goto end; } } } //---------------------------------------------TRANSISTOR-------------------------------------------- else if (PartFound == PART_TRANSISTOR) { if(PartReady == 0) { // 2nd examination never made, e.g. a transistor with protection diode. hfe[1] = hfe[0]; uBE[1] = uBE[0]; } if((hfe[0]>hfe[1])) { // If the amplification factor with the first test was higher: swap C and E hfe[1] = hfe[0]; uBE[1] = uBE[0]; tmp = c; c = e; e = tmp; } if(PartMode == PART_MODE_NPN) lcd_eep_string(NPN); // Message - "NPN" else lcd_eep_string(PNP); // Message - "PNP" lcd_eep_string(bstr); // Message - " B=" lcd_data(GetPinAlias(b + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(cstr); // Message - ";C=" lcd_data(GetPinAlias(c + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(estr); // Message - ";E=" lcd_data(GetPinAlias(e + ASCII_1)); // Display 1, 2, or 3 Line2(); // Start second line // Amplification factor compute, hFE = Emitter current/base current lhfe = hfe[1]; lhfe *= (((unsigned long)rhval * 100) / (unsigned long)rlval); // 500000/750 = 666.666r if(uBE[1]<11) uBE[1] = 11; lhfe /= uBE[1]; hfe[1] = (unsigned int) lhfe; lcd_eep_string(hfestr); // Message - "hFE=" lcd_string(utoa(hfe[1], outval, 10)); SetCursor(2,7); // Cursor on line 2, character 7 if(NumOfDiodes > 2) // Transistor with protection diode lcd_data(LCD_CHAR_DIODE); // Diode indicate else lcd_data(' '); for(c=0;c<NumOfDiodes;c++) { if(( (diodes[c].Cathode == e) && (diodes[c].Anode == b) && \ (PartMode == PART_MODE_NPN)) || ((diodes[c].Anode == e) && \ (diodes[c].Cathode == b) && (PartMode == PART_MODE_PNP))) { lcd_eep_string(Uf); // Message - "Uf=" lcd_string(itoa(diodes[c].Voltage, outval, 10)); lcd_data('m'); goto end; } } goto end; } //---------------------------------------------FET--------------------------------------------------- else if (PartFound == PART_FET) { // JFET or MOSFET if(PartMode & 1) // N-channel lcd_data('N'); else lcd_data('P'); // P-channel if((PartMode == PART_MODE_N_D_MOS) || (PartMode == PART_MODE_P_D_MOS)) { lcd_eep_string(dmode); // Message - "-D" lcd_eep_string(mosfet); // Message - "-MOS" } else { if((PartMode == PART_MODE_N_JFET) || (PartMode == PART_MODE_P_JFET)) lcd_eep_string(jfet); // Message - "-JFET" else { lcd_eep_string(emode); // Message - "-E" lcd_eep_string(mosfet); // Message - "-MOS" } } // Gate capacity if(PartMode < 3) { // Enrichment MOSFET lcd_eep_string(GateCap); // Message - " C=" ReadCapacity(b,e); // Measurement hfe[0] = (unsigned int)cv; if(hfe[0]>2) hfe[0] -= 3; utoa(hfe[0], outval2, 10); tmpval = strlen(outval2); tmpval2 = tmpval; if(tmpval>4) tmpval = 4; // If capacity > 100nF drop fractional part to fit on the LCD lcd_show_format_cap(outval2, tmpval, tmpval2); lcd_data('n'); } Line2(); // Start second line lcd_eep_string(gds); // Message - "GDS=" lcd_data(GetPinAlias(b + ASCII_1)); // Display 1, 2, or 3 lcd_data(GetPinAlias(c + ASCII_1)); // Display 1, 2, or 3 lcd_data(GetPinAlias(e + ASCII_1)); // Display 1, 2, or 3 if((NumOfDiodes > 0) && (PartMode < 3)) // MOSFET with protection diode; it gives only with enrichment FETs lcd_data(LCD_CHAR_DIODE); // Diode indicate else lcd_data(' '); // Blank if(PartMode < 3) { // Enrichment MOSFET gthvoltage=(gthvoltage/8); lcd_eep_string(vt); // Message - "Vt=" lcd_string(utoa(gthvoltage, outval, 10)); // Gate threshold voltage, was determined before lcd_data('m'); } goto end; } //---------------------------------------------THYRISTOR--------------------------------------------- else if (PartFound == PART_THYRISTOR) { lcd_eep_string(Thyristor); // Message - "Thyristor" Line2(); // Start second line lcd_eep_string(GAK); // Message - "GAC=" lcd_data(GetPinAlias(b + ASCII_1)); // Display 1, 2, or 3 lcd_data(GetPinAlias(c + ASCII_1)); // Display 1, 2, or 3 lcd_data(GetPinAlias(e + ASCII_1)); // Display 1, 2, or 3 goto end; } //---------------------------------------------TRIAC------------------------------------------------- else if (PartFound == PART_TRIAC) { lcd_eep_string(Triac); // Message - "Triac" Line2(); // Start second line lcd_eep_string(Gate); // Message - "G=" lcd_data(GetPinAlias(b + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(A1); // Message - ";A1=" lcd_data(GetPinAlias(e + ASCII_1)); // Display 1, 2, or 3 lcd_eep_string(A2); // Message - ";A2=" lcd_data(GetPinAlias(c + ASCII_1)); // Display 1, 2, or 3 goto end; } //---------------------------------------------RESISTOR---------------------------------------------- else if(PartFound == PART_RESISTOR) { lcd_eep_string(Resistor); // Message - "Resistor: €€" lcd_data(GetPinAlias(ra + ASCII_1)); // Display 1, 2, or 3 Pin data lcd_data('-'); lcd_data(GetPinAlias(rb + ASCII_1)); // Display 1, 2, or 3 Line2(); // Start second line if(rv[0] > HALF_ADC_RANGE) // Examine, how far the Voltages across the test resistances deviate from 512 hfe[0] = (rv[0] - HALF_ADC_RANGE); else hfe[0] = (HALF_ADC_RANGE - rv[0]); if(rv[1] > HALF_ADC_RANGE) hfe[1] = (rv[1] - HALF_ADC_RANGE); else hfe[1] = (HALF_ADC_RANGE - rv[1]); if(hfe[0] > hfe[1]) { radcmax[0] = radcmax[1]; rv[0] = rv[1]; // Result use, which is more near because of 512 (accuracy improves) rv[1] = rhval; // High - Test resistance } else rv[1] = rlval; // Low - Test resistance if(rv[0] == 0) rv[0] = 1; lhfe = (unsigned long)((unsigned long)((unsigned long)rv[1] * \ (unsigned long)rv[0]) / (unsigned long)((unsigned long)radcmax[0] - (unsigned long)rv[0])); // Resistance compute ultoa(lhfe,outval,10); if(rv[1] == rhval) { // 470k- Resisted? ra = strlen(outval); // Necessarily, in order to indicate comma for(rb=0;rb<ra;rb++) { lcd_data(outval[rb]); if(rb == (ra-2)) lcd_data(','); // comma } lcd_data ('K'); // Kilo ohm, if 470k uses resistance } else lcd_string(outval); lcd_data(LCD_CHAR_OMEGA); // Omega for ohms goto end; } //---------------------------------------------CAPACITOR--------------------------------------------- else if(PartFound == PART_CAPACITOR) { // Capacitor measurement lcd_eep_string(Capacitor); // Message - "Capacitor: €€" lcd_data(GetPinAlias(ca + ASCII_1)); // Display 1, 2, or 3 Pin - Data lcd_data('-'); lcd_data(GetPinAlias(cb + ASCII_1)); // Display 1, 2, or 3 Line2(); // Start second line tmpval2 = 'n'; // n for nF if(cv > 99999) { // Too big cv /= 1000; // convert to Micro Farads tmpval2 = LCD_CHAR_U; // change n to greek char for micro } ultoa(cv, outval, 10); // outval now a string version of cv tmpval = strlen(outval); lcd_show_format_cap(outval, tmpval, tmpval); lcd_data(tmpval2); // display the SI Suffix lcd_data('F'); // F for Farads goto end; } //---------------------------------------------NOT-FOUND-OR-DAMAGED--------------------------------------------------------- if(NumOfDiodes == 0) { // Nothing found. Tell user. lcd_eep_string(TestFailed1); Line2(); lcd_eep_string(TestFailed2); } else { // Data found but bad result or no positive ident lcd_eep_string(BadResult1); Line2(); lcd_eep_string(BadResult2); lcd_data(NumOfDiodes + ASCII_0); lcd_data(LCD_CHAR_DIODE); } end: while(!(ON_PIN_REG & (1<<RST_PIN))); // wait, to tracers released _delay_ms(200); for(hfe[0] = 0;hfe[0]<10000;hfe[0]++) { // 10 Seconds untill power off. if(!(ON_PIN_REG & (1<<RST_PIN))) // if the button is pressed, start all over goto start; wdt_reset(); // We want to wait the full 10 Seconds _delay_ms(1); // 1mS 10,000 times = 10 seconds } if(PowerMode==PWR_9V) { // If in battery mode; try to turn off; otherwise wait for a reset POWER_OFF(); } wdt_disable(); // Watchdog out // Continuous loop, no timer while(1) { if(!(RESET_GET())) // only one reaches, if the automatic disconnection was not inserted goto start; } return 0; } // End of main()
int main(void) { uchar i; int intro = 1; static char reciveErrorCount = 0; static char carrierErrorCount = 0; wdt_enable(WDTO_1S); /* Even if you don't use the watchdog, turn it off here. On newer devices, * the status of the watchdog (on/off, period) is PRESERVED OVER RESET! * RESET status: all port bits are inputs without pull-up. * That's the way we need D+ and D-. Therefore we don't need any * additional hardware initialization. */ usbInit(); usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */ i = 0; while (--i) { // fake USB disconnect for > 250 ms wdt_reset(); _delay_ms(1); } usbDeviceConnect(); //sei(); //Ports initialization and other piperials LCD_Initalize(); LCD_Clear(); /* About project screen */ //LCD_GoTo(center("SMiW 2011/2012"), 0); //LCD_WriteText("SMiW 2011/2012"); //LCD_GoTo(center("Marcin Jabrzyk"), 2); //LCD_WriteText("Marcin Jabrzyk"); irmp_init(); //IR libary timer_init(); //IR timmer and ADC starter adc_init(); //ADC configuration cli(); intro = 0; if (RFM70_Initialize(0, (uint8_t*) "Smiw2")) { LCD_GoTo(center("Init RFM70"), 2); LCD_WriteText("Init RFM70"); _delay_ms(100); } else { LCD_GoTo(center("ERR init RFM70"), 1); LCD_WriteText("ERR init RFM70"); } if (RFM70_Present()) { LCD_GoTo(center("RFM70 present"), 3); LCD_WriteText("RFM70 present"); } else { LCD_GoTo(center("RFM70 not present"), 3); LCD_WriteText("RFM70 not present"); } sei(); for (;;) { /* main event loop */ wdt_reset(); usbPoll(); if (RFM70_Present()) { sprintf(screenDebug[0], screenDebugTemplate[0], "OK"); } else { sprintf(screenDebug[0], screenDebugTemplate[0], "ERROR"); } if (Carrier_Detected()) { sprintf(screenDebug[1], screenDebugTemplate[1], "OK"); carrierErrorCount = 0; } else { carrierErrorCount++; } if (carrierErrorCount > 50) { sprintf(screenDebug[1], screenDebugTemplate[1], "NONE"); } char* _tempGrzejnik; if (Packet_Received()) { sprintf(screenDebug[2], screenDebugTemplate[2], "OK"); Receive_Packet(message); //if from grzejnik starts with "a" else from piec _tempGrzejnik = strchr(message, 'a'); if (_tempGrzejnik != NULL ) { strncpy(tempFromGrzejnik, _tempGrzejnik, 4); sprintf(screenCenter[2], screenCenterTemplate[2], _tempGrzejnik); } else { strncpy(tempFromPiec, message, 4); sprintf(screenCenter[1], screenCenterTemplate[1], message); } reciveErrorCount = 0; } else { reciveErrorCount++; } if (reciveErrorCount > 90) { sprintf(screenDebug[2], screenDebugTemplate[2], "WAIT"); } if (irmp_get_data(&irmp_data)) { // When IR decodes a new key presed. lastKey = irmp_data.command; //Save the key itoa(irmp_data.command, lastKeyStr, 10); //Convert it to string sprintf(screenCenter[3], screenCenterTemplate[3], lastKeyStr); isChanged = 1; intro = 0; } if (intro == 0) { switch (lastKey) { //Change the view case 69: printScreenWithCenter(screenLeft); break; //CH- case 70: printScreen(screenCenter); break; //CH case 71: printScreenWithCenter(screenRight); break; //CH+ case 82: printScreen(screenDebug); break; default: printScreen(screenCenter); break; //Any other key } } usbPoll(); } return 0; }
static void wdt_ping(void) { wdt_enable(heartbeat * WDOG_COUNTER_RATE); }
void init(void) { uint8_t i; bool updated; //*********************************************************** // I/O setup //*********************************************************** // Set port directions DDRA = 0x30; // Port A DDRB = 0x0A; // Port B DDRC = 0xFC; // Port C DDRD = 0xF2; // Port D // Hold all PWM outputs low to stop glitches // M5 and M6 are on PortA for KK2.1 MOTORS = 0; M5 = 0; M6 = 0; // Preset I/O pins LED1 = 0; // LED1 off LVA = 0; // LVA alarm OFF LCD_SCL = 1; // GLCD clock high // Set/clear pull-ups (1 = set, 0 = clear) PINB = 0xF5; // Set PB pull-ups PIND = 0x0C; // Set PD pull-ups (Don't pull up RX yet) //*********************************************************** // Spektrum receiver binding. Must be done immediately on power-up // // 3 low pulses: DSM2 1024/22ms // 5 low pulses: DSM2 2048/11ms // 7 low pulses: DSMX 1024/22ms // 9 low pulses: DSMX 2048/11ms //*********************************************************** PIND = 0x0C; // Release RX pull up on PD0 _delay_ms(63); // Pause while satellite wakes up // and pull-ups have time to rise. // Tweak until bind pulses about 68ms after power-up // Bind as master if any single button pressed. // NB: Have to wait until the button pull-ups rise before testing for a button press. // Button 1 if ((PINB & 0xf0) == 0x70) { DDRD = 0xF3; // Switch PD0 to output bind_master(3); } // Button 2 if ((PINB & 0xf0) == 0xb0) { DDRD = 0xF3; // Switch PD0 to output bind_master(5); } // Button 3 if ((PINB & 0xf0) == 0xd0) { DDRD = 0xF3; // Switch PD0 to output bind_master(7); } // Button 4 if ((PINB & 0xf0) == 0xE0) { DDRD = 0xF3; // Switch PD0 to output bind_master(9); } DDRD = 0xF2; // Reset Port D directions PIND = 0x0D; // Set PD pull-ups (now pull up RX as well) //*********************************************************** // Timers //*********************************************************** // Timer0 (8bit) - run @ 20MHz / 1024 = 19.531kHz or 51.2us - max 13.1ms // Slow timer to extend Timer 1 TCCR0A = 0; // Normal operation TCCR0B = 0x05; // Clk / 1024 = 19.531kHz or 51.2us - max 13.1ms TIMSK0 |= (1 << TOIE0); // Enable interrupts TCNT0 = 0; // Reset counter // Timer1 (16bit) - run @ 2.5MHz (400ns) - max 26.2ms // Used to measure Rx Signals & control ESC/servo output rate TCCR1A = 0; TCCR1B |= (1 << CS11); // Clk/8 = 2.5MHz // Timer2 8bit - run @ 20MHz / 1024 = 19.531kHz or 51.2us - max 13.1ms // Used to time arm/disarm intervals TCCR2A = 0; TCCR2B = 0x07; // Clk/1024 = 19.531kHz TIMSK2 = 0; TIFR2 = 0; TCNT2 = 0; // Reset counter //*********************************************************** // Interrupts and pin function setup //*********************************************************** // Pin change interrupt enables PCINT1, PCINT2 and PCINT3 (Throttle, AUX and CPPM input) PCICR = 0x0A; // PCINT8 to PCINT15 (PCINT1 group - AUX) // PCINT24 to PCINT31 (PCINT3 group - THR) PCIFR = 0x0F; // Clear PCIF0 interrupt flag // Clear PCIF1 interrupt flag // Clear PCIF2 interrupt flag // Clear PCIF3 interrupt flag // External interrupts INT0 (Elevator) and INT1 (Aileron) and INT2 (Rudder) EICRA = 0x15; // Any change INT0 // Any change INT1 // Any change INT2 EIFR = 0x07; // Clear INT0 interrupt flag (Elevator) // Clear INT1 interrupt flag (Aileron) // Clear INT2 interrupt flag (Rudder/CPPM) //*********************************************************** // Start up //*********************************************************** // Preset important flags Interrupted = false; // Load EEPROM settings updated = Initial_EEPROM_Config_Load(); // Config now contains valid values //*********************************************************** // RX channel defaults for when no RC connected // Not doing this can result in the FC trying (unsuccessfully) to arm // and makes entry into the menus very hard //*********************************************************** for (i = 0; i < MAX_RC_CHANNELS; i++) { RxChannel[i] = 3750; } RxChannel[THROTTLE] = 2500; // Min throttle //*********************************************************** // GLCD initialisation //*********************************************************** // Initialise the GLCD st7565_init(); // Make sure the LCD is blank without clearing buffer (and so no logo) clear_screen(); //*********************************************************** // ESC calibration //*********************************************************** // Calibrate ESCs if ONLY buttons 1 and 4 pressed if ((PINB & 0xf0) == 0x60) { // Display calibrating message st7565_command(CMD_SET_COM_NORMAL); // For text (not for logo) clear_buffer(buffer); LCD_Display_Text(59,(const unsigned char*)Verdana14,10,25); write_buffer(buffer); clear_buffer(buffer); // For each output for (i = 0; i < MAX_OUTPUTS; i++) { // Check for motor marker if (Config.Channel[i].Motor_marker == MOTOR) { // Set output to maximum pulse width ServoOut[i] = MOTOR_100; } else { ServoOut[i] = SERVO_CENTER; } } // Output HIGH pulse (1.9ms) until buttons released while ((PINB & 0xf0) == 0x60) { // Pass address of ServoOut array and select all outputs output_servo_ppm_asm(&ServoOut[0], 0xFF); // Loop rate = 20ms (50Hz) _delay_ms(20); } // Output LOW pulse (1.1ms) after buttons released // For each output for (i = 0; i < MAX_OUTPUTS; i++) { // Check for motor marker if (Config.Channel[i].Motor_marker == MOTOR) { // Set output to maximum pulse width ServoOut[i] = MOTOR_0; } } // Loop forever here while(1) { // Pass address of ServoOut array and select all outputs output_servo_ppm_asm(&ServoOut[0], 0xFF); // Loop rate = 20ms (50Hz) _delay_ms(20); } } //*********************************************************** // Reset EEPROM settings //*********************************************************** // This delay prevents the GLCD flashing up a ghost image of old data _delay_ms(300); // Reload default eeprom settings if middle two buttons are pressed if ((PINB & 0xf0) == 0x90) { // Display reset message st7565_command(CMD_SET_COM_NORMAL); // For text (not for logo) clear_buffer(buffer); LCD_Display_Text(262,(const unsigned char*)Verdana14,40,25); // "Reset" write_buffer(buffer); clear_buffer(buffer); // Reset EEPROM settings Set_EEPROM_Default_Config(); Save_Config_to_EEPROM(); // Set contrast to the default value st7565_set_brightness(Config.Contrast); _delay_ms(500); // Save is now too fast to show the "Reset" text long enough } // Display message in place of logo when updating eeprom structure if (updated) { st7565_command(CMD_SET_COM_NORMAL); // For text (not for logo) clear_buffer(buffer); LCD_Display_Text(259,(const unsigned char*)Verdana14,30,13); // "Updating" LCD_Display_Text(260,(const unsigned char*)Verdana14,33,37); // "settings" write_buffer(buffer); clear_buffer(buffer); _delay_ms(1000); } else { // Write logo from buffer write_buffer(buffer); _delay_ms(1000); } clear_buffer(buffer); write_buffer(buffer); st7565_init(); // Seems necessary for KK2 mini //*********************************************************** // i2c init //*********************************************************** i2c_init(); init_i2c_gyros(); init_i2c_accs(); //*********************************************************** // Remaining init tasks //*********************************************************** // Display "Hold steady" message clear_buffer(buffer); st7565_command(CMD_SET_COM_NORMAL); // For text (not for logo) LCD_Display_Text(263,(const unsigned char*)Verdana14,18,25); // "Hold steady" write_buffer(buffer); clear_buffer(buffer); // Do startup tasks Init_ADC(); init_int(); // Initialise interrupts based on RC input mode init_uart(); // Initialise UART // Initial gyro calibration if (!CalibrateGyrosSlow()) { clear_buffer(buffer); LCD_Display_Text(61,(const unsigned char*)Verdana14,25,25); // "Cal. failed" write_buffer(buffer); _delay_ms(1000); // Reset cli(); wdt_enable(WDTO_15MS); // Watchdog on, 15ms while(1); // Wait for reboot } // Update voltage detection SystemVoltage = GetVbat(); // Check power-up battery voltage UpdateLimits(); // Update travel and trigger limits // Disarm on start-up if Armed setting is ARMABLE if (Config.ArmMode == ARMABLE) { General_error |= (1 << DISARMED); // Set disarmed bit } // Check to see that throttle is low if RC detected if (Interrupted) { RxGetChannels(); if (MonopolarThrottle > THROTTLEIDLE) // THROTTLEIDLE = 50 { General_error |= (1 << THROTTLE_HIGH); // Set throttle high error bit } } // Reset IMU reset_IMU(); // Beep that init is complete LVA = 1; _delay_ms(25); LVA = 0; #ifdef ERROR_LOG // Log reboot add_log(REBOOT); #endif } // init()
int __attribute__((noreturn)) main(void) { int led_timer = 0; uchar led_counter = 0; wdt_enable(WDTO_1S); /* Even if you don't use the watchdog, turn it off here. On newer devices, * the status of the watchdog (on/off, period) is PRESERVED OVER RESET! */ /* RESET status: all port bits are inputs without pull-up. * That's the way we need D+ and D-. Therefore we don't need any * additional hardware initialization. */ odDebugInit(); DBG1(0x00, 0, 0); /* debug output: main starts */ usbInit(); #if 0 usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */ i = 0; while(--i){ /* fake USB disconnect for > 250 ms */ wdt_reset(); _delay_ms(1); } usbDeviceConnect(); #endif sei(); /* usbflattiny code */ DDRB |= (1<<PORTB5) | (1<<PORTB4) | (1<<PORTB3) | (1<<PORTB1); PORTB |= (1<<PORTB5); PORTB |= (1<<PORTB3); PORTB &= ~(1<<PORTB4); PORTB &= ~(1<<PORTB1); /* /usbflattiny code */ DBG1(0x01, 0, 0); /* debug output: main loop starts */ for(;;){ /* main event loop */ DBG1(0x02, 0, 0); /* debug output: main loop iterates */ wdt_reset(); usbPoll(); if(usbInterruptIsReady()){ /* called after every poll of the interrupt endpoint */ advance_mouse(); DBG1(0x03, 0, 0); /* debug output: interrupt report prepared */ usbSetInterrupt((void *)&reportBuffer, sizeof(reportBuffer)); } /* usbflattiny code */ led_timer++; if (led_timer == 23*1000) { led_counter++; if (led_counter == 0x10) led_counter = 0; if (led_counter & 0x1) PORTB |= (1<<PORTB4); else PORTB &= ~(1<<PORTB4); if (led_counter & 0x2) PORTB |= (1<<PORTB3); else PORTB &= ~(1<<PORTB3); if (led_counter & 0x4) PORTB |= (1<<PORTB5); else PORTB &= ~(1<<PORTB5); if (led_counter & 0x8) PORTB |= (1<<PORTB1); else PORTB &= ~(1<<PORTB1); led_timer = 0; } /* /usbflattiny code */ } }
/* * Do all the startup-time peripheral initializations. */ static void ioinit(void) { uint16_t pwm_from_eeprom; /* * Set up the 16-bit timer 1. * * Timer 1 will be set up as a 10-bit phase-correct PWM (WGM10 and * WGM11 bits), with OC1A used as PWM output. OC1A will be set when * up-counting, and cleared when down-counting (COM1A1|COM1A0), this * matches the behaviour needed by the STK500's low-active LEDs. * The timer will runn on full MCU clock (1 MHz, CS10 in TCCR1B). */ TCCR1A = _BV(WGM10) | _BV(WGM11) | _BV(COM1A1) | _BV(COM1A0); TCCR1B = _BV(CS10); OCR1A = 0; /* set PWM value to 0 */ /* enable pull-ups for pushbuttons */ CONTROL_PORT = _BV(TRIGGER_DOWN) | _BV(TRIGGER_UP) | _BV(TRIGGER_ADC); /* * Enable Port D outputs: PD6 for the clock output, PD7 for the LED * flasher. PD1 is UART TxD but not DDRD setting is provided for * that, as enabling the UART transmitter will automatically turn * this pin into an output. */ CONTROL_DDR = _BV(CLOCKOUT) | _BV(FLASH); /* * As the location of OC1A differs between supported MCU types, we * enable that output separately here. Note that the DDRx register * *might* be the same as CONTROL_DDR above, so make sure to not * clobber it. */ PWMDDR |= _BV(PWMOUT); UCSRA = _BV(U2X); /* improves baud rate error @ F_CPU = 1 MHz */ UCSRB = _BV(TXEN)|_BV(RXEN)|_BV(RXCIE); /* tx/rx enable, rx complete intr */ UBRRL = (F_CPU / (8 * 9600UL)) - 1; /* 9600 Bd */ /* * enable ADC, select ADC clock = F_CPU / 8 (i.e. 125 kHz) */ ADCSRA = _BV(ADEN) | _BV(ADPS1) | _BV(ADPS0); TIMSK = _BV(TOIE1); sei(); /* enable interrupts */ /* * Enable the watchdog with the largest prescaler. Will cause a * watchdog reset after approximately 2 s @ Vcc = 5 V */ wdt_enable(WDTO_2S); /* * Read the value from EEPROM. If it is not 0xffff (erased cells), * use it as the starting value for the PWM. */ if ((pwm_from_eeprom = eeprom_read_word(&ee_pwm)) != 0xffff) OCR1A = (pwm = pwm_from_eeprom); }
boolean MySensor::process() { uint8_t pipe; boolean available = RF24::available(&pipe); if (!available || pipe>6) return false; uint8_t len = RF24::getDynamicPayloadSize(); RF24::read(&msg, len); RF24::writeAckPayload(pipe,&pipe, 1 ); // Add string termination, good if we later would want to print it. msg.data[mGetLength(msg)] = '\0'; debug(PSTR("read: %d-%d-%d s=%d,c=%d,t=%d,pt=%d,l=%d:%s\n"), msg.sender, msg.last, msg.destination, msg.sensor, mGetCommand(msg), msg.type, mGetPayloadType(msg), mGetLength(msg), msg.getString(convBuf)); if(!(mGetVersion(msg) == PROTOCOL_VERSION)) { debug(PSTR("version mismatch\n")); return false; } uint8_t command = mGetCommand(msg); uint8_t type = msg.type; uint8_t sender = msg.sender; uint8_t last = msg.last; uint8_t destination = msg.destination; if (repeaterMode && command == C_INTERNAL && type == I_FIND_PARENT) { // Relaying nodes should always answer ping messages // Wait a random delay of 0-2 seconds to minimize collision // between ping ack messages from other relaying nodes delay(millis() & 0x3ff); sendWrite(sender, build(msg, nc.nodeId, sender, NODE_SENSOR_ID, C_INTERNAL, I_FIND_PARENT_RESPONSE, false).set(nc.distance), true); return false; } else if (destination == nc.nodeId) { // Check if sender requests an ack back. if (mGetRequestAck(msg)) { // Copy message ack = msg; mSetRequestAck(ack,false); // Reply without ack flag (otherwise we would end up in an eternal loop) mSetAck(ack,true); ack.sender = nc.nodeId; ack.destination = msg.sender; sendRoute(ack); } // This message is addressed to this node if (repeaterMode && last != nc.parentNodeId) { // Message is from one of the child nodes. Add it to routing table. addChildRoute(sender, last); } if (command == C_INTERNAL) { if (type == I_FIND_PARENT_RESPONSE && !isGateway) { // We've received a reply to a FIND_PARENT message. Check if the distance is // shorter than we already have. uint8_t distance = msg.getByte(); if (distance<nc.distance-1) { // Found a neighbor closer to GW than previously found nc.distance = distance + 1; nc.parentNodeId = msg.sender; eeprom_write_byte((uint8_t*)EEPROM_PARENT_NODE_ID_ADDRESS, nc.parentNodeId); eeprom_write_byte((uint8_t*)EEPROM_DISTANCE_ADDRESS, nc.distance); debug(PSTR("new parent=%d, d=%d\n"), nc.parentNodeId, nc.distance); } return false; } else if (sender == GATEWAY_ADDRESS) { bool isMetric; if (type == I_REBOOT) { #ifndef __Raspberry_Pi // Requires MySensors or other bootloader with watchdogs enabled wdt_enable(WDTO_15MS); for (;;); #endif } else if (type == I_ID_RESPONSE) { if (nc.nodeId == AUTO) { nc.nodeId = msg.getByte(); // Write id to EEPROM if (nc.nodeId == AUTO) { // sensor net gateway will return max id if all sensor id are taken debug(PSTR("full\n")); while (1); // Wait here. Nothing else we can do... } else { RF24::openReadingPipe(CURRENT_NODE_PIPE, TO_ADDR(nc.nodeId)); eeprom_write_byte((uint8_t*)EEPROM_NODE_ID_ADDRESS, nc.nodeId); } debug(PSTR("id=%d\n"), nc.nodeId); } } else if (type == I_CONFIG) { // Pick up configuration from controller (currently only metric/imperial) // and store it in eeprom if changed isMetric = msg.getString()[0] == 'M' ; if (cc.isMetric != isMetric) { cc.isMetric = isMetric; eeprom_write_byte((uint8_t*)EEPROM_CONTROLLER_CONFIG_ADDRESS, isMetric); } } else if (type == I_CHILDREN) { if (repeaterMode && msg.getString()[0] == 'C') { // Clears child relay data for this node debug(PSTR("rd=clear\n")); for (uint8_t i=0;i< sizeof(childNodeTable); i++) { removeChildRoute(i); } sendRoute(build(msg, nc.nodeId, GATEWAY_ADDRESS, NODE_SENSOR_ID, C_INTERNAL, I_CHILDREN,false).set("")); } } else if (type == I_TIME) { if (timeCallback != NULL) { // Deliver time to callback timeCallback(msg.getULong()); } } return false; } } // Call incoming message callback if available if (msgCallback != NULL) { msgCallback(msg); } // Return true if message was addressed for this node... return true; } else if (repeaterMode && pipe == CURRENT_NODE_PIPE) { // We should try to relay this message to another node uint8_t route = getChildRoute(msg.destination); if (route>0 && route<255) { // This message should be forwarded to a child node. If we send message // to this nodes pipe then all children will receive it because the are // all listening to this nodes pipe. // // +----B // -A // +----C------D // // We're node C, Message comes from A and has destination D // // lookup route in table and send message there sendWrite(route, msg); } else { // A message comes from a child node and we have no // route for it. // // +----B // -A // +----C------D <-- Message comes from D // // We're node C // // Message should be passed to node A (this nodes relay) // This message should be routed back towards sensor net gateway sendWrite(nc.parentNodeId, msg); // Add this child to our "routing table" if it not already exist addChildRoute(sender, last); } } return false; }
/*----------------------------------------------------------------------------- * process received bus telegrams */ static void ProcessBus(void) { uint8_t ret; TClient *pClient; TBusMsgType msgType; uint8_t i; uint8_t *p; bool msgForMe = false; ret = BusCheck(); if (ret == BUS_MSG_OK) { msgType = spRxBusMsg->type; switch (msgType) { case eBusDevReqReboot: case eBusDevRespSwitchState: case eBusDevReqActualValue: case eBusDevReqSetClientAddr: case eBusDevReqGetClientAddr: case eBusDevReqInfo: case eBusDevReqSetAddr: case eBusDevReqEepromRead: case eBusDevReqEepromWrite: if (spRxBusMsg->msg.devBus.receiverAddr == MY_ADDR) { msgForMe = true; } break; default: break; } } if (msgForMe == false) { return; } switch (msgType) { case eBusDevReqReboot: /* reset controller with watchdog */ /* set watchdog timeout to shortest value (14 ms) */ cli(); wdt_enable(WDTO_15MS); /* wait for reset */ while (1); break; case eBusDevRespSwitchState: pClient = sClient; for (i = 0; i < sNumClients; i++) { if ((pClient->address == spRxBusMsg->senderAddr) && (pClient->state == eWaitForConfirmation)) { if (spRxBusMsg->msg.devBus.x.devResp.switchState.switchState == sWindSwitch) { pClient->state = eConfirmationOK; } break; } pClient++; } break; case eBusDevReqActualValue: sTxBusMsg.senderAddr = MY_ADDR; sTxBusMsg.type = eBusDevRespActualValue; sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr; sTxBusMsg.msg.devBus.x.devResp.actualValue.devType = eBusDevTypeWind; sTxBusMsg.msg.devBus.x.devResp.actualValue.actualValue.wind.state = sWindSwitch; sTxBusMsg.msg.devBus.x.devResp.actualValue.actualValue.wind.wind = sMaxWind; //sWind; BusSend(&sTxBusMsg); break; case eBusDevReqSetClientAddr: sTxBusMsg.senderAddr = MY_ADDR; sTxBusMsg.type = eBusDevRespSetClientAddr; sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr; for (i = 0; i < BUS_MAX_CLIENT_NUM; i++) { p = &(spRxBusMsg->msg.devBus.x.devReq.setClientAddr.clientAddr[i]); eeprom_write_byte((uint8_t *)(CLIENT_ADDRESS_BASE + i), *p); } BusSend(&sTxBusMsg); GetClientListFromEeprom(); break; case eBusDevReqGetClientAddr: sTxBusMsg.senderAddr = MY_ADDR; sTxBusMsg.type = eBusDevRespGetClientAddr; sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr; for (i = 0; i < BUS_MAX_CLIENT_NUM; i++) { p = &(sTxBusMsg.msg.devBus.x.devResp.getClientAddr.clientAddr[i]); *p = eeprom_read_byte((const uint8_t *)(CLIENT_ADDRESS_BASE + i)); } BusSend(&sTxBusMsg); break; case eBusDevReqInfo: sTxBusMsg.type = eBusDevRespInfo; sTxBusMsg.senderAddr = MY_ADDR; sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr; sTxBusMsg.msg.devBus.x.devResp.info.devType = eBusDevTypeWind; strncpy((char *)(sTxBusMsg.msg.devBus.x.devResp.info.version), version, BUS_DEV_INFO_VERSION_LEN); sTxBusMsg.msg.devBus.x.devResp.info.version[BUS_DEV_INFO_VERSION_LEN - 1] = '\0'; BusSend(&sTxBusMsg); break; case eBusDevReqSetAddr: sTxBusMsg.senderAddr = MY_ADDR; sTxBusMsg.type = eBusDevRespSetAddr; sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr; p = &(spRxBusMsg->msg.devBus.x.devReq.setAddr.addr); eeprom_write_byte((uint8_t *)MODUL_ADDRESS, *p); BusSend(&sTxBusMsg); break; case eBusDevReqEepromRead: sTxBusMsg.senderAddr = MY_ADDR; sTxBusMsg.type = eBusDevRespEepromRead; sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr; sTxBusMsg.msg.devBus.x.devResp.readEeprom.data = eeprom_read_byte((const uint8_t *)spRxBusMsg->msg.devBus.x.devReq.readEeprom.addr); BusSend(&sTxBusMsg); break; case eBusDevReqEepromWrite: sTxBusMsg.senderAddr = MY_ADDR; sTxBusMsg.type = eBusDevRespEepromWrite; sTxBusMsg.msg.devBus.receiverAddr = spRxBusMsg->senderAddr; p = &(spRxBusMsg->msg.devBus.x.devReq.writeEeprom.data); eeprom_write_byte((uint8_t *)spRxBusMsg->msg.devBus.x.devReq.readEeprom.addr, *p); BusSend(&sTxBusMsg); break; default: break; } }
/** main function */ int main(void) { /* {{{ */ reboot = 0; wdt_enable(WDTO_1S); #if RANDOM unsigned long int cnt = 1000; unsigned char white, red, green, blue; unsigned char save = 0; srand(eeprom_read_word(&seed)); #endif init_output(); #if COLORFUL_INIT uint16_t j = 0; LED01_PORT |= _BV(LED_CHANNEL0); //Switch On for (j = 0; j <= 10; j ++) { wdt_reset(); _delay_ms(10); } LED01_PORT &= ~_BV(LED_CHANNEL0); //Switch Off for (j = 0; j <= 17; j ++) { wdt_reset(); _delay_ms(10); } LED01_PORT |= _BV(LED_CHANNEL1); //Switch On for (j = 0; j <= 10; j ++) { wdt_reset(); _delay_ms(10); } LED01_PORT &= ~_BV(LED_CHANNEL1); //Switch Off for (j = 0; j <= 17; j ++) { wdt_reset(); _delay_ms(10); } LED23_PORT |= _BV(LED_CHANNEL2); //Switch On for (j = 0; j <= 10; j ++) { wdt_reset(); _delay_ms(10); } LED23_PORT &= ~_BV(LED_CHANNEL2); //Switch Off for (j = 0; j <= 17; j ++) { wdt_reset(); _delay_ms(10); } LED23_PORT |= _BV(LED_CHANNEL3); //Switch On for (j = 0; j <= 10; j ++) { wdt_reset(); _delay_ms(10); } LED23_PORT &= ~_BV(LED_CHANNEL3); //Switch Off #endif init_pwm(); #if RC5_DECODER init_rc5(); #endif #if STATIC_SCRIPTS init_script_threads(); #if RS485_CTRL == 0 /* start the example scripts */ //script_threads[0].handler.execute = &memory_handler_flash; //script_threads[0].handler.position = (uint16_t) &blinken; //script_threads[0].flags.disabled = 0; script_threads[0].handler.execute = &memory_handler_flash; script_threads[0].handler.position = (uint16_t) &strobo_rgb; script_threads[0].flags.disabled = 0; #endif #endif #if RS485_CTRL /* init command bus */ UCSR0A = _BV(MPCM0); /* enable multi-processor communication mode */ UCSR0C = _BV(UCSZ00) | _BV(UCSZ01); /* 9 bit frame size */ #define UART_UBRR 8 /* 115200 baud at 16mhz */ UBRR0H = HIGH(UART_UBRR); UBRR0L = LOW(UART_UBRR); UCSR0B = _BV(RXEN0) | _BV(TXEN0) | _BV(UCSZ02); /* enable receiver and transmitter */ #endif #if USB usbInit(); usbDeviceDisconnect(); /* enforce re-enumeration, do this while interrupts are disabled! */ uchar i = 0; while(--i){ /* fake USB disconnect for > 250 ms */ _delay_ms(1); } usbDeviceConnect(); //TCCR0 = 5; /* set prescaler to 1/1024 */ #endif /* enable interrupts globally */ sei(); while (1) { wdt_reset(); #if USB usbPoll(); #endif // if (TIFR & (1 << TOV0)) { // TIFR |= 1 << TOV0; /* clear pending flag */ // } if (reboot) { soft_reset(); } if (global.flags.new_cycle) { global.flags.new_cycle = 0; update_brightness(); #if RANDOM if (++cnt == 1200) { red = pwmtable[rand() % 16]; green = pwmtable[rand() % 16]; blue = pwmtable[rand() % 16]; white = whitetable[rand() % 8]; set_fade(1, blue, 800); set_fade(2, green, 800); set_fade(3, red, 800); if (blue + green + red <= 32) set_fade(0, white, 800); else set_fade(0, 0, 800); cnt = 0; if (++save == 100) eeprom_write_word(&seed, rand()); } #endif #if STATIC_SCRIPTS execute_script_threads(); #endif continue; } } #if RC5_DECODER /* check if we received something via ir */ if (global_rc5.new_data) { static uint8_t toggle_bit = 2; /* if key has been pressed again */ if (global_rc5.received_command.toggle_bit != toggle_bit) { /* if code is 0x01 (key '1' on a default remote) */ if (global_rc5.received_command.code == 0x01) { /* install script into thread 1 */ script_threads[1].handler.execute = &memory_handler_flash; script_threads[1].handler.position = (uint16_t) &green_flash; script_threads[1].flags.disabled = 0; script_threads[1].handler_stack_offset = 0; } /* store new toggle bit state */ toggle_bit = global_rc5.received_command.toggle_bit; } /* reset the new_data flag, so that new commands can be received */ global_rc5.new_data = 0; continue; } #endif #if RS485_CTRL if (UCSR0A & _BV(RXC0)) { uint8_t address = UCSR0B & _BV(RXB80); /* read nineth bit, zero if data, one if address */ uint8_t data = UDR0; static uint8_t buffer[8]; static uint8_t fill = 0; if (UCSR0A & _BV(MPCM0) || address) { /* if MPCM mode is still active, or ninth bit set, this is an address packet */ /* check if we are ment */ if (data == 0 || data == RS485_ADDRESS) { /* remove MPCM flag and reset buffer fill counter */ UCSR0A &= ~_BV(MPCM0); fill = 0; continue; } else {/* turn on MPCM */ UCSR0A |= _BV(MPCM0); continue; } } /* else this is a data packet, put data into buffer */ buffer[fill++] = data; if (buffer[0] == 0x01) { /* soft reset */ jump_to_bootloader(); } else if (buffer[0] == 0x02 && fill == 4) { /* set color */ CHANNEL0_PWM = buffer[1]; CHANNEL1_PWM = buffer[2]; CHANNEL2_PWM = buffer[3]; CHANNEL3_PWM = buffer[4]; for (uint8_t pos = 0; pos < PWM_CHANNELS; pos++) { global_pwm.channels[pos].target_brightness = buffer[pos + 1]; global_pwm.channels[pos].brightness = buffer[pos + 1]; } UCSR0A |= _BV(MPCM0); /* return to MPCM mode */ } else if (buffer[0] == 0x03 && fill == 6) { /* fade to color */ for (uint8_t pos = 0; pos < PWM_CHANNELS; pos++) { global_pwm.channels[pos].speed_h = buffer[1]; global_pwm.channels[pos].speed_l = buffer[2]; global_pwm.channels[pos].target_brightness = buffer[pos + 3]; } UCSR0A |= _BV(MPCM0); /* return to MPCM mode */ } } #endif }
static void wdt_reboot(void) { wdt_reset(); wdt_enable(WDTO_2S); }
//Обрабатываем значения HoldingRegisters void ModbusSaver() { switch (usRegHoldingBuf[MB_OFFSET+MB_COMMAND]) { case 1: wdt_enable(WDTO_15MS); // enable watchdog while(1); // wait for watchdog to reset processor break; break; case 2: ADXL345_Calibrate(); break; } usRegHoldingBuf[MB_OFFSET+MB_COMMAND] = 0; if (usRegHoldingBuf[MB_OFFSET+MB_LED_BLUE]) { LED_On(LED_BLUE); } else { LED_Off(LED_BLUE); } if (usRegHoldingBuf[MB_OFFSET+MB_LED_GREEN]) { LED_On(LED_GREEN); } else { LED_Off(LED_GREEN); } if (bit_is_set(usRegHoldingBuf[MB_OFFSET+MB_SOUND], 0)) { Sound_On(); } else { Sound_Off(); } if (usRegHoldingBuf[MB_OFFSET+MB_ALL]<16000UL) { usRegHoldingBuf[MB_OFFSET+MB_ALL]=16000UL; } if (bit_is_set(usRegHoldingBuf[MB_OFFSET+MB_MANUAL], 4)) { float speeds[4]; speeds[FRONT_LEFT] = (float)usRegHoldingBuf[MB_OFFSET + MB_FRONT_LEFT]; speeds[FRONT_RIGHT] = (float)usRegHoldingBuf[MB_OFFSET + MB_FRONT_RIGHT]; speeds[REAR_LEFT] = (float)usRegHoldingBuf[MB_OFFSET + MB_REAR_LEFT]; speeds[REAR_RIGHT] = (float)usRegHoldingBuf[MB_OFFSET + MB_REAR_RIGHT]; SetMotors(speeds); } else { usRegHoldingBuf[MB_OFFSET + MB_FRONT_LEFT] = counter[FRONT_LEFT]; usRegHoldingBuf[MB_OFFSET + MB_FRONT_RIGHT] = counter[FRONT_RIGHT]; usRegHoldingBuf[MB_OFFSET + MB_REAR_LEFT] = counter[REAR_LEFT]; usRegHoldingBuf[MB_OFFSET + MB_REAR_RIGHT] = counter[REAR_RIGHT]; } //t_Ox.value = 0; //t_Oy.value = 0; t_Ox.array[0] = usRegHoldingBuf[2]; t_Ox.array[1] = usRegHoldingBuf[3]; t_Oy.array[0] = usRegHoldingBuf[4]; t_Oy.array[1] = usRegHoldingBuf[5]; t_Oz.array[0] = usRegHoldingBuf[6]; t_Oz.array[1] = usRegHoldingBuf[7]; ModbusEEPROMLoader(); }
/****************************************************************************** * File: main.c * Author: Kevin Day * Date: February, 2005 * Description: * Main program for audi radio interface * * Copyright (c) 2005 Kevin Day * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * *******************************************************************************/ #include <avr/interrupt.h> #include <avr/pgmspace.h> #include <avr/io.h> #include <avr/wdt.h> #include "types.h" #include "tasks.h" #include "comms_generic.h" #include "timers.h" #include "adc.h" #include "persist.h" #include "hcms.h" #include "gpsavr.h" #include "hud.h" #include "spimaster.h" #include "avrcan.h" #include "avrms2.h" #include "swuart.h" #include "hwi2c.h" #include "adcgauges.h" #include "miscgpio.h" #include "sensors.h" #define LED_PORT PORTG #define LED_DIR DDRG #define LED_PIN PING #define LED_BIT 0 #define ANT_PORT PORTB #define ANT_DIR DDRB #define ANT_PIN PINB #define ANT_BIT 2 void debug_led(u8 val); static inline void start_blink_timer(); void bufferpool_init(); task_t* comms_task_create(); task_t *radio_input_task_create(); #define STACK_CANARY 0xC5 void StackPaint(void) __attribute__ ((naked)) __attribute__ ((section (".init1"))); void StackPaint(void) { #if 0 uint8_t *p = &_end; while(p <= &__stack) { *p = STACK_CANARY; p++; } #else __asm volatile (" ldi r30,lo8(_end)\n" " ldi r31,hi8(_end)\n" " ldi r24,lo8(0xc5)\n" /* STACK_CANARY = 0xc5 */ " ldi r25,hi8(__stack)\n" " rjmp .cmp\n" ".loop:\n" " st Z+,r24\n" ".cmp:\n" " cpi r30,lo8(__stack)\n" " cpc r31,r25\n" " brlo .loop\n" " breq .loop"::); #endif } extern uint8_t __heap_start; /* not _end because of .bufferpool */ extern uint8_t __stack; uint16_t StackCount(void) { const uint8_t *p = &__heap_start; uint16_t c = 0; while(*p == STACK_CANARY && p <= &__stack) { p++; c++; } return c; } #define ADC_CONTEXTS 8 adc_context_t adc_context[ADC_CONTEXTS]; u8 num_adc; u16 stack_high; #define DISPAVR_RESET_PIN 4 /* on port B */ int main() { u8 mcusr_rst = MCUSR; MCUSR = 0; wdt_disable(); wdt_enable(WDTO_2S); /* Disable JTAG so the ADC pins are available. * Don't do this if the JTAG reset flag is set -- * presumably the jtag pod is connected in that * case. */ if (! (mcusr_rst & (1<<JTRF))) { MCUCR |= (1<<JTD); } /* Assert remote AVR reset */ PORTB &= ~(1<<DISPAVR_RESET_PIN); DDRB |= (1<<DISPAVR_RESET_PIN); bufferpool_init(); init_persist_data(); systimer_init(); //fuel_gauge_init(&adc_context[num_adc++]); num_adc = sensors_init(&adc_context[num_adc], num_adc); adc_init_adc(ADC_DIV128, num_adc, adc_context); /* Deassert remote AVR reset */ PORTB |= (1<<DISPAVR_RESET_PIN); spimaster_init(); init_avrms2(); // swuart_init(); /* Enable interrupts */ sei(); /* Populate the tasklist in priority order */ tasklist[num_tasks++] = comms_task_create(); tasklist[num_tasks++] = gps_task_create(); tasklist[num_tasks++] = can_task_create(); tasklist[num_tasks++] = hud_task_create(); // tasklist[num_tasks++] = i2c_task_create(); tasklist[num_tasks++] = gpio_task_create(); // start_blink_timer(); /* non-preemptive static priority scheduler */ while(1) { wdt_reset(); u8 taskidx; u8 r; for(taskidx=0; taskidx<num_tasks; taskidx++) { r = tasklist[taskidx]->taskfunc(); if (r) break; } if (r == 0) { stack_high = StackCount(); /* only run this after all tasks run */ } } }
SV_STATUS processSVMessage( lnMsg *LnPacket ) { SV_Addr_t unData ; if( ( LnPacket->sv.mesg_size != (byte) 0x10 ) || ( LnPacket->sv.command != (byte) OPC_PEER_XFER ) || ( LnPacket->sv.sv_type != (byte) 0x02 ) || ( LnPacket->sv.sv_cmd & (byte) 0x40 ) || ( ( LnPacket->sv.svx1 & (byte) 0xF0 ) != (byte) 0x10 ) || ( ( LnPacket->sv.svx2 & (byte) 0xF0 ) != (byte) 0x10 ) ) return SV_OK ; decodePeerData( &LnPacket->px, unData.abPlain ) ; if ((LnPacket->sv.sv_cmd != SV_DISCOVER) && (LnPacket->sv.sv_cmd != SV_CHANGE_ADDRESS) && (unData.stDecoded.unDestinationId.w != readSVDestinationId())) { return SV_OK; } switch( LnPacket->sv.sv_cmd ) { case SV_WRITE_SINGLE: if (!CheckAddressRange(unData.stDecoded.unVendorIdOrSvAddress.w, 1)) return SV_ERROR; writeSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w, unData.abPlain[4]); // fall through inteded! case SV_READ_SINGLE: if (!CheckAddressRange(unData.stDecoded.unVendorIdOrSvAddress.w, 1)) return SV_ERROR; unData.abPlain[4] = readSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w); break; case SV_WRITE_MASKED: if (!CheckAddressRange(unData.stDecoded.unVendorIdOrSvAddress.w, 1)) return SV_ERROR; // new scope for temporary local variables only { unsigned char ucOld = readSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w) & (~unData.abPlain[5]); unsigned char ucNew = unData.abPlain[4] & unData.abPlain[5]; writeSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w, ucOld | ucNew); } unData.abPlain[4] = readSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w); break; case SV_WRITE_QUAD: if (!CheckAddressRange(unData.stDecoded.unVendorIdOrSvAddress.w, 4)) return SV_ERROR; writeSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w+0, unData.abPlain[4]); writeSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w+1, unData.abPlain[5]); writeSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w+2, unData.abPlain[6]); writeSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w+3, unData.abPlain[7]); // fall through intended! case SV_READ_QUAD: if (!CheckAddressRange(unData.stDecoded.unVendorIdOrSvAddress.w, 4)) return SV_ERROR; unData.abPlain[4] = readSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w+0); unData.abPlain[5] = readSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w+1); unData.abPlain[6] = readSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w+2); unData.abPlain[7] = readSVStorage(unData.stDecoded.unVendorIdOrSvAddress.w+3); break; case SV_DISCOVER: DeferredSrcAddr = LnPacket->sv.src ; DeferredProcessingRequired = 1 ; return SV_DEFERRED_PROCESSING_NEEDED ; break; case SV_IDENTIFY: unData.stDecoded.unDestinationId.w = readSVDestinationId(); unData.stDecoded.unVendorIdOrSvAddress.w = SV_VENDOR_ID; unData.stDecoded.unDeviceId.w = SV_DEVICE_ID; unData.stDecoded.unSerialNumber.b.lo = readSVStorage(SV_ADDR_SERIAL_NUMBER_L); unData.stDecoded.unSerialNumber.b.hi = readSVStorage(SV_ADDR_SERIAL_NUMBER_H); break; case SV_CHANGE_ADDRESS: if(SV_VENDOR_ID != unData.stDecoded.unVendorIdOrSvAddress.w) return SV_OK; // not addressed if(SV_DEVICE_ID != unData.stDecoded.unDeviceId.w) return SV_OK; // not addressed if(readSVStorage(SV_ADDR_SERIAL_NUMBER_L) != unData.stDecoded.unSerialNumber.b.lo) return SV_OK; // not addressed if(readSVStorage(SV_ADDR_SERIAL_NUMBER_H) != unData.stDecoded.unSerialNumber.b.hi) return SV_OK; // not addressed if (writeSVDestinationId(unData.stDecoded.unDestinationId.w) != 0) { SendLAck(44); // failed to change address (not implemented or failed to write) return SV_OK ; // the LN reception was ok, we processed the message } break; case SV_RECONFIGURE: break; // actual handling is done after sending out the reply default: SendLAck(43); // not yet implemented return SV_ERROR; } encodePeerData( &LnPacket->px, unData.abPlain ); // recycling the received packet LnPacket->sv.sv_cmd |= 0x40; // flag the message as reply sendLocoNetPacket(LnPacket); // send successful reply if (LnPacket->sv.sv_cmd == (SV_RECONFIGURE | 0x40)) { wdt_enable(WDTO_15MS); // prepare for reset while (1) {} // stop and wait for watchdog to knock us out } return SV_OK ; }
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 } }