0

I want to write "11111111" through serial port connection in C, however, the write() from will read each of the 1 as a character and send a binary representation of 1, which is "0011 0001", how can I solve this problem. And I am using the code from here to open and write through serial port How to open, read, and write from serial port in C?

char *data = "11111111"; char c = strtol(data, 0, 2);

write(port,c,8);

doesn't work. It can be compiled, but there is no signal sent, confirmed by the oscilloscope.

  • Since `c` is a single byte, it should be `write(port, &c, 1)`. The call `write(port, c, 8)` should crash the program. – user3386109 Jun 24 '19 at 18:12

1 Answers1

0

You are writing a string of 8 '1' characters.

Since your data is 8 bits and a char is 8 bits long, you can store it in a single char.

char data = 0xFF;
write(port,&data,1);

Should do the trick.

Im using hexadecimal as 0xFF equals 11111111 in binary. Also note that you should pass a pointer to your data to write function. if you are using an array of data, then you can pass the array itself as arrays and pointers are basically the same thing in C.

if you have more data, just save them numerically on an array of chars, and set the number of bytes (the 1 in the code above) accordingly.

Solid State
  • 114
  • 5
  • Thank you! You are right and just a reminder, we should not put single quote around the hex value, char data = '0xff' WILL NOT work !!! – user11672711 Jun 30 '19 at 21:22