Initial commit of Fertirrega v6

This commit is contained in:
2026-07-16 12:04:22 +01:00
commit 08709213d9
247 changed files with 126849 additions and 0 deletions
+610
View File
@@ -0,0 +1,610 @@
/**
* @file ad5934_driver.c
* @brief Implementation of AD5934 I2C impedance converter driver.
*
* This driver provides functions to configure and read from the AD5934
* 16-bit, 200kHz I2C impedance converter. The device supports frequency sweep
* measurements and provides magnitude and phase data.
*
* @note Based on AD5934 datasheet Rev. E October 2017
*/
#include "ad5934_driver.h"
const float calibrationResistance[3] = {AD5934_GAIN_FACTOR_100R, AD5934_GAIN_FACTOR_1K, AD5934_GAIN_FACTOR_10K};
int16_t temperature_dut_samples[AD5934_TEMP_AVERAGES][2]={{0},{0}};
int16_t temperature_ref_samples[AD5934_TEMP_AVERAGES][2]={{0},{0}};
float temperature_display[AD5934_TEMP_AVERAGES] = {0};
int16_t ec_dut_samples[AD5934_EC_AVERAGES][2]={{0},{0}};
int16_t ec_ref_samples_H[AD5934_EC_AVERAGES][2]={{0},{0}};
int16_t ec_ref_samples_L[AD5934_EC_AVERAGES][2]={{0},{0}};
float ec_display[AD5934_EC_AVERAGES] = {0};
/******************************************************************************
* @brief Set an AD5934 internal register value.
*
* @param registerAddress - Address of AD5934 register. LB Byte Address when more than 1 byte
*
* @param registerValue - Value of data to be written in the register.
*
* @param numberOfBytes - Number of bytes to be written in the register
*
* @return None.
******************************************************************************/
void AD5934_SetRegisterValue(uint8_t registerAddress, uint32_t registerValue, uint8_t numberOfBytes)
{
uint8_t writeData[2] = {0, 0};
HAL_StatusTypeDef status;
union Bytes2Long AD5934_reg;
AD5934_reg.number = registerValue;
for (uint8_t i = 0; i < numberOfBytes; i++)
{
writeData[0] = registerAddress - i;
writeData[1] = AD5934_reg.bytes[i];
status = HAL_I2C_Master_Transmit(&hi2c2, AD5934_I2C_ADDRESS, writeData, 2, 5);
}
return;
}
/******************************************************************************
* @brief Read an AD5934 internal register value.
*
* @param registerAddress - Address of AD5933 register.
*
* @param numberOfBytes - Number of bytes to be read from the register.
*
* @return Register value.
******************************************************************************/
uint32_t AD5934_GetRegisterValue(uint8_t registerAddress, uint8_t numberOfBytes)
{
uint8_t readData[1] = {0};
uint8_t writeData[2]; //= {AD5934_ADDR_POINTER, registerAddress};
union Bytes2Long AD5934_reg;
HAL_StatusTypeDef status;
if(numberOfBytes > 4)
return 0xFFFFFFFF; //Overflow
AD5934_reg.number = 0;
for (uint8_t i = 0; i < numberOfBytes; i++)
{
writeData[0] = AD5934_ADDR_POINTER;
writeData[1] = registerAddress - i;
status = HAL_I2C_Master_Transmit(&hi2c2, AD5934_I2C_ADDRESS, writeData, 2, 5);
//HAL_Delay(1);
readData[0] = 0;
status = HAL_I2C_Master_Receive(&hi2c2, AD5934_I2C_ADDRESS, readData, 1, 5);
AD5934_reg.bytes[i]=readData[0];
}
/*
AD5934_value.byte[0] = (uint16_t)(AD5934_reg.number & 0x0000FFFF) + 2048;
AD5934_value.ints[1] = (uint16_t)((AD5934_reg.number & 0xFFFF0000)>>16) + 2048;
*/
return AD5934_reg.number;
}
/************************************************************************************
* @brief Lê um registrador do AD5934 usando a abstração Mem_Read (mais segura).
*
* @param regAddr Endereço do registrador no AD5934.
* @return uint32_t Valor lido do registrador.
***********************************************************************************/
uint32_t AD5934_ReadRegister(uint8_t regAddr, uint8_t numberOfBytes)
{
uint32_t registerValue = 0;
uint8_t readData[4] = {0,0,0,0}; // Buffer para receber 16 bits (AD5934 usa regs de 16-bit)
uint8_t writeData[2] = {AD5934_ADDR_POINTER,regAddr};
HAL_StatusTypeDef status;
//Limit buffer size to prevent stack overflow (AD5934 regs are max 4 bytes) */
if (numberOfBytes > 4)
{
return 0xFFFFFFFF;
}
status = HAL_I2C_Master_Transmit(&hi2c2, AD5934_I2C_ADDRESS, writeData, 2, 5);
HAL_Delay(1);
// Usamos Mem_Read que faz: START -> ADDR+W -> REG_ADDR -> REPEATED_START -> ADDR+R -> DATA -> STOP
status = HAL_I2C_Mem_Read(&hi2c2, AD5934_I2C_ADDRESS, AD5934_BLOCK_READ, I2C_MEMADD_SIZE_8BIT, readData, numberOfBytes, 5);
/* 5. Reconstruct value from Big-Endian buffer */
for (uint8_t i = 0; i < numberOfBytes; i++)
{
registerValue = (registerValue << 8) | readData[i];
}
return registerValue;
}
/******************************************************************************
* @brief Configure and Start the AD5934 frequency sweep parameters.
*
* @param None.
*
* @return None.
******************************************************************************/
void AD5934_Init(void)
{
/************ Config Sweep******************/
// Place AD5934 in reset
AD5934_SetRegisterValue(AD5934_CONTROL_REG_LB, (AD5934_CONTROL_FUNCTION(AD5934_RESET)), 1);
// Configure starting frequency
AD5934_SetRegisterValue(AD5934_START_FREQ_REG_LB, AD5934_FREQ_1K590HZ, 3);
// Configure frequency increment step
AD5934_SetRegisterValue(AD5934_FREQ_INCR_REG_LB, AD5934_FREQ_0HZ, 3);
// Configure number of steps
AD5934_SetRegisterValue(AD5934_NR_INCR_REG_LB, AD5934_STEP_FREQ_0, 2);
// Set 128 Settling Time
AD5934_SetRegisterValue(AD5934_NR_SETTLE_REG_LB, AD5934_SETTLING_TIME_0S01, 2);
}
/******************************************************************************
* @brief Re-Start the AD5934 frequency sweep parameters.
*
* @param None.
*
* @return None.
******************************************************************************/
void AD5934_RestartSweep(void)
{
// Place AD5934 in standby
AD5934_SetRegisterValue(AD5934_CONTROL_REG_HB, (AD5934_CONTROL_FUNCTION(AD5934_STANDBY) | AD5934_CONTROL_RANGE(AD5934_400mVpp_RANGE) | AD5934_PGA_GAIN(AD5934_PGA_GAIN_X5)), 1);
// Initialize starting frequency, Start frequency sweep, standby
AD5934_SetRegisterValue(AD5934_CONTROL_REG_HB, ((AD5934_CONTROL_FUNCTION(AD5934_INIT_START_FREQ)) | AD5934_CONTROL_RANGE(AD5934_400mVpp_RANGE) | AD5934_PGA_GAIN(AD5934_PGA_GAIN_X5)), 1);
// Configure Range Output, PGA gain andPlace AD5934 in sweep
AD5934_SetRegisterValue(AD5934_CONTROL_REG_HB, (AD5934_CONTROL_FUNCTION(AD5934_START_FREQ_SWEEP) | AD5934_CONTROL_RANGE(AD5934_400mVpp_RANGE) | AD5934_PGA_GAIN(AD5934_PGA_GAIN_X5)), 1);
// Wait for data to be valid
AD5934_Wait_For_Data_Valid();
// Power Down
AD5934_SetRegisterValue(AD5934_CONTROL_REG_HB, (AD5934_CONTROL_FUNCTION(AD5934_POWER_DOWN) | AD5934_CONTROL_RANGE(AD5934_400mVpp_RANGE) | AD5934_PGA_GAIN(AD5934_PGA_GAIN_X5)), 1);
}
/******************************************************************************
* @brief Start the AD5934 frequency sweep parameters.
*
* @param: channel = AD5934_CH_REF_100R, AD5934_CH_REF_1K, AD5934_CH_REF_10K, AD5934_CH_PT100, AD5934_CH_PT1000 or AD5934_CH_EC
*
* @return Real(int16) and Imaginary(int16) numbers into a int32.
******************************************************************************/
uint32_t AD5934_Sweep(void)
{
int16_t real_value, imag_value;
uint32_t value=0;
// Restart Sweeping
AD5934_RestartSweep();
real_value = ((AD5934_GetRegisterValue(AD5934_REAL_REG_LB,2)));
imag_value = ((AD5934_GetRegisterValue(AD5934_IMG_REG_LB,2)));
// Get Real (16-bit) and Imaginary (16-bit) values into an unsigned 32-bit
value = ((((uint16_t)(imag_value))<<16) | ((uint16_t)(real_value)));
return value;
}
/******************************************************************************
* @brief Calculate Temperature.
*
* @param channel - AD5934_CH_PT100 or AD5934_CH_PT1000.
*
* @return impedance.
******************************************************************************/
float AD5934_GetTemperature(void)
{
uint8_t i, channel;
uint32_t sample;
int32_t ref_sum[2], dut_sum[2];
float real_ref,imag_ref, real_dut, imag_dut, ratio, discriminant, mag_dut, mag_ref, ratio_mag, impedance_dut, temperature_sum;
if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_7) == GPIO_PIN_SET) // OFF = PT1000, ON = PT100, PA7 has internal pull-up and switch connects to GND
channel = AD5934_CH_PT100;
else
channel = AD5934_CH_PT1000;
ADG715_Update(channel + AD5934_CH_DELTA); // Set the Reference Resistor on board in the Analog Mux
HAL_Delay(2); //Wait a little
sample = AD5934_Sweep(); // Get Reference Resistor Values from ADC
// Move values in the vectors
for (i = (AD5934_TEMP_AVERAGES-1); i > 0; i--)
{
temperature_ref_samples[i][0] = temperature_ref_samples[i-1][0]; //real
temperature_ref_samples[i][1] = temperature_ref_samples[i-1][1]; //imag
}
// Read real and imaginary data
temperature_ref_samples[0][0] = (int16_t)(sample & 0x0000FFFF); //real
//temperature_ref_samples[0][1] = 0xFFFF-(((sample & 0xFFFF0000)>>16)); //imag
temperature_ref_samples[0][1] = (int16_t)((sample & 0xFFFF0000)>>16); //imag
// Sum values in the vectors
for (i = 0, ref_sum[0]=0, ref_sum[1]=0; i < AD5934_TEMP_AVERAGES; i++)
{
ref_sum[0] += (int32_t)temperature_ref_samples[i][0]; //real
ref_sum[1] += (int32_t)temperature_ref_samples[i][1]; //imag
}
real_ref = ((float)ref_sum[0])/((float)AD5934_TEMP_AVERAGES);
imag_ref = ((float)ref_sum[1])/((float)AD5934_TEMP_AVERAGES);
// Calculate gain factor impedance
mag_ref = sqrtf((real_ref * real_ref) + (imag_ref * imag_ref));
ADG715_Update(channel);
HAL_Delay(2);
sample = AD5934_Sweep(); // Get PT100/PT1000 Values from ADC
for (i = (AD5934_TEMP_AVERAGES-1); i > 0; i--)
{
temperature_dut_samples[i][0] = temperature_dut_samples[i-1][0]; //real
temperature_dut_samples[i][1] = temperature_dut_samples[i-1][1]; //imag
}
// Read real and imaginary data
temperature_dut_samples[0][0] = (int16_t)(sample & 0x0000FFFF); //real
//temperature_dut_samples[0][1] = 0xFFFF-(((sample & 0xFFFF0000)>>16)); //imag
temperature_dut_samples[0][1] = (int16_t)((sample & 0xFFFF0000)>>16); //imag
for (i = 0, dut_sum[0]=0, dut_sum[1]=0; i < AD5934_TEMP_AVERAGES; i++)
{
dut_sum[0] += (int32_t)temperature_dut_samples[i][0]; //real
dut_sum[1] += (int32_t)temperature_dut_samples[i][1]; //imag
}
real_dut = ((float)dut_sum[0])/((float)AD5934_TEMP_AVERAGES);
imag_dut = ((float)dut_sum[1])/((float)AD5934_TEMP_AVERAGES);
// Calculate magnitude
mag_dut = sqrtf((real_dut * real_dut) + (imag_dut * imag_dut));
for (i = (AD5934_TEMP_AVERAGES-1); i > 0; i--)
temperature_display[i] = temperature_display[i-1];
ratio_mag = mag_ref / mag_dut;
if(channel==AD5934_CH_PT100)
impedance_dut = AD5934_Linear_Correction((calibrationResistance[channel & 0x0F]) * ratio_mag);
else
impedance_dut = (calibrationResistance[channel & 0x0F]) * ratio_mag;
// Calculate impedance ratio with the Reference Resistor
ratio = impedance_dut / (calibrationResistance[channel & 0x0F]);
// Calculate impedance discriminant with the ratio
discriminant = (AD5934_RTD_A*AD5934_RTD_A)-(4.0f * AD5934_RTD_B * (1.0f - ratio));
// Calculate new temperature with the discriminant
temperature_display[0] = (-AD5934_RTD_A + sqrtf(discriminant))/(2.0f * AD5934_RTD_B);
// Sum of all temperatures
for (i = 0, temperature_sum=0.0f; i < AD5934_TEMP_AVERAGES; i++)
temperature_sum += temperature_display[i];
// Is the temperature stable?
if(temperature_display[0]>0.0f && (abs(temperature_display[0]-temperature_display[AD5934_TEMP_AVERAGES-1])/temperature_display[0])<0.1f)
return(AD5934_Round_Float_Precision(temperature_sum/((float)AD5934_TEMP_AVERAGES),1)); // Sum / number of averages
else
return 0.0f; //instable values return always 0
}
/******************************************************************************
* @brief Calculate impedance.
*
* @param none.
*
* @return impedance.
******************************************************************************/
float AD5934_GetImpedance(void)
{
uint8_t i, channel;
uint32_t sample_H, sample_L, sample_dut;
int32_t ref_sum_H[2], ref_sum_L[2], dut_sum[2];
float real_number, imag_number, mag_dut, mag_ref_H, mag_ref_L, gain_factor_H, gain_factor_L, gain_factor_dut, slope, admittance;
/* STEP 1: Two points reference curve */
ADG715_Update(AD5934_CH_REF_1K); // Set the Reference for High Resistor on board in the Analog Mux
HAL_Delay(2); //Wait a little
sample_H = AD5934_Sweep(); // Get Reference Resistor 1 from ADC
ADG715_Update(AD5934_CH_REF_100R); // Set the Reference for Low Resistor on board in the Analog Mux
HAL_Delay(2); //Wait a little
sample_L = AD5934_Sweep(); // Get Reference Resistor 2 from ADC
// Move values in the vectors
for (i = (AD5934_EC_AVERAGES-1); i > 0; i--)
{
ec_ref_samples_H[i][0] = ec_ref_samples_H[i-1][0]; //real
ec_ref_samples_H[i][1] = ec_ref_samples_H[i-1][1]; //imag
ec_ref_samples_L[i][0] = ec_ref_samples_L[i-1][0]; //real
ec_ref_samples_L[i][1] = ec_ref_samples_L[i-1][1]; //imag
}
// Read real and imaginary data
ec_ref_samples_H[0][0] = (int16_t)(sample_H & 0x0000FFFF); //real
ec_ref_samples_H[0][1] = (int16_t)((sample_H & 0xFFFF0000)>>16); //imag
//ec_ref_samples_H[0][1] = (int16_t)((0xFFFF - (sample_H & 0xFFFF0000)>>16)); //imag
// Read real and imaginary data
ec_ref_samples_L[0][0] = (int16_t)(sample_L & 0x0000FFFF); //real
ec_ref_samples_L[0][1] = (int16_t)((sample_L & 0xFFFF0000)>>16); //imag
//ec_ref_samples_L[0][1] = (int16_t)((0xFFFF - (sample_L & 0xFFFF0000)>>16)); //imag
// Sum values in the vectors
for (i = 0, ref_sum_H[0]=0, ref_sum_H[1]=0, ref_sum_L[0]=0, ref_sum_L[1]=0; i < AD5934_EC_AVERAGES; i++)
{
ref_sum_H[0] += (int32_t)ec_ref_samples_H[i][0]; //real
ref_sum_H[1] += (int32_t)ec_ref_samples_H[i][1]; //imag
ref_sum_L[0] += (int32_t)ec_ref_samples_L[i][0]; //real
ref_sum_L[1] += (int32_t)ec_ref_samples_L[i][1]; //imag
}
real_number = ((float)ref_sum_H[0])/((float)AD5934_EC_AVERAGES);
imag_number = ((float)ref_sum_H[1])/((float)AD5934_EC_AVERAGES);
// Calculate gain factor impedance
mag_ref_H = sqrtf((real_number * real_number) + (imag_number * imag_number));
if(mag_ref_H > 0.0f)
gain_factor_H = 1.0f / (1000.0f * mag_ref_H);
else
gain_factor_H = 0.0f;
real_number = ((float)ref_sum_L[0])/((float)AD5934_EC_AVERAGES);
imag_number = ((float)ref_sum_L[1])/((float)AD5934_EC_AVERAGES);
// Calculate gain factor impedance
mag_ref_L = sqrtf((real_number * real_number) + (imag_number * imag_number));
if(mag_ref_L > 0.0f)
gain_factor_L = 1.0f / (100.0f * mag_ref_L);
else
gain_factor_L = 0.0f;
/* STEP 2: Set the Amplification related to the maximum set value */
if(HAL_GPIO_ReadPin(GPIOA, GPIO_PIN_6) == GPIO_PIN_SET) // PA6 has internal pull-up and the Switch connects to GND
channel = AD5934_CH_EC_5MS; // Switch OFF = 5 mS/cm
else
channel = AD5934_CH_EC_10MS; // Switch ON = 10 mS/cm
ADG715_Update(channel);
HAL_Delay(2);
sample_dut = AD5934_Sweep(); // Get PT100/PT1000 Values from ADC
for (i = (AD5934_EC_AVERAGES-1); i > 0; i--)
{
ec_dut_samples[i][0] = ec_dut_samples[i-1][0]; //real
ec_dut_samples[i][1] = ec_dut_samples[i-1][1]; //imag
}
// Read real and imaginary data
ec_dut_samples[0][0] = (int16_t)(sample_dut & 0x0000FFFF); //real
ec_dut_samples[0][1] = (int16_t)((sample_dut & 0xFFFF0000)>>16); //imag
//ec_dut_samples[0][1] = (int16_t)((0xFFFF - (sample_dut & 0xFFFF0000)>>16)); //imag
for (i = 0, dut_sum[0]=0, dut_sum[1]=0; i < AD5934_EC_AVERAGES; i++)
{
dut_sum[0] += (int32_t)ec_dut_samples[i][0]; //real
dut_sum[1] += (int32_t)ec_dut_samples[i][1]; //imag
}
real_number = ((float)dut_sum[0])/((float)AD5934_EC_AVERAGES);
imag_number = ((float)dut_sum[1])/((float)AD5934_EC_AVERAGES);
// Calculate unknown magnitude
mag_dut = sqrtf((real_number * real_number) + (imag_number * imag_number));
// Calculate gain factor for the unknown magnitude
if(mag_ref_H != mag_ref_L)
slope = ((gain_factor_H - gain_factor_L)/(mag_ref_H - mag_ref_L));
//slope = ((gain_factor_H - gain_factor_L)/(log10f(mag_ref_H) - log10f(mag_ref_L)));
else
return 0.0f;
//gain_factor_dut = gain_factor_L + (log10f(mag_dut) - log10f(mag_ref_L)) * slope;
gain_factor_dut = gain_factor_L + (mag_dut - mag_ref_L) * slope;
// Calculate and return admittance in mS
return(10.0f * mag_dut * gain_factor_dut);
}
/**
* @brief Monitora o status com TIMEOUT para evitar travamento do sistema.
*/
void AD5934_Wait_For_Data_Valid(void)
{
uint32_t timeout_counter = 0;
const uint32_t MAX_TIMEOUT = 10000; // Limite de tentativas
uint8_t status;
while (1)
{
status = (uint8_t)AD5934_GetRegisterValue(AD5934_STATUS_REG, 1);
if ((status & AD5934_STATUS_DATA_VALID) != 0)
{
break; // Sucesso!
}
timeout_counter++;
if (timeout_counter >= MAX_TIMEOUT)
{
// TRATAMENTO DE ERRO: O sistema não travou, mas o chip falhou.
break;
}
HAL_Delay(1); // Pequeno delay para não sobrecarregar o barramento I2C
}
}
/**
* @brief Reduz a precisão decimal de um float através de truncamento.
*
* @param valor O valor float original.
* @param casas_decimais Quantidade de casas que devem permanecer após a vírgula.
* @return float O valor com as casas decimais excedentes removidas.
*/
float AD5934_Round_Float_Precision(float value, uint8_t number_of_decimals)
{
float multiply = 1.0f;
for (uint8_t i = 0; i < number_of_decimals; i++)
multiply *= 10.0f;
return roundf(value * multiply) / multiply;
}
/**
* @brief Performs a linear transformation optimized to match the provided dataset.
*
* This function implements a linear regression model: y = mx + c
* Derived from least squares fitting of the input/output pairs:
* m (slope) ≈ 1.02236
* c (offset) ≈ -2.1163
*
* The implementation is branchless (no conditionals) to ensure constant
* execution time (O(1)) and prevent pipeline stalls in ARM Cortex-M3.
*
* @param input_val The raw float value from sensor/ADC.
* @return float The transformed value following the requested trend.
*/
float AD5934_Linear_Correction(float raw_value)
{
/* Pre-calculated constants from regression analysis */
const float slope = 1.02281f;
const float offset = (-2.1409f);
/* Single FPU instruction (if FPU available) or optimized software float mul/add */
return (raw_value * slope) + offset;
}
/*****************************************************************************
* ADG715
*****************************************************************************
* @brief Writes data into a register.
*
* @param registerAddress - Address of the register.
* @param registerValue - Data value to write.
* @param bytesNumber - Number of bytes.
*
* @return None.
*******************************************************************************/
void ADG715_SetRegisterValue(char value)
{
uint8_t writeData[1] = {value};
HAL_StatusTypeDef status;
status = HAL_I2C_Master_Transmit(&hi2c2, ADG715_I2C_ADDRESS, writeData, 1, 1);
return;
}
void ADG715_SetChannels(uint8_t ch1, uint8_t ch2)
{
ADG715_SetRegisterValue(ch1+ch2);
}
void ADG715_ResetChannels(void)
{
ADG715_SetRegisterValue(0);
}
/******************************************************************************
* @brief Update Channels on the ADG715 and stop-start AD5934.
*
* @param: channel = AD5934_CH_REF_100R, AD5934_CH_REF_1K, AD5934_CH_REF_10K, AD5934_CH_PT100, AD5934_CH_PT1000 or AD5934_CH_EC
*
* @return none.
******************************************************************************/
void ADG715_Update(uint8_t channel)
{
HAL_StatusTypeDef status;
// Disconnect all Analog Switches
ADG715_ResetChannels();
// Set the pair of connections
if(channel == AD5934_CH_REF_100R)
{
ADG715_SetChannels(ADG715_SW1, ADG715_SW4); // Rf = 150R, Ch = Ref_100R
}
else if(channel == AD5934_CH_REF_1K)
{
ADG715_SetChannels(ADG715_SW2, ADG715_SW5); // Rf = 1k5, Ch = Ref_1k
}
else if(channel == AD5934_CH_REF_10K)
{
ADG715_SetChannels(ADG715_SW3, ADG715_SW6); // Rf = 6k2, Ch = Ref_10k
}
else if(channel == AD5934_CH_PT100)
{
ADG715_SetChannels(ADG715_SW1, ADG715_SW7); // Rf = 150R, Ch = PT100
}
else if(channel == AD5934_CH_PT1000)
{
ADG715_SetChannels(ADG715_SW2, ADG715_SW7); // Rf = 1k5, Ch = PT1000
}
else if(channel == AD5934_CH_EC_10MS)
{
ADG715_SetChannels(ADG715_SW2, ADG715_SW8); // Rf = 1k5, Ch = EC 10 mS/cm Max
}
else if(channel == AD5934_CH_EC_5MS)
{
ADG715_SetChannels(ADG715_SW3, ADG715_SW8); // Rf = 6k2, Ch = EC 5 mS/cm Max
}
}
+205
View File
@@ -0,0 +1,205 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file adc.c
* @brief This file provides code for the configuration
* of the ADC instances.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "adc.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
ADC_HandleTypeDef hadc1;
ADC_HandleTypeDef hadc2;
/* ADC1 init function */
void MX_ADC1_Init(void)
{
/* USER CODE BEGIN ADC1_Init 0 */
/* USER CODE END ADC1_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC1_Init 1 */
/* USER CODE END ADC1_Init 1 */
/** Common config
*/
hadc1.Instance = ADC1;
hadc1.Init.ScanConvMode = ADC_SCAN_DISABLE;
hadc1.Init.ContinuousConvMode = DISABLE;
hadc1.Init.DiscontinuousConvMode = DISABLE;
hadc1.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc1.Init.NbrOfConversion = 1;
if (HAL_ADC_Init(&hadc1) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_0;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC1_Init 2 */
/* USER CODE END ADC1_Init 2 */
}
/* ADC2 init function */
void MX_ADC2_Init(void)
{
/* USER CODE BEGIN ADC2_Init 0 */
/* USER CODE END ADC2_Init 0 */
ADC_ChannelConfTypeDef sConfig = {0};
/* USER CODE BEGIN ADC2_Init 1 */
/* USER CODE END ADC2_Init 1 */
/** Common config
*/
hadc2.Instance = ADC2;
hadc2.Init.ScanConvMode = ADC_SCAN_DISABLE;
hadc2.Init.ContinuousConvMode = DISABLE;
hadc2.Init.DiscontinuousConvMode = DISABLE;
hadc2.Init.ExternalTrigConv = ADC_SOFTWARE_START;
hadc2.Init.DataAlign = ADC_DATAALIGN_RIGHT;
hadc2.Init.NbrOfConversion = 1;
if (HAL_ADC_Init(&hadc2) != HAL_OK)
{
Error_Handler();
}
/** Configure Regular Channel
*/
sConfig.Channel = ADC_CHANNEL_1;
sConfig.Rank = ADC_REGULAR_RANK_1;
sConfig.SamplingTime = ADC_SAMPLETIME_1CYCLE_5;
if (HAL_ADC_ConfigChannel(&hadc2, &sConfig) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN ADC2_Init 2 */
/* USER CODE END ADC2_Init 2 */
}
void HAL_ADC_MspInit(ADC_HandleTypeDef* adcHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(adcHandle->Instance==ADC1)
{
/* USER CODE BEGIN ADC1_MspInit 0 */
/* USER CODE END ADC1_MspInit 0 */
/* ADC1 clock enable */
__HAL_RCC_ADC1_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**ADC1 GPIO Configuration
PA0-WKUP ------> ADC1_IN0
PA1 ------> ADC1_IN1
*/
GPIO_InitStruct.Pin = AIN1_Pin|AIN2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* USER CODE BEGIN ADC1_MspInit 1 */
/* USER CODE END ADC1_MspInit 1 */
}
else if(adcHandle->Instance==ADC2)
{
/* USER CODE BEGIN ADC2_MspInit 0 */
/* USER CODE END ADC2_MspInit 0 */
/* ADC2 clock enable */
__HAL_RCC_ADC2_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**ADC2 GPIO Configuration
PA1 ------> ADC2_IN1
*/
GPIO_InitStruct.Pin = AIN2_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_ANALOG;
HAL_GPIO_Init(AIN2_GPIO_Port, &GPIO_InitStruct);
/* USER CODE BEGIN ADC2_MspInit 1 */
/* USER CODE END ADC2_MspInit 1 */
}
}
void HAL_ADC_MspDeInit(ADC_HandleTypeDef* adcHandle)
{
if(adcHandle->Instance==ADC1)
{
/* USER CODE BEGIN ADC1_MspDeInit 0 */
/* USER CODE END ADC1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_ADC1_CLK_DISABLE();
/**ADC1 GPIO Configuration
PA0-WKUP ------> ADC1_IN0
PA1 ------> ADC1_IN1
*/
HAL_GPIO_DeInit(GPIOA, AIN1_Pin|AIN2_Pin);
/* USER CODE BEGIN ADC1_MspDeInit 1 */
/* USER CODE END ADC1_MspDeInit 1 */
}
else if(adcHandle->Instance==ADC2)
{
/* USER CODE BEGIN ADC2_MspDeInit 0 */
/* USER CODE END ADC2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_ADC2_CLK_DISABLE();
/**ADC2 GPIO Configuration
PA1 ------> ADC2_IN1
*/
HAL_GPIO_DeInit(AIN2_GPIO_Port, AIN2_Pin);
/* USER CODE BEGIN ADC2_MspDeInit 1 */
/* USER CODE END ADC2_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
+326
View File
@@ -0,0 +1,326 @@
/**
* @file ads1015_driver.c
* @brief Implementation of the ADS1015 I2C ADC driver.
*
* This driver provides functions to configure and read from the ADS1015
* 12-bit, 128 SPS I2C ADC. The device supports up to four single-ended
* inputs or two differential inputs.
*/
#include "ads1015_driver.h"
#include "main.h" // Assuming HAL is included via main.h
float temp_calib, ph_compensated, v_ph4=0, v_ph7=0;
// Write the register
static void writeRegister(ADS1015_I2C *i2c, uint8_t reg, uint16_t value) {
uint8_t pData[3] = { reg, (uint8_t) (value >> 8), (uint8_t) (value & 0xFF) };
HAL_I2C_Master_Transmit(i2c->hi2c, i2c->m_i2cAddress, pData, 3, 10);
}
// Read the register
static uint16_t readRegister(ADS1015_I2C *i2c, uint8_t reg) {
HAL_I2C_Master_Transmit(i2c->hi2c, i2c->m_i2cAddress, &reg, 1, 10);
uint8_t pData[2] = { 0, 0 };
HAL_I2C_Master_Receive(i2c->hi2c, i2c->m_i2cAddress, pData, 2, 10);
return ((pData[0] << 8) | pData[1]);
}
// Check if we have correct connection.
static void ADSbegin(ADS1015_I2C *i2c) {
if (HAL_I2C_IsDeviceReady(i2c->hi2c, i2c->m_i2cAddress, 10, 10) != HAL_OK)
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET); // This MUST have GPIO PA5 ready to use - ERROR I2C - Wrong address
}
// Declare an ADS1015 structure
void ADS1015(ADS1015_I2C *i2c, I2C_HandleTypeDef *hi2c, uint8_t i2cAddress) {
i2c->hi2c = hi2c;
i2c->m_i2cAddress = i2cAddress << 1; // It's Important to shift the address << 1
i2c->m_conversionDelay = ADS1015_CONVERSIONDELAY;
i2c->m_bitShift = 4;
i2c->m_gain = GAIN_TWOTHIRDS; /* +/- 6.144V range (limited to VDD +0.3V max!) */
//ADSbegin(i2c); //Ready is not used
}
/*
* // The ADC input range (or gain) can be changed via the following
// functions, but be careful never to exceed VDD +0.3V max, or to
// exceed the upper and lower limits if you adjust the input range!
// Setting these values incorrectly may destroy your ADC!
// ADS1015 ADS1115
// ------- -------
// ADSsetGain(GAIN_TWOTHIRDS); // 2/3x gain +/- 6.144V 1 bit = 3mV 0.1875mV (default)
// ADSsetGain(GAIN_ONE); // 1x gain +/- 4.096V 1 bit = 2mV 0.125mV
// ADSsetGain(GAIN_TWO); // 2x gain +/- 2.048V 1 bit = 1mV 0.0625mV
// ADSsetGain(GAIN_FOUR); // 4x gain +/- 1.024V 1 bit = 0.5mV 0.03125mV
// ADSsetGain(GAIN_EIGHT); // 8x gain +/- 0.512V 1 bit = 0.25mV 0.015625mV
// ADSsetGain(GAIN_SIXTEEN); // 16x gain +/- 0.256V 1 bit = 0.125mV 0.0078125mV
*/
void ADSsetGain(ADS1015_I2C *i2c, adsGain_t gain) {
i2c->m_gain = gain;
}
// Get the gain
adsGain_t ADSgetGain(ADS1015_I2C *i2c) {
return i2c->m_gain;
}
// Gets a single-ended ADC reading from the specified channel
uint16_t ADSreadADC_SingleEnded(ADS1015_I2C *i2c, uint8_t channel) {
if (channel > 3) {
return 0;
}
// Start with default values
uint16_t config =
ADS1015_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val)
ADS1015_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val)
ADS1015_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val)
ADS1015_REG_CONFIG_CMODE_TRAD | // Traditional comparator (default val)
ADS1015_REG_CONFIG_DR_1600SPS | // 1600 samples per second (default)
ADS1015_REG_CONFIG_MODE_SINGLE; // Single-shot mode (default)
// Set PGA/voltage range
config |= i2c->m_gain;
// Set single-ended input channel
switch (channel) {
case (0):
config |= ADS1015_REG_CONFIG_MUX_SINGLE_0;
break;
case (1):
config |= ADS1015_REG_CONFIG_MUX_SINGLE_1;
break;
case (2):
config |= ADS1015_REG_CONFIG_MUX_SINGLE_2;
break;
case (3):
config |= ADS1015_REG_CONFIG_MUX_SINGLE_3;
break;
}
// Set 'start single-conversion' bit
config |= ADS1015_REG_CONFIG_OS_SINGLE;
// Write config register to the ADC
writeRegister(i2c, ADS1015_REG_POINTER_CONFIG, config);
// Wait for the conversion to complete
HAL_Delay(i2c->m_conversionDelay);
// Read the conversion results
// Shift 12-bit results right 4 bits for the ADS1015
return readRegister(i2c, ADS1015_REG_POINTER_CONVERT) >> i2c->m_bitShift;
}
/*
* Reads the conversion results, measuring the voltage
* difference between the P (AIN0) and N (AIN1) input. Generates
* a signed value since the difference can be either positive or negative.
*/
int16_t ADSreadADC_Differential_0_1(ADS1015_I2C *i2c) {
// Start with default values
uint16_t config =
ADS1015_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val)
ADS1015_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val)
ADS1015_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val)
ADS1015_REG_CONFIG_CMODE_TRAD | // Traditional comparator (default val)
ADS1015_REG_CONFIG_DR_128SPS | // 128 samples per second (default)
ADS1015_REG_CONFIG_MODE_SINGLE; // Single-shot mode (default)
// Set PGA/voltage range
config |= i2c->m_gain;
// Set channels
config |= ADS1015_REG_CONFIG_MUX_DIFF_0_1; // AIN0 = P, AIN1 = N
// Set 'start single-conversion' bit
config |= ADS1015_REG_CONFIG_OS_SINGLE;
// Write config register to the ADC
writeRegister(i2c, ADS1015_REG_POINTER_CONFIG, config);
// Wait for the conversion to complete
HAL_Delay(i2c->m_conversionDelay);
// Read the conversion results
uint16_t res = readRegister(i2c, ADS1015_REG_POINTER_CONVERT) >> i2c->m_bitShift;
if (i2c->m_bitShift == 0) {
return (int16_t) res;
} else {
// Shift 12-bit results right 4 bits for the ADS1015,
// making sure we keep the sign bit intact
if (res > 0x07FF) {
// negative number - extend the sign to 16th bit
res |= 0xF000;
}
return (int16_t) res;
}
}
/*
* Reads the conversion results, measuring the voltage
* difference between the P (AIN2) and N (AIN3) input. Generates
* a signed value since the difference can be either positive or negative.
*/
int16_t ADSreadADC_Differential_2_3(ADS1015_I2C *i2c) {
// Start with default values
uint16_t config =
ADS1015_REG_CONFIG_CQUE_NONE | // Disable the comparator (default val)
ADS1015_REG_CONFIG_CLAT_NONLAT | // Non-latching (default val)
ADS1015_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val)
ADS1015_REG_CONFIG_CMODE_TRAD | // Traditional comparator (default val)
ADS1015_REG_CONFIG_DR_1600SPS | // 1600 samples per second (default)
ADS1015_REG_CONFIG_MODE_SINGLE; // Single-shot mode (default)
// Set PGA/voltage range
config |= i2c->m_gain;
// Set channels
config |= ADS1015_REG_CONFIG_MUX_DIFF_2_3; // AIN2 = P, AIN3 = N
// Set 'start single-conversion' bit
config |= ADS1015_REG_CONFIG_OS_SINGLE;
// Write config register to the ADC
writeRegister(i2c, ADS1015_REG_POINTER_CONFIG, config);
// Wait for the conversion to complete
HAL_Delay(i2c->m_conversionDelay);
// Read the conversion results
uint16_t res = readRegister(i2c, ADS1015_REG_POINTER_CONVERT) >> i2c->m_bitShift;
if (i2c->m_bitShift == 0) {
return (int16_t) res;
} else {
// Shift 12-bit results right 4 bits for the ADS1015,
// making sure we keep the sign bit intact
if (res > 0x07FF) {
// negative number - extend the sign to 16th bit
res |= 0xF000;
}
return (int16_t) res;
}
}
/*
* Sets up the comparator to operate in basic mode, causing the
* ALERT/RDY pin to assert (go from high to low) when the ADC
* value exceeds the specified threshold.
* This will also set the ADC in continuous conversion mode.
*/
void ADSstartComparator_SingleEnded(ADS1015_I2C *i2c, uint8_t channel, int16_t threshold) {
// Start with default values
uint16_t config =
ADS1015_REG_CONFIG_CQUE_1CONV | // Comparator enabled and asserts on 1 match
ADS1015_REG_CONFIG_CLAT_LATCH | // Latching mode
ADS1015_REG_CONFIG_CPOL_ACTVLOW | // Alert/Rdy active low (default val)
ADS1015_REG_CONFIG_CMODE_TRAD | // Traditional comparator (default val)
ADS1015_REG_CONFIG_DR_1600SPS | // 1600 samples per second (default)
ADS1015_REG_CONFIG_MODE_CONTIN | // Continuous conversion mode
ADS1015_REG_CONFIG_MODE_CONTIN; // Continuous conversion mode
// Set PGA/voltage range
config |= i2c->m_gain;
// Set single-ended input channel
switch (channel) {
case (0):
config |= ADS1015_REG_CONFIG_MUX_SINGLE_0;
break;
case (1):
config |= ADS1015_REG_CONFIG_MUX_SINGLE_1;
break;
case (2):
config |= ADS1015_REG_CONFIG_MUX_SINGLE_2;
break;
case (3):
config |= ADS1015_REG_CONFIG_MUX_SINGLE_3;
break;
}
// Set the high threshold register
// Shift 12-bit results left 4 bits for the ADS1015
writeRegister(i2c, ADS1015_REG_POINTER_HITHRESH, threshold << i2c->m_bitShift);
// Write config register to the ADC
writeRegister(i2c, ADS1015_REG_POINTER_CONFIG, config);
}
/*
* In order to clear the comparator, we need to read the conversion results.
* This function reads the last conversion results without changing the config value.
*/
int16_t ADSgetLastConversionResults(ADS1015_I2C *i2c) {
// Wait for the conversion to complete
HAL_Delay(i2c->m_conversionDelay);
// Read the conversion results
uint16_t res = readRegister(i2c, ADS1015_REG_POINTER_CONVERT) >> i2c->m_bitShift;
if (i2c->m_bitShift == 0) {
return (int16_t) res;
} else {
// Shift 12-bit results right 4 bits for the ADS1015,
// making sure we keep the sign bit intact
if (res > 0x07FF) {
// negative number - extend the sign to 16th bit
res |= 0xF000;
}
return (int16_t) res;
}
}
float ADSCalculate_ph_Volts(int16_t adc_raw)
{
// 1. Converter leitura bruta do ADC para tensão real (Volts)
return ((float)adc_raw * ADS1015_ADC_VREF) / ADS1015_ADC_MAX;
}
/**
* @brief Calcula o valor de pH compensado pela temperatura.
*
* @param adc_raw Valor bruto lido do ADC (0 a 4095).
* @param temp_dut Temperatura atual medida em Celsius.
*
* @return float Valor de pH calculado (0.0 a 14.0).
*/
float ADSCalculate_ph_Compensated(int16_t adc_raw, float temp_dut)
{
// 1. Converter leitura bruta do ADC para tensão real (Volts)
float v_measured = ((float)adc_raw * ADS1015_ADC_VREF) / ADS1015_ADC_MAX;
// 2. Calcular o Slope original (medido na temperatura da calibração)
// Delta pH é fixo em 3.0 (de pH 7 para pH 4)
float delta_v_calib = v_ph7 - v_ph4;
if (delta_v_calib == 0.0f)
{
return 0.0f; // Proteção contra erro de calibração/divisão por zero
}
float slope_at_calib = 3.0f / delta_v_calib;
// 3. Calcular o Fator de Correção Térmica (Equação de Nernst)
float temp_k_now = temp_dut + ADS1015_KELVIN_OFFSET;
float temp_k_ref = temp_calib + ADS1015_KELVIN_OFFSET;
// Fator: (T_atual / T_referencia)
float thermal_factor = temp_k_now / temp_k_ref;
/*
* 4. Cálculo Final do pH
* O Slope ajustado para a temperatura atual é: slope_at_calib / thermal_factor
* Fórmula: pH = pH_ref + (V_medido - V_ref_7) * Slope_ajustado
*/
float ph_result = 7.0f + ((v_measured - v_ph7) * (slope_at_calib / thermal_factor));
// 5. Clamping (Garantir limites físicos)
if (ph_result < 0.0f) ph_result = 0.0f;
if (ph_result > 14.0f) ph_result = 14.0f;
return ph_result;
}
+127
View File
@@ -0,0 +1,127 @@
/**
* @file analog_loop_driver.c
* @brief Driver implementation for current loop analog signal processing.
*/
#include "analog_loop_driver.h"
// --- Static Variables ---
static ADC_HandleTypeDef* s_hadc = NULL;
static uint32_t s_raw_value = 0;
static int16_t s_voltage_mV = 0;
static int16_t s_current_uA = 0;
/**
* @brief Initializes the analog loop driver.
*
* @param hadc Pointer to the ADC handle structure.
* @return HAL_StatusTypeDef HAL status.
*/
HAL_StatusTypeDef AnalogLoop_Init(ADC_HandleTypeDef *hadc)
{
if (hadc == NULL)
{
return HAL_ERROR;
}
s_hadc = hadc;
// Reset stored values
s_raw_value = 0;
s_voltage_mV = 0;
s_current_uA = 0;
return HAL_OK;
}
/**
* @brief Gets the raw ADC value from the analog loop.
*
* @return uint32_t Raw ADC value.
*/
uint32_t AnalogLoop_GetRawValue(void)
{
return s_raw_value;
}
/**
* @brief Calculates and returns the current in microamps.
*
* @return int16_t Current in uA.
*/
int16_t AnalogLoop_GetCurrent_uA(void)
{
// Convert raw ADC value to voltage (mV)
uint32_t voltage_mV = (s_raw_value * ANALOG_LOOP_VREF_MV) / 4095U;
// Apply calibration and convert to current (uA)
// V_out = I * R2 / R1 => I = (V_out * R1) / R2
// Convert to uA: I(uA) = (V_out(mV) * R1(ohms) * 1000) / R2(ohms)
uint32_t current_uA = (voltage_mV * ANALOG_LOOP_R1_OHMS * 1000U) / ANALOG_LOOP_R2_OHMS;
// Clamp to valid range
if (current_uA < ANALOG_LOOP_CURRENT_MIN_UA)
{
current_uA = ANALOG_LOOP_CURRENT_MIN_UA;
}
else if (current_uA > ANALOG_LOOP_CURRENT_MAX_UA)
{
current_uA = ANALOG_LOOP_CURRENT_MAX_UA;
}
s_current_uA = (int16_t)current_uA;
return s_current_uA;
}
/**
* @brief Calculates and returns the voltage in millivolts.
*
* @return int16_t Voltage in mV.
*/
int16_t AnalogLoop_GetVoltage_mV(void)
{
// Convert raw ADC value to voltage (mV)
uint32_t voltage_mV = (s_raw_value * ANALOG_LOOP_VREF_MV) / 4095U;
s_voltage_mV = (int16_t)voltage_mV;
return s_voltage_mV;
}
/**
* @brief Updates the internal ADC reading.
*
* This function should be called periodically or when new ADC data is available.
*
* @return HAL_StatusTypeDef HAL status.
*/
HAL_StatusTypeDef AnalogLoop_Update(void)
{
if (s_hadc == NULL)
{
return HAL_ERROR;
}
// Perform ADC conversion
HAL_StatusTypeDef status = HAL_ADC_Start(s_hadc);
if (status != HAL_OK)
{
return status;
}
// Wait for conversion to complete
status = HAL_ADC_PollForConversion(s_hadc, HAL_MAX_DELAY);
if (status != HAL_OK)
{
return status;
}
// Get the raw ADC value
s_raw_value = HAL_ADC_GetValue(s_hadc);
// Stop ADC conversion
HAL_ADC_Stop(s_hadc);
return HAL_OK;
}
@@ -0,0 +1,119 @@
/**
* @file digital_outputs_driver.c
* @brief Simplified Driver implementation for 8 independent open-drain digital outputs
* on STM32F103C8T6 using global static state.
*/
#include "digital_outputs_driver.h"
/**
* @brief Internal structure to track pin hardware mapping
*/
typedef struct {
GPIO_TypeDef* port;
uint16_t pin;
} pin_map_t;
/**
* @brief Static configuration of pins (Hardware Abstraction Layer)
*/
static const pin_map_t output_pins[OUTPUT_PINS_COUNT] = {
{GPIOB, GPIO_PIN_0}, // Index 0
{GPIOB, GPIO_PIN_1}, // Index 1
{GPIOB, GPIO_PIN_2}, // Index 2
{GPIOB, GPIO_PIN_8}, // Index 3
{GPIOB, GPIO_PIN_9}, // Index 4
{GPIOC, GPIO_PIN_13}, // Index 5
{GPIOC, GPIO_PIN_14}, // Index 6
{GPIOC, GPIO_PIN_15} // Index 7
};
/**
* @brief Static array to track current software state of pins
*/
static uint8_t pin_states[OUTPUT_PINS_COUNT] = {0};
/**
* @brief Initializes the GPIO hardware and sets initial states.
* @note This function replaces the handle-based init.
* @retval None
*/
void digital_outputs_init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
for (int i = 0; i < OUTPUT_PINS_COUNT; i++) {
GPIO_InitStruct.Pin = output_pins[i].pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD; // Open-drain
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(output_pins[i].port, &GPIO_InitStruct);
// Force initial state to LOW (Reset)
HAL_GPIO_WritePin(output_pins[i].port, output_pins[i].pin, GPIO_PIN_RESET);
pin_states[i] = 0;
}
}
/**
* @brief Sets the state of a specific output pin.
* @param pin Index of the pin (0 to OUTPUT_PINS_COUNT-1)
* @param state Desired state (0 = LOW, 1 = HIGH)
* @retval None
*/
void digital_outputs_set_state(digital_output_pin_t pin, uint8_t state)
{
if (pin >= OUTPUT_PINS_COUNT) {
return; // Simple boundary protection
}
GPIO_TypeDef* port = output_pins[pin].port;
uint16_t pin_mask = output_pins[pin].pin;
if (state) {
HAL_GPIO_WritePin(port, pin_mask, GPIO_PIN_SET);
pin_states[pin] = 1;
} else {
HAL_GPIO_WritePin(port, pin_mask, GPIO_PIN_RESET);
pin_states[pin] = 0;
}
}
/**
* @brief Gets the current state of a specific output pin.
* @param pin Index of the pin
* @param p_state Pointer to a variable where the state will be stored
* @retval None
*/
void digital_outputs_get_state(digital_output_pin_t pin, uint8_t* p_state)
{
if ((pin < OUTPUT_PINS_COUNT) && (p_state != NULL)) {
*p_state = pin_states[pin];
}
}
/**
* @brief Toggles the state of a specific output pin.
* @param pin Index of the pin
* @retval None
*/
void digital_outputs_toggle(digital_output_pin_t pin)
{
if (pin < OUTPUT_PINS_COUNT) {
// Simple toggle logic using the internal state array
uint8_t new_state = !pin_states[pin];
digital_outputs_set_state(pin, new_state);
}
}
/**
* @brief Resets all outputs to LOW.
* @retval None
*/
void digital_outputs_reset_all(void)
{
for (int i = 0; i < OUTPUT_PINS_COUNT; i++) {
digital_outputs_set_state(i, 0);
}
}
+69
View File
@@ -0,0 +1,69 @@
/**
* @file flash_storage.c
*/
#include "flash_manager.h"
/**
* @brief Grava a página inteira de uma vez.
* @param pPage Ponteiro para a estrutura de 1KB na RAM.
* @return HAL_OK em caso de sucesso.
*/
HAL_StatusTypeDef Flash_Save_Page(FlashPage_t *pPage) {
if (pPage == NULL) return HAL_ERROR;
HAL_StatusTypeDef status = HAL_OK;
HAL_FLASH_Unlock();
// 1. Apagar a página inteira (limpa os 1024 bytes)
FLASH_EraseInitTypeDef EraseInitStruct;
uint32_t PageError = 0;
EraseInitStruct.TypeErase = FLASH_TYPEERASE_PAGES;
EraseInitStruct.PageAddress = FLASH_PAGE_ADDR;
EraseInitStruct.NbPages = 1;
if (HAL_FLASHEx_Erase(&EraseInitStruct, &PageError) != HAL_OK) {
status = HAL_ERROR;
goto Exit;
}
// 2. Gravar o bloco de 1KB
// Como a estrutura é exatamente 1KB e alinhada, podemos tratar como um array de uint32_t.
// O STM32F1 grava preferencialmente em DoubleWord (64-bit), mas HalfWord (16-bit)
// funciona de forma segura para qualquer tamanho múltiplo de 2.
uint32_t *pSrc = (uint32_t *)pPage;
uint32_t *pDest = (uint32_t *)FLASH_PAGE_ADDR;
uint32_t iterations = FLASH_PAGE_SIZE / sizeof(uint32_t); // 1024 / 4 = 256 iterações
for (uint32_t i = 0; i < iterations; i++) {
// Usamos o modo de gravação de 32-bit (Word) se disponível,
// ou simulamos com duas gravações de 16-bit para máxima compatuidade no F1.
if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, (uint32_t)&pDest[i], pSrc[i]) != HAL_OK) {
status = HAL_ERROR;
break;
}
}
Exit:
HAL_FLASH_Lock();
return status;
}
/**
* @brief Lê a página da Flash para a RAM.
*/
HAL_StatusTypeDef Flash_Load_Page(FlashPage_t *pDest) {
if (pDest == NULL) return HAL_ERROR;
// Leitura direta por memcpy (A Flash é mapeada no espaço de endereçamento comum)
memcpy(pDest, (void *)FLASH_PAGE_ADDR, FLASH_PAGE_SIZE);
// Validação da integridade através do Magic Number
if (pDest->magic_number != 0xDEADBEEF) {
return HAL_ERROR;
}
return HAL_OK;
}
+173
View File
@@ -0,0 +1,173 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file gpio.c
* @brief This file provides code for the configuration
* of all used GPIO pins.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "gpio.h"
/* USER CODE BEGIN 0 */
#include "stm32f1xx_hal.h"
/* USER CODE END 0 */
/*----------------------------------------------------------------------------*/
/* Configure GPIO */
/*----------------------------------------------------------------------------*/
/* USER CODE BEGIN 1 */
volatile uint32_t last_interrupt_time=0;
volatile uint8_t first_time_state=1;
volatile GPIO_PinState original_pin_state = GPIO_PIN_RESET, last_original_pin = GPIO_PIN_SET;
volatile int8_t edge_state = NO_EDGE;
/* USER CODE END 1 */
/** Configure pins as
* Analog
* Input
* Output
* EVENT_OUT
* EXTI
* Free pins are configured automatically as Analog (this feature is enabled through
* the Code Generation settings)
*/
void MX_GPIO_Init(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* GPIO Ports Clock Enable */
__HAL_RCC_GPIOC_CLK_ENABLE();
__HAL_RCC_GPIOD_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOC, DIGI_OUT5_Pin|DIGI_OUT6_Pin|DIGI_OUT7_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(GPIOB, DIGI_OUT0_Pin|DIGI_OUT1_Pin|DIGI_OUT2_Pin|LED_Red_Pin
|LED_Green_Pin|DIGI_OUT3_Pin|DIGI_OUT4_Pin, GPIO_PIN_RESET);
/*Configure GPIO pin Output Level */
HAL_GPIO_WritePin(TX_EN_RS485_GPIO_Port, TX_EN_RS485_Pin, GPIO_PIN_RESET);
/*Configure GPIO pins : DIGI_OUT5_Pin DIGI_OUT6_Pin DIGI_OUT7_Pin */
GPIO_InitStruct.Pin = DIGI_OUT5_Pin|DIGI_OUT6_Pin|DIGI_OUT7_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOC, &GPIO_InitStruct);
/*Configure GPIO pins : RS485_Addr0_Pin RS485_Addr1_Pin RS485_Addr2_Pin RS485_Addr3_Pin
SYS_CFG0_Pin SYS_CFG1_Pin PG_RS485_Pin PG_CE_Pin
PG_PH_Pin */
GPIO_InitStruct.Pin = RS485_Addr0_Pin|RS485_Addr1_Pin|RS485_Addr2_Pin|RS485_Addr3_Pin
|SYS_CFG0_Pin|SYS_CFG1_Pin|PG_RS485_Pin|PG_CE_Pin
|PG_PH_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/*Configure GPIO pins : DIGI_OUT0_Pin DIGI_OUT1_Pin DIGI_OUT2_Pin LED_Red_Pin
LED_Green_Pin DIGI_OUT3_Pin DIGI_OUT4_Pin */
GPIO_InitStruct.Pin = DIGI_OUT0_Pin|DIGI_OUT1_Pin|DIGI_OUT2_Pin|LED_Red_Pin
|LED_Green_Pin|DIGI_OUT3_Pin|DIGI_OUT4_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pins : RS485_Addr4_Pin RS485_Addr5_Pin RS485_Addr6_Pin RS485_Addr7_Pin */
GPIO_InitStruct.Pin = RS485_Addr4_Pin|RS485_Addr5_Pin|RS485_Addr6_Pin|RS485_Addr7_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/*Configure GPIO pin : TX_EN_RS485_Pin */
GPIO_InitStruct.Pin = TX_EN_RS485_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
GPIO_InitStruct.Pull = GPIO_NOPULL;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(TX_EN_RS485_GPIO_Port, &GPIO_InitStruct);
/*Configure GPIO pin : Calib_PH_Pin */
GPIO_InitStruct.Pin = Calib_PH_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING_FALLING;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(Calib_PH_GPIO_Port, &GPIO_InitStruct);
/* EXTI interrupt init*/
HAL_NVIC_SetPriority(EXTI3_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(EXTI3_IRQn);
}
/* USER CODE BEGIN 2 */
/**
* @brief EXTI line3 interrupt callback.
* @details This function is called by the HAL EXTI IRQ Handler.
* It distinguishes between rising and falling edges by reading the pin state.
* @param GPIO_Pin: Specifies the pins connected to the EXTI line.
* @retval None
*/
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
if (GPIO_Pin == Calib_PH_Pin)
{
uint32_t current_time = HAL_GetTick();
GPIO_PinState pin_state = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_3);
if(pin_state != last_original_pin)
{
if(first_time_state == 1)
{
original_pin_state = pin_state;
first_time_state = 0;
}
else if(((current_time - last_interrupt_time) > 70U) && (pin_state == original_pin_state))
{
if(pin_state == GPIO_PIN_RESET)
{
/* --- LOGIC FOR FALLING EDGE HERE --- */
//HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_SET);
//HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);
edge_state = FALLING_EDGE;
}
else
{
/* --- LOGIC FOR RISING EDGE HERE --- */
//HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_RESET);
//HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_SET);
edge_state = RISING_EDGE;
}
last_interrupt_time = current_time;
last_original_pin = original_pin_state;
first_time_state = 1;
}
}
}
}
/* USER CODE END 2 */
+187
View File
@@ -0,0 +1,187 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file i2c.c
* @brief This file provides code for the configuration
* of the I2C instances.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "i2c.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
I2C_HandleTypeDef hi2c1;
I2C_HandleTypeDef hi2c2;
/* I2C1 init function */
void MX_I2C1_Init(void)
{
/* USER CODE BEGIN I2C1_Init 0 */
/* USER CODE END I2C1_Init 0 */
/* USER CODE BEGIN I2C1_Init 1 */
/* USER CODE END I2C1_Init 1 */
hi2c1.Instance = I2C1;
hi2c1.Init.ClockSpeed = 100000;
hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c1.Init.OwnAddress1 = 0;
hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c1.Init.OwnAddress2 = 0;
hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN I2C1_Init 2 */
/* USER CODE END I2C1_Init 2 */
}
/* I2C2 init function */
void MX_I2C2_Init(void)
{
/* USER CODE BEGIN I2C2_Init 0 */
/* USER CODE END I2C2_Init 0 */
/* USER CODE BEGIN I2C2_Init 1 */
/* USER CODE END I2C2_Init 1 */
hi2c2.Instance = I2C2;
hi2c2.Init.ClockSpeed = 100000;
hi2c2.Init.DutyCycle = I2C_DUTYCYCLE_2;
hi2c2.Init.OwnAddress1 = 0;
hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c2.Init.OwnAddress2 = 0;
hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c2) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN I2C2_Init 2 */
/* USER CODE END I2C2_Init 2 */
}
void HAL_I2C_MspInit(I2C_HandleTypeDef* i2cHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(i2cHandle->Instance==I2C1)
{
/* USER CODE BEGIN I2C1_MspInit 0 */
/* USER CODE END I2C1_MspInit 0 */
__HAL_RCC_GPIOB_CLK_ENABLE();
/**I2C1 GPIO Configuration
PB6 ------> I2C1_SCL
PB7 ------> I2C1_SDA
*/
GPIO_InitStruct.Pin = I2C1_SCL_PH_Pin|I2C1_SDA_PH_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* I2C1 clock enable */
__HAL_RCC_I2C1_CLK_ENABLE();
/* USER CODE BEGIN I2C1_MspInit 1 */
/* USER CODE END I2C1_MspInit 1 */
}
else if(i2cHandle->Instance==I2C2)
{
/* USER CODE BEGIN I2C2_MspInit 0 */
/* USER CODE END I2C2_MspInit 0 */
__HAL_RCC_GPIOB_CLK_ENABLE();
/**I2C2 GPIO Configuration
PB10 ------> I2C2_SCL
PB11 ------> I2C2_SDA
*/
GPIO_InitStruct.Pin = I2C2_SCL_CE_Pin|I2C2_SDA_CE_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
/* I2C2 clock enable */
__HAL_RCC_I2C2_CLK_ENABLE();
/* USER CODE BEGIN I2C2_MspInit 1 */
/* USER CODE END I2C2_MspInit 1 */
}
}
void HAL_I2C_MspDeInit(I2C_HandleTypeDef* i2cHandle)
{
if(i2cHandle->Instance==I2C1)
{
/* USER CODE BEGIN I2C1_MspDeInit 0 */
/* USER CODE END I2C1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_I2C1_CLK_DISABLE();
/**I2C1 GPIO Configuration
PB6 ------> I2C1_SCL
PB7 ------> I2C1_SDA
*/
HAL_GPIO_DeInit(I2C1_SCL_PH_GPIO_Port, I2C1_SCL_PH_Pin);
HAL_GPIO_DeInit(I2C1_SDA_PH_GPIO_Port, I2C1_SDA_PH_Pin);
/* USER CODE BEGIN I2C1_MspDeInit 1 */
/* USER CODE END I2C1_MspDeInit 1 */
}
else if(i2cHandle->Instance==I2C2)
{
/* USER CODE BEGIN I2C2_MspDeInit 0 */
/* USER CODE END I2C2_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_I2C2_CLK_DISABLE();
/**I2C2 GPIO Configuration
PB10 ------> I2C2_SCL
PB11 ------> I2C2_SDA
*/
HAL_GPIO_DeInit(I2C2_SCL_CE_GPIO_Port, I2C2_SCL_CE_Pin);
HAL_GPIO_DeInit(I2C2_SDA_CE_GPIO_Port, I2C2_SDA_CE_Pin);
/* USER CODE BEGIN I2C2_MspDeInit 1 */
/* USER CODE END I2C2_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
+487
View File
@@ -0,0 +1,487 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file : main.c
* @brief : Main program body
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "i2c.h"
#include "usart.h"
#include "gpio.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "ads1015_driver.h"
#include "digital_outputs_driver.h"
#include "ad5934_driver.h"
#include "rs485_driver.h"
#include <string.h>
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
/* USER CODE END PTD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
uint8_t rx_buffer[256]; /*!< Buffer for received data */
uint8_t tx_data[] = "Hello RS-485 Broadcast!"; /*!< Data to send */
uint8_t adc_text[6];
uint8_t real_text[6];
uint8_t imag_text[6];
uint8_t rs485_text[6];
uint8_t newline[]={'\r','\n'};
uint8_t doubleSpace[]={'_','_'};
uint8_t newline_ph[]={'_','p','H','\r','\n'};
uint8_t newline_admi[]={'_','m','S','\r','\n'};
uint8_t newline_real[]={'_','°','C','\r','\n'};
uint8_t newline_imag[]={'_','O','h','m','\r','\n'};
uint8_t newline_485[]={'_','a','d','\r','\n'};
uint8_t minus[]={'-',' '};
uint8_t rs485_address=0;
ADS1015_I2C i2c;
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
void intToStr(int N, char *str);
void FloatToString(char * buf, double val);
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* @brief The application entry point.
* @retval int
*/
int main(void)
{
/* USER CODE BEGIN 1 */
HAL_StatusTypeDef status0,status1;
// Variables to store previous LED states
uint8_t previous_green_state = 0;
uint8_t previous_red_state = 0;
// Variables for timing
uint32_t previous_millis_green = 0;
uint32_t previous_millis_red = 0;
uint32_t current_millis;
float temperature_RTD, admittance_EC;
/*! Temporary variables */
char tempString[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
long double tempValue = 0;
/* USER CODE END 1 */
/* MCU Configuration--------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* USER CODE BEGIN Init */
/* USER CODE END Init */
/* Configure the system clock */
SystemClock_Config();
/* USER CODE BEGIN SysInit */
/* USER CODE END SysInit */
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_ADC1_Init();
MX_ADC2_Init();
MX_I2C1_Init();
MX_I2C2_Init();
MX_USART1_UART_Init();
/* USER CODE BEGIN 2 */
digital_outputs_init();
// Initialize RS-485 driver
rs485_init();
ADS1015(&i2c, &hi2c1, ADS_ADDR_GND);
ADSsetGain(&i2c, GAIN_SIXTEEN);
// Start CE and RTD Measurement
AD5934_Init();
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while (1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
current_millis = HAL_GetTick();
// Piscar LED verde em PB5 a cada 0,5 segundos
if ((current_millis - previous_millis_green) >= 800)
{
previous_millis_green = current_millis;
/*HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_5);
// Check if state changed and send via RS485
uint8_t current_green_state = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_5);
if (current_green_state != previous_green_state)
{
previous_green_state = current_green_state;
uint8_t led_data[2] = {0x01, current_green_state}; // Command 0x01 for green LED
}*/
temperature_RTD = AD5934_GetTemperature();
FloatToString(tempString, temperature_RTD);
status0 = rs485_send_broadcast(tempString, (strlen((char*)tempString)-1));
status1 = rs485_send_broadcast(newline_real, strlen((char*)newline_real));
if(edge_state == FALLING_EDGE)
{
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_SET);
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_RESET);
temp_calib = temperature_RTD;
v_ph4 = ADSCalculate_ph_Volts(2048 - ADSreadADC_Differential_0_1(&i2c));
edge_state = NO_EDGE;
HAL_Delay(500);
}else if(edge_state == RISING_EDGE)
{
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_4, GPIO_PIN_RESET);
HAL_GPIO_WritePin(GPIOB, GPIO_PIN_5, GPIO_PIN_SET);
v_ph7 = ADSCalculate_ph_Volts(2048 - ADSreadADC_Differential_0_1(&i2c));
edge_state = NO_EDGE;
HAL_Delay(500);
}
ph_compensated = ADSCalculate_ph_Compensated((2048 - ADSreadADC_Differential_0_1(&i2c)),temp_calib);
FloatToString(tempString, ph_compensated);
status0 = rs485_send_broadcast(tempString, (strlen((char*)tempString)-1));
status1 = rs485_send_broadcast(newline_ph, strlen((char*)newline_ph));
admittance_EC = AD5934_GetImpedance();
FloatToString(tempString, admittance_EC);
status0 = rs485_send_broadcast(tempString, (strlen((char*)tempString)-1));
status1 = rs485_send_broadcast(newline_admi, strlen((char*)newline_admi));
}
// Piscar LED vermelho em PB4 a cada 1 segundo
/* if ((current_millis - previous_millis_red) >= 700)
{
previous_millis_red = current_millis;
HAL_GPIO_TogglePin(GPIOB, GPIO_PIN_4);
// Check if state changed and send via RS485
uint8_t current_red_state = HAL_GPIO_ReadPin(GPIOB, GPIO_PIN_4);
if (current_red_state != previous_red_state)
{
previous_red_state = current_red_state;
uint8_t led_data[2] = {0x02, current_red_state}; // Command 0x02 for red LED
}
// Check if state changed and send via RS485
rs485_address = rs485_get_address();
intToStr(rs485_address, rs485_text);
// Send broadcast message
status0 = rs485_send_broadcast(rs485_text, strlen((char*)rs485_text));
status1 = rs485_send_broadcast(newline_485, strlen((char*)newline_485));
status1 = rs485_send_broadcast(newline, strlen((char*)newline));
// Set channels in the Analog Switch
//tempByte = ad5934_sample_BL.bytes[0];
//ad5934_sample_BL.bytes[0] = ad5934_sample_BL.bytes[1];
//ad5934_sample_BL.bytes[1] = tempByte;
//tempByte = ad5934_sample_BL.bytes[2];
//ad5934_sample_BL.bytes[2] = ad5934_sample_BL.bytes[3];
//ad5934_sample_BL.bytes[3] = tempByte;
//ad5934_sample_IL.number = ad5934_sample_BL.number;
// ad5934_sample_IL.number = AD5934_Sweep();
// intToStr((ad5934_sample_IL.ints[0]), real_text);
// status0 = rs485_send_broadcast(real_text, strlen((char*)real_text));
// status1 = rs485_send_broadcast(newline_real, strlen((char*)newline_real));
// intToStr((ad5934_sample_IL.ints[1]), imag_text);
//status0 = rs485_send_broadcast(imag_text, strlen((char*)imag_text));
//status1 = rs485_send_broadcast(newline_imag, strlen((char*)newline_imag));
//AD5934_GetImpedance(CH_EC);
//FloatToString(tempString, ad5934_impedances_average[0]);
//status0 = rs485_send_broadcast(tempString, strlen((char*)tempString));
//status1 = rs485_send_broadcast(newline_imag, strlen((char*)newline_imag));
//impedance_EC = AD5934_CalculateImpedance();
//FloatToString(tempString, impedance_EC);
//status0 = rs485_send_broadcast(tempString, strlen((char*)tempString));
//status1 = rs485_send_broadcast(newline_imag, strlen((char*)newline_imag));
// Read ADC value
int16_t adc_value = 2048 - ADSreadADC_Differential_0_1(&i2c);
intToStr(adc_value, adc_text);
//
status0 = rs485_send_broadcast(adc_text, strlen((char*)adc_text));
status1 = rs485_send_broadcast(newline_ph, strlen((char*)newline_ph));
status1 = rs485_send_broadcast(newline, strlen((char*)newline));
}*/
// Read ADC value
// int16_t adc_value = 2048 - ADSreadADC_Differential_0_1(&i2c);
// intToStr(adc_value, adc_text);
//
// status0 = rs485_send_broadcast(adc_text, strlen((char*)adc_text));
// status1 = rs485_send_broadcast(newline_ph, strlen((char*)newline_ph));
// status1 = rs485_send_broadcast(newline, strlen((char*)newline));
}
/* USER CODE END 3 */
}
/**
* @brief System Clock Configuration
* @retval None
*/
void SystemClock_Config(void)
{
RCC_OscInitTypeDef RCC_OscInitStruct = {0};
RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
/** Initializes the RCC Oscillators according to the specified parameters
* in the RCC_OscInitTypeDef structure.
*/
RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
RCC_OscInitStruct.HSEState = RCC_HSE_ON;
RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
RCC_OscInitStruct.HSIState = RCC_HSI_ON;
RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL2;
if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
{
Error_Handler();
}
/** Initializes the CPU, AHB and APB buses clocks
*/
RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
|RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;
if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_0) != HAL_OK)
{
Error_Handler();
}
PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_ADC;
PeriphClkInit.AdcClockSelection = RCC_ADCPCLK2_DIV8;
if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
{
Error_Handler();
}
}
/* USER CODE BEGIN 4 */
/***************************************************************************//**
* @brief Converts a float value to a character array with 3 digits of accuracy.
*
* @param *buf - returns the converterd value
* @param val - value to be converted
*
* @return None.
*******************************************************************************/
void FloatToString(char * buf, double val)
{
long intPart = 0;
short fracPart = 0;
short charPos = 0;
char localBuf[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
short i = sizeof(localBuf) - 1;
intPart = (long)val;
fracPart = (short)((val - intPart) * 1000 + 0.5);
while(i > sizeof(localBuf) - 4)
{
localBuf[i] = (fracPart % 10) + 0x30;
fracPart /= 10;
i--;
}
localBuf[i] = '.';
if(intPart == 0)
{
i --;
localBuf[i] = '0';
}
while(intPart)
{
i --;
localBuf[i] =(intPart % 10) + 0x30;
intPart /= 10;
}
for(charPos = i; charPos < sizeof(localBuf); charPos ++)
{
*buf = localBuf[charPos];
buf ++;
}
*buf = 0;
}
void intToStr(int N, char *str) {
int i = 0;
// Save the copy of the number for sign
int sign = N;
// If the number is negative, make it positive
if (N < 0)
N = -N;
// Extract digits from the number and add them to the
// string
while (N > 0) {
// Convert integer digit to character and store
// it in the str
str[i++] = N % 10 + '0';
N /= 10;
}
// If the number was negative, add a minus sign to the
// string
if (sign < 0) {
str[i++] = '-';
}
// Null-terminate the string
str[i] = '\0';
// Reverse the string to get the correct order
for (int j = 0, k = i - 1; j < k; j++, k--) {
char temp = str[j];
str[j] = str[k];
str[k] = temp;
}
}
/* USER CODE END 4 */
/**
* @brief This function is executed in case of error occurrence.
* @retval None
*/
void Error_Handler(void)
{
/* USER CODE BEGIN Error_Handler_Debug */
/* User can add his own implementation to report the HAL error return state */
__disable_irq();
while (1)
{
}
/* USER CODE END Error_Handler_Debug */
}
#ifdef USE_FULL_ASSERT
/**
* @brief Reports the name of the source file and the source line number
* where the assert_param error has occurred.
* @param file: pointer to the source file name
* @param line: assert_param error line source number
* @retval None
*/
void assert_failed(uint8_t *file, uint32_t line)
{
/* USER CODE BEGIN 6 */
/* User can add his own implementation to report the file name and line number,
ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
/* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
+184
View File
@@ -0,0 +1,184 @@
/**
* @file rs485_driver.c
* @brief Implementation file for RS-485 communication driver.
*
* This driver provides functions to configure and control RS-485 communication
* using USART with RTS pin as TX enable. Each device has an 8-bit address
* defined by 4 bits on PB12-PB15 (upper nibble) and 4 bits on PA2-PA5 (lower nibble),
* all with pull-up resistors enabled.
*
* @note Based on STM32F103C8T6 microcontroller and USART configuration
*/
#include "rs485_driver.h"
/* --- Local Variables --- */
static rs485_address_t device_address;
static UART_HandleTypeDef huart1; /*!< Handle for USART1 */
/* --- Local Function Prototypes --- */
static void rs485_configure_gpio_address(void);
static void rs485_configure_usart1(void);
/**
* @brief Initializes the RS-485 driver.
* @note This function configures GPIOs for address detection and USART1 for communication.
*/
void rs485_init(void)
{
/* Configure GPIOs for address detection */
rs485_configure_gpio_address();
/* Configure USART1 for RS-485 communication */
rs485_configure_usart1();
/* Get the current device address from GPIOs */
device_address.full_address = rs485_get_address();
}
/**
* @brief Gets the current device address from GPIOs.
* @return The 8-bit device address.
*/
uint8_t rs485_get_address(void)
{
return ((uint8_t) ((((LL_GPIO_ReadInputPort(GPIOB) & RS485_ADDR_MASK_HIGH)>>RS485_ADDR_BIT_SET_HIGH) | (LL_GPIO_ReadInputPort(GPIOA) & RS485_ADDR_MASK_LOW)>>RS485_ADDR_BIT_SET_LOW)));
}
/**
* @brief Sends data to a specific RS-485 address.
* @param address Target device address.
* @param data Pointer to the data buffer.
* @param length Number of bytes to send.
* @retval HAL_OK on success, otherwise error code.
*/
HAL_StatusTypeDef rs485_send_to_address(uint8_t address, uint8_t* data, uint16_t length)
{
/* Enable transmission mode */
rs485_enable_tx();
/* Send the address first */
HAL_UART_Transmit(&huart1, &address, 1, HAL_MAX_DELAY);
/* Send the data */
HAL_StatusTypeDef status = HAL_UART_Transmit(&huart1, data, length, HAL_MAX_DELAY);
/* Disable transmission mode after sending */
rs485_disable_tx();
return status;
}
/**
* @brief Sends data to all devices (broadcast).
* @param data Pointer to the data buffer.
* @param length Number of bytes to send.
* @retval HAL_OK on success, otherwise error code.
*/
HAL_StatusTypeDef rs485_send_broadcast(uint8_t* data, uint16_t length)
{
/* Enable transmission mode */
rs485_enable_tx();
/* Send the broadcast address (0x00) first */
uint8_t broadcast_address = 0x00;
HAL_UART_Transmit(&huart1, &broadcast_address, 1, HAL_MAX_DELAY);
/* Send the data */
HAL_StatusTypeDef status = HAL_UART_Transmit(&huart1, data, length, HAL_MAX_DELAY);
/* Disable transmission mode after sending */
rs485_disable_tx();
return status;
}
/**
* @brief Receives data from RS-485 bus.
* @param data Pointer to the receive buffer.
* @param length Maximum number of bytes to receive.
* @retval Number of bytes received, or 0 on error.
*/
uint16_t rs485_receive(uint8_t* data, uint16_t length)
{
HAL_StatusTypeDef status;
uint16_t bytes_received = 0;
/* Enable reception mode (transmission disabled) */
rs485_disable_tx();
/* Receive data with timeout */
status = HAL_UART_Receive(&huart1, data, length, HAL_MAX_DELAY);
if (status == HAL_OK)
{
bytes_received = length;
}
return bytes_received;
}
/**
* @brief Enables transmission mode on RS-485 transceiver.
*/
void rs485_enable_tx(void)
{
/* Set TX EN pin high to enable transmitter */
HAL_GPIO_WritePin(RS485_TX_EN_PORT, RS485_TX_EN_PIN, GPIO_PIN_SET);
}
/**
* @brief Disables transmission mode on RS-485 transceiver.
*/
void rs485_disable_tx(void)
{
/* Set TX EN pin low to disable transmitter */
HAL_GPIO_WritePin(RS485_TX_EN_PORT, RS485_TX_EN_PIN, GPIO_PIN_RESET);
}
/**
* @brief Configures GPIOs for address detection.
*/
static void rs485_configure_gpio_address(void)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
/* Enable clock for GPIOA and GPIOB */
__HAL_RCC_GPIOA_CLK_ENABLE();
__HAL_RCC_GPIOB_CLK_ENABLE();
/* Configure PA2-PA5 as input with pull-up */
GPIO_InitStruct.Pin = GPIO_PIN_2 | GPIO_PIN_3 | GPIO_PIN_4 | GPIO_PIN_5;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* Configure PB12-PB15 as input with pull-up */
GPIO_InitStruct.Pin = GPIO_PIN_12 | GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_PULLUP;
HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}
/**
* @brief Configures USART1 for RS-485 communication.
*/
static void rs485_configure_usart1(void)
{
/* Enable clock for USART1 */
__HAL_RCC_USART1_CLK_ENABLE();
huart1.Instance = USART1;
huart1.Init.BaudRate = 9600; /*!< Default baud rate for RS-485 */
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE; /*!< Use NONE as TX enable */
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
/* Initialization Error */
while(1);
}
}
@@ -0,0 +1,85 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f1xx_hal_msp.c
* @brief This file provides code for the MSP Initialization
* and de-Initialization codes.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN Define */
/* USER CODE END Define */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN Macro */
/* USER CODE END Macro */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* External functions --------------------------------------------------------*/
/* USER CODE BEGIN ExternalFunctions */
/* USER CODE END ExternalFunctions */
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/**
* Initializes the Global MSP.
*/
void HAL_MspInit(void)
{
/* USER CODE BEGIN MspInit 0 */
/* USER CODE END MspInit 0 */
__HAL_RCC_AFIO_CLK_ENABLE();
__HAL_RCC_PWR_CLK_ENABLE();
/* System interrupt init*/
/** NOJTAG: JTAG-DP Disabled and SW-DP Enabled
*/
__HAL_AFIO_REMAP_SWJ_NOJTAG();
/* USER CODE BEGIN MspInit 1 */
/* USER CODE END MspInit 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
+231
View File
@@ -0,0 +1,231 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file stm32f1xx_it.c
* @brief Interrupt Service Routines.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f1xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
/* USER CODE END Includes */
/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */
/* USER CODE END TD */
/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */
/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */
/* USER CODE END PM */
/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
/* USER CODE END PV */
/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */
/* USER CODE END PFP */
/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
/* External variables --------------------------------------------------------*/
extern UART_HandleTypeDef huart1;
/* USER CODE BEGIN EV */
/* USER CODE END EV */
/******************************************************************************/
/* Cortex-M3 Processor Interruption and Exception Handlers */
/******************************************************************************/
/**
* @brief This function handles Non maskable interrupt.
*/
void NMI_Handler(void)
{
/* USER CODE BEGIN NonMaskableInt_IRQn 0 */
/* USER CODE END NonMaskableInt_IRQn 0 */
/* USER CODE BEGIN NonMaskableInt_IRQn 1 */
while (1)
{
}
/* USER CODE END NonMaskableInt_IRQn 1 */
}
/**
* @brief This function handles Hard fault interrupt.
*/
void HardFault_Handler(void)
{
/* USER CODE BEGIN HardFault_IRQn 0 */
/* USER CODE END HardFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_HardFault_IRQn 0 */
/* USER CODE END W1_HardFault_IRQn 0 */
}
}
/**
* @brief This function handles Memory management fault.
*/
void MemManage_Handler(void)
{
/* USER CODE BEGIN MemoryManagement_IRQn 0 */
/* USER CODE END MemoryManagement_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
/* USER CODE END W1_MemoryManagement_IRQn 0 */
}
}
/**
* @brief This function handles Prefetch fault, memory access fault.
*/
void BusFault_Handler(void)
{
/* USER CODE BEGIN BusFault_IRQn 0 */
/* USER CODE END BusFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_BusFault_IRQn 0 */
/* USER CODE END W1_BusFault_IRQn 0 */
}
}
/**
* @brief This function handles Undefined instruction or illegal state.
*/
void UsageFault_Handler(void)
{
/* USER CODE BEGIN UsageFault_IRQn 0 */
/* USER CODE END UsageFault_IRQn 0 */
while (1)
{
/* USER CODE BEGIN W1_UsageFault_IRQn 0 */
/* USER CODE END W1_UsageFault_IRQn 0 */
}
}
/**
* @brief This function handles System service call via SWI instruction.
*/
void SVC_Handler(void)
{
/* USER CODE BEGIN SVCall_IRQn 0 */
/* USER CODE END SVCall_IRQn 0 */
/* USER CODE BEGIN SVCall_IRQn 1 */
/* USER CODE END SVCall_IRQn 1 */
}
/**
* @brief This function handles Debug monitor.
*/
void DebugMon_Handler(void)
{
/* USER CODE BEGIN DebugMonitor_IRQn 0 */
/* USER CODE END DebugMonitor_IRQn 0 */
/* USER CODE BEGIN DebugMonitor_IRQn 1 */
/* USER CODE END DebugMonitor_IRQn 1 */
}
/**
* @brief This function handles Pendable request for system service.
*/
void PendSV_Handler(void)
{
/* USER CODE BEGIN PendSV_IRQn 0 */
/* USER CODE END PendSV_IRQn 0 */
/* USER CODE BEGIN PendSV_IRQn 1 */
/* USER CODE END PendSV_IRQn 1 */
}
/**
* @brief This function handles System tick timer.
*/
void SysTick_Handler(void)
{
/* USER CODE BEGIN SysTick_IRQn 0 */
/* USER CODE END SysTick_IRQn 0 */
HAL_IncTick();
/* USER CODE BEGIN SysTick_IRQn 1 */
/* USER CODE END SysTick_IRQn 1 */
}
/******************************************************************************/
/* STM32F1xx Peripheral Interrupt Handlers */
/* Add here the Interrupt Handlers for the used peripherals. */
/* For the available peripheral interrupt handler names, */
/* please refer to the startup file (startup_stm32f1xx.s). */
/******************************************************************************/
/**
* @brief This function handles EXTI line3 interrupt.
*/
void EXTI3_IRQHandler(void)
{
/* USER CODE BEGIN EXTI3_IRQn 0 */
/* USER CODE END EXTI3_IRQn 0 */
HAL_GPIO_EXTI_IRQHandler(Calib_PH_Pin);
/* USER CODE BEGIN EXTI3_IRQn 1 */
/* USER CODE END EXTI3_IRQn 1 */
}
/**
* @brief This function handles USART1 global interrupt.
*/
void USART1_IRQHandler(void)
{
/* USER CODE BEGIN USART1_IRQn 0 */
/* USER CODE END USART1_IRQn 0 */
HAL_UART_IRQHandler(&huart1);
/* USER CODE BEGIN USART1_IRQn 1 */
/* USER CODE END USART1_IRQn 1 */
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */
+176
View File
@@ -0,0 +1,176 @@
/**
******************************************************************************
* @file syscalls.c
* @author Auto-generated by STM32CubeIDE
* @brief STM32CubeIDE Minimal System calls file
*
* For more information about which c-functions
* need which of these lowlevel functions
* please consult the Newlib libc-manual
******************************************************************************
* @attention
*
* Copyright (c) 2020-2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes */
#include <sys/stat.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/times.h>
/* Variables */
extern int __io_putchar(int ch) __attribute__((weak));
extern int __io_getchar(void) __attribute__((weak));
char *__env[1] = { 0 };
char **environ = __env;
/* Functions */
void initialise_monitor_handles()
{
}
int _getpid(void)
{
return 1;
}
int _kill(int pid, int sig)
{
(void)pid;
(void)sig;
errno = EINVAL;
return -1;
}
void _exit (int status)
{
_kill(status, -1);
while (1) {} /* Make sure we hang here */
}
__attribute__((weak)) int _read(int file, char *ptr, int len)
{
(void)file;
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
*ptr++ = __io_getchar();
}
return len;
}
__attribute__((weak)) int _write(int file, char *ptr, int len)
{
(void)file;
int DataIdx;
for (DataIdx = 0; DataIdx < len; DataIdx++)
{
__io_putchar(*ptr++);
}
return len;
}
int _close(int file)
{
(void)file;
return -1;
}
int _fstat(int file, struct stat *st)
{
(void)file;
st->st_mode = S_IFCHR;
return 0;
}
int _isatty(int file)
{
(void)file;
return 1;
}
int _lseek(int file, int ptr, int dir)
{
(void)file;
(void)ptr;
(void)dir;
return 0;
}
int _open(char *path, int flags, ...)
{
(void)path;
(void)flags;
/* Pretend like we always fail */
return -1;
}
int _wait(int *status)
{
(void)status;
errno = ECHILD;
return -1;
}
int _unlink(char *name)
{
(void)name;
errno = ENOENT;
return -1;
}
int _times(struct tms *buf)
{
(void)buf;
return -1;
}
int _stat(char *file, struct stat *st)
{
(void)file;
st->st_mode = S_IFCHR;
return 0;
}
int _link(char *old, char *new)
{
(void)old;
(void)new;
errno = EMLINK;
return -1;
}
int _fork(void)
{
errno = EAGAIN;
return -1;
}
int _execve(char *name, char **argv, char **env)
{
(void)name;
(void)argv;
(void)env;
errno = ENOMEM;
return -1;
}
+79
View File
@@ -0,0 +1,79 @@
/**
******************************************************************************
* @file sysmem.c
* @author Generated by STM32CubeIDE
* @brief STM32CubeIDE System Memory calls file
*
* For more information about which C functions
* need which of these lowlevel functions
* please consult the newlib libc manual
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* Includes */
#include <errno.h>
#include <stdint.h>
/**
* Pointer to the current high watermark of the heap usage
*/
static uint8_t *__sbrk_heap_end = NULL;
/**
* @brief _sbrk() allocates memory to the newlib heap and is used by malloc
* and others from the C library
*
* @verbatim
* ############################################################################
* # .data # .bss # newlib heap # MSP stack #
* # # # # Reserved by _Min_Stack_Size #
* ############################################################################
* ^-- RAM start ^-- _end _estack, RAM end --^
* @endverbatim
*
* This implementation starts allocating at the '_end' linker symbol
* The '_Min_Stack_Size' linker symbol reserves a memory for the MSP stack
* The implementation considers '_estack' linker symbol to be RAM end
* NOTE: If the MSP stack, at any point during execution, grows larger than the
* reserved size, please increase the '_Min_Stack_Size'.
*
* @param incr Memory size
* @return Pointer to allocated memory
*/
void *_sbrk(ptrdiff_t incr)
{
extern uint8_t _end; /* Symbol defined in the linker script */
extern uint8_t _estack; /* Symbol defined in the linker script */
extern uint32_t _Min_Stack_Size; /* Symbol defined in the linker script */
const uint32_t stack_limit = (uint32_t)&_estack - (uint32_t)&_Min_Stack_Size;
const uint8_t *max_heap = (uint8_t *)stack_limit;
uint8_t *prev_heap_end;
/* Initialize heap end at first call */
if (NULL == __sbrk_heap_end)
{
__sbrk_heap_end = &_end;
}
/* Protect heap from growing into the reserved MSP stack */
if (__sbrk_heap_end + incr > max_heap)
{
errno = ENOMEM;
return (void *)-1;
}
prev_heap_end = __sbrk_heap_end;
__sbrk_heap_end += incr;
return (void *)prev_heap_end;
}
+406
View File
@@ -0,0 +1,406 @@
/**
******************************************************************************
* @file system_stm32f1xx.c
* @author MCD Application Team
* @brief CMSIS Cortex-M3 Device Peripheral Access Layer System Source File.
*
* 1. This file provides two functions and one global variable to be called from
* user application:
* - SystemInit(): Setups the system clock (System clock source, PLL Multiplier
* factors, AHB/APBx prescalers and Flash settings).
* This function is called at startup just after reset and
* before branch to main program. This call is made inside
* the "startup_stm32f1xx_xx.s" file.
*
* - SystemCoreClock variable: Contains the core clock (HCLK), it can be used
* by the user application to setup the SysTick
* timer or configure other parameters.
*
* - SystemCoreClockUpdate(): Updates the variable SystemCoreClock and must
* be called whenever the core clock is changed
* during program execution.
*
* 2. After each device reset the HSI (8 MHz) is used as system clock source.
* Then SystemInit() function is called, in "startup_stm32f1xx_xx.s" file, to
* configure the system clock before to branch to main program.
*
* 4. The default value of HSE crystal is set to 8 MHz (or 25 MHz, depending on
* the product used), refer to "HSE_VALUE".
* When HSE is used as system clock source, directly or through PLL, and you
* are using different crystal you have to adapt the HSE value to your own
* configuration.
*
******************************************************************************
* @attention
*
* Copyright (c) 2017-2021 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/** @addtogroup CMSIS
* @{
*/
/** @addtogroup stm32f1xx_system
* @{
*/
/** @addtogroup STM32F1xx_System_Private_Includes
* @{
*/
#include "stm32f1xx.h"
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_TypesDefinitions
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_Defines
* @{
*/
#if !defined (HSE_VALUE)
#define HSE_VALUE 8000000U /*!< Default value of the External oscillator in Hz.
This value can be provided and adapted by the user application. */
#endif /* HSE_VALUE */
#if !defined (HSI_VALUE)
#define HSI_VALUE 8000000U /*!< Default value of the Internal oscillator in Hz.
This value can be provided and adapted by the user application. */
#endif /* HSI_VALUE */
/*!< Uncomment the following line if you need to use external SRAM */
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
/* #define DATA_IN_ExtSRAM */
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
/* Note: Following vector table addresses must be defined in line with linker
configuration. */
/*!< Uncomment the following line if you need to relocate the vector table
anywhere in Flash or Sram, else the vector table is kept at the automatic
remap of boot address selected */
/* #define USER_VECT_TAB_ADDRESS */
#if defined(USER_VECT_TAB_ADDRESS)
/*!< Uncomment the following line if you need to relocate your vector Table
in Sram else user remap will be done in Flash. */
/* #define VECT_TAB_SRAM */
#if defined(VECT_TAB_SRAM)
#define VECT_TAB_BASE_ADDRESS SRAM_BASE /*!< Vector Table base address field.
This value must be a multiple of 0x200. */
#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
#else
#define VECT_TAB_BASE_ADDRESS FLASH_BASE /*!< Vector Table base address field.
This value must be a multiple of 0x200. */
#define VECT_TAB_OFFSET 0x00000000U /*!< Vector Table base offset field.
This value must be a multiple of 0x200. */
#endif /* VECT_TAB_SRAM */
#endif /* USER_VECT_TAB_ADDRESS */
/******************************************************************************/
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_Macros
* @{
*/
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_Variables
* @{
*/
/* This variable is updated in three ways:
1) by calling CMSIS function SystemCoreClockUpdate()
2) by calling HAL API function HAL_RCC_GetHCLKFreq()
3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
Note: If you use this function to configure the system clock; then there
is no need to call the 2 first functions listed above, since SystemCoreClock
variable is updated automatically.
*/
uint32_t SystemCoreClock = 8000000;
const uint8_t AHBPrescTable[16U] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9};
const uint8_t APBPrescTable[8U] = {0, 0, 0, 0, 1, 2, 3, 4};
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_FunctionPrototypes
* @{
*/
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
#ifdef DATA_IN_ExtSRAM
static void SystemInit_ExtMemCtl(void);
#endif /* DATA_IN_ExtSRAM */
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
/**
* @}
*/
/** @addtogroup STM32F1xx_System_Private_Functions
* @{
*/
/**
* @brief Setup the microcontroller system
* Initialize the Embedded Flash Interface, the PLL and update the
* SystemCoreClock variable.
* @note This function should be used only after reset.
* @param None
* @retval None
*/
void SystemInit (void)
{
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
#ifdef DATA_IN_ExtSRAM
SystemInit_ExtMemCtl();
#endif /* DATA_IN_ExtSRAM */
#endif
/* Configure the Vector Table location -------------------------------------*/
#if defined(USER_VECT_TAB_ADDRESS)
SCB->VTOR = VECT_TAB_BASE_ADDRESS | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM. */
#endif /* USER_VECT_TAB_ADDRESS */
}
/**
* @brief Update SystemCoreClock variable according to Clock Register Values.
* The SystemCoreClock variable contains the core clock (HCLK), it can
* be used by the user application to setup the SysTick timer or configure
* other parameters.
*
* @note Each time the core clock (HCLK) changes, this function must be called
* to update SystemCoreClock variable value. Otherwise, any configuration
* based on this variable will be incorrect.
*
* @note - The system frequency computed by this function is not the real
* frequency in the chip. It is calculated based on the predefined
* constant and the selected clock source:
*
* - If SYSCLK source is HSI, SystemCoreClock will contain the HSI_VALUE(*)
*
* - If SYSCLK source is HSE, SystemCoreClock will contain the HSE_VALUE(**)
*
* - If SYSCLK source is PLL, SystemCoreClock will contain the HSE_VALUE(**)
* or HSI_VALUE(*) multiplied by the PLL factors.
*
* (*) HSI_VALUE is a constant defined in stm32f1xx.h file (default value
* 8 MHz) but the real value may vary depending on the variations
* in voltage and temperature.
*
* (**) HSE_VALUE is a constant defined in stm32f1xx.h file (default value
* 8 MHz or 25 MHz, depending on the product used), user has to ensure
* that HSE_VALUE is same as the real frequency of the crystal used.
* Otherwise, this function may have wrong result.
*
* - The result of this function could be not correct when using fractional
* value for HSE crystal.
* @param None
* @retval None
*/
void SystemCoreClockUpdate (void)
{
uint32_t tmp = 0U, pllmull = 0U, pllsource = 0U;
#if defined(STM32F105xC) || defined(STM32F107xC)
uint32_t prediv1source = 0U, prediv1factor = 0U, prediv2factor = 0U, pll2mull = 0U;
#endif /* STM32F105xC */
#if defined(STM32F100xB) || defined(STM32F100xE)
uint32_t prediv1factor = 0U;
#endif /* STM32F100xB or STM32F100xE */
/* Get SYSCLK source -------------------------------------------------------*/
tmp = RCC->CFGR & RCC_CFGR_SWS;
switch (tmp)
{
case 0x00U: /* HSI used as system clock */
SystemCoreClock = HSI_VALUE;
break;
case 0x04U: /* HSE used as system clock */
SystemCoreClock = HSE_VALUE;
break;
case 0x08U: /* PLL used as system clock */
/* Get PLL clock source and multiplication factor ----------------------*/
pllmull = RCC->CFGR & RCC_CFGR_PLLMULL;
pllsource = RCC->CFGR & RCC_CFGR_PLLSRC;
#if !defined(STM32F105xC) && !defined(STM32F107xC)
pllmull = ( pllmull >> 18U) + 2U;
if (pllsource == 0x00U)
{
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
}
else
{
#if defined(STM32F100xB) || defined(STM32F100xE)
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
/* HSE oscillator clock selected as PREDIV1 clock entry */
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
#else
/* HSE selected as PLL clock entry */
if ((RCC->CFGR & RCC_CFGR_PLLXTPRE) != (uint32_t)RESET)
{/* HSE oscillator clock divided by 2 */
SystemCoreClock = (HSE_VALUE >> 1U) * pllmull;
}
else
{
SystemCoreClock = HSE_VALUE * pllmull;
}
#endif
}
#else
pllmull = pllmull >> 18U;
if (pllmull != 0x0DU)
{
pllmull += 2U;
}
else
{ /* PLL multiplication factor = PLL input clock * 6.5 */
pllmull = 13U / 2U;
}
if (pllsource == 0x00U)
{
/* HSI oscillator clock divided by 2 selected as PLL clock entry */
SystemCoreClock = (HSI_VALUE >> 1U) * pllmull;
}
else
{/* PREDIV1 selected as PLL clock entry */
/* Get PREDIV1 clock source and division factor */
prediv1source = RCC->CFGR2 & RCC_CFGR2_PREDIV1SRC;
prediv1factor = (RCC->CFGR2 & RCC_CFGR2_PREDIV1) + 1U;
if (prediv1source == 0U)
{
/* HSE oscillator clock selected as PREDIV1 clock entry */
SystemCoreClock = (HSE_VALUE / prediv1factor) * pllmull;
}
else
{/* PLL2 clock selected as PREDIV1 clock entry */
/* Get PREDIV2 division factor and PLL2 multiplication factor */
prediv2factor = ((RCC->CFGR2 & RCC_CFGR2_PREDIV2) >> 4U) + 1U;
pll2mull = ((RCC->CFGR2 & RCC_CFGR2_PLL2MUL) >> 8U) + 2U;
SystemCoreClock = (((HSE_VALUE / prediv2factor) * pll2mull) / prediv1factor) * pllmull;
}
}
#endif /* STM32F105xC */
break;
default:
SystemCoreClock = HSI_VALUE;
break;
}
/* Compute HCLK clock frequency ----------------*/
/* Get HCLK prescaler */
tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4U)];
/* HCLK clock frequency */
SystemCoreClock >>= tmp;
}
#if defined(STM32F100xE) || defined(STM32F101xE) || defined(STM32F101xG) || defined(STM32F103xE) || defined(STM32F103xG)
/**
* @brief Setup the external memory controller. Called in startup_stm32f1xx.s
* before jump to __main
* @param None
* @retval None
*/
#ifdef DATA_IN_ExtSRAM
/**
* @brief Setup the external memory controller.
* Called in startup_stm32f1xx_xx.s/.c before jump to main.
* This function configures the external SRAM mounted on STM3210E-EVAL
* board (STM32 High density devices). This SRAM will be used as program
* data memory (including heap and stack).
* @param None
* @retval None
*/
void SystemInit_ExtMemCtl(void)
{
__IO uint32_t tmpreg;
/*!< FSMC Bank1 NOR/SRAM3 is used for the STM3210E-EVAL, if another Bank is
required, then adjust the Register Addresses */
/* Enable FSMC clock */
RCC->AHBENR = 0x00000114U;
/* Delay after an RCC peripheral clock enabling */
tmpreg = READ_BIT(RCC->AHBENR, RCC_AHBENR_FSMCEN);
/* Enable GPIOD, GPIOE, GPIOF and GPIOG clocks */
RCC->APB2ENR = 0x000001E0U;
/* Delay after an RCC peripheral clock enabling */
tmpreg = READ_BIT(RCC->APB2ENR, RCC_APB2ENR_IOPDEN);
(void)(tmpreg);
/* --------------- SRAM Data lines, NOE and NWE configuration ---------------*/
/*---------------- SRAM Address lines configuration -------------------------*/
/*---------------- NOE and NWE configuration --------------------------------*/
/*---------------- NE3 configuration ----------------------------------------*/
/*---------------- NBL0, NBL1 configuration ---------------------------------*/
GPIOD->CRL = 0x44BB44BBU;
GPIOD->CRH = 0xBBBBBBBBU;
GPIOE->CRL = 0xB44444BBU;
GPIOE->CRH = 0xBBBBBBBBU;
GPIOF->CRL = 0x44BBBBBBU;
GPIOF->CRH = 0xBBBB4444U;
GPIOG->CRL = 0x44BBBBBBU;
GPIOG->CRH = 0x444B4B44U;
/*---------------- FSMC Configuration ---------------------------------------*/
/*---------------- Enable FSMC Bank1_SRAM Bank ------------------------------*/
FSMC_Bank1->BTCR[4U] = 0x00001091U;
FSMC_Bank1->BTCR[5U] = 0x00110212U;
}
#endif /* DATA_IN_ExtSRAM */
#endif /* STM32F100xE || STM32F101xE || STM32F101xG || STM32F103xE || STM32F103xG */
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
+123
View File
@@ -0,0 +1,123 @@
/* USER CODE BEGIN Header */
/**
******************************************************************************
* @file usart.c
* @brief This file provides code for the configuration
* of the USART instances.
******************************************************************************
* @attention
*
* Copyright (c) 2026 STMicroelectronics.
* All rights reserved.
*
* This software is licensed under terms that can be found in the LICENSE file
* in the root directory of this software component.
* If no LICENSE file comes with this software, it is provided AS-IS.
*
******************************************************************************
*/
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "usart.h"
/* USER CODE BEGIN 0 */
/* USER CODE END 0 */
UART_HandleTypeDef huart1;
/* USART1 init function */
void MX_USART1_UART_Init(void)
{
/* USER CODE BEGIN USART1_Init 0 */
/* USER CODE END USART1_Init 0 */
/* USER CODE BEGIN USART1_Init 1 */
/* USER CODE END USART1_Init 1 */
huart1.Instance = USART1;
huart1.Init.BaudRate = 115200;
huart1.Init.WordLength = UART_WORDLENGTH_8B;
huart1.Init.StopBits = UART_STOPBITS_1;
huart1.Init.Parity = UART_PARITY_NONE;
huart1.Init.Mode = UART_MODE_TX_RX;
huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;
huart1.Init.OverSampling = UART_OVERSAMPLING_16;
if (HAL_UART_Init(&huart1) != HAL_OK)
{
Error_Handler();
}
/* USER CODE BEGIN USART1_Init 2 */
/* USER CODE END USART1_Init 2 */
}
void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
{
GPIO_InitTypeDef GPIO_InitStruct = {0};
if(uartHandle->Instance==USART1)
{
/* USER CODE BEGIN USART1_MspInit 0 */
/* USER CODE END USART1_MspInit 0 */
/* USART1 clock enable */
__HAL_RCC_USART1_CLK_ENABLE();
__HAL_RCC_GPIOA_CLK_ENABLE();
/**USART1 GPIO Configuration
PA9 ------> USART1_TX
PA10 ------> USART1_RX
*/
GPIO_InitStruct.Pin = TX_RS485_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_MEDIUM;
HAL_GPIO_Init(TX_RS485_GPIO_Port, &GPIO_InitStruct);
GPIO_InitStruct.Pin = RX_RS485_Pin;
GPIO_InitStruct.Mode = GPIO_MODE_INPUT;
GPIO_InitStruct.Pull = GPIO_NOPULL;
HAL_GPIO_Init(RX_RS485_GPIO_Port, &GPIO_InitStruct);
/* USART1 interrupt Init */
HAL_NVIC_SetPriority(USART1_IRQn, 0, 0);
HAL_NVIC_EnableIRQ(USART1_IRQn);
/* USER CODE BEGIN USART1_MspInit 1 */
/* USER CODE END USART1_MspInit 1 */
}
}
void HAL_UART_MspDeInit(UART_HandleTypeDef* uartHandle)
{
if(uartHandle->Instance==USART1)
{
/* USER CODE BEGIN USART1_MspDeInit 0 */
/* USER CODE END USART1_MspDeInit 0 */
/* Peripheral clock disable */
__HAL_RCC_USART1_CLK_DISABLE();
/**USART1 GPIO Configuration
PA9 ------> USART1_TX
PA10 ------> USART1_RX
*/
HAL_GPIO_DeInit(GPIOA, TX_RS485_Pin|RX_RS485_Pin);
/* USART1 interrupt Deinit */
HAL_NVIC_DisableIRQ(USART1_IRQn);
/* USER CODE BEGIN USART1_MspDeInit 1 */
/* USER CODE END USART1_MspDeInit 1 */
}
}
/* USER CODE BEGIN 1 */
/* USER CODE END 1 */