Continue to Site

Welcome to our site!

Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

  • Welcome to our site! Electro Tech is an online community (with over 170,000 members) who enjoy talking about and building electronic circuits, projects and gadgets. To participate you need to register. Registration is free. Click here to register now.

Detect number of 1's in 8-bit register

Status
Not open for further replies.

abr_pr90

New Member
Hello

The problem is this:

A pic18f4520 receives serially 8 bits, how to set a flag if the number of 1's in the register is even , and if not , clear the flag.


If you know how to do this with assembly language , the better.

Maybe it can be done with xorf , but no idea.
 
Set the page register to point at the page of RAM that controls the UART.
There is a bit test instruction. Test the LSB of the UARD data.
Then use the bit set/bit clear instruction to set/clear a bit in memory, if you need to.
 
Ron I think the OP wants to know if the number of 1's in the register is even or odd. Your are thinking about the even or oddness of the number.

The only way to do that is with a loop. Should not be too hard to do in ASM.
Code:
// assume value is the 8 bit number you want to check.
char bit, count;
bit=0;
count=0;
for(bit=0;bit<8;bit++)
{
   if (value&0x01)
      count++;
   value>>1;  
 }
}
at this point you can check the low order bit of count for oddness as Ron suggested.
 
Hi,

Another way that requires just 7 operations (on 8 bits) is to XOR all the bits.
x=A xor B
x=x xor C
x=x xor D
x=x xor E
x=x xor F
x=x xor G
x=x xor H
Result is in x, done.
Of course you have to have access to all the bits to use this method.
 
To do it in asm is fairly easy,
Code:
	movwf	temp
	rrf	temp,f
	xorwf	temp,w
	rrf	temp,f
	xorwf	temp,w
	rrf	temp,f
	xorwf	temp,w
	rrf	temp,f
	xorwf	temp,w
	rrf	temp,f
	xorwf	temp,w
	rrf	temp,f
	xorwf	temp,w
	rrf	temp,f
	xorwf	temp,w
The parity is now bit zero of W.

Edit, Start with byte to test in W.

Mike.
 
Last edited:
One thing, if you're doing this with a software UART (I'm assuming you're calculating parity from a serial transmission) then you can just test each bit as it arrives. If one = increment a counter register, else do nothing. Then after, you check the LSB of that counter register, which will indicate the number of 1's you've recieved in that byte.

Can also be done for checking certain bits in a stream, such as hamming encoding/decoding on the fly. Works out rather quick - but of course its only for 'software' bit banging comms.
 
Last edited:
Status
Not open for further replies.

New Articles From Microcontroller Tips

Back
Top