9511_workbook

solved exercises from algorithms & programming I (9511) prof. Cardozo
Index Commits Files Refs README
guia07/ex11.c (1748B)
   1 #include <stdio.h>
   2 
   3 #define MASK_SPIE    0x80
   4 #define MASK_SPE    0x40
   5 #define MASK_CPOL    0x08
   6 #define MASK_SPR1    0x04
   7 #define MASK_SPR0    0x02
   8 
   9 #define SHIFT_SPIE    7
  10 #define SHIFT_SPE    6
  11 #define SHIFT_CPOL    3
  12 #define SHIFT_SPR1    2
  13 #define SHIFT_SPR0    1
  14 
  15 typedef unsigned char uchar;
  16 typedef enum { LO, HI } bit_t;
  17 
  18 bit_t getSPIE(uchar);
  19 bit_t getCPOL(uchar);
  20 uchar getPrescalingFactor(uchar SPCR);
  21 
  22 void getCOMControl(uchar control, uchar *prescalingFactor, uchar *divisionFactor);
  23 void setCPOL(uchar *, bit_t);
  24 
  25 int main (void)
  26 {
  27     uchar SPCR = 0xCE; /* 1100 1110 */
  28 
  29     printf("Interrupciones: %s\n", getSPIE(SPCR) ? "habilitadas" : " deshabilitadas");
  30     printf("Reloj activo: %s\n", getCPOL(SPCR) ? "nivel bajo" : "nivel alto");
  31     printf("Factor de division: %d\n", getPrescalingFactor(SPCR));
  32     
  33     printf("0x%X\n", SPCR);
  34 
  35     /* Sets CPOL bit to LOW */
  36     setCPOL(&SPCR, LO);
  37 
  38     printf("0x%X\n", SPCR);
  39 
  40     return 0;
  41 }
  42 
  43 bit_t getSPIE(uchar SPCR)
  44 {
  45     return (SPCR & MASK_SPIE) >> SHIFT_SPIE;
  46 }
  47 
  48 bit_t getCPOL(uchar SPCR)
  49 {
  50     return (SPCR & MASK_CPOL) >> SHIFT_CPOL;
  51 }
  52 
  53 uchar getPrescalingFactor(uchar SPCR)
  54 {
  55     static uchar divFactor[4] = { 2, 4, 16, 32 };
  56     return divFactor[(SPCR & (MASK_SPR0 + MASK_SPR1)) >> SHIFT_SPR0];
  57 }
  58 
  59 void getCOMControl(uchar control, uchar *prescalingFactor, uchar *divisionFactor)
  60 {
  61     if(!prescalingFactor || !divisionFactor) return;
  62 
  63     /* static because otherwise it would have to load the array into memmory everytime the function is called */
  64     static uchar divFactor[4] = { 2, 4, 16, 32 };
  65 
  66     *prescalingFactor = ((control & (MASK_SPR0 + MASK_SPR1)) >> SHIFT_SPR0);
  67     *divisionFactor = divFactor[*prescalingFactor];
  68 }
  69 
  70 void setCPOL(uchar *control, bit_t CPOL)
  71 {
  72     if(!control) return;
  73 
  74     *control = ((*control & ~MASK_CPOL) + (CPOL << SHIFT_CPOL));
  75 }