1

I am working a serial stepper motor controller and programming it in C. The problem I have run into is that the controller returns values in binary representations and I am not sure how to display. Obviously converting it to int is not an option as I need the exact binary representation that the controller sends.

The output is of the form: MSB -> LSB (Most Significant Bit to Least Significant Bit).

At the moment I am trying something like:

char buff[] = "@01 STAT\r";
char readbuff[10];
fd = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NDELAY);
n = write (fd,buff, len);
......

n = read(fd, readbuff, 3);
printf("STAT returns %c\n", readbuff);
......

This returns nonsensical data ie weird shapes and symbols. I have set output to raw and am using 0 parity. I have skipped the initialization parameters but can add them if it helps.

If anyone is curious I am using an Ocean Control KTA-190 Serial Stepper Motor.

dsolimano
  • 8,870
  • 3
  • 48
  • 63
Talha
  • 11
  • 1

1 Answers1

3

You're printing out the values as %c, i.e. ASCII characters, hence the "weird shapes and symbols".

If you change %c to %d or %x then you will get the decimal or hexadecimal representation of the value. You can then interpret that as binary as you wish (for example 0x0A would be 00001010).

You also need to make sure you get each character out of readbuff. You might want to loop through and print out %x for each array index, as in:

for (i = 0; i < 10; i++)
{
    printf("readbuff[%d]: 0x%x\n", i, readbuff[i]);
}

(Note, it is better to avoid magic numbers, so it would be nicer to do something like #define READBUFF_LEN 10 and then use READBUFF_LEN in place of 10 in the definition of readbuff and the loop termination condition.

If you really want the binary value printed out, i.e. it is not sufficient to print out hex or decimal, then you will need to do this conversion yourself using bit shifting. There's an example of how to do this in the answers here: Is there a printf converter to print in binary format?

Community
  • 1
  • 1
Vicky
  • 12,934
  • 4
  • 46
  • 54