Boas precisava de ajuda porque quero enviar os dados de 4 sensores ultrassom por comunicação 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);

}
}

Hello, do yourself a favour and please read How to get the best out of this forum and modify your post accordingly (including code tags and necessary documentation of your ask).
—-

tópico movido no fórum português. Inglês é usado em fóruns gerais

Olá,

Precisas de enviar os dados através de comunicação série para onde? Para outro Arduino? Qual o Arduino que usas? Usas os sensores HC-SR04?

Para formatar o código coloca três acentos graves seguidos antes do código e depois do código, ou Ctrl+E.

Eu estou a utilizar dois arduinos unos e sim estou a usar 4 sensores HC-SR04.

O meu problema principal é que a informação não está a chegar ao arduino que tem que as receber

Pelo código, parece que um dos Arduinos tem o RX/TX nos pinos 11/10 e o outro nos pinos 10/11, respectivamente. Então usas 3 fios para ligar os pinos directamente de cada Arduino, é isso? O 10 ao 10, o 11 ao 11 e o GND ao GND? Qual o tamanho destes fios?

Se colocares o esquema fica mais fácil ajudar :wink:

No SENDER declaras e inicializas uma instância do SoftwareSerial mas depois apenas usas o periférico da UART (hardware). Provavelmente será boa ideia configurar a velocidade do mySerial no setup() (tá comentado) e usar o mySerial no loop() para enviar dados para o pino TX ligado ao RX do outro Arduino.

Qual o formato da mensagem a enviar ao outro Arduino? Se tiver o mesmo formato que usas para mostrar no monitor série, o código ficará algo do tipo:

// 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.flush();
  Serial.println("SDM-T3 Arduino Sender");
  mySerial.begin(4800); // Os Arduinos comunicam ambos a 4800 baud?
  mySerial.flush();
}

void loop() {

  // Envia os dados para o outro Arduino.
  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.
    mySerial.print(i);
    mySerial.print("=");
    mySerial.print(sonar[i].ping_cm());
    mySerial.print("cm ");

  }
  mySerial.println();
    
  // Envia os dados para a consola.
  // 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();
}

Eu liguei o pino 10 do sender no pino 11 no receber e vice-versa e os cabos são pequenos tem 7 centímetros de comprimento

Como no sender e no receiver os pinos TX/RX estão trocados:

//SENDER
#define SERIAL_RX 11
#define SERIAL_TX 10
//RECEIVER
#define SERIAL_RX 10
#define SERIAL_TX 11

Os cabos têm de ser ligados do 10 ao 10 (TX de um ao RX do outro) e do 11 ao 11 (RX de um ao TX do outro), e um cabo para o GND de um ao GND do outro.

O receber só fica a imprimir 0 o que pode ser?

Mas primeiro imprime uma serie de numeros mas não tem nada a haver com o que eu pretendo imprimir

No receptor, no inicio da função loop() troca:

if (Serial.available())

por:

if (mySerial.available())

Não compreendo esse processamento que é feito na recepção, dentro desse bloco IF.

Como a mensagem enviada tem caracteres e dígitos provavelmente terás de a processar byte a byte. Vai dar algum trabalho. Há uma thread que explica como processar os dados recebidos pelo porto série: Serial Input Basics . Sugiro que tentes fazer um programa à parte para perceber como processar dados série.

Voce conhece outro método que para enviar myserial mensagem para o outro arduino?

Coloco aqui um exemplo que fiz usando a função parseInt(). Fiz este exemplo com base na informação nestes dois links: https://www.arduino.cc/en/Tutorial/LibraryExamples/SoftwareSerialExample e How to communicate between Arduinos using SoftwareSerial.h - #11 by warren631 .

Neste exemplo ambos o emissor e receptor usam os mesmos pinos TX e RX. Portanto é necessário ligar o pino de TX de um ao RX do outro:

  • Pino 10 do Arduino1 liga ao pino 11 do Arduino2.
  • Pino 11 do Arduino1 liga ao pino 10 do Arduino2.

O formato dos dados enviados é ligeiramente diferente do teu. Envio números inteiros separados por ponto e vírgula (';') e no final o new line ('\n'). Penso que assim fica mais fácil o processamento no receptor, usando a função parseInt() em vez de fazer uma função específica para processar os dados byte a byte. Vê se consegues adaptar ao teu código.

Código exemplo do SENDER:

// Ref. links:
// https://www.arduino.cc/en/Tutorial/LibraryExamples/SoftwareSerialExample
// https://forum.arduino.cc/t/how-to-communicate-between-arduinos-using-softwareserial-h/174469/11

// Adapted from code from above ref. links.

// Send a few integers from one Arduino Uno to another using SoftwareSerial.

// Software RX pin: 10
// Software TX pin: 11

// Connect RX pin from Arduino1 to Arduino2 TX pin.
// Connect TX pin from Arduino1 to Arduino2 RX pin.

// SENDER

#include <SoftwareSerial.h>

#define PIN_RX 10
#define PIN_TX 11
#define DAT_SIZE 4

int dat_send[DAT_SIZE]; // To hold array of integers to send.

SoftwareSerial mySerial(PIN_RX, PIN_TX); // RX, TX

void softserial_dat_send( void );

void setup() {
  // Set pins IN/OUT.
  pinMode(PIN_RX, INPUT);
  pinMode(PIN_TX, OUTPUT);

  // Open serial communications and wait for port to open.
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only.
  }
  mySerial.begin(4800);

  // Init data to send with some values.
  dat_send[0] = 32543;
  dat_send[1] = 12123;
  dat_send[2] = 28555;
  dat_send[3] = 17111;

  Serial.println("Arduino SoftwareSerial Sender Example");
}


void loop() {

  softserial_dat_send();  // Send data repeatedly.
 
  delay(100);
}


// SoftwareSerial send data from global array: dat_send.
void softserial_dat_send( void ) {

  // Send each element from dat_send.
  for ( int i = 0; i < DAT_SIZE; i++ ) {
    mySerial.print(dat_send[i]);
    if ( (i+1) < DAT_SIZE ) {
      mySerial.print(";");  // Element separator.
    } else {
      mySerial.print("\n"); // End of message.
    }
  }

}

Código exemplo do RECEIVER:

// Ref. links:
// https://www.arduino.cc/en/Tutorial/LibraryExamples/SoftwareSerialExample
// https://forum.arduino.cc/t/how-to-communicate-between-arduinos-using-softwareserial-h/174469/11

// Adapted from code from above ref. links.

// Send a few integers from one Arduino Uno to another using SoftwareSerial.

// Software RX pin: 10
// Software TX pin: 11

// Connect RX pin from Arduino1 to Arduino2 TX pin.
// Connect TX pin from Arduino1 to Arduino2 RX pin.

// RECEIVER

#include <SoftwareSerial.h>

#define PIN_RX 10
#define PIN_TX 11
#define DAT_SIZE 4

int dat_receive[DAT_SIZE] = {0}; // To hold received data.

SoftwareSerial mySerial(PIN_RX, PIN_TX); // RX, TX

void softserial_dat_receive( void );

void setup() {
  // Set pins IN/OUT.
  pinMode(PIN_RX, INPUT);
  pinMode(PIN_TX, OUTPUT);

  // Open serial communications and wait for port to open.
  Serial.begin(9600);
  while (!Serial) {
    ; // wait for serial port to connect. Needed for Native USB only.
  }
  mySerial.begin(4800);
  mySerial.setTimeout(50);  // Set parseInt() timeout in milliseconds.
  
  Serial.println("Arduino SoftwareSerial Receiver Example");
}


void loop() {

  if ( mySerial.available() ) { // If data is available:
    softserial_dat_receive();   // Receive data.
  }

}


// SoftwareSerial receive data to global array dat_receive
// and also print it to the console.
void softserial_dat_receive( void ) {

  Serial.print("Receiving: ");
  for ( int i = 0; i < DAT_SIZE; i++ ) {
    dat_receive[i] = mySerial.parseInt();
    Serial.print(dat_receive[i]);
    if (mySerial.read() == '\n') {
      Serial.print("\n");
    } else {
      Serial.print(";");
    }
  }

}

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