ian
June 25, 2025, 11:00am
1
I stumbled on a little “trick”, or rather something in the C language I did not know was possible.
uint8_t cmd[2] = {0x24, 0x00}; // Single shot measurement command
if (i2c_write(SHT3X_ADDRESS, cmd, sizeof(cmd))) {
return; // Error writing to the sensor
}
In the past I put e.g. I2C data into an array, and then included the array in the function call.
if (i2c_write(SHT3X_ADDRESS, (uint8_t[]){0x24, 0x00}, 2)) {
return; // Error writing to the sensor
}
I learned the constant character data can be packed directly into the function call like this, which I think is much easier to write and read.
1 Like
I think that’s a neat hack.
Non-standard coding practices feel cool.
However, this does have some downsides:
No symbolic name for that array, so debugger can’t show it to you.
sizeof(byte_array)
is not possible, so you have to manually update the size … making copy/paste errors more likely.
Perhaps something along the following lines:
static const uint8_t cmd[] = {0x24, 0x00};
if (i2c_write(SHT3X_ADDRESS, cmd, sizeof(cmd))) {
// ...
By excluding the size of the command array, copy/paste errors are less likely. Even better, give the array a better name, and put the commands all up in a single location:
static const uint8_t CMD_SINGLE_SHOT_MEASURE[] = { 0x24, 0x00 };
static const uint8_t CMD_SOMETHING_ELSE[] = { ... };
Then the code is almost documents itself.
2 Likes
ian
June 25, 2025, 11:13am
3
Yeah, you’re right, this is much cleaner for writing drivers.
1 Like