1
votes

I'm trying to speed up my Arduino code by direct writing to registers. I wrote a short test script, but it doesn't seem to do much. If I use the 'digitalWrite()' function I can see an output on the oscilloscope, but using this code it just stays 0. I used this link as a reference. I can't quite grasp what I missed.

byte *outputRegister;
byte bitMask;

void setup() {
  pinMode(8,OUTPUT);
  outputRegister = portOutputRegister(8);
  bitMask = digitalPinToBitMask(8);
}

void loop() {
  *outputRegister |= bitMask;
  delay(1);
  *outputRegister &= ~bitMask;
  delay(1);
}

EDIT: The portOutRegister should return the port where the output pins are set. The digitalPinToBitmask function returns a bitmask (something like 0b00000001 for the first pin on the respective port). With some further testing, I concluded that the digitalWrite function doesn't seem to actually change the values in these registers, which does nothing more than confuse me.

1
delay(1)? try delay(1000) - Juraj
Hard to say without see portOutputRegister and digitalPinToBitMask code - Duloren
compare the result of portOutRegister to your expected value: Arduino Pin 8 on an atmega328 (uno/nano) is PORTB - datafiddler

1 Answers

0
votes

Arduino, if its Model = Uno, then it is ATmega-328 AVR, the best way to solve critical timing issues and achieve better execution times and code optimizations you should program via direct register modifications. That being said, use AVR-GCC, include and then do bit twiddling. Your code is not readable and hard to understand. IMO you should either write in C++ inside Arduino IDE >> slower but easier option, or start programming outside IDE inC and directly the AVR, >> orders of magnitude performance increase. Get to know the AVR Freaks Forum.