C# WPF Serial port communication convert? - c#

Hi there I'm a complete newbie and I'm asking dumb questions, so thanks for the time...
I'm trying to send a command that is a string to a device I have - "Robot" that I control via USB -> Serial Port. This string should look like that :01013100010010 and it should tell a certain step motor to make a specific amount of steps. Every time i try to send that string like that :01013100010010 it doesn't do anything, but if I open Hyper Terminal and send it like that it does the command.
Do I need to convert it to something special or the problem is something else ?
Another thing is how can I assign the string ":01013100010010" to be sent when a button is pressed so if someone can show me a sample code of how to do that i.e. send the data on button click I would be grateful !
Here is the code I have for now it's a simple UI :
private void button2_Click(object sender, EventArgs e)
{
if (!serialPort1.IsOpen)
{
serialPort1.PortName = "COM2";
serialPort1.BaudRate = 9600;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.DataBits = 8;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.ReadTimeout = 500;
serialPort1.WriteTimeout = 500;
serialPort1.DtrEnable = true;
serialPort1.RtsEnable = true;
serialPort1.Open();
richTextBox1.Text = "Connected";
}
}
private void button1_Click(object sender, EventArgs e)
{
if(serialPort1.IsOpen){
string text = richTextBox1.Text;
serialPort1.WriteLine(text);}
}
}
}

You need to write on the SerialPort. to do that, use something like this
serialPort1.Open();
serialPort1.Write(#":01013100010010");
Thread.Sleep(200);
serialPort1.Close();
I´m using Thread.Sleep on the code because in my work sometimes our device don´t receive the full command if we just write and then close the port.
#edit: Sample code working on client
portaserial = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
portaserial.Open();
portaserial.Write(mensagem.ToString());
Thread.Sleep(500);
portaserial.Close();
Source: myself

Add:
serialPort1.NewLine = "\r\n";

Related

Communication between C# and Arduino

Code for C#
using System;
using System.Windows.Forms;
using System.IO.Ports;
SerialPort port;
private void btnStart_Click(object sender, EventArgs e)
{
port = new SerialPort("COM6", 9600);
port.Open();
port.Write("START");
port.Close();
}
Code for Arduino
"#"include "MOVIShield.h"
MOVI recognizer(true);
Code inside the loop
signed int res=recognizer.poll();
if(Serial.available() > 0){
String data = Serial.readString();
if(data = "START"){
recognizer.ask("Hello. My name is John");
}
}
I tried to click the btnStart to send "START" to my Arduino Program and the Arduino Program should run ask("Hello. My name is John") after received the data from C# program. But when I clicked the btnStart, there is nothing happened.
You can try different a couple of different things:
1- Make sure COM port parameters are the same on both sides
As explained at http://www.instructables.com/id/How-to-connect-Arduino-to-a-PC-through-the-serial-/
Add this to the Arduino C code outside the loop:
Serial.begin(9600);
And change your C# to a code similar to:
private void btnStart_Click(object sender, EventArgs e)
{
port = new SerialPort("COM6", 9600);
port.DataBits = 8;
port.StopBits = StopBits.One;
port.Handshake = Handshake.None;
port.Parity = Parity.None;
port.Open();
port.Write("START");
port.Close();
}
2- Use a different tool than C# to test if you can communicate to the Arduino.
e.g. this tool has 15 days demo: https://www.eltima.com/rs232-testing-software/
I imagine the single equals in this line may have something to do with it.
if(data = "START")

Serial Port listening in C#

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!

unable to communicate with obd-II

I am trying to communicate with ECUsim 2000 which is OBD-ll ECU simulator (link). Yet, responses I always receive from device are something like "??" or "?" (when I run programs like TouchScan or OBD Auto Doctor, they successfully reads data so device is working properly). I am sending comand in C# via
serialPort1.Write("010D\r")
and I am receiving signal in SerialPort's DataReceived event as
message = "Data Received: " + serialPort1.ReadExisting();
this.Invoke(new EventHandler(displayText));
I do not now what I am missing. Here is the full source code
private void Form1_Load(object sender, EventArgs e)
{
serialPort1.PortName = "COM3";
serialPort1.BaudRate = 115200;
serialPort1.Parity = System.IO.Ports.Parity.None;
serialPort1.StopBits = System.IO.Ports.StopBits.One;
serialPort1.DataBits = 8;
serialPort1.Handshake = System.IO.Ports.Handshake.None;
serialPort1.Open();
}
private void button1_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Write("010D\r");
}
}
private void displayText(object sender, EventArgs e)
{
textBox1.AppendText(message + "\n");
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
message = "Data Received: " + serialPort1.ReadExisting();
this.Invoke(new EventHandler(displayText));
}
Default communication settings of ECUsim 2000 are
Baud Rate: 115200
Data bits: 8
Parity: none
Stop bits:1
protocol is ISO 15765-4 and there are two switches on the device which are protocol attribute CAN ID 29/11 bit and CAN Baud Rate 500 kbps/250kbps. Maybe, the problem are related with these such that there is no proper communication set.
Another question -> Is there a way to set protocol (like ISO 15765-4) in serial communication?
There are two problems related with the code given.
1) There are two connector on the ECUsim 2000. One of them is type B USB port, other one is Diagnostic Link Connector (DLC). If one wants to get connected to device via type B USB port, baud rate is: 115200. If DLC is used, Baud Rate is most probably either 9600 or 38400. Here, connection is made through scan tool, therefore (for my case) baud rate 38400 worked for me.
2) As mentioned in the comment, In order to get data, Read() method of SerialPort must be used. It can be used as the following code:
int buffSize = 1024;
bool cont = true;
int count = 0;
byte[] bff = new byte[buffSize];
string returnVal = string.Empty;
count = serialPort1.Read(bff, 0, buffSize);
returnVal += System.Text.Encoding.Default.GetString(bff, 0, count);

Get last call duration using AT+CLCC command

I coded a program to dial automatically when phone is connected to the laptop and get the last call duration.I used AT+CLCC command to get current call status..Though it should return the Some string value as .......etc i got nothing like that so far...Here is my code..
_serialPort.BaudRate = 9600;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
_serialPort.DtrEnable = true;
_serialPort.RtsEnable = true;
string phonenr = "";
// string mesaj;
if (!_serialPort.IsOpen)
{
_serialPort.Open();
}
_serialPort.WriteLine("AT\r");
{
Console.WriteLine("Enter the phone number:", phonenr);
phonenr = Console.ReadLine();
_serialPort.WriteLine("ATD" + phonenr + ";" + "\r");
Console.WriteLine("Ring...");
Thread.Sleep(10000);
_serialPort.WriteLine("AT+CLCC");
_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
//As a seperate function....
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}
What is the wrong with this code????How can i get the response as the format ...etc ???
AT+CLCC command does not provide information about the last call. It provides information during a call (during dialing/ringing/waiting etc). Read this for detailed information
I think you can make the phone to output last call details automatically to the terminal, when the call is disconnected but I'm not sure if it provides call duration. You might have to monitor/record the time manually with your application
I have seen other posts where you have asked similar questions. I would recommend using a simple serial port terminal (putty or terminal etc.) to communicate with the phone and grasp the AT commands concept, before moving on to controlling the phone using your own code.

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.

Categories