2012-01-26 2206 views
7

我只是在看一些示例代碼,遇到了一條線,我不完全明白爲什麼它需要完成。我明白你正在接受模擬值。顯然這個值在0到1024之間?爲什麼是這樣?爲什麼輸出需要在0到255之間映射?什麼決定了這裏使用的論點?有問題的行:Arduino map()方法 - 爲什麼?

// map it to the range of the analog out: 
     outputValue = map(sensorValue, 0, 1024, 0, 255); 

在代碼中突出顯示:

created 29 Dec. 2008 
Modified 4 Sep 2010 
by Tom Igoe 

This example code is in the public domain. 

*/ 

// These constants won't change. They're used to give names 
// to the pins used: 
const int analogInPin = A0; // Analog input pin that the potentiometer is attached to 
const int analogOutPin = 9; // Analog output pin that the LED is attached to 

int sensorValue = 0;  // value read from the pot 
int outputValue = 0;  // value output to the PWM (analog out) 

void setup() { 
    // initialize serial communications at 9600 bps: 
    Serial.begin(9600); 
} 

void loop() { 
    // read the analog in value: 
    sensorValue = analogRead(analogInPin);    
    **// map it to the range of the analog out: 
    outputValue = map(sensorValue, 0, 1024, 0, 255);** 
    // change the analog out value: 
    analogWrite(analogOutPin, outputValue);   

    // print the results to the serial monitor: 
    Serial.print("sensor = ");      
    Serial.print(sensorValue);  
    Serial.print("\t output = ");  
    Serial.println(outputValue); 

    // wait 10 milliseconds before the next loop 
    // for the analog-to-digital converter to settle 
    // after the last reading: 
    delay(10);      
} 

非常感謝您的答覆。

回答

11

模擬輸出僅具有可接受的範圍爲0之間和255

因此,該值必須被接受的範圍內映射。

文檔在地圖的方法是在這裏:http://arduino.cc/en/Reference/map

由於Arduino的具有0-1023的analogRead分辨率和只有一個0-255分辨率analogWrite,需要來自電位計這個原始數據進行縮放在使用它之前...

這解釋來自一個Arduino傳感器教程( '代碼' 標題下):http://arduino.cc/en/Tutorial/AnalogInOutSerial

+3

有人可能會爭辯說,除以4的整數除此之外也會起作用,但map()也可以正常工作。 – Mchl

+3

在抓握的手上,可以右移整數2. –

+0

如果輸出必須介於0-255之間,analogInput爲0-1024,爲什麼? –

1

爲什麼?有時,您需要將0到1023轉換爲0到1023以外的值範圍,map()函數試圖使您對工程師更容易。 I explain one situation in some detail on this forum post,我可以將0到90或100個數值爲0到1023的數組索引轉換爲x-y圖形圖!

idx範圍爲0〜100附近
test[idx]一些值是ADC值,因此範圍爲0〜1023

int x1= map(1, 0, idxmax, 0, 160); 
int y1= yf - 2 - map(test[1], TPS_floor[_tps], TPS_max[_tps], 0, dy); 
for(idx=0; idx < idxmax-1; ){ 
    int x0 = map(idx, 0, idxmax, 0, 160); 
    int y0 = yf - 2 - map(test[idx], TPS_floor[_tps], TPS_max[_tps], 0, dy); 
    tft.drawLine(x0, y0, x1, y1, YELLOW); 
    idx++; 
    x1 = map(idx+1, 0, idxmax, 0, 160); 
    y1 = yf - 2 - map(test[idx+1], TPS_floor[_tps], TPS_max[_tps], 0, dy); 
} 

所以上面的代碼轉換的0-〜100和x y的0-1023分成這樣: map() translated an array's index and its values into that plot!

我的版本的write up is here。 (並且截至2013年7月31日,正在進行中)

我個人認爲清楚地說明「爲什麼」是最好的解釋。我希望我的回答可以幫助任何人質疑這個「爲什麼」......爲什麼。

+0

非常有趣和翔實。仍然通過論壇帖子工作,但我發現這非常吸引人! –

+1

謝謝,西蒙!把'map()'看作某種縮放函數......?歡迎您在該論壇上提問等問題。 :) –