LED Brightness Control Using I2C

Solving Approach

How do you plan to solve it?

  1. Read the ADC value obtained from pot and store it in 8 bit array of size '2'. Store lower 8 bits in 0th position and upper 2 bits in 1st position.
  2. Trasmit the data from Master to slave, sending upper bits followed by lower bits.
  3. On Slave, the data is received and reconfigured into 10 bit form.
  4. The received and rebuilted adc value is displayed on Serial monitor and LED brightness is controlled by converting adc range into 0 to 255 for PWM.

MASTER CODE: ARDUINO UNO:

#include <Wire.h>
#define pot A0

uint8_t adc_buffer[2];

void split_adc_val(uint16_t * adcval, uint8_t adc_buffer[]){
  adc_buffer[0] = (*adcval)&(0xFF); //Store first 8 bits in 0th position of the array.
  adc_buffer[1] = (*adcval)>>8 & (0x03); //Store remaining 2 bits in the 1st position of the array.
}

void setup(){
  Wire.begin();
  Serial.begin(9600);
  pinMode(pot, INPUT);
}

void loop(){
  uint16_t adcval = analogRead(pot);
  split_adc_val(&adcval, adc_buffer);

  //Start transmission of the data:
  Wire.beginTransmission(0x0F);
  Wire.write(adc_buffer[1]); //Send upper 2 bits first
  Wire.write(adc_buffer[0]); //Send lower 2 bits afterwards.
  Wire.endTransmission();
  delay(5);

  Serial.println("Data Transmitted Successfully");
  delay(2000);
}

SLAVE CODE: ARDUINO UNO:

#include <Wire.h>
#define led 6

uint8_t data_buffer[2] = {0x00, 0x00};
bool avai = false;

void setup(){
  Wire.begin(0x0F);
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  Wire.onReceive(receive_fn);
}

void loop(){
  if(avai){
    uint16_t adc_ten_bit = 0x0000;
    adc_ten_bit |= data_buffer[0]; //Load lower 8 bits
    adc_ten_bit |= data_buffer[1] << 8; //Load upper 2 bits.
    Serial.println("ADC value received is : " +String(adc_ten_bit));
    analogWrite(led, (adc_ten_bit*255/1023));
    //Clear the data:
    data_buffer[0] = 0x00;
    data_buffer[1] = 0x00;
    avai = false;
  }
}

void receive_fn(int bytes){
  if(bytes == 2){ //Checks whether the data is received correctly or not.
    data_buffer[1] = Wire.read();
    data_buffer[0] = Wire.read(); 
    avai = true;
  }
}

Photo of Output

Upvote
Downvote

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!