634Views1Replies

Author Options:

how to run dc motor using keypad? Answered

this is my code, i can't read the keypad input and turn it into pwm value ranging 0-255


#include <Keypad.h>

const byte numRows= 4; //number of rows on the keypad
const byte numCols= 3; //number of columns on the keypad

//keymap defines the key pressed according to the row and columns just as appears on the keypad
char keymap[numRows][numCols]=
{
{'1', '2', '3'},
{'4', '5', '6'},
{'7', '8', '9'},
{'*', '0', '#'}
};

//Code that shows the the keypad connections to the arduino terminals
byte rowPins[numRows] = {8,7,6,5}; //Rows 0 to 3
byte colPins[numCols]= {4,3,2}; //Columns 0 to 3

//initializes an instance of the Keypad class
Keypad myKeypad= Keypad(makeKeymap(keymap), rowPins, colPins, numRows, numCols);
char Data[5];
int motorpin = 9;
int speed=0;
int currentCommand = 0;
int keyIn;
long NewData=0;
void setup()
{
Serial.begin(9600);
}

void loop()
{
char keypressed = myKeypad.getKey();
if (keypressed != NO_KEY)
{
  Data[currentCommand++]=keypressed;
  NewData= constrain (speed,0,255);
  keyIn = atoi(Data);
}
else {
  Serial.println(keyIn);
  analogWrite(motorpin,keyIn);
  while(currentCommand !=0) {
    Data[currentCommand--]=0;
  }
}
}

//With this code, once we press a key on the keypad, it should show up on the serial monitor of the arduino software once the code is compiled and uploaded to the arduino board.

Comments

The forums are retiring in 2021 and are now closed for new topics and comments.
0
Nighter3D
Nighter3D

4 years ago

Ok a bit scarce in data here. Let's see. it is obviously a arduino code. It is using a Keypad library. Seems ok. So it should be in the loop.

Ah i see the problem. The loop is completely messed up. Right now it will constantly check for a keypress and if there if you haven't pressed a key it will empty the string before looping back (it doesn't wait till you press a key). Right now this code will keep resetting the string and printing 0 as often as it possibly can!

What you will want is for the code to only do the println and such when a specific condition is met. Like having pressed "#".