|
I have pasted below the code that I am now using. As I am new to this, I thought a timer could be relatively easy to implement instead of the btnStart_Click event. Also, I know timing could really mess things up, but not sure how to deal with that either...
private void btnStart_Click(object sender, EventArgs e)
{
try
{
if (!sp1.IsOpen)
sp1.Open();
sp1.Write("*X01\r");
}
catch (Exception ex)
{
MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
}
}
private void Form1_Load(object sender, EventArgs e)
{
sp1 = new SerialPort("COM1", 9600, Parity.Odd, 7, StopBits.One);
sp1.Handshake = Handshake.None;
sp1.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
sp1.ReadTimeout = 500;
sp1.WriteTimeout = 500;
sp1.Open();
}
void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
Thread.Sleep(100);
string data = sp1.ReadExisting();
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { data });
}
private void si_DataReceived(string data)
{
char[] charsToTrim = {'X','0','1'};
textBox1.Text = data.TrimStart(charsToTrim);
}
|
|
|
|
|
If it's woking that way, then leave it alone.
But now I'm confused as to what you're writing and how.
|
|
|
|
|
The device I am using (a Newport meter) requires a string *X01\r in order to return the value that is on the display. When the button is clicked, it writes that string to the com port and then returns a series of characters, some of which are the actual value on the display. The problem is the button needs to be clicked. I want to have a start button and a stop button that begins and ends a thread used for automatically reading and writing to the com port, displaying the read value in a form label. Since I'm just learning C#, this is not an easy task. If anyone has any pointers, that would be greatly appreciated.
Thanks,Mike
|
|
|
|
|
I would likely use a System.Timers.Timer; the Elapsed event handler would handle the writing, the code you have above would deal with the incoming data.
|
|
|
|
|
I tried that without success. If I move the button click event to a timer tick event, nothing happens. I have even set the timer tick time to be >>Timer.Sleep (100) to make sure that there are no timing issues, but still nothing happens. However, if it did "work", seems that there would be a better way than a Timer.Sleep method....., but I'd take a successful timer function, if it would work. Thoughts?
|
|
|
|
|
I've never had trouble with timers.
You start the timer?
And set it to AutoReset?
Does it elapse at least once?
|
|
|
|
|
I checked the timer again.....Would help if it were enabled. Sometimes I wonder.
Seems that a stopwatch, as Rajesh suggest, may be the better way to handle this?
|
|
|
|
|
mprice214 wrote: enabled
Yes, but that's what Start does anyway.
I prefer the Timer Elapsed handler for sending and the event handler for receiving.
|
|
|
|
|
why are you going for timer to read the comport buffer,
i used stopwatch for this one , see the below code this may help u
Stopwatch ObjStopWatch = new Stopwatch();
ObjStopWatch.Start();
long StDelay = ObjStopWatch.ElapsedMilliseconds;
try
{
string FromModem = "";
Comport.ClearInputBuffer();
Comport.Write(Command);
Comport.Write(new byte[] { 0x0D, 0x0A });
do
{
if (Comport.InBufferCount>0)
{
Comport.Read(Comport.InBufferCount);
FromModem += Comport.InputStreamString;
if (FromModem.Contains("OK"))
break;
}
} while ((StDelay + 5000) > ObjStopWatch.ElapsedMilliseconds);
Frommodem holds the value of the comport buffer. here my timeout is 5000 milliseconds..
Thanks
Rajesh B --> A Poor Workman Blames His Tools <--
|
|
|
|
|
Hi Rajesh,
The issue I'm now having is that using a timer doesn't seem to be the most deterministic approach. In other words, I have a string that is written to the device at certain intervals. The serial data received method (SerialDataReceivedEventArgs) then Invokes the function that writes the returned string to a text box. However, to make sure the entire string is sitting in the buffer to be read, there is the Thread.Sleep. This seems very ineffecient and I'm trying to verify if that assumption is correct. What I would like to do is to write and read as fast as possible without the thread getting all tied up with timing issues. The device I'm talking to sends a carriage return at the end of the string. It seems that the fastest way to do this would be if I have a loop that writes a command string/waits for the string ending with a cr/writes that read value to whatever (textbox, etc) and writes the command string again.
Since I am new to this, I'm not sure if the stopwatch is the way to go, but I think a timer/thread.sleep combination is asking for crashing problems when I'm trying to do this a fast as possible.
Thoughts?
|
|
|
|
|
Here is what I have:
private void DisplayText(object sender, EventArgs e)
{
textBox1.Text = RxString;
serialPort1.DiscardInBuffer();
while (serialPort1.BytesToRead == 0)
serialPort1.WriteLine("*X01\r");
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString = "";
try
{
RxString = serialPort1.ReadTo("\r");
}
catch (Exception Exception)
{
return;
}
this.Invoke(new EventHandler(DisplayText));
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
}
I want to get rid of the timer and have a while loop that writes the ("*X01\r") once the buffer is empty. Then I won't need the timer. However, I can't get a while loop to work.
|
|
|
|
|
Hai All ,
I have input page there i have one textarea field i entered some data in pragraph format and new lines also ..
and now i stored these data in oracle table with datatatype as nvarchar2
now i am retrieving in another page thru dataset and i am displaying in label
the problem is it is displaying in jumble(mixed lines,no pragraph or no new line), not like paragraphs or new lines ...
Please reply me how to display like paragraphs ..
Thanks in Advance
|
|
|
|
|
You will need to use a richtextbox to display formatted text.
For an example, see here.
Me, I'm dishonest. And a dishonest man you can always trust to be dishonest. Honestly. It's the honest ones you want to watch out for...
|
|
|
|
|
|
<code>//executed in the main class
int testint = 0;
NewClass.test(this);
//NewClass
public void test(object sender)
{
PropertyInfo[] properties = sender.GetType().GetProperties();
foreach (PropertyInfo prop in properties)
{
MessageBox.Show(prop.Name);
}
}</code>
Im trying to write a reusable class for updating a ToolStripStatusLabel on multiple forms, Im using the code above which seems to work when i manually create a new class instance but when i try to use the sender properties.Length comes up as 0.
Im trying to get all the properties of the mainclass like testint
|
|
|
|
|
Cwhen this is not working which object you are passing other that your custom class.Is a label class
|
|
|
|
|
Can you try,
sender.GetType().GetProperties(BindingFlags.Instance)
Let us know if it works.
|
|
|
|
|
<pre>MessageBox.Show(properties.Length.ToString());
foreach (PropertyInfo prop in properties)
{
MessageBox.Show(prop.Name);
}</pre>
The above still comes up as 0 so the foreach isnt run.
sender.GetType().Name returns the class name though.
|
|
|
|
|
Could you please post the Meta details of the Class that Contains the ToolStripStatusLabel Property
|
|
|
|
|
|
GetProperties(BindingFlags.NonPublic | BindingFlags.Static) still gives a length of 0
heres the class im launching the the function from if it helps.
<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using System.Web;
namespace TestAplication
{
class MainClass
{
string URL;
string Name;
int Count = 0;
int SectionNumber = 0;
public int Delay = 0;
Taskbar TaskbarClass = new Taskbar();
public void GetSections(Form this, string CurrentmURL, string CurrentFormName)
{
TaskbarClass.test(this);</code>
|
|
|
|
|
Hello,
i sometimes get the "Safe handle has been closed" exception when i CLOSE my application (in debug mode). When i run it from the exe and try to close the app i simple get the "program has stopped working" error. I use a com port to communicate with an external device.
I hear it has something to do with a .net bug but is there anything i can do in the Form_closing event perhaps or somewhere else to stop it from showing when i close my program. How could i handle that exception?
Heres the stack trace:
System.ObjectDisposedException was unhandled
Message="Safe handle has been closed"
Source="mscorlib"
ObjectName=""
StackTrace:
at Microsoft.Win32.Win32Native.SetEvent(SafeWaitHandle handle)
at System.Threading.EventWaitHandle.Set()
at System.IO.Ports.SerialStream.AsyncFSCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOverlapped)
at System.Threading._IOCompletionCallback.PerformIOCompletionCallback(UInt32 errorCode, UInt32 numBytes, NativeOverlapped* pOVERLAP)
InnerException:
My idea was the following: (to make sure that the communication thread does not send anything else when user wants to exit)
Form_Closing event
{
signal_comm_thread
loop while(getSignal_from_comm_thread)
}
Comm_thread
{
if(signal_received)
signal_Form_Closing event
break;
}
But the program wont close at all this way Tried to use ManualResetEvents, public static variables for the signaling but nothing helps. Only way the program closes is if i add a "MessageBox.Show" in Form_Closing event after signaling comm_thread. How can that help?
TY
|
|
|
|
|
I've seen similar things happens when attempting to close a serial port read thread at form close.
What I do now is allow the reader thread to close the port and wait in the UI thread until the reader thread has exited. Like this:
private void ReadWriteThreadProc() {
continueLooping = 1;
try {
while (continueLooping != 0) {
try {
received = com.Read(buffer, 0, buffer.Length);
} catch (TimeoutException) {
}
}
} finally {
com.Close();
}
}
public void CloseCom() {
Interlocked.Exchange(ref continueLooping, 0);
ReadWriteThread.Join();
}
The timeout is rather crucial as it ensures that the exit condition is polled.
Alan.
|
|
|
|
|
Are you using a serial port, or a USB-to-serial converter? The SerialPort object in .Net does not behave well at all if a port is open on a USB-to-serial converter that is unplugged. I don't know any good libraries, but I'm sure they're out there. For my application, I coded a silly little helper application which acts as a bridge between a TCP socket and a .net SerialPort object; if the SerialPort object dies, the helper application quits without jinxing the main app.
|
|
|
|
|
Hello,
I am a experienced C# developer and I have good knowledges about security and viruss.
I started this project a week ago, i finished some parts like scanner that read the file Hex and compare some parts to our ScannerDatabase.
What i need is some one to help in some things, like getting Trojan keys in the registry after detecting it, and also i need a security expert so he can show me how does trojan hide in other processes like Internet Explorer.
Tanck you, and i am waiting for your replies .
|
|
|
|
|