Serial input.. noob in a jam

hello to everyone,

I am a new member and am having difficulty getting my head around converting serial.read and its single byte, into a meaningful int for servo.write, 180 read from the terminal program and then 180 written to the servo for eg.

#include <Servo.h>

Servo myservo;
int pos;
char buffer[2];
int rec;

void setup()
{
  Serial.begin(9600);
  myservo.attach(9, 220, 2200);
  rec = 0;
  buffer[rec] = '\0';
}

void loop()
{
  if (Serial.available()) 
  {
    buffer[rec++] = Serial.read();
    buffer[rec++] = '\0';
    if (rec >= (sizeof(buffer)-1))
    {
      pos = atoi(buffer);
      rec = rec+1;
    }
    if (pos <= 180)
    {
      
      myservo.write(pos);
      Serial.print(pos);
      pos = 0;
      
    }
  }
}

At the moment if I enter 44 for example, it works once, any number I enter after that it keeps outputting 44. If I enter something like 180 it comes out as 111?!

will definitely have to pick up some more knowledge about the language, but what am I doing wrong in this code?

I am sure this question has been asked before, I just don’t have the programming background to implement the examples into my code

Thanks,

Ryan

rec = rec+1

try

rec = 0;

And lose the "pos = 0;" after the servo write.

And "buffer" should be at least 4 bytes long (three digits plus terminator).

But, I have to say, yours is the best first attempt I've seen here in a while - thanks for persevering! Wel done. :)

It probably wasn't much of a perseverance on my part, I cobbled together from examples, and help on irc :)

I tried your suggestion, I still seem to be getting strange output, and seems to be repeating the output like before. Seems to be something wrong with my program structure

Can you post what you've currently got?

#include <Servo.h>

Servo myservo;
int pos;
char buffer[4];
int rec;

void setup()
{
  Serial.begin(9600);
  myservo.attach(9, 220, 2200);
  rec = 0;
  buffer[rec] = '\0';
}

void loop()
{
  if (Serial.available()) 
  {
    buffer[rec++] = Serial.read();
    buffer[rec++] = '\0';
    if (rec >= (sizeof(buffer)-1))
    {
      pos = atoi(buffer);
      rec = 0;
    }
    if (pos <= 180)
    {
      
      myservo.write(pos);
      Serial.print(pos);
      
    }
  }
}

Getting pretty much the same results as before. For example if I enter 11, i get 01 returned, I enter 22 I get 12. Then I enter 33 and get 23 and so forth, so it seems to truncate the second character and return it on the next loop cycle

Part of your problem is that your program always expects to receive a full buffer before converting the ASCII to decimal, here:

if (rec >= (sizeof(buffer)-1))

If you don't enter three digits, you won't perform the conversion.

If you sent some terminator character (like "return") after the number when you entered it, your program could detect this, and not have to wait to fill the buffer before the "atoi".