Austin Brown
/
2171_MicroLab_3
Make 2171 Great Again
Embed:
(wiki syntax)
Show/hide line numbers
main.cpp
00001 #include "mbed.h" 00002 #include "HWsetup.h" 00003 00004 //MicroLab, simplified. No DSA. 00005 00006 00007 DigitalOut ledpin(LED1); // LED output 00008 AnalogOut dac_1(PA_4); // DAC output pin 00009 DigitalOut comp_time(PA_12); // D2 00010 DigitalOut ref_trig(D6); 00011 00012 00013 00014 Serial pc(PA_2, PA_3); 00015 int Lcount = 0; 00016 float U_ref = 0.0f; 00017 float U = 0.0f; 00018 float Uv = 0.0f; 00019 float Y = 0.0f; 00020 int Yint = 0; 00021 float ctrl_error = 0.0f; 00022 00023 00024 extern "C" void TIM1_UP_TIM16_IRQHandler(void) { 00025 00026 if (TIM1->SR & TIM_SR_UIF ) { 00027 //comp_time = 1; 00028 if ( TIM1->CR1 & TIM_CR1_DIR ) { 00029 00030 comp_time = 1; 00031 00032 while ((ADC1->ISR) & ADC_ISR_EOC == 0 ) {} // wait til ADC finishes conversion 00033 DAC->DHR12R1 = (ADC1->DR); // set ADC value to DAC 00034 00035 //set reference 00036 if (Lcount == 250) { U_ref = 0.050f; ref_trig = 1;} //50 mA 00037 if (Lcount == 500) {Lcount = 0, U_ref = 0.025f; ref_trig = 0;} //25 mA 00038 Lcount++; 00039 00040 00041 // fix these 00042 float ADC_gain = 1.0f; 00043 float Current_gain = 1.0f; 00044 Uv = int(ADC1->DR) * ADC_gain; // get ADC input in volts 00045 U = Uv * Current_gain; // get U in amps, divide by resistor divider gain 00046 00047 00048 00049 //controller 00050 ctrl_error = U_ref-U; 00051 00052 // Bang-bang controller is written below. Replace this with your PI controller. 00053 00054 if (U > 4096*0.4f) { Y = 0.3f*1440.0f; } // ADC readings scaled correctly 00055 if (U < 4096*0.2f) { Y = 0.7f*1440.0f; } 00056 00057 00058 // end controller 00059 00060 float PWM_gain = 1.0f; // fix this 00061 00062 Yint = Y*PWM_gain; //convert Y to integer and scale 00063 if (Yint > 1430) { Yint = 1430; } // constrain 00064 if (Yint < 0) { Yint = 0; } 00065 00066 TIM1->CCR1 = Yint; // set duty cycle 00067 00068 00069 00070 00071 } 00072 comp_time = 0; 00073 } 00074 TIM1->SR = 0x0; 00075 } 00076 00077 00078 int main() { 00079 00080 wait_ms(200); 00081 pc.baud(115200); 00082 pc.printf(" bumping clock "); // set micro freq to 72MHz 00083 BumpClock(); // must be done before PWM setup, otherwise RCC gets confused 00084 pc.baud(102400); // actually 115200 00085 pc.printf(" clock ready "); 00086 wait_ms(50); 00087 Init_All_HW(); // Setup PWM, ADC 00088 wait_ms(50); 00089 Init_ADC_Tim_Sync(); 00090 wait_ms(5); 00091 TIM1->BDTR |= TIM_BDTR_MOE; // enable switching 00092 TIM1->DIER |= TIM_DIER_UIE; // start interrupt 00093 wait_ms(5); 00094 00095 while(1) { 00096 //while(1) {} 00097 00098 00099 ledpin = !ledpin; // toggle LED 00100 pc.printf(" ADC raw: %i ",ADC1->DR); 00101 pc.printf("U, amps: %f ",U); 00102 pc.printf(" Y, volts: %f ",Y); 00103 pc.printf(" Y, PWM counts: %i ",Yint); 00104 pc.printf(" \r\n"); 00105 00106 00107 00108 00109 } 00110 }
Generated on Thu Jul 14 2022 17:13:08 by 1.7.2