elhacker.net cabecera Bienvenido(a), Visitante. Por favor Ingresar o Registrarse
¿Perdiste tu email de activación?.


Tema destacado: Sigue las noticias más importantes de seguridad informática en el Twitter! de elhacker.NET


+  Foro de elhacker.net
|-+  Programación
| |-+  Programación C/C++ (Moderadores: Eternal Idol, Littlehorse, K-YreX)
| | |-+  ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
0 Usuarios y 1 Visitante están viendo este tema.
Páginas: [1] 2 Ir Abajo Respuesta Imprimir
Autor Tema: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento  (Leído 4,478 veces)
Meta


Desconectado Desconectado

Mensajes: 3.502



Ver Perfil WWW
ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« en: 27 Octubre 2024, 00:02 am »

Buenas.

Este es el código que me da error probándolo con Visual Studio 2022 de C++ nativo.

Gravedad   Código   Descripción   Proyecto   Archivo   Línea   Estado suprimido   Detalles
Error (activo)   E0289   ninguna instancia del constructor "Serial::Serial" coincide con la lista de argumentos   Arduino y puerto serie CPP Consola 01   D:\Visual Studio 2022\Arduino y puerto serie CPP Consola 01\Arduino y puerto serie CPP Consola 01\Arduino y puerto serie CPP Consola 01.cpp   56   
   

Gravedad   Código   Descripción   Proyecto   Archivo   Línea   Estado suprimido   Detalles
Error   C2665   'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento   Arduino y puerto serie CPP Consola 01   D:\Visual Studio 2022\Arduino y puerto serie CPP Consola 01\Arduino y puerto serie CPP Consola 01\Arduino y puerto serie CPP Consola 01.cpp   56      




Código
  1. /*
  2.     Para crear conexión con los puertos COM1 - COM9.
  3.     Serial* Arduino = new Serial("COM7");
  4.  
  5.     Para crear conexión con los puertos COM10 en adelante.
  6.     Serial* Arduino = new Serial("\\\\.\\COM10");
  7. */
  8. #include <iostream>
  9. #include <fstream>
  10. #include <windows.h> // Para mostrar texto en el título de la ventana.
  11. #include <stdio.h>   // Cambio color de fondo y letras.
  12. #include "SerialClass.h"
  13.  
  14. using namespace std;
  15. //using std::cout;
  16. //using std::cin;
  17.  
  18. // Función posición del cursor.
  19. void gotoxy(int ancho_x, int alto_y)
  20. {
  21. HANDLE hcon;
  22. hcon = GetStdHandle(STD_OUTPUT_HANDLE);
  23. COORD dwPos{};
  24. dwPos.X = ancho_x;
  25. dwPos.Y = alto_y;
  26. SetConsoleCursorPosition(hcon, dwPos);
  27. }
  28.  
  29. int main()
  30. {
  31. #pragma region "Configuración ventana."
  32. // Mostrar caracteres correctamente en pantalla y título de la ventana.
  33. SetConsoleOutputCP(65001);
  34. wchar_t titulo[128];
  35. MultiByteToWideChar(CP_UTF8, 0, "Arduino puerto serie - C++ nativo", -1, titulo, 128);
  36. SetConsoleTitleW(titulo);
  37.  
  38. // Tamaño de la pantalla. Se cambia en los dos últimos dígitos.
  39. SMALL_RECT r = { 0, 0, 120, 40 }; // X = 80, Y = 20.
  40. SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &r);
  41.  
  42. // Cambio color de 6 (amarillo / naranja), color letras 0 (negro).
  43. system("color 60");
  44.  
  45. // Ocultar cursor.
  46. CONSOLE_CURSOR_INFO cci;
  47. GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
  48. cci.bVisible = 0; // 0 oculta. 1 muestra cursor.
  49. SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci);
  50. #pragma endregion
  51.  
  52.    // Puerto serie.
  53.    Serial* Puerto = new Serial("COM3");
  54.  
  55.    // Comandos para Arduino.
  56.    char Luz_ON[] = "Luz_ON"; // Envía "Luz_ON" al puerto serie.
  57.    char Luz_OFF[] = "Luz_OFF";
  58.    char lectura[50] = "\0"; // Guardan datos de entrada del puerto.
  59.  
  60.    int opc; // Guarda un 1 o 2 tipo entero queintroduces desde la consola.
  61.  
  62.    while (Puerto->IsConnected())
  63.    {
  64.        cout << endl; // Retorno.
  65.        cout << "Introduzca la opcion deseada: " << endl;
  66.        cout << "Pulse 1 para encender el Led, pulse 2 para apagar." << endl << endl; // Muestra texto en pantalla.
  67.  
  68.        cin >> opc; // Aquí introduces un número, el 1 o el 2.
  69.  
  70.        switch (opc) // Espera recibir un 1 o un 2.
  71.        {
  72.        case 1:
  73.            // Encener luz.
  74.            cout << "Enviando: " << Luz_ON << endl; // Muestra en pantalla textos.
  75.            Puerto->WriteData(Luz_ON, sizeof(Luz_ON) - 1); // Envía al puerto el texto "Luz_ON".
  76.            break;
  77.  
  78.        case 2:
  79.            // Apagar luz.
  80.            cout << "Enviando: " << Luz_OFF << endl;
  81.            Puerto->WriteData(Luz_OFF, sizeof(Luz_OFF) - 1);
  82.            break;
  83.  
  84.        default: // Si haz pulsado otro número distinto del 1 y 2, muestra
  85.            cout << "Puse del 1 al 2."; // este mensaje.
  86.        }
  87.  
  88.  
  89.        Sleep(500);
  90.        int n = Puerto->ReadData(lectura, 49); // Recibe datos del puerto serie.
  91.        if (n > 0)
  92.        {
  93.            lectura[n + 1] = '\0'; // Limpia de basura la variable.
  94.            cout << "Recibido: " << lectura << endl; // Muestra en pantalla dato recibido.
  95.            cout << "-------------------" << endl;
  96.        }
  97.  
  98.        cin.ignore(256, '\n'); // Limpiar buffer del teclado.
  99.    }
  100. }

¿Alguna idea?

Saludos.


En línea

Eternal Idol
Kernel coder
Moderador
***
Desconectado Desconectado

Mensajes: 5.969


Israel nunca torturó niños, ni lo volverá a hacer.


Ver Perfil WWW
Re: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« Respuesta #1 en: 27 Octubre 2024, 00:57 am »

¿Alguna idea?

Pasarle al constructor el tipo de paramatro que requiere, evidentemente no es un literal de cadena (o es otro tipo o hay mas parametros, es imposible saberlo con la informacion disponible).


En línea

La economía nunca ha sido libre: o la controla el Estado en beneficio del Pueblo o lo hacen los grandes consorcios en perjuicio de éste.
Juan Domingo Perón
Meta


Desconectado Desconectado

Mensajes: 3.502



Ver Perfil WWW
Re: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« Respuesta #2 en: 27 Octubre 2024, 01:10 am »

En SerialClass.h.



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

Espero que esta vez te diga algo.
En línea

Eternal Idol
Kernel coder
Moderador
***
Desconectado Desconectado

Mensajes: 5.969


Israel nunca torturó niños, ni lo volverá a hacer.


Ver Perfil WWW
Re: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« Respuesta #3 en: 27 Octubre 2024, 01:26 am »

Estas pasandole un const char, cambia el constructor a const char *.
En línea

La economía nunca ha sido libre: o la controla el Estado en beneficio del Pueblo o lo hacen los grandes consorcios en perjuicio de éste.
Juan Domingo Perón
Meta


Desconectado Desconectado

Mensajes: 3.502



Ver Perfil WWW
Re: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« Respuesta #4 en: 27 Octubre 2024, 01:39 am »

Estas pasandole un const char, cambia el constructor a const char *.

¿Exactamente dónde del código?

Si te refieres aquí.

De este.
Código
  1. char Luz_ON[] = "Luz_ON"; // Envía "Luz_ON" al puerto serie.

Por este orto.
Código
  1. const char* Luz_ON[] = "Luz_ON"; // Envía "Luz_ON" al puerto serie.

Sale otro error.
« Última modificación: 27 Octubre 2024, 07:48 am por Meta » En línea

Eternal Idol
Kernel coder
Moderador
***
Desconectado Desconectado

Mensajes: 5.969


Israel nunca torturó niños, ni lo volverá a hacer.


Ver Perfil WWW
Re: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« Respuesta #5 en: 27 Octubre 2024, 08:16 am »

¿Que? No ...

Serial* Puerto = new Serial("COM3"); << aca usas un const char
Serial(char *portName); << el constructor no coincide, cambialo


En línea

La economía nunca ha sido libre: o la controla el Estado en beneficio del Pueblo o lo hacen los grandes consorcios en perjuicio de éste.
Juan Domingo Perón
Meta


Desconectado Desconectado

Mensajes: 3.502



Ver Perfil WWW
Re: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« Respuesta #6 en: 27 Octubre 2024, 21:28 pm »

Si te refieres a esto:

De:
Código
  1. Serial(char *portName);

A:
Código
  1. Serial(const char *portName);

No sirve.
En línea

Eternal Idol
Kernel coder
Moderador
***
Desconectado Desconectado

Mensajes: 5.969


Israel nunca torturó niños, ni lo volverá a hacer.


Ver Perfil WWW
Re: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« Respuesta #7 en: 27 Octubre 2024, 23:21 pm »

Sirve; algo habras hecho mal.

El problema reducido a su minima expresion:
Código
  1. #include <windows.h>
  2.  
  3. struct Serial
  4. {
  5. #ifdef FIX
  6.        Serial(const char *portName)
  7. {
  8. }
  9. #else
  10. Serial(char *portName)
  11. {
  12. }
  13. #endif
  14. };
  15.  
  16. void main()
  17. {
  18.    Serial* Puerto = new Serial("COM3");
  19. }



En línea

La economía nunca ha sido libre: o la controla el Estado en beneficio del Pueblo o lo hacen los grandes consorcios en perjuicio de éste.
Juan Domingo Perón
Meta


Desconectado Desconectado

Mensajes: 3.502



Ver Perfil WWW
Re: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« Respuesta #8 en: 28 Octubre 2024, 00:51 am »

Había que ponerlo aquí. Ahora me funciona.

Código
  1. #include "SerialClass.h"
  2.  
  3. Serial::Serial(const 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. }

Muchas gracias mi muy distinguido amigo.
En línea

Eternal Idol
Kernel coder
Moderador
***
Desconectado Desconectado

Mensajes: 5.969


Israel nunca torturó niños, ni lo volverá a hacer.


Ver Perfil WWW
Re: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento
« Respuesta #9 en: 28 Octubre 2024, 01:05 am »

De nada. Y si, claro, si solo cambias el tipo en la declaracion - en el archivo de cabecera - vas a tener otro error (por implementar un constructor no declarado; error C2511: 'Serial::Serial(char *)': overloaded member function not found in 'Serial').
En línea

La economía nunca ha sido libre: o la controla el Estado en beneficio del Pueblo o lo hacen los grandes consorcios en perjuicio de éste.
Juan Domingo Perón
Páginas: [1] 2 Ir Arriba Respuesta Imprimir 

Ir a:  

WAP2 - Aviso Legal - Powered by SMF 1.1.21 | SMF © 2006-2008, Simple Machines