STMicroelectronics STM8 Manual page 116

Table of Contents

Advertisement

BH1750_write(power_down);
s--;
}
lux_value >>= 3;
return ((unsigned int)lux_value);
}
Explanation
Firstly both the CPU and peripheral clocks are set. Note the CPU is slower than last few examples. This
has no significance.
CLK_HSIPrescalerConfig(CLK_PRESCALER_HSIDIV8);
CLK_SYSCLKConfig(CLK_PRESCALER_CPUDIV2);
....
....
CLK_PeripheralClockConfig(CLK_PERIPHERAL_I2C, ENABLE);
I2C I/Os are set as open drain outputs because they have external pull-up resistors that terminate the
bus I/Os to VDD lines. SCL pin is always an output from host microcontroller's end however SDA pin's
direction varies with reading and writing operations. This is automatically done by the I2C hardware.
GPIO_DeInit(GPIOB);
GPIO_Init(GPIOB, GPIO_PIN_4, GPIO_MODE_OUT_OD_HIZ_FAST);
GPIO_Init(GPIOB, GPIO_PIN_5, GPIO_MODE_OUT_OD_HIZ_FAST);
I2C setup has many parameters to set, firstly the I2C bus clock speed, then its own ID, clock duty
cycle, address mode, acknowledgement type and clock speed of the peripheral. Here the own ID and
slave ID are both set same because we are not using our STM8 as a slave. It doesn't matter. You can
also set something else.
void I2C_setup(void)
{
I2C_DeInit();
I2C_Init(100000,
BH1750_addr,
I2C_DUTYCYCLE_2,
I2C_ACK_CURR,
I2C_ADDMODE_7BIT,
(CLK_GetClockFreq() / 1000000));
I2C_Cmd(ENABLE);
}
If you have used compilers with built-in I2C library before then you may get some hiccups studying
the following part. This is because those built-in libraries accomplish many tasks in the background
that you never felt necessary. Flags and acknowledgments are such stuffs that are mostly
automatically dealt by the compiler and ignore by most users. Personally, I had to struggle with these
before settling this code. Another big difference is fact that the SPL's functions, their operations and
nomenclatures for I2C are different than most I2C libraries one has seen before. Lastly, I2C examples
with STM's SPL on the internet are rare and most of them demonstrate I2C example with 24 series
EEPROMs only. I wanted to do something different and so I used BH1750 I2C digital sensor instead of
repeating another EEPROM example.

Advertisement

Table of Contents
loading
Need help?

Need help?

Do you have a question about the STM8 and is the answer not in the manual?

Questions and answers

Table of Contents

Save PDF