banner
xingli

xingli

猫娘爱好者

Reading Serial Data in Godot

Communication NuGet Package#

NuGet Gallery | System.IO.Ports 8.0.0-preview.3.23174.8

dotnet add package System.IO.Ports --version 8.0.0-preview.3.23174.8

Creating a Serial Instance#

Explain this line of code: SerialPort mySerialPort = new SerialPort("COM17", 9600, Parity.None, 8, StopBits.One);

This line of code creates an instance of the SerialPort class for communication with a serial port. The constructor of the SerialPort class accepts the following parameters:

  • portName (string): The name of the serial port, for example, "COM17".
  • baudRate (integer): The baud rate, for example, 9600.
  • parity (Parity enum): The parity bit, for example, Parity.None.
  • dataBits (integer): The number of data bits, for example, 8.
  • stopBits (StopBits enum): The number of stop bits, for example, StopBits.One.

In the above code, we create a SerialPort object for communication with the serial port named "COM17". We specify a baud rate of 9600, no parity bit, 8 data bits, and 1 stop bit.

You can modify these parameters according to your specific requirements for communication with your development board.

Communication Encoding#

Modify the communication encoding

If the encoding is UTF-8

If your development board uses UTF-8 encoding, you can specify the Encoding property of the SerialPort object as System.Text.Encoding.UTF8 when creating it, as shown below:

SerialPort mySerialPort = new SerialPort("COM17", 9600, Parity.None, 8, StopBits.One);
mySerialPort.Encoding = System.Text.Encoding.UTF8;

This way, your Godot program will read the serial data using UTF-8 encoding, avoiding any issues with garbled characters.

????

If you see a bunch of question marks in the console, it may be due to character encoding issues. When communicating via serial port, the sender and receiver need to use the same character encoding, otherwise the received data may appear garbled.

You can check the character encoding used by your development board when sending data and ensure that you use the same character encoding to read the data in your Godot program. For example, if your development board uses ASCII encoding, you can specify the Encoding property when creating the SerialPort object, as shown below:

SerialPort mySerialPort = new SerialPort("COM17", 9600, Parity.None, 8, StopBits.One);
mySerialPort.Encoding = System.Text.Encoding.ASCII;

I hope this information helps you resolve the issue.

If your program is unable to read data from the serial port, there could be several reasons:

  1. Incorrect serial port name. Please ensure that the serial port name specified in the constructor of the SerialPort class matches the serial port name connected to your development board.
  2. Incorrect baud rate. Please ensure that the baud rate specified in the constructor of the SerialPort class matches the baud rate used by your development board.
  3. Serial port not opened. Please ensure that you call the SerialPort.Open method to open the serial port.
  4. Development board not sending data. Please ensure that your development board is sending data through the serial port.

You can use the SerialPort.IsOpen property to check if the serial port is open. If the property returns true, it means the serial port is open; otherwise, it means the serial port is not open.

Additionally, you can add some debugging information in the catch (TimeoutException) block to help identify the issue. For example, you can do the following:

try
{
    string message = mySerialPort.ReadLine();
    GD.Print(message);
}
catch (TimeoutException)
{
    GD.Print("TimeoutException: Failed to read data from serial port.");
}

I hope this information helps you resolve the issue.

Multithreading#

Yes, the while (true) loop in this code will run indefinitely until you manually close the program. This can cause your Godot project to freeze after it starts.

If you want to read serial data in Godot without blocking the main thread, you can consider using threads or timers. For example, you can use the System.Threading.Thread class to create a new thread and read serial data in that thread, printing it to the console. Here's a simple example code:

using Godot;
using System;
using System.IO.Ports;
using System.Threading;

public partial class io : Node
{
    private bool _isRunning = true;

    public override void _Ready()
    {
        // Create and start a new thread
        Thread thread = new Thread(ReadSerialPort);
        thread.Start();
    }

    private void ReadSerialPort()
    {
        // Set the serial port name, baud rate, and timeout
        SerialPort mySerialPort = new SerialPort("COM17", 115200, Parity.None, 8, StopBits.One);
        mySerialPort.ReadTimeout = 500;

        // Open the serial port
        mySerialPort.Open();

        // Read data and print to the console
        while (_isRunning)
        {
            try
            {
                string message = mySerialPort.ReadLine();
                GD.Print(message);
            }
            catch (TimeoutException) { }
        }

        // Close the serial port
        mySerialPort.Close();
    }

    public override void _ExitTree()
    {
        // Stop the thread
        _isRunning = false;
    }
}

In the above code, we create a new thread and read serial data in that thread. When the Godot project exits, we stop the thread by setting the _isRunning variable to false. This way, we can read serial data without blocking the main thread.

Sending Serial Data#

If you want to send data to your development board via the serial port, you can use the Write method or WriteLine method of the SerialPort class. For example, the following code demonstrates how to send a string to the development board:

// Set the serial port name, baud rate, and timeout
SerialPort mySerialPort = new SerialPort("COM17", 9600, Parity.None, 8, StopBits.One);

// Open the serial port
mySerialPort.Open();

// Send data to the development board
string message = "Hello, world!";
mySerialPort.WriteLine(message);

// Close the serial port
mySerialPort.Close();

In the above code, we use the WriteLine method to send a string to the development board. You can also use the Write method to send byte arrays or other types of data.

I hope this information helps you resolve the issue.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.