Guest User

Untitled

a guest
Jan 16th, 2019
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.58 KB | None | 0 0
  1. // I have initialized PORTB like this
  2.  
  3. PORTB=0x00;
  4. DDRB=0xBF;
  5.  
  6. // SPI initialisation
  7. // SPI clock rate fck/16
  8. // SPI master
  9. // SPI MSB first
  10. // SPI CPOL = 1, CPHA = 1
  11.  
  12. SPCR=0x5D;
  13. PORTB.3 = 1;
  14.  
  15. void main (void){
  16.  
  17. printf("adc value :%xn",ReadAd());
  18.  
  19. }
  20.  
  21. #define ADC_CS PORTB.3
  22. #define WG_CS PORTB.4
  23. #define MOSI PORTB.5
  24. #define MISO PINB.6
  25. #define SCK PORTB.7
  26.  
  27. #define ADC_CS_PIN PINB.3
  28. #define WG_CS_PIN PINB.4
  29.  
  30. char spi(char data)
  31. {
  32. //Start transmision
  33. SPDR = data;
  34. //Wait for transmision complete
  35. while(!(SPSR & 0x80));
  36. return SPDR;
  37. }
  38.  
  39. //Sets the waveform generator output to given phase
  40. void SetWGPhase(unsigned int phase)
  41. {
  42. SPCR = 0x5A;
  43. WG_CS = 0;
  44. while(WG_CS_PIN);
  45. spi(0x20);
  46. spi(0x00);
  47. spi((char)((phase>>8)|0xC0)); //Load into phase register 0
  48. spi((char)(phase & 0x00FF));
  49. WG_CS = 1;
  50. }
  51.  
  52. unsigned int ReadAd(void)
  53. {
  54. unsigned int data;
  55. ChipSelectAd(1);
  56. //Read data
  57. CheckStatus(); //Wait for data ready in
  58. adc register
  59. spi(0x58); //Place readinstruction
  60. in communication register
  61. data = (spi(0xFF)<<8); //Read 8 most significant
  62. bits from data register
  63. data |= spi(0xFF); //Read 8 leastsignificant
  64. bits from data register
  65. return data;
  66.  
  67. ChipSelectAd(0);
  68. }
  69.  
  70. void CheckStatus(void)
  71. {
  72. char adcStatus;
  73.  
  74. do
  75. {
  76. (void) spi(0x40);
  77. adcStatus = spi(0xFF);
  78. } while((adcStatus & 0x80) > 0);
  79. }
  80.  
  81. void ChipSelectAd(char s)
  82. {
  83. if(s == 1){
  84. PORTB.3 = 0; //Switch on AD
  85. while(PINB.3); //Wait for chip select pin
  86. }
  87. else
  88. PORTB.3 = 1; //Switch of AD
  89. }
Add Comment
Please, Sign In to add comment