用电位计控制电机

时间:2014-01-18 22:26:52

标签: arduino

我正在尝试使用我的arduino和电位计在电位计超过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);                     

}

1 个答案:

答案 0 :(得分: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);                     
}