簡體   English   中英

在 Arduino 中顯示負數

[英]Displaying negative numbers in Arduino

我和我的朋友正在 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() 發送一個負值而不是數字前面的負號時,我在負號應該顯示的位置顯示了一個八。 任何想法為什么?

我認為你想多了你的if語句。 在您的版本中,兩個if語句都在數字為負數時執行。 試試這個:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM