|
|
|
|
C
|
98 lines
|
81 sloc
|
1.875 kB
  1. #include <stdio.h> 
  2. #include <wiringPi.h> 
  3.  
  4. // allocate pins 
  5. #define CLK 11 
  6. #define MOSI 10 
  7. #define MISO 9 
  8. #define CS 8 
  9.  
  10. int * take_twf(channel, samples, samplerate) 
  11. {	 
  12. 	double sampletime = (1 / samplerate); 
  13. 	 
  14. 	// create the twf array 
  15. 	static int twf[samples]; 
  16. 	 
  17. 	// set pin modes 
  18. 	pinMode(CLK, OUTPUT); 
  19. 	pinMode(MOSI, OUTPUT); 
  20. 	pinMode(MISO, INPUT); 
  21. 	pinMode(CS, OUTPUT); 
  22. 	 
  23. 	// set up send byte 
  24. 	int send; 
  25. 	send = channel; 
  26. 	send |= 0b00010000; 
  27. 	send <<= 3; 
  28. 	 
  29. 	// start SPI transfer 
  30. 	double nextcall = micros();	 
  31. 	int i = 0; 
  32. 	while(i < samples) 
  33. 	{	 
  34. 		if( micros() > nextcall) 
  35. 		{	 
  36. 			// increase next call and the i counter 
  37. 			nextcall += sampletime; 
  38. 			i++; 
  39. 						 
  40. 			// create the recieve variable / set it back to 0 
  41. 			int recieve = 0; 
  42. 			 
  43. 			// flip chip select to select ADC 
  44. 			digitalWrite(CS, HIGH); 
  45. 			digitalWrite(CS, LOW); 
  46. 			 
  47. 			// begin sending the bits to ADC 
  48. 			int a; 
  49. 			for(a = 0; a < 5; a++) 
  50. 			{ 
  51. 				// flip clock for next bit 
  52. 				digitalWrite(CLK, HIGH); 
  53. 				digitalWrite(CLK, LOW); 
  54. 				 
  55. 				// send bit 
  56. 				if((send & 0b10000000) == 0b10000000) 
  57. 				{ 
  58. 					digitalWrite(MOSI, HIGH); 
  59. 				} 
  60. 				else 
  61. 				{ 
  62. 					digitalWrite(MOSI, LOW); 
  63. 				} 
  64. 				 
  65. 				// select the next bit in send byte 
  66. 				send <<= send;  
  67. 			} 
  68. 			 
  69. 			// begin recieving data from the ADC 
  70. 			int b; 
  71. 			for(b = 0; b < 14; b++) 
  72. 			{ 
  73. 				// flip clock for next bit 
  74. 				digitalWrite(CLK, HIGH); 
  75. 				digitalWrite(CLK, LOW); 
  76. 				 
  77. 				// record the bit if high 
  78. 				if(digitalRead(MISO)) 
  79. 				{ 
  80. 					recieve |= 0b1; 
  81. 				} 
  82. 				// select the next bit for the recieve 
  83. 				recieve <<= 1; 
  84. 			} 
  85. 			// shift the last null bit out of recieve 
  86. 			recieve >>= 1; 
  87. 			 
  88. 			// store the recieved value in the twf array 
  89. 			twf[i] = recieve; 
  90. 			 
  91. 			// deselect the ADC 
  92. 			digitalWrite(CS, HIGH); 
  93. 		}	 
  94. 	} 
  95.  
  96. 	 
  97. 	return twf;	 
  98. }