NodeMCU based ESP8266 has Hardware SPI with four pins (D5 ~ D8 in the red square below) available for SPI communication. With this SPI interface, we can connect any SPI enabled device with NodeMCU and make communication possible with it.
ESP8266 has SPI pins (SD1, CMD, SD0, CLK) which are exclusively used for Quad-SPI communication with flash memory on ESP-12E, hence, they can’t be used for SPI applications (the pins in the blue square). We can use Hardware SPI interface for user end applications.
Below figure shows Quad SPI interface pins that are internally used for flash. It consists quad i/o (4-bit data bus) i.e. four (SDIO_DATA0 – SDIO_DATA3) bidirectional (i/p and o/p) data signals with synchronize clock (SDIO_CLK) and chip select pin (SDIO_CMD). It is mostly used to get more bandwidth/throughput than dual i/o (2-bit data bus) interface.
Note,
When connecting NodeMCU to other SPI devices, always use the hardware SPI pins (D5 ~ D8) and pay attention to the chip select pin used in the library.
The schematic
Connect NodeMCU to Arduino Uno according to the pic below. Be sure to connect the GND.
Sketch for NodeMCU (Master)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | #include<SPI.h> char buff[]="Hello Slave\n"; void setup() { Serial.begin(9600); /* begin serial with 9600 baud */ SPI.begin(); /* begin SPI */ } void loop() { for (int i = 0; i < sizeof buff; i++) {/* transfer buff data per second */ SPI.transfer(buff[i]); } Serial.println("Hello Slave__"); delay(2000); } |
Sketch for Arduino Uno (Slave)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | #include <SPI.h> char buff [100]; volatile byte index; volatile bool receivedone; /* use reception complete flag */ void setup (void) { Serial.begin (9600); SPCR |= bit(SPE); /* Enable SPI */ pinMode(MISO, OUTPUT); /* Make MISO pin as OUTPUT */ index = 0; receivedone = false; SPI.attachInterrupt(); /* Attach SPI interrupt */ } void loop (void) { if (receivedone) /* Check and print received buffer if any */ { buff[index] = 0; Serial.println(buff); index = 0; receivedone = false; } } // SPI interrupt routine ISR (SPI_STC_vect) { uint8_t oldsrg = SREG; cli(); char c = SPDR; if (index <sizeof buff) { buff [index++] = c; if (c == '\n'){ /* Check for newline character as end of msg */ receivedone = true; } } SREG = oldsrg; } |
Compile and upload the sketches to NodeMCU and Arduino Uno.
The output from Arduino Uno.
The output from NodeMCU.
Reference:
NodeMCU SPI with Arduino IDE
http://www.electronicwings.com/nodemcu/nodemcu-spi-with-arduino-ide
No comments:
Post a Comment