#1 2023-10-10 11:55:52

Андр.
Учасник
Зареєстрований: 2015-12-01
Повідомлень: 23

Arduino mega + e32 433t20d LoRa modul

Доброго всім дня! Потрібна допомога. Є дві плати ардуіно мега і два радіо модуля e32 433t20d LoRa. Передаю через них структуру даних. На платі ардуіно Send стоїть два джойстика та клавіатура і екран я передаю на плату Receive дані положення джойстиків і значення клавіатури та двох кнопок. Коли ні чого не роблю то все приходить норм без проблем. Як що змінюю положення джойстика то значення змінюються. А ось коли натискаю кнопку то збивається передача даних і не коректно показує дані  потім і значення зміщаються. Прикладаю код двох плат та те що відбувається в порту. Може хтось може допомогти в цьому?

Send arduino (що посилає значення)

#include <Wire.h>
#include <Keypad.h>
#include <LiquidCrystal.h>  
#include <SoftwareSerial.h>

LiquidCrystal lcd(12, 11, 5, 4, 3, 2); 

#include "EBYTE.h"

#define PIN_RX 9
#define PIN_TX 8
#define PIN_M0 7
#define PIN_M1 6
#define PIN_AX 10

#define pinX_1    A0  
#define pinY_1    A1  
#define swPin_1   30

#define pinX_2    A2  
#define pinY_2    A3  
#define swPin_2   31

int buttonState = LOW; 
int lastButtonState = LOW;

struct DATA {
  
  char Key;
  int X1_send;
  int Y1_send;
  int X2_send;
  int Y2_send;
  int swPin1_send;
  int swPin2_send;

};
int Chan;
DATA MyData;

SoftwareSerial ESerial(PIN_RX, PIN_TX);

const byte ROWS = 4; 
const byte COLS = 4; 

char hexaKeys[ROWS][COLS] = {
  
  {'D','C','B','A'},
  {'#','9','6','3'},
  {'0','8','5','2'},
  {'*','7','4','1'}
};
byte rowPins[ROWS] = {25, 24, 23, 22}; 
byte colPins[COLS] = {29, 28, 27, 26}; 

Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

EBYTE Transceiver(&ESerial, PIN_M0, PIN_M1, PIN_AX);

void setup(){
  
 lcd.begin(16, 2);   
            
 Serial.begin(9600);
 
 ESerial.begin(9600);

 Transceiver.init();

 pinMode(pinX_1, INPUT);
 pinMode(pinY_1, INPUT);
 pinMode(swPin_1, INPUT_PULLUP);
 pinMode(pinX_2, INPUT);
 pinMode(pinY_2, INPUT);
 pinMode(swPin_2, INPUT_PULLUP);


 lcd.setCursor(2, 0);
 lcd.print("Browning");
 lcd.setCursor(4, 1);
 lcd.print("Ver.:1.1");
 
 lcd.clear();
 
  //Transceiver.PrintParameters();
}

void loop(){
  
  Keypad_mod();

  analog_joy();

  Send_message();

  Transceiver.SendStruct(&MyData, sizeof(MyData));

}

void Keypad_mod(){

  char customKey = customKeypad.getKey();
  
  if (customKey){
    MyData.Key = customKey;
    lcd.begin(16, 2); 
    lcd.setCursor(0, 0);
    lcd.print(customKey);
    //lcd.print("  ");
    //Serial.println(customKey);
  }   
  //Serial.print("Key: "); Serial.print(MyData.Key);
}
void analog_joy(){
  
  int X1 = analogRead(pinX_1);              // считываем значение оси Х
  int Y1 = analogRead(pinY_1); 
  int X2 = analogRead(pinX_2);              // считываем значение оси Х
  int Y2 = analogRead(pinY_2);

  int X1_Analog = map(X1, 516, 1023, 0, 100);
  int Y1_Analog = map(Y1, 510, 1023, 0, 100);

  int X2_Analog = map(X2, 510, 1023, 0, 100);
  int Y2_Analog = map(Y2, 510, 1023, 0, 100);

  int State_swPin1 = digitalRead(swPin_1);
  int State_swPin2 = digitalRead(swPin_2);

  lcd.setCursor(0, 0);
  lcd.print("X1:");
  lcd.setCursor(3, 0);
  lcd.print(X1_Analog);
  lcd.print("   ");

  lcd.setCursor(0, 1);
  lcd.print("Y1:");
  lcd.setCursor(3, 1);
  lcd.print(Y1_Analog);
  lcd.print("  ");
  
  lcd.setCursor(7, 0);
  lcd.print("X2:");
  lcd.setCursor(10, 0);
  lcd.print(X2_Analog);
  lcd.print("  ");

  lcd.setCursor(7, 1);
  lcd.print("Y2:");
  lcd.setCursor(10, 1);
  lcd.print(Y2_Analog);
  lcd.print("  ");

  lcd.setCursor(13, 0);
  lcd.print("B:");
  lcd.setCursor(15, 0);
  lcd.print(State_swPin1);
  lcd.print("  ");

  lcd.setCursor(13, 1);
  lcd.print("B:");
  lcd.setCursor(15, 1);
  lcd.print(State_swPin2);
  lcd.print("  ");
  //Serial.println(Y2);
  
}
void Send_message(){
  
  int X1 = analogRead(pinX_1);              // считываем значение оси Х
  int Y1 = analogRead(pinY_1); 
  int X2 = analogRead(pinX_2);              // считываем значение оси Х
  int Y2 = analogRead(pinY_2);

  int State_swPin1 = digitalRead(swPin_1);
  int State_swPin2 = digitalRead(swPin_2);

  MyData.X1_send = analogRead(pinX_1);
  MyData.Y1_send = analogRead(pinY_1);
  MyData.X2_send = analogRead(pinX_2);
  MyData.Y2_send = analogRead(pinY_2);

  MyData.swPin1_send = digitalRead(swPin_1);
  MyData.swPin2_send = digitalRead(swPin_2);
  
   /* //Serial.print("Key: "); Serial.print(MyData.Key);
    Serial.print("  X1: "); Serial.print(MyData.X1_send);
    Serial.print("  Y1: "); Serial.print(MyData.Y1_send);
    Serial.print("  X2: "); Serial.print(MyData.X2_send);
    Serial.print("  Y2: "); Serial.print(MyData.Y2_send);
    Serial.print("  swPin1_send: "); Serial.print(MyData.swPin1_send);
    Serial.print("  swPin2_send: "); Serial.println(MyData.swPin2_send);   */

}

Receive Arduino (що приймає значення)

#include <AccelStepper.h>
#include <SoftwareSerial.h>
#include "EBYTE.h"
 
const int stepPin = 9;
const int directionPin = 8;
const int enablePin = 7;

const int SPEED = 1000;
 
const int setSPEED = 1000;

#define PIN_RX 53
#define PIN_TX 52
#define PIN_M0 51
#define PIN_M1 50
#define PIN_AX 48

// i recommend putting this code in a .h file and including it
// from both the receiver and sender modules
struct DATA {
  
  char Key;
  int X1_send;
  int Y1_send;
  int X2_send;
  int Y2_send;
  int swPin1_send;
  int swPin2_send;

};
int Chan;
DATA MyData;
unsigned long Last;

// connect to any digital pin to connect to the serial port
// don't use pin 01 and 1 as they are reserved for USB communications
SoftwareSerial ESerial(PIN_RX, PIN_TX);

// create the transceiver object, passing in the serial and pins
EBYTE Transceiver(&ESerial, PIN_M0, PIN_M1, PIN_AX);

AccelStepper stepper(AccelStepper::DRIVER, stepPin, directionPin);

void setup() {

  Serial.begin(9600);

  stepper.setEnablePin(enablePin);
  stepper.enableOutputs();
  stepper.setMaxSpeed(SPEED);
  //stepper.setAcceleration(1000);
  stepper.setSpeed(SPEED);

  ESerial.begin(9600);
  
  Transceiver.init();
 
}

void loop() {
      
    Read_arduinoMega();
    X1_left_rigth_state();
    //MoveConerLeft ();
    MoveConerRigth ();
  
}

void X1_left_rigth_state(){
  
  int X1_left_rigth;

  X1_left_rigth = map(MyData.X1_send, 516, 1023, 0, 100);

  //Serial.println(X1_left_rigth);
  
  if (X1_left_rigth >= 20){
      stepper.setSpeed(setSPEED);
      stepper.runSpeed();
    }else if(X1_left_rigth <= -20){
      stepper.setSpeed(-setSPEED);
      stepper.runSpeed();
    }else {
          stepper.setSpeed(0);
          stepper.stop();
    }
      
   //Serial.println(MyData.swPin2_send);
}
void MoveConerLeft (){
    
    int ButtonStateConer = MyData.swPin1_send;

    if (ButtonStateConer == LOW){
      int setSPEED = 3000;
      stepper.setSpeed(setSPEED);
      stepper.setAcceleration(3000);
      stepper.runToNewPosition(1000);
      stepper.run();
      //Serial.println(ButtonStateConer); 
      
    }
    else if (ButtonStateConer == HIGH){
        stepper.setCurrentPosition(0);
        stepper.setSpeed(0);
        //Serial.println(ButtonStateConer); 
    }
    //stepper.run();
  
}
void MoveConerRigth (){

    //int ButtonStateConer2 = MyData.swPin2_send;

    if (MyData.swPin2_send == 0){
      int setSPEED = 3000;
      stepper.setSpeed(-setSPEED);
      stepper.setAcceleration(3000);
      stepper.runToNewPosition(-1000);
      stepper.run();
      //Serial.println(ButtonStateConer2);
      
    }
    else if (MyData.swPin2_send == 1){
        stepper.setCurrentPosition(0);
        stepper.setSpeed(0);
        //Serial.println(ButtonStateConer2);
    }
  //Serial.println(MyData.Key);
  
}


void Read_arduinoMega(){
  
  if (ESerial.available()) {

    Transceiver.GetStruct(&MyData, sizeof(MyData));
  //ESerial.readBytes((uint8_t*)& MyData, (uint8_t) sizeof(MyData));
  
    Serial.print("Key: "); Serial.print(MyData.Key);
    Serial.print("  X1: "); Serial.print(MyData.X1_send);
    Serial.print("  Y1: "); Serial.print(MyData.Y1_send);
    Serial.print("  X2: "); Serial.print(MyData.X2_send);
    Serial.print("  Y2: "); Serial.print(MyData.Y2_send);
    Serial.print("  swPin1_send: "); Serial.print(MyData.swPin1_send);
    Serial.print("  swPin2_send: "); Serial.println(MyData.swPin2_send);


    Last = millis();

  }
  else {

    if ((millis() - Last) > 300) {
      //Serial.println("Searching: ");
      Last = millis();
    }

  }
}

і ось що приходить в Serial port:

Key: #  X1: 520  Y1: 510  X2: 506  Y2: 509  swPin1_send: 1  swPin2_send: 1
Key: #  X1: 519  Y1: 511  X2: 506  Y2: 509  swPin1_send: 1  swPin2_send: 0  // натиснув кнопку
Key: #  X1: 520  Y1: 511  X2: 505  Y2: 510  swPin1_send: 1  swPin2_send: 1
Key: #  X1: 519  Y1: 511  X2: 506  Y2: 509  swPin1_send: 1  swPin2_send: 1
Key: #  X1: 519  Y1: 511  X2: 506  Y2: 509  swPin1_send: 1  swPin2_send: 1
Key: #  X1: 520  Y1: 511  X2: 506  Y2: 510  swPin1_send: 1  swPin2_send: 1
Key: #  X1: 520  Y1: 510  X2: 505  Y2: 510  swPin1_send: 1  swPin2_send: 1827 // і потім щось пішло не так
Key:   X1: 511  Y1: 505  X2: 509  Y2: 1  swPin1_send: 1  swPin2_send: 2083
Key:   X1: 511  Y1: 506  X2: 510  Y2: 1  swPin1_send: 1  swPin2_send: 2083
Key:   X1: 511  Y1: 505  X2: 510  Y2: 1  swPin1_send: 1  swPin2_send: 2083
Key:   X1: 511  Y1: 506  X2: 509  Y2: 1  swPin1_send: 1  swPin2_send: 2083
Key:   X1: 511  Y1: 505  X2: 509  Y2: 1  swPin1_send: 1  swPin2_send: 2083
Key:   X1: 511  Y1: 506  X2: 510  Y2: 1  swPin1_send: 1  swPin2_send: 1827

Як можна вирішити це питання? Щось з struct DATA, а як вирішити це поки не розумію.

Неактивний

#2 2023-10-10 19:31:48

Honey
Учасник
З Київ
Зареєстрований: 2020-09-26
Повідомлень: 415

Re: Arduino mega + e32 433t20d LoRa modul

Андр. пише:

А ось коли натискаю кнопку то збивається передача даних

Спробуйте натискати цю ж кнопку, але в програмі опитувати якусь іншу, так відокремите - апаратна чи програмна проблема.

Неактивний

#3 2023-10-20 14:43:25

Андр.
Учасник
Зареєстрований: 2015-12-01
Повідомлень: 23

Re: Arduino mega + e32 433t20d LoRa modul

Honey пише:
Андр. пише:

А ось коли натискаю кнопку то збивається передача даних

Спробуйте натискати цю ж кнопку, але в програмі опитувати якусь іншу, так відокремите - апаратна чи програмна проблема.

З цім розібрався, кнопки працюють все правильно, діло не в них. Тепер у мене інша проблема. Я передаю значення з ардуіно-1 на ардуіно-2 і все ОК, я зчитую данні з джойстика який стоїть на ардуіно-1. А ось я хочу налаштувати зворотній зв'язок, і тут проблема, не знаю чому перешукав багато туторіалів та коду і у мене не виходить відправити "ОК" з ардуіно-2 на ардуіно-1 коли кнопка натиснута. При цьому коли я відправляю sendMessage з ардуіно-2 то зависає передача в Serial port-у і приходиться його закрити і знов відкрити тоді все ок данні передавати відновлюються а ось меседж так і не приходить на ардуіно-1.

ось код нижче, може хтось з цим стикався та знає як вирішити?

#include <SPI.h>              
#include <LoRa.h>
#include <Wire.h>

const int csPin = 52;          // LoRa radio chip select
const int resetPin = 3;       // LoRa radio reset
const int irqPin = 2;         // change for your board; must be a hardware interrupt pin

byte msgCount = 0;            // count of outgoing messages
byte localAddress = 0xBB;     // address of this device
byte destination = 0xFF;      // destination to send to
long lastSendTime = 0;        // last send time
int interval = 50;          // interval between sends

boolean flag1 = false;

int RLY1=2;

int Sensor1 = 0; 

int relay1Status;

String outgoing;              // outgoing message

String statusmessage = "";

void setup() {
  Serial.begin(9600);                   // initialize serial

  //LoRa.setPins(csPin, resetPin, irqPin);// set CS, reset, IRQ pin
  
 pinMode(RLY1,OUTPUT);

  Serial.println("LoRa Duplex");

  if (!LoRa.begin(433E6)) {             // initialize ratio at 915 MHz
    Serial.println("LoRa init failed. Check your connections.");
    while (true);                       // if failed, do nothing
  }

  Serial.println("LoRa init succeeded.");
}

void loop() {

  if (millis() - lastSendTime > interval) {
    relay1Status = digitalRead(RLY1);
    lastSendTime = millis();            // timestamp the message
    interval = random(50) + 100;    // 2-3 seconds
  }

  onReceive(LoRa.parsePacket());

  //LoRa.receive();
}

void sendMessage(String outgoing) {
  LoRa.beginPacket();                   // start packet
  LoRa.write(destination);              // add destination address
  LoRa.write(localAddress);             // add sender address
  LoRa.write(msgCount);                 // add message ID
  LoRa.write(outgoing.length());        // add payload length
  LoRa.print(outgoing);                 // add payload
  LoRa.endPacket();                     // finish packet and send it
  msgCount++;                           // increment message ID
}

void onReceive(int packetSize) {
  if (packetSize == 0) return;          // if there's no packet, return

  // read packet header bytes:
  int recipient = LoRa.read();          // recipient address
  byte sender = LoRa.read();            // sender address
  byte incomingMsgId = LoRa.read();     // incoming msg ID
  byte incomingLength = LoRa.read();    // incoming msg length

  String incoming = "";

  while (LoRa.available()) {
    incoming += (char)LoRa.read();
  }

  if (incomingLength != incoming.length()) {   // check length for error
   // Serial.println("error: message length does not match length");
   ;
    return;                             // skip rest of function
  }

  // if the recipient isn't this device or broadcast,
  if (recipient != localAddress && recipient != 0xFF) {
    //Serial.println("This message is not for me.");
    ;
    return;                             // skip rest of function
  }

  // if message is for this device, or broadcast, print details:
 // Serial.println("Received from: 0x" + String(sender, HEX));
 // Serial.println("Sent to: 0x" + String(recipient, HEX));
  //Serial.println("Message ID: " + String(incomingMsgId));
 // Serial.println("Message length: " + String(incomingLength));
  Serial.println("Message: " + incoming);
  //Serial.println("RSSI: " + String(LoRa.packetRssi()));
  //Serial.println("Snr: " + String(LoRa.packetSnr()));
 // Serial.println();

 
String q = getValue(incoming, ',', 0); 
 
Sensor1 = q.toInt();

//Serial.println(Sensor1);

if((Sensor1 == 1)&&(flag1==false))
{
 
  digitalWrite(RLY1,HIGH);
   relay1Status = 1;
  Serial.println("Relay 1 is turned on");
  flag1=true;
}

if((Sensor1 == 0)&&(flag1 ==true))
{

  digitalWrite(RLY1,LOW);
  relay1Status = 0;
  Serial.println("Relay 1 is turned off");
  statusmessage = statusmessage + relay1Status;
  sendMessage(statusmessage); 
  delay(1000);
  flag1=false;
}

incoming = "";

  //statusmessage = statusmessage + relay1Status + "," + relay2Status + "," + relay3Status + "," + relay4Status;
  //sendMessage(statusmessage); 
}
String getValue(String data, char separator, int index)
{
    int found = 0;
    int strIndex[] = { 0, -1 };
    int maxIndex = data.length() - 1;
 
    for (int i = 0; i <= maxIndex && found <= index; i++) {
        if (data.charAt(i) == separator || i == maxIndex) {
            found++;
            strIndex[0] = strIndex[1] + 1;
            strIndex[1] = (i == maxIndex) ? i+1 : i;
        }
    }
    return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}

Остання редакція Андр. (2023-10-20 14:44:22)

Неактивний

Швидке повідомлення

Введіть повідомлення і натисніть Надіслати

Підвал форуму