2014-01-18 79 views
0

我試圖用電位器在電位器超過0時使電動機旋轉一個方向,而當電位器超過另一個方向時使另一個電位器旋轉。該代碼正在處理SensorValue < 512端,但不在> 507端。用電位器控制電機

const int analogInPin = A1; // Analog input pin that the potentiometer is attached to 
const int analogOutPin = 9; // 
const int analogOutPin_2 = 11; // 
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() { 

    sensorValue = analogRead(analogInPin);    

    if (sensorValue < 507) {  

    analogWrite(analogOutPin, LOW); 
    outputValue = map(sensorValue, 0, 512, 0, 255); 

    analogWrite(analogOutPin_2, outputValue);  
    } 
    if (512 > sensorValue) {  

    analogWrite(analogOutPin_2, LOW); 
    outputValue = map(sensorValue, 512, 1023, 0, 255); 

analogWrite(analogOutPin, outputValue);  
    } 
    else { 


} 

    delay(2);      

} 
+0

其他什麼正確的地圖值,我認爲這是正確的,也許我的芯片被打破 – Rufus

回答

0

爲了解決這樣的問題。我推薦幾個戰略打印和一個for循環來模擬數據範圍,揭示了一些調整,下面的代碼工作不是找出更好

const int analogInPin = A1; // Analog input pin that the potentiometer is attached to 
const int analogOutPin = 9; // 
const int analogOutPin_2 = 11; // 
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); 
    delay(1000); 
    Serial.println("Begin1"); 
} 

void loop() { 
// sensorValue = analogRead(analogInPin);    
    for (sensorValue = 0; sensorValue < 1024; sensorValue++) { 
    Serial.print("sensorValue = "); 
    Serial.print(sensorValue); 

    if (sensorValue < 507) {  
     outputValue = map(sensorValue, 0, 512, 255, 0); 
     Serial.print(" Forward : "); 
     Serial.print(outputValue); 
     analogWrite(analogOutPin, LOW); 
     analogWrite(analogOutPin_2, outputValue);  
    } else if (512 < sensorValue) {  
     outputValue = map(sensorValue, 512, 1023, 0, 255); 
     Serial.print(" Reverse : "); 
     Serial.print(outputValue); 
     analogWrite(analogOutPin_2, LOW); 
     analogWrite(analogOutPin, outputValue);  
    } 
    Serial.println(); 

    } 
    while(1); 
    delay(1000);      
}