I am working on an extended weekend project where I wanted to see if I could send and print a GCODE file from my windows PC via the serial port and C#.
I am getting the printer to connect but I am not getting consistent results when trying to write to the serial stream. I am not even sure that my serial port settings are correct, I couldn't find any good examples of how OctoPrint connects to my printer for example. I think my problem is that I am sending too much data all at once but I am also struggling to read from the serial connection and wait for only "ok" as they seem to come out of order.
I can connect and send a single line, no problem. Once I give it an entire file with many lines the printer gets to various parts of the file and just hangs.
How can I stream large files over the serial port to a 3D printer without overloading the printers internal buffer?
Code I am using:
private static async Task Main(string[] args)
{
var ports = SerialPort.GetPortNames();
if (!ports.Any())
{
Console.WriteLine("No ports found");
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
}
else
{
using (SerialPort mySerialPort = new SerialPort(ports.First()))
{
mySerialPort.BaudRate = 115200;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.Open();
mySerialPort.DataReceived += DataRecieved;
using (var fileToPrint = File.OpenRead({Path to GCODE file})
using (var lineReader = new StreamReader(fileToPrint))
{
while (!lineReader.EndOfStream && lineReader is not null)
{
var line = await lineReader.ReadLineAsync() ?? string.Empty;
if (!line.StartsWith(";"))
{
var cleanLine = line. Split(";").First().Trim();
mySerialPort.WriteLine(cleanLine);
}
}
}
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
mySerialPort.Close();
}
}
}
private static void DataRecieved(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
var line = sp.ReadLine();
Console.WriteLine("Data from printer: {0}", line);
}