Untitled
unknown
plain_text
a year ago
2.0 kB
7
Indexable
#include <avr/io.h> #include <util/delay.h> double temp; double lastTemp; double vIn; void checkADC(){ unsigned int adcVal = ADCW; vIn = (adcVal * 5.0) / 1024.0; // Convert ADC value to voltage temp = vIn * 100.0; // Convert voltage to temperature (LM35 outputs 10mV/°C) if (temp - lastTemp >= 10) { if (OCR0 < 255) { OCR0 += (10 * 255) / 100; // Increase PWM duty cycle by 10% if (OCR0 > 255) OCR0 = 255; // Cap at 100% } lastTemp = temp; } else if (temp - lastTemp <= -10) { if (OCR0 > 0) { OCR0 -= (10 * 255) / 100; // Decrease PWM duty cycle by 10% if (OCR0 < 0) OCR0 = 0; // Cap at 0% } lastTemp = temp; } } int main() { DDRB |= (1 << PORTB3); // OC0 pin is output // ADC setup ADMUX = (0 << REFS1) | (1 << REFS0); // Vref = AVcc, ADC0 selected ADCSRA = (1 << ADEN) | (1 << ADPS2) | (1 << ADPS1) | (1 << ADPS0); // Enable ADC, prescaler 128 // PWM setup TCCR0 |= (1 << WGM01) | (1 << WGM00); // Fast PWM mode TCCR0 |= (1 << COM01); // Clear OC0 on compare match TCCR0 |= (1 << CS01); // Prescaler of 8 // Initial ADC read ADCSRA |= (1 << ADSC); // Start conversion while (ADCSRA & (1 << ADSC)); // Wait for conversion to complete vIn = (ADCW * 5.0) / 1024.0; // Convert initial ADC value to voltage temp = vIn * 100.0; // Convert voltage to temperature lastTemp = temp; OCR0 = 0; // Initial motor speed while (1) { ADCSRA |= (1 << ADSC); // Start conversion while (ADCSRA & (1 << ADSC)); // Wait for conversion to complete checkADC(); // Check and adjust motor speed based on temperature _delay_ms(500); // Add some delay for stability } }
Editor is loading...
Leave a Comment