2012-06-24 537 views
1

我和朋友正在为Arduino板上的数字温度计接线/编码,并且正在编写代码。我们的温度计工作得很好,基本的温度数据输入到我们用于输出的4位7段LED屏幕。我试图编写代码来显示负温度(零度以下),并且无法正确输出。代替输出负的符号,它输出一个8在Arduino中显示负数

这里的环()方法:

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

'lightNumber','digitalWrite'在哪里?我想可能需要看更多的代码来回答。 – Tim

+0

不要这样做:'temp + =(temp *(-2));'!这是混乱和低效率2。那么'temp = temp *(-1);'? – JimmyB

回答

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;