From 190da3df3bd83968c598fed3c416bbe5aeedc52e Mon Sep 17 00:00:00 2001 From: Roman Chyla Date: Mon, 8 Feb 2016 17:21:48 -0500 Subject: [PATCH] Added tutorial for writing C module --- docs/en/cmodule.md | 230 +++++++++++++++++++++++++++++++++++++++++++++ docs/en/faq.md | 5 + mkdocs.yml | 1 + 3 files changed, 236 insertions(+) create mode 100644 docs/en/cmodule.md diff --git a/docs/en/cmodule.md b/docs/en/cmodule.md new file mode 100644 index 0000000000..b4abdd8d07 --- /dev/null +++ b/docs/en/cmodule.md @@ -0,0 +1,230 @@ + +This short tutorial will show you how to enhance the NodeMCU firmware with your own module written in C/C++. Bear in mind that most of the times you don't need to do that, as the existing modules may already provide what you need. But if for whatever reason you want to add your C/C++ code, you can. + +You will need to have a build chain, or you may want to use the docker image, see (https://github.com/nodemcu/nodemcu-firmware#building-the-firmware) + + +## C Module + +First, we'll create our C module - I'll use here a real example, which actually does something useful. It is just one file (and does not define functions in the header). It is saved inside `app/modules/easygpio.c`. The module reads data from GPIO channels. + + +```c +// Module for interfacing with GPIOs + +// Usage: +// easygpio.read(PIN_CLK, PIN_OUT, num_bits, extra_ticks, delay_us, initial_val, ready_state) +// easygpio.read(5, 6, 24, 1, 1, 0, 0) +// -- read 24 bits, from pin 6, pin 5 is CLOCK, hold it for 1us, initial value +// -- written to pin 5 is LOW (0), and ready state is when the pin 6 changes to LOW (0) + + +#include "lualib.h" +#include "lauxlib.h" +#include "platform.h" +#include "module.h" +#include "c_types.h" +#include "c_string.h" + +#define PULLUP PLATFORM_GPIO_PULLUP +#define FLOAT PLATFORM_GPIO_FLOAT +#define OUTPUT PLATFORM_GPIO_OUTPUT +#define INPUT PLATFORM_GPIO_INPUT +#define INTERRUPT PLATFORM_GPIO_INT +#define HIGH PLATFORM_GPIO_HIGH +#define LOW PLATFORM_GPIO_LOW + + +unsigned int PIN_CLK; +unsigned int PIN_DATA; +unsigned int STATE_INDICATOR; + + +bool is_ready() { + if (STATE_INDICATOR == 0) + return platform_gpio_read(PIN_DATA) == LOW; + return platform_gpio_read(PIN_DATA) == HIGH; +} + +long read(int pin_clk, int pin_data, int num_bits, int after_ticks, + int delay_us, int initial_clk_write, int ready_state) { + unsigned long Count; + unsigned char i; + Count=0; + + platform_gpio_write(pin_clk, initial_clk_write); + + while (platform_gpio_read(pin_data) != ready_state); + + for (i=0;i