GY56 infrared laser ranging sensor (STM32, MSP432 code included)


1. Introduction to GY56

1 Overview

insert image description here

GY-56 is a low-cost digital infrared distance sensor module. Working voltage 3-5v, low power consumption, small size, easy installation. Its working principle is that the infrared LED emits light, and after irradiating the object to be measured, the returned light is received by the MCU, and the MCU calculates the time difference to obtain the distance. Output the distance value directly. This module has two ways to read data, that is, serial port UART (TTL level) + IIC (2-wire) mode, the baud rate of the serial port is 9600bps and 115200bps, configurable, there are two ways of continuous and query output, you can Save settings when power off. GY-56 can set the upper and lower limit distance alarm value, switch output, if there is a measured object in the set range, it will directly output high level. In IIC mode, if necessary, you can set the internal IIC address to be different, so that multiple sensors can be directly connected to the same bus.

2. Features

  • cost-effective
  • Built-in MCU to calculate distance
  • IIC, serial communication protocol
  • Equipped with corresponding PC software

3. Parameters

insert image description here

4. Pin description

insert image description here

5. Application

  • smart robot
  • Teaching Laboratory Instruments
  • Production line product testing
  • Infrared ranging

2. Communication protocol

1. Serial port

Tips: The module defaults to the serial port

(1) Serial communication parameters (the default baud rate is 9600bps, which can be set by software)
Baud rate: 9600 bps Check digit: N Data bits: 8 Stop bits: 1
Baud rate: 115200 bps Check digit: N Data bits: 8 Stop bits: 1

(2) Module output format, each frame contains 8-13 bytes (hexadecimal):
①.Byte0: 0x5A frame header flag
②.Byte1: 0x5A frame header flag
③.Byte2: 0x15 This frame data
type④ .Byte3: 0x03 data amount⑤.Byte4
: 0x00~0xFF the first high 8 bits of
the data⑥.Byte5: 0x00~0xFF the first low 8 bits of
the data⑦.Byte6: 0x00~0xFF the module measurement mode⑧.Byte7
: 0x00~0xFF the module
temperature⑨ .Byte8: 0x00~0xFF checksum (accumulated sum of the previous data, leaving only the lower 8 bits)

insert image description here

Data calculation method (distance length calculation method):

Distance= (Byte4<<8) | Byte5 in cm
Mode= Byte6
Temp= Byte7 (MCU temperature)

Example: One frame of data
< 5A-5A-15-04-00-0A-02-1A-F3>
Distance =(0x00<<8)|0x0A =10cm
Mode=2 (high precision mode)
Temp=0x1A=26℃

(3) Command bytes, sent by the external controller to the GY-56 module (hexadecimal)
serial port command command:
Command format: 0xA5+function command+command value+sum
insert image description here
Example 1: Set serial port continuous output data, (if required Power-down save, please send power-down save command)
Continuous output command=0xA5+0x65+0x01+0x0B

Example 2: Set the OUT pin to output a high level within the range of 10cm-50cm
(if you need power-down storage, please send a power-down storage command)
set the upper limit threshold 50CM=0xA5+0x98+0x32+0x6F
set the lower limit threshold 10CM=0xA5+0xA9+0x0A+0x58

Example 3: Power-down save command = 0xA5+0x87+0x01+0x2D

2. IIC protocol

It is used when the GY-56 module hardware ps solder spot is welded, CT is SCL, DR is SDA
insert image description here

IIC clock: below 250K, the default 8bit IIC address of the module is 0XE0;
1bit write: 0;
1bit read: 1;
insert image description here

3. How to use the module

The module is a serial port and IIC output module, and the module defaults to serial port mode. After the module is connected to the power supply, if the detection distance is not within the upper limit threshold, the LED will flash for 1 second. If the detection distance is within the upper limit threshold, the LED indicator will be on. If the indicator light keeps flashing, it means that the module initialization failed and the module cannot be used
.

Serial port mode (default) : pull the PS port high (by default, the PS solder joint is open), the module is powered on, and the default configuration is 9600 baud rate, high-precision measurement, and continuous output mode; The module should be set accordingly; please select the port and baud rate before using the host computer, and then click the "Open Serial Port" button, at this time, the host computer will display the corresponding data.

There are two serial port output modes, one is continuous output and the other is query output. The frequency of continuous output
varies according to the measurement mode, please refer to the meaning of Byte6 for details; the form of query output is that after the module receives the query command, the module starts a measurement, and returns a frame of measurement data after the measurement is completed. Different output modes and different measurement modes lead to different current consumption of the module. When the module is not measuring the distance, the current is about 15mA. In the query output mode, the current is about 15mA after the measurement is completed. For the current in the continuous output mode, refer to Byte6 for details. Description of meaning.

  • 1. SET, OUT pin instructions:

S represents the distance between the module and the measured object;
S1 represents the set maximum alarm threshold (upper limit threshold);
S2 represents the set minimum alarm limit threshold (lower limit threshold);
S3 represents the release of the maximum alarm limit State value; relationship between S3 and S1, S3+3≤S1. For example, if S1=100, then S3≤97;
S4 means to release the minimum alarm state value; the relationship between S4 and S2, S4-3≥S2. For example, if S2=50, then S3≥53;
the state of OUT pin is high level and low level. High level means S2<S<S1; low level means S>S1 or S<S2.

(1) OUT changes from high level to low level. When the module S>S1 or S<S2, the OUT pin becomes low level, and the module LED light will change from on to off.
(2) OUT changes from low level to high level. When S>S1, let S≤S3 (that is, when the actual distance is lower than the maximum alarm threshold 3cm), the OUT pin will change from low level to high level, and the module LED will turn from off to on. When S<S2, let S≥S4 (that is, when the actual distance is greater than the minimum alarm threshold 3cm), the OUT pin will change from low level to high level, and the module LED will turn from off to on.

  • 2. Set the maximum alarm threshold: It can be set by sending commands or manually through the SET pin.

(1) In the continuous output mode of the module, for example, if the maximum alarm threshold S1 is set to 100cm, then place the module at a position of 97cm from the measured object to set the SET pin, or send the command: (A5 98 64 A1) 0x64 Yes 100 in decimal.
(2) Manually connect the SET pin to a 3.3V high level for about 3 seconds, wait for the module LED indicator to flash twice, then disconnect the 3.3V connection of the SET pin, about 5 seconds after disconnection, wait for the LED to flash 3 times, the setting is successful. If the LED blinks 4 times, it means the setup failed. There are two reasons for the failure. One is that the high level time is not enough, and the other is that the set distance value is less than the minimum alarm threshold.

  • 3. Set the minimum alarm threshold: it can be set by sending commands or by SET pin.

(1) In the continuous output mode of the module, for example, if the minimum alarm threshold S2 is set to 50cm, then place the module at a position 53cm away from the measured object, set the SET pin, or send the command: (A5 A9 32 B2) 0x32 is 50 in decimal.
(2) Manually connect the SET pin to GND for about 3 seconds, wait for the module LED indicator to flash 2 times, then disconnect the SET pin GND connection, about 5 seconds after disconnection, wait for the LED to flash 3 times, then set success. If the LED blinks 4 times, it means the setup failed. There are two reasons for the failure, one is that the low level access time is not enough, and the other is that the set distance value is greater than the maximum alarm threshold.

  • 4. Calibration instruction of GY56 module under serial port:

The module consists of ranging sensors and an MCU.
(1) SPADs correction: When the distance measuring sensor is covered by a transparent material object, the module needs to perform this correction once,
and load the SPADs correction parameters after power-on. By default, the module will perform a SPADs correction operation after each power-on. If the user manually performs a SPADs correction and sets the power-on load SPADs correction parameter, the module will not perform the SPADs correction operation after power-on, which can shorten the module time. Initialization time; send the hexadecimal A5 0A 01 B0 to the module through the host computer, the module LED is on, and the calibration is completed when it is off.
(2) Temperature correction: When the temperature of the working environment of the module changes by more than 8 degrees Celsius, the sensitivity of the ranging sensor will change, and a temperature correction is required; by default, the module will perform a temperature correction operation after each power-on, such as the module The temperature of the working environment is constant. After a manual temperature correction, set the temperature correction parameters to be loaded after the module is powered on, which can shorten the initialization time of the module; Perform a temperature correction; send the hexadecimal A5 10 01 B6 to the module through the host computer, the module LED will light up, and the calibration will be completed when it is off.
(3) Deviation calibration: This operation can be performed when there is an inherent deviation between the distance measurement value of the module and the actual value.
The command of offset calibration=0xA5+0x21+command value+sum, the command value is the actual distance value. For example, if the distance measurement value of the module is
13CM, but the actual value is 10CM, then the command value in the command is 10 in decimal; if you need to load the compensation value after power on again, you need to set the load offset calibration parameter after power on. Send the hexadecimal command to the module through the host computer, the module LED is on, and the calibration is completed after it is off.
(4) Window calibration:When the ranging sensor is covered by a transparent material object, and the module performs this operation when the value of the full-range ranging is not linear. As shown in the figure below:
insert image description here
The X-axis is the actual value, and the Y-axis is the measured value. The green dotted line indicates that the material has no effect on the distance measurement or the surface of the sensor
is not covered by the task material. The blue line indicates a slight impact, the red line indicates a moderate impact, and the green solid line indicates a severe impact.
Window calibration command=0xA5+0x32+command value+sum;

Selection of command value: use a 17% gray reflectivity target, then set the distance between the module and the measured target as S. For
mild impact, see the left blue line in the figure below, as long as S is between A and B. The command value is the actual distance value. Select the area between the red line AB on the right with moderate influence. If you need to load the compensation value after power on again, you need to set the load window calibration parameters after power on. Send the hexadecimal command to the module through the host computer, the module LED is on, and the calibration is completed after it is off.
insert image description here

IIC mode : In this mode, the module will perform a ranging operation every time the start measurement command is sent, and the distance value can be read only after the ranging is completed. The ranging time depends on which measurement mode the module is in, as shown in the table below, for example, high In precision mode, you need to read the ranging value after about 200ms. The measurement mode configuration of the module needs to be set through the serial port.

insert image description here

4. GY56 upper computer

insert image description here

Five, STM32 driver code

1. Serial port initialization

	//GPIO端口设置
	GPIO_InitTypeDef GPIO_InitStructure;
	USART_InitTypeDef USART_InitStructure;
	NVIC_InitTypeDef NVIC_InitStructure;

	RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE);	//使能USART2,GPIOA时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
    
	//USART2_TX   GPIOA
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2; //PA.2
	GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;	//复用推挽输出
	GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.2

	//USART2_RX	  GPIOA
	GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;//PA3
	GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//浮空输入
	GPIO_Init(GPIOA, &GPIO_InitStructure);//初始化GPIOA.3 

	//Usart1 NVIC 配置
	NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
	NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//抢占优先级3
	NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3;		//子优先级3
	NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;			//IRQ通道使能
	NVIC_Init(&NVIC_InitStructure);	//根据指定的参数初始化VIC寄存器

	//USART 初始化设置

	USART_InitStructure.USART_BaudRate = bound;//串口波特率
	USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
	USART_InitStructure.USART_StopBits = USART_StopBits_1;//一个停止位
	USART_InitStructure.USART_Parity = USART_Parity_No;//无奇偶校验位
	USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
	USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;	//收发模式

  USART_Init(USART2, &USART_InitStructure); //初始化串口2
  USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);//开启串口接受中断
  USART_Cmd(USART2, ENABLE);                    //使能串口2

2. Send command

void USART_Send(uint8_t *Buffer, uint8_t Length)
{
    
    
	uint8_t i=0;
	while(i<Length)
	{
    
    
		if(i<(Length-1))
		Buffer[Length-1]+=Buffer[i];//累加Length-1前的数据
		while(USART_GetFlagStatus(USART2,USART_FLAG_TC)==RESET); //循环发送,直到发送完毕   
		USART_SendData(USART2,Buffer[i++]); 
	}
}

void send_com(u8 function,u8 value )
{
    
    
	u8 bytes[4]={
    
    0};
	bytes[0]=0xa5;
	bytes[1]=function;//功能指令
	bytes[2]=value;//指令值
	USART_Send(bytes,4);//发送帧头、功能字节、校验和
}

3. Receive interrupt

void USART2_IRQHandler(void)                	//串口2中断服务程序
{
    
    
	static uint8_t i=0,rebuf[20]={
    
    0};
	if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET)//判断接收标志
	{
    
    
		rebuf[i++]=USART_ReceiveData(USART2);//读取串口数据,同时清接收标志
		if (rebuf[0]!=0x5a)//帧头不对
			i=0;	
		if ((i==2)&&(rebuf[1]!=0x5a))//帧头不对
			i=0;
	
		if(i>3)//i等于4时,已经接收到数据量字节rebuf[3]
		{
    
    
			if(i!=(rebuf[3]+5))//判断是否接收一帧数据完毕
				return;	
			switch(rebuf[2])//接收完毕后处理
			{
    
    
				case 0x15:
					if(!Receive_ok)//当数据处理完成后才接收新的数据
					{
    
    
						memcpy(re_Buf_Data,rebuf,9);//拷贝接收到的数据
						Receive_ok=1;//接收完成标志
					}
					break;
			
			}
			i=0;//缓存清0
		}
	}
} 

4. Data Analysis

if(Receive_ok)//串口接收完毕
{
    
    
	for(sum=0,i=0;i<(re_Buf_Data[3]+4);i++)
	sum+=re_Buf_Data[i];
	if(sum==re_Buf_Data[i])//校验和判断
	{
    
    
		GY56.distance=re_Buf_Data[4]<<8|re_Buf_Data[5];
		GY56.mode=re_Buf_Data[6];
		GY56.temp=re_Buf_Data[7];		
		printf("%d\r\n",GY56.distance);
	}
	Receive_ok=0;//处理数据完毕标志
}

6. MSP432 driver code

1. Serial port initialization

void UARTA2_Init(void)
{
    
    
    //1.配置GPIO复用
    GPIO_setAsPeripheralModuleFunctionInputPin(GPIO_PORT_P3, GPIO_PIN2 | GPIO_PIN3, GPIO_PRIMARY_MODULE_FUNCTION);

    //2.配置UART结构体
#ifdef EUSCI_A_UART_7_BIT_LEN
    //固件库v3_40_01_02
    //默认SMCLK 48MHz 比特率 115200
    const eUSCI_UART_ConfigV1 uartConfig =
        {
    
    
            EUSCI_A_UART_CLOCKSOURCE_SMCLK,                // SMCLK Clock Source
            26,                                            // BRDIV = 26
            0,                                             // UCxBRF = 0
            111,                                           // UCxBRS = 111
            EUSCI_A_UART_NO_PARITY,                        // No Parity
            EUSCI_A_UART_LSB_FIRST,                        // MSB First
            EUSCI_A_UART_ONE_STOP_BIT,                     // One stop bit
            EUSCI_A_UART_MODE,                             // UART mode
            EUSCI_A_UART_OVERSAMPLING_BAUDRATE_GENERATION, // Oversampling
            EUSCI_A_UART_8_BIT_LEN                         // 8 bit data length
        };
    eusci_calcBaudDividers((eUSCI_UART_ConfigV1 *)&uartConfig, 115200); //配置波特率
#else
    //固件库v3_21_00_05
    //默认SMCLK 48MHz 比特率 115200
    const eUSCI_UART_Config uartConfig =
        {
    
    
            EUSCI_A_UART_CLOCKSOURCE_SMCLK,                // SMCLK Clock Source
            26,                                            // BRDIV = 26
            0,                                             // UCxBRF = 0
            111,                                           // UCxBRS = 111
            EUSCI_A_UART_NO_PARITY,                        // No Parity
            EUSCI_A_UART_LSB_FIRST,                        // MSB First
            EUSCI_A_UART_ONE_STOP_BIT,                     // One stop bit
            EUSCI_A_UART_MODE,                             // UART mode
            EUSCI_A_UART_OVERSAMPLING_BAUDRATE_GENERATION, // Oversampling
        };
    eusci_calcBaudDividers((eUSCI_UART_Config *)&uartConfig, 115200); //配置波特率
#endif
    //3.初始化串口
    UART_initModule(EUSCI_A2_BASE, &uartConfig);

    //4.开启串口模块
    UART_enableModule(EUSCI_A2_BASE);
	
    //5.开启串口相关中断
    UART_enableInterrupt(EUSCI_A2_BASE, EUSCI_A_UART_RECEIVE_INTERRUPT);

    //6.开启串口端口中断
    Interrupt_enableInterrupt(INT_EUSCIA2);

    //7.开启总中断
    Interrupt_enableMaster();
}

2. Send command

void USART2_Send(uint8_t *Buffer, uint8_t Length)
{
    
    
	uint8_t i=0;
	while(i<Length)
	{
    
    
		if(i<(Length-1))
		Buffer[Length-1]+=Buffer[i];//累加Length-1前的数据
		//while (!(UART_getInterruptStatus(EUSCI_A2_BASE, EUSCI_A_UART_TRANSMIT_COMPLETE))); //循环发送,直到发送完毕   
		UART_transmitData(EUSCI_A2_BASE, Buffer[i++]);
	}
}

void send_com(u8 function,u8 value )
{
    
    
	u8 bytes[4]={
    
    0};
	bytes[0]=0xa5;
	bytes[1]=function;//功能指令
	bytes[2]=value;//指令值
	USART2_Send(bytes,4);//发送帧头、功能字节、校验和
}

3. Receive interrupt

void EUSCIA2_IRQHandler(void)
{
    
    
    uint32_t status = UART_getEnabledInterruptStatus(EUSCI_A2_BASE);
	static uint8_t i=0,rebuf[20]={
    
    0};
	
    if(status & EUSCI_A_UART_RECEIVE_INTERRUPT_FLAG) //接收中断
    {
    
    
		rebuf[i++]=MAP_UART_receiveData(EUSCI_A2_BASE);;//读取串口数据,同时清接收标志
		if (rebuf[0]!=0x5a)//帧头不对
			i=0;	
		if ((i==2)&&(rebuf[1]!=0x5a))//帧头不对
			i=0;
	
		if(i>3)//i等于4时,已经接收到数据量字节rebuf[3]
		{
    
    
			if(i!=(rebuf[3]+5))//判断是否接收一帧数据完毕
				return;	
			switch(rebuf[2])//接收完毕后处理
			{
    
    
				case 0x15:
					if(!Receive_ok)//当数据处理完成后才接收新的数据
					{
    
    
						memcpy(re_Buf_Data,rebuf,9);//拷贝接收到的数据
						Receive_ok=1;//接收完成标志
					}
					break;
			
			}
			i=0;//缓存清0
		}
    }

}

4. Data Analysis

if(Receive_ok)//串口接收完毕
{
    
    
	for(sum=0,i=0;i<(re_Buf_Data[3]+4);i++)
	sum+=re_Buf_Data[i];
	if(sum==re_Buf_Data[i])//校验和判断
	{
    
    
		GY56.distance=re_Buf_Data[4]<<8|re_Buf_Data[5];
		GY56.mode=re_Buf_Data[6];
		GY56.temp=re_Buf_Data[7];		
		printf("%d\r\n",GY56.distance);
	}
	Receive_ok=0;//处理数据完毕标志
}

Guess you like

Origin blog.csdn.net/Dustinthewine/article/details/131492162