Advertisement
Guest User

Untitled

a guest
Jun 3rd, 2013
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //global variables
  2.  
  3. //Analog pin 1 for reading in the analog voltage from the MaxSonar device.
  4. //This variable is a constant because the pin will not change throughout execution of this code.
  5. const int anPin = 1;
  6.  
  7. //variables needed to store values
  8. long anVolt, inches;
  9. int sum=0;//Create sum variable so it can be averaged
  10. int avgrange=10;//Quantity of values to average (sample size)
  11. int waitTime=1000;//time before calibration starts in miliseconds.
  12. int maxDistanceInInch;
  13. boolean isShooting=false;
  14.  
  15. //MaxSonar Analog reads are known to be very sensitive. See the Arduino forum for more information.
  16.   //A simple fix is to average out a sample of n readings to get a more consistant reading.\\
  17.   //Even with averaging I still find it to be less accurate than the pw method.\\
  18.  
  19. void setup() {
  20.   //This opens up a serial connection to shoot the results back to the PC console
  21.   Serial.begin(9600);
  22.  
  23.   delay(waitTime);
  24.  
  25.   pinMode(anPin, INPUT);
  26.  
  27.   //measure 10 times to calibrate
  28.   for(int i = 0; i < 10 ; i++)
  29.   {
  30.     //Used to read in the analog voltage output that is being sent by the MaxSonar device.
  31.     //Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in
  32.     //Arduino analog pin goes from 0 to 1024, so the value has to be divided by 2 to get the actual inches
  33.     anVolt = analogRead(anPin)/2;
  34.     sum += anVolt;
  35.     delay(10);
  36.   }  
  37.   maxDistanceInInch = sum/10;
  38.  
  39. }
  40. void loop() {
  41.  
  42.  
  43. for(int i = 0; i < avgrange ; i++)
  44.   {
  45.     //Used to read in the analog voltage output that is being sent by the MaxSonar device.
  46.     //Scale factor is (Vcc/512) per inch. A 5V supply yields ~9.8mV/in
  47.     //Arduino analog pin goes from 0 to 1024, so the value has to be divided by 2 to get the actual inches
  48.     anVolt = analogRead(anPin)/2;
  49.     sum += anVolt;
  50.     delay(10);
  51.   }  
  52.  
  53.   inches = sum/avgrange;
  54.  
  55.   if(inches <= maxDistanceInInch&& !isShooting)//if someone comes close and we aren't shooting already
  56.   {
  57.     startShooting();
  58.   }
  59.   else if(inches>maxDistanceInInch && isShooting)//if no one is close but we are shooting
  60.   {
  61.     stopShooting();
  62.   }
  63.  
  64.   delay(500);
  65. }
  66.  
  67. void startShooting()
  68. {
  69.   isShooting=true;
  70. //TODO: Code to start shooting
  71. }
  72.  
  73. void stopShooting()
  74. {
  75. //todo:Code to stop shooting
  76.  
  77. isShooting=false;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement