Electronic – How to V-USB screw up the built-in SPI of an ATmega328p

atmegaavrsdspiusb device

I'm working on a V-USB project that shows up as a Keyboard using an ATmega328p. The USB part is working great (it's not my first V-USB project), but after I start the V-USB stack with usbInit(), all calls to the SD card library fail. If I call the same functions before usbInit(), everything works perfectly.

I use an Arduino clone called Diavolino, but without the Arduino/wiring framework. I have the USB connected to digital I/O 2 and 3, and the SD card to 10-13 (built-in SPI lines).

I looked through the SD card library and found no sign of it using any interrupts or registers other than SPxx. I also grep'd though the V-USB code, but it doesn't even touch the SPxx registers.

The first sign of the problem was when the device disconnected when it was supposed to access the SD card. Then I put usbPoll() and wdt_reset() calls into all SD card handling loops, and found that in case of writing, the card waits forever for acknowledgement from the card after having sent the last two bytes (CRC-16).

The SD card library I use is sd_raw by Roland Riegel.

Best Answer

I had a problem like that with USART and resolved it by changing the watch dog settings. As you know V-USB uses a watch dog and if you put extra time in one operation, the watch dog gets activated. Try deactivating the watch dog and if you see everything goes well, you can change the watch dog time or you can split the interfering code (the SD card codes in your case) into smaller parts and "Resetting" the watch dog between them. But don't forget to re-activate your watch dog after debugging as it is not recommended to use V-USB without that.

Related Topic