Go Down

Topic: using flex sensors to control servos (Read 762 times) previous topic - next topic

Costello

i get what you mean. im just not sure how to write that in code. ill look into string writing though. thanks for your help

HazardsMind

No no, dont use strings, send it as an array, but set it up like a string. '<','1','5','0', ',(separating comma)' ,'1','8','0', ...'>'
Created Libraries:
TFT_Extension, OneWireKeypad, SerialServo, (UPD)WiiClassicController, VWID

Costello

something like this?

sending
Code: [Select]
int flexSensor[3] = {1,2,3};

int sentValues[3];

// Change these if your minimum value is greater than 0
int from[] = {420,420 ,420};

// Change these if you maximum value is less than 1023
int to[] = {480,480,480};

void setup()
{
   Serial.begin(9600);
}

void loop()
{
   for(int i=0; i<3; i++)
   {
     int val;
       // Read a sensor's value
       val = analogRead(flexSensor[i]);

       // Map it to the servo range using it's min/max range
       val = map(val, from[i], to[i], 0, 179);

       // If the new val is not the same as the last val sent
       if(val != sentValues[i])
      {
        Serial.print("<"); // Start of packet marker
        Serial.print(i);     // which servo to move
        Serial.print(":");  // delimiter
        Serial.print(val);  // servo position to move to
        Serial.print(">"); // End of packet marker

          // Record the value sent, so we don't send again unless there is a change
        sentValues[i] = val;
      }
   }
}


receiving
Code: [Select]
#include <Servo.h>

String readString, servo1, servo2, servo3;
Servo myservo1, myservo2, myservo3;  // create servo object to control a servo

void setup()
{
   Serial.begin(9600);

}

void loop()
{
   if(Serial.available() > 0)
   {
    char c = Serial.read();  //gets one byte from serial buffer
    readString +=c;
    if (c == ',') {
      if (readString.length() >1) {
        Serial.println(readString); //prints string to serial port out

        servo1 = readString.substring(0, 4);
        servo2 = readString.substring(4, 8);
       
        Serial.println(servo1);
        Serial.println(servo2);
        Serial.println(servo3);
          //convert readString into a number
       
        int n1 = servo1.toInt();
        int n2 = servo2.toInt();
        int n3 = servo3.toInt();
        // auto select appropriate value, copied from someone elses code
       
        myservo1.write(n1); 
        myservo2.write(n2);
        myservo3.write(n3);
       
       
        }
         readString=""; //clears variable for new input
      }


 
   }
}

HazardsMind

Close, but it better to check if the incoming char is NOT equal to ',' and store the variables, and if it is equal, to switch the array.
Created Libraries:
TFT_Extension, OneWireKeypad, SerialServo, (UPD)WiiClassicController, VWID

Go Up