bme680-air-meter-sw/main.c
2019-10-17 23:18:18 +02:00

137 lines
2.9 KiB
C

#include <stm32f0xx.h>
#include <delay.h>
#include <lcd.h>
#include <stdlib.h>
#include <stdio.h>
#include <meas.h>
unsigned int i = 0x12345678;
unsigned char c = 2;
#define OUTPUT(pin) (0x01U << (pin * 2))
#define PULLUP(pin) (0x1U << (pin* 2))
#define ALTFUNC(pin) ((0x2) << (pin * 2))
#define PINMASK(pin) ((0x3) << (pin * 2))
#define SETAF(PORT,PIN,AF) PORT->AFR[(PIN < 8 ? 0 : 1)] |= AF << ((PIN < 8 ? PIN : (PIN - 8)) * 4)
static void setup_hw(void)
{
RCC->AHBENR |= RCC_AHBENR_GPIOFEN | RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN;
RCC->APB2ENR |= RCC_APB2ENR_SPI1EN;
GPIOA->MODER |= OUTPUT(4) | ALTFUNC(5) | ALTFUNC(7) | ALTFUNC(6) | OUTPUT(0) | OUTPUT(1) | OUTPUT(2) | OUTPUT(3) | OUTPUT(9) | OUTPUT(10);
SETAF(GPIOA, 5, 0);
SETAF(GPIOA, 6, 0);
SETAF(GPIOA, 7, 0);
GPIOF->MODER |= OUTPUT(0);
GPIOF->PUPDR |= PULLUP(1);
GPIOF->ODR &= ~(1<<0);
GPIOB->MODER |= OUTPUT(1);
GPIOB->ODR &= ~(1<<1);
GPIOA->ODR |= (1<<4);
SPI1->CR1 = SPI_CR1_BR_2 | SPI_CR1_MSTR | SPI_CR1_SSM | SPI_CR1_SSI;
SPI1->CR1 |= SPI_CR1_SPE;
/* Configure Systick for 1ms interval */
SysTick_Config(8000/*00*/);
lcd_init();
}
static void format(int temp, char *string, uint8_t decimals, uint8_t digits)
{
int digit;
for (digit = decimals+digits; digit >= 1; digit--) {
if (digit >= digits+1)
string[digit] = (temp % 10) + 0x30;
else
string[digit-1] = (temp % 10) + 0x30;
temp /= 10;
}
string[digits] = '.';
string[decimals+digits+1] = 0x00;
}
static void print_data_to_display(int32_t temp, uint32_t pressure, uint32_t humidity)
{
char lcd_line[17];
lcd_clear();
lcd_home();
lcd_string("Temp: ");
format(temp, lcd_line, 2, 2);
lcd_string(lcd_line);
lcd_setcursor(0, 1);
lcd_string("RH: ");
format((int)humidity, lcd_line, 3, 2);
lcd_string(lcd_line);
lcd_setcursor(0, 2);
lcd_string("Pr.: ");
format((int)pressure, lcd_line, 2, 4);
lcd_string(lcd_line);
}
int main(void) {
struct bme680_field_data data;
int8_t ambient_temp = 25;
int32_t temp_calib;
int i;
setup_hw();
meas_init_without_gas();
temp_calib = 0;
lcd_home();
lcd_string("Initializing...");
for (i = 0; i < 8; i++) {
i = 0;
delay_ms(1000);
if (meas_do(false, &data, ambient_temp)) {
/* Measurement failed. retry */
i--;
continue;
}
temp_calib += data.temperature;
ambient_temp = (int8_t)(data.temperature / 100);
print_data_to_display(data.temperature, data.pressure, data.humidity);
}
temp_calib /= 8;
}
void HardFault_Handler(void)
{
while(1);
}
void SysTick_Handler(void) {
static int internal_tick = 0;
static volatile uint8_t backlight_counter;
/* Blink bad air LED */
tick++;
internal_tick++;
if (!(GPIOF->IDR & (1U<<1))) {
backlight_counter = 30;
GPIOB->ODR |= (1U<<1);
}
if (internal_tick > 200) {
internal_tick = 0;
if (backlight_counter > 0) {
backlight_counter--;
} else if (backlight_counter == 0) {
GPIOB->ODR &= ~(1U<<1);
}
//GPIOF->ODR ^= (1<<0);
}
}