-2

I need to send some number sequences to a microcontroller. Here is my function:

void DriveForward()
{       
      printf("137 0 0 128 0");          
}

The micro does not accept ASCII while my function sends as ASCII. I need to send that ASCII string as uint8. Any idea how can I do the conversion?

In this case, printf does not print on screen but it directly sends to serial port. And its the only command that sends to serial port, so I need to do some conversion beforehand.

Dumbo
  • 13,555
  • 54
  • 184
  • 288
  • ASCII is a text encoding. `uint8` is not. It's a data type. You will have to tell us what text encoding the controller expects. – Nikos C. Dec 17 '12 at 00:31
  • Have you looked at atoi()? http://www.cplusplus.com/reference/cstdlib/atoi/ – HeavenAgain Dec 17 '12 at 00:31
  • Do you mean that instead of the characters "137", you want to pass a character (byte) with a value of 137? If so, you can't use `printf()` because it will stop at the first character with a value of zero. – Jonathan Wood Dec 17 '12 at 00:34
  • You cannot embed zeros into a string, and expect it to be printed through `printf`. You need to go character-by-character. – Sergey Kalinichenko Dec 17 '12 at 00:34

2 Answers2

4

I may be confused by your question, but you can try something like (just for this case to test):

  printf("%c%c%c%c%c", 137, 0, 0, 128, 0);

This will send four characters encoded in ASCII with the numerical values you put afterwards.

Also, most technical documentation that tells you that you should use uint8 is refering that you send to the cable a full 8-bit value (speaking of characters here or ASCII then does not apply. They're just values of 8 bits that can be represented using an unit8).

How this is usually done is by using some low-level functions such as write, that can send an buffer of uint8, so, if you have to send that values, you can have a buffer like this:

uint8 send_buffer[] = {137, 0, 0, 128, 0};

and then:

write (send_buffer, 5, output_file_or_serial_conn);
Diego Sevilla
  • 28,636
  • 4
  • 59
  • 87
0

If you can't change your function, try receiving with scanf, it's the inverse of printf, so if your code looks something like this:

printf("%i %i %i", value1, value2, value3);

Then receive it with something like this:

char value1, value2, value3;
sscanf(received_string, "%i %i %i", &value1, &value2, &value3);

edit: 2 years later, I revisit this answer, I'm not so sure scanf is the inverse of printf. I'm not deleting this answer for historical reasons.

NiñoScript
  • 4,523
  • 2
  • 27
  • 33