#include <Wire.h> #include <SoftwareSerial.h> #define trigPin 3 #define echoPin 2 #define RX 1 #define TX 0 SoftwareSerial window(RX, TX); void setup() { pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); window.begin(9600); Wire.begin(); } void loop() { long duration, distance; digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); duration = pulseIn(echoPin, HIGH); distance = (duration/2) / 29.1; if(distance <= 10) { Wire.beginTransmission(8); Wire.write(1); Wire.endTransmission(); window.println("Human within 10cm"); } else if(distance > 10 && distance <=30) { Wire.beginTransmission(8); Wire.write(0); Wire.endTransmission(); window.println("Human within 30cm"); } delay(5000); }
#include <Wire.h> #define led1 3 void setup() { pinMode(led1, OUTPUT); Wire.begin(8); Wire.onReceive(receiveEvent); } void loop() { delay(100); } void receiveEvent() { int x = Wire.read(); if (x == 1) { digitalWrite(led1, HIGH); } else if (x == 0) { digitalWrite(led1, LOW); } }