2024-03-12 12:37:29 +00:00
|
|
|
#include "voltage.h"
|
2024-03-13 11:13:38 +00:00
|
|
|
#include "uart.h"
|
2024-03-13 10:46:02 +00:00
|
|
|
|
2024-03-12 12:37:29 +00:00
|
|
|
void ADC0_init(void) {
|
2024-03-13 11:13:38 +00:00
|
|
|
/* Initializing ADC0 pin*/
|
2024-04-09 11:37:38 +00:00
|
|
|
/*Voltage reading on pin pd6*/
|
2024-03-12 12:37:29 +00:00
|
|
|
PORTD.PIN6CTRL &= ~PORT_ISC_gm;
|
2024-03-13 11:13:38 +00:00
|
|
|
PORTD.PIN6CTRL |= PORT_ISC_INPUT_DISABLE_gc; /* Disable */
|
2024-03-12 12:37:29 +00:00
|
|
|
PORTD.PIN6CTRL &= PORT_PULLUPEN_bm;
|
2024-04-09 11:37:38 +00:00
|
|
|
|
2024-04-09 11:50:02 +00:00
|
|
|
/* Thermistor */
|
|
|
|
|
PORTD.PIN3CTRL &= ~PORT_ISC_gm;
|
|
|
|
|
PORTD.PIN3CTRL |= PORT_ISC_INPUT_DISABLE_gc; /* Disable */
|
|
|
|
|
PORTD.PIN3CTRL &= PORT_PULLUPEN_bm;
|
2024-04-09 11:37:38 +00:00
|
|
|
|
2024-03-12 12:37:29 +00:00
|
|
|
ADC0.CTRLC = ADC_PRESC_DIV4_gc;
|
|
|
|
|
VREF.ADC0REF = VREF_REFSEL_VDD_gc; /* Internal reference */
|
|
|
|
|
ADC0.CTRLA = ADC_ENABLE_bm /* ADC Enable: enabled */
|
|
|
|
|
| ADC_RESSEL_10BIT_gc; /* 10-bit mode */
|
|
|
|
|
/* Select ADC channel */
|
|
|
|
|
ADC0.MUXPOS = ADC_MUXPOS_AIN6_gc;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
uint16_t ADC0_read(void) {
|
|
|
|
|
/* Start ADC conversion */
|
|
|
|
|
ADC0.COMMAND = ADC_STCONV_bm;
|
|
|
|
|
/* Wait until ADC conversion done */
|
|
|
|
|
while (!(ADC0.INTFLAGS & ADC_RESRDY_bm)) {
|
|
|
|
|
;
|
|
|
|
|
}
|
2024-03-20 13:18:45 +00:00
|
|
|
// Clear the interrupt flag by writing 1:
|
2024-03-20 14:53:26 +00:00
|
|
|
ADC0.INTFLAGS = ADC_RESRDY_bm;
|
2024-03-12 12:37:29 +00:00
|
|
|
return ADC0.RES;
|
|
|
|
|
}
|
2024-03-13 10:46:02 +00:00
|
|
|
|
2024-04-09 12:36:11 +00:00
|
|
|
uint16_t thermistor_voltage_read() {
|
2024-03-20 14:45:24 +00:00
|
|
|
/* Gets value for the diode */
|
2024-04-09 12:36:11 +00:00
|
|
|
ADC0.MUXPOS = 0x03;
|
2024-04-09 13:54:42 +00:00
|
|
|
uint16_t adc_val = ADC0_read();
|
2024-03-20 14:45:24 +00:00
|
|
|
|
2024-04-09 12:56:14 +00:00
|
|
|
return adc_val;
|
2024-03-20 14:45:24 +00:00
|
|
|
}
|
2024-03-20 14:53:26 +00:00
|
|
|
|
2024-04-09 13:54:42 +00:00
|
|
|
uint16_t external_voltage_read(){
|
|
|
|
|
ADC0.MUXPOS = 0x02;
|
|
|
|
|
uint16_t adc_val = ADC0_read();
|
|
|
|
|
|
|
|
|
|
return adc_val;
|
|
|
|
|
}
|
|
|
|
|
|
2024-03-20 14:53:26 +00:00
|
|
|
uint16_t internal_voltage_read() {
|
2024-03-20 14:45:24 +00:00
|
|
|
/* Gets value for the internal voltage reffreance*/
|
2024-04-09 12:56:14 +00:00
|
|
|
|
|
|
|
|
ADC0.MUXPOS = 0x44;
|
|
|
|
|
uint8_t adc_val = ADC0_read();
|
|
|
|
|
|
|
|
|
|
return adc_val*10;
|
2024-03-20 15:11:01 +00:00
|
|
|
}
|
2024-04-09 13:54:42 +00:00
|
|
|
|
|
|
|
|
uint16_t convert_to_voltage(uint16_t adc_val){
|
|
|
|
|
uint16_t min_in= 0;
|
|
|
|
|
uint16_t min_out= 0;
|
|
|
|
|
uint16_t max_in= 1023;
|
|
|
|
|
uint16_t max_out= 3.3;
|
|
|
|
|
uint16_t voltage = (adc_val-min_in)*(max_out-min_out)/(max_in-min_in) + min_out;
|
|
|
|
|
return voltage;
|
|
|
|
|
|
|
|
|
|
}
|