Page 196 - 15 Dangerously Mad Projects for the Evil Genius
P. 196

Chapter 13    ■  Levitation Machine     173



          LISTING 13-1

           // Project 13 - Anti-gravity
           // 15 Dangerous Projects for the Evil Genius


           #define coilPin 11
           #define irPin 13
           #define sensorPin 0


           int A = 2;
           // Adjust B to improve stability
           int B = 60;
           int C = 20;
           int D = 1000;

           int maxPower = 255;
           long powerCountThreshold = 300000;
           int objectPresent = 0;
           int monitoring = false;

           void setup()
           {
              pinMode(coilPin, OUTPUT);
              pinMode(irPin, OUTPUT);
              pinMode(sensorPin, INPUT);
              Serial.begin(9600);
              Serial.println("Ready");
              Serial.println("m - toggle monitoring");
              Serial.println("B - increase B");
              Serial.println("b - decrease B");
           }

           void loop()
           {
              static int count = 0;
              static int oldPosition = 0;
              static int ambient = 0;
              static long powerCount = 0;
              count ++;

              if (count == 1000)
              {
                ambient = readAmbient();
                count = 0;
                objectPresent = (powerCount < powerCountThreshold);
                powerCount = 0;
              }
              int raw = 1024 - analogRead(sensorPin);
              // position from top (0) of sensor region to the bottom (650)
              int position = raw - ambient;
              // positive value means going downwards, negative going upwards
              int velocity = position - oldPosition;
              int power = position / A + velocity * B + C;


                                                                                        (continued on next page)
   191   192   193   194   195   196   197   198   199   200   201