Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Implementing I²C on an STM8S in IAR Embedded Workbench is reliable when you treat it as three separate jobs: verify the exact MCU pins and electrical bus, calculate timing from the actual peripheral clock, and follow the STM8S event-clearing and ACK sequences in RM0016. IAR builds and debugs the firmware; it does not fix pull-ups, addresses, timing registers, or bus faults.

Scope and prerequisites

This guide targets STM8S devices that actually include the I²C peripheral, such as selected STM8S003/103/105 variants. Confirm the complete part number, package, datasheet pinout, alternate-function settings, and errata before copying code. ST’s family documentation is available from STM8S series documentation and STM8S103/105 documentation.

  • Use a known peripheral input clock, not an assumed CPU frequency.
  • Assume a 7-bit slave address and external pull-ups unless your hardware documentation says otherwise.
  • Choose Standard mode (nominally 100 kHz) or Fast mode only after checking the exact device datasheet, rise time, voltage and bus capacitance.
  • Use timeouts in every polling loop.

Hardware: pins, pull-ups and voltage

Find SDA and SCL in the exact device datasheet. Family names do not guarantee identical pin mappings, and small packages may not expose every alternate-function pin. Configure those pins for the I²C-capable open-drain function required by that device; do not leave them as ordinary push-pull GPIO.

I²C lines are released high and require pull-up resistors. Check that both lines rise to the bus voltage, that all devices share ground, and that the voltage is within the STM8S and peripheral limits. Resistor selection depends on voltage, bus capacitance, speed and sink-current limits, so no single value is universal. A logic analyzer must use a threshold suitable for the actual voltage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Elebase USB to USB C Adapter for iPhone 18 Pro Max,USBC Car Charger Adapter
  • Read Before You Buy — No Video Output: These adapters support charging and USB 2.0 data transfer, but cannot transmit video signals. Except for standard USB webcams (which use USB data only), they are not compatible with HDMI/DisplayPort cables, video-capable USB-C hubs, or docking stations with video output.
  • Convert USB-A Ports to USB-C: Designed to connect USB-C earphones, cables, flash drives, card readers, and other USB-C accessories to standard USB-A ports. Plug-and-play with no drivers or software required.
  • Aluminum Alloy Housing: Built with a sturdy aluminum alloy shell that aids in heat dissipation and protects against daily wear and scratches. Designed to maintain a stable and secure connection.
  • Compact & Travel-Friendly: The ultra-compact design allows the adapter to stay plugged into your device without blocking adjacent ports or adding bulk, reducing wear and tear on your original USB ports.
  • 12-Month Warranty: Backed by a 12-month manufacturer warranty for peace of mind. Designed to meet strict quality control standards for reliable everyday performance.

What IAR does—and does not do

IAR Embedded Workbench supplies the STM8 compiler, linker, assembler, debugger and project environment; STM8 is listed as a supported architecture on IAR’s STM8 page and the Embedded Workbench product page. It does not configure board pull-ups, discover a slave address, select the correct pins, or replace the STM8 reference manual.

The public update page currently lists EWSTM8 3.11.4, published June 21, 2021: EWSTM8 updates. Verify the installed release before relying on menu labels or debugger behavior; do not assume STM8 receives updates on the same cadence as newer IAR toolchains.

Create and configure an EWSTM8 project

  1. Install EWSTM8 and select New Project for an STM8 C project.
  2. Select the exact target device, not a generic STM8 family.
  3. Add the application and I²C driver sources, then include the matching device header.
  4. Select the linker configuration that matches the device’s flash and RAM size.
  5. Set compiler optimization and runtime-library options appropriate to the product.
  6. Build and inspect the map file for code and RAM usage.
  7. Connect a supported debug probe and target board, then program and debug. IAR’s STM8/ST-LINK workflow is documented in this getting-started guide.

The IAR development guide is at EWSTM8 Development Guide; IDE details are in the EWSTM8 IDE Guide.

STM8S I²C peripheral model

The peripheral can operate as master or slave. In master mode, firmware generates START, sends an address and direction bit, transfers bytes MSB-first, handles ACK/NACK, and issues STOP. The principal registers are I2C_CR1, I2C_CR2, I2C_FREQR, I2C_DR, I2C_SR1, I2C_SR2, I2C_SR3, I2C_CCRL, I2C_CCRH and I2C_TRISER. The authoritative sequencing is in ST RM0016.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Calculate timing registers

Peripheral clock and FREQR

I2C_FREQR contains the I²C peripheral input clock in MHz. RM0016 specifies at least 1 MHz for Standard mode and 4 MHz for Fast mode. These are peripheral-clock requirements, not the desired SCL frequency. If the clock tree divides or switches the peripheral clock, use that actual value.

Standard mode

For Standard mode:

fSCL = fMASTER / (2 × CCR)
CCR = fMASTER / (2 × fSCL)

Rank #2
Anker USB-C Hub, 5-in-1 USB Hub for Laptops, 4K HDMI Multiport Adapter
  • 5-in-1 USB-C Hub: Experience comprehensive connectivity featuring a Power Delivery input, two USB-A 2.0 ports, a USB-A 3.0 port, and an HDMI port. (Note: The USB-C power delivery input port is only for connecting an external wall charger to power your laptop and cannot power peripheral devices.)
  • 90W Pass-Through Charging: Achieve optimal charging with 90W pass-through power to your laptop, supported by a total input of 100W, with the hub reserving 10W for operational efficiency. (Note: Wall charger not included.)
  • Quick Data Transfers: Accelerate your productivity with rapid data transfers using a high-speed 5Gbps USB 3.0 port and two 480Mbps USB 2.0 ports.
  • 4K HDMI Display: Enhance your visual experience with a hub capable of delivering 4K resolution at 30Hz in both mirror and extend modes. Please note that this hub is compatible with MacBook (macOS 12 and newer), Windows 10 and 11, ChromeOS, and laptops equipped with DP Alt Mode and Power Delivery. Note: This device is not compatible with Linux.
  • What You Get: Anker USB-C Hub (5-in-1, 4K HDMI), welcome guide, 18-month warranty, and our friendly customer service.

At 16 MHz and a nominal 100 kHz bus, CCR = 80 (0x50). At 8 MHz, CCR = 40 (0x28). RM0016 gives the 8 MHz example and specifies a minimum Standard-mode CCR of 0x04.

Fast mode

With DUTY = 0, fSCL = fMASTER / (3 × CCR); with DUTY = 1, fSCL = fMASTER / (25 × CCR). RM0016 describes the corresponding low/high ratios as 2:1 and 16:9. Check electrical limits and measured rise time before claiming 400 kHz operation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

TRISE

Use TRISE = maximum_allowed_rise_time / tMASTER + 1. At 8 MHz, tMASTER = 125 ns; using the 1000 ns Standard-mode maximum gives TRISE = 9 (0x09). At 16 MHz the same assumption gives 17. Program TRISE while PE = 0; these values are not universal constants.

Initialization order

  1. Configure the MCU clock and determine the I²C peripheral clock.
  2. Configure the selected SDA/SCL alternate-function GPIO mode.
  3. Verify pull-ups and voltage compatibility.
  4. Disable I²C while changing timing registers.
  5. Write I2C_FREQR, I2C_CCRL/I2C_CCRH and I2C_TRISER.
  6. Set ACK and interrupt policy.
  7. Enable the peripheral with I2C_CR1.PE.
  8. Confirm the bus is idle before START.
/* Register-level template; replace symbols with the selected device header. */
I2C_CR1 = 0x00;       /* PE = 0 while timing is programmed */
I2C_FREQR = 16;       /* actual peripheral clock, MHz */
I2C_CCRH = 0x00;      /* Standard mode, DUTY = 0 */
I2C_CCRL = 80;        /* 16 MHz, nominal 100 kHz */
I2C_TRISER = 17;      /* 16 MHz and 1000 ns rise-time assumption */
I2C_CR2 = 0x00;       /* no START or STOP yet */
I2C_CR1 = 0x01;       /* PE = 1 */

This is a template, not a universal driver. Confirm reset values, header symbols, pin mapping and errata for the selected part.

Addressing and a blocking master write

Keep the API unambiguous by accepting a 7-bit address:

uint8_t address_byte = (address7 << 1) | read_bit;

For example, a 7-bit address of 0x50 becomes wire byte 0xA0 for write and 0xA1 for read. Do not pass 0xA0 to a function that shifts its argument again.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Anker USB C Hub, 7in1 Multi-Port USB Adapter, 4K@60Hz USBC to HDMI Splitter
  • Sleek 7-in-1 USB-C Hub: Features an HDMI port, two USB-A 3.0 ports, and a USB-C data port, each providing 5Gbps transfer speeds. It also includes a USB-C PD input port for charging up to 100W and dual SD and TF card slots, all in a compact design.
  • Flawless 4K@60Hz Video with HDMI: Delivers exceptional clarity and smoothness with its 4K@60Hz HDMI port, making it ideal for high-definition presentations and entertainment. (Note: Only the HDMI port supports video projection; the USB-C port is for data transfer only.)
  • Double Up on Efficiency: The two USB-A 3.0 ports and a USB-C port support a fast 5Gbps data rate, significantly boosting your transfer speeds and improving productivity.
  • Fast and Reliable 85W Charging: Offers high-capacity, speedy charging for laptops up to 85W, so you spend less time tethered to an outlet and more time being productive.
  • What You Get: Anker USB-C Hub (7-in-1), welcome guide, 18-month warranty, and our friendly customer service.
  1. Wait for I2C_SR3.BUSY to clear, with a timeout.
  2. Set I2C_CR2.START and wait for I2C_SR1.SB.
  3. Read SR1, then write the 8-bit address byte to I2C_DR to clear the START event.
  4. Wait for address acknowledgment and clear ADDR using RM0016’s required status-register read sequence.
  5. For each byte, wait for TXE or the applicable transfer event, write I2C_DR, and check AF, BERR, ARLO and timeout.
  6. After the final transfer condition (typically TXE/BTF), set STOP and wait for BUSY to clear.

Never wait forever. Return a status such as OK, NACK, bus error, arbitration lost or timeout.

Master reads: ACK timing matters

One byte

  1. Generate START and send the address with the read bit.
  2. Disable ACK at the required point.
  3. Clear ADDR using the prescribed sequence.
  4. Set STOP immediately at the required point.
  5. Wait for RXNE, read I2C_DR, and verify the bus returns idle.

RM0016 warns that this sequence must complete before the current byte’s ACK pulse.

Multiple bytes

  • With more than two bytes remaining, continue ACKing received bytes.
  • With two bytes remaining, use the STM8S-specific POS/ACK sequence from RM0016.
  • For the final byte, disable ACK, clear ADDR at the required point, issue STOP, then read the byte.

A generic “read until RXNE” loop loses the final-byte timing and commonly produces a missing or extra byte.

Combined write/read transactions

Sensor-register and EEPROM accesses normally use one bus ownership sequence:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
START
slave address + write
register or memory address
REPEATED START
slave address + read
data bytes
NACK
STOP

Implement this as one combined-transfer operation. A repeated START is not equivalent to STOP followed by a new START; retaining ownership can be required by the peripheral being addressed.

Polling or interrupt-driven code?

Approach Best fit Trade-offs
Polling Bring-up, boot-time access and short, infrequent transfers Simple and traceable, but blocks the CPU and requires timeouts
Interrupt state machine Longer transfers, tight real-time work or concurrent activities Non-blocking, but more complex ACK/error sequencing

For interrupts, enable the appropriate buffer, event and error sources through I2C_ITR and use explicit states such as IDLE, START_SENT, ADDRESS_SENT, TRANSMIT_DATA, REPEATED_START, RECEIVE_DATA, SEND_STOP, COMPLETE, ERROR and RECOVERY. Keep blocking loops out of the ISR.

Rank #4
Sale
UGREEN USB to USB C Adapter Combo 4-Pack, 10Gbps USB C Converter Space Gray
  • Dual Converters, Infinite Potential:Includes 2× USB C male to USB A female adapters and 2× USB A male to USB C female adapters. Perfect for a wide range of uses—tablets with Bluetooth keyboards, expand USB ports on macbook, and more. Two different converters for all your daily needs
  • Next-Level 10Gbps & 3A Charging: No more slow 480Mbps, this usb to usb c adapter has a transfer speed of up to 10Gbps, allowing you to do more transferring in less time. This usb adapter fits both USB A and USB C charger, supporting up to 3A fast charging
  • Upgraded Exquisite Craftsmanship: With an aluminum alloy housing and metal connector, the usbc to usb adapter is extremely durable and sturdy. Rigorously tested to withstand more than 10,000 times of plugging and unplugging, ensuring long-lasting performance
  • Broad Compatible: The usb c to usb adapter widely supports all USB C/ USB A devices like laptops, tablets, cellphones, car chargers, and phone chargers. Such as compatible with MacBook Pro/Air 2023/2022, Thunderbolt 4/3 Devices,Apple MagSafe Watch 9/8/7/SE/Ultra, iPad Pro 2022/2021, Samsung Galaxy S23/S20/S10, and iPhone 17/16/15 Pro. Plug and play
  • Please Note: To reach 10Gbps speed, keep the cable under 3.3 ft. For USB A Male to USB C adapters, try flipping the USB C connector. USB C Male to USB A adapters support bidirectional 10Gbps transfer within 3.3 ft

Debug with a logic analyzer

Check the electrical bus before stepping through C: correct pins, common ground, pull-ups, voltage, and no device holding SDA or SCL low. A valid trace should show START, a 7-bit address plus R/W bit, ACK or NACK, data bytes with ACK/NACK, and STOP.

Flag Diagnostic meaning
SB START completed; write the address to DR
ADDR Address phase completed; clear with the prescribed reads
TXE Transmit register empty
RXNE Received byte available
BTF Byte transfer finished; timing matters before STOP or the next byte
AF NACK, often wrong address, direction, absent device or intentional slave NACK
BERR Illegal START/STOP or electrical disturbance
ARLO Arbitration lost
OVR Overrun or underrun
BUSY Bus occupied or physically stuck

Record SR1, SR2, SR3, CR1, CR2, FREQR, CCRL, CCRH and TRISER when an operation fails. Compare the first failing flag with the waveform to separate GPIO, address, event-clearing, direction and STOP problems.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Failure modes and recovery

Immediate AF

Verify 7-bit versus shifted address, the R/W bit, address-select pins, device power/reset state and wiring. A public API that accepts only address7 prevents double shifting.

BUSY stuck or lines low

Inspect SDA and SCL physically. A slave may be stretching SCL, or a reset may have left it expecting clocks. On timeout, disable I²C, preserve status registers, recheck line levels, optionally pulse SCL as GPIO if the hardware permits, issue a recovery STOP-like sequence, reinitialize and report an error.

Wrong frequency or intermittent NACKs

Recalculate FREQR from the actual peripheral clock, CCR from the selected mode and target rate, and TRISE from rise time. Measure SCL rather than trusting constants copied from another clock configuration.

Stalled transfer or missing first byte

Check that START and ADDR are cleared exactly as RM0016 specifies. Reading the wrong status registers, or reading them in the wrong order, can leave SCL held low or discard the first data byte.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Anker USB C Hub, 5-in-1 USBC to HDMI Splitter with 4K Display
  • 5-in-1 Connectivity: Equipped with a 4K HDMI port, a 5 Gbps USB-C data port, two 5 Gbps USB-A ports, and a USB C 100W PD-IN port. Note: The USB C 100W PD-IN port supports only charging and does not support data transfer devices such as headphones or speakers.
  • Powerful Pass-Through Charging: Supports up to 85W pass-through charging so you can power up your laptop while you use the hub. Note: Pass-through charging requires a charger (not included). Note: To achieve full power for iPad, we recommend using a 45W wall charger.
  • Transfer Files in Seconds: Move files to and from your laptop at speeds of up to 5 Gbps via the USB-C and USB-A data ports. Note: The USB C 5Gbps Data port does not support video output.
  • HD Display: Connect to the HDMI port to stream or mirror content to an external monitor in resolutions of up to 4K@30Hz. Note: The USB-C ports do not support video output.
  • What You Get: Anker 332 USB-C Hub (5-in-1), welcome guide, our worry-free 18-month warranty, and friendly customer service.

Works at 100 kHz but not Fast mode

Measure edge rise time, verify pull-up strength and capacitance, and confirm the exact MCU datasheet permits the selected conditions. Fast-mode formulas and peripheral support do not override electrical limits.

Register driver, library or bit-banging?

Direct registers

Register code exposes the STM8S flag-clearing order and avoids dependence on legacy library assumptions, but it is verbose and header-specific.

ST peripheral library or examples

Libraries can speed initial development, yet packages may target another device or compiler and may hide mandatory event sequences. ST’s software documentation, including material such as AN2737, is indexed at STM8 embedded-software documentation. Verify every function’s address convention and exact part support.

Bit-banged GPIO

Software I²C can be a fallback when pins or peripheral behavior make hardware I²C unsuitable, but it consumes CPU time and must still implement open-drain signaling, clock stretching, arbitration policy and recovery. Hardware I²C is normally preferable when the peripheral and pins are available.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When IAR is the right commercial choice

IAR is a sensible choice when an existing STM8 project, compiler ABI, debugger workflow or organizational standard requires it. IAR offers a free evaluation described at its free-trials page; the page states that evaluations last 14 days and include non-commercial-use restrictions and other limitations. For a new, cost-sensitive project, verify current pricing, support terms, device coverage and probe compatibility before committing.

Frequently Asked Questions

Should an STM8S I²C function accept a 7-bit or 8-bit address?

Prefer a 7-bit address in the public API and shift it internally, adding the read/write bit exactly once.

Are CCR and TRISE values portable between STM8S projects?

No. They depend on the actual peripheral clock, bus mode, target SCL rate, duty cycle and rise time.

Why does the bus hang after the address phase?

Common causes are incorrect ADDR-clearing reads, a missing ACK, a slave stretching SCL, or a physically held-low line.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.