Arduino 和 C++ 更改端口

Arduino and C++ changing port

我正在尝试使用 Qt 做一个 GUI 应用程序,但是由于我忽略的原因,只有一个命令到达 arduino 卡,下一个命令没有到达。当我尝试重新连接卡时,它不允许我这样做。所以我有两个问题,第一个是更改 Arduino 卡的端口,以防它不是同一张卡,第二个是成功向 arduino 卡发送多个命令而无需每次重新启动程序。

主要代码为

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "envoie.h"
#include "batterie.h"
#include "SerialClass.h"
#include <QtWidgets>
#include "iostream"
using namespace std;

int niveau_de_decharge = 80;
string entree;
bool marche_programme;

MainWindow::MainWindow(QWidget *parent)
    : QWidget(parent)
{
    brancherButton = new QPushButton(tr("Brancher"));
    brancherButton->show();
    debrancherButton = new QPushButton(tr("Débrancher"));
    debrancherButton->show();
    connectButton = new QPushButton(tr("Connexion"));
    connectButton->show();
    disconnectButton = new QPushButton(tr("Déconnexion"));
    disconnectButton->show();
    testButton = new QPushButton(tr("Test de la connexion"));
    testButton->show();
    pourcentagebatterieBar = new QProgressBar;
    retourText = new QTextBlock;
    valeurdefautSlider = new QSlider;
    connect(brancherButton, &QPushButton::clicked, this, &MainWindow::brancher);
    connect(connectButton, &QPushButton::clicked, this, &MainWindow::connexion);
    connect(debrancherButton, &QPushButton::clicked, this, &MainWindow::debrancher);
    connect(disconnectButton, &QPushButton::clicked, this, &MainWindow::deconnexion);
    connect(testButton, &QPushButton::clicked, this, &MainWindow::test);
    QVBoxLayout *buttonLayout1 = new QVBoxLayout;
        buttonLayout1->addWidget(brancherButton, Qt::AlignTop);
        buttonLayout1->addWidget(debrancherButton);
        buttonLayout1->addWidget(connectButton);
        buttonLayout1->addWidget(disconnectButton);
        buttonLayout1->addWidget(testButton);
        buttonLayout1->addStretch();
    QGridLayout *mainLayout = new QGridLayout;
           // mainLayout->addWidget(retourText, 0, 0, Qt::AlignTop); // ne marche pas actuellement
            mainLayout->addWidget(valeurdefautSlider, 0, 1, Qt::AlignTop);
            mainLayout->addWidget(pourcentagebatterieBar, 1, 0, Qt::AlignTop);
            mainLayout->addLayout(buttonLayout1, 1, 2);
    setLayout(mainLayout);
    setWindowTitle("TIPE Protection des batteries");
}

MainWindow::~MainWindow()
{
}

std::wstring s2wsbis(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

std::wstring stempbis = s2wsbis("\\.\COM3");
LPCWSTR portbis = stempbis.c_str();

Serial SPbis = Serial(portbis);

auto donnee(){
    cout << "Taper la commande a effectuer : " << endl;
    auto f = std::async(std::launch::async, [] {    //début de bout de programme qui fait quelque chose d'un peu magique
            auto s = ""s;
            if (std::cin >> s) return s;
            });                                 //fin de l'incompréhension
    while(f.wait_for(30s) != std::future_status::ready) {
        if (batterie()>=niveau_de_decharge){
            cout << "Batterie chargee" << endl;
            if(SPbis.IsConnected()){
                envoie("debrancher", SPbis);
            }
            else {
                cout << "Veuillez connecter la carte arduino ou relancer le programme" << endl;
            }
            cout << "Taper la commande a effectuer : " << endl;
        }
    }
       entree = f.get();

        if (entree=="change"){
            cout << "Changement de la valeur de la variable decharge_defaut" << endl << "Valeur actuelle : " << niveau_de_decharge << endl;
            cout << "Nouvelle valeur : ";
            cin >> niveau_de_decharge;
            cout << "Valeur changee : " << niveau_de_decharge << "% est le nouveau seuil de charge maximal" << endl;
        }
        else if (entree=="batterie") {
            cout << "Le niveau de batterie est de " << batterie() << "%." <<endl;
            if (branchement()==1){
                cout << "L'ordinateur est branche" << endl;
            }
            else {
                cout << "Ordinateur sur batterie" << endl;
            }
        }
        else if (entree=="close"){
                marche_programme=false;
        }
        else if (entree=="help") {
            cout << "   Liste des commandes : " << endl
                        << "        connect" << endl
                        << "        close" << endl
                        << "        change" << endl
                        << "        batterie" << endl
                        << "        brancher" << endl
                        << "        changeport" << endl;
        }
        else {
            envoie(entree, SPbis);
        }
    return 0;
}

void MainWindow::test() {
    if(SPbis.IsConnected()){
        cout << "Arduino connectée" << endl;
    }
    else {
     cout << "Erreur";
    }
}

void MainWindow::brancher() {
    envoie("brancher", SPbis);
};

void MainWindow::debrancher() {
    envoie("debrancher", SPbis);
};

void MainWindow::pourcentagebatterie() {
    batterie();
};

void MainWindow::connexion(){
    cout << "Tentative de connexion sur le port " << portbis << "..." << endl;
    Serial SPbis=Serial(portbis);
    Sleep(500);
    if(SPbis.IsConnected()){
        cout<<"Connexion etablie"<<endl<<endl;
    }
    else{
        cout << "Impossible de se connecter" << endl;
    }
}

我用 https://playground.arduino.cc/Interfacing/CPPWindows/ 在arduino和电脑之间进行通信

编辑

我修改了发送命令和检索 arduino 信息,当我发送新命令时,Arduino 卡不会发回任何信息,因此,尽管连接测试中为“true”,但信​​息不会进入打开的端口

我通过在我的函数 envoie() here 中实现它成功解决了“只有一个命令上传”

#include "envoie.h"
#include <string>
#include "SerialClass.h"
#include <QtWidgets>
#include "mainwindow.h"
#include <iostream>
using namespace std;

unsigned int MAX_DATA_LENGTH=255;
//char previousoutput[255];
char output[255];
char incomingData[255];
char prevoutput[255];

std::wstring s2ws3(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0);
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}




std::wstring stemp9 = s2ws3("\\.\COM9");
LPCWSTR port9 = stemp9.c_str();
Serial SP = Serial(port9);

bool envoie(string data)
{
        cout << "Tentative d'envoie de la commande '" << data << "'" << endl;
        if (SP.IsConnected()) {
            char* charArray = new char[data.size() + 1];

            copy(data.begin(), data.end(), charArray);
            charArray[data.size()] = '[=10=]';                  //stopsign for compliler


            SP.WriteData(charArray, MAX_DATA_LENGTH);

            Sleep(ARDUINO_WAIT_TIME);

            SP.ReadData(output, MAX_DATA_LENGTH);
            cout << "Retour de la carte : " << output << endl;
            std::fill_n(output,255,0);
           /* if (strcmp(prevoutput,output)==0){      //ne marche pas
                cout << "Retour identiques" << endl;
            }*/
            SP.ReadData(prevoutput, MAX_DATA_LENGTH);
            cout << charArray << " envoye avec succes" << endl;
            delete[] charArray;
        }
        else {
            cout << "Arduino deconnecte" << endl;
        }
        return 0;
    }

每次重新打开网卡与电脑的连接

编辑

添加了一个连接和断开连接按钮,以便更改仅通过替换

才能工作的端口
Serial SP = new Serial(port9);
SP.IsConnected();

来自

Serial* SP = new Serial(port9);
SP->IsConnected();

希望这对某人有所帮助