cancel
Showing results for 
Search instead for 
Did you mean: 

Please correct my function ?

antonius
Senior

Dear Member,

I'm confused between pointer and array,

Please correct me :

void sim7600_modem(char *SIM_TxBuffer)

{

   printf("sim7600_modem ATI\r\n");

   //Clear buffer

   HAL_UART_Transmit_IT(&huart1,(uint8_t*)&aTxBuffer4, sizeof(aTxBuffer4));

   HAL_Delay(5);

   HAL_UART_Transmit_IT(&huart1,(uint8_t*)SIM_TxBuffer, sizeof(SIM_TxBuffer));

   HAL_UART_Receive_IT(&huart1, (uint8_t *)&SIM900.rxBuffer,1);

}   

on main :

sim7600_modem("ATI\r");

thanks

4 REPLIES 4
S.Ma
Principal

char *SIM_TxBuffer;

sizeof(aTxBuffer))

strings are null terminated, use it to calc the length.

Compiler will not simply even if main is in the same code file as the function...

JChau
Associate II

I don't know how do you manage aTxBuffer, but I suspect that may be another point of failure.

First, Array is not pointer, pointer is not array

char* a = "Test string", int* b;
sizeof(a) // is 4
sizeof(b) // is also 4
//sizeof gives you size of the pointer, not the data it points to
char c[] = "Test string";
sizeof(c) // is 12, it is the same as sizeof(char[12]), which is size of the array itself
strlen(a) //is 12 too, this is a function that counts the length of a string

You can simply replace sizeof(SIM_TxBuffer) with strlen(SIM_TxBuffer) for simpler code, but I prefer passing length as a parameter for better optimization on constant length commands.

void sim7600_modem(char *SIM_TxBuffer, size_t length)
{
   printf("sim7600_modem ATI\r\n");
   //Clear buffer
   HAL_UART_Transmit_IT(&huart1,(uint8_t*)&aTxBuffer4, sizeof(aTxBuffer4));
   HAL_Delay(5);
   HAL_UART_Transmit_IT(&huart1,(uint8_t*)SIM_TxBuffer, length);
 
   HAL_UART_Receive_IT(&huart1, (uint8_t *)&SIM900.rxBuffer,1);
}   
 
const char command[] = "ATI\r";
sim7600_modem(command, sizeof(command));

const char command[] = "ATI\r";

can not be changed to variables ?

I do not quite understand what do you mean cannot be changed to variables, if it cannot be a variable, you can do either

sim7600_modem("ATI\r", 4);

or just use strlen()

#include <string.h>
void sim7600_modem(char *SIM_TxBuffer)
{
   printf("sim7600_modem ATI\r\n");
   //Clear buffer
   HAL_UART_Transmit_IT(&huart1,(uint8_t*)&aTxBuffer4, sizeof(aTxBuffer4));
   HAL_Delay(5);
   HAL_UART_Transmit_IT(&huart1,(uint8_t*)SIM_TxBuffer, strlen(SIM_TxBuffer));
 
   HAL_UART_Receive_IT(&huart1, (uint8_t *)&SIM900.rxBuffer,1);
}   

but to my understanding, even you simply supply a constant ("ATR\r"), compiler will still convert it to a variable because, well, that string still need a place to be stored, so

sim7600_modem("ATI\r", 4);

will still be compiled as something like

const _A = "ATI\r";
const _B = 4;
sim7600_modem(_A, _B);