1

I am making a code for a robot that will return to its original position when hit. To do so I am recording the amount of time that a key is pressed.

            switch (key) {
            case KeyEvent.VK_UP:
                // System.out.println("UP pressed");
                // state = "";
                pressCount += 1;
                xTimeStart = System.currentTimeMillis();
                myFinch.setWheelVelocities(255, 255);
                myFinch.setLED(0, 0, 255);
                // tempDistance = 1;
                break;
            }

That is for when the key is pressed, xTimeStart records the time at which the button is first pressed.

        switch (key) {
        case KeyEvent.VK_UP:
            // System.out.println("UP released");
            xTimeEnd = System.currentTimeMillis();
            System.out.println(xTimeEnd-xTimeStart);
            pressCount = 0;
            // tempDistance = 1;
            break;
       }

As you can see, I retrieve the time when the button is released and print out the difference between the two. Without dividing by 1000 or converting to seconds, the outcome is always around 24 (ranges from 23-25).

Help would be very much appreciated, thanks in advance :D.

  • Why not use a utility class like Guava's `Stopwatch`? For more precision you should base your code on [`nanoTime`](http://stackoverflow.com/q/351565/589259). – Maarten Bodewes Apr 19 '15 at 00:01
  • 1
    Even with Stopwatch/nanoTime the resolution is bound by the event listeners which is limited by the operating system's UI message pump. You can get a more precise value, but not a more accurate one.. – user2864740 Apr 19 '15 at 00:02
  • Two part of your code, the case value are both `KeyEvent.VK_UP` ? – youngzy Apr 19 '15 at 07:38
  • yes. one is for when the up button is pressed and the second is for when it is released – Thaejaesh Sooriyakumaran Apr 19 '15 at 11:38

0 Answers0