Hackster is hosting Hackster Holidays, Ep. 7: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Friday!Stream Hackster Holidays, Ep. 7 on Friday!
Madhav Reddy
Published © GPL3+

I2C Communication between Arduino and Raspberry Pi

Have a successful connection between Arduino and Raspberry Pi using I2C Communication Protocol.

BeginnerProtip1 hour44,488
I2C Communication between Arduino and Raspberry Pi

Things used in this project

Story

Read more

Schematics

Circiut Diagram

This circuit helps to connect components.

Code

Arduino Code

C/C++
This code is should be dumped to arduino which will read analog value from ldr on A0 pin and send it to Pi when it request
#include <Wire.h>  // Library which contains functions to have I2C Communication
#define SLAVE_ADDRESS 0x40 // Define the I2C address to Communicate to Uno

byte response[2]; // this data is sent to PI
volatile short LDR_value; // Global Declaration
const int LDR_pin=A0; //pin to which LDR is connected A0 is analog A0 pin  
void setup() {
  // put your setup code here, to run once:

  Serial.begin(9600);
  Wire.begin(SLAVE_ADDRESS); // this will begin I2C Connection with 0x40 address
  Wire.onRequest(sendData); // sendData is funtion called when Pi requests data
  pinMode(LDR_pin,INPUT);
}

void loop() {
  // put your main code here, to run repeatedly:
  
delay(1000);
}
void sendData(){
  LDR_value=analogRead(LDR_pin);
  // Arduino returns 10bit data but we need to convert it to 8bit 
  LDR_value=map(LDR_value,0,1023,0,255);
  response[0]=(byte)LDR_value;
  Wire.write(response,2); // return data to PI
}

Xaml Ui

C#
change your MainPage.xaml content with this
<Page
    x:Class="I2CComm.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:I2CComm"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Margin="20">
            <TextBlock Text="LDR Value from Arduino " FontSize="25"></TextBlock>
            <TextBlock Name="ldr_val" Text="This will change to value return" ></TextBlock>
        </StackPanel>
    </Grid>
</Page>

Raspberry Pi Code

Open .sln file and dump it to Raspberry

Credits

Madhav Reddy
1 project • 5 followers
I Am B.Tech Student and Have enthusiasm on Electronics and Software Projects Which Will Help people

Comments