Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //global variables
- //Analog pin 1 for reading in the analog voltage from the MaxSonar device.
- //This variable is a constant because the pin will not change throughout execution of this code.
- const int anPin = 1;
- //variables needed to store values
- long anVolt, inches;
- int sum=0;//Create sum variable so it can be averaged
- int avgrange=10;//Quantity of values to average (sample size)
- int waitTime=1000;//time before calibration starts in miliseconds.
- int maxDistanceInInch;
- boolean isShooting=false;
- //MaxSonar Analog reads are known to be very sensitive. See the Arduino forum for more information.
- //A simple fix is to average out a sample of n readings to get a more consistant reading.\\
- //Even with averaging I still find it to be less accurate than the pw method.\\
- void setup() {
- //This opens up a serial connection to shoot the results back to the PC console
- Serial.begin(9600);
- delay(waitTime);
- pinMode(anPin, INPUT);
- //measure 10 times to calibrate
- for(int i = 0; i < 10 ; i++)
- {
- //Used to read in the analog voltage output that is being sent by the MaxSonar device.
- //Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in
- //Arduino analog pin goes from 0 to 1024, so the value has to be divided by 2 to get the actual inches
- anVolt = analogRead(anPin)/2;
- sum += anVolt;
- delay(10);
- }
- maxDistanceInInch = sum/10;
- }
- void loop() {
- for(int i = 0; i < avgrange ; i++)
- {
- //Used to read in the analog voltage output that is being sent by the MaxSonar device.
- //Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in
- //Arduino analog pin goes from 0 to 1024, so the value has to be divided by 2 to get the actual inches
- anVolt = analogRead(anPin)/2;
- sum += anVolt;
- delay(10);
- }
- inches = sum/avgrange;
- if(inches <= maxDistanceInInch&& !isShooting)//if someone comes close and we aren't shooting already
- {
- startShooting();
- }
- else if(inches>maxDistanceInInch && isShooting)//if no one is close but we are shooting
- {
- stopShooting();
- }
- delay(500);
- }
- void startShooting()
- {
- isShooting=true;
- //TODO: Code to start shooting
- }
- void stopShooting()
- {
- //todo:Code to stop shooting
- isShooting=false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement