# Count number of 1 in a binary data trame through the serial port DB9

• 01-28-2009
minhdung_hoang
Count number of 1 in a binary data trame through the serial port DB9
Hi guys,
i have a question. can we count the number of 1 in the data trame continuous incoming from the RxD pin of the serial port DB9 (it a binary signal 0 and 1)?
thank you very much
• 01-28-2009
tabstop
Always assuming you have some method of accessing the serial port. Do you have some method of accessing the serial port?
• 01-28-2009
matsp
Normal asynchronous serial ports (RS232 compatible for example) give you 8 bits of data at a time, in a packet of 10 bits of start + 8 data + stop bits. If you receive a 8-bit data packet, you can of course count the number of ones in it:
Code:

```int count = 0; unsigned char data = DataFromSerialPort(); for(i = 0; i < 8;i++) {   count += data & 1;   data >>= 1; }```
(There are ways to do a table that holds for example 16 values, with the corresponding number of 1s of each 4-bit half of an 8 bit number, which speeds up the process a bit. But it's a lot more to write].

--
Mats
• 01-28-2009
itCbitC
If on UNIX, open the device file that corresponds to the serial port, read data from it and bitwise AND it with the binary equivalent of the RxD pin set.
• 01-28-2009
matsp
Quote:

Originally Posted by itCbitC
If on UNIX, open the device file that corresponds to the serial port, read data from it and bitwise AND it with the binary equivalent of the RxD pin set.

Huh?
Reading the device-file will give you, a byte at a time, from the serial port's RxD pin - since that's the pin that receives the data from the other end. There is no need for any AND operation in this place. Of course, to count the number of 1s, we'd have to use the AND operator (at least, if we use the method from above).

--
Mats
• 01-28-2009
itCbitC
Quote:

Originally Posted by matsp
Huh?
Reading the device-file will give you, a byte at a time, from the serial port's RxD pin - since that's the pin that receives the data from the other end.

Need not be a single byte but a number of them depending on the characters available in the serial input buffers though the read() can be constrained to get one character at a time.
Quote:

Originally Posted by matsp
There is no need for any AND operation in this place. Of course, to count the number of 1s, we'd have to use the AND operator (at least, if we use the method from above).

--
Mats

What did you think I was implying, if not the obvious??