Communicating Arduino and STM32 with Cubemx on I2C

Communicating Arduino and STM32 with Cubemx on I2C

Hello everyone, in this article we are going to see the communication between Arduino and STM32 over I2C communication protocol. We will use CubeMx and HAL library at STM32 side.

Let's get started.

Firstly let's configure STM side program. In this example we are going to use STM32F429ZI nucleo board. First create a CubeMx project with STM32F429ZI nucleo board and enable I2C hardware.

Below image you can see configuration of I2C: Cubemx Stm32f429 I2C enabling and configuration
Then create project. I am suing MDK uVision Keil MDK IDE for development.

In here we are in need of an char array to store incoming data from I2C and communication address value of I2C protocol.

I defined them inside Private Variables section like below:

/* USER CODE BEGIN PV */

#define ARDUINO_PRO_MICRO_I2C_RECEIVE_ADDRESS 0x33<<1
unsigned char ArduinoProMicroI2CData[50];

/* USER CODE END PV */
And in the while loop we need to make requests from Arduino:

while( HAL_I2C_Master_Receive(&hi2c1, ARDUINO_PRO_MICRO_I2C_RECEIVE_ADDRESS , ArduinoProMicroI2CData, 50, 100) != HAL_OK )
{ }
HAL_Delay(1000);

Until here our STM32 program is ready and now Arduinos turn.

Create an Arduino project and write below codes inside:

#include <Wire.h> 

#define DEVICE_ID 0x33 
int counter = 0;

void setup() {
  Wire.begin(DEVICE_ID);  
  Wire.onRequest(requestEvent); 

  Serial.begin(9600);
}

void loop() { }

void requestEvent()
{
  counter++;
  String data = "Counter from Arduino: " + String(counter);
  Serial.println(data);
  Wire.write(data.c_str());  
}
In here:
  • First we included Wire library
  • Then we initialized I2C communication protocol
  • Last created request handler to answer on I2C data requestion.

And lastly most important part of example. Do not forget the connection of Arduino and STM32.

Below list you can see the connections:
  • Arduino SCL STM32 PB6
  • Arduino SDA STM32 PB9
  • Arduino GND STM32 GND
  • Arduino 5V STM32 5V. (if you are connecting only one board over USB to your PC otherwise this step not required. )

And that is it.

Below image you can see the output of our example: Communicating Arduino and STM32 with Cubemx on I2C Example output

That is all in this article.

Have a great communication.

Burak Hamdi TUFAN


Tags


Share this Post

Send with Whatsapp

Post a Comment

Success! Your comment sent to post. It will be showed after confirmation.
Error! There was an error sending your comment. Check your inputs!

Comments

  • There is no comment. Be the owner of first comment...