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()一個負值,而不是數字前面的負號,我得到一個八負顯示的地方應該是。 任何想法爲什麼?
'lightNumber','digitalWrite'在哪裏?我想可能需要看更多的代碼來回答。 – Tim
不要這樣做:'temp + =(temp *(-2));'!這是混亂和低效率2。那麼'temp = temp *(-1);'? – JimmyB