Add const to pointers to avoid accidental modification of input-only data

Publisher:Blissful444Latest update time:2021-11-04 Source: eefocusKeywords:Pointer Reading articles on mobile phones Scan QR code
Read articles on your mobile phone anytime, anywhere

1. Use proteus to draw a simple circuit diagram for subsequent simulation

2. Programming


/********************************************************************************************************************

---- @Project: Pointer

---- @File: main.c

---- @Edit: ZHQ

---- @Version: V1.0

---- @CreationTime: 20200809

---- @ModifiedTime: 20200809

---- @Description:

---- The baud rate is: 9600.

---- Communication protocol: EB 00 55 XX YY  

---- Sort the 5 random data from large to small using the bubble method.

---- Through the computer serial port debugging assistant, send the EB 00 55 08 06 09 05 07 command to the microcontroller, where EB 00 55 is the data header, and 08 06 09 05 07 is the 5 random raw data involved in the sorting. After receiving the command, the microcontroller will return 13 data. The first 5 data are the sorting results of the first method, and the middle 3 data EE EE EE are the dividing lines between the first and second methods. For the convenience of observation, there is no practical meaning. The last 5 data are the sorting results of the second method.

----

---- For example, computer sends: EB 00 55 08 06 09 05 07

---- The MCU returns: 09 08 07 06 05 EE EE EE 09 08 07 06 05 

---- Microcontroller: AT89C52

****************************************************************************************************************************/

#include "reg52.h"

/*——————Macro definition——————*/

#define FOSC 11059200L

#define BAUD 9600

#define T1MS (65536-FOSC/12/500) /*0.5ms timer calculation method in 12Tmode*/

 

#define const_array_size 5 /* The size of the array involved in sorting*/

 

#define const_voice_short 19 /*Duration of the buzzer short call*/

#define const_rc_size 10 /*Buffer array size for receiving serial port interrupt data*/

 

#define const_receive_time 5 /*If no serial data comes in after this time, it is considered that a string of data has been received. This time can be adjusted according to the actual situation*/

 

/*——————Variable function definition and declaration——————*/

/*Buzzer driver IO port*/

sbit BEEP = P2^7;

/*LED*/

sbit LED = P3^5;

 

unsigned int uiSendCnt = 0; /*Timer used to identify whether the serial port has received a string of data*/

unsigned char ucSendLock = 1; /*Self-locking variable of the serial port service program, each time a string of data is received, it is only processed once*/

unsigned int uiRcregTotal = 0; /*Indicates how much data the current buffer has received*/

unsigned char ucRcregBuf[const_rc_size]; /*buffer array for receiving serial port interrupt data*/

unsigned int uiRcMoveIndex = 0; /*Intermediate variable used to parse data protocol*/

 

unsigned int uiVoiceCnt = 0; /*Buzzer beeping duration counter*/

 

unsigned char ucUsartBuffer[const_array_size]; /* The original data received from the serial port that needs to be sorted*/

unsigned char ucGlobalBuffer_3[const_array_size]; /* The third method, the global variable array involved in the specific sorting algorithm*/

unsigned char ucGlobalBuffer_4[const_array_size]; /* The fourth method is used to receive the global variable array of output interface data*/

 

/**

* @brief Timer 0 initialization function

* @param None

* @retval initialize T0

**/

void Init_T0(void)

{

TMOD = 0x01; /*set timer0 as mode1 (16-bit)*/

TL0 = T1MS; /*initial timer0 low byte*/

TH0 = T1MS >> 8; /*initial timer0 high byte*/

}

 

/**

* @brief Serial port initialization function

* @param None

* @retval initialize T0

**/

void Init_USART(void)

{

SCON = 0x50;

TMOD = 0x21;                    

TH1=TL1=-(FOSC/12/32/BAUD);

}

 

/**

* @brief peripheral initialization function

* @param None

* @retval Initialize peripheral

* Transfer the contents displayed by the digital tube to the following variable interfaces to facilitate the writing of higher-level window programs in the future.

* Simply change the content of the corresponding variables below to display the numbers you want.

**/

void Init_Peripheral(void)

{

ET0 = 1;/*Enable timer interrupt*/

TR0 = 1;/*Start timing interrupt*/

TR1 = 1;

ES = 1; /*Enable serial port interrupt*/

EA = 1;/*Open the general interrupt*/  

}

 

/**

* @brief initialization function

* @param None

* @retval initialize the MCU

**/

void Init(void)

{

LED = 0;

Init_T0();

Init_USART();

}

/**

* @brief delay function

* @param None

* @retval None

**/

void Delay_Long(unsigned int uiDelayLong)

{

   unsigned int i;

   unsigned int j;

   for(i=0;i   {

      for(j=0;j<500;j++) /*Number of empty instructions in the embedded loop*/

          {

             ; /*A semicolon is equivalent to executing an empty statement*/

          }

   }

}

/**

* @brief delay function

* @param None

* @retval None

**/

void Delay_Short(unsigned int uiDelayShort)

{

  unsigned int i;

  for(i=0;i  {

; /*A semicolon is equivalent to executing an empty statement*/

  }

}

 

/**

* @brief Serial port sending function

* @param unsigned char ucSendData

* @retval Function that sends a byte to the host computer

**/

void eusart_send(unsigned char ucSendData)

{

ES = 0; /* Disable serial port interrupt */

TI = 0; /* Clear the serial port transmission completion interrupt request flag */

SBUF = ucSendData; /* Send one byte */

 

Delay_Short(400); /* The delay between each byte is very critical and is also the most prone to error. Please adjust the delay size according to the actual project*/

TI = 0; /* Clear the serial port transmission completion interrupt request flag */

ES = 1; /* Enable serial port interrupt */

}

 

 

/**

* @brief Method 3

* @param p_ucInputBuffer p_ucOutputBuffer

* @retval 

* The third method, in order to improve the user experience of the second method, uses a pointer to add an array output interface to the function.

* In this way, the function's array has both input interface and output interface, which is perfect.

* In this program, *p_ucInputBuffer is the input interface, and *p_ucOutputBuffer is the output interface.

* All pointers used as input interfaces should be marked with the const tag, which can turn the original bidirectional interface into a unidirectional interface. It has two advantages:

* First: If you are using a function that has been packaged by someone else, and you find that the interface pointer has a const label, it is enough to explain

* This pointer can only be used as an input interface. When you use it, you don't have to worry about the input data being modified.

* Second: If you write your own function, you add a const tag to the pointer of the input interface, which can prevent you from writing the internal code of the function.

* Accidentally modify the input interface data. For example, if you try to add an instruction to modify the input interface data at the end of the following function,

* When you click Compile, it will fail to compile and an error message will appear: error C183: unmodifiable lvalue.

**/

void big_to_small_sort_3(const unsigned char *p_ucInputBuffer, unsigned char *p_ucOutputBuffer)

{

unsigned char i;

unsigned char k;

unsigned char ucTemp; /* In the process of exchanging data between two devices, it is used to temporarily store a variable to be exchanged*/

    unsigned char ucBuffer_3[const_array_size]; /* The third method, local variable array involved in the specific sorting algorithm*/

 

for(i = 0; i < const_array_size; i ++) /* Before participating in the sorting algorithm, move all the data of the input interface to the local variable array. */

{

ucBuffer_3[i] = p_ucInputBuffer[i];

}

 

/* Bubble method*/

for(i = 0; i < (const_array_size - 1); i ++) /* The number of bubbling is (const_array_size-1) times*/

{

for(k = 0; k < (const_array_size - 1 - i); k++)

{

if (ucBuffer_3[const_array_size - 1 - k] > ucBuffer_3[const_array_size - 1 - 1 - k])

{

ucTemp = ucBuffer_3[const_array_size - 1 - 1 - k];

ucBuffer_3[const_array_size - 1 - 1 - k] = ucBuffer_3[const_array_size - 1 - k];

ucBuffer_3[const_array_size - 1 - k] = ucTemp;

}

}

}

for(i = 0; i < const_array_size; i ++) /* After participating in the sorting algorithm, all the data of the calculation results are moved to the output interface to facilitate external program calls*/

{

p_ucOutputBuffer[i] = ucBuffer_3[i];

}

 

// /* 

// * The following is an instruction that attempts to modify the input interface data. If it is not blocked, an error will be prompted during compilation: error C183: unmodifiable lvalue?

// */

// p_ucInputBuffer[0] = 0; /* Instructions for modifying input interface data*/

}

 

/**

* @brief Method 4

* @param p_ucInputAndOutputBuffer 

* @retval 

* The fourth method: In the function interface, the pointer can be used as both input and output by nature. It is bidirectional, similar to the characteristics of global variables.

* We can directly merge the input interface and output interface together when necessary according to the actual project situation.

* The disadvantage of this method is that it does not separate input and output, which is not so intuitive. But the advantage is also obvious, that is,

* It saves program ROM capacity and data RAM capacity, and its operation efficiency is also faster. Now I will introduce it to you.

* *p_ucInputAndOutputBuffer of this program is the input and output interface.

**/

void big_to_small_sort_4(unsigned char *p_ucInputAndOutputBuffer)

{

unsigned char i;

unsigned char k;

unsigned char ucTemp; /* In the process of exchanging data between two devices, it is used to temporarily store a variable to be exchanged*/

 

/* Bubble method*/

for(i = 0; i < (const_array_size - 1); i ++) /* The number of bubbling is (const_array_size-1) times*/

{

for(k = 0; k < (const_array_size - 1 - i); k++)

{

if (p_ucInputAndOutputBuffer[const_array_size - 1 - k] > p_ucInputAndOutputBuffer[const_array_size - 1 - 1 - k])

{

ucTemp = p_ucInputAndOutputBuffer[const_array_size - 1 - 1 - k];

p_ucInputAndOutputBuffer[const_array_size - 1 - 1 - k] = p_ucInputAndOutputBuffer[const_array_size - 1 - k];

p_ucInputAndOutputBuffer[const_array_size - 1 - k] = ucTemp;

}

}

}

}

 

/**

* @brief Serial port service program

* @param None

* @retval 

* The following function shows that multiple return statements can be inserted into an empty function.

[1] [2]
Keywords:Pointer Reference address:Add const to pointers to avoid accidental modification of input-only data

Previous article:The fifth benefit of pointers: pointers act as a transit station in many arrays
Next article:The fourth benefit of pointers is that pointers serve as input and output interfaces for arrays in functions.

Latest Microcontroller Articles
Change More Related Popular Components

EEWorld
subscription
account

EEWorld
service
account

Automotive
development
circle

About Us Customer Service Contact Information Datasheet Sitemap LatestNews


Room 1530, 15th Floor, Building B, No.18 Zhongguancun Street, Haidian District, Beijing, Postal Code: 100190 China Telephone: 008610 8235 0740

Copyright © 2005-2024 EEWORLD.com.cn, Inc. All rights reserved 京ICP证060456号 京ICP备10001474号-1 电信业务审批[2006]字第258号函 京公网安备 11010802033920号