I have a matrix d1000+ digital scale. I want it's weight in my application using c# but I have no idea how to do this. It is connected with my computer through rs232.
I am using this code but weight is shown incorrect format like 1+e00023 please tell me what can i do to correct it.
public partial class ManageSale : Form
{
private SerialPort port = new SerialPort(
"COM1", 4800, Parity.None,8, StopBits.One);
public ManageSale()
{
InitializeComponent();
port.DataReceived +=
new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
port.DtrEnable = true;
port.RtsEnable = true;
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.label1.Text = port.ReadExisting();
}
private void ManageSale_Load(object sender, EventArgs e)
{
port.WriteLine("5");
}
}
hi evryone my problem is still there plese help me to solve this problem see my code where i am wrong please tell me how to correct it.
Contact the manufacturer, and ask for the API kit. You'll probably have to link against a dll written in C / C++, using a DllImport statement. Working out the proper data types between C / C++ can be time consuming, but is doable.
See the Serial Port Api in the .Net Framework. There's an example there:
using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
static bool _continue;
static SerialPort _serialPort;
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message) );
}
}
readThread.Join();
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
public static string SetPortName(string defaultPortName)
{
string portName;
Console.WriteLine("Available Ports:");
foreach (string s in SerialPort.GetPortNames())
{
Console.WriteLine(" {0}", s);
}
Console.Write("COM port({0}): ", defaultPortName);
portName = Console.ReadLine();
if (portName == "")
{
portName = defaultPortName;
}
return portName;
}
public static int SetPortBaudRate(int defaultPortBaudRate)
{
string baudRate;
Console.Write("Baud Rate({0}): ", defaultPortBaudRate);
baudRate = Console.ReadLine();
if (baudRate == "")
{
baudRate = defaultPortBaudRate.ToString();
}
return int.Parse(baudRate);
}
public static Parity SetPortParity(Parity defaultPortParity)
{
string parity;
Console.WriteLine("Available Parity options:");
foreach (string s in Enum.GetNames(typeof(Parity)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Parity({0}):", defaultPortParity.ToString());
parity = Console.ReadLine();
if (parity == "")
{
parity = defaultPortParity.ToString();
}
return (Parity)Enum.Parse(typeof(Parity), parity);
}
public static int SetPortDataBits(int defaultPortDataBits)
{
string dataBits;
Console.Write("Data Bits({0}): ", defaultPortDataBits);
dataBits = Console.ReadLine();
if (dataBits == "")
{
dataBits = defaultPortDataBits.ToString();
}
return int.Parse(dataBits);
}
public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
{
string stopBits;
Console.WriteLine("Available Stop Bits options:");
foreach (string s in Enum.GetNames(typeof(StopBits)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString());
stopBits = Console.ReadLine();
if (stopBits == "")
{
stopBits = defaultPortStopBits.ToString();
}
return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
}
public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
{
string handshake;
Console.WriteLine("Available Handshake options:");
foreach (string s in Enum.GetNames(typeof(Handshake)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Handshake({0}):", defaultPortHandshake.ToString());
handshake = Console.ReadLine();
if (handshake == "")
{
handshake = defaultPortHandshake.ToString();
}
return (Handshake)Enum.Parse(typeof(Handshake), handshake);
}
}
Related
I have a task to create web app with ASP .NET core 2.0 where you can communicate with modem and send SMS using AT command. I have a piece of code which can send messages using Serial Port but ASP doesn't have this library so how can I use this code in ASP .NET?
Method:
private SerialPort _serialPort;
public void SendSms()
{
Console.WriteLine("Write phone number");
string phoneNr = Console.ReadLine();
Console.WriteLine("Write message");
string message = Console.ReadLine();
_serialPort = new SerialPort("COM2", 9600);
Thread.Sleep(1000);
_serialPort.Open();
Thread.Sleep(1000);
_serialPort.Write("AT+CMGF=1\r");
Thread.Sleep(1000);
_serialPort.Write("AT+CMGS=\"" + phoneNr + "\"\r\n");
Thread.Sleep(1000);
_serialPort.Write(message + "\x1A");
Thread.Sleep(1000);
_serialPort.Close();
}
Also in my app I have chat window so I want to use input box and button to write and send SMS.
<form method="post">
<input asp-for="MessageBody" id="textInput" type="text" placeholder="Enter message..." class="form-control " />
<button asp-action="SendMessage" id="sendButton" class="btn btn-primary btn-block" type="submit">Send</button>
</form>
For now SendMessage only saves message into database.
Sorry if my question is formulated not in the best way, writing here for the first time.
Can you try to add "\n" in this line.
_serialPort.Write("AT+CMGF=1\r");
It should be something like this
_serialPort.Write("AT+CMGF=1\r\n");
Here is the documentation you are looking for Serial port communication in .net core
Example from the link for completeness:
using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
static bool _continue;
static SerialPort _serialPort;
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
// Display Port values and prompt user to enter a port.
public static string SetPortName(string defaultPortName)
{
string portName;
Console.WriteLine("Available Ports:");
foreach (string s in SerialPort.GetPortNames())
{
Console.WriteLine(" {0}", s);
}
Console.Write("Enter COM port value (Default: {0}): ", defaultPortName);
portName = Console.ReadLine();
if (portName == "" || !(portName.ToLower()).StartsWith("com"))
{
portName = defaultPortName;
}
return portName;
}
// Display BaudRate values and prompt user to enter a value.
public static int SetPortBaudRate(int defaultPortBaudRate)
{
string baudRate;
Console.Write("Baud Rate(default:{0}): ", defaultPortBaudRate);
baudRate = Console.ReadLine();
if (baudRate == "")
{
baudRate = defaultPortBaudRate.ToString();
}
return int.Parse(baudRate);
}
// Display PortParity values and prompt user to enter a value.
public static Parity SetPortParity(Parity defaultPortParity)
{
string parity;
Console.WriteLine("Available Parity options:");
foreach (string s in Enum.GetNames(typeof(Parity)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Enter Parity value (Default: {0}):", defaultPortParity.ToString(), true);
parity = Console.ReadLine();
if (parity == "")
{
parity = defaultPortParity.ToString();
}
return (Parity)Enum.Parse(typeof(Parity), parity, true);
}
// Display DataBits values and prompt user to enter a value.
public static int SetPortDataBits(int defaultPortDataBits)
{
string dataBits;
Console.Write("Enter DataBits value (Default: {0}): ", defaultPortDataBits);
dataBits = Console.ReadLine();
if (dataBits == "")
{
dataBits = defaultPortDataBits.ToString();
}
return int.Parse(dataBits.ToUpperInvariant());
}
// Display StopBits values and prompt user to enter a value.
public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
{
string stopBits;
Console.WriteLine("Available StopBits options:");
foreach (string s in Enum.GetNames(typeof(StopBits)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Enter StopBits value (None is not supported and \n" +
"raises an ArgumentOutOfRangeException. \n (Default: {0}):", defaultPortStopBits.ToString());
stopBits = Console.ReadLine();
if (stopBits == "" )
{
stopBits = defaultPortStopBits.ToString();
}
return (StopBits)Enum.Parse(typeof(StopBits), stopBits, true);
}
public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
{
string handshake;
Console.WriteLine("Available Handshake options:");
foreach (string s in Enum.GetNames(typeof(Handshake)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Enter Handshake value (Default: {0}):", defaultPortHandshake.ToString());
handshake = Console.ReadLine();
if (handshake == "")
{
handshake = defaultPortHandshake.ToString();
}
return (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
}
}
So I have searched a lot of areas for this answer and I am confused on what this error is doing. Whenever I press the start server button...
...I get this error "An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll"
My code is quite long but I have no clue what to do...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private bool isserver = false;
public const int MAXSIZE = 10;
public Form1()
{
InitializeComponent();
clearoutput();
}
TcpListener tcpl = new TcpListener(IPAddress.Parse(getip()), 2546);
List<TcpClient> clients = new List<TcpClient>();
List<string> names = new List<string>();
bool CommandMode = false;
List<string> banlist = new List<string>();
TcpClient Client = new TcpClient();
//client setup
private void button1_Click(object sender, EventArgs e)
{
try {
Output.Text = Output.Text + "You have joined as a client";
Client = new TcpClient();
Client.Connect(IP_address.Text, 2546);
Thread myThread = new Thread(new ParameterizedThreadStart(Listen));
myThread.Start(Client);
//whenever you send a message you must include the next two lines
//Client.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount(name + " has joined") }, 0, 1);
//Client.GetStream().Write(Encoding.Unicode.GetBytes(name + " has joined"), 0, Encoding.Unicode.GetByteCount(name + " has joined"));
//the two lines above
Client.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount("\\join" + getip()) }, 0, 1);
Client.GetStream().Write(Encoding.Unicode.GetBytes("\\join" + getip()), 0, Encoding.Unicode.GetByteCount("\\join" + getip()));
}
catch { }
IP_address.Visible = false;
Join_btn.Visible = false;
Start_btn.Visible = false;
Output.Visible = true;
Input.Visible = true;
text1.Visible = true;
text1.Visible = true;
}
private void clearoutput()
{
Output.Text = "";
}
//server setup---
private void Start_btn_Click(object sender, EventArgs e)
{
isserver = true;
server_IP_lbl.Text = $"Since you are a server:\nYour ip address is : "+getip();
//if You need a new banlist make sure you click here and allow this
Write_to_output("you are a server");
try
{
StreamReader readerfrban = new StreamReader("banlist");
readerfrban.Close();
Write_to_output("we found a banlist \n no worries");
}
catch
{
Write_to_output("Error- could not find a banlist creating one now");
StreamWriter banlistmaker = new StreamWriter("banlist");
banlistmaker.Close();
}
//open banlist
StreamReader readerforban = new StreamReader("banlist");
string reader = "";
//read all bans in
do
{
reader = readerforban.ReadLine();
if (reader != null)
banlist.Add(reader);
} while (reader != null);
tcpl.Start();
//Thread AcceptSocketsThread = new Thread(AcceptSockets);
//AcceptSocketsThread.Start();
/* while (true)
{
string Message = Console.ReadLine();
if (Message.StartsWith("\\Kick"))
{
Console.Clear();
CommandMode = true;
int clientID = 0;
foreach (TcpClient client in clients)
{
Write_to_output(clientID.ToString() + ") " + names[clientID] + " " + client.Client.RemoteEndPoint);
clientID++;
}
Write_to_output("\n\n Enter the number of the person you want to kick");
TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
toRemove.Close();
clients.Remove(toRemove);
CommandMode = false;
}
else if (Message.StartsWith("\\Reset"))
{
foreach (TcpClient client in clients)
{
client.Close();
}
clients.Clear();
Write_to_output("KICKED EVERY BODY");
}
else if (Message.StartsWith("\\ban"))
{
Console.Clear();
CommandMode = true;
int clientID = 0;
foreach (TcpClient client in clients)
{
Write_to_output(clientID.ToString() + ") " + names[clientID] + " " + client.Client.RemoteEndPoint);
clientID++;
}
Write_to_output("\n\n Enter the number of the person you want to kick and ban");
TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
banlist.Add(toRemove.Client.RemoteEndPoint.ToString().Split(new char[] { ':' })[0]);
toRemove.Close();
clients.Remove(toRemove);
CommandMode = false;
}
//starts game
else
{
foreach (TcpClient client in clients)
{
SendMessage(Message, client);
}
}
}*/
IP_address.Visible = false;
Join_btn.Visible = false;
Start_btn.Visible = false;
Output.Visible = true;
Input.Visible = true;
text1.Visible = true;
text1.Visible = true;
}
void SendMessage(string message, TcpClient reciever)
{
try {
reciever.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount(message) }, 0, 1);
reciever.GetStream().Write(Encoding.Unicode.GetBytes(message), 0, Encoding.Unicode.GetByteCount(message));
}
catch
{
Write_to_output("Was unable to send to any users error code 1.0.0.0");
}
}
void AcceptSockets()
{
while (true)
{
TcpClient client = tcpl.AcceptTcpClient();
Thread myThread = new Thread(new ParameterizedThreadStart(Listen));
clients.Add(client);
myThread.Start(client);
}
}
void setname(string name)
{
names.Add(name);
}
void Listen(object obj)
{
TcpClient TCPClient = (TcpClient)obj;
while (true)
{
try
{
byte[] fBuffer = new byte[1];
TCPClient.GetStream().Read(fBuffer, 0, 1);
byte[] buffer = new byte[(int)fBuffer[0]];
TCPClient.GetStream().Read(buffer, 0, (int)fBuffer[0]);
string message = Encoding.Unicode.GetString(buffer).Trim();
if (message.StartsWith("\\join"))
{
message = message.Remove(0, 5);
int a = 0;
for (int i = 0; i < banlist.Count; i++)
{
if (message.StartsWith(banlist[i]))
{
a = 1;
}
}
if (a == 0)
{
//int namespaceer = 0;
//foreach (char chars in message)
//{
// namespaceer += 1;
// if (chars == '+')
// break;
//}
// message = message.Remove(0, namespaceer);
}
else
{
//Write_to_output("Person on banlist");
// TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
//toRemove.Close();
}
}
else
{
foreach (TcpClient client in clients)
{
if (client != TCPClient)
{
SendMessage(message, client);
}
}
if (!CommandMode)
{
Write_to_output(message.Trim());
}
else
{
}
}
}
catch (Exception e)
{
Write_to_output(e.ToString());
}
}
}
static string getip()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
}
public void Write_to_output(string towrite)
{
//check outputs length
int numLines = 0;
string text = Output.Text;
numLines = Text.Split('\n').Length;
if (numLines == MAXSIZE)
{
Output.Text = towrite;
}
else
{
Output.Text = Output.Text + $"\n" + towrite;
}
}
private void Input_Leave(object sender, EventArgs e)
{
string message = Input.Text;
if (isserver == false)
{
//send client code
SendMessage(message,Client);
}
else
{
//send server code
foreach (TcpClient client in clients)
{
SendMessage(message, client);
}
}
}
}
}
Please help me...
Check if the port TCP 2546 is not busy by another process or code instance on the listening machine.
Or choose another free port to listen to.
I am new at programming.
I am making a terminal program for some testing, the program has to send and receive data over serial-null modem. I found an example at MSDN: http://msdn.microsoft.com/en-us/library/y2sxhat8.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
But I cant get it to work. Here is what I have now:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Threading;
namespace Terminal_0._0._0._2
{
class Program
{
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
SerialPort _serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = "COM8";
_serialPort.BaudRate = 115200;
_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();
var _continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
}
I get this error:
Expected class, delegate, enum, interface, or struct
on line: 66
Column: 19
Thanks in advance.
As far as I can tell, there may be several things causing it not to work.
First of all, the Read method is outside the Program scope, resulting in it not working.
Secondly, moving it inside won't work either, until you also make "_continue" and "_serialPort" fields (outside methods).
Reworked code (removed redundant 'using' statements):
using System;
using System.IO.Ports;
using System.Threading;
namespace Terminal_0._0._0._2
{
class Program
{
private static bool _continue;
private static SerialPort _serialPort;
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
var readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort
{
PortName = "COM8",
BaudRate = 115200,
Parity = Parity.None,
DataBits = 8,
StopBits = StopBits.One,
Handshake = Handshake.None,
ReadTimeout = 500,
WriteTimeout = 500
};
// Allow the user to set the appropriate properties.
// Set the read/write timeouts
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
}
}
Since I don't have any serial devices, I can't test it, but the compiler compiled it without errors.
Thanks
Bjarke
This program is designed to open two COM ports and send data from one to the other ever 1 second. The user inputs which port transmits and which port recieves. The problem I am having is with the ElapsedEventHandler() takes in the OnTimedEvent() function which has two default arguments. I want the OnTimedEvent() function to write something to the send port and read it in on the recieve port, then display it to the console. Obviously my code will not work the way I have it now because the ports and message are not in the scope of OnTimedEvent(). What can I do to make that function work the way I want? Thanks in advance.
using System;
using System.IO.Ports;
using System.Timers;
public class serial_test1
{
public static void Main(string[] args)
{
string sender;
string recver;
string buff_out;
string message;
SerialPort send_port;
SerialPort recv_port;
if (args.Length == 1)
{
sender = "UART";
recver = "USB";
message = args[0];
}
else if (args.Length == 2)
{
sender = args[0];
message = args[1];
if (sender == "USB")
{
recver = "UART";
}
else
{
recver = "USB";
}
}
else
{
sender = "UART";
recver = "USB";
message = "TEST MESSAGE";
}
int baud = 115200;
int data_bits = 8;
Parity parity = Parity.None;
StopBits stop_bits = StopBits.One;
buff_out = message;
SerialPort UARTport = new SerialPort("COM1", baud, parity, data_bits, stop_bits);
SerialPort USBport = new SerialPort("COM7", baud, parity, data_bits, stop_bits);
UARTport.Open();
USBport.Open();
if (sender == "USB")
{
send_port = USBport;
recv_port = UARTport;
}
if (sender == "UART")
{
send_port = UARTport;
recv_port = USBport;
}
string header = "from " + sender + " port to " + recver + " port";
Console.WriteLine(header);
Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 1 second.
aTimer.Interval = 1000;
aTimer.Enabled = true;
UARTport.Close();
USBport.Close();
Console.ReadLine();
}
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
string buff_in;
send_port.WriteLine(buff_out);
buff_in = recv_port.ReadLine();
Console.WriteLine(buff_in);
}
}
I suggest using System.Threading.Timer instead, you can pass in a state object into the constructor that is passed in to the TimerCallback.
You can use one of these options:
01 - Simply use an auxiliar object
static string _value;
static void MyElapsedMethod(object sender, ElapsedEventArgs e)
{
Console.WriteLine(_value);
}
02 - Or use a closed class
class CustomTimer : System.Timers.Timer
{
public string Data;
}
private void StartTimer()
{
var timer = new CustomTimer
{
Interval = 3000,
Data = "Foo Bar"
};
timer.Elapsed += timer_Elapsed;
timer.Start();
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
string data = ((CustomTimer)sender).Data;
}
I am trying to build a simply app that returns the number calling via a modem, however I only seem to be getting the first line of the data received from the modem.
When I run HyperTerminal and pass through the AT#CID=1 command, ring the number, I get a full output of :
OK
DATE=0314
TIME=1111
NMBR=4936
NAME=Stuart E
RING
In my app i only seem to receive the first section containing the "OK" part. Any help on what i am doing wrong or am missing?
Code:
public partial class Form1 : Form
{
public SerialPort port = new SerialPort("COM3", 115200,Parity.None,8,StopBits.One);
public String sReadData = "";
public String sNumberRead = "";
public String sData = "AT#CID=1";
public Form1()
{
InitializeComponent();
}
private void btnRun_Click(object sender, EventArgs e)
{
SetModem();
ReadModem();
MessageBox.Show(sReadData);
}
public void SetModem()
{
if (port.IsOpen == false)
{
port.Open();
}
port.WriteLine(sData + System.Environment.NewLine);
port.BaudRate = iBaudRate;
port.DtrEnable = true;
port.RtsEnable = true;
}
public string ReadModem()
{
try
{
sReadData = port.ReadExisting().ToString();
return (sReadData);
}
catch (Exception ex)
{
String errorMessage;
errorMessage = "Error in Reading: ";
errorMessage = String.Concat(errorMessage, ex.Message);
errorMessage = String.Concat(errorMessage, " Line: ");
errorMessage = String.Concat(errorMessage, ex.Source);
MessageBox.Show(errorMessage, "Error");
return "";
}
}
private void btnExit_Click(object sender, EventArgs e)
{
port.Close();
Close();
}
}
}
In ReadModem() try to use port.ReadLine() in a loop instead and loop until you get a line saying RING (if that is the final line you are expecting).
You are just reading the Modem once after setting it. You need to subscribe the DataReceivedEvent on serialPort to continuously get data from the port.
public void SetModem()
{
if (port.IsOpen == false)
{
port.Open();
}
port.WriteLine(sData + System.Environment.NewLine);
port.BaudRate = iBaudRate;
port.DtrEnable = true;
port.RtsEnable = true;
port.DataReceived += port_DataReceived;
}
void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
//For e.g. display your incoming data in RichTextBox
richTextBox1.Text += this.serialPort1.ReadLine();
//OR
ReadModem();
}