/*----------------------------------------------------------------------------- * main */ int main(void) { uint8_t ret; int sioHdl; /* set clock prescaler to 2 (set clock to 7.3928 MHz) */ CLKPR = 1 << CLKPCE; CLKPR = 1; /* get module address from EEPROM */ sMyAddr = eeprom_read_byte((const uint8_t *)MODUL_ADDRESS); GetClientListFromEeprom(); PortInit(); TimerInit(); ButtonInit(); PwmInit(); ApplicationInit(); SioInit(); SioRandSeed(sMyAddr); /* sio for bus interface */ sioHdl = SioOpen("USART1", eSioBaud9600, eSioDataBits8, eSioParityNo, eSioStopBits1, eSioModeHalfDuplex); SioSetIdleFunc(sioHdl, IdleSio1); SioSetTransceiverPowerDownFunc(sioHdl, BusTransceiverPowerDown); BusTransceiverPowerDown(true); BusInit(sioHdl); spBusMsg = BusMsgBufGet(); /* warten for full operation voltage */ while (!POWER_GOOD); /* enable ints before RestorePwm() */ ENABLE_INT; TimerStart(); RestorePwm(); /* ext int for power fail: INT0 low level sensitive */ EICRA &= ~((1 << ISC01) | (1 << ISC00)); EIMSK |= (1 << INT0); ApplicationStart(); /* Hauptschleife */ while (1) { Idle(); ret = BusCheck(); ProcessBus(ret); CheckButton(); PwmCheck(); ApplicationCheck(); CheckEvent(); } return 0; }
static DeviceStatus_TYPE _drv_devinit(pDeviceAbstract pdev){ //PWM in standard mode PwmInit(UCLK_2,PWMCON0_PWMIEN_DIS,PWMCON0_SYNC_DIS,PWMCON1_TRIPEN_DIS); //UCLK/2 to PWM, Enable IRQs _pwm_heat_pins_disable(); _pwm_rhref_pins_disable(); //The length of the PWM period is defined by PWMxLEN. Each pair has an associated counter. //the PWMxCOMx MMRs controls the point at which the PWM output changes state //PWM 1 must have a duty cycle <=PWM0 return DEVICE_OK; }
void System_Config(void) { LED_GPIO_Config(); USART2_DT_Config(); SPI2_Init(); AT25512_SPI_GPIO_Config(); PwmInit(); Timer5Init(); Timer3Init(); Receive_Config(); SPI4_Config(); MS5803_Config(); MPU9250_Config(); mavlink_int(); }
//###########################################################################// // MAIN ROUTINE // //###########################################################################// // void main(void) { // --- Initialisation // _SOURCE_ DeviceInit(); // DeviceInit.c GpioInit(); // GpioInit.c PwmInit(); // PwmInit.c CpuTimer0Regs.PRD.all = mSec100; // Flag CpuTimer0 every 100ms [100ms*2 (# of LED states) = 0.2s blink rate] // --- Infinite Loop while(1) { if(CpuTimer0Regs.TCR.bit.TIF == 1) // Flag check { CpuTimer0Regs.TCR.bit.TIF = 1; // Clear flag GpioDataRegs.GPBTOGGLE.bit.GPIO34 = 1; // Toggle GPIO34 (LED) } } }
/**************************************************************************** Function: int main(void) Summary: main function Description: main function Precondition: None Parameters: None Return Values: int - exit code for main function Remarks: None ***************************************************************************/ int main(void) { DWORD size = 0; BOOL responseNeeded; BYTE mode = 0; BYTE wasMode = 0; BYTE pushButtonValues = 0xFF; BYTE potPercentage = 0xFF; BOOL buttonsNeedUpdate = FALSE; BOOL potNeedsUpdate = FALSE; BOOL motorON = FALSE; BOOL readyToRead = TRUE; BOOL writeInProgress = FALSE; BYTE tempValue = 0xFF; BYTE errorCode; ACCESSORY_APP_PACKET* command_packet = NULL; CLKDIV = 0; /* set for default clock operations Fcyc = 4MHz */ AD1PCFGL = 0xffff; AD1PCFGH = 0x0003; BOOL connected_to_app = FALSE; BOOL need_to_disconnect_from_app = FALSE; #if defined(__PIC32MX__) InitPIC32(); #endif #if defined(__dsPIC33EP512MU810__) || defined (__PIC24EP512GU810__) // Configure the device PLL to obtain 60 MIPS operation. The crystal // frequency is 8MHz. Divide 8MHz by 2, multiply by 60 and divide by // 2. This results in Fosc of 120MHz. The CPU clock frequency is // Fcy = Fosc/2 = 60MHz. Wait for the Primary PLL to lock and then // configure the auxilliary PLL to provide 48MHz needed for USB // Operation. PLLFBD = 38; /* M = 60 */ CLKDIVbits.PLLPOST = 0; /* N1 = 2 */ CLKDIVbits.PLLPRE = 0; /* N2 = 2 */ OSCTUN = 0; /* Initiate Clock Switch to Primary * Oscillator with PLL (NOSC= 0x3)*/ __builtin_write_OSCCONH(0x03); __builtin_write_OSCCONL(0x01); while (OSCCONbits.COSC != 0x3); // Configuring the auxiliary PLL, since the primary // oscillator provides the source clock to the auxiliary // PLL, the auxiliary oscillator is disabled. Note that // the AUX PLL is enabled. The input 8MHz clock is divided // by 2, multiplied by 24 and then divided by 2. Wait till // the AUX PLL locks. ACLKCON3 = 0x24C1; ACLKDIV3 = 0x7; ACLKCON3bits.ENAPLL = 1; while(ACLKCON3bits.APLLCK != 1); TRISBbits.TRISB5 = 0; LATBbits.LATB5 = 1; #endif USBInitialize(0); AndroidAppStart(&myDeviceInfo); responseNeeded = FALSE; mInitPOT(); InitializeTimer2For_PWM(); PwmInit(); //InitMOTOR(); DEBUG_Init(0); InitAllLEDs(); while(1) { //Keep the USB stack running USBTasks(); //If the device isn't attached yet, if(device_attached == FALSE || mode == 1) { buttonsNeedUpdate = TRUE; potNeedsUpdate = TRUE; need_to_disconnect_from_app = FALSE; connected_to_app = FALSE; size = 0; /**/ BYTE curPush = GetPushbuttons(); if ((curPush == 0x8) || (mode == 1)) { LED0_On(); mode = 1; if (wasMode == 0) { pot2LEDs(); PwmInit(); } tempValue = ReadPOT(); wasMode = 1; //If it is different than the last time we read the pot, then we need // to send it to the Android device if(tempValue != potPercentage) { potNeedsUpdate = TRUE; //setRPM(tempValue); setPWM(); } } if ((curPush == 0x4) || (mode == 0)) { mode = 0; //LED0_Off(); if (wasMode == 1) { SetLEDs(0b00000000); wasMode = 0; setRPM(0); } //Reset the accessory state variables InitAllLEDs(); //Continue to the top of the while loop to start the check over again. continue; } /* //Reset the accessory state variables InitAllLEDs(); //Continue to the top of the while loop to start the check over again. continue; }*/ //} } //If the accessory is ready, then this is where we run all of the demo code if(readyToRead == TRUE && mode == 0) { errorCode = AndroidAppRead(device_handle, (BYTE*)&read_buffer, (DWORD)sizeof(read_buffer)); //If the device is attached, then lets wait for a command from the application if( errorCode != USB_SUCCESS) { //Error DEBUG_PrintString("Error trying to start read"); } else { readyToRead = FALSE; } } size = 0; if(AndroidAppIsReadComplete(device_handle, &errorCode, &size) == TRUE) { //We've received a command over the USB from the Android device. if(errorCode == USB_SUCCESS) { //Maybe process the data here. Maybe process it somewhere else. command_packet = (ACCESSORY_APP_PACKET*)&read_buffer[0]; } else { //Error DEBUG_PrintString("Error trying to complete read request"); } } while(size > 0) { if(connected_to_app == FALSE) { if(command_packet->command == COMMAND_APP_CONNECT) { connected_to_app = TRUE; need_to_disconnect_from_app = FALSE; } } else { switch(command_packet->command) { case COMMAND_SET_LEDS: SetLEDs(command_packet->data); break; case COMMAND_APP_DISCONNECT: need_to_disconnect_from_app = TRUE; break; case COMMAND_SET_PWM: setRPM(command_packet->data); break; default: //Error, unknown command DEBUG_PrintString("Error: unknown command received"); break; } } //All commands in this example are two bytes, so remove that from the queue size -= 2; //And move the pointer to the next packet (this works because // all command packets are 2 bytes. If variable packet size // then need to handle moving the pointer by the size of the // command type that arrived. command_packet++; if(need_to_disconnect_from_app == TRUE) { break; } } if(size == 0) { readyToRead = TRUE; } //Get the current pushbutton settings tempValue = GetPushbuttons(); //If the current button settings are different than the last time // we read the button values, then we need to send an update to the // attached Android device if(tempValue != pushButtonValues) { buttonsNeedUpdate = TRUE; pushButtonValues = tempValue; } //Get the current potentiometer setting tempValue = ReadPOT(); //If it is different than the last time we read the pot, then we need // to send it to the Android device if(tempValue != potPercentage) { potNeedsUpdate = TRUE; potPercentage = tempValue; } //If there is a write already in progress, we need to check its status if( writeInProgress == TRUE ) { if(AndroidAppIsWriteComplete(device_handle, &errorCode, &size) == TRUE) { writeInProgress = FALSE; if(need_to_disconnect_from_app == TRUE) { connected_to_app = FALSE; need_to_disconnect_from_app = FALSE; } if(errorCode != USB_SUCCESS) { //Error DEBUG_PrintString("Error trying to complete write"); } } } if((need_to_disconnect_from_app == TRUE) && (writeInProgress == FALSE)) { outgoing_packet.command = COMMAND_APP_DISCONNECT; outgoing_packet.data = 0; writeInProgress = TRUE; errorCode = AndroidAppWrite(device_handle,(BYTE*)&outgoing_packet, 2); if( errorCode != USB_SUCCESS ) { DEBUG_PrintString("Error trying to send button update"); } } if(connected_to_app == FALSE) { //If the app hasn't told us to start sending data, let's not do anything else. continue; } //If we need up update the button status on the Android device and we aren't // already busy in a write, then we can send the new button data. if((buttonsNeedUpdate == TRUE) && (writeInProgress == FALSE)) { outgoing_packet.command = COMMAND_UPDATE_PUSHBUTTONS; outgoing_packet.data = pushButtonValues; errorCode = AndroidAppWrite(device_handle,(BYTE*)&outgoing_packet, 2); if( errorCode != USB_SUCCESS ) { DEBUG_PrintString("Error trying to send button update"); } buttonsNeedUpdate = FALSE; writeInProgress = TRUE; } //If we need up update the pot status on the Android device and we aren't // already busy in a write, then we can send the new pot data. if((potNeedsUpdate == TRUE) && (writeInProgress == FALSE)) { outgoing_packet.command = COMMAND_UPDATE_POT; outgoing_packet.data = potPercentage; errorCode = AndroidAppWrite(device_handle,(BYTE*)&outgoing_packet, 2); if( errorCode != USB_SUCCESS ) { DEBUG_PrintString("Error trying to send pot update"); } potNeedsUpdate = FALSE; writeInProgress = TRUE; } } //while(1) main loop }
void main(void) { int i=0; // Loop Variable timeout_ctr = 0 ; //############################ Initialisation ###############################// // _SOURCE_ DeviceInit(); // DeviceInit.c InitGpio(); // GpioInit.c InitPieVectTable(); // PieVect.c InitPieCtrl(); // PieCtrl.c InitSci(); // Serial.c init_lcd_menu(); // LcdMenu.c lcd_init(); // LcdDriver.c SineRefInit(); // SineRefInit.c AdcInit(); // AdcInit.c PwmInit(); // PwmInit.c State.all = 0; State.bit.Start = 1; PeripheralEn.bit.Buttons= 1; // Allow button checks EnableInterrupts(); // PieCtrl.c DisableInverter(); // Ensure inverter is disabled on start-up lcd_position(0x5,0x0); lcd_puts("Kingfisher"); // Print introductory message on top line lcd_position(0x0,0x1); // Start Cursor From First Line lcd_puts(" Hydro Controller "); // Print introductory message on bottom line asm(" CLRC INTM, DBGM"); // Enable global interrupts and real-time debug CpuTimer0Regs.PRD.all = COUNTER0_PRD; // Initialise CPU timer0 CpuTimer1Regs.PRD.all = COUNTER1_PRD; // Initialise CPU timer0 //############################# Polling Loop ################################// while(1) { //#######################################################################// // STATES // //#######################################################################// // //############################ START STATE ##############################// if(State.bit.Start) { asm("NOP"); } //######################### EXCITATION STATE ############################// if (State.bit.Excitation) { data_out.bit.led_ctrl_green = 1; data_out.bit.led_ctrl_red = 0; if ( (AdcSignal.V_HVDC < 50) && (AdcSignal.Shaft_Velocity > 2000) && !(State.bit.Fault) ) { // PeripheralEn.bit.Buttons= 0; timeout_ctr++; if (timeout_ctr > 3) { State.all = 0; State.bit.Fault = 1; timeout_ctr = 0; } else { data_out.bit.startup = 1; shift_data_out(); if (CpuTimer0Regs.TCR.bit.TIF == 1) { for (i=1;i<=2;i++) // wait 2 seconds { CpuTimer0Regs.TCR.bit.TIF = 1; // Clear flag while(!CpuTimer0Regs.TCR.bit.TIF); } } data_out.bit.startup = 0; shift_data_out(); if (CpuTimer0Regs.TCR.bit.TIF == 1) { for(i=1;i<=3;i++) // wait 3 seconds { CpuTimer0Regs.TCR.bit.TIF = 1; // Clear flag while(!CpuTimer0Regs.TCR.bit.TIF); } } } } else if ( (AdcSignal.V_HVDC >= 50) && (AdcSignal.V_HVDC < 250) ) { timeout_ctr = 0; State.all = 0; State.bit.Excited = 1; // Perhaps change LCD Screen to message saying "Slowly increase turbine speed to increase voltage." } else if ( (AdcSignal.V_HVDC > 250) ) { timeout_ctr = 0; // Resets the timeout counter for excitation State.all = 0; State.bit.StartupSequence = 1; } } //############################ EXCITED STATE ############################// if (State.bit.Excited) { if (AdcSignal.V_HVDC > 250) { timeout_ctr = 0; // Resets the timeout counter for excitation State.all = 0; State.bit.StartupSequence = 1; } else { // !!!!! ADD SOME CODE FOR THIS CONDITION !!!!! } } //############################# FAULT STATE #############################// if (State.bit.Fault) { if (PeripheralEn.bit.Inverter) { DisableInverter(); data_out.bit.led_dump1 = 0; data_out.bit.led_dump2 = 0; data_out.bit.led_inverter = 0; data_out.bit.led_update = 0; } data_out.bit.protect_trig = 1; data_out.bit.led_ctrl_green = 0; data_out.bit.led_ctrl_red = 1; if ( !(LED_Fault_Ctr++ % 16384) ) { data_out.bit.led_dump1 = ~(data_out.bit.led_dump1); data_out.bit.led_dump2 = ~(data_out.bit.led_dump2); data_out.bit.led_inverter = ~(data_out.bit.led_inverter); data_out.bit.led_update = ~(data_out.bit.led_update); } } //########################### DC STABLE STATE ###########################// if (State.bit.DcStable) { if ( !(PeripheralEn.bit.Inverter) ) EnableInverter(); data_out.bit.led_ctrl_green = 1; data_out.bit.led_ctrl_red = 0; } //############################## TEST STATE #############################// if (State.bit.Test) { } //########################### TURNED OFF STATE ##########################// if (State.bit.TurnOff) { data_out.bit.led_ctrl_green = 0; data_out.bit.led_ctrl_red = 0; data_out.bit.led_dump1 = 0; data_out.bit.led_dump2 = 0; data_out.bit.led_inverter = 0; data_out.bit.led_update = 0; } //#######################################################################// // FLAGS // //#######################################################################// // //######################## SCREEN UPDATE FLAG #######################// if (flag_bc) { menu_update_lcd(); flag_bc = 0; } asm(" nop"); //########################### READ IN DATA FLAG #########################// if (flag.bit.DataIN) { shift_data_in(); check_buttons(); flag.bit.DataIN = 0; } //########################## SEND OUT DATA FLAG #########################// if (flag.bit.DataOUT) { shift_data_out(); flag.bit.DataOUT = 0; } //######################## HVDC VOLTAGE REGULATION ######################// if (flag.bit.V_HVDC) { if ( !(State.bit.TurnOff) && !(State.bit.Fault) ) { V_DcError = V_DC_REF - AdcSignal.V_HVDC; // Calculate the DC error from the reference DutyError = 0.75*K_DC*V_DcError + 0.25*DutyError; // Modify the dump load duty cycle with respect to the DC error if (V_DcError > 0) // If the DC voltage is less than the reference, dump no power { EPwm3Regs.CMPA.half.CMPA= 0; EPwm3Regs.CMPB = 0; } else if (DutyError > DUMP1_DUTY_MAX) { DutyFeedback = 1.0*(DUMP1_DUTY_MAX)*DUMP_PRD; EPwm3Regs.CMPA.half.CMPA= DutyFeedback; DutyFeedback = 1.0*(DutyError - DUMP1_DUTY_MAX)*DUMP_PRD; EPwm3Regs.CMPB = DutyFeedback; } else { DutyFeedback = 1.0*(DutyError)*DUMP_PRD; EPwm3Regs.CMPA.half.CMPA= DutyFeedback; EPwm3Regs.CMPB = 0; } }else // If there is a fault or the system is off, dump all power { EPwm3Regs.CMPA.half.CMPA = (DUMP1_DUTY_MAX)*DUMP_PRD; // Dump all power! EPwm3Regs.CMPB = DUMP_PRD; // Dump all power! } flag.bit.V_HVDC = 0; // Reset the flag } //###################### SHAFT VELOCITY MEASUREMENT #####################// if (ShaftVelocCtr >= 1000) // Updates the measured velocity every 1000*(1/EPWM8) = 0.5s { AdcSignal.Shaft_Velocity = shaftspeedtest; //0.8*(ShaftPulseCtr/0.5)*60 + 0.2*AdcSignal.Shaft_Velocity; // Where 1 pulse = 1 rotation ShaftPulseCtr = 0; // { Reset counters ShaftVelocCtr = 0; // { } //################### OUTPUT AC VOLTAGE FREQUENCY MEASURE ################// if (V_AcOutPrdCtr >= 10) { AdcSignal.V_AcOut_Freq = (SYSCLK/ADC_SAMP_PRD+1)*(V_AcOutPrdCtr/FreqOutDivCtr); // Approximate frequency over at least 10 periods AcOutFreqError = AC_OUT_FREQ - AdcSignal.V_AcOut_Freq; // Find frequency error V_AcOutReqFreq = V_AcOutReqFreq + 0.05*AcOutFreqError; // Frequency feedback loop sinGen.freq = V_AcOutReqFreq*(BIT31)*(2*BIT32*INVERTER_PWM_PRD)*(1/(sinGen.step_max*SYSCLK)); // Alter reference sine wave frequency V_AcOutPrdCtr = 0 ; // } FreqOutDivCtr = 0 ; // } Reset counters } //####################### INVERTER CONTROL #######################// if (flag.bit.Inverter) { /* BROKEN InverterMaxDuty = V_AC_OUT_REF*(1.0/(AdcSignal.V_HVDC)); // Find the maximum duty cycle necessary to create Vacoutpeak=325V DutyScaleMax = (BIT16*InverterMaxDuty-BIT15)*30.51850948e-6; // 30.51850948e-6 = 1/(BIT15-1) if ( !(State.bit.InvSoftStart) ) { DutyScaleError = DutyScaleMax - DutyScale; DutyScale = DutyScale + 0.01*DutyScaleError; if (DutyScale < 0.2) { DutyScale = 0.2; ADD SOME CODE IN CASE IT IS DANGEROUS TO GO BELOW 0.2 } } */ // ----- Toggle the onboard LED to show inverter control is active if (GPIO34_count >= 4000) // toggle_time = GPIO34_count_limit/fpwm { GpioDataRegs.GPBTOGGLE.bit.GPIO34 = 1; // Toggle the pin GPIO34_count = 0; // Reset the count } flag.bit.Inverter = 0; } //################### INPUT AC VOLTAGE FREQUENCY MEASURE ################// if (V_AcInPrdCtr >= 10) { AdcSignal.V_AcIn_Freq = 0.8*((SYSCLK/ADC_SAMP_PRD+1)*(V_AcInPrdCtr/FreqInDivCtr)) + 0.2*(AdcSignal.V_AcIn_Freq); // Approximate frequency over at least 10 periods genSlip = 100*((AdcSignal.V_AcIn_Freq*60) - (AdcSignal.Shaft_Velocity))/(AdcSignal.V_AcIn_Freq*60); // Calculates slip: s= 100%*((ns-nr)/ns) V_AcInPrdCtr = 0 ; // } FreqInDivCtr = 0 ; // } Reset counters } /* if(SendADCResult) { SendADCResult = 0; SerialSendStr("Voltage: "); SerialSendInt((int)V_DC_measured); SerialSendStr(" PWM1: "); SerialSendInt((int)(EPwm3Regs.CMPA.half.CMPA*100.0/(DUMP_PRD*1.0))); SerialSendCR(); SerialSendStr(" PWM2: "); SerialSendInt((int)((EPwm3Regs.CMPB*100.0)/(DUMP_PRD*1.0))); SerialSendCR(); }*/ } }