STM32 Adventures – Communication using I2C


When working with STM32 using registries only it is important that you have REFERENCE MANUAL and DATASHEET available. We will use them a lot 🙂


 

Today we start with I2C communication protocol. Configuration of it might be a bit of tricky at the beginning gut I hope to explain to you what I have came across of when trying to get the protocol to work. For more details about I2C itself check out wiki .

Device address

Since I have worked with it I usually like to start off with defining address of the device that I’m working with ( or devices if you work with more than one ).

This has saved me many times from problems with wrong addressing and spending time troubleshooting something which is easy as above 🙂

Transmission flow

So now its time to dive back into RM. We need to find part about I2C. Since we will be building a master device we focus there (at least for now ). As you can see on image below its shows really nice what we must program. Specific events at specific point of transmissions ( for transmitter and receiver ). This makes it really easy to code against.

RMf407vgen_DM00031020_i2c_01

 

Configuration of peripherial

Let’s move on to configuration. What is important for you is to know that the code presented here is not using interrupts or DMA. Reason for this is slow build up of skills. I will document those later on and update the links in this post accordingly.

Let’s start by finding which PINs we need to configure. For that one I jump to DS and search for I2C1 (that one I want to use ) and checkout Alternate Function Mappings

DSF407VGen_DM00037051_af_i2c

 

So now I can choose even what suits me more 🙂 I will stick with PB6 and PB7. Below function will set those pins as alternate function, high speed , open drain and finally configure that we use AF4 for those pins.

If you have by any chance forgotten about RCC here is my routine which I used to enable all peripherals

Once hardware is ready we can configure the I2C registries.

Its quite easy here – we set freq of peripherial ( in my case it was 8Mhz ) then set clock rate ( which has simple formula ) and then we setup time rise. All of this is documented in RM and clearly explained.

The only thing that is left now is to read and write from the device.

Read using I2C

Writing using I2C

Summary

Code presented above has still work in progress as I need to add error control and timeouts – otherwise if something would go wrong now it would block whole uC

 


logo_github

 

Code for this exercise can be of course found at github https://github.com/RafPe/STM32F4DISCOVERY-I2C

 

 

 


 

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *