Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- ReadAnalogVoltage
- Reads an analog input on pin 0, converts it to voltage, and prints the result to the serial monitor.
- Attach the center pin of a potentiometer to pin A0, and the outside pins to +5V and ground.
- This example code is in the public domain.
- */
- const int buttonPin = 2;
- int buttonState = 0;
- int ammo_count = 100;
- unsigned long startTime = -1;
- // the setup routine runs once when you press reset:
- void setup() {
- // initialize serial communication at 9600 bits per second:
- Serial.begin(9600);
- Serial.println(ammo_count);
- ammo_count --;
- pinMode(buttonPin, INPUT);
- }
- // the loop routine runs over and over again forever:
- void loop() {
- checkIfSelectorSwitchPressed();
- float a0Voltage;
- boolean bbDetectedA0 = false;
- while(!bbDetectedA0) {
- a0Voltage = getSensorVoltage(A0);
- bbDetectedA0 = bbDetected(a0Voltage);
- }
- startTime = micros();
- Serial.println(ammo_count);
- ammo_count--;
- float a1Voltage;
- boolean bbDetectedA1 = false;
- while(!bbDetectedA1 && (micros() - startTime) < 250000) {
- a1Voltage = getSensorVoltage(A1);
- bbDetectedA1 = bbDetected(a1Voltage);
- }
- if(bbDetectedA1){
- unsigned long duration = micros() - startTime;
- Serial.print("bb traveling: ");
- float seconds = duration / 1000000.0;
- float inchesPerSecond = 2 / seconds;
- Serial.println(inchesPerSecond / 12);
- startTime = -1;
- } else {
- Serial.print("Did not detect BB at A1 sensor!");
- }
- }
- void checkIfSelectorSwitchPressed() {
- int curButtonState = digitalRead(buttonPin);
- if(curButtonState == 1 && curButtonState != buttonState){
- Serial.println("toggled");
- buttonState = curButtonState;
- } else if(curButtonState == 0){
- buttonState = 0;
- }
- }
- float getSensorVoltage(int pin) {
- int sensorValue = analogRead(pin);
- // Convert the analog reading (which goes from 0 - 1023) to a voltage (0 - 5V):
- return sensorValue * (5.0 / 1023.0);
- }
- boolean bbDetected(float sensorVoltage) {
- if(sensorVoltage >= 2.25){
- return true;
- }
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement