Arduino Serial Control - Strings?

Hi guys,

I'm trying to make a robot with the Arduino that will be commanded trought the serial port of a router with DD Wrt. So, I've tried a little code I learned from the internet that is the following:

#define LED 13

int input = 0;      

void setup() {
  pinMode(LED,OUTPUT);    
  Serial.begin(9600);       
}

void loop () {
  input = Serial.read();     


  if (input == '1' ) {
    digitalWrite(LED,HIGH);
    Serial.println("LED13 is ON");
  } 
  if (input == '0'){
      digitalWrite(LED, LOW);
      Serial.println("LED13 is OFF");
  }
}

Simple. 0 for LED turned off, 1 for LED turned on. However, this has a little problem: since the router is always sending serial data trought it's serial port, the LED (and other components in the future) will always answering to orders that I don't want. So, I tought and I guess that I could use instead of "0" and "1" and other characters, use a string of them. Like, for LED on, "010101010" or simply "LEDON". So, I replaced the code with various alternatives, but I was not successfull.

Then I made a few reading and I found that the baud rate could be to high to the arduino from the router (they were the same, and at this moment I had a baudrate of 115200bps). I tought I've changed it on the router (I'm not even sure I can do that with this version of ddwrt) and on arduino to 9600bps. However, even with the Arduino connected only to the PC it wouldn't still not work!

A few moments of research later I found that I might need to use a string. But, according to what I've read this brings me two main problems: 1- The coding. I've seen a few examples of code with string and I just don't get it! 2- I've read that strings take a lot of memory from the Arduino, and I need a relatively fast processing time.

So, what I need to use are strings? If yes, can you teach me how to code them, please? Or should I use an alternative?

Thank you guys in advance, so much! This problem is really messing with me, I don't even know to where should I turn to!

Best regardings,

Tiago Ferreira.

strings take a lot of memory from the Arduino, and I need a relatively fast processing time

These are two independent issues. BTW: In most loop runs you'd find that there is no input available (input ==-1).

Sending multi character commands like "LEDON" will arrive as single characters, as long as you maintain your fast processing time. You already noticed this is more difficult to handle. You're more flexible though and there is no other option if you need to send values (numbers) to arduino. How to deal with Serial communcation is the most common topic here and hopefully soon you'll run into Nick Gammon's hints (http://www.gammon.com.au/forum/).

You have so many false assumptions in your post that it is hard to know where to begin.

However, this has a little problem: since the router is always sending serial data trought it's serial port, the LED (and other components in the future) will always answering to orders that I don't want.

Routers do not make up serial data to send. Something is causing the router to forward data. It is that device that you need to get control of, not the router.

Then I made a few reading and I found that the baud rate could be to high to the arduino from the router (they were the same, and at this moment I had a baudrate of 115200bps). I tought I've changed it on the router (I'm not even sure I can do that with this version of ddwrt) and on arduino to 9600bps.

Slowing down the baud rate is the wrong thing to do. The Arduino and router need to be at the same speed. Generally, higher is better.

A few moments of research later I found that I might need to use a string. But, according to what I've read this brings me two main problems: 1- The coding. I've seen a few examples of code with string and I just don't get it!

That's not the Arduino's problem, the router's problem, or the device that is sending data to the router's problem. That is your problem. String processing is easy if you pay attention to a few well discussed rules.

It is really unlikely to be a solution, though.

I've read that strings take a lot of memory from the Arduino, and I need a relatively fast processing time.

Poor String handling does. Good string handling does not. That bit about needing fast processing does not go with strings or lowering the baud rate. Make up your mind what you need to do.

I don't even know to where should I turn to!

Start with a full picture. What is sending data to the router?

http://www.gammon.com.au/forum/?id=11425 Tiago- Ve la se isto ajuda Transltd= See if this helps in any way !!

and have a look of how he done it through serial registers (though a different project). Not sure if it helps but just in case

Hi guys!

Ok, thanks for your help but until now I haven't found anything that works. A friend is helping me, however until now we have no results. So, I'll start with a geral picture:

This will be to control an entire robot. I'm only using this example of LED On/Off to simplify everything. Once I understand how to do this, It will be very easy to apply to everything else.

So, the computer will send commands to the router that will transmit them to the arduino, trought the serial port. I need to make the LED turn on with a command like "aaaa". It must be with "aaaa", not "abab" or "aaaba" or even just "a". Also, I need to turn it off with the command "bbbb".

Everything else received that it is not defined as an action will be ignored.

So, can someone teach how to do this or do this for me (I'm willing to pay for it, if necessary).

Best regardings,

Tiago Ferreira.

Im gonna guess ur problem might be the flow control...Does your ur router supports it with hardware ? Im not an expert in that side of things myself, but some more details would probably help. Connections wise. isnt using a computer instead to transmit the data an option ?! would solve most of your problems

So, the computer will send commands to the router that will transmit them to the arduino, through the serial port.

Does that work ? If yes, the rest is easy.
If not, you can work in parallel
A) using the Serial Monitor to send data to Arduino and log debugging messages, and
B) find out how that router communication is supposed to work.

All commands are exactly 4 characters long?
Yes: Wait until there are 4 characters available < Serial.available() >,
then read them into a char array and compare that to your known commands. < strcmp >
Read additional characters as well ( space, new line, … )
No: Read the characters, keep track of what you got, until the cmd is received completely.
It’s easier if this is recognized by a special character (usually a Linefeed, 0x0A)

But wont he need to control the flow somehow ?!? Most routers dont do it with the hardware; only through software...Am i right there ?!?

iyahdub:

I don’t know what you’ve asked me, to be honest. But my router supports communication. In this phase described in this post I’m still struggling with the computer part.

michael_x:

Yes, the communication is working. If the code is simpler and I use just “a” or “b” I can control the arduino remotelly. But I need to do it using “aaaa”, as described.
Can you teach how to do that? I’m trying, but I can’t figure it out!

Thank you!

Seems he done it, Tiago.

Well, as i said this is not my strong point, but dont you need a way of controlling the flow of data ?!? Like handshake, etc ?!? That is where you having problems.. am i right ?! I might be seeing it from a wrong perspective ?!?

tgferreira: michael_x:

Yes, the communication is working. If the code is simpler and I use just "a" or "b" I can control the arduino remotelly. But I need to do it using "aaaa", as described. Can you teach how to do that? I'm trying, but I can't figure it out!

This is the best example I know: http://gammon.com.au/serial (Sorry, my previous link was too unspecific, and rather leads into Australian MUD , where the D stands for dungeons)

You learn most by telling what does not work in your code. ( And it's nice that you reduce your problem to 2 commands and a LED, thank you )

BTW: there's a difference between "a" and 'a'.

@iyahdub: I don't think it's about flow control.

Ok guys, my friend has helped me and made this little code:

#include <stdio.h>

#define LED 13

void setup() {
  pinMode(LED, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() == 4) {
    char command[5];

    for (int i = 0; i < 4; i++) command[i] = Serial.read();
    command[4] = '\0';

    Serial.println(command);
    
    if (strcmp(command, "AAAA") == 0) {
      digitalWrite(LED, HIGH);
      Serial.println("LED13 is ON");
    } else if (strcmp(command, "BBBB") == 0) {
      digitalWrite(LED, LOW);
      Serial.println("LED13 is OFF");
    }
  } else {
    Serial.flush();
  }
}

Everything works, except for one little and very important thing:
If I send AAAA, it will print AAAA and do the action. However If I send AAAAA, it will make everything the same way and print only AAAA. But when I send BBBB (for example), it will print ABBB. In my words, It is “saving” a character. And this must not happen since the router will be sending “random” stuff trought serial that must be ignored and must not mess with the commands that I send.

Anyone knows how to solve this? Thanks!

That's because you didn't read in the last A, so it just sat in the buffer until the next command was sent.

Two possible solutions: Add a small delay at the end of your if block and then read and discard the rest of the buffer. For simple applications that aren't very time sensitive, where commands aren't set frequently, this would be the easy option.

Or you can send start and stop bytes. When you receive the start byte, you reset your buffer index to 0. Then, read until you receive a stop byte. This is useful if the length of the message is unknown. You can then just compare the first 4 characters. This would require you to read only one character per iteration of loop(), and is probably to more common method.

Add a small delay at the end of your if block and then read and discard the rest of the buffer.

No, no, no. Please do NOT do this.

First,

 if (Serial.available() == 4) {

is wrong. The == should be >=. Then, if there should be 5 or 8 characters in the buffer, they are not permanently stuck there.

Second, you MUST send start and end of packet markers, so that and are separate packets. Then, you can use code like this:

#define SOP '<'
#define EOP '>'

bool started = false;
bool ended = false;

char inData[80];
byte index;

void setup()
{
   Serial.begin(57600);
   // Other stuff...
}

void loop()
{
  // Read all serial data available, as fast as possible
  while(Serial.available() > 0)
  {
    char inChar = Serial.read();
    if(inChar == SOP)
    {
       index = 0;
       inData[index] = '\0';
       started = true;
       ended = false;
    }
    else if(inChar == EOP)
    {
       ended = true;
       break;
    }
    else
    {
      if(index < 79)
      {
        inData[index] = inChar;
        index++;
        inData[index] = '\0';
      }
    }
  }

  // We are here either because all pending serial
  // data has been read OR because an end of
  // packet marker arrived. Which is it?
  if(started && ended)
  {
    // The end of packet marker arrived. Process the packet

    // Reset for the next packet
    started = false;
    ended = false;
    index = 0;
    inData[index] = '\0';
  }
}

To read the whole packet, and nothing but the packet. Where it says “Parse the packet” is where if if(strcmp()) tests go.

PaulS:

Add a small delay at the end of your if block and then read and discard the rest of the buffer.

No, no, no. Please do NOT do this.

I know the hip thing to do here is oppose any usage of delay, and discarding data, more often than not, is not a good idea, but do you have any other reason for why this would work in simple applications?

but do you have any other reason for why this would work in simple applications?

Delay() is a bandaid that often masks an underlying problem. I'd really prefer to fix the underlying problem than mask it.

Dumping random amounts of unread data is also generally not a smart thing to do. Getting a real handle on the exchange of data is a better idea.

Just my opinion, of course, and no more right, or wrong, than yours.

See? that is why i thought had to do with the lack of handshake/flow control and cts/rts. You end up with things like this to sort and debug. But if you keep it simple should be easy in this case. That tutorial on Nick's site explains several ways of getting around that !! Though in this case is to do with reading the buffer properly, right ?!

Its actually good and im also learning a lot with this case, as i never needed to come down so detailed like this to send data, programming wise...So, deffo a good lesson for me !!!