How to transfer the contents of a Port into a variable in xmega a3bu?

Go To Last Post
4 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

uint8_t keypresscode =(PORTA.IN | PORTB.IN);
 

This is the code I have written to copy the contents of port a and port b into keypresscode variable, is this the right way to do it? 

Nitin Shenoy

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

No, Not the way. What you wrote OR's the two together. For example, if PORTA.IN = 00000001 and PORTB.IN = 00001001, your keypress code would be 00001001 and you have lost all the information about which bits came from PORTA and which came from PORTB.

 

If you must do something like that, I would write

 

uint16_t keypresscode = (PORTA.IN<<8) + PORTB.IN;

This reads PORTA.IN, and shifts it left by 8 bits so that it occupies the high 8-bits of a 16-bit value. Then it adds PORTB.IN which then occupies the low 8-bits of the 16-bit value.

 

There are several other ways to do this basic task, which end up executing very similarly.

 

Jim

Jim Wagner Oregon Research Electronics, Consulting Div. Tangent, OR, USA http://www.orelectronics.net

Last Edited: Tue. Jan 8, 2019 - 05:44 AM
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

It kind of depends what you plan to do with the bits once you have read them. It could be that reading the separate ports into separate 8 bit variables might actually be more "manageable" in the long run so you need to ask yourself questions such as "is it really all 8 bits in each of the 2 ports so a full 16 bits in total?" or is it perhaps "a selection of bits from A and a selection of bits from B" ? And, like I say, having read it how will the value be further used/processed?

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Agree. Hence my statement (emphasis added):

 

If you must do something like that ...

There are a few cases where you might want to put the values of two ports into a single variable, though I've never had to do that. Won't two separate 8-bit variables do? Or, two 8-bit variables in a struct? Or an array? There are many ways to store this information and the "best" way really depends on how you wish to use this information.

 

Jim 

Jim Wagner Oregon Research Electronics, Consulting Div. Tangent, OR, USA http://www.orelectronics.net

Last Edited: Tue. Jan 8, 2019 - 06:56 PM