Wire.h
library for I2C communication which enables the internal pull-up resistor( 20k to 50K ) by default.Note: While communicating with devices using the I2C communication protocol, pull-up resistors should be used. The value of pull-up resistors may vary depending on the devices used.
Wire.setClock(frequency);
. Maximum frequency is 400KHz for Arduino UNO.Let's do the hardware connection.
We need to develop two separate codes one for master and another for slave.
#include <Wire.h>
#define potPin A1
#define slaveAddress 0x08 // Slave address
uint16_t brightness;
uint8_t previousvalue;
uint8_t error;
void setup() {
// Initialize Arduino UNO as I2C master
Wire.begin();
Serial.begin(9600);
}
void loop() {
// It map the potentiometer value(0 to 1023) to PWM value(0 to 255) i.e 1023/255 = ~4
brightness = analogRead(potPin) / 4;
if (brightness != previousvalue) {
Wire.beginTransmission(slaveAddress);
Wire.write(brightness); // write data in i2c buffer
error = Wire.endTransmission(); // send brightness value using i2c
if (error == 0) {
Serial.println("Successful data transmission");
} else {
Serial.println("ERROR in data transmission");
}
previousvalue = brightness;
}
delay(10); // time duration for proper communication
}
#include <Wire.h>
#define slaveAddress 0x08
#define ledPin 9
void setup() {
// Initialize Arduino as I2C slave (Slave address is 0x08)
Wire.begin(slaveAddress);
Wire.onReceive(receiveEvent); // Attach a function to handle incoming data
pinMode(ledPin, OUTPUT);
}
void loop() {
}
// Function to handle incoming data
void receiveEvent(int bytes) {
while (Wire.available()){
int received = Wire.read(); // Read the incoming byte
analogWrite(ledPin, received); // Generate PWM signal, to control brightness of LED
}
}
Wire.write ()
; It is used to write potentiometer values mapped between 0 to 255 in I2C buffer.Wire.endTransmission();
It transmits the data from the I2C buffer and returns one of the following values:void receiveEvent(int bytes);
It is a callback function that handles the incoming data received from the master. So this function controls the brightness of LED as per potentiometer value using PWM.