getting string into an array

07 Dec 2010

Another  newbiw  question here.

 

I am getting a string in through the serial port.  I know its working, because I can getcchar and then putchar and it prints out on the terminal.

What I want to do is store the incoming  string in an array so I can then sscanf it,  and based on the result,  take some action (turning relays on and off,  LED's etc).  here is the snippet (ch and remcom are declared at the top of the file thus:  remcom[20], ch;

void serialstream(void) {

   
    int r=0;
   
    myled!=myled;
   
    while ((ch=getchar()) !='\n'){
    //pc.putc(remote.getc()); 
    remcom[r]= ch;//(remote.getc()); /* get the char and send  to the terminal */
    r++;}
    //pc.putc(remote.getc());

    //myled!=myled;
}

 

This is not working - what am I doing wrong?  Thanks

07 Dec 2010

Define "not working".

07 Dec 2010

 

I tried this to see if the data was  getting  into the array

int r=0, k=0;
   
    myled=!myled;
   
    while ((ch=getchar()) !='\n'){
    //pc.putc(remote.getc()); 
    remcom[r]= ch;//(remote.getc());
    r++;}
    //pc.putc(remote.getc());
    for (k<r; putc("%c",remcom[k]);k++);
    //myled!=myled;

 

but the compiler is  telling me I have string incapatibility errors and my 'for(k<r . . . ) expression 'has no effect'

 

 

07 Dec 2010

I think you need to read up on the for operator, or stick to the while. Try the following.

for (k = 0; k < r; k++)
{
  putc("%c(%02X)\n", remcom[k], remcom[k]);
}

(this will print out character itself followed by its hex code, one char per line).

07 Dec 2010

See MODSERIAL

Specifically, see the end of teh page that shows how to get a string deliniated by a char such as \n

07 Dec 2010

ok thanks - let  me try  this.  much appreciated.

07 Dec 2010

I'm still not there yet.

I just want to get  a string coming in on the serial port into an array so I can then work with it.

 

Any ideas?

07 Dec 2010

Hi Andrew,

How about something like this:

#include "mbed.h"

Serial remote(USBTX, USBRX);

int main() {
    char str[64];
    if(remote.scanf("%s", str) == 1) {
        printf("I got [%s]\n", str);
    } else {
        printf("Failed to read string\n");
    }
}

Simon

09 Dec 2010

 

Thanks Simon.  Its  working!