问题
最近做一个小项目,想使用Arduino和SX1278与PLC的485进行通讯。使用Arduino Nano以及Arduino Pro Mini都无法和SX1278进行通讯,不管是采用了安信可科技公司的没有采用SPI通讯的例程还是采用Arduino公司印度人编写的LoRa库都不能实现通讯。使用无SPI通讯例程在Arduino MRK WIFI 1010与SX1278通讯可以读取寄存器的信息,但无法写信息到寄存器。而使用SPI库即可以读取寄存器的信息也可以写寄存器。在这提供给大家为想使用SX1278的朋友做参考。
程序
#include <SPI.h>
const int NSS = 7;
const int RESET = 6;
const byte READ = 0b01111111; // 读命令
const byte WRITE = 0b10000000; // 写命令
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
while(!Serial);
Serial.println("Hello world!");
SPI.begin();
pinMode(NSS, OUTPUT);
pinMode(RESET, OUTPUT);
digitalWrite(NSS, HIGH);
digitalWrite(RESET, HIGH);
SX1278Reset();
byte ver_data = readRegister(0x42);
Serial.print("The version of LoRa is 0x");
Serial.println(ver_data, HEX);
writeRegister(0x01, 0x00); // 写0x01寄存器
// REG_RF_OPMODE, Sleep_mode
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available())
{
byte inBytes = Serial.read(); // 输入数字1,获取寄存器地址
inBytes = inBytes - 48; // inByte = 1
Serial.println(inBytes, DEC);
byte ver_data = readRegister(inBytes);
Serial.print("The register ");
Serial.print(inBytes);
Serial.print("\tThe data is 0x");
Serial.println(ver_data, HEX);
}
}
byte readRegister(byte thisRegister)
{
byte dataToSend = thisRegister & READ;
byte result = 0;
digitalWrite(NSS, LOW); // NSS = 0
SPI.transfer(dataToSend); // 发送地址
result = SPI.transfer(0x00); // 发送0x00获取返回值
digitalWrite(NSS, HIGH); // 片选NSS = 1
return result;
}
void writeRegister(byte thisRegister, byte thisValue)
{
byte dataToSend = thisRegister | WRITE;
digitalWrite(NSS, LOW);
SPI.transfer(dataToSend); // Send register location
SPI.transfer(thisValue); // Send value to record into register
digitalWrite(NSS, HIGH);
}
void SX1278Reset(void)
{
digitalWrite(RESET, LOW);
delay(200);
digitalWrite(RESET, HIGH);
delay(500);
}
程序说明
键盘输入1时显示寄存器1的内容,寄存器1已经被置为Sleep_mode模式,也可以读取寄存器0x42 版本号的内容,0x12。希望对大家有用!
请教
LoRa库函数在Arduino MKR WIFI 1010中为什么不能正常使用?请有经验的朋友指点一下。在这里先谢谢了!今天还有朋友的文章中说使用SPI库在发送SCLK脉冲时会出现9个脉冲,也请有经验的朋友指点一下,因为我在使用Arduino Pro Mini及SPI库时也碰到读回来的寄存器值不是0x00就是0xFF的现象。