arduino / ArduinoCore-megaavr

Arduino Core for the ATMEGA4809 CPU
103 stars 62 forks source link

SPI default configuration fails #106

Open JojoS62 opened 3 years ago

JojoS62 commented 3 years ago

The SPI configuration is using a SPISettings class from ArduinoCore-API, which is converted to a temporary object of type SPISettingsMegaAVR . This conversion in https://github.com/arduino/ArduinoCore-megaavr/blob/5717c2a3ac8ecc6e5f382715b7f6225e1c809007/libraries/SPI/src/SPI.h#L179-L181 is using this constructor: https://github.com/arduino/ArduinoCore-megaavr/blob/5717c2a3ac8ecc6e5f382715b7f6225e1c809007/libraries/SPI/src/SPI.h#L69 There the SPISettingsMegaAVR object is created on the stack, and then destroyed. It does not initialize the SPISettingsMegaAVR that is used in the config() call. This problem is hidden because it works by sudden and is compiler version dependant. There is a discussion and some test code to reproduce the problem in https://forum.arduino.cc/t/houston-spi-has-a-problem-with-avr-gcc-11-1-0 The assumption that this is a compiler problem was false, its simply an uninitialized SPISettingsMegaAVR object.

A solution would be to use constructor delegation as explained here: https://www.geeksforgeeks.org/constructor-delegation-c/

mikrocoder commented 3 years ago

Hi,

Thanks Jojo for the description of the problem. This causes the SPI registers to be overwritten with random numbers in the begin() method. Likewise in the beginTransaction(...) method.

In April 2020 the API was changed. What was the reason for this? That it is better understood. port to ArduinoAPI