blippy
Posts: 25
Joined: Fri Nov 03, 2017 3:07 pm

I2C misreads of ATTiny85 slave

Thu Sep 20, 2018 6:39 pm

I'm fairly new to all this, so please try to keep things within my realm of understanding.

I have set up an ATTiny85 (at 8MHz) as a slave. All it does is increment a counter each time it is called, and writes the counter out again. Here is the code:

Code: Select all

// Code for the ATtiny85
#define I2C_SLAVE_ADDRESS 0x4 // Address of the slave
 
#include <TinyWireS.h>
 
int i=0;
 
void setup()
{
    TinyWireS.begin(I2C_SLAVE_ADDRESS); // join i2c network
    //TinyWireS.onReceive(receiveEvent); // not using this
    TinyWireS.onRequest(requestEvent);
}
 
void loop()
{
    // This needs to be here
    TinyWireS_stop_check();
}
 
// Gets called when the ATtiny receives an i2c request
void requestEvent()
{
    TinyWireS.send(i);
    i++;
}
I then set up an Arduino to act as a test master. It asks the slave for a byte, and then prints it to serial:

Code: Select all

#include <Wire.h>
 
void setup()
{
 Wire.begin(); // join i2c bus (address optional for master)
 Serial.begin(9600); // start serial for output
}
 
void loop()
{
 Wire.requestFrom(4, 1); // request 1 byte from slave device address 4
 
while(Wire.available()) // slave may send less than requested
 {
 int i = Wire.read(); // receive a byte as character
 Serial.println(i); // print the character
 }
 
delay(500);
}
It outputs the numbers 0 to 255 consecutively, and repeats the cycle. So it looks like the ATTiny85 chip is doing exactly what it is supposed to do. HOWEVER ...

There are problems on the Pi3 side. I wire up the ATTiny85 to the Pi3, and run the following code:

Code: Select all

import smbus, time
bus = smbus.SMBus(1)
add = 0x4

while True:
	b = bus.read_byte(addr)
	print(b)
	time.sleep(0.08)
bus.close()
What happens is that Python prints out the numbers 0...127 repeatedly. So it looks like it is dropping the most significant bit. But there's another oddity: occasionally an anomalous number crops up, as in the sequence:
35
36
37
166
39
40
....

Notice that 38+256-166 = 128. Whenever there is an anomaly, a similar 128 difference arises. So it seems to be dropping the second-most significant bit on occasion.

I'm wondering if there are clock speed issues or something? And what to do about it? Maybe I have to fiddle around with pullup resistors or something? I tried doing that, but it didn't seem to help. Or maybe I should set my ATTiny85 to run at 1MHz?

Any ideas?

blippy
Posts: 25
Joined: Fri Nov 03, 2017 3:07 pm

Re: I2C misreads of ATTiny85 slave

Thu Sep 20, 2018 7:26 pm

OK. So I did a little tweak to config.txt to set the baudrate to 400000. This seems to fix the problem. The program reports numbers from 0...255, with no strange numbers cropping up.

So, what's the conclusion? That the I2C was reading slower than the ATTiny85 was sending out signals, thereby causing bytes to be corrupted?

Return to “Interfacing (DSI, CSI, I2C, etc.)”