How to approach an complex Arduino Uno project (Serial, SPI, Ethernet) in pure C, without libraries?
I have a college assignment where I need to get serial output, the Ethernet shield and SPI communication with other boards to work. We are not allowed to use any existing libraries, though we can use them as strong inspiration, as long as we are able to explain every line we have in our final code.
Since there appears to be a lack of C resource I spent lots of time trying to reverse engineer the CPP libraries but I am hopelessly overwhelmed by anything beyond getting a pure C blinky to run.
Do you have any idea how I should approach this? Are there C resources about the Ethernet shield and Arduino SPI?
2 Answers 2
As Hans Neve wrote, you should really refer to the docs.
This is how it works in real life, when you want to write a driver for a new piece of HW.
You have to at least understand the block diagram, programming models and register sets of the device you want to control.
Then read whatever existing code you might find. In the practical case you have the driver for the version N-1 of the HW. Or maybe for something close enough.
As generic programming advice goes:
- avoid any dynamic memory allocation, you will thank yourself later on, when you do not have to debug unexplained memory issues
- if you want to write a driver, consider making it reentrant, should the same code be shared across multiple IP blocks
- if you want to use OOP, avoid anything that requires runtime lookup. The compiler should have enough information to resolve everything statically.
WRT debugging: both device drivers might suffer from interference if you try to use the serial port. Consider using some ICD tools, like the AVR Dragon. Alternatively, you might find that debugging over I2C is less penalizing. But you have to define your debugging messages.
SPI is pretty trivial (see the existing SPI library). Serial is easy enough. As for the Ethernet shield you would need to look at either the existing library or the manufacturer's datasheet. Some Ethernet chips are much easier to work with than others.
If you look at the datasheet for the Atmega328P (as used in the Uno) they have example code (in C) for SPI - along with comments. That should let you knock off the SPI part in an hour.
They also have example code for serial. Add in a ring buffer and you should be able to get serial going in half a day.
After all, the assignment doesn't tell you to not use the datasheet.
Depending on the Ethernet chip, you should be able to dig up (possibly in the chip datasheet) example code for that as well.
You could always use existing libraries (eg. Serial.print) for debugging, and then pull that code out once you are happy your own code works.
Since there appears to be a lack of C resource I spent lots of time trying to reverse engineer the CPP libraries
- you aren't allowed to use C++?