Connecting to NI USB to 232/4 failure - c#

Currently trying to send basic messages through an NI USB-232/4 to a power supply. While connecting with my code, the messages will not get sent through, and the PORT led remains red/orange.
When connecting with the power supply's code, messages can be received perfectly fine, the PORT led turns green. The power supply reacts to commands given.
When connecting the supplied program trough virtual serial ports to a terminal, the messages sent are identical to the messages my program is sending. When input directly from a terminal window to the power supply, the commands work fine. Again, the port led turns green while connecting through the terminal.
The serial settings, as far as I can tell, are identical to those that both the supplied program and the terminal are using. However, the power supply refuses to accept the messages.
public Serial(){
ThreadSafe.serialVoltage.Enqueue("*IDN?");
ThreadSafe.serialVoltage.Enqueue("SYST:REM\n");
ThreadSafe.serialVoltage.Enqueue("INST SECO");
ThreadSafe.serialVoltage.Enqueue("OUTP 1");
ThreadSafe.serialVoltage.Enqueue("VOLT 9V");
}
public void ListenForVoltageChange()
{
string result;
_serialPort = new System.IO.Ports.SerialPort();
OpenPort();
Thread.Sleep(1000);
while (true) {
if (!ThreadSafe.serialVoltage.IsEmpty) {
ThreadSafe.serialVoltage.TryDequeue(out result);
Debug.WriteLine(result);
_serialPort.WriteLine(result);
}
Thread.Sleep(1000);
}
}
public bool OpenPort()
{
Debug.WriteLine("Port Open");
Debug.WriteLine(_serialPort.IsOpen);
if (!_serialPort.IsOpen)
{
_serialPort.PortName = "COM4";
_serialPort.BaudRate = 9600;
_serialPort.Parity = System.IO.Ports.Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = System.IO.Ports.StopBits.One;
_serialPort.RtsEnable = false;
_serialPort.Handshake = System.IO.Ports.Handshake.None;
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
try
{ _serialPort.Open(); }
catch { return false; }
}
return true;
}

Related

Serial COM read returns null [duplicate]

I am developing program which need to interact with COM ports.
By learning from this Q&A: .NET SerialPort DataReceived event not firing, I make my code like that.
namespace ConsoleApplication1
{
class Program
{
static SerialPort ComPort;
public static void OnSerialDataReceived(object sender, SerialDataReceivedEventArgs args)
{
string data = ComPort.ReadExisting();
Console.Write(data.Replace("\r", "\n"));
}
static void Main(string[] args)
{
string port = "COM4";
int baud = 9600;
if (args.Length >= 1)
{
port = args[0];
}
if (args.Length >= 2)
{
baud = int.Parse(args[1]);
}
InitializeComPort(port, baud);
string text;
do
{
String[] mystring = System.IO.Ports.SerialPort.GetPortNames();
text = Console.ReadLine();
int STX = 0x2;
int ETX = 0x3;
ComPort.Write(Char.ConvertFromUtf32(STX) + text + Char.ConvertFromUtf32(ETX));
} while (text.ToLower() != "q");
}
private static void InitializeComPort(string port, int baud)
{
ComPort = new SerialPort(port, baud);
ComPort.PortName = port;
ComPort.BaudRate = baud;
ComPort.Parity = Parity.None;
ComPort.StopBits = StopBits.One;
ComPort.DataBits = 8;
ComPort.ReceivedBytesThreshold = 9;
ComPort.RtsEnable = true;
ComPort.DtrEnable = true;
ComPort.Handshake = System.IO.Ports.Handshake.XOnXOff;
ComPort.DataReceived += OnSerialDataReceived;
OpenPort(ComPort);
}
public static void OpenPort(SerialPort ComPort)
{
try
{
if (!ComPort.IsOpen)
{
ComPort.Open();
}
}
catch (Exception e)
{
throw e;
}
}
}
}
My problem is DataReceived event never gets fired.
My program specifications are:
Just .net console programming
I use VSPE from http://www.eterlogic.com
My computer has COM1 and COM2 ports already.
I created COM2 and COM4 by using VSPE.
I get output result from mystring array (COM1, COM2, COM3, COM4)
But I still don't know why DataReceived event is not fired.
Updated
Unfortunately, I still could not make to fire DataReceived event in any way.
So, I created new project by hoping that I will face a way to solve.
At that new project [just console application], I created a class...
public class MyTest
{
public SerialPort SPCOM4;
public MyTest()
{
SPCOM4 = new SerialPort();
if(this.SerialPortOpen(SPCOM4, "4"))
{
this.SendToPort(SPCOM4, "com test...");
}
}
private bool SerialPortOpen(System.IO.Ports.SerialPort objCom, string portName)
{
bool blnOpenStatus = false;
try
{
objCom.PortName = "COM" + portName;
objCom.BaudRate = 9600;
objCom.DataBits = 8;
int SerParity = 2;
int SerStop = 0;
switch (SerParity)
{
case 0:
objCom.Parity = System.IO.Ports.Parity.Even;
break;
case 1:
objCom.Parity = System.IO.Ports.Parity.Odd;
break;
case 2:
objCom.Parity = System.IO.Ports.Parity.None;
break;
case 3:
objCom.Parity = System.IO.Ports.Parity.Mark;
break;
}
switch (SerStop)
{
case 0:
objCom.StopBits = System.IO.Ports.StopBits.One;
break;
case 1:
objCom.StopBits = System.IO.Ports.StopBits.Two;
break;
}
objCom.RtsEnable = false;
objCom.DtrEnable = false;
objCom.Handshake = System.IO.Ports.Handshake.XOnXOff;
objCom.Open();
blnOpenStatus = true;
}
catch (Exception ex)
{
throw ex;
}
return blnOpenStatus;
}
private bool SendToPort(System.IO.Ports.SerialPort objCom, string strText)
{
try
{
int STX = 0x2;
int ETX = 0x3;
if (objCom.IsOpen && strText != "")
{
objCom.Write(Char.ConvertFromUtf32(STX) + strText + Char.ConvertFromUtf32(ETX));
}
}
catch (Exception ex)
{
throw ex;
}
return true;
}
}
I am not sure that I face good luck or bad luck because this new class could make fire DataReceived event which is from older console application that is still running. It is miracle to me which I have no idea how this happen.
Let me tell you more detail so that you could give me suggestion for better way.
Finally I created 2 console projects.
First project is the class which I posted as a question yesterday.
Second project is the class called MyTest which could make fire DataReceived event from First project, at the same time when two of the project is running.
Could anyone give me suggestions on how could I combine these two projects as a single project?
ComPort.Handshake = Handshake.None;
The problem is not that the DataReceived event doesn't fire, the problem is that the serial port isn't receiving any data. There are very, very few serial devices that use no handshaking at all. If you set it to None then the driver won't turn on the DTR (Data Terminal Ready) and RTS (Request To Send) signals. Which a serial port device interprets as "the machine is turned off (DTR)" or "the machine isn't ready to receive data (RTS)". So it won't send anything and your DataReceived event won't fire.
If you really want None then set the DTREnable and RTSEnable properties to true. But it is likely you want HandShake.RequestToSend since the device appears to be paying attention to the handshake signals.
If you still have trouble then use another serial port program like Putty or HyperTerminal to ensure the connection and communication parameters are good and the device is responsive. SysInternals' PortMon utility gives a low-level view of the driver interaction so you can compare good vs bad.
I have never worked with VSPE so I'm not sure if that causes the problem. I have worked with a COM port before and I looked up my code. The only main difference is the way you declare the event. You have:
ComPort.DataReceived += OnSerialDataReceived;
I have it like this:
ComPort.DataReceived += new SerialDataReceivedEventHandler(OnSerialDataReceived);
OnSerialDataReceived is your eventhandler. I'm not sure if this will make any difference, but you can try it. I hope this helps!
I had a quite similar problem. In a graphical application (C# win form) I had a class which encapsulate a SerialPort component. The DataReceived event was firing only one time, but then any following data received didn't fire any event. I solved the problem by calling the Close method in my principal form Closed event function.
No idea of why that changes anything, but now it's working.

Loop get paused/diactivated inside catch() block

I am trying to send AT commands to COM ports, so I can find the GSM dongle. Below is the code
public bool findGsmModem()
{
bool sendStatus = false;
//Get all the available ports
string[] serialPorts = SerialPort.GetPortNames();
for (int i = 0; i < serialPorts.Length; i++)
{
Console.WriteLine(serialPorts[i]);
}
//Iterate through all the ports sending AT commands to find a modem
for (int i = 0; i < 1; i++)
{
try
{
//port.PortName = serialPorts[i].Trim();
port.PortName = "COM7";
openPort();
string res = ATCommandCaller("AT", 300,"Unable to connect to the phone"); //Connecting to the phone
//res = ATCommandCaller("AT+CMGF=1", 300); //Setting the message Format
sendStatus = true;
break;
}
catch (System.InvalidOperationException ex)
{
//port.PortName = null;
port.Close();
autoInitializer();
//port = new SerialPort();
continue;
//throw ex;
}
}
return sendStatus;
}
Here is how I call this method inside another class
if (sms.findGsmModem())
{
MessageBox.Show("Modem Found: " + sms.getPortName());
}
else
{
MessageBox.Show("No modem found");
}
OK, now in the findGsmModem() method if I use port.PortName = "COM5"; the above second code works successfully and display the message. That is because the Modem is actually in COM5 and the value is hard coded, so the statement do not reach the catch() block.
But, if I use port.PortName = serialPorts[i].Trim(); or port.PortName = serialPorts[i]; then it seems like nothing is happening instead of printing the port names (inside findGsmModem()). Following ports are being printed
COM1
COM2
COM8
COM9
COM5
COM4
COM3
As you can see, the COM5, the port where the gms modem actually exists is in the 5th element of the array, so findGsmModem() calls catch() part before it access the COM5.
I do believe I am not getting anything when port.PortName = serialPorts[i].Trim() is used because it goes to the catch() part and something terrible happens there.
Any idea?
Here is the openPort() method
public void openPort()
{
try
{
port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
if (!port.IsOpen)
{
port.Open();
}
port.RtsEnable = true;
port.DtrEnable = true;
}
catch (Exception ex)
{
throw ex;
}
}
EDIT
Here is the most weirdest part. I just noticed the catch() block never get reached when the loop is called! I tried ex.Message to print the stack trace, and it didn't print anything!
catch (Exception ex)
This is the trouble with catch-em-all exception handling. You are getting an InvalidOperationException because you change the PortName property on a opened port. That's a bug in your code, nothing actually went wrong with the serial port.
You'll need to call the Close() method if you find out that it port is not connected to the GSM modem.
Then you can't call Open() again on that same SerialPort instance, it takes time for internal worker thread to shut down. Best thing to do is to create a new instance of SerialPort instead of trying to keep using the same one repeatedly.

SerialPort First Command OK. Second Command Error

I'm writing a serialport app to talk to a Bluetooth module over serial port. The first At command I send to the device runs fine and I get a response of the module version. All subsequent commands fail with a response of ERROR.
Part of the code is here:
namespace PhoneApp
{
public partial class Form1 : Form
{
//SerialPort myport = OPenPort.OpenIt();
SerialPort myport = new SerialPort();
public Form1()
{
InitializeComponent();
myport.PortName = "COM3";
myport.BaudRate = 115200;
myport.Parity = Parity.None;
myport.DataBits = 8;
myport.StopBits = StopBits.One;
myport.NewLine = System.Environment.NewLine;
myport.ReadTimeout = 500;
myport.WriteTimeout = 500;
myport.DtrEnable = false;
myport.RtsEnable = false;
myport.WriteBufferSize = 4096;
myport.ReadBufferSize = 4096;
myport.Handshake = Handshake.None;
myport.Encoding = System.Text.Encoding.ASCII;
if (!myport.IsOpen)
{
myport.Open();
}
calling.Visible = false;
myport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
mycommand.Text = #"AT+BGVER";
the button which sends the command. The device requires a newline after each comand.
private void button2_Click(object sender, EventArgs e)
{
try
{
myport.WriteLine(mycommand.Text.Trim());
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Not sure what I'm missing here.
Thanks for the replies. i found the problem. In fact I had to use myport.Write instead of myport.WriteLine. I deleted the line myport.NewLine and I appended "\r" to every command. Now the device responds as expected. As for DTR and RTS they are not required by the device according to the vendor
Not sure if this solves your problem, but I noticed that you don't have flow control enabled (e.g. myport.RtsEnable = false; myport.DtrEnable = false;).
Have you checked the documentation to make sure that the Bluetooth module doesn't require it? Typically devices with 115kbps and higher need flow control.
Another thing to check is the NewLine constant. You set it to the sys default which is likely Cr+Lf. Make sure that the module expects that.

get the port no where gsm modem is connected using C#

I am planning to send sms using a modem in C# from an asp.net application.As the project will be
integrated to another project it wont be having any field for user input to enter the com port.How can i get the port number where my modem in connected from C#.
Thanks,
Sagar.
To check that a modem is connected to particular port you can send AT command into this port.
This function below returns true if we found a modem on the current COM port:
private bool CheckExistingModemOnComPort(SerialPort serialPort)
{
if ((serialPort == null) || !serialPort.IsOpen)
return false;
// Commands for modem checking
string[] modemCommands = new string[] { "AT", // Check connected modem. After 'AT' command some modems autobaud their speed.
"ATQ0" }; // Switch on confirmations
serialPort.DtrEnable = true; // Set Data Terminal Ready (DTR) signal
serialPort.RtsEnable = true; // Set Request to Send (RTS) signal
string answer = "";
bool retOk = false;
for (int rtsInd = 0; rtsInd < 2; rtsInd++)
{
foreach (string command in modemCommands)
{
serialPort.Write(command + serialPort.NewLine);
retOk = false;
answer = "";
int timeout = (command == "AT") ? 10 : 20;
// Waiting for response 1-2 sec
for (int i = 0; i < timeout; i++)
{
Thread.Sleep(100);
answer += serialPort.ReadExisting();
if (answer.IndexOf("OK") >= 0)
{
retOk = true;
break;
}
}
}
// If got responses, we found a modem
if (retOk)
return true;
// Trying to execute the commands without RTS
serialPort.RtsEnable = false;
}
return false;
}
On the next stage we can collect some data from the modem.
ATQ0 - switch on confirmations (receive OK on each request)
ATE0 - switch on echo
ATI - get modem details
ATI3 - get extended modem details (not all modems supports this command)

Using SerialPort class to read response from connected device

I'm using C#'s SerialPort class to try and send a AT command to a device and get a response back. I've verified it works correctly in HyperTerminal, if I send a command of AT it responds back with OK. However, in my console app, if I send AT, it replies back with an echo AT. The code is below, any insight into what I'm doing wrong in my receiving code would be greatly appreciated:
ComPort.DataReceived += new SerialDataReceivedEventHandler(ComPort_DataReceived);
public void Open()
{
Console.WriteLine();
//close port if already open.
if (ComPort.IsOpen)
{
ComPort.Close();
}
//setup port.
ComPort.PortName = ConfigurationManager.AppSettings["PortName"].ToString();
ComPort.BaudRate = Convert.ToInt32(ConfigurationManager.AppSettings["BaudRate"]);
ComPort.Parity = Parity.None;
ComPort.StopBits = StopBits.One;
ComPort.DataBits = 8;
ComPort.DtrEnable = true;
ComPort.RtsEnable = true;
if (Convert.ToBoolean(ConfigurationManager.AppSettings["HWFlowControlEnabled"]))
{
ComPort.Handshake = Handshake.RequestToSend;
}
//open port.
Console.WriteLine("Opening port " + ComPort.PortName + "...");
ComPort.Open();
Console.WriteLine("Opened port " + ComPort.PortName);
}
void ComPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
string message = ComPort.ReadExisting();
Console.WriteLine("RECEIVED: " + message);
if (message.IndexOf("OK") > -1)
{
ReceivedOK = true;
}
}
I think the default is to echo your commands back to you, then the OK. Send an ATE0 first to turn off echo:
http://tigger.cc.uic.edu/depts/accc/network/dialin/modem_codes.html
By default, the device (a modem I guess) is configured to echo all communication back. There are AT commands to turn echo on and off. Also, several hardware signalling approaches exist to control the flow of data. Have a look here for a basic overview.
It's quite a while (> 10 years actually) since I was doing modem communications, so I'm sorry in case my answer isn't 100% precise.

Categories