Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
3.0 kB
30
Indexable
Never
// Karl Alvene G. Hansol
// EEE 158 - HUV
// Lab 05 Activity 2 (Analog-to-digital Conversion (ADC))

#include <stdint.h>
#include <stm32f4xx.h>
#include <stm32f411xe.h>
uint16_t adc_value = 0x0000;
uint16_t temp_bit = 0x0000;
uint16_t mask = 0x0000;
uint16_t move = 0x0000;

void GPIO_init(void);
void ADC_init(void);
void ADC_enable(void);
void ADC_startconv(void);
void ADC_waitconv(void);
int ADC_GetVal(void);
void TempSense(int);
void delay_ms(int delay);

int main(void) {

	GPIO_init();
	ADC_init();

	/* Loop forever */
	while (1) {
		//start adc conversion
		ADC_enable();
		//start conversion
		ADC_startconv();
		//wait for conversion to finish
		ADC_waitconv();
		//store converted data to a variable
		adc_value = ADC_GetVal();

		//monitor temperature here
		TempSense(adc_value);
	}
}

void GPIO_init(void) {
	//enable GPIOA clock
	RCC->AHB1ENR |= (1 << 0);

	RCC->AHB1ENR |= (1 << 1); // Add this one

	//configure PA1 to analog mode
	GPIOA->MODER |= (1 << 3);
	GPIOA->MODER |= (1 << 2);

	//configure other GPIO pins here (Modify this code)
	GPIOB->MODER &= ~(1 << 3);
	GPIOB->MODER |= (1 << 2);

	GPIOB->MODER &= ~(1 << 5);
	GPIOB->MODER |= (1 << 4);

	GPIOB->OTYPER &= ~(1<<1);
	GPIOB->OTYPER &= ~(1<<2);
}

void ADC_init(void) {
	//enable adc clock
	RCC->APB2ENR |= (1 << 8);

	//prescaler = 2
	ADC->CCR &= ~(1 << 16);
	ADC->CCR &= ~(1 << 17);

	//configure ADC resolution
	ADC1->CR1 &= ~(1 << 25);
	ADC1->CR1 &= ~(1 << 24);

	//Configure to Scan mode
	ADC1->CR1 |= (1 << 8);
	//Enable Interrupt for EOC
	ADC1->CR1 |= (1 << 5);
	//configure sampling time
	ADC1->SMPR2 &= ~(1 << 5);
	ADC1->SMPR2 &= ~(1 << 4);
	ADC1->SMPR2 |= (1 << 3);
	//end of conversion selection
	ADC1->CR2 &= ~(1 << 10);

	//configure data alignment
	ADC1->CR2 &= ~(1 << 11);

	//total number of conversions in the channel conversion sequence
	ADC1->SQR1 &= ~(1 << 23);
	ADC1->SQR1 &= ~(1 << 22);
	ADC1->SQR1 &= ~(1 << 21);
	ADC1->SQR1 &= ~(1 << 20);

	//assign channel for first conversion
	ADC1->SQR3 |= (1 << 0);

	//cont conversion mode
	ADC1->CR2 |= (1 << 1);
}

void ADC_enable(void) {
	ADC1->CR2 |= (1 << 0); //enable the adc
	delay_ms(1); // required to ensure adc stable
}

void ADC_startconv(void) {
	ADC1->CR2 |= (1 << 30);
}

void ADC_waitconv(void) {
	//wait for the end of conversion
	while (!((ADC1->SR) & (1 << 1))) {
		;
	}
}

int ADC_GetVal(void) {
	return ADC1->DR; //read the value contained at the data register
}

void TempSense(int adc_value){
	//do something useful here
	if (adc_value > 1800) {
		GPIOB->ODR &= ~(1 << 2);
		GPIOB->ODR |= (1 << 1);
	}
	else {
		GPIOB->ODR &= ~(1 << 1);
		GPIOB->ODR |= (1 << 2);
	}
}

void delay_ms(int delay) {
	int i;
	for (; delay > 0; delay--) {
		for (i = 0; i < 2657; i++)
			;
	}
}

//PUT YOUR ANSWER TO THE QUESTION BELOW.. just make sure they are commented as well :)
Leave a Comment