I2C Issue

Hello,

For a school project I am using a I2C configuration where an Arduino Uno sends some simple commands to Arduino Nano’s. I’m trying to send some simple 1’s and 2’s but I can’t figure it out.

I have it set up so when I press button 1 it should send “1” to the slave and when I press button 2 it should send “2”. When I open the serial monitor and check what it send through, it sends 2 when I haven’t got any buttons pressed and 0 when I press button 1.

Does anybody have an idea what the issue is?

master code

#include <Wire.h>
int s1;
int s2;
int button1 =3;
int button2 =5;
int x = 0;

void setup() 
{
  pinMode(button1, INPUT_PULLUP);
  pinMode(button2, INPUT_PULLUP);
  Wire.begin(); 
  Serial.begin(9600);
}

void loop() 
{
s1 =  digitalRead(button1);
s2 =  digitalRead(button2);
  Wire.beginTransmission(9);
  Wire.write(x);
  Wire.endTransmission();
  x++;
  delay(100);
  Serial.println(x);
  
  if (s1 == HIGH)
  {
  x = 1;
  delay(100);
  }
  
  if (s2 == HIGH) 
  {
  x = 2;
  delay(100);
  }

  if (s1 == LOW)
  {
  x = 0;
  delay(100);
  }

  if (s2 == LOW) 
  {
  x = 0;
  delay(100);
  }
}

Slave code

#include <Wire.h>
int LED = 13;
int x = 0;

void setup() 
{
  pinMode (LED, OUTPUT);
  Wire.begin(9); 
  Wire.onReceive(receiveEvent);
  Serial.begin(9600);
}
  
void receiveEvent(int bytes) 
{
  x = Wire.read();
}
void loop() 
{
  Serial.println(x);
  if (x == '1') {
    digitalWrite(LED, HIGH);
    delay(1000);
    digitalWrite(LED, LOW);
    delay(0);
  }
  
  if (x == '2') {
    digitalWrite(LED, HIGH);
    delay(1000);
    digitalWrite(LED, LOW);
    delay(500);
  }
}

I’ve used this instructables page as guide

When I open the serial monitor and check what it send through, it sends 2 when I haven't got any buttons pressed and 0 when I press button 1.

Does anybody have an idea what the issue is?

Take paper and pencil and write down the value of x and s1 and s2 at every line of your code for different button conditions. You will see that it is doing exactly as expected.

Remember, that with INPUT_PULLUP, the pins will read HIGH when the button is not pressed