Отказоустойчивый контроллер PS4, используемый для управления двигателями постоянного тока

Я работаю над проектом по управлению старыми двигателями постоянного тока на радиоуправлении через Arduino Uno и L298N. У меня работают моторы, но я хочу включить отказоустойчивую систему, которая останавливает моторы, если bluetooth выходит за пределы диапазона, чтобы он просто не продолжал двигаться, пока не сломался. Код начинается ниже с моей попытки отказоустойчивости в самом низу.

    //This begins the actual motor stuff 

int forwards = (PS4.getAnalogButton(R2)); // Read R2 Button for forward 
int backwards = (PS4.getAnalogButton(L2)); // Read L2 Button for backwards 
forwards  = map(forwards,  0, 255, 0, 255); //Need to figure out how to add offset to remove buzzing 
//noise from motor. 
backwards = map(backwards, 0, 255, 0, 255);

//This is for Rear motor Forwards
if ((PS4.getAnalogButton( R2 )) > 0 ) {
analogWrite(enA, forwards );
digitalWrite(in1, HIGH);
digitalWrite(in2, LOW);}
//This is for Rear motor Backwards 
if  ((PS4.getAnalogButton( L2 )) > 0 ) {
 analogWrite(enA, backwards );
digitalWrite(in1, LOW);
digitalWrite(in2, HIGH);} 
//This is so that if neither L2/R2 is pressed the motor does nothing.
if (PS4.getAnalogButton( R2 ) == 0  &&
PS4.getAnalogButton( L2 ) == 0  ){
  analogWrite(enA, 255);
digitalWrite(in1, LOW);
digitalWrite(in2, LOW); }


//This is for front l/r Motor

int steer = (PS4.getAnalogHat(LeftHatX) ); 
steer = map(steer, 0, 255, 255, 255);


//This is for front motor turning left 
//code for analog for l/r 
 if ((PS4.getAnalogHat(LeftHatX)) >135 ){
 analogWrite(enB, steer); 
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW);} 
else if ((PS4.getAnalogHat(LeftHatX)) <115 ){
 analogWrite(enB, steer);
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH); } 
 else{
  analogWrite(enB, 255);
digitalWrite(in3, LOW);
digitalWrite(in4, LOW); }
//This is code to turn off motor if controller is out of range and disconnect still a wip 
//if (PS4.disconnect())return = true;{      //this comes back as an error "could not convert 
'PS4.PS4BT::<anonymous>.BTHID::disconnect()' from 'void' to 'bool' "
 //analogWrite(enA, 255);
 //digitalWrite(in1, LOW);
 //digitalWrite(in2, LOW);}

 }}

person David Duronslet    schedule 12.08.2020    source источник


Ответы (3)



В вашем коде используется функция .disconnect(), которая фактически отключает ваше устройство, если оно подключено, поэтому это void вместо bool. Вместо этого я бы использовал метод .connected(), который возвращает bool, сообщая, подключено ли ваше устройство. Чтобы реализовать это, вы должны:

if (PS4.connected() == false {
// do whatever you need to do here to turn off your motors
}

Я надеюсь, что это помогло, и если вам понадобится дополнительная помощь с функциональностью Bluetooth на Arduino, библиотеку, из которой я получил функцию function .connected(), можно найти здесь: https://www.arduino.cc/en/Reference/CurieBLE

person a43nigam    schedule 12.08.2020
comment
Я только что понял, что вы также можете использовать цикл while, чтобы реализовать этот отказоустойчивый; вы можете поместить всю программу в большой цикл while, который говорит что-то вроде, while (PS4.connected ()) {do the program} - person a43nigam; 12.08.2020
comment
Я думаю, что оба из них вызывают ошибку - person David Duronslet; 13.08.2020
comment
нет, но в итоге я нашел кое-что, что сработало, добавил- ›bool Paired = false; под глобальными переменными - ›if (PS4.connected ()) {Paired = true; а затем иначе if (Paired == true) {// это означает, что ранее был подключен, но больше не подключен. // остановка всех двигателей analogWrite (enA, 255); digitalWrite (in1, LOW); digitalWrite (in2, LOW); - person David Duronslet; 15.08.2020

закончилось добавлением нескольких вещей, поэтому, если контроллер был подключен, а больше не был, благодаря приятелю, который помог мне

/*
PS4 Bluetooth Controlled RC Car- developed by David Duronslet, 
Code adapted from example sketch for the PS4 Bluetooth library by Kristian Lauszus
 */
#include <PS4BT.h>
#include <usbhub.h>
#ifdef dobogusinclude
#include <spi4teensy3.h>
#endif
#include <SPI.h>


////////////GLOBALS DEFINED HERE///////////

bool Paired=false; 
//For motor 1 
#define enA 9
#define in1 4
#define in2 5

//For motor 2 
#define in3 6
#define in4 7
#define enB 10 

//For PS4 Controller inputs on debug menu 
#define ENABLE_UHS_DEBUGGING 1

USB Usb; //use Usb class
BTD Btd(&Usb);
bool printAngle, printTouch;
uint8_t oldL2Value, oldR2Value;

int val = map(PS4.getAnalogButton(R2), 255, 100, 100, 255)   ; //map function for R2 button 

void setup() {
  Serial.begin(115200);//communication baud rate for the Serial port.
  
#if !defined(__MIPSEL__)
  while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
#endif
  if (Usb.Init() == -1) {
    Serial.print(F("\r\nOSC did not start"));
    while (1); // Permanently Halt
  }
  Serial.print(F("\r\nPS4 Bluetooth Library Started "));

  //Motor Controller Pin Setup
  pinMode(enA, OUTPUT);
  pinMode(enB, OUTPUT);
  pinMode(in1, OUTPUT);
  pinMode(in2, OUTPUT);
  pinMode(in3, OUTPUT);
  pinMode(in4, OUTPUT);
}

void loop() {
  Usb.Task();
 if (PS4.connected()) {
  Paired=true; //for the range checker 
//This begins the actual motor stuff 

int forwards = (PS4.getAnalogButton(R2)); // Read R2 Button for forward 
int backwards = (PS4.getAnalogButton(L2)); // Read L2 Button for backwards 
forwards  = map(forwards,  0, 255, 0, 255); //Need to figure out how to add offset to remove buzzing noise from motor. 
backwards = map(backwards, 0, 255, 0, 255);

//This is for Rear motor Forwards
  if ((PS4.getAnalogButton( R2 )) > 0 ) {
    analogWrite(enA, forwards );
    digitalWrite(in1, HIGH);
    digitalWrite(in2, LOW);}
//This is for Rear motor Backwards 
if  ((PS4.getAnalogButton( L2 )) > 0 ) {
     analogWrite(enA, backwards );
    digitalWrite(in1, LOW);
    digitalWrite(in2, HIGH);} 
//This is so that if neither L2/R2 is pressed the motor does nothing.
if (PS4.getAnalogButton( R2 ) == 0  &&
    PS4.getAnalogButton( L2 ) == 0  ){
      analogWrite(enA, 255);
    digitalWrite(in1, LOW);
    digitalWrite(in2, LOW); }

    
//This is for front l/r Motor

int steer = (PS4.getAnalogHat(LeftHatX) ); 
steer = map(steer, 0, 255, 255, 255);


//This is for front motor turning left 
//code for analog for l/r 
 if ((PS4.getAnalogHat(LeftHatX)) >135 ){
 analogWrite(enB, steer); 
digitalWrite(in3, LOW);
digitalWrite(in4, HIGH);} 
else if ((PS4.getAnalogHat(LeftHatX)) <115 ){
 analogWrite(enB, steer);
digitalWrite(in3, HIGH);
digitalWrite(in4, LOW); } 
 else{
      analogWrite(enB, steer);//Change 255 value?
    digitalWrite(in3, LOW);
    digitalWrite(in4, LOW); }

 }

//Out of range condition goes here! 
else if(Paired==true){//this means the was Connected in the past but is no longer connected.
  //stop all motors
    analogWrite(enA, 255);
    digitalWrite(in1, LOW);
    digitalWrite(in2, LOW);
}
 }
person David Duronslet    schedule 14.08.2020