 //
 int joystick_get()
 {
+    static int last_button = JOYSTICK_NONE;
+    int button;
+
+    // Read pin A0.
     int input = analogRead(0);
 
-    if (input > 882) return JOYSTICK_NONE;
-    if (input > 624) return JOYSTICK_UP;
-    if (input > 424) return JOYSTICK_RIGHT;
-    if (input > 242) return JOYSTICK_DOWN;
-    if (input > 73)  return JOYSTICK_SELECT;
-
-    return JOYSTICK_LEFT;
+    // Convert analog value into button.
+    if      (input > 882)  button = JOYSTICK_NONE;
+    else if (input > 624)  button = JOYSTICK_UP;
+    else if (input > 424)  button = JOYSTICK_RIGHT;
+    else if (input > 242)  button = JOYSTICK_DOWN;
+    else if (input > 73)   button = JOYSTICK_SELECT;
+    else                   button = JOYSTICK_LEFT;
+
+    // Wait until state is stable.
+    if (button != last_button) {
+        last_button = button;
+        return JOYSTICK_NONE;
+    }
+    return button;
 }
 
 void setup()
 {
-    lcd.LCD_init();
-    lcd.LCD_clear();
+    lcd.begin();
+    lcd.setContrast(50);
+    lcd.clearDisplay();
+    lcd.display();
 }
 
 void loop()

/*
 * LCD screen.
 */
#define MAXROW      48
#define MAXCOL      84

static unsigned char screen[MAXROW*MAXCOL/8];

/*
 * Output piece coordinates given its center and angle

    h *= 4;
    w *= 4;
    if (visible) {
        fill_rect(LCDWIDTH-1 - h, w, LCDWIDTH-1 - (h + 3), w + 3, 1);
    } else {
        fill_rect(LCDWIDTH-1 - h, w, LCDWIDTH-1 - (h + 3), w + 3, 0);

        if (h == (PITDEPTH-1)*5)
            lcd.drawPixel(LCDWIDTH-1 - (h + 3), w + 2, 1);

        if (w == 0)
            lcd.drawPixel(LCDWIDTH-1 - (h + 2), w, 1);
        else if (w % 16 == 12)
            lcd.drawPixel(LCDWIDTH-1 - (h + 2), w + 3, 1);
    }
}

