Compare commits

...

8 Commits

Author SHA1 Message Date
Ben V. Brown
4718efe79b 2.04 bugfixes
Should help with UI lockups
2018-05-07 21:24:29 +10:00
Ben V. Brown
771f0a1b9e Cleanup LCD on/off commands into buffer 2018-05-06 20:06:16 +10:00
Ben V. Brown
1fef2fb53a Move OLED LCD update to be DMA'ed
Start Cleaning up I2C HAL
2018-05-06 18:56:38 +10:00
Ben V. Brown
bf1fa74d72 Update debug info
Change pin configs
Clean up some code
2018-05-06 18:01:34 +10:00
freetushkan
1ae8b2f216 Additional changes in russian localization (#284)
Changes in russian localization (typos, improvements, machine translation replacements). I'd like to maintain this in the future.
2018-05-05 14:55:15 +10:00
Jan Krupička
98ed6be197 factory reset as last item (again) (#282) 2018-05-05 14:54:48 +10:00
freetushkan
19240f2ae5 Some changes in russian localisation (#276) 2018-04-30 08:58:14 +10:00
Ben V. Brown
dd2fdbcb8e Fix button lockout
Fixes #278
2018-04-28 11:46:07 +10:00
17 changed files with 372 additions and 418 deletions

View File

@@ -3467,48 +3467,7 @@ void HAL_I2C_EV_IRQHandler(I2C_HandleTypeDef *hi2c)
}
}
}
/* Slave mode selected */
else
{
/* ADDR set --------------------------------------------------------------*/
if(((sr1itflags & I2C_FLAG_ADDR) != RESET) && ((itsources & I2C_IT_EVT) != RESET))
{
I2C_Slave_ADDR(hi2c);
}
/* STOPF set --------------------------------------------------------------*/
else if(((sr1itflags & I2C_FLAG_STOPF) != RESET) && ((itsources & I2C_IT_EVT) != RESET))
{
I2C_Slave_STOPF(hi2c);
}
/* I2C in mode Transmitter -----------------------------------------------*/
else if((sr2itflags & I2C_FLAG_TRA) != RESET)
{
/* TXE set and BTF reset -----------------------------------------------*/
if(((sr1itflags & I2C_FLAG_TXE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET))
{
I2C_SlaveTransmit_TXE(hi2c);
}
/* BTF set -------------------------------------------------------------*/
else if(((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET))
{
I2C_SlaveTransmit_BTF(hi2c);
}
}
/* I2C in mode Receiver --------------------------------------------------*/
else
{
/* RXNE set and BTF reset ----------------------------------------------*/
if(((sr1itflags & I2C_FLAG_RXNE) != RESET) && ((itsources & I2C_IT_BUF) != RESET) && ((sr1itflags & I2C_FLAG_BTF) == RESET))
{
I2C_SlaveReceive_RXNE(hi2c);
}
/* BTF set -------------------------------------------------------------*/
else if(((sr1itflags & I2C_FLAG_BTF) != RESET) && ((itsources & I2C_IT_EVT) != RESET))
{
I2C_SlaveReceive_BTF(hi2c);
}
}
}
}
/**

View File

@@ -4280,7 +4280,7 @@ uint32_t HAL_TIM_ReadCapturedValue(TIM_HandleTypeDef *htim, uint32_t Channel)
*/
/**
* @brief Period elapsed callback in non blocking mode
* @brief Period elapsed callback in non blocking mode
* @param htim : TIM handle
* @retval None
*/

View File

@@ -7,6 +7,7 @@ endif
# Discover the source files to build
SOURCE := $(shell find . -type f -name '*.c')
SOURCE_CPP := $(shell find . -type f -name '*.cpp')
SOURCES := $(shell find . -type f -name '*.c*')
S_SRCS := $(shell find . -type f -name '*.s')
APP_INC_DIR = ./inc
@@ -31,7 +32,7 @@ HEXFILE_DIR=Hexfile
OUTPUT_DIR=Objects
# code optimisation ------------------------------------------------------------
OPTIM=-O2 -finline-small-functions -findirect-inlining -fdiagnostics-color
OPTIM=-Os -finline-small-functions -findirect-inlining -fdiagnostics-color -ffunction-sections -fdata-sections
# global defines ---------------------------------------------------------------
@@ -130,7 +131,11 @@ CXXFLAGS=$(CPUFLAGS) \
-fno-rtti \
-fno-exceptions \
-fno-non-call-exceptions \
-fno-use-cxa-atexit \
-fno-use-cxa-atexit \
-fno-strict-aliasing \
-fno-rtti \
-fno-exceptions \
-fno-threadsafe-statics \
-T$(LDSCRIPT)
@@ -173,7 +178,7 @@ OUT_OBJS_S=$(addprefix $(OUTPUT_DIR)/,$(OBJS_S))
OUT_HEXFILE=$(addprefix $(HEXFILE_DIR)/,$(OUTPUT_EXE))
all: $(OUT_HEXFILE).hex
#
# The rule to create the target directory
#

View File

@@ -101,12 +101,14 @@
#define configTICK_RATE_HZ ((TickType_t)100)
#define configMAX_PRIORITIES ( 4 )
#define configMINIMAL_STACK_SIZE ((uint16_t)256)
#define configTOTAL_HEAP_SIZE ((size_t)10240)
#define configMAX_TASK_NAME_LEN ( 16 )
#define configTOTAL_HEAP_SIZE ((size_t)10240) /*Currently use about 9000*/
#define configMAX_TASK_NAME_LEN ( 48 )
#define configUSE_16_BIT_TICKS 0
#define configUSE_MUTEXES 1
#define configQUEUE_REGISTRY_SIZE 8
#define configUSE_PORT_OPTIMISED_TASK_SELECTION 1
#define configCHECK_FOR_STACK_OVERFLOW 2
/* Co-routine definitions. */
#define configUSE_CO_ROUTINES 0
@@ -122,6 +124,7 @@ to exclude the API function. */
#define INCLUDE_vTaskDelayUntil 0
#define INCLUDE_vTaskDelay 1
#define INCLUDE_xTaskGetSchedulerState 1
#define INCLUDE_uxTaskGetStackHighWaterMark 1
/* Cortex-M specific definitions. */
#ifdef __NVIC_PRIO_BITS

View File

@@ -57,7 +57,7 @@ private:
FRToSI2C* i2c; //i2c Pointer
const uint8_t* currentFont; // Pointer to the current font used for rendering to the buffer
uint8_t screenBuffer[14 + 96 + 96 + 10]; // The data buffer
uint8_t screenBuffer[16 + 96 + 96 + 10]; // The data buffer
uint8_t* firstStripPtr; // Pointers to the strips to allow for buffer having extra content
uint8_t* secondStripPtr; //Pointers to the strips
bool inLeftHandedMode; // Whether the screen is in left or not (used for offsets in GRAM)

View File

@@ -11,31 +11,34 @@
#define SETTINGS_H_
#include <stdint.h>
#include "stm32f1xx_hal.h"
#define SETTINGSVERSION 0x13 /*Change this if you change the struct below to prevent people getting out of sync*/
#define SETTINGSVERSION 0x14 /*Change this if you change the struct below to prevent people getting out of sync*/
/*
* This struct must be a multiple of 2 bytes as it is saved / restored from flash in uint16_t chunks
*/
typedef struct {
uint16_t SolderingTemp; //current set point for the iron
uint16_t SleepTemp; //temp to drop to in sleep
uint8_t SleepTime; //minutes timeout to sleep
uint8_t cutoutSetting; // The voltage we cut out at for under voltage
uint8_t OrientationMode:2; //If true we want to invert the display for lefties
uint8_t sensitivity :4; //Sensitivity of accelerometer (5 bits)
uint8_t autoStartMode :2; //Should the unit automatically jump straight into soldering mode when power is applied
uint8_t ShutdownTime; //Time until unit shuts down if left alone
uint8_t boostModeEnabled :1; //Boost mode swaps BUT_A in soldering mode to temporary soldering temp over-ride
uint8_t coolingTempBlink :1; //Should the temperature blink on the cool down screen until its <50C
uint16_t SolderingTemp; //current set point for the iron
uint16_t SleepTemp; //temp to drop to in sleep
uint8_t SleepTime; //minutes timeout to sleep
uint8_t cutoutSetting; // The voltage we cut out at for under voltage
uint8_t OrientationMode:2; //If true we want to invert the display for lefties
uint8_t sensitivity :4; //Sensitivity of accelerometer (5 bits)
uint8_t autoStartMode :2; //Should the unit automatically jump straight into soldering mode when power is applied
uint8_t ShutdownTime; //Time until unit shuts down if left alone
uint8_t boostModeEnabled :1; //Boost mode swaps BUT_A in soldering mode to temporary soldering temp over-ride
uint8_t coolingTempBlink :1; //Should the temperature blink on the cool down screen until its <50C
uint8_t detailedIDLE :1; //Detailed idle screen
uint8_t detailedSoldering :1; //Detailed soldering screens
uint8_t temperatureInF; //Should the temp be in F or C (true is F)
uint8_t descriptionScrollSpeed:1; // Description scroll speed
uint16_t voltageDiv; //Voltage divisor factor
uint16_t BoostTemp; //Boost mode set point for the iron
int16_t CalibrationOffset; //This stores the temperature offset for this tip in the iron.
uint8_t version; //Used to track if a reset is needed on firmware upgrade
uint32_t padding; //This is here for in case we are not an even divisor so that nothing gets cut off
uint8_t temperatureInF; //Should the temp be in F or C (true is F)
uint8_t descriptionScrollSpeed:1; // Description scroll speed
uint16_t voltageDiv; //Voltage divisor factor
uint16_t BoostTemp; //Boost mode set point for the iron
int16_t CalibrationOffset; //This stores the temperature offset for this tip in the iron.
uint8_t PID_P; //PID P Term
uint8_t PID_I; //PID I Term
uint8_t PID_D; //PID D Term
uint8_t version; //Used to track if a reset is needed on firmware upgrade
uint32_t padding; //This is here for in case we are not an even divisor so that nothing gets cut off
} systemSettingsType;
extern volatile systemSettingsType systemSettings;

View File

@@ -28,6 +28,7 @@ void waitForButtonPressOrTimeout(uint32_t timeout);
#ifdef __cplusplus
extern "C" {
#endif
void HAL_ADCEx_InjectedConvCpltCallback(ADC_HandleTypeDef* hadc);
void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c);
@@ -35,6 +36,7 @@ void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_MasterRxCpltCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c);
void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c);
void vApplicationStackOverflowHook( xTaskHandle *pxTask, signed portCHAR *pcTaskName );
#ifdef __cplusplus
}

View File

@@ -14,12 +14,13 @@ FRToSI2C::FRToSI2C(I2C_HandleTypeDef* i2chandle) {
void FRToSI2C::CpltCallback() {
BaseType_t xHigherPriorityTaskWoken = pdFALSE;
i2c->State = HAL_I2C_STATE_READY;//Force state reset
if (I2CSemaphore) {
xSemaphoreGiveFromISR(I2CSemaphore, &xHigherPriorityTaskWoken);
portYIELD_FROM_ISR(xHigherPriorityTaskWoken);
}
}
void FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t MemAddress,
@@ -33,11 +34,14 @@ void FRToSI2C::Mem_Read(uint16_t DevAddress, uint16_t MemAddress,
//RToS is active, run threading
//Get the mutex so we can use the I2C port
//Wait up to 1 second for the mutex
if ( xSemaphoreTake( I2CSemaphore, ( TickType_t ) 1000 ) == pdTRUE) {
HAL_I2C_Mem_Read(i2c, DevAddress, MemAddress, MemAddSize, pData,
Size, 5000);
if ( xSemaphoreTake( I2CSemaphore, ( TickType_t ) 5000 ) == pdTRUE) {
if (HAL_I2C_Mem_Read(i2c, DevAddress, MemAddress, MemAddSize, pData,
Size, 5000) != HAL_OK) {
NVIC_SystemReset();
}
xSemaphoreGive(I2CSemaphore);
} else {
NVIC_SystemReset();
}
}
@@ -55,11 +59,15 @@ void FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress,
//RToS is active, run threading
//Get the mutex so we can use the I2C port
//Wait up to 1 second for the mutex
if ( xSemaphoreTake( I2CSemaphore, ( TickType_t ) 1000 ) == pdTRUE) {
HAL_I2C_Mem_Write(i2c, DevAddress, MemAddress, MemAddSize, pData,
Size, 5000);
if ( xSemaphoreTake( I2CSemaphore, ( TickType_t ) 5000 ) == pdTRUE) {
if (HAL_I2C_Mem_Write(i2c, DevAddress, MemAddress, MemAddSize,
pData, Size, 5000) != HAL_OK) {
NVIC_SystemReset();
}
xSemaphoreGive(I2CSemaphore);
} else {
NVIC_SystemReset();
}
}
@@ -67,7 +75,7 @@ void FRToSI2C::Mem_Write(uint16_t DevAddress, uint16_t MemAddress,
}
void FRToSI2C::FRToSInit() {
I2CSemaphore = xSemaphoreCreateMutex();
I2CSemaphore = xSemaphoreCreateBinary();
xSemaphoreGive(I2CSemaphore);
}
@@ -80,9 +88,14 @@ void FRToSI2C::Transmit(uint16_t DevAddress, uint8_t* pData, uint16_t Size) {
//RToS is active, run threading
//Get the mutex so we can use the I2C port
//Wait up to 1 second for the mutex
if ( xSemaphoreTake( I2CSemaphore, ( TickType_t ) 1000 ) == pdTRUE) {
HAL_I2C_Master_Transmit(i2c, DevAddress, pData, Size, 5000);
xSemaphoreGive(I2CSemaphore);
if ( xSemaphoreTake( I2CSemaphore, ( TickType_t ) 5000 ) == pdTRUE) {
if (HAL_I2C_Master_Transmit_DMA(i2c, DevAddress, pData, Size)
!= HAL_OK) {
NVIC_SystemReset();
}
//xSemaphoreGive(I2CSemaphore);
} else {
NVIC_SystemReset();
}
}

View File

@@ -34,7 +34,7 @@ void MMA8652FC::initalize() {
I2C_RegisterWrite(PL_COUNT_REG, 200); //200 count debounce
I2C_RegisterWrite(PL_BF_ZCOMP_REG, 0b01000111); //Set the threshold to 42 degrees
I2C_RegisterWrite(P_L_THS_REG, 0b10011100); //Up the trip angles
I2C_RegisterWrite( CTRL_REG4, 0x01 | (1 << 4)); // Enable dataready interrupt & orientation interrupt
I2C_RegisterWrite( CTRL_REG4, 0); // Disable IRQ's
I2C_RegisterWrite( CTRL_REG5, 0x01); // Route data ready interrupts to INT1 ->PB5 ->EXTI5, leaving orientation routed to INT2
I2C_RegisterWrite( CTRL_REG2, 0x12); //Set maximum resolution oversampling
I2C_RegisterWrite( XYZ_DATA_CFG_REG, (1 << 4)); //select high pass filtered data

View File

@@ -49,8 +49,8 @@ OLED::OLED(FRToSI2C* i2cHandle) {
currentFont = FONT_12;
fontWidth = 12;
inLeftHandedMode = false;
firstStripPtr = &screenBuffer[15];
secondStripPtr = &screenBuffer[15 + 96];
firstStripPtr = &screenBuffer[16 + 1];
secondStripPtr = &screenBuffer[16 + 1 + 96];
fontHeight = 16;
fontWidth = 12;
displayOffset = 0;
@@ -60,34 +60,34 @@ OLED::OLED(FRToSI2C* i2cHandle) {
void OLED::initialize() {
HAL_Delay(5);
HAL_GPIO_WritePin(OLED_RESET_GPIO_Port, OLED_RESET_Pin, GPIO_PIN_SET);
HAL_Delay(5);
HAL_Delay(10);
//Send the setup settings
i2c->Transmit( DEVICEADDR_OLED, (uint8_t*) OLED_Setup_Array, configLength);
//displayOnOff(true);
displayOnOff(true);
}
//Write out the buffer to the OLEd & call any rendering objects
void OLED::refresh() {
screenBuffer[0] = 0x80;
screenBuffer[1] = 0x21;
screenBuffer[1] = displayOnOffState ? 0xAF : 0xAE;
screenBuffer[2] = 0x80;
screenBuffer[3] = inLeftHandedMode ? 0 : 32; //display is shifted by 32 in left handed mode as driver ram is 128 wide
screenBuffer[3] = 0x21;
screenBuffer[4] = 0x80;
screenBuffer[5] = inLeftHandedMode ? 95 : 0x7F; //End address of the ram segment we are writing to (96 wide)
screenBuffer[6] = 0x80; /*Set COM Scan direction*/
screenBuffer[7] = inLeftHandedMode ? 0xC8 : 0xC0;
screenBuffer[8] = 0x80; //Set pages to rollover after 2
screenBuffer[9] = 0x22;
screenBuffer[10] = 0x80;
screenBuffer[11] = 0x00; //start page 0
screenBuffer[5] = inLeftHandedMode ? 0 : 32; //display is shifted by 32 in left handed mode as driver ram is 128 wide
screenBuffer[6] = 0x80;
screenBuffer[7] = inLeftHandedMode ? 95 : 0x7F; //End address of the ram segment we are writing to (96 wide)
screenBuffer[8] = 0x80; /*Set COM Scan direction*/
screenBuffer[9] = inLeftHandedMode ? 0xC8 : 0xC0;
screenBuffer[10] = 0x80; //Set pages to rollover after 2
screenBuffer[11] = 0x22;
screenBuffer[12] = 0x80;
screenBuffer[13] = 0x01;
screenBuffer[14] = 0x40; //start of data marker
screenBuffer[13] = 0x00; //start page 0
screenBuffer[14] = 0x80;
screenBuffer[15] = 0x01;
screenBuffer[16] = 0x40; //start of data marker
i2c->Transmit( DEVICEADDR_OLED, screenBuffer, 14 + 96 * 2 + 1);
i2c->Transmit( DEVICEADDR_OLED, screenBuffer, 16 + (96 * 2) + 1);
}
@@ -152,16 +152,7 @@ void OLED::drawChar(char c, char PrecursorCommand) {
}
void OLED::displayOnOff(bool on) {
if (on != displayOnOffState) {
uint8_t data[6] = { 0x80, 0X8D, 0x80, 0X14, 0x80, 0XAF }; //on
if (!on) {
data[3] = 0x10;
data[5] = 0xAE;
}
i2c->Transmit( DEVICEADDR_OLED, data, 6);
displayOnOffState = on;
}
displayOnOffState = on;
}
void OLED::setRotation(bool leftHanded) {
@@ -174,7 +165,8 @@ void OLED::setRotation(bool leftHanded) {
OLED_Setup_Array[11] = 0xC0;
OLED_Setup_Array[19] = 0xA0;
}
i2c->Transmit( DEVICEADDR_OLED, (uint8_t*) OLED_Setup_Array, 50);
i2c->Transmit( DEVICEADDR_OLED, (uint8_t*) OLED_Setup_Array,
configLength);
inLeftHandedMode = leftHanded;
}
}
@@ -342,7 +334,7 @@ void OLED::fillArea(int16_t x, int8_t y, uint8_t wide, uint8_t height,
}
void OLED::drawFilledRect(uint8_t x0, uint8_t y0, uint8_t x1, uint8_t y1,
bool clear) {
bool clear) {
//Draw this in 3 sections
//This is basically a N wide version of vertical line

View File

@@ -90,6 +90,10 @@ void resetSettings() {
systemSettings.CalibrationOffset = 10; //This appears to be quite close for both of my tips, in both of my handles
systemSettings.temperatureInF = 0; //default to 0
systemSettings.descriptionScrollSpeed=0;//default to slow
systemSettings.PID_P =42;
systemSettings.PID_I =50;
systemSettings.PID_D =15;
saveSettings();
}

View File

@@ -38,7 +38,7 @@ void Setup_HAL() {
MX_TIM2_Init();
MX_IWDG_Init();
HAL_ADC_Start_DMA(&hadc1, (uint32_t*) ADCReadings, 64);//start DMA of normal readings
HAL_ADC_Start_DMA(&hadc1, (uint32_t*) ADCReadings, 64); //start DMA of normal readings
HAL_ADCEx_InjectedStart(&hadc1); //enable injected readings
}
@@ -131,7 +131,9 @@ static void MX_ADC1_Init(void) {
//F in = 10.66 MHz
/*
* Injected time is 1 delay clock + (12 adc cycles*4)+4*sampletime =~217 clocks = 0.2ms
*
* Charge time is 0.016 uS ideally
* So Sampling time must be >= 0.016uS
* 1/10.66MHz is 0.09uS, so 1 CLK is *should* be enough
* */
sConfigInjected.InjectedChannel = ADC_CHANNEL_8;
sConfigInjected.InjectedRank = 1;
@@ -143,20 +145,25 @@ static void MX_ADC1_Init(void) {
sConfigInjected.InjectedOffset = 0;
HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
sConfigInjected.InjectedSamplingTime = ADC_SAMPLETIME_1CYCLE_5;
sConfigInjected.InjectedRank = 2;
HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
sConfigInjected.InjectedRank = 3;
HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
sConfigInjected.InjectedRank = 4;
HAL_ADCEx_InjectedConfigChannel(&hadc1, &sConfigInjected);
SET_BIT(hadc1.Instance->CR1, ( ADC_CR1_JEOCIE ));//Enable end of injected conv irq
SET_BIT(hadc1.Instance->CR1, ( ADC_CR1_JEOCIE )); //Enable end of injected conv irq
// Run ADC internal calibration
while (HAL_ADCEx_Calibration_Start(&hadc1) != HAL_OK)
;
}
/* I2C1 init function */
static void MX_I2C1_Init(void) {
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 300000; //300Khz
hi2c1.Init.ClockSpeed = 100000; // OLED doesnt handle >100k when its asleep (off).
hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
@@ -288,13 +295,13 @@ static void MX_DMA_Init(void) {
/* DMA interrupt init */
/* DMA1_Channel1_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 5, 0);
HAL_NVIC_SetPriority(DMA1_Channel1_IRQn, 15, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel1_IRQn);
/* DMA1_Channel6_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel6_IRQn, 5, 0);
HAL_NVIC_SetPriority(DMA1_Channel6_IRQn, 15, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel6_IRQn);
/* DMA1_Channel7_IRQn interrupt configuration */
HAL_NVIC_SetPriority(DMA1_Channel7_IRQn, 5, 0);
HAL_NVIC_SetPriority(DMA1_Channel7_IRQn, 15, 0);
HAL_NVIC_EnableIRQ(DMA1_Channel7_IRQn);
}
@@ -336,13 +343,16 @@ static void MX_GPIO_Init(void) {
| GPIO_PIN_15;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
//Set PA 11 and PA 12 to GND to stop usb detection, 14 re-rused for debug
//Set PA 11 and PA 12 to GND to stop usb detection, 13/14 re-rused for debug
GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12 | GPIO_PIN_14 | GPIO_PIN_13;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_11, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_12, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_13, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_14, GPIO_PIN_RESET);
/*Configure GPIO pins : KEY_B_Pin KEY_A_Pin */
GPIO_InitStruct.Pin = KEY_B_Pin | KEY_A_Pin;
@@ -361,10 +371,11 @@ static void MX_GPIO_Init(void) {
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(OLED_RESET_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pins : INT_Orientation_Pin INT_Movement_Pin */
/* Configure GPIO pins : INT_Orientation_Pin INT_Movement_Pin */
/* Not used anymore*/
GPIO_InitStruct.Pin = INT_Orientation_Pin | INT_Movement_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_FALLING;
GPIO_InitStruct.Pull = GPIO_PULLUP; //Technically the IMU is P-P but safer to pullup (very tiny current cost)
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure peripheral I/O remapping */

View File

@@ -75,6 +75,15 @@ const char* SettingsDescriptions[17] = {
/* Calibrate input voltage */ "VIN Calibration. Buttons adjust, long press to exit",
/* Advanced soldering screen enabled */ "Display detailed information while soldering",
/* Description Scroll Speed */ "Speed this text scrolls past at",
#ifdef PIDSETTINGS
"PID P term. Inverse values! This acts as a divisor. So Larger numbers == typically smaller in other systems",
"PID I term. Inverse values! This acts as a divisor. So Larger numbers == typically smaller in other systems",
"PID D term. Inverse values! This acts as a divisor. So Larger numbers == typically smaller in other systems",
#endif
};
const char* SettingsCalibrationWarning = "Please ensure the tip is at room temperature before continuing!";
@@ -121,6 +130,13 @@ const char* SettingsShortNames[17][2] = {
/* (<= 16) Calibrate input voltage */ {"Calibrate", "input voltage?"},
/* (<= 13) Advanced soldering screen enabled */ {"Detailed", "solder screen"},
/* (<= 11) Display Help Text Scroll Speed */ {"Description","Scroll Speed"},
#ifdef PIDSETTINGS
{"PID","P"},
{"PID","I"},
{"PID","D"},
#endif
};
// SettingsMenuEntries lengths <= 13 per line (\n starts second line)
@@ -225,23 +241,23 @@ const char* SettingsMenuEntriesDescriptions[4] = {
const char* SettingsDescriptions[17] = {
// These are all the help text for all the settings.
// No requirements on spacing or length.
/* Power source (DC or batt) */ "Установка напряжения отключения. <DC - 10V, 3S - 9.9V, 4S - 13.2V, 5S - 16.5V, 6S - 19.8V>",
/* Sleep temperature */ "Температура режима ожидания <C°/F°>",
/* Sleep timeout */ "Время до перехода в режим ожидания <Доступно отключение>",
/* Shutdown timeout */ "Время до отключения <Доступно отключение>",
/* Motion sensitivity level */ "Акселерометр <0 - Выкл. 1 - мин. чувствительный 9 - макс. чувствительный>",
/* Temperature in F and C */ "Единица измерения температуры < C - Цельсий, F - Фаренгейт >",
/* Advanced idle display mode enabled */ "Показывать детальную в режиме настроек <Вместо картинки>",
/* Display rotation mode */ "Ориентация дисплея <A - Автоповорот, L - Левша, R - Правша>",
/* Boost enabled */ "Турбо-режим при удержании кнопки А при пайке ",
/* Boost temperature */ "Температура в Турбо-режиме",
/* Power source (DC or batt) */ "Установка минимального напряжения. <DC - 10V, 3S - 9.9V, 4S - 13.2V, 5S - 16.5V, 6S - 19.8V>",
/* Sleep temperature */ "Температура режима ожидания <C°/F°>.",
/* Sleep timeout */ "Время до перехода в режим ожидания <Доступно отключение>.",
/* Shutdown timeout */ "Время до отключения <Доступно отключение>.",
/* Motion sensitivity level */ "Акселерометр <0 - Выкл., 1 - Мин. чувствительность, 9 - Макс. чувствительность>.",
/* Temperature in F and C */ "Единица измерения температуры. < C - Цельсий, F - Фаренгейт >",
/* Advanced idle display mode enabled */ "Показывать детальную в режиме настроек <Вместо картинки>.",
/* Display rotation mode */ "Ориентация дисплея. <A - Автоповорот, L - Левша, R - Правша>",
/* Boost enabled */ "Турбо-режим при удержании кнопки А в режиме пайки.",
/* Boost temperature */ "Температура в Турбо-режиме.",
/* Automatic start mode */ "Автоматический переход в режим пайки при включении питания.",
/* Cooldown blink */ "Показывать температуру на экране охлаждения, пока жало остается горячим, при этом экран моргает",
/* Cooldown blink */ "Показывать изменение температуры в процессе охлаждения, мигая экраном.",
/* Temperature calibration enter menu */ "Калибровка температурного датчика.",
/* Settings reset command */ "Сброс всех настроек к исходным значения.",
/* Calibrate input voltage */ "Калибровка напряжения входа. Настройка кнопками, нажать и удержать чтобы завершить.",
/* Advanced soldering screen enabled */ "Показывать детальную информацию при пайке.",
/* Description Scroll Speed */ "Скорость прокрутки текста",
/* Description Scroll Speed */ "Скорость прокрутки текста.",
};
const char* SettingsCalibrationWarning = "Убедитесь, что жало остыло до комнатной температуры, прежде чем продолжать!";
@@ -303,7 +319,7 @@ const char* SettingsMenuEntries[4] = {
/* Advanced Menu*/"Другие", };
const char* SettingsMenuEntriesDescriptions[4] ={
"Настройки для режима пайки. Действуют при включенном жале.",
"Настройки при бездействии. Полезно что бы не обжечься и случайно не сжечь жилище.",
"Настройки при бездействии. Полезно чтобы не обжечься и случайно не сжечь жилище.",
"Пользовательский интерфейс.",
"Расширенные настройки. Дополнительные удобства."
};

View File

@@ -31,7 +31,15 @@ static void settings_setAdvancedIDLEScreens(void);
static void settings_displayAdvancedIDLEScreens(void);
static void settings_setScrollSpeed(void);
static void settings_displayScrollSpeed(void);
#ifdef PIDSETTINGS
static void settings_setPIDP(void);
static void settings_displayPIDP(void);
static void settings_setPIDI(void);
static void settings_displayPIDI(void);
static void settings_setPIDD(void);
static void settings_displayPIDD(void);
#endif
static void settings_setDisplayRotation(void);
static void settings_displayDisplayRotation(void);
static void settings_setBoostModeEnabled(void);
@@ -181,6 +189,15 @@ const menuitem advancedMenu[] = {
settings_displayCalibrate } }, /*Calibrate tip*/
{ (const char*) SettingsDescriptions[14], { settings_setCalibrateVIN }, {
settings_displayCalibrateVIN } }, /*Voltage input cal*/
#ifdef PIDSETTINGS
{ (const char*) SettingsDescriptions[17], { settings_setPIDP }, {
settings_displayPIDP } }, /*Voltage input cal*/
{ (const char*) SettingsDescriptions[18], { settings_setPIDI }, {
settings_displayPIDI } }, /*Voltage input cal*/
{ (const char*) SettingsDescriptions[19], { settings_setPIDD }, {
settings_displayPIDD } }, /*Voltage input cal*/
#endif
{ NULL, { NULL }, { NULL } } // end of menu marker. DO NOT REMOVE
};
@@ -363,13 +380,13 @@ static void settings_setTempF(void) {
}
// Rescale both to be multiples of 10
systemSettings.BoostTemp = systemSettings.BoostTemp/10;
systemSettings.BoostTemp *=10;
systemSettings.SolderingTemp = systemSettings.SolderingTemp/10;
systemSettings.SolderingTemp *=10;
systemSettings.SleepTemp = systemSettings.SleepTemp/10;
systemSettings.SleepTemp *=10;
systemSettings.BoostTemp = systemSettings.BoostTemp / 10;
systemSettings.BoostTemp *= 10;
systemSettings.SolderingTemp = systemSettings.SolderingTemp / 10;
systemSettings.SolderingTemp *= 10;
systemSettings.SleepTemp = systemSettings.SleepTemp / 10;
systemSettings.SleepTemp *= 10;
}
static void settings_displayTempF(void) {
@@ -488,6 +505,33 @@ static void settings_displayBoostTemp(void) {
lcd.printNumber(systemSettings.BoostTemp, 3);
}
#ifdef PIDSETTINGS
static void settings_setPIDP(void) {
systemSettings.PID_P++;
systemSettings.PID_P %= 100;
}
static void settings_displayPIDP(void) {
printShortDescription(17, 6);
lcd.printNumber(systemSettings.PID_P, 2);
}
static void settings_setPIDI(void) {
systemSettings.PID_I++;
systemSettings.PID_I %= 100;
}
static void settings_displayPIDI(void) {
printShortDescription(18, 6);
lcd.printNumber(systemSettings.PID_I, 2);
}
static void settings_setPIDD(void) {
systemSettings.PID_D++;
systemSettings.PID_D %= 100;
}
static void settings_displayPIDD(void) {
printShortDescription(19, 6);
lcd.printNumber(systemSettings.PID_D, 2);
}
#endif
static void settings_setAutomaticStartMode(void) {
systemSettings.autoStartMode++;
systemSettings.autoStartMode %= 2;
@@ -495,7 +539,6 @@ static void settings_setAutomaticStartMode(void) {
static void settings_displayAutomaticStartMode(void) {
printShortDescription(10, 7);
lcd.drawCheckbox(systemSettings.autoStartMode);
}

View File

@@ -27,7 +27,6 @@ uint32_t lastButtonTime = 0;
// FreeRTOS variables
osThreadId GUITaskHandle;
osThreadId PIDTaskHandle;
osThreadId ROTTaskHandle;
osThreadId MOVTaskHandle;
static TaskHandle_t pidTaskNotification = NULL;
@@ -35,7 +34,6 @@ static TaskHandle_t pidTaskNotification = NULL;
void startGUITask(void const *argument);
void startPIDTask(void const *argument);
void startMOVTask(void const *argument);
void startRotationTask(void const *argument);
// End FreeRTOS
// Main sets up the hardware then hands over to the FreeRTOS kernel
@@ -81,9 +79,6 @@ int main(void) {
osThreadDef(PIDTask, startPIDTask, osPriorityRealtime, 0, 512); //2k
PIDTaskHandle = osThreadCreate(osThread(PIDTask), NULL);
if (PCBVersion != 3) {
/* definition and creation of ROTTask */
osThreadDef(ROTTask, startRotationTask, osPriorityLow, 0, 256); //1k
ROTTaskHandle = osThreadCreate(osThread(ROTTask), NULL);
/* definition and creation of MOVTask */
osThreadDef(MOVTask, startMOVTask, osPriorityNormal, 0, 512); //2k
MOVTaskHandle = osThreadCreate(osThread(MOVTask), NULL);
@@ -96,10 +91,15 @@ int main(void) {
while (1) {
}
}
void printVoltage() {
lcd.printNumber(getInputVoltageX10(systemSettings.voltageDiv) / 10, 2);
lcd.drawChar('.');
lcd.printNumber(getInputVoltageX10(systemSettings.voltageDiv) % 10, 1);
}
void GUIDelay() {
osDelay(66); // 15Hz
}
void gui_drawTipTemp() {
void gui_drawTipTemp(bool symbol) {
// Draw tip temp handling unit conversion & tolerance near setpoint
uint16_t Temp = getTipRawTemp(0);
@@ -112,6 +112,12 @@ void gui_drawTipTemp() {
// Temp = systemSettings.SolderingTemp;
lcd.printNumber(Temp, 3); // Draw the tip temp out finally
if (symbol) {
if (systemSettings.temperatureInF)
lcd.print("F");
else
lcd.print("C");
}
}
ButtonState getButtonState() {
/*
@@ -221,11 +227,7 @@ static bool checkVoltageForExit() {
lcd.print(UndervoltageString);
lcd.setCursor(0, 8);
lcd.print(InputVoltageString);
lcd.printNumber(getInputVoltageX10(systemSettings.voltageDiv) / 10,
2);
lcd.drawChar('.');
lcd.printNumber(getInputVoltageX10(systemSettings.voltageDiv) % 10,
1);
printVoltage();
lcd.print("V");
} else {
@@ -332,56 +334,6 @@ static void gui_solderingTempAdjust() {
}
}
static int gui_showTipTempWarning() {
for (;;) {
uint16_t tipTemp = tipMeasurementToC(getTipRawTemp(0));
lcd.clearScreen();
lcd.setCursor(0, 0);
if (systemSettings.detailedSoldering) {
lcd.setFont(1);
lcd.print(WarningAdvancedString);
lcd.setCursor(0, 8);
lcd.print(WarningTipTempString);
if (systemSettings.temperatureInF) {
lcd.printNumber(tipMeasurementToF(getTipRawTemp(0)), 3);
lcd.print("F");
} else {
lcd.printNumber(tipMeasurementToC(getTipRawTemp(0)), 3);
lcd.print("C");
}
} else {
lcd.setFont(0);
lcd.drawArea(0, 0, 24, 16, WarningBlock24);
lcd.setCursor(24, 0);
// lcd.print(WarningSimpleString);
lcd.print(" ");
if (systemSettings.temperatureInF) {
lcd.printNumber(tipMeasurementToF(getTipRawTemp(0)), 3);
lcd.drawSymbol(0);
} else {
lcd.printNumber(tipMeasurementToC(getTipRawTemp(0)), 3);
lcd.drawSymbol(1);
}
}
if (systemSettings.coolingTempBlink && tipTemp > 70) {
if (xTaskGetTickCount() % 50 < 25)
lcd.clearScreen();
}
lcd.refresh();
ButtonState buttons = getButtonState();
if (buttons == BUTTON_F_SHORT)
return 1;
else if (buttons == BUTTON_B_SHORT || buttons == BUTTON_BOTH)
return 0;
if (tipTemp < 50)
return 0; //Exit the warning screen
GUIDelay();
}
return 0;
}
static uint16_t min(uint16_t a, uint16_t b) {
if (a > b)
return b;
@@ -401,14 +353,15 @@ static int gui_SolderingSleepingMode() {
if (checkVoltageForExit())
return 1; // return non-zero on error
if (systemSettings.temperatureInF)
if (systemSettings.temperatureInF) {
currentlyActiveTemperatureTarget = ftoTipMeasurement(
min(systemSettings.SleepTemp,
systemSettings.SolderingTemp));
else
} else {
currentlyActiveTemperatureTarget = ctoTipMeasurement(
min(systemSettings.SleepTemp,
systemSettings.SolderingTemp));
}
// draw the lcd
uint16_t tipTemp;
if (systemSettings.temperatureInF)
@@ -430,11 +383,7 @@ static int gui_SolderingSleepingMode() {
lcd.print("C");
lcd.print(" ");
lcd.printNumber(getInputVoltageX10(systemSettings.voltageDiv) / 10,
2);
lcd.drawChar('.');
lcd.printNumber(getInputVoltageX10(systemSettings.voltageDiv) % 10,
1);
printVoltage();
lcd.drawChar('V');
} else {
lcd.setFont(0);
@@ -530,24 +479,9 @@ static void gui_solderingMode() {
lcd.setCursor(0, 8);
lcd.print(SleepingTipAdvancedString);
uint16_t Temp = getTipRawTemp(0);
if (systemSettings.temperatureInF)
Temp = tipMeasurementToF(Temp);
else
Temp = tipMeasurementToC(Temp);
lcd.printNumber(Temp, 3);
if (systemSettings.temperatureInF)
lcd.print("F");
else
lcd.print("C");
gui_drawTipTemp(true);
lcd.print(" ");
lcd.printNumber(
getInputVoltageX10(systemSettings.voltageDiv) / 10, 2);
lcd.drawChar('.');
lcd.printNumber(
getInputVoltageX10(systemSettings.voltageDiv) % 10, 1);
printVoltage();
lcd.drawChar('V');
} else {
// We switch the layout direction depending on the orientation of the lcd.
@@ -556,13 +490,7 @@ static void gui_solderingMode() {
gui_drawBatteryIcon();
lcd.drawChar(' '); // Space out gap between battery <-> temp
if (systemSettings.temperatureInF) {
gui_drawTipTemp(); // Draw current tip temp
lcd.drawSymbol(0); // deg F
} else {
gui_drawTipTemp(); // Draw current tip temp
lcd.drawSymbol(1); // deg C
}
gui_drawTipTemp(true); // Draw current tip temp
// We draw boost arrow if boosting, or else gap temp <-> heat indicator
if (boostModeOn)
@@ -580,14 +508,7 @@ static void gui_solderingMode() {
lcd.drawSymbol(2);
else
lcd.drawChar(' ');
if (systemSettings.temperatureInF) {
gui_drawTipTemp(); // Draw current tip temp
lcd.drawSymbol(0); // deg F
} else {
gui_drawTipTemp(); // Draw current tip temp
lcd.drawSymbol(1); // deg C
}
gui_drawTipTemp(true); // Draw current tip temp
lcd.drawChar(' '); // Space out gap between battery <-> temp
@@ -632,36 +553,65 @@ static void gui_solderingMode() {
}
}
void showVersion(void) {
uint8_t screen = 0;
ButtonState b;
for (;;) {
lcd.clearScreen(); // Ensure the buffer starts clean
lcd.setCursor(0, 0); // Position the cursor at the 0,0 (top left)
lcd.setFont(1); // small font
lcd.print((char *) "V2.05 PCB"); // Print version number
lcd.printNumber(PCBVersion, 1); //Print PCB ID number
lcd.setCursor(0, 8); // second line
switch (screen) {
case 0:
lcd.print(__DATE__); // print the compile date
break;
case 1:
lcd.print("Heap: ");
lcd.printNumber(xPortGetFreeHeapSize(), 5);
break;
case 2:
lcd.print("HWMG: ");
lcd.printNumber(uxTaskGetStackHighWaterMark(GUITaskHandle), 5);
break;
case 3:
lcd.print("HWMP: ");
lcd.printNumber(uxTaskGetStackHighWaterMark(PIDTaskHandle), 5);
break;
case 4:
lcd.print("HWMM: ");
lcd.printNumber(uxTaskGetStackHighWaterMark(MOVTaskHandle), 5);
break;
case 5:
lcd.print("Time: ");
lcd.printNumber(xTaskGetTickCount() / 100, 5);
break;
case 6:
lcd.print("Move: ");
lcd.printNumber(lastMovementTime / 100, 5);
break;
}
lcd.refresh();
b = getButtonState();
if (b == BUTTON_B_SHORT)
return;
else if (b == BUTTON_F_SHORT) {
screen++;
screen = screen % 7;
}
}
}
/* StartGUITask function */
void startGUITask(void const *argument) {
i2cDev.FRToSInit();
/*
* Main program states:
*
* * Soldering (gui_solderingMode)
* -> Main loop where we draw temp, and animations
* --> User presses buttons and they goto the temperature adjust screen
* ---> Display the current setpoint temperature
* ---> Use buttons to change forward and back on temperature
* ---> Both buttons or timeout for exiting
* --> Long hold front button to enter boost mode
* ---> Just temporarily sets the system into the alternate temperature for
* PID control
* --> Long hold back button to exit
* --> Double button to exit
* * Settings Menu (gui_settingsMenu)
* -> Show setting name
* --> If no button press for > 3 Seconds, scroll description
* -> If user presses back button, adjust the setting
* -> Currently the same as 1.x (future to make more depth based)
*/
uint8_t animationStep = 0;
uint8_t tempWarningState = 0;
bool buttonLockout = false;
HAL_IWDG_Refresh(&hiwdg);
switch (systemSettings.OrientationMode) {
case 0:
lcd.setRotation(false);
@@ -685,8 +635,6 @@ void startGUITask(void const *argument) {
ticks = xTaskGetTickCount(); //make timeout now so we will exit
GUIDelay();
}
HAL_IWDG_Refresh(&hiwdg);
if (systemSettings.autoStartMode) {
// jump directly to the autostart mode
if (systemSettings.autoStartMode == 1)
@@ -723,18 +671,7 @@ void startGUITask(void const *argument) {
case BUTTON_B_LONG:
// Show the version information
{
lcd.clearScreen(); // Ensure the buffer starts clean
lcd.setCursor(0, 0); // Position the cursor at the 0,0 (top left)
lcd.setFont(1); // small font
lcd.print((char *) "V2.04 PCB"); // Print version number
lcd.printNumber(PCBVersion, 1); //Print PCB ID number
lcd.setCursor(0, 8); // second line
lcd.print(__DATE__); // print the compile date
lcd.refresh();
waitForButtonPress();
lcd.setFont(0); // reset font
}
showVersion();
break;
case BUTTON_F_LONG:
gui_solderingTempAdjust();
@@ -744,7 +681,7 @@ void startGUITask(void const *argument) {
lcd.setFont(0);
lcd.displayOnOff(true); // turn lcd on
gui_solderingMode(); // enter soldering mode
buttonLockout = true;
break;
case BUTTON_B_SHORT:
lcd.setFont(0);
@@ -797,11 +734,7 @@ void startGUITask(void const *argument) {
}
lcd.setCursor(0, 8);
lcd.print(InputVoltageString);
lcd.printNumber(getInputVoltageX10(systemSettings.voltageDiv) / 10,
2);
lcd.drawChar('.');
lcd.printNumber(getInputVoltageX10(systemSettings.voltageDiv) % 10,
1);
printVoltage();
lcd.print("V");
} else {
@@ -829,12 +762,11 @@ void startGUITask(void const *argument) {
}
//draw in the temp
lcd.setFont(0); //big font
gui_drawTipTemp(); // draw in the temp
gui_drawTipTemp(false); // draw in the temp
}
}
lcd.refresh();
animationStep++;
GUIDelay();
}
}
@@ -855,76 +787,85 @@ void startPIDTask(void const *argument) {
osDelay(500);
int32_t integralCount = 0;
int32_t derivativeLastValue = 0;
int32_t kp, ki, kd;
ki = 50;
kd = 15;
// REMEBER ^^^^ These constants are backwards
// They act as dividers, so to 'increase' a P term, you make the number
// smaller.
if (getInputVoltageX10(systemSettings.voltageDiv) < 150) {
//Boot P term if < 15 Volts
kp = 30;
} else
kp = 42;
// REMEBER ^^^^ These constants are backwards
// They act as dividers, so to 'increase' a P term, you make the number
// smaller.
const int32_t itermMax = 100;
pidTaskNotification = xTaskGetCurrentTaskHandle();
for (;;) {
ulTaskNotifyTake( pdTRUE, 50); //Wait a max of 50ms
//This is a call to block this thread until the ADC does its samples
uint16_t rawTemp = getTipRawTemp(1); // get instantaneous reading
if (currentlyActiveTemperatureTarget) {
// Compute the PID loop in here
// Because our values here are quite large for all measurements (0-16k ~=
// 33 counts per C)
// P I & D are divisors, so inverse logic applies (beware)
if (ulTaskNotifyTake( pdTRUE, 50)) {
//Wait a max of 50ms
//This is a call to block this thread until the ADC does its samples
uint16_t rawTemp = getTipRawTemp(1); // get instantaneous reading
if (currentlyActiveTemperatureTarget) {
// Compute the PID loop in here
// Because our values here are quite large for all measurements (0-16k ~=
// 33 counts per C)
// P I & D are divisors, so inverse logic applies (beware)
// Cap the max set point to 450C
if (currentlyActiveTemperatureTarget > ctoTipMeasurement(450)) {
currentlyActiveTemperatureTarget = ctoTipMeasurement(450);
// Cap the max set point to 450C
if (currentlyActiveTemperatureTarget > ctoTipMeasurement(450)) {
currentlyActiveTemperatureTarget = ctoTipMeasurement(450);
}
int32_t rawTempError = currentlyActiveTemperatureTarget
- rawTemp;
int32_t ierror = (rawTempError / ((int32_t)systemSettings.PID_I));
integralCount += ierror;
if (integralCount > (itermMax / 2))
integralCount = itermMax / 2; // prevent too much lead
else if (integralCount < -itermMax)
integralCount = itermMax;
int32_t dInput = (rawTemp - derivativeLastValue);
/*Compute PID Output*/
int32_t output = (rawTempError / ((int32_t)systemSettings.PID_P));
if (((int32_t)systemSettings.PID_I))
output += integralCount;
if (((int32_t)systemSettings.PID_D))
output -= (dInput / ((int32_t)systemSettings.PID_D));
if (output > 100) {
output = 100; // saturate
} else if (output < 0) {
output = 0;
}
/*if (currentlyActiveTemperatureTarget < rawTemp) {
output = 0;
}*/
setTipPWM(output);
derivativeLastValue = rawTemp; // store for next loop
} else {
setTipPWM(0); // disable the output driver if the output is set to be off
integralCount = 0;
derivativeLastValue = 0;
}
int32_t rawTempError = currentlyActiveTemperatureTarget - rawTemp;
int32_t ierror = (rawTempError / ki);
integralCount += ierror;
if (integralCount > (itermMax / 2))
integralCount = itermMax / 2; // prevent too much lead
else if (integralCount < -itermMax)
integralCount = itermMax;
int32_t dInput = (rawTemp - derivativeLastValue);
/*Compute PID Output*/
int32_t output = (rawTempError / kp);
if (ki)
output += integralCount;
if (kd)
output -= (dInput / kd);
if (output > 100) {
output = 100; // saturate
} else if (output < 0) {
output = 0;
}
/*if (currentlyActiveTemperatureTarget < rawTemp) {
output = 0;
}*/
setTipPWM(output);
derivativeLastValue = rawTemp; // store for next loop
} else {
setTipPWM(0); // disable the output driver if the output is set to be off
integralCount = 0;
derivativeLastValue = 0;
osDelay(100); //sleep for a bit longer
HAL_IWDG_Refresh(&hiwdg);
}
HAL_IWDG_Refresh(&hiwdg);
}
}
#define MOVFilter 8
void startMOVTask(void const *argument) {
osDelay(250); // wait for accelerometer to stabilize
switch (systemSettings.OrientationMode) {
case 0:
lcd.setRotation(false);
break;
case 1:
lcd.setRotation(true);
break;
case 2:
lcd.setRotation(false);
break;
default:
break;
}
lastMovementTime = 0;
int16_t datax[MOVFilter];
int16_t datay[MOVFilter];
@@ -940,20 +881,29 @@ void startMOVTask(void const *argument) {
#if ACCELDEBUG
uint32_t max = 0;
#endif
uint8_t rotation = 0;
for (;;) {
int32_t threshold = 1500 + (9 * 200);
threshold -= systemSettings.sensitivity * 200; // 200 is the step size
if (PCBVersion == 2)
accel2.getAxisReadings(&tx, &ty, &tz);
else if (PCBVersion == 1)
accel.getAxisReadings(&tx, &ty, &tz);
if (PCBVersion == 2) {
accel2.getAxisReadings(&tx, &ty, &tz);
rotation = accel2.getOrientation();
} else if (PCBVersion == 1) {
accel.getAxisReadings(&tx, &ty, &tz);
rotation = accel.getOrientation();
}
if (systemSettings.OrientationMode == 2) {
if (rotation != 0) {
lcd.setRotation(rotation == 2); // link the data through
}
}
datax[currentPointer] = (int32_t) tx;
datay[currentPointer] = (int32_t) ty;
dataz[currentPointer] = (int32_t) tz;
currentPointer = (currentPointer + 1) % MOVFilter;
#if ACCELDEBUG
// Debug for Accel
avgx = avgy = avgz = 0;
@@ -995,6 +945,7 @@ void startMOVTask(void const *argument) {
// So now we have averages, we want to look if these are different by more
// than the threshold
//Sum the deltas
int32_t error = (abs(avgx - tx) + abs(avgy - ty) + abs(avgz - tz));
// If error has occurred then we update the tick timer
if (error > threshold) {
@@ -1004,52 +955,14 @@ void startMOVTask(void const *argument) {
osDelay(100); // Slow down update rate
}
}
/* StartRotationTask function */
void startRotationTask(void const *argument) {
/*
* This task is used to manage rotation of the LCD screen & button re-mapping
*
*/
switch (systemSettings.OrientationMode) {
case 0:
lcd.setRotation(false);
break;
case 1:
lcd.setRotation(true);
break;
case 2:
lcd.setRotation(false);
break;
default:
break;
}
osDelay(250); // wait for accel to stabilize
for (;;) {
// a rotation event has occurred
uint8_t rotation = 0;
if (PCBVersion == 2) {
rotation = accel2.getOrientation();
} else if (PCBVersion == 1) {
rotation = accel.getOrientation();
}
if (systemSettings.OrientationMode == 2) {
if (rotation != 0) {
lcd.setRotation(rotation == 2); // link the data through
}
}
osDelay(500);
}
}
#define FLASH_LOGOADDR \
(0x8000000 | 0xF800) /*second last page of flash set aside for logo image*/
bool showBootLogoIfavailable() {
// check if the header is there (0xAA,0x55,0xF0,0x0D)
// If so display logo
// check if the header is there (0xAA,0x55,0xF0,0x0D)
// If so display logo
//TODO REDUCE STACK ON THIS ONE, USE DRAWING IN THE READ LOOP
uint16_t temp[98];
for (uint8_t i = 0; i < (98); i++) {
@@ -1097,7 +1010,6 @@ void HAL_I2C_MasterTxCpltCallback(I2C_HandleTypeDef *hi2c) {
i2cDev.CpltCallback();
}
void HAL_I2C_MemTxCpltCallback(I2C_HandleTypeDef *hi2c) {
i2cDev.CpltCallback();
}
void HAL_I2C_ErrorCallback(I2C_HandleTypeDef *hi2c) {
@@ -1109,3 +1021,9 @@ void HAL_I2C_AbortCpltCallback(I2C_HandleTypeDef *hi2c) {
void HAL_I2C_MemRxCpltCallback(I2C_HandleTypeDef *hi2c) {
i2cDev.CpltCallback();
}
void vApplicationStackOverflowHook( xTaskHandle *pxTask,
signed portCHAR *pcTaskName) {
//We dont have a good way to handle a stack overflow at this point in time
NVIC_SystemReset();
}

View File

@@ -28,9 +28,9 @@ void HAL_MspInit(void) {
/**NOJTAG: JTAG-DP Disabled and SW-DP Enabled
*/
__HAL_AFIO_REMAP_SWJ_NOJTAG()
;
// __HAL_AFIO_REMAP_SWJ_DISABLE(); /*Disable swd for debug io use*/
//__HAL_AFIO_REMAP_SWJ_NOJTAG()
//;
__HAL_AFIO_REMAP_SWJ_DISABLE(); /*Disable swd for debug io use*/
}
@@ -68,7 +68,7 @@ void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) {
__HAL_LINKDMA(hadc, DMA_Handle, hdma_adc1);
/* ADC1 interrupt Init */
HAL_NVIC_SetPriority(ADC1_2_IRQn, 5, 0);
HAL_NVIC_SetPriority(ADC1_2_IRQn, 15, 0);
HAL_NVIC_EnableIRQ(ADC1_2_IRQn);
}
@@ -118,9 +118,9 @@ void HAL_I2C_MspInit(I2C_HandleTypeDef* hi2c) {
__HAL_LINKDMA(hi2c, hdmatx, hdma_i2c1_tx);
/* I2C1 interrupt Init */
HAL_NVIC_SetPriority(I2C1_EV_IRQn, 5, 0);
HAL_NVIC_SetPriority(I2C1_EV_IRQn, 15, 0);
HAL_NVIC_EnableIRQ(I2C1_EV_IRQn);
HAL_NVIC_SetPriority(I2C1_ER_IRQn, 5, 0);
HAL_NVIC_SetPriority(I2C1_ER_IRQn, 15, 0);
HAL_NVIC_EnableIRQ(I2C1_ER_IRQn);
}

View File

@@ -7,7 +7,6 @@
extern TIM_HandleTypeDef htim1; //used for the systick
/******************************************************************************/
/* Cortex-M3 Processor Interruption and Exception Handlers */
/******************************************************************************/
@@ -55,8 +54,6 @@ void SysTick_Handler(void) {
void DMA1_Channel1_IRQHandler(void) {
HAL_DMA_IRQHandler(&hdma_adc1);
}
//ADC interrupt used for DMA
void ADC1_2_IRQHandler(void) {
HAL_ADC_IRQHandler(&hadc1);
@@ -65,7 +62,6 @@ void ADC1_2_IRQHandler(void) {
//Timer 1 has overflowed, used for HAL ticks
void TIM1_UP_IRQHandler(void) {
HAL_TIM_IRQHandler(&htim1);
}
//Timer 3 is used for the PWM output to the tip
void TIM3_IRQHandler(void) {
@@ -76,15 +72,6 @@ void TIM3_IRQHandler(void) {
void TIM2_IRQHandler(void) {
HAL_TIM_IRQHandler(&htim2);
}
//EXTI 3 is triggered via the accelerometer on orientation change
void EXTI3_IRQHandler(void) {
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_3);
}
//EXTI 5 is triggered via the accelerometer on movement
void EXTI9_5_IRQHandler(void) {
HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_5);
}
void I2C1_EV_IRQHandler(void) {
HAL_I2C_EV_IRQHandler(&hi2c1);
@@ -93,12 +80,10 @@ void I2C1_ER_IRQHandler(void) {
HAL_I2C_ER_IRQHandler(&hi2c1);
}
void DMA1_Channel6_IRQHandler(void)
{
HAL_DMA_IRQHandler(&hdma_i2c1_tx);
void DMA1_Channel6_IRQHandler(void) {
HAL_DMA_IRQHandler(&hdma_i2c1_tx);
}
void DMA1_Channel7_IRQHandler(void)
{
HAL_DMA_IRQHandler(&hdma_i2c1_rx);
void DMA1_Channel7_IRQHandler(void) {
HAL_DMA_IRQHandler(&hdma_i2c1_rx);
}