Advertisement
alexanderik

Battery Protection from Discharge

Apr 30th, 2016
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.62 KB | None | 0 0
  1. // ATtiny13
  2. // Battery Protection from discharge
  3. // © Grigoriev Alexander , 2016
  4. // ADC Module
  5.  
  6. #include <avr/io.h>
  7. #define F_CPU 8000000UL
  8. #include <compat/deprecated.h>
  9.  
  10.  
  11. #define GATE PORTB0
  12. #define VOLT PORTB4
  13. #define WARN PORTB3
  14.  
  15.  
  16. int ReadADC();
  17.  
  18.  
  19. /*
  20. R1=100K;
  21. R2=20K;
  22. Vout=(R2/(R1+R2));  ~0.166667
  23. 11.1*0.16667 =
  24. 1024*1.85/5=378.88;
  25. 1024*2.03/5=415.7;
  26. c=34.13
  27. 11.1*34.13=378.8
  28.  
  29. */
  30.  
  31.  
  32. uint16_t  LTHR = 379; //11.1
  33. uint16_t  HTHR = 415; //12.2;
  34.  
  35. #define SRAM __attribute__((section(".noinit")))
  36.  
  37. SRAM int temp ;
  38.  
  39. void initadc()
  40. {
  41.     ADMUX |= (0 << REFS0); // VCC as Reference
  42.     //
  43.     //  MUX[1:0] Single Ended Input
  44.     //  00 ADC0 (PB5)
  45.     //  01 ADC1 (PB2)
  46.     //  10 ADC2 (PB4)
  47.     //  11 ADC3 (PB3)
  48.     ADMUX |= (1 << MUX1) | (0 << MUX0); // ADC2 PB.4
  49.  
  50. }
  51. int __attribute__((naked))
  52. main (void)
  53. {
  54.     sbi(DDRB,GATE); //  DDRB |= (1 << GATE); // output
  55.     sbi(PORTB,GATE); //null
  56.  
  57.     cbi(DDRB,VOLT); //  DDRB &= ~(1 << VOLT);
  58.     cbi(PORTB,VOLT); //PORTB &= ~(1 << VOLT);
  59.    
  60. //  Bit 7 – ADEN: ADC Enable
  61. //  Writing this bit to one enables the ADC. By writing it to zero, the ADC is turned off. Turning the
  62. //  ADC off while a conversion is in progress, will terminate this conversion.
  63.  
  64.     initadc();
  65.     ADCSRA |= (1 << ADEN); // Enable ADC
  66.  
  67.  
  68.     while (1)
  69.     {
  70.        
  71.         temp=ReadADC();
  72.         if(temp<=LTHR)
  73.         {cbi(PORTB,GATE);
  74.          cbi(PORTB,WARN); }
  75.         else
  76.         if (temp>=HTHR){
  77.         sbi(PORTB,GATE);
  78.         cbi(PORTB,WARN);
  79.         }      
  80.         else
  81.         sbi(PORTB,WARN);
  82.        
  83.  
  84.     }
  85. }
  86.  
  87.  
  88.  
  89.  
  90. int ReadADC()
  91. {
  92. initadc();
  93.  
  94. ADCSRA |= (1 << ADSC); // Start Converstion
  95.  
  96.     while((ADCSRA & 0x40) !=0){}; //wait for conv complete
  97.  
  98.     return ADC;
  99. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement