From 663f15a9b2b1175b2c5e344ff3f30fc9cde37222 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Martin=20J=C3=A4ger?= Date: Tue, 2 Aug 2016 14:05:23 +0200 Subject: [PATCH] Initial commit --- .gitignore | 3 + .travis.yml | 65 +++++ lib/DogLCD/DogLCD.cpp | 319 ++++++++++++++++++++++ lib/DogLCD/DogLCD.h | 94 +++++++ lib/DogLCD/font_16x32nums.h | 92 +++++++ lib/DogLCD/font_6x8.h | 120 ++++++++ lib/DogLCD/font_8x16.h | 120 ++++++++ lib/DogLCD/font_8x8.h | 120 ++++++++ lib/HalfBridge/HalfBridge.cpp | 169 ++++++++++++ lib/HalfBridge/HalfBridge.h | 86 ++++++ lib/PID/PID.cpp | 324 ++++++++++++++++++++++ lib/PID/PID.h | 213 +++++++++++++++ lib/readme.txt | 38 +++ platformio.ini | 33 +++ src/main.cpp | 498 ++++++++++++++++++++++++++++++++++ stlink_extra_script.py | 15 + 16 files changed, 2309 insertions(+) create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 lib/DogLCD/DogLCD.cpp create mode 100644 lib/DogLCD/DogLCD.h create mode 100644 lib/DogLCD/font_16x32nums.h create mode 100644 lib/DogLCD/font_6x8.h create mode 100644 lib/DogLCD/font_8x16.h create mode 100644 lib/DogLCD/font_8x8.h create mode 100644 lib/HalfBridge/HalfBridge.cpp create mode 100644 lib/HalfBridge/HalfBridge.h create mode 100644 lib/PID/PID.cpp create mode 100644 lib/PID/PID.h create mode 100644 lib/readme.txt create mode 100644 platformio.ini create mode 100644 src/main.cpp create mode 100644 stlink_extra_script.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7f52f2d --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.pioenvs +.clang_complete +.gcc-flags.json \ No newline at end of file diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..b57f6fa --- /dev/null +++ b/.travis.yml @@ -0,0 +1,65 @@ +# Continuous Integration (CI) is the practice, in software +# engineering, of merging all developer working copies with a shared mainline +# several times a day < http://docs.platformio.org/en/latest/ci/index.html > +# +# Documentation: +# +# * Travis CI Embedded Builds with PlatformIO +# < https://docs.travis-ci.com/user/integration/platformio/ > +# +# * PlatformIO integration with Travis CI +# < http://docs.platformio.org/en/latest/ci/travis.html > +# +# * User Guide for `platformio ci` command +# < http://docs.platformio.org/en/latest/userguide/cmd_ci.html > +# +# +# Please choice one of the following templates (proposed below) and uncomment +# it (remove "# " before each line) or use own configuration according to the +# Travis CI documentation (see above). +# + + +# +# Template #1: General project. Test it using existing `platformio.ini`. +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# install: +# - pip install -U platformio +# +# script: +# - platformio run + + +# +# Template #2: The project is intended to by used as a library with examples +# + +# language: python +# python: +# - "2.7" +# +# sudo: false +# cache: +# directories: +# - "~/.platformio" +# +# env: +# - PLATFORMIO_CI_SRC=path/to/test/file.c +# - PLATFORMIO_CI_SRC=examples/file.ino +# - PLATFORMIO_CI_SRC=path/to/test/directory +# +# install: +# - pip install -U platformio +# +# script: +# - platformio ci --lib="." --board=TYPE_1 --board=TYPE_2 --board=TYPE_N diff --git a/lib/DogLCD/DogLCD.cpp b/lib/DogLCD/DogLCD.cpp new file mode 100644 index 0000000..3018372 --- /dev/null +++ b/lib/DogLCD/DogLCD.cpp @@ -0,0 +1,319 @@ + /* mbed Library for EA DOG display + * + * This library is partly based on mbed DogLCD class by Igor Skochinsky and + * the official Electronic Assembly library for Arduino + */ + + +#include "DogLCD.h" + +// macro to make sure x falls into range from low to high (inclusive) +#define CLAMP(x, low, high) { if ( (x) < (low) ) x = (low); if ( (x) > (high) ) x = (high); } while (0); + +void DogLCD::_send_commands(const unsigned char* buf, size_t size) +{ + // for commands, A0 is low +#ifdef READJUST_SPI_FREQUENCY + _spi.format(8,0); + _spi.frequency(10000000); +#endif + _cs = 0; + _a0 = 0; + while ( size-- > 0 ) + _spi.write(*buf++); + _cs = 1; +} + +void DogLCD::_send_data(const unsigned char* buf, size_t size) +{ + // for data, A0 is high +#ifdef READJUST_SPI_FREQUENCY + _spi.format(8,0); + _spi.frequency(10000000); +#endif + _cs = 0; + _a0 = 1; + while ( size-- > 0 ) + _spi.write(*buf++); + _cs = 1; + _a0 = 0; +} + +// set column and page number +// void dog_1701::position(byte column, byte page) +void DogLCD::_set_xy(int x, int y) +{ + int column = x; + int page = y; + + if (_view == VIEW_TOP) + column += 30; + + unsigned char cmd[3]; + cmd[0] = 0x10 + (column>>4); //MSB adress column + cmd[1] = 0x00 + (column&0x0F); //LSB adress column + cmd[2] = 0xB0 + (page&0x0F); //adress page + + /* + //printf("_set_xy(%d,%d)\n", x, y); + CLAMP(x, 0, LCDWIDTH-1); + CLAMP(y, 0, LCDPAGES-1); + unsigned char cmd[3]; + cmd[0] = 0xB0 | (y & 0xF); + cmd[1] = (x & 0xF); + cmd[2] = 0x10 | ((x >> 4) & 0xF); + */ + _send_commands(cmd, 3); +} + +// initialize and turn on the display +void DogLCD::init() +{ + const unsigned char init_seq[] = { + 0x40, //Display start line 0 + 0xa1, //ADC reverse + 0xc0, //Normal COM0...COM63 + 0xa6, //Display normal + 0xa2, //Set Bias 1/9 (Duty 1/65) + 0x2f, //Booster, Regulator and Follower On + 0xf8, //Set internal Booster to 4x + 0x00, + 0x27, //Contrast set + 0x81, + 0x09, + 0xac, //No indicator + 0x00, + 0xaf, //Display on + }; +#ifndef READJUST_SPI_FREQUENCY + _spi.format(8,0); + _spi.frequency(10000000); +#endif + //printf("Reset=L\n"); + _reset = 0; + _cs = 1; + wait_ms(1); + + //printf("Reset=H\n"); + _reset = 1; + wait_ms(5); + //printf("Sending init commands\n"); + _send_commands(init_seq, sizeof(init_seq)); +} + +/*---------------------------- +Func: string +Desc: shows string with selected font on position +Vars: column (0..127/131), page(0..3/7), font adress in programm memory, stringarray +------------------------------*/ +void DogLCD::string(int column, int page, const char *font_adress, const char *str) +{ + unsigned int pos_array; //Postion of character data in memory array + int x, y, column_cnt, width_max; //temporary column and page adress, couloumn_cnt tand width_max are used to stay inside display area + int start_code, last_code, width, page_height, bytes_p_char; //font information, needed for calculation + const char *string; + + start_code = font_adress[2]; //get first defined character + last_code = font_adress[3]; //get last defined character + width = font_adress[4]; //width in pixel of one char + page_height = font_adress[6]; //page count per char + bytes_p_char = font_adress[7]; //bytes per char + + if(page_height + page > 8) //stay inside display area + page_height = 8 - page; + + //The string is displayed character after character. If the font has more then one page, + //the top page is printed first, then the next page and so on + for(y = 0; y < page_height; y++) + { + _set_xy(column, page+y); //set startpositon and page + column_cnt = column; //store column for display last column check + string = str; //temporary pointer to the beginning of the string to print + _cs = 0; + _a0 = 1; + while(*string != 0) + { + if((int)*string < start_code || (int)*string > last_code) //make sure data is valid + string++; + else + { + //calculate positon of ascii character in font array + //bytes for header + (ascii - startcode) * bytes per char) + pos_array = 8 + (unsigned int)(*string++ - start_code) * bytes_p_char; + pos_array += y*width; //get the dot pattern for the part of the char to print + + if(column_cnt + width > 102) //stay inside display area + width_max = 102-column_cnt; + else + width_max = width; + for(x=0; x < width_max; x++) //print the whole string + { + _spi.write(font_adress[pos_array+x]); + //spi_out(pgm_read_byte(&font_adress[pos_array+x])); //double width font (bold) + } + column_cnt += width; + } + } + _cs = 1; + _a0 = 0; + } +} + +/*---------------------------- +Func: view +Desc: ssets the display viewing direction +Vars: direction (top view 0xC8, bottom view (default) = 0xC0) +------------------------------*/ +void DogLCD::view(unsigned int direction) +{ + unsigned char cmd[2]; + + if(direction == VIEW_TOP) + { + cmd[0] = 0xA0; + _view = VIEW_TOP; + } + else + { + cmd[0] = 0xA1; + _view = VIEW_BOTTOM; + } + cmd[1] = direction; + _send_commands(cmd, 2); + + clear_screen(); //Clear screen, as old content is not usable (mirrored) +} + +void DogLCD::send_pic(const unsigned char* data) +{ + //printf("Sending picture\n"); + for (int i=0; i | * | * | + | * | * | + | * | * | + +---+---+ + */ + //printf("fill(x=%d, y=%d, width=%d, height=%d, colour=%x)\n", x, y, width, height, colour); + CLAMP(x, 0, LCDWIDTH-1); + CLAMP(y, 0, LCDHEIGHT-1); + CLAMP(width, 0, LCDWIDTH - x); + CLAMP(height, 0, LCDHEIGHT - y); + int page = y/8; + int firstpage = page; + int partpage = y%8; + if ( partpage != 0 ) + { + // we need to process partial bytes in the top page + unsigned char mask = (1<= 8 ) + { + memset(&_framebuffer[page*LCDWIDTH + x], colour == 0 ? 0 : 0xFF, width); + page++; + height -= 8; + } + if ( height != 0 ) + { + // we need to process partial bytes in the bottom page + unsigned char mask = ~((1<AHBENR |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN; + + // Enable TIM1 clock + RCC->APB2ENR |= RCC_APB2ENR_TIM1EN; + + // Select alternate function mode on PA8 und PB13 + GPIOA->MODER = (GPIOA->MODER & ~(GPIO_MODER_MODER8)) | GPIO_MODER_MODER8_1; + GPIOB->MODER = (GPIOB->MODER & ~(GPIO_MODER_MODER13)) | GPIO_MODER_MODER13_1; + + // Select AF2 on PA8 (TIM1_CH1) + GPIOA->AFR[1] |= 0x2 << ((8 - 8)*4); // AFR[1] for pins 8-15 + + // Select AF2 on PB13 (TIM1_CH1N) + GPIOB->AFR[1] |= 0x2 << ((13 - 8)*4); // AFR[1] for pins 8-15 + + // No prescaler --> timer frequency = 48 MHz + TIM1->PSC = 0; + + // Capture/Compare Mode Register 1 + // OC1M = 110: Select PWM mode 1 on OC1 + // OC1PE = 1: Enable preload register on OC1 (reset value) + TIM1->CCMR1 |= TIM_CCMR1_OC1M_2 | TIM_CCMR1_OC1M_1 | TIM_CCMR1_OC1PE; + + // Capture/Compare Enable Register + // CC1E = 1: Enable the output on OC1 + // CC1P = 0: Active high polarity on OC1 (default) + // CC1NE = 1: Enable the output on OC1N + // CC1NP = 0: Active high polarity on OC1N (default) + TIM1->CCER |= TIM_CCER_CC1E | TIM_CCER_CC1NE;// | TIM_CCER_CC1NP; + + // Control Register 1 + // TIM_CR1_CMS = 01: Select center-aligned mode 1 + // TIM_CR1_CEN = 1: Counter enable + TIM1->CR1 |= TIM_CR1_CMS_0 | TIM_CR1_CEN; + + // Control Register 2 + // OIS1 = OIS1N = 0: Output Idle State is set to off + //TIM1->CR2 |= ; + + // Force update generation (UG = 1) + TIM1->EGR |= TIM_EGR_UG; + + // initialize frequency to set _pwm_resolution + frequency_kHz(1); + + set_duty_cycle(0.5); // safer than 0 for DC/DC +} + +void HalfBridge::frequency_kHz(int freq) { + + _pwm_resolution = SystemCoreClock / (freq * 1000); + + // Auto Reload Register + // center-aligned mode --> divide resolution by 2 + TIM1->ARR = _pwm_resolution / 2; +} + + +void HalfBridge::set_duty_cycle(float duty) { + + float duty_target; + // protection against wrong settings which could destroy the hardware + if (duty < _min_duty) { + duty_target = _min_duty; + } + else if (duty > _max_duty) { + duty_target = _max_duty; + } + else { + duty_target = duty; + } + + TIM1->CCR1 = _pwm_resolution / 2 * duty_target; +} + +void HalfBridge::duty_cycle_step(int delta) +{ + float duty_target; + duty_target = (float)(TIM1->CCR1 + delta) / (_pwm_resolution / 2); + + // protection against wrong settings which could destroy the hardware + if (duty_target < _min_duty) { + set_duty_cycle(_min_duty); + } + else if (duty_target > _max_duty) { + set_duty_cycle(_max_duty); + } + else { + TIM1->CCR1 = TIM1->CCR1 + delta; + } +} + + + +float HalfBridge::get_duty_cycle() { + return (float)(TIM1->CCR1) / (_pwm_resolution / 2);; +} + + +void HalfBridge::deadtime_ns(int deadtime) { + + uint8_t deadtime_clocks = (SystemCoreClock / 1000 / 1000) * deadtime / 1000; + + // Break and Dead-Time Register + // MOE = 1: Main output enable + // OSSR = 0: Off-state selection for Run mode -> OC/OCN = 0 + // OSSI = 0: Off-state selection for Idle mode -> OC/OCN = 0 + TIM1->BDTR |= (deadtime_clocks & (uint32_t)0x7F); // ensure that only the last 7 bits are changed +} + + +void HalfBridge::start() { + + // Break and Dead-Time Register + // MOE = 1: Main output enable + TIM1->BDTR |= TIM_BDTR_MOE; +} + + +void HalfBridge::stop() { + + // Break and Dead-Time Register + // MOE = 1: Main output enable + TIM1->BDTR &= ~(TIM_BDTR_MOE); +} + + +void HalfBridge::lock_settings() { + + // TODO: does not work properly, yet... + + // Break and Dead-Time Register + TIM1->BDTR |= TIM_BDTR_LOCK_1 | TIM_BDTR_LOCK_0; +} + +void HalfBridge::duty_cycle_limits(float min_duty, float max_duty) { + + _min_duty = min_duty; + _max_duty = max_duty; + + // adjust set value to new limits + if (get_duty_cycle() < _min_duty) { + set_duty_cycle(_min_duty); + } + else if (get_duty_cycle() > _max_duty) { + set_duty_cycle(_max_duty); + } +} diff --git a/lib/HalfBridge/HalfBridge.h b/lib/HalfBridge/HalfBridge.h new file mode 100644 index 0000000..a7b9774 --- /dev/null +++ b/lib/HalfBridge/HalfBridge.h @@ -0,0 +1,86 @@ +/* mbed library for half bridge driver PWM generation + * Copyright (c) 2016 Martin Jäger (www.libre.solar) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mbed.h" + +class HalfBridge +{ +public: + + /** Create a half bridge class for the specified pins + * + * @param pin_HS PinName of the high-side output + * @param pin_LS PinName of the low-side output + */ + HalfBridge(PinName pin_HS, PinName pin_LS); + + /** Set the PWM frequency in kHz + * + * @param freq Frequency in kHz + */ + void frequency_kHz(int freq); + + /** Set the deadtime between switching the two FETs on/off + * + * @param deadtime Deadtime in ns + */ + void deadtime_ns(int deadtime); + + /** Lock the settings of PWM generation to prevent accidental changes + * (does not work properly, yet! --> TODO) + */ + void lock_settings(void); + + /** Start the PWM generation + */ + void start(); + + /** Stop the PWM generation + */ + void stop(); + + /** Set the duty cycle of the PWM signal between 0.0 and 1.0 + * + * @param duty Duty cycle between 0.0 and 1.0 + */ + void set_duty_cycle(float duty); + + /** Adjust the duty cycle with minimum step size + * + * @param delta Number of steps (positive or negative) + */ + void duty_cycle_step(int delta); + + /** Read the currently set duty cycle + * + * @returns + * Duty cycle between 0.0 and 1.0 + */ + float get_duty_cycle(); + + /** Set limits for the duty cycle to prevent hardware damages + * + * @param min_duty Minimum duty cycle (e.g. 0.5 for limiting input voltage) + * @param max_duty Maximum duty cycle (e.g. 0.97 for charge pump) + */ + void duty_cycle_limits(float min_duty, float max_duty); + +private: + int _pwm_resolution; + float _min_duty; + float _max_duty; + +}; diff --git a/lib/PID/PID.cpp b/lib/PID/PID.cpp new file mode 100644 index 0000000..9d85064 --- /dev/null +++ b/lib/PID/PID.cpp @@ -0,0 +1,324 @@ +/** + * @author Aaron Berk + * + * @section LICENSE + * + * Copyright (c) 2010 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @section DESCRIPTION + * + * A PID controller is a widely used feedback controller commonly found in + * industry. + * + * This library is a port of Brett Beauregard's Arduino PID library: + * + * http://www.arduino.cc/playground/Code/PIDLibrary + * + * The wikipedia article on PID controllers is a good place to start on + * understanding how they work: + * + * http://en.wikipedia.org/wiki/PID_controller + * + * For a clear and elegant explanation of how to implement and tune a + * controller, the controlguru website by Douglas J. Cooper (who also happened + * to be Brett's controls professor) is an excellent reference: + * + * http://www.controlguru.com/ + */ + +/** + * Includes + */ +#include "PID.h" + +PID::PID(float Kc, float tauI, float tauD, float interval) { + + usingFeedForward = false; + inAuto = false; + + //Default the limits to the full range of I/O: 3.3V + //Make sure to set these to more appropriate limits for + //your application. + setInputLimits(0.0, 3.3); + setOutputLimits(0.0, 3.3); + + tSample_ = interval; + + setTunings(Kc, tauI, tauD); + + setPoint_ = 0.0; + processVariable_ = 0.0; + prevProcessVariable_ = 0.0; + controllerOutput_ = 0.0; + prevControllerOutput_ = 0.0; + + accError_ = 0.0; + bias_ = 0.0; + + realOutput_ = 0.0; + +} + +void PID::setInputLimits(float inMin, float inMax) { + + //Make sure we haven't been given impossible values. + if (inMin >= inMax) { + return; + } + + //Rescale the working variables to reflect the changes. + prevProcessVariable_ *= (inMax - inMin) / inSpan_; + accError_ *= (inMax - inMin) / inSpan_; + + //Make sure the working variables are within the new limits. + if (prevProcessVariable_ > 1) { + prevProcessVariable_ = 1; + } else if (prevProcessVariable_ < 0) { + prevProcessVariable_ = 0; + } + + inMin_ = inMin; + inMax_ = inMax; + inSpan_ = inMax - inMin; + +} + +void PID::setOutputLimits(float outMin, float outMax) { + + //Make sure we haven't been given impossible values. + if (outMin >= outMax) { + return; + } + + //Rescale the working variables to reflect the changes. + prevControllerOutput_ *= (outMax - outMin) / outSpan_; + + //Make sure the working variables are within the new limits. + if (prevControllerOutput_ > 1) { + prevControllerOutput_ = 1; + } else if (prevControllerOutput_ < 0) { + prevControllerOutput_ = 0; + } + + outMin_ = outMin; + outMax_ = outMax; + outSpan_ = outMax - outMin; + +} + +void PID::setTunings(float Kc, float tauI, float tauD) { + + //Verify that the tunings make sense. + if (Kc == 0.0 || tauI < 0.0 || tauD < 0.0) { + return; + } + + //Store raw values to hand back to user on request. + pParam_ = Kc; + iParam_ = tauI; + dParam_ = tauD; + + float tempTauR; + + if (tauI == 0.0) { + tempTauR = 0.0; + } else { + tempTauR = (1.0 / tauI) * tSample_; + } + + //For "bumpless transfer" we need to rescale the accumulated error. + if (inAuto) { + if (tempTauR == 0.0) { + accError_ = 0.0; + } else { + accError_ *= (Kc_ * tauR_) / (Kc * tempTauR); + } + } + + Kc_ = Kc; + tauR_ = tempTauR; + tauD_ = tauD / tSample_; + +} + +void PID::reset(void) { + + float scaledBias = 0.0; + + if (usingFeedForward) { + scaledBias = (bias_ - outMin_) / outSpan_; + } else { + scaledBias = (realOutput_ - outMin_) / outSpan_; + } + + prevControllerOutput_ = scaledBias; + prevProcessVariable_ = (processVariable_ - inMin_) / inSpan_; + + //Clear any error in the integral. + accError_ = 0; + +} + +void PID::setMode(int mode) { + + //We were in manual, and we just got set to auto. + //Reset the controller internals. + if (mode != 0 && !inAuto) { + reset(); + } + + inAuto = (mode != 0); + +} + +void PID::setInterval(float interval) { + + if (interval > 0) { + //Convert the time-based tunings to reflect this change. + tauR_ *= (interval / tSample_); + accError_ *= (tSample_ / interval); + tauD_ *= (interval / tSample_); + tSample_ = interval; + } + +} + +void PID::setSetPoint(float sp) { + + setPoint_ = sp; + +} + +void PID::setProcessValue(float pv) { + + processVariable_ = pv; + +} + +void PID::setBias(float bias){ + + bias_ = bias; + usingFeedForward = 1; + +} + +float PID::compute() { + + //Pull in the input and setpoint, and scale them into percent span. + float scaledPV = (processVariable_ - inMin_) / inSpan_; + + if (scaledPV > 1.0) { + scaledPV = 1.0; + } else if (scaledPV < 0.0) { + scaledPV = 0.0; + } + + float scaledSP = (setPoint_ - inMin_) / inSpan_; + if (scaledSP > 1.0) { + scaledSP = 1; + } else if (scaledSP < 0.0) { + scaledSP = 0; + } + + float error = scaledSP - scaledPV; + + //Check and see if the output is pegged at a limit and only + //integrate if it is not. This is to prevent reset-windup. + if (!(prevControllerOutput_ >= 1 && error > 0) && !(prevControllerOutput_ <= 0 && error < 0)) { + accError_ += error; + } + + //Compute the current slope of the input signal. + float dMeas = (scaledPV - prevProcessVariable_) / tSample_; + + float scaledBias = 0.0; + + if (usingFeedForward) { + scaledBias = (bias_ - outMin_) / outSpan_; + } + + //Perform the PID calculation. + controllerOutput_ = scaledBias + Kc_ * (error + (tauR_ * accError_) - (tauD_ * dMeas)); + + //Make sure the computed output is within output constraints. + if (controllerOutput_ < 0.0) { + controllerOutput_ = 0.0; + } else if (controllerOutput_ > 1.0) { + controllerOutput_ = 1.0; + } + + //Remember this output for the windup check next time. + prevControllerOutput_ = controllerOutput_; + //Remember the input for the derivative calculation next time. + prevProcessVariable_ = scaledPV; + + //Scale the output from percent span back out to a real world number. + return ((controllerOutput_ * outSpan_) + outMin_); + +} + +float PID::getInMin() { + + return inMin_; + +} + +float PID::getInMax() { + + return inMax_; + +} + +float PID::getOutMin() { + + return outMin_; + +} + +float PID::getOutMax() { + + return outMax_; + +} + +float PID::getInterval() { + + return tSample_; + +} + +float PID::getPParam() { + + return pParam_; + +} + +float PID::getIParam() { + + return iParam_; + +} + +float PID::getDParam() { + + return dParam_; + +} diff --git a/lib/PID/PID.h b/lib/PID/PID.h new file mode 100644 index 0000000..089ef32 --- /dev/null +++ b/lib/PID/PID.h @@ -0,0 +1,213 @@ +/** + * @author Aaron Berk + * + * @section LICENSE + * + * Copyright (c) 2010 ARM Limited + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * @section DESCRIPTION + * + * A PID controller is a widely used feedback controller commonly found in + * industry. + * + * This library is a port of Brett Beauregard's Arduino PID library: + * + * http://www.arduino.cc/playground/Code/PIDLibrary + * + * The wikipedia article on PID controllers is a good place to start on + * understanding how they work: + * + * http://en.wikipedia.org/wiki/PID_controller + * + * For a clear and elegant explanation of how to implement and tune a + * controller, the controlguru website by Douglas J. Cooper (who also happened + * to be Brett's controls professor) is an excellent reference: + * + * http://www.controlguru.com/ + */ + +#ifndef PID_H +#define PID_H + +/** + * Includes + */ +#include "mbed.h" + +/** + * Defines + */ +#define MANUAL_MODE 0 +#define AUTO_MODE 1 + +/** + * Proportional-integral-derivative controller. + */ +class PID { + +public: + + /** + * Constructor. + * + * Sets default limits [0-3.3V], calculates tuning parameters, and sets + * manual mode with no bias. + * + * @param Kc - Tuning parameter + * @param tauI - Tuning parameter + * @param tauD - Tuning parameter + * @param interval PID calculation performed every interval seconds. + */ + PID(float Kc, float tauI, float tauD, float interval); + + /** + * Scale from inputs to 0-100%. + * + * @param InMin The real world value corresponding to 0%. + * @param InMax The real world value corresponding to 100%. + */ + void setInputLimits(float inMin , float inMax); + + /** + * Scale from outputs to 0-100%. + * + * @param outMin The real world value corresponding to 0%. + * @param outMax The real world value corresponding to 100%. + */ + void setOutputLimits(float outMin, float outMax); + + /** + * Calculate PID constants. + * + * Allows parameters to be changed on the fly without ruining calculations. + * + * @param Kc - Tuning parameter + * @param tauI - Tuning parameter + * @param tauD - Tuning parameter + */ + void setTunings(float Kc, float tauI, float tauD); + + /** + * Reinitializes controller internals. Automatically + * called on a manual to auto transition. + */ + void reset(void); + + /** + * Set PID to manual or auto mode. + * + * @param mode 0 -> Manual + * Non-zero -> Auto + */ + void setMode(int mode); + + /** + * Set how fast the PID loop is run. + * + * @param interval PID calculation peformed every interval seconds. + */ + void setInterval(float interval); + + /** + * Set the set point. + * + * @param sp The set point as a real world value. + */ + void setSetPoint(float sp); + + /** + * Set the process value. + * + * @param pv The process value as a real world value. + */ + void setProcessValue(float pv); + + /** + * Set the bias. + * + * @param bias The bias for the controller output. + */ + void setBias(float bias); + + /** + * PID calculation. + * + * @return The controller output as a float between outMin and outMax. + */ + float compute(void); + + //Getters. + float getInMin(); + float getInMax(); + float getOutMin(); + float getOutMax(); + float getInterval(); + float getPParam(); + float getIParam(); + float getDParam(); + +private: + + bool usingFeedForward; + bool inAuto; + + //Actual tuning parameters used in PID calculation. + float Kc_; + float tauR_; + float tauD_; + + //Raw tuning parameters. + float pParam_; + float iParam_; + float dParam_; + + //The point we want to reach. + float setPoint_; + //The thing we measure. + float processVariable_; + float prevProcessVariable_; + //The output that affects the process variable. + float controllerOutput_; + float prevControllerOutput_; + + //We work in % for calculations so these will scale from + //real world values to 0-100% and back again. + float inMin_; + float inMax_; + float inSpan_; + float outMin_; + float outMax_; + float outSpan_; + + //The accumulated error, i.e. integral. + float accError_; + //The controller output bias. + float bias_; + + //The interval between samples. + float tSample_; + + //Controller output as a real world value. + volatile float realOutput_; + +}; + +#endif /* PID_H */ diff --git a/lib/readme.txt b/lib/readme.txt new file mode 100644 index 0000000..607a92a --- /dev/null +++ b/lib/readme.txt @@ -0,0 +1,38 @@ + +This directory is intended for the project specific (private) libraries. +PlatformIO will compile them to static libraries and link to executable file. + +The source code of each library should be placed in separate directory, like +"lib/private_lib/[here are source files]". + +For example, see how can be organized `Foo` and `Bar` libraries: + +|--lib +| |--Bar +| | |--docs +| | |--examples +| | |--src +| | |- Bar.c +| | |- Bar.h +| |--Foo +| | |- Foo.c +| | |- Foo.h +| |- readme.txt --> THIS FILE +|- platformio.ini +|--src + |- main.c + +Then in `src/main.c` you should use: + +#include +#include + +// rest H/C/CPP code + +PlatformIO will find your libraries automatically, configure preprocessor's +include paths and build them. + +See additional options for PlatformIO Library Dependency Finder `lib_*`: + +http://docs.platformio.org/en/latest/projectconf.html#lib-install + diff --git a/platformio.ini b/platformio.ini new file mode 100644 index 0000000..08189d7 --- /dev/null +++ b/platformio.ini @@ -0,0 +1,33 @@ +# +# Project Configuration File +# +# A detailed documentation with the EXAMPLES is located here: +# http://docs.platformio.org/en/latest/projectconf.html +# + +# A sign `#` at the beginning of the line indicates a comment +# Comment lines are ignored. + +# Simple and base environment +# [env:mybaseenv] +# platform = %INSTALLED_PLATFORM_NAME_HERE% +# framework = +# board = +# +# Automatic targets - enable auto-uploading +# targets = upload + +[env:stlink] +platform = ststm32 +framework = mbed +board = nucleo_f072rb +upload_protocol = stlink +extra_script = stlink_extra_script.py +# enable float formatting for printf, adding approx. 7 kB of bin file size +build_flags = -Wl,-u_printf_float + +#[env:nucleo_f072rb] +#platform = ststm32 +#framework = mbed +#board = nucleo_f072rb +#upload_port = G: diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..52686be --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,498 @@ + /* LibreSolar MPPT charge controller firmware + * Copyright (c) 2016 Martin Jäger (www.libre.solar) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "mbed.h" +#include "HalfBridge.h" +#include "PID.h" +#include "DogLCD.h" +#include "font_6x8.h" + +#define DISPLAY_ENABLED +#define ADC_AVG_SAMPLES 8 // number of ADC values to read for averaging +#define MPPT_SAFE_MODE 1 + +// DC/DC converter settings +const int _pwm_frequency = 100; // kHz +const int min_solar_current = 100; // mA --> if lower, charger is switched off +const int solar_voltage_offset_start = 4000; // mV charging switched on if Vsolar > Vbat + offset +const int solar_voltage_offset_stop = 2000; // mV charging switched off if Vsolar < Vbat + offset +const int max_charge_current = 8000; // mA PCB maximum: 12 A +const int max_solar_voltage = 55000; // mV + +const int k_pedal_generator = 5; // W/V bezogen auf Spannungsdifferenz zwischen Eingang und Ausgang + +// typcial lead-acid battery +/* +const int num_cells = 6; +const int v_cell_max = 2400; // max voltage per cell +const int v_cell_trickle = 2300; // voltage for trickle charging of lead-acid batteries +const int v_cell_load_disconnect = 1950; +const int v_cell_load_reconnect = 2200; +*/ + +// typcial LiFePO4 battery +const int num_cells = 4; +const int v_cell_max = 3550; // max voltage per cell +const int v_cell_trickle = 3550; // voltage for trickle charging of lead-acid batteries +const int v_cell_load_disconnect = 3000; +const int v_cell_load_reconnect = 3150; + +//---------------------------------------------------------------------------- +// global variables + +SPI spi(PB_5, NC, PB_3); + +#ifdef DISPLAY_ENABLED +DogLCD lcd(spi, PA_1, PA_3, PA_2); // spi, cs, a0, reset +#endif + +Serial serial(PB_10, PB_11); + +HalfBridge mppt(PA_8, PB_13); + +DigitalOut led1(PA_9); +DigitalOut led2(PA_10); +DigitalOut led3(PB_12); + +AnalogIn v_bat(PA_4); +AnalogIn v_solar(PA_5); +AnalogIn i_load(PA_6); +AnalogIn i_dcdc(PA_7); + +Ticker tick1, tick2; + +// ST HAL for ADC for internal temperature and voltage measurements +ADC_HandleTypeDef adc_handle; + +//PID(float Kc, float tauI, float tauD, float interval) +#define PID_UPDATE_RATE 0.01 +PID controller(-2e-4, 3e-3, 0, PID_UPDATE_RATE); +//PID controller(2, 0, 0, PID_UPDATE_RATE); + +int solar_voltage; // mV +int battery_voltage; // mV +int dcdc_current; // mA +int load_current; // mA + +float temperature = 0.0; + + +int dcdc_current_target = 0; +int solar_power_prev = 0; // unit: mW +int solar_power = 0; // unit: mW + +int pwm_delta = 1; + +enum charger_states {STANDBY, CHG_CC, CHG_CV, CHG_TRICKLE, BAT_ERROR, CHG_BIKE}; // states for charger state machine +int state = BAT_ERROR; + +//---------------------------------------------------------------------------- +// function prototypes + +void setup(); +void update_measurements(); +void update_controller(); +void enter_state(int next_state); +void state_machine(); +void adjust_input_voltage(int delta_mV); + +#ifdef DISPLAY_ENABLED +void update_screen(); +#endif + + +//---------------------------------------------------------------------------- +int main() +{ + setup(); + + enter_state(STANDBY); + +#ifdef DISPLAY_ENABLED + tick1.attach(&update_screen, 0.5); +#endif + + //tick2.attach(&update_controller, PID_UPDATE_RATE); + + while(1) { + update_measurements(); + state_machine(); + wait(0.2); + } +} + +//---------------------------------------------------------------------------- +void setup() +{ +#ifdef DISPLAY_ENABLED + lcd.init(); + lcd.view(VIEW_TOP); +#endif + + mppt.frequency_kHz(_pwm_frequency); + mppt.deadtime_ns(300); + mppt.set_duty_cycle(0.90); + mppt.lock_settings(); + + mppt.duty_cycle_limits(0.5, 0.97); +// mppt.duty_cycle_limits((float) v_cell_load_disconnect * num_cells / max_solar_voltage, 0.97); + + update_measurements(); + + + controller.setInputLimits(0.0, 12000); + controller.setOutputLimits(13000, 55000); + //controller.setBias(0.0); + controller.setMode(AUTO_MODE); + + serial.baud(115200); + serial.printf("\nSerial interface started...\n"); + + // Configure the global features of the ADC (Clock, Resolution, Data Alignment and number of conversion) + adc_handle.Instance = ADC1; + adc_handle.Init.ClockPrescaler = ADC_CLOCKPRESCALER_PCLK_DIV4; + adc_handle.Init.Resolution = ADC_RESOLUTION12b; + adc_handle.Init.ScanConvMode = DISABLE; + adc_handle.Init.ContinuousConvMode = DISABLE; + adc_handle.Init.DiscontinuousConvMode = DISABLE; + adc_handle.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; + adc_handle.Init.DataAlign = ADC_DATAALIGN_RIGHT; + adc_handle.Init.DMAContinuousRequests = DISABLE; + adc_handle.Init.EOCSelection = EOC_SINGLE_CONV; + HAL_ADC_Init(&adc_handle); //Go turn on the ADC +} + + +// actions to be performed upon entering a state +void enter_state(int next_state) +{ + switch (next_state) + { + case STANDBY: + serial.printf("Enter State: STANDBY\n"); + mppt.stop(); + led1 = 1; + led3 = 0; + break; + + case CHG_CC: + serial.printf("Enter State: CHG_CC\n"); + mppt.set_duty_cycle((float) battery_voltage / (solar_voltage - 1000.0)); // start with proper PWM duty cycle + mppt.start(); + led3 = 1; + break; + + case CHG_CV: + serial.printf("Enter State: CHG_CV\n"); + // coming from CHG_CC --> DC/DC FETs already on and charging enabled + break; + + case CHG_TRICKLE: + serial.printf("Enter State: CHG_TRICKLE\n"); + break; + + case CHG_BIKE: + serial.printf("Enter State: CHG_BIKE\n"); + //if (solar_voltage < battery_voltage) + // solar_voltage = battery_voltage + solar_voltage_offset; + mppt.set_duty_cycle((float) battery_voltage / (solar_voltage - 1000.0)); // start with proper PWM duty cycle + //mppt.start(); + //led3 = 1; + break; + + case BAT_ERROR: + serial.printf("Enter State: BAT_ERROR\n"); + mppt.stop(); + led3 = 0; + break; + + default: + mppt.stop(); + led3 = 0; + break; + } + state = next_state; +} + +/***************************************************************************** + * Charger state machine + * + * INIT Initial state when system boots up. Checks communication to BMS + * and turns the CHG and DSG FETs on + * STANDBY Battery can be discharged, but no charging power is available + * or battery is fully charged + * CHG_CC Constant current (CC) charging with maximum current possible + * (MPPT algorithm is running) + * CHG_CV Constant voltage (CV) charging at maximum cell voltage + * BAT_ERROR An error occured. Charging disabled. + + */ +void state_machine() +{ + int err = 0, p_target; + + switch (state) { + + case STANDBY: + if (solar_voltage > battery_voltage + solar_voltage_offset_start) { + //enter_state(CHG_BIKE); + enter_state(CHG_CC); + } + break; + + case CHG_CC: + //serial.printf("CHG_CC state still alive\n"); + if (battery_voltage > num_cells * v_cell_max) { + enter_state(CHG_CV); + } + else if (dcdc_current > max_charge_current) { + // increase PV voltage + mppt.duty_cycle_step(-1); + } + if (solar_voltage < battery_voltage + solar_voltage_offset_stop + || dcdc_current < min_solar_current) { + enter_state(STANDBY); + return; + } + else { // start MPPT + + if (solar_power_prev > solar_power) { + pwm_delta = -pwm_delta; + } + mppt.duty_cycle_step(pwm_delta); + } + solar_power_prev = solar_power; + break; + + case CHG_CV: + + if (dcdc_current < min_solar_current) { + enter_state(STANDBY); + return; + } + else { + if (battery_voltage > num_cells * v_cell_max) { + // increase input voltage and decrease PV current + mppt.duty_cycle_step(-1); + } + else { + mppt.duty_cycle_step(1); + } + } + break; + + case CHG_BIKE: + p_target = ((solar_voltage - battery_voltage) / 100.0) * ((solar_voltage - battery_voltage) / 100.0) * k_pedal_generator; // mW + //serial.printf("P_target = %d, p_actual = %d\n", p_target, solar_power); + if (p_target < 0) { + p_target = 0; + } + + dcdc_current_target = (float) p_target / battery_voltage * 1000.0; + + if (solar_power > p_target) { + // increase input voltage and decrease motor torque + //mppt.set_duty_cycle(mppt.get_duty_cycle() - 0.001); + } + else { + //mppt.set_duty_cycle(mppt.get_duty_cycle() + 0.001); + } + break; + + + case BAT_ERROR: + if (err == 0) { + enter_state(STANDBY); + } + break; + + default: + mppt.stop(); + break; + } +} + + +//---------------------------------------------------------------------------- + +void adjust_input_voltage(int delta_mV) +{ + float duty_cycle = mppt.get_duty_cycle(); + + duty_cycle = (float)battery_voltage / (battery_voltage / duty_cycle + delta_mV); + + //if (sqrt(pow(duty_cycle - mppt.get_duty_cycle(), 2.0)) < 1) { + serial.printf("New duty cycle: %.1f %%\n", duty_cycle * 100.0); + mppt.set_duty_cycle(duty_cycle); + //} +} + + +//---------------------------------------------------------------------------- + +void update_controller(void) +{ + int input_voltage; + + //dcdc_current_target = 300; +// dcdc_current = 1100; + + //We want the process variable to be 1.7V + controller.setSetPoint((float)dcdc_current_target); +// controller.setSetPoint(800); + + // update the process variable. + controller.setProcessValue((float)dcdc_current); +// controller.setProcessValue(1); + + // set the new output. + input_voltage = (int)controller.compute(); + + mppt.set_duty_cycle((float) battery_voltage / input_voltage); + +// serial.printf("Controller: actual = %d, target = %d, output = %d, duty = %f\n", dcdc_current, dcdc_current_target, input_voltage, (float) battery_voltage / input_voltage); +// serial.printf("Controller: actual = %d, target = %d, output = %d\n", dcdc_current, dcdc_current_target, input_voltage); + +} + +#ifdef DISPLAY_ENABLED +void update_screen(void) +{ + char str[20]; + + lcd.clear_screen(); + + sprintf(str, "V Sol: %.2fV", solar_voltage / 1000.0); + lcd.string(0,0,font_6x8, str); + + sprintf(str, "V Bat: %.2fV", battery_voltage / 1000.0); + lcd.string(0,1,font_6x8, str); + + sprintf(str, "I DCDC %.2fA", dcdc_current / 1000.0); + lcd.string(0,2,font_6x8, str); + + sprintf(str, "I Load: %.2fA", load_current / 1000.0); + lcd.string(0,3,font_6x8, str); + + sprintf(str, "Power: %.2f W", solar_power / 1000.0); + lcd.string(0,4,font_6x8, str); + + sprintf(str, "PWM duty: %.1f %%", mppt.get_duty_cycle() * 100.0); + lcd.string(0,5,font_6x8, str); + + lcd.string(0,6,font_6x8,"State:"); + switch (state) { + case STANDBY: + lcd.string(7*6,6,font_6x8,"Standby"); + break; + case CHG_CC: + lcd.string(7*6,6,font_6x8,"CC charge"); + break; + case CHG_CV: + lcd.string(7*6,6,font_6x8,"CV charge"); + break; + case CHG_TRICKLE: + lcd.string(7*6,6,font_6x8,"Trickle chg"); + break; + case CHG_BIKE: + lcd.string(7*6,6,font_6x8,"Bike gen"); + break; + } + + sprintf(str, "Temp: %.1f C", temperature); + lcd.string(0,7,font_6x8, str); +} +#endif // DISPLAY_ENABLED + + +//---------------------------------------------------------------------------- +void update_measurements(void) +{ + const int vcc = 3300; // mV + + // solar voltage divider o-- 150k --o-- 6.8k --o + unsigned long sum_adc_readings = 0; + for (int i = 0; i < ADC_AVG_SAMPLES; i++) { + sum_adc_readings += v_solar.read_u16(); + } + solar_voltage = (sum_adc_readings / ADC_AVG_SAMPLES) * 1568 / 68 * vcc / 0xFFFF; + + // battery voltage divider o-- 120k --o-- 10k --o + sum_adc_readings = 0; + for (int i = 0; i < ADC_AVG_SAMPLES; i++) { + sum_adc_readings += v_bat.read_u16(); + } + battery_voltage = (sum_adc_readings / ADC_AVG_SAMPLES) * 130 / 10 * vcc / 0xFFFF; + + sum_adc_readings = 0; + for (int i = 0; i < ADC_AVG_SAMPLES; i++) { + sum_adc_readings += i_dcdc.read_u16(); + } + dcdc_current = (sum_adc_readings / ADC_AVG_SAMPLES) * 1000 / 5 / 50 * vcc / 0xFFFF; + + sum_adc_readings = 0; + for (int i = 0; i < ADC_AVG_SAMPLES; i++) { + sum_adc_readings += i_load.read_u16(); + } + load_current = (sum_adc_readings / ADC_AVG_SAMPLES) * 1000 / 5 / 50 * vcc / 0xFFFF; + + solar_power = battery_voltage * dcdc_current / 1000; + + // Trying internal temperature and voltage reference + // Results: + // - LDO is more accurate than internal voltage reference + // - Temperature reading very inaccurate (>40°C at 25°C) + + // read factory calibration values + const uint16_t VREFINT_CAL = *((uint16_t *)0x1FFFF7BA); // 2 Byte at this address is VRefInt @3.3V/30°C + const uint16_t TS_CAL1 = *((uint16_t *)0x1FFFF7B8); + const uint16_t TS_CAL2 = *((uint16_t *)0x1FFFF7C2); + + //serial.printf("TS_CAL1 = %d, TS_CAL2 = %d\n", TS_CAL1, TS_CAL2); + + // ST HAL for internal voltage and temperature measurements + + ADC_ChannelConfTypeDef sConfig; //Declare the ST HAL ADC object + sConfig.Rank = ADC_RANK_CHANNEL_NUMBER; + sConfig.SamplingTime = ADC_SAMPLETIME_7CYCLES_5; + + adc_handle.Instance->CHSELR = 0; + + sConfig.Channel = ADC_CHANNEL_VREFINT; + HAL_ADC_ConfigChannel(&adc_handle, &sConfig); + HAL_ADC_Start(&adc_handle); // Start conversion + + // Wait end of conversion and get value + if (HAL_ADC_PollForConversion(&adc_handle, 10) == HAL_OK) { + uint16_t value = HAL_ADC_GetValue(&adc_handle); + //vcc = (float) VREFINT_CAL / value * 3.3; + //serial.printf("VCC = %f\n", vcc); + } + + adc_handle.Instance->CHSELR = 0; + + sConfig.Channel = ADC_CHANNEL_TEMPSENSOR; + HAL_ADC_ConfigChannel(&adc_handle, &sConfig); + //ADC->CCR |= ADC_CCR_TSEN; + HAL_ADC_Start(&adc_handle); // Start conversion + + // Wait end of conversion and get value + if (HAL_ADC_PollForConversion(&adc_handle, 10) == HAL_OK) { + uint16_t value = HAL_ADC_GetValue(&adc_handle); + temperature = (float) (30.0 + (110.0 - 30.0) / (TS_CAL2 - TS_CAL1) * (value - TS_CAL1)); + //serial.printf("Internal Temperature = %f\n", temperature); + } +} diff --git a/stlink_extra_script.py b/stlink_extra_script.py new file mode 100644 index 0000000..363979f --- /dev/null +++ b/stlink_extra_script.py @@ -0,0 +1,15 @@ +from SCons.Script import DefaultEnvironment +from os.path import join + +env = DefaultEnvironment() + +env.Replace( + UPLOADER=join("$PIOPACKAGES_DIR", "tool-stlink", "st-flash"), + MYUPLOADERFLAGS=[ + "--reset", # reset board before and after flashing + "write", # write in flash + "$SOURCES", # firmware path to flash + "0x08000000" # flash start adress + ], + UPLOADCMD='$UPLOADER $MYUPLOADERFLAGS', +) \ No newline at end of file