I'm building an IoT power usage monitor in which the data is logged using a RTC and an SD card module and a web app hosted on an ESP8266 gives access to this data. My question is can I use the exact same code (with libraries like "ESP8266.h") on a standalone ATmega programmed using Arduino as ISP?
Almost all of my projects are roll-your-own-duinos with Atmega 328p chips, with code generated for an "Arduino/Genuino Uno" board. Many of them use an ESP8266-01 board as a WiFi interface. I either run the entire board at 3.3v or use a daughter-board that interfaces the ESP to a 5v environment.
If you're porting code from an actual Arduino Uno, there is nothing to do except to make sure your pinouts are the same between the Arduino and the RYO-duino. Otherwise, make all your pin definitions constants and group them together in such a way (e.g. with #ifdef / #else / #endif) that you can easily enable one or the other group just before you compile.
There's a bit more required, for example, the clock rate needs to match or the timing will be off ...
I did gloss over the power & clock since the question hadn't asked about departures from the Uno's design. But yes, a RYO will need a compatible power supply and a matching clock rate, to be able to assume an arbitrary sketch could be run on it successfully. To make the RYO look like an UNO, it will need 5v power and a 16 MHz crystal, just as the Uno design provides.
If a RYO is designed be other than like an Uno, considering power source, clock rate, fuse options, DIP instead of an SMT, then there is nothing to support the supposition that a port from an Uno could succeed without modifying the code for those differences.
You can run any code on an ATMEGA328P that you can run on an Arduino Uno. For maximum compatibility, you would configure the ATMEGA328P with a 16Mhz crystal/resonator. There are instructions for using an Arduino Uno as an ISP for programming other devices, many of which require a Uno with a DIP version of the ATMEGA chip which can be removed. What you cannot do is directly run code for an ESP8266 on an ATMEGA328P.
Yes, it might work. But as a minimum you should check that the following is mapped between the two in a compatible way:
- Pinout and configuration of pins. ESP8266 allows INPUT_PULLDOWN in some pins, whereas ATmega328 doesn't.
- Use of timers and interrupts. ESP8266 accepts "true" interrupts on all I/O pins, whereas ATmega328 only accepts them in 2 pins (although you can use Pin Change Interrupts (PCIx), which are far less powerful than "true" External Interrupts (INTx)). Also, ESP8266 accepts HIGH level interrupts, whereas ATmega328 doesn't (even on INT-capable pins).
- Use of specific ESP8266 libraries which won't work at all on an ATmega328
The Arduino library ports for ESP8266 may work as expected out of the box, it may require minor tweaks, or it may require a major revamp of key code fragments. It's difficult to say without seeing the code.