diff --git a/TeensyPwm.cpp b/TeensyPwm.cpp index 670269c..a472c71 100644 --- a/TeensyPwm.cpp +++ b/TeensyPwm.cpp @@ -37,11 +37,11 @@ const float Ctrl_P = 5.0; const float Ctrl_I = 2.0; const float Ctrl_D = 0.0; -const float U_des = 12.0; +volatile float U_des = 12.0; LiquidCrystal lcd(LCD_RS, LCD_E, LCD_D4, LCD_D5, LCD_D6, LCD_D7); -Control ctrl((float)PWM_MIN, (float)PWM_MAX, Ctrl_P, Ctrl_I, Ctrl_D); +volatile Control ctrl((float)PWM_MIN, (float)PWM_MAX, Ctrl_P, Ctrl_I, Ctrl_D); @@ -49,43 +49,47 @@ void setup() { lcd.begin(LCD_COLS, LCD_ROWS); lcd.print("Teensy SMPS"); pinMode(PWM_PIN, OUTPUT); + analogWrite(PWM_PIN, 0); analogWriteFrequency(PWM_PIN, PWM_FREQ); analogWriteResolution(PWM_RES); + attachInterrupt(PWM_PIN, cycle, RISING); analogReadResolution(ADC_RES); analogReference(DEFAULT); // analogReadAveraging(16); pinMode(ADC_IN, INPUT); - analogWrite(PWM_PIN, 0); +} + + +volatile uint32_t lastCycle = 0; +volatile float u_curr = 0; +volatile uint16_t newPwm = 0; +volatile uint32_t cycleDelay = 0; +volatile uint32_t maxCycleDelay = 0; + +void cycle() { + uint32_t currentTime = micros(); + cycleDelay = currentTime - lastCycle; + if (cycleDelay > maxCycleDelay) { + maxCycleDelay = cycleDelay; + } + lastCycle = currentTime; + uint16_t adcIn = analogRead(ADC_IN); + float u_adc = ((float)adcIn) * U_ref / ((float)ADC_MAX); + u_curr = u_adc * (R_top + R_bottom) / R_bottom; + + float newPwm_f = ctrl.cycle(U_des, u_curr); + newPwm = (uint16_t) newPwm_f; + + analogWrite(PWM_PIN, newPwm); } void loop() { - static uint32_t lastCycle = 0; - static float u_curr = 0; - static uint16_t newPwm = 0; - static uint32_t cycleDelay = 0; - static uint32_t maxCycleDelay = 0; - static uint32_t cycleCnt = 0; - uint32_t currentTime = micros(); - if ((lastCycle + CYCLE_TIME <= currentTime) || (lastCycle > currentTime)) { - cycleDelay = currentTime - lastCycle; - if (cycleDelay > maxCycleDelay) { - maxCycleDelay = cycleDelay; - } - lastCycle = currentTime; - uint16_t adcIn = analogRead(ADC_IN); - float u_adc = ((float)adcIn) * U_ref / ((float)ADC_MAX); - u_curr = u_adc * (R_top + R_bottom) / R_bottom; - - float newPwm_f = ctrl.cycle(U_des, u_curr); - newPwm = (uint16_t) newPwm_f; - - analogWrite(PWM_PIN, newPwm); - } static uint32_t lastDisplayCycle = 0; + static uint32_t cycleCnt = 0; currentTime = micros(); if ((lastDisplayCycle + DISPLAY_UPDATE_TIME <= currentTime) || (lastDisplayCycle > currentTime)) { lastDisplayCycle = currentTime; @@ -102,8 +106,9 @@ void loop() { lcd.print(maxCycleDelay); float dutyCycle = ((float)newPwm) / ((float)PWM_MAX) * 100.0; lcd.setCursor(8, 1); - lcd.print(dutyCycle); - lcd.print("%"); +// lcd.print(dutyCycle); +// lcd.print("%"); + lcd.print(cycleDelay); } }