ATtiny85 Light Sensor – I2C slave device

I love AVR ATtinyx5 series microcontrollers. They are cheap, easy to use, they can be programmed just like Arduinos and comparing to their size they offer great features. For example, they can be used as remote analog to digital converters connected to master device using I2C bus.
Background: few year ago I’ve build a weather station based on Raspberry Pi. It collects various data and displays them on dedicated web page and Android app. Every few months I try to add a new sensor to it. Last time it was a daylight sensor. Raspberry Pi does not offer ADC inputs and I has few ATtiny85 on hand that time. One to another, few hours later: photo resistor based daylight meter sensor connected via I2C bus.
Electric assembly is pretty simple: ATtiny85 directly connected to Raspberry Pi via I2C, photo resistor with 10kOhm pull down connected to ATtiny85 and signal LED.
ATtiny85 Light Sensor – I2C slave device
Code driving this rig is also pretty simple: watchdog timer wakes up ATtiny every few minutes, measures voltage, filters it and stores in memory. Every time read operation is requested, last filtered ADC value (10 bits as 2 bytes).
I2C support is provided by Tiny Wires library that configures USI as I2C slave.

 * This function is executed when there is a request to read sensor
 * To get data, 2 reads of 8 bits are required
 * First requests send 8 older bits of 16bit unsigned int
 * Second request send 8 lower bytes
 * Measurement is executed when request for first batch of data is requested
void request Event()
  Tiny Wires. send(i2c_regs[reg_ position]);
  reg_ position++;
  if (reg_ position >= reg_ size)
      reg_ position = 0;
 * Setup I2C
Tiny Wires. begin(I2C_SLAVE_ADDRESS);
Tiny Wires. on Request(request Event); //Set I2C read event handler

Example code to read from device might look like this:

<pre>`Wire. request From(0x13, 2);    // request 2 bytes from slave device #0x13

int i =0;
unsigned int readout = 0;

while (Wire. available()) { // slave may send less than requested
byte c = Wire. read(); // receive a byte as character

if (i == 0) {
    readout = c;
} else {
    readout = readout &lt;&lt; 8;
    readout = readout + c;


Serial. print(readout);

Read More: ATtiny85 Light Sensor – I2C slave device

Leave a Comment

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