我需要使用4x3键盘来移动使用伺服库的无刷直流电机。我设法将键盘输入放在一个字符串中,但我不能对其进行null终止。代码的想法是,我输入一个介于0-180之间的伺服值,以从键盘上移动伺服。然后,输入值被中继到bldc。不知何故,我该如何终止字符串??
#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);
}
}发布于 2017-02-28 16:08:34
您通常不需要终止字符串。如果你知道长度,这通常就足够了。所以keys是一个4x3数组,您不需要终止这4个字符串中的任何一个。
在value[4]中存储一个字符。然后,对它进行空终止,总是在value[1]。
你真正的问题是=是赋值,==是比较。
发布于 2017-02-28 18:16:32
在源代码中,您首先使用value[i] = 0空终止char[]数组,但是当按下#时,您会在打印之前用value[i]= true;覆盖该位置,这显然会导致问题。
这是一个快速修复的方法:
...
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;
}
}请注意,在这个源码示例中,需要#来终止一个数字序列,并且序列中第三个数字之后的每个数字都被忽略。这并不能准确地重组你的原始行为,但我认为交互的一致性是首选的。
https://stackoverflow.com/questions/42499339
复制相似问题