Go Down

Topic: Servo motor code with flex resistor - bad programming, need help finding source (Read 631 times) previous topic - next topic

brendanhogan

Hello all,

I'm using two flex resistors to control two servo motors. Somewhere in the code (pasted below) I have an error. The code compiles correctly, but when I flash it to an Uno R3, the servo attached to pin 10 flies fully counterclockwise and gets stuck in that position. I'm using Parallax standard servos. If I alter the code and swap pin 9 for pin 10, the erroneous servo behavior is copied to the other motor and the previously problematic motor behaves correctly. I have not doubt it is something really obvious that I am just missing after an all night work session. The code is as follows:

Code

#include <Servo.h>

Servo servoLeft, servoRight;

int flexpin = A0;
int flexpin1 = A1;


void setup()
{
  servoLeft.attach(9);
  servoRight.attach(10);
  Serial.begin(9600);
 
}


void loop()
{
 
  int flexposition;
  int servoposition;
  int flexposition1;
  int servoposition1;
 
  flexposition = analogRead(flexpin);
  flexposition1 = analogRead(flexpin1);
 
  servoposition = map(flexposition, 760, 905, 0, 180);
  servoposition = constrain(servoposition, 0, 180);
  servoposition1 = map(flexposition1, 760, 905, 0, 180);
  servoposition1 = constrain(flexposition1, 0, 180);
 
  servoLeft.write(servoposition);
  servoRight.write(servoposition1);
 
  Serial.print("sensor1: ");
  Serial.print(flexposition);
  Serial.print(" servo1: ");
  Serial.println(servoposition);
  Serial.print("sensor2: ");
  Serial.print(flexposition1);
  Serial.print(" servo2: ");
  Serial.println(servoposition1);
 
  delay(100);
}

/code

Thanks very much.

wildbill

Code: [Select]

  servoposition = map(flexposition, 760, 905, 0, 180);
  servoposition = constrain(servoposition, 0, 180);
  servoposition1 = map(flexposition1, 760, 905, 0, 180);
  servoposition1 = constrain(flexposition1, 0, 180);


Your second constrain is using flexposition1 where it should be using Servoposition1

brendanhogan

oh for goodness sake. I knew it must have been something painfully obvious like that. Thank you, wildbill.

Go Up