我的朋友和我在Arduino板上连接/编码数字温度计,我正在编写代码。我们已经让温度计工作得很好,基本的临时数据会传到我们用于输出的4位7段LED屏幕上。我正在尝试编写代码以显示负(零下)温度,并且无法获得正确的输出。它不输出负号,而是输出8.
这是loop()方法:
void loop(void) {
int temp = getTemp();
boolean neg = false;
if (temp < 0) {
// Since the temperature is negative, multiplying it by -2 and adding it
// to itself gives us the absolute value of the number
temp += (temp * (-2));
// We set the neg boolean to true, indicating that we're dealing with a negative number
neg = true;
}
displayNumber(temp, neg);
}
这是(截断的)displayNumber()方法:
void displayNumber(int toDisplay, boolean negative) {
int num = toDisplay;
// The digits are 1-4, left to right
for(int digit = 4; digit > 0 ; digit--) {
//Turn on a digit for a short amount of time
switch(digit) {
case 1:
// The leftmost digit only needs to be on for temps 100.0 or above,
// or to display the negative sign for temps -10.0 or below
if (num >= 1000 || (num >= 100 && negative == true)) {
digitalWrite(digit1, HIGH);
}
if (num >= 100 && negative == true) {
lightNumber(11);
}
break;
case 2:
// Only needs to be on for temps 10.0 degrees or above, or
// for single-digit subzero temps.
if (num >= 100 || negative == true) {
digitalWrite(digit2, HIGH);
}
if (num < 100 && negative == true) {
lightNumber(11);
}
break;
case 3:
digitalWrite(digit3, HIGH);
break;
case 4:
digitalWrite(digit4, HIGH);
break;
}
//Turn on the right segments for this digit
lightNumber(toDisplay % 10);
toDisplay /= 10;
//Turn off all segments
lightNumber(10);
//Turn off all digits
digitalWrite(digit1, LOW);
digitalWrite(digit2, LOW);
digitalWrite(digit3, LOW);
digitalWrite(digit4, LOW);
}
}
...而lightNumber()方法的代码正确地为数字0-9打开或关闭段,其中10表示所有段关闭,11表示仅为中心段,表示负号。它使用带有整数参数的switch语句作为开关。 问题是,当我发送displayNumber()一个负值,而不是在数字前面的负号时,我会在负号应该显示的位置显示八个。 有什么想法吗?
答案 0 :(得分:0)
我认为,如果发表言论,你就过度思考了。在您的版本中,当数字为负数时,都会执行if语句。 Tyr:
case 1:
// The leftmost digit only needs to be on for temps 100.0 or above,
// or to display the negative sign for temps -10.0 or below
if (num >= 1000 ){
digitalWrite(digit1, HIGH);
}
if (num >= 100 && negative == true) {
lightNumber(11);
}
break;