How to combine numbers into one

Hello, I'm trying to make a circuit that involves a bluetooth module and connecting a servo so I can control a servo from my phone with an app I created. everything works fine except for 1 thing. my app sends numbers over bluetooth to the arduino but the way it does it is by sending 1 character at a time for example if it needs to send 152 it will send 1 then 5 then 2 instead of 152. since im using degrees that goes from 0 all the way to 170, it can be single, double or tripple digit, so I cant just combine it three times because if its a single digit it will try waiting for 2 more digits. any ideas on how to fix this?

heres my code :

#include <Servo.h>
char Deg = 0;
Servo myservo;
void setup() {
  Serial.begin(9600);
  myservo.attach(9);
}
void loop() {
  while(Serial.available()==0){
  }
  while(Serial.available()>0){
  Deg = Serial.read();
  Serial.print(Deg);
  delay(2);
  }
  myservo.write(Deg);
  Serial.println("   ");
}

Does the sketch you posted work at all? It looks like you are reacting to every single character, and that character's ASCII code is being put in the servo.

You may want to look at Serial.parseInt, it will wait and gather characters and return you a number which may be just right for this circumstance.

HTH

a7

yes I tried using parseInt, but decided not to use it because it has a long delay from when I tell the servo to do something.

No doubt you tinkered with Serial.setTimeout() in your efforts to make you system more responsive.

a7

wow, works perfectly now, thanks!

Yay!

Why not post your code so we can all see what you did?

a7

to fix my issues all I did was add 1 line of code :
Serial.setTimeout(25);
for anyone else that has the issue you might need to fidle around with the timing of the timeout so you would need to change 25 to a number that supports you

original code:

#include <Servo.h>
int Deg = 0;
Servo myservo;
void setup() {
  Serial.begin(9600);
  myservo.attach(9);
}

void loop() {
  while(Serial.available()==0){

  }
  while(Serial.available()>0){
  Deg = Serial.parseInt();
  Serial.print(Deg);
  delay(2);
  }
  myservo.write(Deg);
  Serial.println("   ");
}

code after fix:

#include <Servo.h>
int Deg = 0;
Servo myservo;
void setup() {
  Serial.begin(9600);
  myservo.attach(9);
  Serial.setTimeout(25);
}

void loop() {
  while(Serial.available()==0){

  }
  while(Serial.available()>0){
  Deg = Serial.parseInt();
  Serial.print(Deg);
  delay(2);
  }
  myservo.write(Deg);
  Serial.println("   ");
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.