Servo control using Keypad Arduino code & circuit

In any type of servo position control methods like using a potentiometer, press switch, etc, the Arduino is actually writing each position values in degrees corresponding to the input change. In all that methods the exact servo positions are not given as input or the user is unable to write the servo position to exact degrees unless the values are entered via the serial monitor.

This is an easy method to move the servo position by giving the degrees of the servo motors as a numeric value. This method is useful for servo testing and accurate position control without a serial monitor.

Refer to the interface of a keypad with Arduino & Arduino servo connection tutorial.


#include <Keypad.h>
#include <Servo.h>
const byte ROWS = 4;
const byte COLS = 4;
char keys[ROWS][COLS] = {
  {'1', '2', '3', 'A'},
  {'4', '5', '6', 'B'},
  {'7', '8', '9', 'C'},
  {'*', '0', '#', 'D'}
byte rowPins[ROWS] = {2, 3, 4, 5};
byte colPins[COLS] = {6, 7, 8, 9};
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
Servo servomotor;
int i = 0, pos = 0;
void setup() {

void loop() {
  char key = keypad.getKey();
  if (key) {
    pos = (pos * 10) + (key - 48);
    if (i >= 3) {
      pos = 0; i = 0;

The sketch is written so as to read consecutive 3 input digits as a single position value in degrees. The servo moves as soon as when 3 button keys are pressed, each set of three keypresses considered as the next position value. That is to move the servo to 90° enter as 090, for 5° degrees 005, and for 165° as 165. This 3-digit entry is used because the degree values can be 1-digit, 2-digit or 3-digit value and the system cannot predetermine the length of the next value. In the code, if you press 2 key and leave the system without entering the 3rd digit, it will keep the previous 2 values until a 3rd input key is pressed and it writes the value only when all 3 inputs are received.

This 3-digit entry can be changed to one or two digits by adding an enter key option. So, if the enter key is pressed after one- or two-digit input then the system can confirm that this is a 1 digit or 2-digit number.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *