Hello i need some help with ultrasonic sensors by communition serial

SENDER

#include <NewPing.h>
#include <SoftwareSerial.h>

#define SONAR_NUM 4 // Number of sensors.
#define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.

NewPing sonar[SONAR_NUM] = { // Sensor object array.
NewPing(7, 6, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
NewPing(3, 2, MAX_DISTANCE),
NewPing(5, 4, MAX_DISTANCE),
NewPing(9, 8, MAX_DISTANCE)
};

#define SERIAL_RX 11
#define SERIAL_TX 10

SoftwareSerial mySerial(SERIAL_RX, SERIAL_TX);

void setup() {
Serial.begin(9600);
Serial.println("SDM-T3 Arduino Sender");
//mySerial.begin(4800);
}

void loop() {

// if (Serial.available())
for (uint8_t i = 0; i < SONAR_NUM; i++) { // Loop through each sensor and display results.
delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
Serial.print(i);
Serial.print("=");
Serial.print(sonar[i].ping_cm());
Serial.print("cm ");

}
Serial.println();
}

Receber

//#include <LiquidCrystal_I2C.h>
#include <Keypad.h>
#include <SPI.h>
#include <RFID.h>
#include <Servo.h>
#include <SoftwareSerial.h>

#define SERIAL_RX 10
#define SERIAL_TX 11
#define LED_PIN 13

SoftwareSerial mySerial(SERIAL_RX, SERIAL_TX);

RFID rfid(10, 9); //PIN10 liga SDA. PIN 9 liga RST
unsigned char status;
unsigned char str[MAX_LEN]; //comprimento do numero de serie

String accesso [1] = {"1171281215114"}; //numero de serie que dá acesso ao parque
int accessGrantedSize = 1; //numero de numeros de serie que dão acesso ao parque

Servo lockServo;
int lockPos = 10; //Servo Motor posição fechada
int unlockPos = 90; //Servo Motor posição aberta
boolean locked = true;
Servo lockServoOut;
int lockPosOut = 10; //Servo Motor saida posição fechada
int unlockPosOut = 90; //Servo Motor saida posição aberta
boolean lockedOut = true;
int redLEDPin = 15;
int greenLEDPin = 16;

const byte ROWS = 4; //NUMERO DE LINHAS DO TECLADO
const byte COLS = 3; //NUMERO DE COLUNAS DO TECLADO
char keys[ROWS][COLS] = { //DECLARAÇÃO DOS NUMEROS, LETRAS E CARACTERES DO TECLADO
{'1','2','3'},
{'4','5','6'},
{'7','8','9'},
{'*','0','#'},
};
byte rowPins[ROWS] = {2, 3, 4, 5 }; // PINOS DE CONEXAO DAS LINHAS DO TECLADO
byte colPins[COLS] = {6, 7, 8}; //PINOS DE CONEXAO DAS COLUNAS DO TECLADO
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS);

int receber;
String mensagemrecebida;

void setup()
{
//Define a velocidade tranferencia de dados por segundo
Serial.begin(9600);
//Apresentar a mensagem no ecra
Serial.println("SDM-T3 Arduino Receiver");
//o que liga os dois arduinos
//mySerial.begin(9600);
//
//lcd.init;
//lcd.begin(16,2);
SPI.begin();
rfid.init();
pinMode(redLEDPin, OUTPUT);
pinMode(greenLEDPin, OUTPUT);
//pinMode(greenLedOutPin, OUTPUT);
delay(200);
digitalWrite(redLEDPin, HIGH);
delay(200);
digitalWrite(greenLEDPin, HIGH);
delay(200);
//digitalWrite(greenLedOutPin, HIGH);
delay(200);
digitalWrite(redLEDPin, LOW);
delay(200);
digitalWrite(greenLEDPin, LOW);
delay(200);
//digitalWrite(greenLedOutPin, LOW);
lockServo.attach(14);
lockServo.write(lockPos); //Servo passa para lock position
//Serial.println("Aproxime o cartão");
mySerial.begin(4800);
}

//Inicio de propgramação
void loop() {
if(Serial.available()){
receber = mySerial.read();
mensagemrecebida = int (receber);
char mensagem[mensagemrecebida.length() + 1];
mensagemrecebida.toCharArray(mensagem, mensagemrecebida.length() + 1);
Serial.println(mensagem);
}

if (rfid.findCard(PICC_REQIDL, str) == MI_OK){

// Serial.println("Só o cartão é aceite");
String temp = "";

if (rfid.anticoll(str) == MI_OK){ 
 // Serial.print("O numnero do cartão é : "); 
  for (int i = 0; i < 4; i++){ 
    temp = temp + (0x0F & (str[i] >> 4)); 
    temp = temp + (0x0F & str[i]); 
  } 
  
  //Serial.println("isto e a puta da variavel ");
  //Serial.println (temp);
  checkAccess (temp);     //Check if the identified tag is an allowed to open tag
} 
rfid.selectTag(str); //Lock card to prevent a redundant read, removing the line will make the sketch read cards continually

}
rfid.halt();
}

void checkAccess(String temp){

boolean granted = false;
for (int i=0; i <= (accessGrantedSize-1); i++){

if(accesso[i] == temp){
  
  //Serial.println("Seja bem vindo, introduza o pin");
  granted = true;
  
  if (locked == true){
      
    String passe = "";
    for (int x = 0; x < 4; x++){
      
      char Key = keypad.waitForKey();
      passe = passe + Key;
    // Serial.println(Key);  
       
    }
  //Serial.println(passe);
  if(passe == "1234"){
    //Serial.println("PIN CORRETO, PODE ENTRAR");
    lockServo.write(unlockPos);
    locked = false;
    digitalWrite(greenLEDPin, HIGH);
    delay(200);

    
  }
  else{
    //Serial.println("PIN INCORRETO");
   
  }
  }
  else if (locked == false){
      lockServo.write(lockPos);
      locked = true;
  }

}
}

if (granted == false){

//Serial.println ("Acesso recusado");
digitalWrite(redLEDPin, HIGH);      
delay(200);
digitalWrite(greenLEDPin, LOW);

}
}

You should post code by using code-tags
There is an automatic function for doing this in the Arduino-IDE
just three steps

  1. press Ctrl-T for autoformatting your code
  2. do a rightclick with the mouse and choose "copy for forum"
  3. paste clipboard into write-window of a posting

You dind't posted a real question.

best regards Stefan

Here is example code to send the ranges from one Uno to another with SoftwareSerial. The received values are written to an array of bytes named ranges[]. The receive code is modified from the example #6 of the serial input basics tutorial. Code successfully tested with my 2 Unos and 4 rangefinders.

Sender

#include <NewPing.h>
#include <SoftwareSerial.h>

#define SONAR_NUM 4 // Number of sensors.
#define MAX_DISTANCE 200 // Maximum distance (in cm) to ping.

NewPing sonar[SONAR_NUM] =   // Sensor object array.
{
   NewPing(7, 6, MAX_DISTANCE), // Each sensor's trigger pin, echo pin, and max distance to ping.
   NewPing(3, 2, MAX_DISTANCE),
   NewPing(5, 4, MAX_DISTANCE),
   NewPing(9, 8, MAX_DISTANCE)
};

#define SERIAL_RX 11
#define SERIAL_TX 10

SoftwareSerial mySerial(SERIAL_RX, SERIAL_TX);

byte ranges[SONAR_NUM];

void setup()
{
   Serial.begin(9600);
   Serial.println("SDM-T3 Arduino Sender");
   mySerial.begin(9600);
}

void loop()
{

   // if (Serial.available())
   for (uint8_t i = 0; i < SONAR_NUM; i++)   // Loop through each sensor and display results.
   {
      delay(50); // Wait 50ms between pings (about 20 pings/sec). 29ms should be the shortest delay between pings.
      Serial.print(i);
      Serial.print("=");
      byte thisRange = (sonar[i].ping_cm());
      Serial.print(thisRange);
      Serial.print("cm ");
      ranges[i] = thisRange;
   }
   Serial.println();
   mySerial.write(0x3C); // start marker
   mySerial.write(ranges, SONAR_NUM);  // binary data
   mySerial.write(0x3E); // end marker   
}

Receiver

// Example 6 - Receiving binary data
#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11);

const byte numBytes = 16;
byte receivedBytes[numBytes];
byte numReceived = 0;

boolean newData = false;

byte ranges[4];

void setup()
{
   Serial.begin(9600);
   Serial.println("<Arduino is ready>");
   mySerial.begin(9600);
}

void loop()
{
   recvBytesWithStartEndMarkers();
   showNewData();
}

void recvBytesWithStartEndMarkers()
{
   static boolean recvInProgress = false;
   static byte ndx = 0;
   byte startMarker = 0x3C;
   byte endMarker = 0x3E;
   byte rb;


   while (mySerial.available() > 0 && newData == false)
   {
      rb = mySerial.read();
      //Serial.print(char(rb));
      if (recvInProgress == true)
      {
         if (rb != endMarker)
         {
            receivedBytes[ndx] = rb;
            ndx++;
            if (ndx >= numBytes)
            {
               ndx = numBytes - 1;
            }
         }
         else
         {
            receivedBytes[ndx] = '\0'; // terminate the string
            recvInProgress = false;
            numReceived = ndx;  // save the number for use when printing
            ndx = 0;
            newData = true;
         }
      }

      else if (rb == startMarker)
      {
         recvInProgress = true;
      }
   }
}

void showNewData()
{
   if (newData == true)
   {
      Serial.print("This just in (DEC values)... ");
      for (byte n = 0; n < numReceived; n++)
      {
         ranges[n] = receivedBytes[n];
         Serial.print(ranges[n], DEC);
         Serial.print(' ');         
      }
      Serial.println();
      newData = false;
   }
}

code formatted with the IDE autoformat tool and posted in code tags. See the the forum guidelines.

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.