I2C communication

Communication between microcontroller and STM32

Connect GND, SDA and SCL between the STM32 and other microcontroller.

STM32 slave

#include <Wire.h>

volatile int val;

void incomingData(int n) 
{
  digitalWrite(PC13, HIGH); 
  val = Wire.read();            
  Serial.println(val);        
  digitalWrite(PC13, LOW);
}

void setup() {

  Wire.setSDA(PB7);
  Wire.setSCL(PB6);

  Wire.begin(9);                // join i2c bus with address #9
  Wire.onReceive(incomingData); // register event

  Serial.begin(115200);
}

void loop() {

  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;

void setup()
{
  pinMode(led, OUTPUT);  
  Wire.begin(); // join i2c bus (address optional for master)
}

byte val = 0;

void loop()
{
  digitalWrite(led, HIGH);    // briefly flash the LED
  Wire.beginTransmission(9);  // transmit to device #9
  Wire.write(val);              // sends one byte
  Wire.endTransmission();     // stop transmitting
  digitalWrite(led, LOW);

  val++;
  delay(500);
}

Check the Wire library documentation for more details

Last updated