## Selecting a single bit in Xmega a3bu

3 posts / 0 new
Author
Message

How to select a single bit in a PORT in xmega a3bu and to set is as output or input or make it high or low using '.OUT' keyword.

For example:

#define row1out  0<PORTA.OUT
#define row1dir   0<<PORTA.DIR // code for 4x4 matrix keypad, row 1 is connected to PA0

Is this the right way to select a single bit and manipulate it later in the program like this?

row1out = 0;

Should'nt this make the bit 0 of the a PORTA low?

Currently confused in this.

Using C code.

Nitin Shenoy

Total votes: 0

I think you need to read this tutorial:

https://www.avrfreaks.net/forum/...

That explains all this stuff. The isolation of a bit is achieved using AND/OR

This is actually fundamental computer science and nothing specific to AVR. There is an argument to say that it's quicker/easier to learn the fundamentals of programming by doing it on a PC than using an AVR (or any other) micro!

For example if I go to:

https://www.onlinegdb.com/online...

and type in:

```#include <stdio.h>
#include <stdint.h>

uint8_t data = 0xD2;

int main()
{
int i;
for (i = 0; i < 8; i++) {
printf("%c\n", (data & (1 << i)) ? '1' : '0');
}

return 0;
}```

Then I get:

That has broken apart the original 0xD2 I started with into individual 1's and 0's.

It was far easier to test this in about a minute on that website than it was to fiddle about trying to do it on an AVR. The key to that code is:

`data & (1 << i)`

This is testing each bit of data individually.

If you follow the link to the tutorial you will see that the "(1 << n)" style of construct is used a lot when doing this.

EDIT and I just spotted that the bits came out "backwards" as my i was counting 0..7 when really I meant it to be 7..0. So I can change the for() loop to be:

`for (i = 7; i >= 0; i--) {`

Then I get:

Last Edited: Fri. Jan 11, 2019 - 10:17 AM
Total votes: 0

Thanks for this info!. I will surely go through it.

Nitin Shenoy