Solved: Cannot get correct i2c data from ATmega8 into raspberry pi

I want to use an old ATmega8 as analog input converter for a raspberry pi to monitor the 5V power supply voltage.
To minimize hardware, the ATmega runs on 8MHz internal clock and is directly connected to the SDA and SCL pins on the raspberry using the latter's internal pullups.
I use the internal 1.1V reference and have a 10k - 2k2 voltage divider to the 5V.

The programs are very simple.
On the ATmega:

#include <Wire.h>

#define  I2C_ADDRESS 0x10        // ATMega8 I2C address
uint16_t adc_value = 0 ;         // Variables to store ADC result

void setup()
{   analogReference( INTERNAL ) ;
    Wire.begin( I2C_ADDRESS ) ;  // Initialize I2C as slave
    Wire.onRequest( sendADC ) ;  // Register function to send ADC value
}
void loop()
{   adc_value = analogRead( A0 ) ;
    delay( 100 ) ;               // Small delay to prevent excessive analog reads
}
void sendADC()                        
{   Wire.write( highByte( adc_value) ) ;        // send ADC value over I2C     
    Wire.write(  lowByte( adc_value) ) ;     
}

And on the Pi:

#!/usr/bin/python
import smbus
import time

I2C_ADDR = 0x10              # Arduino address
bus      = smbus.SMBus( 1 )  # Use I2C bus 1

while True:
    data      = bus.read_i2c_block_data( I2C_ADDR, 0, 2 )  # Read 2 bytes
    adc_value = (data[0] << 8) | data[1]                   # Combine high and low byte
    voltage   = adc_value * (6.1 / 1024)    # Convert ADC value to voltage
    print( f"ADC Value: {adc_value}, Voltage: {voltage:.3f}V")
    time.sleep( 1 )

For testing purposes, I did use the 3.3V of the Pi.
i2cdetect shows that the Pi does see the ATmega on address 10.
The problem is, that I get false readings.
The output shows: ADC Value: 235, Voltage: 1.400V
If I replace the ATmega8 with an Arduino nano and load the very same program, I do get the correct output ADC Value: 556, Voltage 3.312V
So the programs do work, but there seems to be a communication problem with the ATmega8.
I already lowered the i2c baudrate in config.txt to 10000 but nothing changed.
Any clues what I can do to solve the issue?

Solved: My mistake was that the ATmega8 doesn't have a 1.1V internal reference but a 2.56V reference.
Thus, it wasn't the i2c communication but the wrong formula to get the final voltage reading.

2 Likes

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.