Click here to Skip to main content
15,903,033 members
Home / Discussions / C#
   

C#

 
GeneralRe: Read information from serial port in Mathlab format Pin
Richard MacCutchan5-Apr-24 23:41
mveRichard MacCutchan5-Apr-24 23:41 
GeneralRe: Read information from serial port in Mathlab format Pin
Luc Pattyn6-Apr-24 8:16
sitebuilderLuc Pattyn6-Apr-24 8:16 
GeneralRe: Read information from serial port in Mathlab format Pin
Victor Gonzalez 20247-Apr-24 1:12
Victor Gonzalez 20247-Apr-24 1:12 
GeneralRe: Read information from serial port in Mathlab format Pin
Luc Pattyn7-Apr-24 1:52
sitebuilderLuc Pattyn7-Apr-24 1:52 
GeneralRe: Read information from serial port in Mathlab format Pin
Victor Gonzalez 20247-Apr-24 6:04
Victor Gonzalez 20247-Apr-24 6:04 
GeneralRe: Read information from serial port in Mathlab format Pin
Luc Pattyn7-Apr-24 8:13
sitebuilderLuc Pattyn7-Apr-24 8:13 
GeneralRe: Read information from serial port in Mathlab format Pin
Victor Gonzalez 20247-Apr-24 9:53
Victor Gonzalez 20247-Apr-24 9:53 
GeneralRe: Read information from serial port in Mathlab format Pin
Luc Pattyn7-Apr-24 11:04
sitebuilderLuc Pattyn7-Apr-24 11:04 
OK, so message traffic would be pretty low, and problems with the serial communication are rather unlikely. This is my first attempt (not tested!), it does NOT include communication recovery, that is: if something goes wrong (say a serial byte gets lost), it will continue to fail.

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

namespace ConsoleApp1 {
	class PortDataReceived {
		private static SerialPort sp;
		private const string PORTNAME = "COM3";
		private const int MSGLEN = 21;

		public static void Main(string[] args) {
			sp = openPort();
			Console.WriteLine("Press any key to terminate...");
			Console.ReadKey();
			if (sp!=null) sp.Close();
		}

		private static SerialPort openPort() {
			try {
				SerialPort port = new SerialPort(PORTNAME);
				port.BaudRate = 56000;
				port.Parity = Parity.None;
				port.StopBits = StopBits.One;
				port.DataBits = 8;
				port.Handshake = Handshake.None;
				port.RtsEnable = true;
				port.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
				port.Open();
				output("serial port " + PORTNAME + "opened");
				return port;
			} catch(Exception exc) {
				reportError("Error opening serial port (" + exc.Message + ")");
				return null;
			}
		}


		private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) {
			// we will process one or more messages in a loop
			// WARNING: if for some reason the serial data gets out of sync (first byte isn't 0xE0)
			//			then we will not recover, and the data will not be understood at all!

			byte[] message = new byte[MSGLEN];
			while (true) {
				int count = sp.BytesToRead;
				if (count == 0) return; // no more data, exit the handler
				if (count >= MSGLEN) {
					// we now read exactly 21 bytes, no more no less, so when several messages could be present
					// we only obtain the first one in this iteration of the while loop
					int got=sp.Read(message, 0, MSGLEN);
					if (got == MSGLEN) {
						processMessage(message);
					} else {
						// this should never happen
						reportError("Insufficient data bytes in DataReceivedHandler");
					}
				} else {
					// some bytes are present, but not enough; so wait some more
					Thread.Sleep(100);
				}
			}
		}

		private static void processMessage(byte[] bb) {
			// WARNING: this method gets called by DataReceived handler, so it will NOT run on the GUI thread,
			//			and would need Invoking when used in a Windows Forms project
			int count = bb.Length;
			string s = "Got message: (len="+count.ToString()+"): ";
			foreach (byte b in bb) {
				s += b.ToString("X2") + " ";
			}
			string comment = " ?";
			if (count != MSGLEN) comment = " *** ERROR *** Bad length";
			else if (bb[0] != 0xE0) comment = " *** ERROR *** Bad first byte";
			// some examples of message interpretation
			else if (bb[8] == 0xA5 && bb[9] == 0x00) comment = " = Pause on";
			else if (bb[8] == 0xA6 && bb[9] == 0x00) comment = " = Pause off";
			output(s + comment);
		}

		private static void reportError(string message) {
			output("Error: "+message);
		}

		private static void output(string text) {
			Console.WriteLine(text);
		}
	}
}

I expect the above DataReceivedHandler method is OK, you would have to extend or replace the processMessage() method.

Smile | :)
Luc Pattyn [My Articles]
The Windows 11 taskbar is a disgrace; a third-party add-on is needed to reverse the deterioration. I decline such a downgrade.

GeneralRe: Read information from serial port in Mathlab format Pin
Victor Gonzalez 20247-Apr-24 22:42
Victor Gonzalez 20247-Apr-24 22:42 
GeneralRe: Read information from serial port in Mathlab format Pin
Luc Pattyn7-Apr-24 22:45
sitebuilderLuc Pattyn7-Apr-24 22:45 
QuestionDebugging the Sandbox Pin
Richard Andrew x645-Apr-24 3:43
professionalRichard Andrew x645-Apr-24 3:43 
QuestionIParsable? IFormattable? ICustomFormatter? IFormatProvider? TryParse! ToString! Pin
Tracy Dryden24-Mar-24 12:29
Tracy Dryden24-Mar-24 12:29 
AnswerRe: IParsable? IFormattable? ICustomFormatter? IFormatProvider? TryParse! ToString! Pin
Mycroft Holmes24-Mar-24 15:07
professionalMycroft Holmes24-Mar-24 15:07 
GeneralRe: IParsable? IFormattable? ICustomFormatter? IFormatProvider? TryParse! ToString! Pin
Tracy Dryden24-Mar-24 16:19
Tracy Dryden24-Mar-24 16:19 
AnswerRe: IParsable? IFormattable? ICustomFormatter? IFormatProvider? TryParse! ToString! Pin
Ralf Meier24-Mar-24 22:35
mveRalf Meier24-Mar-24 22:35 
GeneralRe: IParsable? IFormattable? ICustomFormatter? IFormatProvider? TryParse! ToString! Pin
Tracy Dryden25-Mar-24 7:51
Tracy Dryden25-Mar-24 7:51 
AnswerRe: IParsable? IFormattable? ICustomFormatter? IFormatProvider? TryParse! ToString! Pin
jschell26-Mar-24 12:00
jschell26-Mar-24 12:00 
Rant(Current) AI Rant. Pin
Gerry Schmitz17-Mar-24 12:29
mveGerry Schmitz17-Mar-24 12:29 
GeneralRe: (Current) AI Rant. Pin
Eddy Vluggen26-Mar-24 5:34
professionalEddy Vluggen26-Mar-24 5:34 
GeneralRe: (Current) AI Rant. Pin
lmoelleb1-Apr-24 21:44
lmoelleb1-Apr-24 21:44 
GeneralRe: (Current) AI Rant. Pin
lmoelleb1-Apr-24 21:49
lmoelleb1-Apr-24 21:49 
QuestionMessageBox Appearing Behind Window Pin
Richard Andrew x6417-Mar-24 1:27
professionalRichard Andrew x6417-Mar-24 1:27 
AnswerRe: MessageBox Appearing Behind Window Pin
OriginalGriff17-Mar-24 4:33
mveOriginalGriff17-Mar-24 4:33 
AnswerRe: MessageBox Appearing Behind Window Pin
Gerry Schmitz17-Mar-24 6:37
mveGerry Schmitz17-Mar-24 6:37 
GeneralRe: MessageBox Appearing Behind Window Pin
Richard Andrew x6417-Mar-24 8:04
professionalRichard Andrew x6417-Mar-24 8:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.