Go Down

Topic: How to make the serial read more than one value? (Read 864 times) previous topic - next topic

zoomkat

The below code is for servos, but it shows a simple way to send two values together from the serial monitor, split the values, and convert the vaues into numbers for use with the servos.

Code: [Select]
// zoomkat 10-20-11 serial servo (2) test
// for writeMicroseconds, use a value like 1500
// for IDE 0022 and later
// Powering a servo from the arduino usually DOES NOT WORK.
// two servo setup with two servo commands
// send eight character string like 15001500 or 14501550

#include <Servo.h>
String readString, servo1, servo2;
Servo myservo1;  // create servo object to control a servo
Servo myservo2;

void setup() {
 Serial.begin(9600);
 myservo1.attach(6);  //the pin for the servo control
 myservo2.attach(7);
 Serial.println("servo-test-22"); // so I can keep track of what is loaded
}

void loop() {

 while (Serial.available()) {
   delay(1);  
   if (Serial.available() >0) {
     char c = Serial.read();  //gets one byte from serial buffer
     readString += c; //makes the string readString
   }
 }

 if (readString.length() >0) {
     Serial.println(readString); //see what was received
     
     // expect a string like 07002100 containing the two servo positions      
     servo1 = readString.substring(0, 4); //get the first four characters
     servo2 = readString.substring(4, 8); //get the next four characters
     
     Serial.println(servo1);  //print to serial monitor to see results
     Serial.println(servo2);
     
     int n1; //declare as number  
     int n2;
     
     int n1 = servo1.toInt();
     int n2 = servo2.toInt();
     
     myservo1.writeMicroseconds(n1); //set servo position
     myservo2.writeMicroseconds(n2);
   readString="";
 }
}

Consider the daffodil. And while you're doing that, I'll be over here, looking through your stuff.   8)

sushyoshi

Thanks all for the help.

zoomkat: Straight to the point! I like it! Your example is very much appreciated, and serves me right  ;)

AWOL

Just be aware that zoomkat's example may not work reliably if you change the serial line speed.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Go Up