Autor
|
Tema: ERROR C2665 'Serial::Serial':ninguna función sobrecargada pudo convertir todos los tipos de argumento (Leído 4,478 veces)
|
Meta
|
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 /* Para crear conexión con los puertos COM1 - COM9. Serial* Arduino = new Serial("COM7"); Para crear conexión con los puertos COM10 en adelante. Serial* Arduino = new Serial("\\\\.\\COM10"); */ #include <iostream> #include <fstream> #include <windows.h> // Para mostrar texto en el título de la ventana. #include <stdio.h> // Cambio color de fondo y letras. #include "SerialClass.h" using namespace std; //using std::cout; //using std::cin; // Función posición del cursor. void gotoxy(int ancho_x, int alto_y) { HANDLE hcon; hcon = GetStdHandle(STD_OUTPUT_HANDLE); COORD dwPos{}; dwPos.X = ancho_x; dwPos.Y = alto_y; SetConsoleCursorPosition(hcon, dwPos); } int main() { #pragma region "Configuración ventana." // Mostrar caracteres correctamente en pantalla y título de la ventana. SetConsoleOutputCP(65001); wchar_t titulo[128]; MultiByteToWideChar(CP_UTF8, 0, "Arduino puerto serie - C++ nativo", -1, titulo, 128); SetConsoleTitleW(titulo); // Tamaño de la pantalla. Se cambia en los dos últimos dígitos. SMALL_RECT r = { 0, 0, 120, 40 }; // X = 80, Y = 20. SetConsoleWindowInfo(GetStdHandle(STD_OUTPUT_HANDLE), TRUE, &r); // Cambio color de 6 (amarillo / naranja), color letras 0 (negro). system("color 60"); // Ocultar cursor. CONSOLE_CURSOR_INFO cci; GetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci); cci.bVisible = 0; // 0 oculta. 1 muestra cursor. SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cci); #pragma endregion // Puerto serie. Serial* Puerto = new Serial("COM3"); // Comandos para Arduino. char Luz_ON[] = "Luz_ON"; // Envía "Luz_ON" al puerto serie. char Luz_OFF[] = "Luz_OFF"; char lectura[50] = "\0"; // Guardan datos de entrada del puerto. int opc; // Guarda un 1 o 2 tipo entero queintroduces desde la consola. while (Puerto->IsConnected()) { cout << endl; // Retorno. cout << "Introduzca la opcion deseada: " << endl; cout << "Pulse 1 para encender el Led, pulse 2 para apagar." << endl << endl; // Muestra texto en pantalla. cin >> opc; // Aquí introduces un número, el 1 o el 2. switch (opc) // Espera recibir un 1 o un 2. { case 1: // Encener luz. cout << "Enviando: " << Luz_ON << endl; // Muestra en pantalla textos. Puerto->WriteData(Luz_ON, sizeof(Luz_ON) - 1); // Envía al puerto el texto "Luz_ON". break; case 2: // Apagar luz. cout << "Enviando: " << Luz_OFF << endl; Puerto->WriteData(Luz_OFF, sizeof(Luz_OFF) - 1); break; default: // Si haz pulsado otro número distinto del 1 y 2, muestra cout << "Puse del 1 al 2."; // este mensaje. } Sleep(500); int n = Puerto->ReadData(lectura, 49); // Recibe datos del puerto serie. if (n > 0) { lectura[n + 1] = '\0'; // Limpia de basura la variable. cout << "Recibido: " << lectura << endl; // Muestra en pantalla dato recibido. cout << "-------------------" << endl; } cin.ignore(256, '\n'); // Limpiar buffer del teclado. } }
¿Alguna idea? Saludos.
|
|
|
En línea
|
|
|
|
Eternal Idol
Kernel coder
Moderador
 
Desconectado
Mensajes: 5.969
Israel nunca torturó niños, ni lo volverá a hacer.
|
¿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
|
En SerialClass.h.  #ifndef SERIALCLASS_H_INCLUDED #define SERIALCLASS_H_INCLUDED #define ARDUINO_WAIT_TIME 2000 #include <windows.h> #include <stdio.h> #include <stdlib.h> class Serial { private: //Serial comm handler HANDLE hSerial; //Connection status bool connected; //Get various information about the connection COMSTAT status; //Keep track of last error DWORD errors; public: //Initialize Serial communication with the given COM port Serial(char *portName); //Close the connection //NOTA: for some reason you can't connect again before exiting //the program and running it again ~Serial(); //Read data in a buffer, if nbChar is greater than the //maximum number of bytes available, it will return only the //bytes available. The function return -1 when nothing could //be read, the number of bytes actually read. int ReadData(char *buffer, unsigned int nbChar); //Writes data from a buffer through the Serial connection //return true on success. bool WriteData(char *buffer, unsigned int nbChar); //Check if we are actually connected bool IsConnected(); }; #endif // SERIALCLASS_H_INCLUDED
Espero que esta vez te diga algo.
|
|
|
En línea
|
|
|
|
Eternal Idol
Kernel coder
Moderador
 
Desconectado
Mensajes: 5.969
Israel nunca torturó niños, ni lo volverá a hacer.
|
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
|
Estas pasandole un const char, cambia el constructor a const char *.
¿Exactamente dónde del código? Si te refieres aquí. De este. char Luz_ON[] = "Luz_ON"; // Envía "Luz_ON" al puerto serie.
Por este orto. 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
Mensajes: 5.969
Israel nunca torturó niños, ni lo volverá a hacer.
|
¿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
|
Si te refieres a esto: De: Serial(char *portName);
A: Serial(const char *portName);
No sirve.
|
|
|
En línea
|
|
|
|
Eternal Idol
Kernel coder
Moderador
 
Desconectado
Mensajes: 5.969
Israel nunca torturó niños, ni lo volverá a hacer.
|
Sirve; algo habras hecho mal. El problema reducido a su minima expresion: #include <windows.h> struct Serial { #ifdef FIX Serial(const char *portName) { } #else Serial(char *portName) { } #endif }; void main() { Serial* Puerto = new Serial("COM3"); }

|
|
|
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
|
Había que ponerlo aquí. Ahora me funciona. #include "SerialClass.h" Serial::Serial(const char *portName) { //We're not yet connected this->connected = false; //Try to connect to the given port throuh CreateFile this->hSerial = CreateFile(portName, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); //Check if the connection was successfull if(this->hSerial==INVALID_HANDLE_VALUE) { //If not success full display an Error if(GetLastError()==ERROR_FILE_NOT_FOUND){ //Print Error if neccessary printf("ERROR: Handle was not attached. Reason: %s not available.\n", portName); } else { printf("ERROR!!!"); } } else { //If connected we try to set the comm parameters DCB dcbSerialParams = {0}; //Try to get the current if (!GetCommState(this->hSerial, &dcbSerialParams)) { //If impossible, show an error printf("failed to get current serial parameters!"); } else { //Define serial connection parameters for the arduino board dcbSerialParams.BaudRate=CBR_115200; dcbSerialParams.ByteSize=8; dcbSerialParams.StopBits=ONESTOPBIT; dcbSerialParams.Parity=NOPARITY; //Set the parameters and check for their proper application if(!SetCommState(hSerial, &dcbSerialParams)) { printf("ALERT: Could not set Serial Port parameters"); } else { //If everything went fine we're connected this->connected = true; //We wait 2s as the arduino board will be reseting Sleep(ARDUINO_WAIT_TIME); } } } } Serial::~Serial() { //Check if we are connected before trying to disconnect if(this->connected) { //We're no longer connected this->connected = false; //Close the serial handler CloseHandle(this->hSerial); } } int Serial::ReadData(char *buffer, unsigned int nbChar) { //Number of bytes we'll have read DWORD bytesRead; //Number of bytes we'll really ask to read unsigned int toRead; //Use the ClearCommError function to get status info on the Serial port ClearCommError(this->hSerial, &this->errors, &this->status); //Check if there is something to read if(this->status.cbInQue>0) { //If there is we check if there is enough data to read the required number //of characters, if not we'll read only the available characters to prevent //locking of the application. if(this->status.cbInQue>nbChar) { toRead = nbChar; } else { toRead = this->status.cbInQue; } //Try to read the require number of chars, and return the number of read bytes on success if(ReadFile(this->hSerial, buffer, toRead, &bytesRead, NULL) && bytesRead != 0) { return bytesRead; } } //If nothing has been read, or that an error was detected return -1 return -1; } bool Serial::WriteData(char *buffer, unsigned int nbChar) { DWORD bytesSend; //Try to write the buffer on the Serial port if(!WriteFile(this->hSerial, (void *)buffer, nbChar, &bytesSend, 0)) { //In case it don't work get comm error and return false ClearCommError(this->hSerial, &this->errors, &this->status); return false; } else return true; } bool Serial::IsConnected() { //Simply return the connection status return this->connected; }
Muchas gracias mi muy distinguido amigo.
|
|
|
En línea
|
|
|
|
Eternal Idol
Kernel coder
Moderador
 
Desconectado
Mensajes: 5.969
Israel nunca torturó niños, ni lo volverá a hacer.
|
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
|
|
|
|
Mensajes similares |
|
Asunto |
Iniciado por |
Respuestas |
Vistas |
Último mensaje |
|
|
LO QUE TODOS ESPERABAN COMO CLONAR UN SB3100 VIA PUERTO SERIAL
Software
|
LIAM_GALLAGHER
|
1
|
2,351
|
18 Julio 2005, 09:04 am
por deimos_asd
|
|
|
Funcion mail() error para ultimo argumento (return-path)
PHP
|
Diabliyo
|
1
|
3,430
|
13 Agosto 2010, 01:18 am
por Diabliyo
|
|
|
conectar impresora fiscal de puerto serial a placa sin puerto serial
Hardware
|
rub'n
|
3
|
5,870
|
30 Mayo 2013, 22:45 pm
por rub'n
|
|
|
leer datos de comunicacion serial (BYTE) de indicador de peso y convertir a int
« 1 2 3 »
Programación C/C++
|
pedromigl010
|
22
|
14,367
|
3 Julio 2016, 17:42 pm
por pedromigl010
|
|
|
Error con comunicación serial en Android
Android
|
gabo1069
|
0
|
2,126
|
14 Junio 2023, 17:14 pm
por gabo1069
|
|