#include //for i2c #include #define drawer_pin 5 //digital input pin #define servo_pin 10 //pwm servo pin #define lock_pin A0 //analog input pin hall sensor #define address_i2c 8 //address bus #define lockthreshold 20 //hall sensor analogue reading threshold #define closepos 20 //servo position closing (block inserted) #define openpos 160 //posizione servo opening (block not inserted) Servo moveLock; // create servo object to control a servo char todo = 'a'; void setup() { Wire.begin(address_i2c); // join i2c bus with address #8 Wire.onReceive(receiveEvent); // register event Wire.onRequest (requestEvent); Serial.begin(115200); // start serial for output Serial.println("Start..."); pinMode (drawer_pin, INPUT); //drawer pin (switch digital input) moveLock.attach(servo_pin); // attaches the servo on pin 10 to the servo object if (drawer() && isLock()) { //initial check to see if it is closed closed(); //move servo motor } else { opened(); //move servo motor todo = 'a'; } } void loop() { switch (todo) { case 'a': //drawer is open and must be closed if (drawer ()) { if (isLock ()) { closed(); todo = '0'; // nothing } } break; case 'b': //The drawer has just opened because the master has told him to do it. and must not close up if ( isLock() == false ) { //do it if the block has been removed todo = 'a'; //make sure that you check whether it should close or not } break; default: break; } delay(100); } //he does it when something is sent to him from the master void receiveEvent(int howMany) { String cmd = ""; //buffer while (Wire.available()) { //if there is at least one byte to read he performs. - 0 lockthreshold); //the more I'm getting closer, the more it increases } //turn servo motor to close void closed () { moveLock.write(closepos); Serial.println("closed"); //write on the serial when it's closing, useful for verification } //turn servo motor to open void opened() { moveLock.write(openpos); Serial.println("opened"); //write on the serial when it's opening, useful for verification } //It's open? if is open: true, if is closed: false bool isOpen () { return (moveLock.read() == openpos); }