I'm using an Attiny84 with the Tiny Core. I'm try to use port manipulation to write the lower four bits of port A. I'm using i2c which occupies bits 5 and 7.
How can I write only to the lower 4 bits to avoid interfering with the i2c?
asked Mar 10, 2018 at 3:19
-
Have you tried doing it, and it has not worked?Nick Gammon– Nick Gammon ♦2018年03月10日 05:40:42 +00:00Commented Mar 10, 2018 at 5:40
1 Answer 1
I don't think you need to worry. A simple piece of code:
void setup()
{
PORTA |= bit (0);
}
void loop() { }
Generates:
00000044 <setup>:
44: d8 9a sbi 0x1b, 0 ; 27
46: 08 95 ret
In other words, the compiler generates code to set that bit, ignoring all the other bits.
answered Mar 10, 2018 at 5:42
-
Presumably PORTA |= bit (0000); would set the 4 least significant bits?Charlie Miller– Charlie Miller2018年03月10日 20:04:55 +00:00Commented Mar 10, 2018 at 20:04
-
Not at all. Zero is zero, no matter how many leading zeroes you put there. You could do this:
PORTA |= 0b00001111;
2018年03月10日 20:52:21 +00:00Commented Mar 10, 2018 at 20:52 -
The
bit
macro sets a bit by shifting the number1
left the number of bits in the argument, sobit (0)
is1 << 0
which is the same as1
.2018年03月10日 20:53:21 +00:00Commented Mar 10, 2018 at 20:53 -
OK, so I understand now that I can set the bits to 1 without touching the i2c pins. Is it the same, but I suppose with the OR operator to set back to 0?Charlie Miller– Charlie Miller2018年03月10日 21:25:55 +00:00Commented Mar 10, 2018 at 21:25
-
No, you use the AND operator.
PORTA &= ~0b00001111;
The~
operator takes the ones-complement, and you AND that into the port. Alternatively:PORTA &= 0b11110000;
2018年03月10日 22:00:38 +00:00Commented Mar 10, 2018 at 22:00