Guest User

Untitled

a guest
Apr 22nd, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. /* Define variables
  2. ************************************/
  3. // Sensor threshold to tell us if ball is moving
  4. // (usually does not break 10, but let's make it 15 to be safe)
  5. int sensorThreshold = 4;
  6.  
  7. // Analog inputs
  8. int analogOne = 1;
  9.  
  10. // LEDs
  11. int ledPin1 = 9;
  12.  
  13. // Readings from the sensor
  14. int sensorValue1 = 0;
  15. int prevSensorValue1 = sensorThreshold;
  16.  
  17. // Brightness of the LED
  18. int brightness = 0;
  19.  
  20. // Was the ball hit?
  21. //boolean wasHit1 = false;
  22. int wasHit1 = 0;
  23.  
  24. // We need to save 5 readings so we can check
  25. // if there are at least 5 zeros in a row
  26. int readings[5];
  27. int total = 0;
  28. int average = 0;
  29. int numReadings = 0;
  30. int totalReadings = 5;
  31. int index = 0;
  32.  
  33. void setup() {
  34. // start serial port at 9600 bps:
  35. Serial.begin(9600);
  36. pinMode(ledPin1, OUTPUT);
  37.  
  38. // Set up our readings array
  39. for (int i=0; i< totalReadings; i++) {
  40. readings[i] = 0;
  41. }
  42. }
  43.  
  44. void loop() {
  45.  
  46. // Read analog input:
  47. sensorValue1 = analogRead(analogOne);
  48. Serial.print("Sensor 1: ");
  49. Serial.print(sensorValue1, DEC);
  50. Serial.print("\n\r");
  51.  
  52. // If the sensor value is greater than our threshold
  53. // and the ball was not previously hit, light up the LED
  54. if (sensorValue1 >= sensorThreshold && wasHit1 == 0) {
  55. wasHit1 = 1;
  56.  
  57. // Fade the LED
  58. for(int fadeValue = 255; fadeValue >= 0; fadeValue -=5) {
  59. // sets the value (range from 0 to 255):
  60. analogWrite(ledPin1, fadeValue);
  61. // wait for 30 milliseconds to see the dimming effect
  62. delay(30);
  63. }
  64. }
  65. else if (sensorValue1 >= sensorThreshold && wasHit1 == 1) {
  66. // Do nothing
  67. }
  68. else if (sensorValue1 < sensorThreshold) {
  69. // Do nothing
  70. }
  71.  
  72. if (wasHit1 == 1) {
  73. //analogWrite(ledPin1, 0);
  74. // Let's grab the sensor readings and average them
  75. if (numReadings < totalReadings) {
  76. readings[index] = sensorValue1;
  77.  
  78. for (int i=0; i<numReadings; i++) {
  79. total += readings[i];
  80. }
  81.  
  82. numReadings += 1;
  83. index += 1;
  84.  
  85. }
  86. else if (numReadings == totalReadings) {
  87. average = total/numReadings;
  88. if (average < 1) {
  89. wasHit1 = 0;
  90. }
  91. average = 0;
  92. numReadings = 0;
  93. total = 0;
  94. }
  95.  
  96. }
  97.  
  98. Serial.print("Was the ball hit: ");
  99. Serial.print(wasHit1);
  100. Serial.print("\n\r");
  101. Serial.print("Total: ");
  102. Serial.print(total);
  103. Serial.print("\n\r");
  104.  
  105. delay(100);
  106. }
Add Comment
Please, Sign In to add comment