0

I am playing with port registers directly to improve speed on a Arduino micro. I have no problem writing them, like

PORTF &= B11101111

However, when I try to read and print it, things get funny and I hope to know why.

Observation 0:

byte dat = PORTF;
Serial.print(dat,BIN);

produces a single 0, where I am expecting 8 0's as for a byte. And, even when I check that a digitalRead correctly gets a 1 from PF5 or A2,

Observation 1:

byte dat = PORTF;
Serial.print(dat,BIN);
Serial.print(dat,BIN);

produces a compiler error like

...cores\arduino\Print.cpp: In function 'println.constprop':
...cores\arduino\Print.cpp:143:1: internal compiler error: Segmentation fault
}
^
  • To reproduce your compiler problem, please post a minimized sketch showing the error. And tell us which PC system (Win, Linux, Mac) you're using. edit your question, don't put additional information in a comment, please! – the busybee Dec 6 '19 at 8:13
  • the compiler error is the error of the compiler. use Arduino boards package 1.6.21. this is not the right way to work with registers. and PORTF &= B11101111 is PORTF = PORTF & B11101111. so if PORTF is all zeros, the result is zero – Juraj Dec 6 '19 at 9:35
  • The compiler error is a compiler bug. What version of the IDE are you using? If it's not the latest, you may want to upgrade. – Edgar Bonet Dec 6 '19 at 10:56
  • @EdgarBonet, it is a problem of avr-gcc used in Arduino AVR core 1.6.22 and 1.6.23. the version in AVR core 1.8.0 and 1.8.1 has the problem of 'over-optimizing'. (1.8.0 was next after 1.6.23. 1.7.x was skipped). – Juraj Dec 6 '19 at 12:05
0

The function Serial.print() and it's siblings cuts all leading zeros. So 0b00001111 get's displayed as 1111 and 0b00000000 as 0. So you actually get what you expect. It's just printing different.

Also, when reading PORTF, you actually read the output state of the pins, as you have set it before. If you want to read the real input level of the pins, you should read PINF instead.

Though I don't know, where that segmentation fault came from.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.