Author Topic: Back to Basics: How to write to entire register  (Read 3507 times)

emcniece

  • Newbie
  • *
  • Posts: 23
  • Seriously guys... I have too many hobbies. <3 DS
Back to Basics: How to write to entire register
« on: March 23, 2013, 05:32:05 pm »
This is a two-part question. I'm working on some bit-banging tests and have noticed that the code examples seem to toggle pins one at a time:
Code: [Select]
digitalWrite(0, HIGH);Is there a faster way of writing to the entire register, say 0b10110 which would send pins 5, 3 and 2 high?


Part 2: I'm running a basic shift register on P0-P5 right now and it works except for P2 which also pulls P0 high with it. Code is literally 6 iterations of the following:
Code: [Select]
  digitalWrite(0, HIGH);
  digitalWrite(1, LOW);
  digitalWrite(2, LOW);
  digitalWrite(3, LOW);
  digitalWrite(4, LOW);
  digitalWrite(5, LOW);
 
  delay(1000); 


Is there any reason that P2 and P0 go high at the same time?

Bluebie

  • Sr. Member
  • ****
  • Posts: 486
Re: Back to Basics: How to write to entire register
« Reply #1 on: March 23, 2013, 05:50:31 pm »
Yes!


Code: [Select]
PORTB = 0b10110;


If you want to toggle a pin, you can also do it like this:


Code: [Select]
PINB = 0b10110;


And the output values of 2, 3, and 5 will all invert from whatever they were before. Both of these are extremely fast - I believe they each use only a single insutrction and all the pins change in sync.


Just be aware that setting PORTB causes every pin to be set, not just the ones you're interested in. This might mess up other libraries if you're doing USB or something. The inverting thing though only inverts the pins at the 1-bits, so the zeros don't change anything and so it can be safer if you already know what your output pin values are at the beginning.

emcniece

  • Newbie
  • *
  • Posts: 23
  • Seriously guys... I have too many hobbies. <3 DS
Re: Back to Basics: How to write to entire register
« Reply #2 on: March 23, 2013, 06:04:55 pm »
SO GOOD. Thanks man! That PINB is pretty slick, saves a bit of effort with bitmasking  ;D

Bluebie

  • Sr. Member
  • ****
  • Posts: 486
Re: Back to Basics: How to write to entire register
« Reply #3 on: March 23, 2013, 06:12:10 pm »
Oh no I really mean it with that 'might mess up other libraries' stuff. If you try and read in PORTB, mask it off, or some stuff in, and then write it back, an interrupt could have fired right in the middle of that mess of instructions and then you'd still be overwriting stuff in PORTB unintentionally! You'd need to disable interrupts around it as well, but the USB libraries are very timing sensitive so that might cause crashes if you aren't quick enough.

dougal

  • Sr. Member
  • ****
  • Posts: 289
Re: Back to Basics: How to write to entire register
« Reply #4 on: March 23, 2013, 10:08:16 pm »
I have got to start keeping a notebook of all these useful snippets of info...