Files
Tool-Probe-Cnc/src/adc_probe_ext.c
2025-05-29 21:47:21 +02:00

40 lines
1.1 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <avr/io.h>
#include "adc_probe_ext.h"
void adc_init(void)
{
// Vcc as reference, select ADC2 (MUX = 0b010)
ADMUX = (0 << REFS1) | (0 << REFS0) | // VCC as reference
(0 << ADLAR) | // Right adjust result
(0b010); // ADC2
// Enable ADC, prescaler = 64 (assuming 8 MHz → ADC freq = 125 kHz)
ADCSRA = (1 << ADEN) | // Enable ADC
(1 << ADPS2) | (1 << ADPS1); // Prescaler = 64
}
uint16_t adc_read(uint8_t channel)
{
// Set channel (07), keeping the other bits in ADMUX
ADMUX = (ADMUX & 0xF8) | (channel & 0x07);
ADCSRA |= (1 << ADSC); // Start conversion
while (ADCSRA & (1 << ADSC))
; // Wait for conversion to finish
return ADC; // Return 10-bit result
}
uint8_t is_device_connected(void)
{
uint16_t value = adc_read(2); // ADC2 = PA2
// Zakładamy 5V Vcc → 2.5V = około 512
if (value > 400 && value < 600)
{
return 1; // Podłączone (w granicach tolerancji)
}
return 0; // Odłączone (napięcie bliskie 0 lub 5V)
}