Skip to main content
CGrov.1
Associate III
January 20, 2020
Question

Writing to slave i2c device always gets stuck. Compiles with no errors...

  • January 20, 2020
  • 2 replies
  • 857 views

I'm setting some registers on a slave device using the code bellow. The code compiles with no errors but gets stuck each time it tries to write to that register. What I want to do is loop through the for loop and set each register to it's corresponding value .

It always gets stuck at this part of the write command:

 while (__HAL_I2C_GET_FLAG(hi2c, Flag) == Status)

which I think means it is communicating, but if I use the same code but hard-code the register locations and data values it works fine, so I'm thinking it must be something to do with the way I'm handling those arrays.

My code segment:

void set_Regs(){
	//read register 0x07, check bit 7 or 0?
	int i=0;
	for(i=0; i<3; i++){
 
	uint8_t reg_addr[] = {0x08, 0x09, 0x0A};
	uint8_t reg_data[] = {0x08, 0x03, 0x01};
 
	uint8_t reg_point = reg_addr[i];
	uint8_t data_point = reg_data[i];
 
	if(HAL_I2C_Mem_Write(&hi2c1, (0x30<<1),reg_point,sizeof(reg_addr), (uint8_t*)(&data_point) , sizeof(reg_data), HAL_MAX_DELAY) != HAL_OK){
				Error_Handler();
				printf("Error Setting Registers \n\r");
			}
	}
 
}

This topic has been closed for replies.

2 replies

CFran.1
Associate III
January 20, 2020

Could it be the type casting and then using the address of the pointer? Trying just sending &data_point and not (uint8_t*)(&data_point). I have not used HAL, so I do not know the parameters of the function, but why do you pass the data_point by reference but the reg_point normally?

CGrov.1
CGrov.1Author
Associate III
January 20, 2020

Nope, same issue. I'm not sure why the compiler isn't showing any errors.

KnarfB
Super User
January 20, 2020

reg_addr and reg_data are arrays. therefore sizeof(reg_data) == sizeof(reg_addr) == 3. This is not what you intended. Try

HAL_I2C_Mem_Write(&hi2c1, (0x30<<1), &reg_addr[i], sizeof(reg_addr[i]), &reg_data[i], sizeof(reg_data[i]), 100);

A small but reasonable delay will timeout earlier which is good for diagnosis.

If you have working register level code, compare the registers.

If the debugger gets stuck in an endless loop, try instruction level stepping to see what's going on.

CGrov.1
CGrov.1Author
Associate III
January 21, 2020

Thank you! I didn't spot that. I got an error about argument 5 being made an integer without a cast but got it working with this:

if(HAL_I2C_Mem_Write(&hi2c1, (0x30<<1),reg_addr[i],sizeof(reg_addr[i]), (uint8_t*)(&reg_data[i]) , sizeof(reg_data[i]),100) != HAL_OK){