Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
12 years ago.
Storing data as an array
Hello, guys. I have a problem in programming. I use a software, called realterm, on PC to send 7 or 8 bytes hexdeciaml commands, like "FF 01 00 00 00 00 01". And I wanna store the command in an array so that I can use one byte among the command. For example, the command is "FF 01 01 00 00 00 02", stored as an array, commmand[7]. And command[0] = FF. Additionlly, what is the meaning of "pc.putc" and "pc.getc"?
Regards.
1 Answer
12 years ago.
getc
and putc
get and put single characters from and to a buffer. Some relevant pages of the handbook are SerialPC and Serial.
It looks to me like your code is mostly unreachable. You will be getting a compilation warning about that and another about the i==0
which does nothing. Also remember that arrays are zero indexed so you'll get an error when the for loop tries to store a value in command[7]
#include "mbed.h" Serial pc(USBTX, USBRX); int main() { pc.printf("The commands received are"); while(1) { if (pc.readable()) { pc.putc(pc.getc()); } } // This while loop never finishes, all following code is unreachable. int i, command[7]; for (i=0; i<=7; i++) { // The less-than-or-equal-to (<=) should be replaced with less-than (<) i == 0; // expression has no effect command[i] = pc.getc(); pc.putc(command[i]); } }
You may have better luck using gets
. This allows you to read a number of bytes into a buffer all at once.
#include "mbed.h" Serial pc(USBTX, USBRX); int main() { // Assuming commands are 7 bytes, 8th byte is for string termination char command[8]; pc.printf("The commands received are\n"); while(1) { if (pc.readable()) { pc.gets(command, 8); for (int i=0; i<8; i++) { pc.printf("%x ", command[i]); } pc.printf("\n"); } } }
Output (typing "abcdefg")
The commands recieved are 61 62 63 64 65 66 67 0
I hope that helps.
Thanks a lot for you help. But I have some questions in your program. First is why the 8th is 0? Can I store 8 numbers in command[i]? Why the output is 61 in hex when you input "a"?
Regards
posted by 28 Nov 2012The last number is a zero as that is the string termination byte. You can store whatever number of bytes you want as long as you allow one extra for the string termination. "a" is represented in ASCII by the number 97, 97 converted into hexadecimal is 61. If the printf statement had "%d" the output would have been "97 98 99 100 101 102 103 0".
posted by 28 Nov 2012
You can copy and paste code rather than bothering to make a screenshot. Just surround it with
posted by Stephen Paulger 28 Nov 2012<<code>>
tags, click "Editing tips" for an example.