Foro de elhacker.net

Programación => Programación C/C++ => Mensaje iniciado por: Meta en 22 Enero 2023, 14:41 pm



Título: No funciona con la versión VS 202
Publicado por: Meta en 22 Enero 2023, 14:41 pm
Buenas gente:

Usando C++ nativo de la época del Visual Studio 2017 el programa funciona de maravilla. Probando ahora la versión del Visual Studio 2022, a pesar que es el mismo código, me da error por todas partes.

El código es C++ nativo, nada de C++ del .net.

Código C++:
Código
  1. #include <iostream>
  2. #include <fstream>
  3. #include <Windows.h>
  4. #include "SerialClass.h"
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9.    // Título de la ventana
  10.    SetConsoleTitle("Control Led Arduino - Visual Studio C++ 2022");
  11.  
  12.    // Puerto serie.
  13.    Serial* Puerto = new Serial("COM4");
  14.  
  15.    // Comandos para Arduino.
  16.    char Luz_ON[] = "Luz_ON"; // Envía "Luz_ON" al puerto serie.
  17.    char Luz_OFF[] = "Luz_OFF";
  18.    char lectura[50] = "\0"; // Guardan datos de entrada del puerto.
  19.  
  20.    int opc; // Guarda un 1 o 2 tipo entero queintroduces desde la consola.
  21.  
  22.    while (Puerto->IsConnected())
  23.    {
  24.        cout << endl; // Retorno.
  25.        cout << "Introduzca la opcion deseada: " << endl;
  26.        cout << "Pulse 1 para encender el Led, pulse 2 para apagar." << endl << endl; // Muestra texto en pantalla.
  27.  
  28.        cin >> opc; // Aquí introduces un número, el 1 o el 2.
  29.  
  30.        switch (opc) // Espera recibir un 1 o un 2.
  31.        {
  32.        case 1:
  33.            // Encener luz.
  34.            cout << "Enviando: " << Luz_ON << endl; // Muestra en pantalla textos.
  35.            Puerto->WriteData(Luz_ON, sizeof(Luz_ON) - 1); // Envía al puerto el texto "Luz_ON".
  36.            break;
  37.  
  38.        case 2:
  39.            // Apagar luz.
  40.            cout << "Enviando: " << Luz_OFF << endl;
  41.            Puerto->WriteData(Luz_OFF, sizeof(Luz_OFF) - 1);
  42.            break;
  43.  
  44.        default: // Si haz pulsado otro número distinto del 1 y 2, muestra
  45.            cout << "Puse del 1 al 2."; // este mensaje.
  46.        }
  47.  
  48.  
  49.        Sleep(500);
  50.        int n = Puerto->ReadData(lectura, 49); // Recibe datos del puerto serie.
  51.        if (n > 0)
  52.        {
  53.            lectura[n + 1] = '\0'; // Limpia de basura la variable.
  54.            cout << "Recibido: " << lectura << endl; // Muestra en pantalla dato recibido.
  55.            cout << "-------------------" << endl;
  56.        }
  57.  
  58.        cin.ignore(256, '\n'); // Limpiar buffer del teclado.
  59.    }
  60. }

Estoy siguiendo la guía del enlace de abajo a partir de la página 54.

Ver tutorial (https://drive.google.com/file/d/0B6HKwsbbpgrLSlpSM3A5Qy1yV00/view?resourcekey=0-xH8FUQc5A-lF3seHVpguDQ).

Saludos.


Título: Re: No funciona con la versión VS 202
Publicado por: Eternal Idol en 22 Enero 2023, 15:37 pm
Usando C++ nativo de la época del Visual Studio 2017 el programa funciona de maravilla. Probando ahora la versión del Visual Studio 2022, a pesar que es el mismo código, me da error por todas partes.

¿Errores al compilar o al ejecutar?


Título: Re: No funciona con la versión VS 202
Publicado por: Meta en 22 Enero 2023, 15:55 pm
No deja compilar, muestra estos errores.

(https://i.postimg.cc/wMNWWb1w/Captura.jpg)

Viene de la librería esta.

SerialClass.cpp:
Código
  1. #include "SerialClass.h"
  2.  
  3. Serial::Serial(char *portName)
  4. {
  5.    //We're not yet connected
  6.    this->connected = false;
  7.  
  8.    //Try to connect to the given port throuh CreateFile
  9.    this->hSerial = CreateFile(portName,
  10.            GENERIC_READ | GENERIC_WRITE,
  11.            0,
  12.            NULL,
  13.            OPEN_EXISTING,
  14.            FILE_ATTRIBUTE_NORMAL,
  15.            NULL);
  16.  
  17.    //Check if the connection was successfull
  18.    if(this->hSerial==INVALID_HANDLE_VALUE)
  19.    {
  20.        //If not success full display an Error
  21.        if(GetLastError()==ERROR_FILE_NOT_FOUND){
  22.  
  23.            //Print Error if neccessary
  24.            printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName);
  25.  
  26.        }
  27.        else
  28.        {
  29.            printf("ERROR!!!");
  30.        }
  31.    }
  32.    else
  33.    {
  34.        //If connected we try to set the comm parameters
  35.        DCB dcbSerialParams = {0};
  36.  
  37.        //Try to get the current
  38.        if (!GetCommState(this->hSerial, &dcbSerialParams))
  39.        {
  40.            //If impossible, show an error
  41.            printf("failed to get current serial parameters!");
  42.        }
  43.        else
  44.        {
  45.            //Define serial connection parameters for the arduino board
  46.            dcbSerialParams.BaudRate=CBR_115200;
  47.            dcbSerialParams.ByteSize=8;
  48.            dcbSerialParams.StopBits=ONESTOPBIT;
  49.            dcbSerialParams.Parity=NOPARITY;
  50.  
  51.             //Set the parameters and check for their proper application
  52.             if(!SetCommState(hSerial, &dcbSerialParams))
  53.             {
  54.                printf("ALERT: Could not set Serial Port parameters");
  55.             }
  56.             else
  57.             {
  58.                 //If everything went fine we're connected
  59.                 this->connected = true;
  60.                 //We wait 2s as the arduino board will be reseting
  61.                 Sleep(ARDUINO_WAIT_TIME);
  62.             }
  63.        }
  64.    }
  65.  
  66. }
  67.  
  68. Serial::~Serial()
  69. {
  70.    //Check if we are connected before trying to disconnect
  71.    if(this->connected)
  72.    {
  73.        //We're no longer connected
  74.        this->connected = false;
  75.        //Close the serial handler
  76.        CloseHandle(this->hSerial);
  77.    }
  78. }
  79.  
  80. int Serial::ReadData(char *buffer, unsigned int nbChar)
  81. {
  82.    //Number of bytes we'll have read
  83.    DWORD bytesRead;
  84.    //Number of bytes we'll really ask to read
  85.    unsigned int toRead;
  86.  
  87.    //Use the ClearCommError function to get status info on the Serial port
  88.    ClearCommError(this->hSerial, &this->errors, &this->status);
  89.  
  90.    //Check if there is something to read
  91.    if(this->status.cbInQue>0)
  92.    {
  93.        //If there is we check if there is enough data to read the required number
  94.        //of characters, if not we'll read only the available characters to prevent
  95.        //locking of the application.
  96.        if(this->status.cbInQue>nbChar)
  97.        {
  98.            toRead = nbChar;
  99.        }
  100.        else
  101.        {
  102.            toRead = this->status.cbInQue;
  103.        }
  104.  
  105.        //Try to read the require number of chars, and return the number of read bytes on success
  106.        if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0)
  107.        {
  108.            return bytesRead;
  109.        }
  110.  
  111.    }
  112.  
  113.    //If nothing has been read, or that an error was detected return -1
  114.    return -1;
  115.  
  116. }
  117.  
  118.  
  119. bool Serial::WriteData(char *buffer, unsigned int nbChar)
  120. {
  121.    DWORD bytesSend;
  122.  
  123.    //Try to write the buffer on the Serial port
  124.    if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0))
  125.    {
  126.        //In case it don't work get comm error and return false
  127.        ClearCommError(this->hSerial, &this->errors, &this->status);
  128.  
  129.        return false;
  130.    }
  131.    else
  132.        return true;
  133. }
  134.  
  135. bool Serial::IsConnected()
  136. {
  137.    //Simply return the connection status
  138.    return this->connected;
  139. }

Antes funcionaba todo. Ya no funciona ni modo 32 bits, ni 64 bits.

Saludos.


Título: Re: No funciona con la versión VS 202
Publicado por: Eternal Idol en 22 Enero 2023, 18:06 pm
https://learn.microsoft.com/es-es/cpp/error-messages/compiler-errors-2/compiler-error-c2665?view=msvc-170

Hay algo que no cierra cuando te dice que hay mas de un constructor definido para la clase Serial y segun el codigo hay uno solo.


Título: Re: No funciona con la versión VS 202
Publicado por: Meta en 22 Enero 2023, 19:46 pm
Holaaaaaaa:

(https://i.postimg.cc/5t7w01rQ/Captura.jpg)

Y la clase.
(https://i.postimg.cc/HxFXwzdp/Captura2.jpg)

Que deje de funcionar los programas que hacer en C++ nativo es lo que me pone de mala leche. En los .net estas cosas ocurren cuando pasan unos 10 años o más.


Título: Re: No funciona con la versión VS 202
Publicado por: Eternal Idol en 22 Enero 2023, 20:47 pm
Me compila perfectamente con esta version tanto en x86 como x64, sera un problema de tu proyecto o el codigo que se compila no es el que crees.

**********************************************************************
** Visual Studio 2022 Developer Command Prompt v17.4.4
** Copyright (c) 2022 Microsoft Corporation
**********************************************************************

cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.34.31937 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: cl [ option... ] filename... [ /link linkoption... ]


Título: Re: No funciona con la versión VS 202
Publicado por: RayR en 22 Enero 2023, 20:56 pm
Dado el tipo de error, lo que deberías postear es el contenido de SerialClass.h. Es casi seguro que ahí esté el problema. O cambia el parámetro de Serial::Serial a const char*, que de cualquier forma, independientemente de que compile o no, es lo correcto si quieres aceptar cadenas literales.


Título: Re: No funciona con la versión VS 202
Publicado por: Meta en 22 Enero 2023, 22:15 pm
No me puedo creer que te funcione.

Si te refieres a esto, da más errores aún.
Código
  1. Serial::Serial(const char *portName)

Ya que hablas del proyecto...
(https://i.postimg.cc/gcNXGbMb/Captura3.jpg)

El .h es este.

Código
  1. #ifndef SERIALCLASS_H_INCLUDED
  2. #define SERIALCLASS_H_INCLUDED
  3.  
  4. #define ARDUINO_WAIT_TIME 2000
  5.  
  6. #include <windows.h>
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9.  
  10. class Serial
  11. {
  12.    private:
  13.        //Serial comm handler
  14.        HANDLE hSerial;
  15.        //Connection status
  16.        bool connected;
  17.        //Get various information about the connection
  18.        COMSTAT status;
  19.        //Keep track of last error
  20.        DWORD errors;
  21.  
  22.    public:
  23.        //Initialize Serial communication with the given COM port
  24.        Serial(char *portName);
  25.        //Close the connection
  26.        //NOTA: for some reason you can't connect again before exiting
  27.        //the program and running it again
  28.        ~Serial();
  29.        //Read data in a buffer, if nbChar is greater than the
  30.        //maximum number of bytes available, it will return only the
  31.        //bytes available. The function return -1 when nothing could
  32.        //be read, the number of bytes actually read.
  33.        int ReadData(char *buffer, unsigned int nbChar);
  34.        //Writes data from a buffer through the Serial connection
  35.        //return true on success.
  36.        bool WriteData(char *buffer, unsigned int nbChar);
  37.        //Check if we are actually connected
  38.        bool IsConnected();
  39.  
  40.  
  41. };
  42.  
  43. #endif // SERIALCLASS_H_INCLUDED


Título: Re: No funciona con la versión VS 202
Publicado por: Eternal Idol en 22 Enero 2023, 22:21 pm
No me puedo creer que te funcione.

Y yo no puedo creer que te de ese error teniendo solo un constructor ... hay algo que no corresponde con lo que decis/mostras. Crea un proyecto nuevo con los mismos archivos fuente QUE PEGASTE ACA EN EL FORO (no los que tenes en el disco) y proba de nuevo (eso es lo que hice).

Si te refieres a esto, da más errores aún.

Si lo cambias en el .h y el .cpp no da ningun error.

Ya que hablas del proyecto...

Eso no muestra nada, el proyecto podria tener por ejemplo (entiendo que no es el caso y por eso no mencione lo de const) esta opcion habilitada:
https://learn.microsoft.com/en-us/cpp/build/reference/zc-strictstrings-disable-string-literal-type-conversion?view=msvc-160

Hay cientos de opciones ... y una de ellas es el standard a usar ... ¿Elegiste ISO C++ 20 por casualidad? Si es asi hace lo que te dijo RayR.

La proxima vez fijate en el output del compilador:
Build started...
1>------ Build started: Project: arduino, Configuration: Debug Win32 ------
1>SerialClass.cpp
1>meta.cpp
1>C:\src\arduino\meta.cpp(13,36): error C2665: 'Serial::Serial': no overloaded function could convert all the argument types
1>C:\src\arduino\SerialClass.h(41,1): message : could be 'Serial::Serial(const Serial &)'
1>C:\src\arduino\meta.cpp(13,36): message : 'Serial::Serial(const Serial &)': cannot convert argument 1 from 'const char [5]' to 'const Serial &'
1>C:\src\arduino\meta.cpp(13,37): message : Reason: cannot convert from 'const char [5]' to 'const Serial'
1>C:\src\arduino\meta.cpp(13,37): message : No constructor could take the source type, or constructor overload resolution was ambiguous
1>C:\src\arduino\SerialClass.h(24,9): message : or       'Serial::Serial(char *)'
1>C:\src\arduino\meta.cpp(13,36): message : 'Serial::Serial(char *)': cannot convert argument 1 from 'const char [5]' to 'char *'
1>C:\src\arduino\meta.cpp(13,37): message : Conversion from string literal loses const qualifier (see /Zc:strictStrings)
1>C:\src\arduino\meta.cpp(13,36): message : while trying to match the argument list '(const char [5])'


Título: Re: No funciona con la versión VS 202
Publicado por: Meta en 22 Enero 2023, 22:46 pm
Uso el que me viene predeterminado.
(https://i.postimg.cc/59Yq0mrt/Captura4.jpg)

Puedes seleccionar el 14, 17 y 20. Hasta ahí llegaron.

No he tocado nada, me imagino que toco el que viene por defecto.

En cuanto al const. Me imagino que será en la .h
Código
  1.    public:
  2.        //Initialize Serial communication with the given COM port
  3.        Serial(const char *portName);

Edito:

Ya compila, por fin. Todo por no incluir el const en cpp y h.

Muchísimas gracias a todos.  ;-) ;-) ;-) ;-) ;-) ;-)


Título: Re: No funciona con la versión VS 202
Publicado por: Eternal Idol en 22 Enero 2023, 22:50 pm
Uso el que me viene predeterminado.

Hay cientos de opciones y se pueden sobreescribir por archivo fuente ... subi el arduino.vcxproj si queres continuar investigando.

En cuanto al const. Me imagino que será en la .h

Tambien en el cpp por supuesto.


Título: Re: No funciona con la versión VS 202
Publicado por: Meta en 22 Enero 2023, 23:19 pm
No te había leído. Reedité el post de la página anterior, ya funciona.


Título: Re: No funciona con la versión VS 202
Publicado por: Meta en 25 Enero 2023, 00:07 am
Quiero añadir este código.
Código
  1. #pragma region "Configuración ventana."
  2.    // Mostrar caracteres correctamente en pantalla y título de la ventana.
  3.    SetConsoleOutputCP(65001);
  4.    wchar_t titulo[128];
  5.    MultiByteToWideChar(CP_UTF8, 0, "Led Arduino C++ nativo", -1, titulo, 128);
  6.    SetConsoleTitle(titulo);
  7.  
  8.    // Tamaño de la pantalla. Se cambia en los dos últimos dígitos.
  9.    SMALL_RECT r = { 0, 0, 80, 20 }; // X = 49, Y = 9.
  10.    SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &r);
  11.  
  12.    // Cambio color de A (verde claro), color letras 0 (negro).
  13.    system("color A0");
  14.  
  15.    // Ocultar cursor.
  16.    CONSOLE_CURSOR_INFO cci;
  17.    GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
  18.    cci.bVisible = 0; // 0 oculta. 1 muestra cursor.
  19.    SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
  20. #pragma endregion

Y me falla con este error.

Gravedad   Código   Descripción   Proyecto   Archivo   Línea   Estado suprimido
Error   C2664   'BOOL SetConsoleTitleA(LPCSTR)': el argumento 1 no puede convertirse de 'wchar_t [128]' a 'LPCSTR'   Led Arduino CPP nativo 02   D:\Visual Studio 2022\Led Arduino CPP nativo 02\Led Arduino CPP nativo 02\Led Arduino CPP nativo 02.cpp   30   


Título: Re: No funciona con la versión VS 202
Publicado por: Eternal Idol en 25 Enero 2023, 00:43 am
Estas llamando a la version ANSI de la funcion y pasandole una cadena ancha. Llama a SetConsoleTitleW (en lugar de SetConsoleTitleA) o pasale una cadena de caracteres de toda la vida.


Título: Re: No funciona con la versión VS 202
Publicado por: Meta en 25 Enero 2023, 07:09 am
Ya funciona, te la saber toda. Muchas gracias horonable Eternal Idol.  ;-)


Título: Re: No funciona con la versión VS 202
Publicado por: Eternal Idol en 25 Enero 2023, 09:55 am
De nadas.