Im trying to get IMEI of a Samsung S7 device. I tried with AT+CGSN via Putty which worked perfectly. When I tried the same with C# SerialPort returns empty string.
Sending AT\r\n on C# SerialPort giving "OK" as expected and all other AT commands are also working except this
It looks bit wired for me on why it was not working for the specific commands where others are working.
Here is the sample.
private static string GetMobileSerialNumber(string PortName)
{
string Serial = "";
SerialPort serialPort = new SerialPort();
serialPort.PortName = PortName;
serialPort.BaudRate = 154200;
serialPort.Handshake = Handshake.None;
serialPort.ReadBufferSize = 16384;
try
{
if (!(serialPort.IsOpen))
serialPort.Open();
serialPort.Write("AT+CGSN\r\n");
Thread.Sleep(1000);
Serial = serialPort.ReadExisting();
serialPort.Close();
Console.WriteLine(Serial);
return Serial;
}
catch (Exception ex)
{
//MessageBox.Show("Error in opening/writing to serial port :: " + ex.Message, "Error!");
return "";
}
}
Sample also available here
PuTTY and teraterm filtering /n /r similar parameters CR LF byte commands.
your cmd wrong
Related
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;
}
There are loads of questions about listening of devices on Serial Port using C#.
However I couldn't find something that will be useful for my application and working.
Now this is a code i finally decided to use however I cannot see why it will not output anything:
namespace SerialPorts
{
class Program
{
static void Main(string[] args)
{
SerialPort myPort = new SerialPort();
myPort.DataReceived += MyPortDataReceived;
myPort.PortName = "COM3";
myPort.BaudRate = 19200;
myPort.DataBits = 7;
myPort.Parity = Parity.Even;
myPort.StopBits = StopBits.One;
myPort.Open();
Console.ReadLine();
myPort.Close();
}
static void MyPortDataReceived(object sender,
SerialDataReceivedEventArgs e)
{
var myPort = sender as SerialPort;
Console.WriteLine(myPort.ReadLine());
}
}
}
My device is OCR PASSORT reader.
I expect a string when i swipe a passport. However I get nothing, no output at all.
Can you please help me what can i do to make it output a string at least?
BTW I know the OCR reader is working since there is an app coming with it that outputs its data and when I use apps that test the COM i get data but with this code I get nothing. Any help will be appreciated!
Regards!
I'm trying to refactor/update some legacy serial comm code. I've got this:
private SerialPort cereal;
private String receivedData;
private FileXferLegacy()
{
cereal = new SerialPort("COM1", 9600);
cereal.PortName = "7727";
cereal.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
// Is this just as well, as the elided part is grayed out above?: cereal.DataReceived += port_DataReceived;
}
...but am getting the err msg "The port '7727:' does not exist" when I try to connect and send a ping:
public void SendDataContentsAsXML(string destinationPath, string XMLData)
{
byte[] stuff;
ExceptionLoggingService.Instance.WriteLog("Reached FileXferLegacy.SendDataContentsAsXML"); // <= This is written to the log file
cereal.Open();
stuff = System.Text.UTF8Encoding.UTF8.GetBytes("PING" + "\n");
cereal.Write(stuff, 0, stuff.Length);
stuff = System.Text.UTF8Encoding.UTF8.GetBytes(XMLData + "\n");
cereal.Write(stuff, 0, stuff.Length);
}
7727 is the same port that is successfully used in the legacy app.
I do see that there is a colon appended, and wonder if that is the problem - why is it seeing "7727:" instead of plain old "7727", and how can I disabuse it of the notion of having an appended colon if that is indeed a problem?
Because PortName refers to the serial port name, not a port number. In your code you're creating your SerialPort object
cereal = new SerialPort("COM1", 9600);
So COM1 is already being assigned to PortName. Your next statement is just overriding it unnecessarily and incorrectly.
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.
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.