#include <stdint.h>
#include <math.h>
static void delay_ms(uint32_t ms) {
for (uint32_t i = 0; i < ms * 6000; i++) {
__asm volatile ("nop");
}
}
static void uart2_write_char(char c) {
while (!(USART2->ISR & (1 << 7)));
USART2->TDR = c;
}
static void uart2_write_string(const char *s) {
while (*s) uart2_write_char(*s++);
}
static void uart2_write_number(uint32_t n) {
char buf[12];
int i = 0;
if (n == 0) {
uart2_write_char('0');
return;
}
while (n > 0) {
buf[i++] = '0' + (n % 10);
n /= 10;
}
while (i > 0) uart2_write_char(buf[--i]);
}
static void gpio_init(void) {
RCC->IOPENR |= (1 << 0);
GPIOA->MODER &= ~(3 << (0 * 2));
GPIOA->MODER |= (3 << (0 * 2));
GPIOA->MODER &= ~(3 << (2 * 2));
GPIOA->MODER |= (2 << (2 * 2));
GPIOA->AFR[0] &= ~(0xF << (2 * 4));
GPIOA->AFR[0] |= (1 << (2 * 4));
GPIOA->MODER &= ~(3 << (8 * 2));
GPIOA->MODER |= (2 << (8 * 2));
GPIOA->AFR[1] &= ~(0xF << ((8 - 8) * 4));
GPIOA->AFR[1] |= (2 << ((8 - 8) * 4));
}
static void uart2_init(void) {
RCC->APBENR1 |= (1 << 17);
USART2->CR1 = 0;
USART2->BRR = 417;
USART2->CR1 |= (1 << 3);
USART2->CR1 |= (1 << 0);
}
static void adc1_init(void) {
RCC->APBENR2 |= (1 << 20);
ADC1->CR &= ~(1 << 0);
ADC1->CR |= (1 << 31);
while (ADC1->CR & (1 << 31));
ADC1->CHSELR = (1 << 0);
ADC1->SMPR = 0x7;
ADC1->CR |= (1 << 0);
while (!(ADC1->ISR & (1 << 0)));
}
static uint16_t adc1_read(void) {
ADC1->CHSELR = (1 << 0);
ADC1->CR |= (1 << 2);
while (!(ADC1->ISR & (1 << 2)));
return (uint16_t)(ADC1->DR & 0x0FFF);
}
static void tim1_pwm_init(void) {
RCC->APBENR2 |= (1 << 11);
TIM1->PSC = 47;
TIM1->ARR = 19999;
TIM1->CCMR1 &= ~(7 << 4);
TIM1->CCMR1 |= (6 << 4);
TIM1->CCMR1 |= (1 << 3);
TIM1->CCER |= (1 << 0);
TIM1->BDTR |= (1 << 15);
TIM1->CCR1 = 1000;
TIM1->EGR |= (1 << 0);
TIM1->CR1 |= (1 << 7);
TIM1->CR1 |= (1 << 0);
}
static void servo_set_angle(uint32_t angle) {
if (angle > 180) angle = 180;
uint32_t pulse_us = 1000 + ((angle * 1000) / 180);
TIM1->CCR1 = pulse_us;
}
void setup() {
gpio_init();
uart2_init();
adc1_init();
tim1_pwm_init();
uart2_write_string("Temperature-Based Smart Cooling Vent Controller\r\n");
}
void loop() {
uint16_t adc_value = adc1_read();
// ADC değeri sıcaklık seviyesi gibi ölçekleniyor
float temperature_f = 1.0f / (logf(1.0f / (4095.0f / adc_value - 1.0f)) / 3950.0f + 1.0f / 298.15f) - 273.15f;
int32_t temperature = (int32_t)temperature_f;
uint32_t angle;
if (temperature < 25) {
angle = 0;
} else if (temperature > 75) {
angle = 180;
} else {
angle = ((temperature - 25) * 180) / 50;
}
servo_set_angle(angle);
uart2_write_string("ADC: ");
uart2_write_number(adc_value);
uart2_write_string(" | Temp Level: ");
uart2_write_number(temperature);
uart2_write_string(" C | Servo Angle: ");
uart2_write_number(angle);
uart2_write_string(" deg\r\n");
delay_ms(100);
}Loading
st-nucleo-c031c6
st-nucleo-c031c6