2013-01-05 130 views
3

我想用arduino使用溫度傳感器來構建一個小程序。Arduino溫度傳感器

我以爲我知道如何去做,但我得到了一些奇怪的輸出。

這裏是我的代碼:

int sensorPin = 0; 
void setup() 
{ 
    Serial.begin(9600); 
} 
void loop() 
{ 
    int reading = analogRead(sensorPin); 
    float voltage = reading * 5.0/1024; 
    float temperatureC = (voltage - 0.5) * 100; 
    Serial.print(temperatureC); Serial.print(" degrees C, "); 
    Serial.print(voltage); Serial.println(" volts"); 
    delay(1000); 
} 

此代碼給我的輸出:

-26.56 degrees C, 0.23 volts 
-26.56 degrees C, 0.23 volts 
-27.05 degrees C, 0.23 volts 
-26.56 degrees C, 0.23 volts 
-26.07 degrees C, 0.24 volts 
-26.07 degrees C, 0.24 volts 

爲什麼度-?爲什麼我可以將其更改爲我想要的任何引腳,並且它仍然會給我一個類似的輸出?

+0

示例'漂浮temperatureC =(電壓 - 0.5)* 100;'如果您的電壓爲0.23五:'(0.23-0.5)* 100C =〜-26C' –

+0

請編輯以表明您正在使用的Arduino電路板版本。同時指出溫度傳感器型號。 – jdr5ca

+0

你從哪裏得到'(電壓-0.5)* 100'公式? – ZnArK

回答

3

模擬輸入0不引腳0

應該使用所定義的符號:
A0,A1,...,A7
爲模擬輸入。

嘗試

int sensorPin = A0; 

和你的程序應該工作。

如果你是好奇的實際值,你的Arduino IDE下的文件中安裝的外觀
.. \五金\ Arduino的\變種\標準\ pins_arduino.h

2

您正確閱讀此輸入。 爲了讓您不會得到負面的學位,您必須以不同的方式處理它。

有了這個:

float temperatureC = (voltage - 0.5) * 100; 

的任何值< 0.5結果由100

負數乘以嘗試打破下來使用可交換的財產。

  • (voltage - 0.5) * 100(voltage * 100) - (0.5 * 100)相同。
  • 這可以進一步簡化爲(voltage * 100) - 50

仍然,對於所有值,其中voltage < 0.5的溫度將是負值。

  • 我會建議由-1乘以temperatureC,使之積極,而不是把傳感器附近的任何東西,是`〜> = 50攝氏度。

此外,由於jdr5ca指出here,你不會得到真正從傳感器還沒有任何數據... :(

你可能得到噪聲(或垃圾)無論從任何pin0是。

編輯

它是用括號使運算順序更清晰的最佳實踐。

  • 即:
    • float voltage = reading * 5.0/1024;
    • 應該是
    • float voltage = reading * (5.0/1024);
0

首先,你必須使用定義的符號A0

int sensorPin = A0; 

in the next 

float voltage = reading * (5.0/1024); 

有一個在File/Examples/Basic/AnalogReadSerial