Delphi interface with Arduino and serial port.

Hello:

I want to use Arduino with Delphi controlling the serial port. Use Delphi Tokyo 10.2.

What you have to do is the interface of Delphi is to turn on and off a Led, then you get messages from Arduino indicating when the Led is on or off.

An example:

The library for Delphi is this:

I want them to help me to be able to turn on and off a led.

The basic Arduino code is this:

const byte Led = 13;   // Declaramos la variable pin del Led.
char caracter;
String comando;

void setup()
{
  pinMode(Led, OUTPUT);  // Inicializa el pin del LED como salida:
  Serial.begin(115200);     // Puerto serie 115200 baudios.
}

void loop()
{
  /*
    Voy leyendo carácter a carácter lo que se recibe por el canal serie
    (mientras llegue algún dato allí), y los voy concatenando uno tras otro
    en una cadena. En la práctica, si usamos el "Serial monitor" el bucle while
    acabará cuando pulsamos Enter. El delay es conveniente para no saturar el
    canal serie y que la concatenación se haga de forma ordenada.
  */
  while (Serial.available() > 0)
  {
    caracter = Serial.read();
    comando.concat(caracter);
    delay(10);
  }

  /*
    Una vez ya tengo la cadena "acabada", compruebo su valor y hago que
    la placa Arduino reacciones según sea este. Aquí podríamos hacer lo
    que quisiéramos: si el comando es "tal", enciende un Led, si es cual,
    mueve un motor... y así.
  */

  // Si le llega el mensaje Luz_ON.
  if (comando.equals("Luz_ON") == true)
  {
    digitalWrite(Led, HIGH); // Enciende el Led 13.
    Serial.write("ON - Led encendido.");    // Envía este mensaje a C++.
  }

  // Si le llega el mensaje Luz_ON.
  if (comando.equals("Luz_OFF") == true)
  {
    digitalWrite(Led, LOW); // Apaga el Led 13.
    Serial.write("OFF - Led apagado. ");  // Envía este mensaje a C++.
  }

  // Limpiamos la cadena para volver a recibir el siguiente comando.
  comando = "";
}

Can you help me?

Greetings.

does the Arduino code work as expected when run with the serial monitor or a terminal emulator?
you could have problems if the string you are testing contains '\n' or '\r'
try testring using String.startsWith() so it ignores '\n', '\r' etc

in Delphi you would add event handlers to the buttons
in the event handlers you transmit the appropriate commands to the selected COM port

Hi:

I do not use \r \n.

I want an example of configuring the serial port from Delphi and being able to send commands to turn on and off a Led.

:wink:

Have a look at the examples in Serial Input Basics - simple reliable ways to receive data.

It is not a good idea to use the String (capital S) class on an Arduino as it can cause memory corruption in the small memory on an Arduino. Just use cstrings - char arrays terminated with 0.

It will be much easier to debug your program if you first get your Arduino program working with the Serial Monitor and then get your Delphi program to take the place of the Serial Monitor with the Arduino code unchanged.

I don't know Delphi - is a Python - Arduino demo any help?

...R

Hi:

The Arduino code works fine with the "Monitor series", I have checked 100% and then I have used it with the code in C ++ Win32 console.

Interface in C ++:

Code:

#include
#include
#include
#include "SerialClass.h"
using namespace std;

void main()
{
    // Título de la ventana
    SetConsoleTitle("Control Led Arduino - Visual Studio C++ 2017");

    // Puerto serie.
    Serial* Puerto = new Serial("COM4");

    // 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.
    }
}

View video.

I did a tutorial in Spanish and PDF on the interface in C ++ Win32, Arduino and serial port.

See tutorial.

I want to make it work with Delphi. Know your code to be able to send commands to turn a Led on and off.

:wink:

Metaconta:
I want to make it work with Delphi. Know your code to be able to send commands to turn a Led on and off.

Ask about serial programming on a Delphi Forum ?

...R

Solved, I already have Delphi and Arduino.

:wink:

Metaconta:
Solved, I already have Delphi and Arduino.

Can you explain what you did for the benefit of others?

Your image is not displaying on my PC.

...R

Hi:

I hope this time you see the image.

It's upside down - did you not proof read it after posting?

And you have not explained how you solved the problem.

...R

Hi:

I solved it thanks to this video.

View video.

Code Delphi:

unit Principal;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, CPort;

type
  TForm1 = class(TForm)
    Button_ON: TButton;
    Button_OFF: TButton;
    Label1: TLabel;
    ComPort1: TComPort;
    Button_COM: TButton;
    Button_Abrir: TButton;
    Memo_Mensajes: TMemo;
    Label_Mensajes: TLabel;
    Button_Limpiar: TButton;
    procedure Button_COMClick(Sender: TObject);
    procedure Button_AbrirClick(Sender: TObject);
    procedure ComPort1AfterClose(Sender: TObject);
    procedure ComPort1AfterOpen(Sender: TObject);
    procedure Button_ONClick(Sender: TObject);
    procedure Button_OFFClick(Sender: TObject);
    procedure ComPort1RxChar(Sender: TObject; Count: Integer);
    procedure Button_LimpiarClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.Button_AbrirClick(Sender: TObject);
begin
  // Si el puerto está conectado.
  if ComPort1.Connected then
  begin
    ComPort1.Close; // Cierra el puerto.

    Button_COM.Enabled := True;
    Button_ON.Enabled := False;
    Button_OFF.Enabled := False;
  end

  else  // En caso contrario.

  begin
    ComPort1.Open;  // Abre el puerto.

    Button_COM.Enabled := False;
    Button_ON.Enabled := True;
    Button_OFF.Enabled := True;
  end;
end;

procedure TForm1.Button_COMClick(Sender: TObject);
begin
ComPort1.ShowSetupDialog; // Abre la configuración del puerto.
end;

procedure TForm1.Button_LimpiarClick(Sender: TObject);
begin
Memo_Mensajes.Clear();  // Limpia el contenido del Memo.
end;

procedure TForm1.Button_ONClick(Sender: TObject);
begin
ComPort1.WriteStr('Luz_ON');  // Envía el comando "Luz_ON" al puerto.
end;

procedure TForm1.Button_OFFClick(Sender: TObject);
begin
ComPort1.WriteStr('Luz_OFF'); // Envía comando al puerto.
end;

procedure TForm1.ComPort1AfterClose(Sender: TObject);
begin
  if Button_Abrir <> nil then
    Button_Abrir.Caption := 'Abrir';
end;

procedure TForm1.ComPort1AfterOpen(Sender: TObject);
begin
Button_Abrir.Caption := 'Cerrar';
end;


procedure TForm1.ComPort1RxChar(Sender: TObject; Count: Integer);
var
  Str: String;
begin
  ComPort1.ReadStr(Str, Count); // Recibe caracteres desde el puerto.
  Memo_Mensajes.Lines.Add( Str ); // Muestra los textos en pantalla.

  Memo_Mensajes.Lines.SaveToFile('archivo.txt');

end;

end.

:wink:

Thanks for that - it rounds the Thread off nicely for future readers.

Personally, I will happily stick to Python.

...R

Robin2:
Personally, I will happily stick to Python.

Good choice as I don't see many job ads for Delphi programmers. :slight_smile:

Hi:

Arduino code.

#include <LiquidCrystal.h>

// Inicializa la librería con sus pines indicados.
// RS, RW, Enable, D4, D5, D6, D7.
LiquidCrystal lcd(8, NULL, 9, 4, 5, 6, 7);
// LiquidCrystal lcd(8, 9, 4, 5, 6, 7);

// Pin 10 para saber que es luz de fondo.
const byte LuzFondo = 10;

const byte Led = 13;   // Declaramos la variable pin del Led.
char caracter;
String comando;

void setup()
{
  pinMode(Led, OUTPUT);  // Inicializa el pin del LED como salida:
  Serial.begin(115200);     // Puerto serie 115200 baudios.
  lcd.begin(16, 2);         // Formato de pantalla.
  lcd.clear();      // Borra la pantalla y su posición superior izquierda.
  lcd.print("    Arduino     ");
  delay(1000);
}

void loop()
{
  /*
    Voy leyendo carácter a carácter lo que se recibe por el canal serie
    (mientras llegue algún dato allí), y los voy concatenando uno tras otro
    en una cadena. En la práctica, si usamos el "Serial monitor" el bucle while
    acabará cuando pulsamos Enter. El delay es conveniente para no saturar el
    canal serie y que la concatenación se haga de forma ordenada.
  */
  while (Serial.available() > 0)
  {
    caracter = Serial.read();
    comando.concat(caracter);
    delay(10);
  }

  /*
    Una vez ya tengo la cadena "acabada", compruebo su valor y hago que
    la placa Arduino reacciones según sea este. Aquí podríamos hacer lo
    que quisiéramos: si el comando es "tal", enciende un Led, si es cual,
    mueve un motor... y así.
  */

  // Si los carácteres es recibido y verdadero.
  if (comando.equals("Luz_ON") == true)
  {
    digitalWrite(Led, HIGH); // Enciende el Led 13.
    Serial.write("ON - Led encendido.");    // Envía este mensaje al PC.
    lcd.setCursor(0, 1);
    lcd.print("Luz ON.         "); // Mostrar en el LCD.
  }


  if (comando.equals("Luz_OFF") == true)
  {
    digitalWrite(Led, LOW); // Apaga el Led 13.
    Serial.write("OFF - Led apagado. ");  // Envía este mensaje al PC.
    lcd.setCursor(0, 1);
    lcd.print("Luz OFF.        "); // Mostrar en el LCD.
  }

  // Limpiamos la cadena para volver a recibir el siguiente comando.
  comando = "";
}

Python I have pending.

I've done tutos with Java, C #, VB .NET, VB 6, C / C ++, Delphi and I'm missing Python. Also F #, MS-DOS and many more with Arduino.

Metaconta:
and I'm missing Python.

Python - Arduino demo

...R

The Delphi and Arduino tutorial is now finished. Now I'm going to make one the same but in Python. Thanks for sharing the link.

Having looked (briefly) at your Delphi demo it seems quite like my Python GUI demo

...R

Robin2:
Having looked (briefly) at your Delphi demo it seems quite like my Python GUI demo

...R

Thanks for the link.

I have many tutorials in Spanish of the same thing. In the future I will make one in Python.

View document. (Spanish).

View in C++.
https://forum.arduino.cc/index.php?topic=466912.0

:wink: