我正在编写一个关于逻辑门工作的简单程序(它是在 arduino 中编程的,输入是使用串行监视器获取的),我不太了解 parseint 的工作原理并阅读了我在网上阅读了许多文章,但我仍然不清楚。这是代码
boolean a,b;
int val;
void setup(){
Serial.begin(9600);
Serial.setTimeout(2000);
Serial.println("Enter what logic you want to implement: \nFor AND enter 1\n For NAND enter 2\n For OR enter 3\n For NOR enter 4\n For EX- OR enter 5\n For EX-NOR enter 6\n For NOT enter 7");
}
void loop(){
if(Serial.available()>0){
val= Serial.read();
if(val=='1')
{
//AND
Serial.println("SELECTED AND GATE:");
Serial.println("Enter your inputs:");
a=Serial.parseInt();
Serial.println(a);
b=Serial.parseInt();
Serial.println(b);
if(a && b){
Serial.print("OUTPUT:");
Serial.println("1");
}
else{
Serial.print("OUTPUT:");
Serial.println("0");
}
}
else if(val=='2'){
//NAND
Serial.println("SELECTED NAND GATE:");
Serial.println("Enter your inputs:");
a=Serial.parseInt();
Serial.println(a);
b=Serial.parseInt();
Serial.println(b);
if(a && b){
Serial.print("OUTPUT:");
Serial.println("0");
}
else{
Serial.print("OUTPUT:");
Serial.println("1");
}
}
else if(val=='3'){
//OR
Serial.println("SELECTED OR GATE:");
Serial.println("Enter your inputs:");
a=Serial.parseInt();
Serial.println(a);
b=Serial.parseInt();
Serial.println(b);
if(a || b){
Serial.print("OUTPUT:");
Serial.println("1");
}
else{
Serial.print("OUTPUT:");
Serial.println("0");
}
}
else if(val=='4'){
//NOR
Serial.println("SELECTED NOR GATE:");
Serial.println("Enter your inputs:");
a=Serial.parseInt();
Serial.println(a);
b=Serial.parseInt();
Serial.println(b);
if(a || b){
Serial.print("OUTPUT:");
Serial.println("0");
}
else{
Serial.print("OUTPUT:");
Serial.println("1");
}
}
else if(val=='5'){
// EX-OR
Serial.println("SELECTED EX-OR GATE:");
Serial.println("Enter your inputs:");
a=Serial.parseInt();
Serial.println(a);
b=Serial.parseInt();
Serial.println(b);
if(a == b){
Serial.print("OUTPUT:"); Serial.println("0");
}
else{
Serial.print("OUTPUT:"); Serial.println("1");
}
}
else if(val=='6'){
//EX-NOR
Serial.println("SELECTED EX-NOR GATE:");
Serial.println("Enter your inputs:");
a=Serial.parseInt();
Serial.println(a);
b=Serial.parseInt();
Serial.println(b);
if(a == b){
Serial.print("OUTPUT:");
Serial.println("1");
}
else{
Serial.print("OUTPUT:");
Serial.println("0");
}
}
else if(val=='7'){
//NOT
Serial.println("SELECTED NOT GATE:");
Serial.println("Enter your inputs:");
a=Serial.parseInt();
Serial.println(a);
if(a==1){
Serial.print("OUTPUT:"); Serial.println("0");
}
else{
Serial.print("OUTPUT:"); Serial.println("1");
}
}
else{
Serial.println("No gate is assigned to this number");
}
}
}
在 serial.available 之后 int 上面的代码我使用 serial.read 读取 val 但如果我使用 serial.parseint 它不起作用,类似地在每个门函数中我使用 parseint (我知道它返回字符串的整数表示),如果我把serial.read它不起作用。有人可以告诉我为什么会发生这种情况以及这两者的实际差异是什么。