MBLOCK 5 SERVO AVEC POTENTIOMETRE


Photo résistance

Programme C Photo Résistance écrit et testé par Guillaume:
#ifndef F_CPU#define F_CPU 16000000L#endif
#include <stdio.h>
#include <avr/io.h>#include <util/delay.h>
#if !defined(NDEBUG)#define DEBUG#endif
#ifdef DEBUG#include "serial_debug.h"#endif
int main(void){ DDRD |= (1<<LED_PIN); // LED_PIN is set as OUTPUT
#ifdef DEBUG USART_Init(COMPUTE_UBRR(F_CPU, BAUD));#endif
// PWM is set up by defining properties on the time counter control register // (TCCR) // Here it is the timer/counter 2 which controls the behavior of the PD3/OC2B // pin TCCR2A = 0x0; TCCR2B = 0x0; // By setting WGM22:0 equal to 3 or 7 PWM is activated. Here WGM22:0 = 0b011 = 3 // By setting COM2B1:0 equal to 0b11 OC2B output is activated (which correspond // to port PD3 that however has to be activated as an output) and in inverted mode TCCR2A = ((1<<COM2B1)|(1<<COM2B0)|(1<<WGM21)|(1<<WGM20)); // CS2:0 controls the prescaler. Here it is equal to 0b111 (prescaler = 1024) TCCR2B = ((1<<CS22)|(1<<CS21)|(1<<CS20)|(0<<WGM22));
// Setting up the analog to digital converter ADMUX |= ((0<<MUX3)|(0<<MUX2)|(0<<MUX1)|(1<<MUX0)); // Select A1 pin ADMUX |= ((1<<REFS1)|(1<<REFS0)); // VREF is internal 1.1V ADCSRA |= ((0<<ADPS2)|(0<<ADPS1)|(0<<ADPS0)); // Prescaler. Factor division = 2 ADMUX |= (0<<ADLAR); // Right adjust the result ADCSRA |= (1<<ADATE); // Select autotrigger mode ADCSRB |= ((0<<ADTS2)|(0<<ADTS1)|(0<<ADTS0)); // Free running mode ADCSRA |= (1<<ADEN); // Enables the ADC
OCR2B = 0x1;
#ifdef DEBUG char dbg_buffer[35];#endif
while(1) { ADCSRA |= (1<<ADSC); // Start a conversion while(!(ADCSRA&(1<<ADIF))); // Waiting for the conversion to finish ADCSRA |= (0<<ADIF); // Clearing conversion flag
uint16_t photo_res_val = ADC; // Read the conversion result
// Compute the value that will be sent to the OCR2B (output compare registe) // to set up the PWM signal const uint32_t led_val = photo_res_val * 256UL / 1024UL;
#ifdef DEBUG sprintf(dbg_buffer, "Value received is %u", photo_res_val); USART0SendData((uint8_t*)dbg_buffer); sprintf(dbg_buffer, "Value sent is %u", (uint8_t) led_val); USART0SendData((uint8_t*)dbg_buffer);#endif
OCR2B = (uint8_t) led_val; _delay_ms(100); }
return 0;}
Servo moteur