Connect GND, SDA and SCL between the STM32 and other microcontroller.
STM32 slave
#include<Wire.h>volatileint val;voidincomingData(int n) {digitalWrite(PC13, HIGH); val =Wire.read(); Serial.println(val); digitalWrite(PC13, LOW);}voidsetup() {Wire.setSDA(PB7);Wire.setSCL(PB6);Wire.begin(9); // join i2c bus with address #9Wire.onReceive(incomingData); // register eventSerial.begin(115200);}voidloop() {if (val >10) {// do something }}
Master writer
Example from the wire.h library
// Wire Master Writer// by Nicholas Zambetti <http://www.zambetti.com>// Demonstrates use of the Wire library// Writes data to an I2C/TWI slave device// Refer to the "Wire Slave Receiver" example for use with this// Created 29 March 2006// This example code is in the public domain.#include<Wire.h>int led = LED_BUILTIN;voidsetup(){pinMode(led, OUTPUT); Wire.begin(); // join i2c bus (address optional for master)}byte val =0;voidloop(){digitalWrite(led, HIGH); // briefly flash the LEDWire.beginTransmission(9); // transmit to device #9Wire.write(val); // sends one byteWire.endTransmission(); // stop transmittingdigitalWrite(led, LOW); val++;delay(500);}