For a course excercise I'm trying to run an example project of a counter running on an ATTiny and after transmitting the vaue to the Nano to show it on its serial monitor.
That code is just to bad to be used in a tutorial.
receiveEvent is called in interrupt context. As there interrupts are disabled you must not call any writing method of the Serial object as it depends on interrupts working to do it's stuff.
Additionally the master reads the data from the slave into a variable of type char which is a signed 8bit value. So if the sent value is turning from 127 to 128 it will change on the master from 127 to -127.
Slave codes should be like this following @pylon post#1:
#include <Wire.h>
volatile bool flag1 = false;
void setup()
{
 Wire.begin(8);         // join i2c bus with address #8
 Wire.onReceive(receiveEvent); // register event
 Serial.begin(9600);      // start serial for output
}
void loop()
{
 if(flqg1 == true)
 {
   byte x = Wire.read();
   Serial.println(x);  //will print all received values as 0, 1, 2, ...., 127, ..., 255
   flag1 = false;
 }
 //delay(100);
}
// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany)
{
  flag1 = true;
  //char c = Wire.read(); // receive byte as a character
  //Serial.print(c);     // print the character
 //}
// int x = Wire.read(); Â Â // receive byte as an integer
// Serial.println(x); Â Â Â Â // print the integer
}
pylon:
The Wire.read() can (and probably should) be executed in the interrupt routine but the rest (especially the serial output must be done in loop).
As people are saying that the interrupt context should be as short as possible, I have done the Wire.read() operation in the loop function. Apart from that I agree with you.
Thanks a lot for the input - I adapted the code but still the counter stops at 127 - seems that I'm missing something very basic here but I just don't get why it's doing what's it doing...
Code on the ATTiny:
#include <twi.h> #include <TinyWire.h>
void setup() {
pinMode(3, OUTPUT);
TinyWire.begin(); // join i2c bus (address optional for master)
}
Thanks a lot for the input - I adapted the code but still the counter stops at 127 - seems that I'm missing something very basic here but I just don't get why it's doing what's it doing...
What does "stops at 127" means? Does it freeze there? Does it start over after 127 with a value of 0?