当前位置:网站首页>Lora communication application development
Lora communication application development
2022-07-27 02:19:00 【Did Li fish today?】
summary :
1. understand Lora Basic knowledge of Technology
2. Understand the purpose of communication protocol
3. master Lora modular SPI Configuration method
4. Master the simple Lora Module data transfer method
5. master Lora How to use the communication protocol
One 、 What is? LoRa
LoRa(Long Range Radio, Long range radio ) It is a long-distance wireless transmission technology based on spread spectrum technology , yes LPWAN One of the communication technologies , yes Semtech Low power LAN Wireless Standard created by the company . This scheme provides users with a simple way to realize long distance 、 Low power wireless communication means . Its biggest feature is that it can spread farther than other wireless methods under the same power consumption , Realize the unity of low power consumption and long distance , At the same power consumption, it is larger than the traditional wireless RF communication distance 3~5 times . at present ,LoRa Mainly in the ISM Band operation , It mainly includes 433MHz、868MHz、915MHz etc. .
2.LoRa Characteristics of
transmission distance : Accessible in cities and towns 2~5km, Suburban accessibility 15km;
Working frequency :ISM Frequency band , Include 433MHz、868MHz、915MHz etc. ;
standard :IEEE 802.15.4g;
Modulation mode : Based on spread spectrum technology , It is linear modulation spread spectrum (CSS) A variation of , With forward error correction (FEC) Ability , yes Semtech Proprietary patented technology of the company ;
Capacity : One LoRa The gateway can connect thousands of LoRa node ;
Battery life : Long 10 year ;
Security :AES128 encryption ;
Transmission rate : Dozens to hundreds kbit/s, The lower the rate, the longer the transmission distance .
Two 、Lora and LoraWAN
Lora yes LoraWAN A subset of ,Lora Include only physical layer definitions ,LoraWAN Including link layer definitions . Actually LoraWAN Not a complete communication protocol , Because it only defines the physical layer and the link layer , The network layer and transport layer do not , The function is not perfect , No roaming , There is no important function of communication protocol such as network management .
3、 ... and 、Lora modular
Adopted LSD4RF-2F717N30 yes LoRa SX1278 470M100mW Standard module , Is based on Semtech RF integrated chip SX127X RF module , It is a high-performance wireless transceiver for the Internet of things .
1.SX1276/77/78 Transceiver
SX1276/77/78 yes 137~1020MHz Low power long distance transceiver , Mainly adopts LoRa Remote modem , For ultra long distance spread spectrum communication , Strong anti-interference , It can minimize current consumption .
With the help of Semtech Of LoRa Patented modulation technology ,SX1276/77/78 Using low-cost products and materials can obtain more than -148dBm High sensitivity of . Besides , High sensitivity and 20dBm The integration of power amplifier makes the link budget of these devices reach the industry-leading level , Become the best choice for long-distance transmission and applications requiring high reliability . Compared with traditional modulation technology ,LoRa Modulation technology also has obvious advantages in anti blocking and selectivity , It solves the problem that the traditional design scheme cannot take into account the distance at the same time 、 Anti interference and power consumption .
These devices also support WM-BusIIEEE 802.15.4g Such as the high performance of the system (G)FSK Pattern . Compared with similar devices ,SX1276/77/78 On the basis of greatly reducing current consumption , The phase noise is also significantly optimized 、 selectivity 、 Receiver linearity 、 Third order input intercept point (IIP3) And other performances .
SX1276 The bandwidth range is 7.8~500kHz, The spread spectrum factor is 6~12, And cover all available frequency bands .SX1277 The bandwidth and frequency range of SX1276 identical , But the spreading factor is 6~9.SX1278 Bandwidth and spread spectrum factor selection and SX1276 identical , But only cover UHF Frequency band .
(1) Key product features
LoRa modems ;
The maximum link budget can reach 168dB;
20dBm-100mW Constant RF power output when voltage changes ;
14dBm High efficiency power amplifier ;
Programmable bit rate up to 300kbit/s;
High sensitivity : As low as -148dBm;
High reliability front end :IIP3=-11dBm;
Excellent anti blocking properties ;
9.9mA Low receiving current ,200nA Register holding current ;
A resolution of 61Hz、 Fully integrated frequency synthesizer ;
Support FSK、GFSK、MSK、GMSK、LoRa And OOK Modulation mode :
Built in bit synchronization , For clock recovery ;
Preamble detection :
127dB Of RSSI Dynamic range :
Automatic RF signal detection ,CAD Mode and super high speed AFC;
with CRC、 the height is 256B Packet engine ;
Built in temperature sensor and low battery indicator .
(2) application
Remote irrigation system ;
Automatic meter reading ;
Home and building automation :
Wireless alarm and security system ;
Industrial monitoring and control ;
Four 、SPI
1.SPI brief introduction
LoRa Chip and MCU adopt SPI communicate .SPI(Serial Peripheral Interface Bus) It is a high-speed full duplex synchronous serial communication protocol developed by Motorola .SPI Support one master and many followers , This is similar to IC, But again with I2C The way of gating slave devices is different ,IC It is to gate the slave by sending the slave address , and SPI It is connected to the slave by pulling down NSS The pin is used to gate the slave .SPI General applications consist of four pins ( A master from ):
SCLK(Serial Clock): The serial clock , Sent by the host ;
MOSI(Master Output,Slave Input): The master outputs the slave input signal , Sent by the host ;
MISO(Master Input,Slave Output): Host input and slave output signals , From the slave :NSS: Select signal , Sent by the host , Generally, low potential is effective .

2. SPI Code configuration
(1) Pin initialization
adopt SpiInit() To achieve , This function is in the BoardDisableIrq( ) Call in .
void SpiInit( Spi_t *obj, PinNames mosi, PinNames miso, PinNames sclk, PinNames nss ) Parameter description :Spi_t *obj: Point to pending initialization SPI Structure ;PinNames mosi: Master output slave input pin ;PinNames miso: Master input slave output pin ;PinNames sclk: Serial clock pin ;PinNames nss: Chip selection pin ;
void SpiInit( Spi_t *obj, PinNames mosi, PinNames miso, PinNames sclk, PinNames nss )
{
BoardDisableIrq( );// No interruptions
// Choose SPI interface according to the given pins
if( mosi == PA_7 )
{
__HAL_RCC_SPI1_FORCE_RESET( );
__HAL_RCC_SPI1_RELEASE_RESET( );
__HAL_RCC_SPI1_CLK_ENABLE( );
obj->Spi.Instance = ( SPI_TypeDef* )SPI1_BASE;// establish SPI, That is to say obj Namely SPI1
// take GPIO Mouth initialization
GpioInit( &obj->Mosi, mosi, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_DOWN, GPIO_AF5_SPI1 );
GpioInit( &obj->Miso, miso, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_DOWN, GPIO_AF5_SPI1 );
GpioInit( &obj->Sclk, sclk, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_DOWN, GPIO_AF5_SPI1 );
GpioInit( &obj->Nss, nss, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_UP, GPIO_AF5_SPI1 );
if( nss == NC )
{
obj->Spi.Init.NSS = SPI_NSS_SOFT;//NSS Chip selection signal is independently controlled by software
SpiFormat( obj, SPI_DATASIZE_8BIT, SPI_POLARITY_LOW, SPI_PHASE_1EDGE, 0 );// Set up SPI Communication mode , Configure to host mode
}
else
{
SpiFormat( obj, SPI_DATASIZE_8BIT, SPI_POLARITY_LOW, SPI_PHASE_1EDGE, 1 );// Set up SPI Communication mode , Configured as slave mode
}
}
else if( mosi == PB_15 )
{// initialization SPI2
__HAL_RCC_SPI2_FORCE_RESET( );
__HAL_RCC_SPI2_RELEASE_RESET( );
__HAL_RCC_SPI2_CLK_ENABLE( );
obj->Spi.Instance = ( SPI_TypeDef* )SPI2_BASE;// establish SPI obj That is to say SPI2
// take GPIO Mouth initialization
GpioInit( &obj->Mosi, mosi, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_DOWN, GPIO_AF5_SPI2 );
GpioInit( &obj->Miso, miso, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_DOWN, GPIO_AF5_SPI2 );
GpioInit( &obj->Sclk, sclk, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_DOWN, GPIO_AF5_SPI2 );
GpioInit( &obj->Nss, nss, PIN_ALTERNATE_FCT, PIN_PUSH_PULL, PIN_PULL_UP, GPIO_AF5_SPI2 );
if( nss == NC )
{
obj->Spi.Init.NSS = SPI_NSS_SOFT;//NSS Chip selection signal is independently controlled by software
SpiFormat( obj, SPI_DATASIZE_8BIT, SPI_POLARITY_LOW, SPI_PHASE_1EDGE, 0 );// Set up SPI Communication mode , Configure to host mode
}
else
{
SpiFormat( obj, SPI_DATASIZE_8BIT, SPI_POLARITY_LOW, SPI_PHASE_1EDGE, 1 );// Set up SPI Communication mode , Configured as slave mode
}
}
SpiFrequency( obj, 10000000 );// Set up SPI Speed
HAL_SPI_Init( &obj->Spi );// take effect
BoardEnableIrq( );// To interrupt
}(2) Set up SPI Communication mode
SpiFormat( Spi_t *obj, int8_t bits, int8_t cpol, int8_t cpha, int8_t slave ) The parameters in are as follows :
Spi_t *obj:SPI Structure ;
int8_t bits: The frame format , choice 8 position
int8_t cpol: Set the clock polarity . Here is the low level
int8_t slave: A master-slave mode ,0 Lord ,1 from
(3)Lora Modulation and demodulation
(1) frequency : The recommended frequency is 433MHZ near , also 430,431,432, The user determines the appropriate channel according to the set frequency .
(2) Transmitting power :Lora The transmission power is determined by the parameter TX_OUTPUT_POWER; The bigger this is , The farther the transmission distance , The maximum value does not exceed 20dBm.
(3)Lora Packet structure :

3. Write key functions NS_Radio.c
void NS_RadioEventsInit( void )// RF initialization function
{
// Radio initialization
RadioEvents.TxDone = OnTxDone;
RadioEvents.RxDone = OnRxDone;
RadioEvents.TxTimeout = OnTxTimeout;
RadioEvents.RxTimeout = OnRxTimeout;
RadioEvents.RxError = OnRxError;
Radio.Init( &RadioEvents );
}
void OnTxDone( void )// Call this function after sending
{
Radio.Sleep( );
Radio.Rx( RX_TIMEOUT_VALUE );
}
void OnRxDone( uint8_t *payload, uint16_t size, int16_t rssi, int8_t snr )// Receive completion call , Reading data 、 Data length 、 Signal strength 、 Signal-to-noise ratio .
{
Radio.Sleep( );
LoRaBufferSize = size;
memcpy( LoRaBuffer, payload, LoRaBufferSize );
RssiValue = rssi;
SnrValue = snr;
// printf( "Rx=%s\r\nRssiValue=%d\r\nSnrValue=%d\r\n",LoRaBuffer,RssiValue,SnrValue );
Radio.Rx( RX_TIMEOUT_VALUE );
}
void OnTxTimeout( void )// Send timeout call
{
Radio.Sleep( );
Radio.Rx( RX_TIMEOUT_VALUE );
}
void OnRxTimeout( void )// Receive timeout call
{
Radio.Sleep( );
Radio.Rx( RX_TIMEOUT_VALUE );
}
void OnRxError( void )// Receive error call
{
Radio.Sleep( );
Radio.Rx( RX_TIMEOUT_VALUE );
}
Project experiment
Project introduction : Square circle 5 Square kilometer botanical garden , Extensive management , The management committee requires that the environment of the park be tested , Temperature, humidity, light, etc . requirement : Low cost , Save money ; First, realize point-to-point , It can acquire data in the upper computer , Later, upgrade the bit cloud platform to obtain .
(1) Analysis of key interface functions :
void LoRa_Send( uint8_t *TxBuffer, uint8_t len )//TxBuffer It's a pointer , Point to what the user needs to send Lora Wireless data first address .
{
Radio.Send( TxBuffer, len);
}
void MyRadioRxDoneProcess( void )// receive Lora Wireless data , Users need to parse the function code or function of wireless data in the function .
{
uint16_t BufferSize = 0;
uint8_t RxBuffer[BUFFER_SIZE];
BufferSize = ReadRadioRxBuffer( (uint8_t *)RxBuffer );
if(BufferSize>0)
{
// The user adds the code of receiving data processing function here
;
printf("LoRa TempRh\r\n");
hal_temHumInit();// Initialize the temperature and humidity module
connectionreset();// Reset the temperature and humidity module IIC signal communication
Tim3McuInit(1);// Timer initialization , Set timing interrupt 1ms Break once
}
}
void PlatformInit(void)// Hardware platform initialization
{
// Development board platform initialization
BoardInitMcu();
BoardInitPeriph();
// Development board device initialization
OLED_Init();// LCD initialization
USART1_Init(115200);// A serial port 1 initialization
OLED_Clear();
OLED_InitView();//OLED The screen displays the initial information
printf(" Education in the new world LoRa \r\n");
//Lora Module initialization
NS_RadioInit( (uint32_t) RF_PING_PONG_FREQUENCY, (int8_t) TX_OUTPUT_POWER, (uint32_t) TX_TIMEOUT_VALUE, (uint32_t) RX_TIMEOUT_VALUE );
// Please add user initialization code below
//IWDG_PrmInit(2048);// Independent watchdog initialization , The timeout is set to 2048ms
}
//-----------------------------------------------------------
// Formulate the response command structure according to the communication protocol
#define START_HEAD 0x55// Frame head
#define CMD_READ 0x01// Reading data
#define ACK_OK 0x00// Respond to OK
#define ACK_NONE 0x01// No data
#define ACK_ERR 0x02// Data error
// Define network number and device address
#define MY_NET_ID 0xD0C2 // The Internet ID
#define MY_ADDR 0x01 // Device address
/* Global variables */
int8_t temperature = 25; // temperature , Company :℃
int8_t humidity = 60; // humidity , Company :%
// Function declaration
void LoRa_Send( uint8_t *TxBuffer, uint8_t len );
void MyRadioRxDoneProcess( void );
void OLED_InitView(void);
void PlatformInit(void);
uint8_t CheckSum(uint8_t *buf, uint8_t len)// Calculate the check sum
{
uint8_t temp = 0;
while(len--)
{
temp += *buf;
buf++;
}
return (uint8_t)temp;
}
/**********************************************************************************************
* function :uint8_t *ExtractCmdframe(uint8_t *buf, uint8_t len, uint8_t CmdStart)
* function : Extract the starting address of the command frame from a string of data
* Input :
* uint8_t *buf, Point to the address of the data buffer to be extracted
* uint8_t len, Buffer data length
* uint8_t CmdStart, Command frame start byte
* Output : nothing
* return : Return the address of the first command frame , If there is no command frame data in the data , Then return to NULL
* Special instructions : nothing
**********************************************************************************************/
uint8_t *ExtractCmdframe(uint8_t *buf, uint8_t len, uint8_t CmdStart)
{
uint8_t *point = NULL;
uint8_t i;
for(i=0; i<len; i++)
{
if(CmdStart == *buf)
{
point = buf;
return point;
}
}
return NULL;
}
/**********************************************************************************************
* function :uint16_t GetHexStr(uint8 *input, uint16_t len, uint8 *output)
* function : To generate an array 16 String format in hexadecimal form , Members are separated by spaces
* for example : from {0xA1,0xB2,0xC3} Generate "A1 B2 C3"
* Input :uint8 *input- Point to the input cache , uint16_t len- Byte length of input data
* Output :uint8 *output- Point to the output cache
* return : Returns the length of the generated string
* Special instructions : nothing
**********************************************************************************************/
uint16_t GetHexStr(uint8_t *input, uint16_t len, uint8_t *output)
{
for(uint16_t i=0; i<len; i++)
{
sprintf((char *)(output+i*3),"%02X ", *input);
input++;
}
return strlen((const char *)output);
}(2) The request command refers to the data communication structure , After the sensor receives the command of the gateway to read the sensing data , The node needs to report to the gateway according to the communication protocol format . The request command parsing data code is as follows :
//--------------------------------------------------------
// Data analysis
void LoRa_DataParse( uint8_t *LoRaRxBuf, uint16_t len )
{
uint8_t *DestData = NULL;
#define HEAD_DATA *DestData // Frame head
#define CMD_DATA *(DestData+1) // command
#define NETH_DATA *(DestData+2) // The Internet ID High byte
#define NETL_DATA *(DestData+3) // The Internet ID Low byte
#define ADDR_DATA *(DestData+4) // Address
#define ACK_DATA *(DestData+5) // Respond to
#define LEN_DATA *(DestData+6) // length
#define DATASTAR_DATA *(DestData+7) // Data field start
DestData = ExtractCmdframe((uint8_t *)LoRaRxBuf, len, START_HEAD);// input data length Frame to DestData
if(DestData != NULL)// Retrieved data frame header
{
if((DestData - LoRaRxBuf) > (len - 6)) return;// The data length is not enough to form a complete frame of data
if(CMD_DATA != CMD_READ) return;// Wrong command
if(CheckSum((uint8_t *)DestData, 5) != (*(DestData+5))) return;// Verification failed , It is only applicable to the verification of the read data command
if(((((uint16_t)NETH_DATA)<<8)+NETL_DATA) != MY_NET_ID) return;// The Internet ID atypism
// Send a read response
if(ADDR_DATA != MY_ADDR) return;// Different addresses
/--------------------------------------------------------------------
// Sending data according to the communication protocol is also called response
uint8_t RspBuf[BUFFER_SIZE]= {0};
memset(RspBuf, '\0', BUFFER_SIZE);
RspBuf[0]=START_HEAD;// Frame head
RspBuf[1]=CMD_READ;// command ,0x01 Read the sensing data
RspBuf[2]=(uint8_t)(MY_NET_ID>>8);// The Internet ID Low byte
RspBuf[3]=(uint8_t)MY_NET_ID;// The Internet ID High byte
RspBuf[4]=MY_ADDR;// Address
RspBuf[5]=ACK_OK;// Respond to OK 0x00
sprintf((char *)(RspBuf+7),"temperature(℃):%d|humidity(%%):%d", temperature, humidity);// Data fields ,sprintf in , Two “%” Indicative output “%”. The collected value has been put into these two variables in the acquisition sensing function , Just send .
RspBuf[6]=strlen((const char *)(RspBuf+7))+1;// Data field length
RspBuf[6+RspBuf[6]]=CheckSum((uint8_t *)RspBuf, 6+RspBuf[6]);
Radio.Send( RspBuf, 7+RspBuf[6]);// Send response data
GpioToggle( &Led1 );// Send data switching light
}
}(3) The host receiving code is as follows :
/**********************************************************************************************
* function :void MyRadioRxDoneProcess( void )
* function : Wireless module data receiving completion processing process function
* Input : nothing
* Output : nothing
* return : nothing
* Special instructions : The received wireless data is saved in RxBuffer in ,BufferSize Is the length of received wireless data
**********************************************************************************************/
void MyRadioRxDoneProcess( void )
{
uint16_t BufferSize = 0;
uint8_t RxBuffer[BUFFER_SIZE];
BufferSize = ReadRadioRxBuffer( (uint8_t *)RxBuffer );
if(BufferSize>0)
{
// The user adds the code of receiving data processing function here
GpioToggle( &Led2 );// Receive the data switching light indication
LoRa_DataParse( (uint8_t *)RxBuffer, BufferSize );// Call the data parsing function
}
}(4) The main function initializes the hardware platform , Continue to cycle the receiving and sending function .
//----------------------------- Get sensor data ------------------------
void LoRa_GetSensorDataProcess(void)
{
const uint16_t time = 1000;
if(User0Timer_MS > time) //1ms Forward interrupt User0Timer_MS ++;
{
User0Timer_MS = 0;
uint16_t Temp, Rh;
call_sht11((uint16_t *)(&Temp), (uint16_t *)(&Rh));// Collect temperature and humidity data
temperature = (int8_t)Temp; // temperature , Company :℃ Pass the collected value to the two variables defined above
humidity = (int8_t)Rh; // humidity , Company :% Pass the collected value to the two variables defined above
//------------------oled Show --------------------------------------------
char StrBuf[64]= {0};
memset(StrBuf, '\0', 64);
sprintf(StrBuf, " %d DegrCe",temperature);
OLED_ShowString(0,4,(uint8_t *)StrBuf);//OLED Displays the current temperature
memset(StrBuf, '\0', 64);
sprintf(StrBuf, " %d %%",humidity);
OLED_ShowString(0,6,(uint8_t *)StrBuf);//OLED Displays the current relative humidity
}
}
int main( void )
{
PlatformInit();
while( 1 )
{
//IWDG_PrmRefresh( );// Hello, the independent watchdog
MyRadioRxDoneProcess();//LoRa Radio frequency receiving data processing process
LoRa_GetSensorDataProcess();
}
}边栏推荐
- Codeforces Round #809 (Div. 2), problem: (C) Qpwoeirut And The City
- JS max?
- 【volatile原理】volatile原理
- Test and open basic daily question brushing (continuous updating...)
- OSPF protocol knowledge summary
- 微信小程序:用户微信登录流程(附:流程图+源码)
- 定时器中断实验
- NAT network address translation experiment
- 2022zui新抖音24小时循环值守直播监控(一)直播间开播监控
- ospf协议概述以及基础概念
猜你喜欢
随机推荐
Text to image intensive reading of paper gr-gan: gradually refine text to image generation
MySQL课程1.简单命令行--简单记录 欢迎补充纠错
Lora通信应用开发
Explain exi interrupt through the counting experiment of infrared sensor
Brief introduction of VLAN principle and specific experimental configuration
[Database Course Design] SQLSERVER database course design (student dormitory management), course design report + source code + database diagram
HCIA静态路由基础模拟实验
[详解C语言]一文带你玩转选择(分支)结构
First knowledge of Web Design
Tcp的三次握手与四次挥手
C语言——while语句、dowhile语句、for循环和循环结构、break语句和continue语句
Lesson 5 - key control LED
RS-485总线通信应用
6.28大华笔试
Self introduction and planning about programming
HCIA(网络初级综合实验练习)
Unity Huatuo revolutionary hot update series [1]
Golang — 解析 yaml 文件
通过对射式红外传感器计次实验讲解EXTI中断
Lecture 4 - explain GPIO_ Write function and related routines









