peterzig

ADC i PWM kod

Nov 25th, 2020
360
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include <avr/io.h>
  2. #include "avr/interrupt.h"
  3. unsigned char cnt=0;
  4. void speedControl(unsigned int speed){
  5.  float _dutyCycle;
  6.  unsigned int dutyCycle;
  7.  _dutyCycle=speed*(100.0/1024);
  8.  //dutyCycle=20;
  9.  dutyCycle=10+(int)_dutyCycle;
  10.  if(cnt<dutyCycle) PORTD|=(1<<0);
  11.  if(cnt>=dutyCycle)  PORTD&=~(1<<0);
  12.  if(cnt>=100) cnt=0;
  13. }
  14. int main(void)
  15. {  unsigned int adcResult;
  16.  //PortD as output
  17.  DDRD=0xFF;
  18.  //PA0 or ADC0 as an analog input
  19.  DDRA=0;
  20.  //Set 1:8 pre-scaler
  21.  TCCR0=0x02;
  22.  //Clear overflow flag
  23.  TIFR=0x01;
  24.  //Enable Timer 0 interrupt
  25.  TIMSK=0x01;
  26.  //set global interrupt
  27.  sei();
  28.  //Turn on the ADC module
  29.  ADCSRA|=(1<<ADEN);
  30.  /*Select ADC7*/
  31.  ADMUX|=0x07;
  32.  while (1)
  33.  {
  34.   //Start the conversion
  35.   ADCSRA|=(1<<ADSC);
  36.   //Wait for the completion
  37.   while((ADCSRA&(1<<ADSC))==1);   //Read the result
  38.   adcResult=ADCL+(ADCH<<8);
  39.   speedControl(adcResult);
  40.  }
  41. }
  42. ISR(TIMER0_OVF_vect){
  43.  //Load -5 to make 10 uS interrupt time
  44.  TCNT0=-5;
  45.  cnt+=1;
  46.  TIFR=0x01;
  47. }
RAW Paste Data