|
10金币
本帖最后由 dyn002000 于 2019-8-28 21:26 编辑
各位大大好,
测试了一下NodeMCU V3 和 Arduino UNO 之间的SPI通信测试。。代码如下:
NodeMCU Master:
[mw_shl_code=arduino,true]#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);
Serial.print(buff);
}
delay(1000);
}[/mw_shl_code]
Arduino UNO Slave:
[mw_shl_code=arduino,true]#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;
}[/mw_shl_code]
测试结果是没问题的 作为从机的UNO能收到“Hello Slave”。
问题就是我想让从机收到后发点信息回去给主机。。 比如:
[mw_shl_code=arduino,true] digitalWrite(SS, LOW);
SPI.transfer(0x23);
digitalWrite(SS, HIGH);[/mw_shl_code]这样的,,是直接加在 if (receivedone) { }里面吗? 然后主机的NodeMCU又要如何读取呢??
还是说根本不能这么操作?
提前感谢各位大大的解答!
|
最佳答案
查看完整内容
从机当次收的数据,肯定来不及本次发出去,最快也得下次才能发出去。
看来从机 SPI.transfer 的确会卡死,不过卡完以后返回的数值,就是下一次主机发的数据啊
|