rjadkins
rjadkins

Reputation: 35

How to null-terminate the keypad input?

i need to use 4x3 keypad to move a bldc motor using servo library. i manage to put the keypad input in a string, but i could not null terminate it. The idea of the code is, i enter a servo value in between 0-180 to move the servo from the keypad. Then the input value is then relayed to the bldc. somehow, how do i terminate the string ??

#include "Keypad.h"
#include <LiquidCrystal.h>
#include <Servo.h>

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0,A1,A2,A3,A4,A5);
Servo myservo;

const byte ROWS = 4; //four rows
const byte COLS = 3; //four columns
char keys[ROWS][COLS] =
 {{'1','2','3'},
  {'4','5','6'},
  {'7','8','9'},
  {'*','0','#'}
  };
byte rowPins[ROWS] = {9,8,7,6}; //connect to the row pinouts of the keypad
byte colPins[COLS] = {5,4,3}; //connect to the column pinouts of the keypad
int count=0;

Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );

void setup()
{
  Serial.begin(9600);
    Serial.print("enter:");
    myservo.attach(11);
}


void loop()

{
  char key = keypad.getKey();
  char value[4];
    int i=0;
    if  (key >= '0' && key <= '9')
  {
     value[i]=key;
     i++;
     value[i]= 0 ;
     if ( i = 3)
     {
      value[i] = true;
     }
  }

  if ( key = '#')
   {
    value[i]= true;
    Serial.print(value);
   }

  if (value[i] = true)
  {
    int pos = value[4].toInt;
    myservo.write( value);
  }


}

Upvotes: 1

Views: 434

Answers (2)

Patrick Trentin
Patrick Trentin

Reputation: 7342

In your source code you first null-terminate your char[] array with value[i] = 0, but then when # is pressed you overwrite that position with value[i]= true; right before printing it, and obviously causes problems.

This is a quick-and-dirty fix:

...

void loop()
{
    static char buffer[4];
    static byte i = 0;

    char key = keypad.getKey();

    // i < 3: prevent buffer overflow
    if  ('0' <= key && key <= '9' && i < 3)
    {
        buffer[i] = key;
        ++i;
    } else if (key == '#' && i > 0) {
        buffer[i] = '\0';              // null-terminate buffer

        Serial.println(buffer);    // debug print ?

        int value = atoi(buffer);
        myservo.write(value);

        i = 0;
    }
}

Please notice that in this source code example # is required to terminate a sequence of digits, and every digit in a sequence after the third one is ignored. This does not exactly reassemble your original behaviour, but I think that consistency of interaction is to be preferred.

Upvotes: 1

MSalters
MSalters

Reputation: 180145

You often don't need to terminate a string. If you know the length, that's usually enough. So keys is a 4x3 array, and you don't need to terminate any of these 4 strings.

You store one character in value[4]. You then do null-terminate it, always at value[1].

Your real problem is that = is assignment and == is comparison.

Upvotes: 1

Related Questions