Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Define variables
- ************************************/
- // Sensor threshold to tell us if ball is moving
- // (usually does not break 10, but let's make it 15 to be safe)
- int sensorThreshold = 4;
- // Analog inputs
- int analogOne = 1;
- // LEDs
- int ledPin1 = 9;
- // Readings from the sensor
- int sensorValue1 = 0;
- int prevSensorValue1 = sensorThreshold;
- // Brightness of the LED
- int brightness = 0;
- // Was the ball hit?
- //boolean wasHit1 = false;
- int wasHit1 = 0;
- // We need to save 5 readings so we can check
- // if there are at least 5 zeros in a row
- int readings[5];
- int total = 0;
- int average = 0;
- int numReadings = 0;
- int totalReadings = 5;
- int index = 0;
- void setup() {
- // start serial port at 9600 bps:
- Serial.begin(9600);
- pinMode(ledPin1, OUTPUT);
- // Set up our readings array
- for (int i=0; i< totalReadings; i++) {
- readings[i] = 0;
- }
- }
- void loop() {
- // Read analog input:
- sensorValue1 = analogRead(analogOne);
- Serial.print("Sensor 1: ");
- Serial.print(sensorValue1, DEC);
- Serial.print("\n\r");
- // If the sensor value is greater than our threshold
- // and the ball was not previously hit, light up the LED
- if (sensorValue1 >= sensorThreshold && wasHit1 == 0) {
- wasHit1 = 1;
- // Fade the LED
- for(int fadeValue = 255; fadeValue >= 0; fadeValue -=5) {
- // sets the value (range from 0 to 255):
- analogWrite(ledPin1, fadeValue);
- // wait for 30 milliseconds to see the dimming effect
- delay(30);
- }
- }
- else if (sensorValue1 >= sensorThreshold && wasHit1 == 1) {
- // Do nothing
- }
- else if (sensorValue1 < sensorThreshold) {
- // Do nothing
- }
- if (wasHit1 == 1) {
- //analogWrite(ledPin1, 0);
- // Let's grab the sensor readings and average them
- if (numReadings < totalReadings) {
- readings[index] = sensorValue1;
- for (int i=0; i<numReadings; i++) {
- total += readings[i];
- }
- numReadings += 1;
- index += 1;
- }
- else if (numReadings == totalReadings) {
- average = total/numReadings;
- if (average < 1) {
- wasHit1 = 0;
- }
- average = 0;
- numReadings = 0;
- total = 0;
- }
- }
- Serial.print("Was the ball hit: ");
- Serial.print(wasHit1);
- Serial.print("\n\r");
- Serial.print("Total: ");
- Serial.print(total);
- Serial.print("\n\r");
- delay(100);
- }
Add Comment
Please, Sign In to add comment