Hey everyone, I have been working on a project that is supposed to move the servo motor back and forth one time per sensor detection to open then close a door. They sensor and motor are communicating through a NRF24L01 transceiver. The issue is that if the sensor detects something, it executes the code moving the servo multiple times at what seems like a random amount.
Transmitter code (has sensor):
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
RF24 radio(9, 10); // CE, CSN
const byte address[6] = "GDoor"; //Byte of array representing the address. This is the address where we will send the data. This should be same on the receiving side.
int inPin = 8;
boolean inPin_state = 0;
void setup() {
Serial.begin(9600);
pinMode(inPin, INPUT);
radio.begin(); //Starting the Wireless communication
radio.openWritingPipe(address); //Setting the address where we will send the data
radio.setPALevel(RF24_PA_MIN); //You can set it as minimum or maximum depending on the distance between the transmitter and receiver.
radio.stopListening(); //This sets the module as transmitter
}
void loop() {
if (digitalRead(inPin) == HIGH) {
inPin_state = HIGH;
}
else {
inPin_state = LOW;
}
radio.write(&inPin_state, sizeof(inPin_state)); //Sending the message to receiver
}
Receiver code (has servo):
#include <Servo.h>
#include <SPI.h>
#include <nRF24L01.h>
#include <RF24.h>
Servo myservo;
RF24 radio(9, 10); // CE, CSN
const byte address[6] = "GDoor";
boolean inPin_state = 0;
int pos = 0;
int outPin = 7;
void setup() {
pinMode(outPin, OUTPUT);
Serial.begin(9600);
radio.begin();
radio.openReadingPipe(0, address); //Setting the address at which we will receive the data
radio.setPALevel(RF24_PA_MIN); //You can set this as minimum or maximum depending on the distance between the transmitter and receiver.
radio.startListening(); //This sets the module as receiver
myservo.attach(8);
}
void loop() {
if (radio.available()) { //Looking for the data
radio.read(&inPin_state, sizeof(inPin_state)); //Reading the data
if (inPin_state == HIGH) {
digitalWrite(outPin, HIGH);
for (pos = 50; pos <= 120; pos += 1) {
myservo.write(pos);
delay(10);
}
delay(5000);
for (pos = 120; pos >= 50; pos -= 1) {
myservo.write(pos);
delay(10);
}
}
else {
digitalWrite(outPin, LOW);
}
}
}