Components Needed:
1. Two Arduino boards (e.g., Arduino Uno)
2. Switch (e.g., push-button)
3. Potentiometer
4. LED
5. Servo motor
6. Resistor (appropriate value for the LED, typically 220 ohms)
7. Resistor (10k ohms for the pull-down resistor for the switch)
8. Connecting wires
Wiring:
Arduino 1 (Master):
• Connect the switch:
o One terminal to digital pin 2.
o The other terminal to GND.
o A 10k ohm resistor between digital pin 2 and GND.
• Connect the potentiometer:
o Middle pin to A0 (analog input).
o Other two pins to 5V and GND.
• Connect SDA (A4 on Uno) to SDA on Arduino 2.
• Connect SCL (A5 on Uno) to SCL on Arduino 2.
• Connect GND on Arduino 1 to GND on Arduino 2.
Arduino 2 (Slave):
• Connect the LED:
o One end to a digital pin (e.g., D9) through a resistor.
o The other end to GND.
• Connect the servo motor:
o Signal pin to a digital pin (e.g., D10).
o VCC to 5V.
o GND to GND.
• Connect SDA (A4 on Uno) to SDA on Arduino 1.
• Connect SCL (A5 on Uno) to SCL on Arduino 1.
• Connect GND on Arduino 2 to GND on Arduino 1.
Code:
Master (Arduino 1):
cpp
Copy code
#include <Wire.h>
const int switchPin = 2;
const int potPin = A0;
void setup() {
pinMode(switchPin, INPUT_PULLUP); // Set switch pin as input
with internal pull-up resistor
Wire.begin(); // join I2C bus as master
Serial.begin(9600);
}
void loop() {
int switchState = digitalRead(switchPin); // Read switch
state
int potValue = analogRead(potPin); // Read potentiometer
value
// Print values to Serial Monitor
Serial.print("Switch State: ");
Serial.println(switchState);
Serial.print("Potentiometer Value: ");
Serial.println(potValue);
// Send values via I2C
Wire.beginTransmission(8); // transmit to device #8
Wire.write(switchState); // send switch state
Wire.write(highByte(potValue)); // send high byte of
potentiometer value
Wire.write(lowByte(potValue)); // send low byte of
potentiometer value
Wire.endTransmission(); // stop transmitting
delay(500);
}
Slave (Arduino 2):
cpp
Copy code
#include <Wire.h>
#include <Servo.h>
const int ledPin = 9;
const int servoPin = 10;
Servo myServo;
int switchState = 0;
int potValue = 0;
void setup() {
pinMode(ledPin, OUTPUT);
myServo.attach(servoPin);
Wire.begin(8); // join I2C bus with address #8
Wire.onReceive(receiveEvent); // register event
Serial.begin(9600);
}
void loop() {
// Control LED based on switch state
if (switchState == HIGH) {
digitalWrite(ledPin, LOW); // LED off
} else {
digitalWrite(ledPin, HIGH); // LED on
}
// Control servo based on potentiometer value
int servoPosition = map(potValue, 0, 1023, 0, 180); // Map
potentiometer value to servo position
myServo.write(servoPosition); // Set servo position
delay(100);
}
void receiveEvent(int howMany) {
if (howMany >= 3) { // Ensure at least 3 bytes received
switchState = Wire.read(); // receive switch state
potValue = (Wire.read() << 8) | Wire.read(); // receive
high and low bytes of potValue
}
}