C# code fails to read serial input from Arduino - c#-4.0

Hi I am trying to read serial input from my Arduino but I am having no luck. I believe I am opening and closing the connection correctly but do not appear to be having much success!
I'm sure the Arduino is outputting data because I can see it in the serial terminal.
The code for my C# program is below, I was wondering if anyone could spot any mistakes I may have missed.
Also this is an example of the serial data I should receive "12.2,1111,332,233"
namespace FridgeProtectionDeviceMonitor
{
public partial class Online_mode : Form
{
public Online_mode()
{
InitializeComponent();
}
private void Online_mode_Load(object sender, EventArgs e)
{
cmbPortSelection.DataSource = SerialPort.GetPortNames();
cmbChartSelection.SelectedIndex = 0;
}
string x = "";
SerialPort port;
private void btnFindPorts_Click(object sender, EventArgs e)
{
var ports = SerialPort.GetPortNames();
cmbPortSelection.DataSource = ports;
}
private void btnOpenPort_Click(object sender, EventArgs e)
{
if (cmbPortSelection.SelectedIndex > -1)
{
port = new SerialPort(cmbPortSelection.Text);
try
{
if (!port.IsOpen)
{
port.BaudRate = 9600;
port.Open();
}
}
catch (Exception)
{
MessageBox.Show("Serial connection request denied: Port is in use!");
}
}
else
{
MessageBox.Show("Serial connection request denied: No port selected!");
}
}
private void btnClosePort_Click(object sender, EventArgs ex)
{
try
{
port.Close();
}
catch (Exception)
{
MessageBox.Show("Serial close connection request denied: ", ex.ToString());
}
}
private void update(object sender, EventArgs e)
{
txtSaveLocation.Text = x;
}
private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
x = port.ReadLine().ToString();
MessageBox.Show(x);
this.Invoke(new EventHandler(update));
}
}
}

I was just working on the same thing as you, you'll have to modify it if you want to use it for your purposes, but here's the code I use that works. The only problem is that for me I need it to read very quickly because it's for a speedometer and it sort of lags (anyone know why?) but anyways here's my code that works for me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
try
{
if (arduinoCom.IsOpen == false)
{
arduinoCom.Open();
}
}
catch
{
MessageBox.Show("Serial Error: Is your serial plugged in?");
}
}
private void refresh_Tick(object sender, EventArgs e)
{
string speedReading = arduinoCom.ReadLine();
speed.Text = speedReading;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
arduinoCom.Close();
}
}
}

I've got a USB to serial converter linked to an XBee wireless bridge linked to PIC micro-controllers and i've found that running the serial port read functions in a separate thread increases communication speeds something chronic!
The readline blocks the code until the newline character is received, therefore blocking your main thread. Before i moved it to another thread my GUI became un-responsive etc.
By the way I'm using ReadByte().
I'm continuously reading bytes from the serial buffer in a backgroundworker and storing them in a thread safe queue. Then checking the queue for my communication start bits and analyzing the packet from there. Using manual reset events I'm syncing everything.
In my experience the port_datareceived event is a nice addition to the serialport class but unfortunately it is relatively useless for fast communications. I'm running at 12900 baud.
If you want code snippets i can provide them.
Regards,
Pete
P.S. I'm using an ATS5004D 4 channel differential oscilloscope with multichannel software. multichannel software can analyse the voltage signal into serial data through it's built in serial analyzer block. That way you can see what's actually being discussed on the serial comms lines!! cutting out all the BS other serial terminals add...

#michael b I'd start by looking at what the actual communication is doing i.e. scope the TX RX lines to see what the arduino board is putting out. I have only little experience with arduino but its predecessor the PICAXE system had a debug function which slowed everything down heaps, is something like this going on?
How many times per second do you want to update the speedo?
The SAE J1939 automotive serial communication standard says that RPM only needs to be updated once every 100ms. The human eye usually can't see/react faster than 300ms. 9600 baud gives you one 8bit byte per millisecond approx.
Personally I wouldn't use the timer to get the updates and instead do everything on a separate thread from main, and let it run as fast/slow as it wants.
this thread shows you roughly how i've set up my communications System.IO.IOException: A device attached to the system is not functioning C# .NET 4.0
hope it helps,
pete

Related

Program closing thread when button pressed Raspberry Pi

I realize there are similar questions here and I have looked at them, I just can't apply the solutions to my own problem.
I am writing an MP3 player for a Pi using visual studio (C#) on a PC, then using Mono on the Pi to run it.
As Mono does not seem to have an MP3 library (happy to be corrected) my workaround is to use a gui interface to control a command line mp3 player (omxplayer).
I have a working test interface which i ssh across to the Pi from my PC to test each time.
The problem is when I hit Button1 to run it, it works fine in that the mp3 plays.
But as soon as I hit button 2 to send the app the "p" key which should pause the program, it just quit out. Ultimately I will have a bunch of buttons sending key presses to control it like next skip stop etc.
I have tested the functionality from a terminal and it works fine.
Any suggestions would be appreciated.
Here is my code.
"Oh", Please don't flame me for making procStartInfo and proc global, I was grasping at straws :)
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
ProcessStartInfo procStartInfo;
System.Diagnostics.Process proc;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = "Button Clicked";
procStartInfo = new ProcessStartInfo("omxplayer", "/home/pi/Music/Debug/Mutter.mp3 &");
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = true;
proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
private void button3_Click(object sender, EventArgs e)
{
SendKeys.Send("{p}");
}
}
}

Video frame rate is too slow from IP Camera using Aforge Jpegstream C#

I'm using Aforge library to try to get a live stream from an IP Camera. My problem is, Frame rate is too slow and about one frame every 3 or 4 seconds! I have connected my camera directly to my computer through LAN port.
Here is my code :
JPEGStream stream;
public Form1()
{
InitializeComponent();
stream = new JPEGStream("http://192.168.1.88/pda.cgi?user=myusername&password=mypass&page=image&cam=1");
stream.NewFrame += stream_NewFrame;
}
private void stream_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
Bitmap bmp =(Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = bmp;
}
private void button5_Click_1(object sender, EventArgs e)
{
stream.Start();
}
private void button9_Click(object sender, EventArgs e)
{
stream.Stop();
}
I don't know if it will count as an answer but, have you tried to edit the FrameInterval Property of the JPEGStream?.
Set that to 0 so you can get as many as frame as possible
stream.FrameInterval = 0;
But I'll suggest use the MJPEGStream instead of JPEGStream if your IP Cam is supporting it. It is faster than the JPEGStream

Serial Port connection problems

I bought a sensor that is able to acquire phisiological parameters; it is connected to my pc with bluetooth protocol, so when it is connected a serial port (named for example COM10) is assigned.
Now I'm writing a simple routine to read the data in real time:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SewLib;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SewDevice myDevice;
SerialPort comPort;
public Form1()
{
InitializeComponent();
comPort = new SerialPort("COM10");
myDevice = new SewDevice(ref comPort);
myDevice.OnSamplesReceived += new ReceivedSamplesHandler(ReceiveData);
}
private void btstart_Click(object sender, EventArgs e)
{
eErrorClassOpcodes reply = myDevice.StartStreaming();
if (reply == eErrorClassOpcodes.Ok)
{
// ok device is connected and streaming is started
}
}
This works for me, but now I would to have a non static procedure for the selection of com port: my idea is to cycle beetween all the ports that my pc detect and select only the port with the bluetooth adapter.
Have you any ideas?
Thanks
Andrea
Auto-detecting your serial devices is a slippery slope. If you absolutely must, then I would just make a new helper class that looks something like this (untested)
class MyAutoDetector
{
public MyAutoDetector(){}
public SewDevice AutoDetect()
{
SerialPort comPort;
SewDevice myDevice = null;
eErrorClassOpcodes reply;
foreach(string portName in SerialPort.GetPortNames().ToList())
{
comPort = new SerialPort("COM10");
myDevice = new SewDevice(ref comPort);
reply = myDevice.StartStreaming();
if (reply == eErrorClassOpcodes.Ok)
{
// ok device is connected and streaming is started
break;
}
}
return myDevice;
}
I don't know about SewLib but you should verify that baud rate, bits, encoding, etc. Usually you configure your serial port with these.... but perhaps SewLib does that for you.
Another option, if you happen to know the unique PID/VID is answered here:
How do I get serial Port device id?

Windows Phone 8 (HTC 8X) Flashlight does not turn on(Without using camera)

As a newbie programmer I am going to ask a silly question. I want to turn on the flashlight of windows phone 8 without blinking (continous like other flashlight apps). Now I tried to use the sample example of
Reflection failure when attempting to access Microsoft.Phone.Media.Extended
but it did not work. I created a button called 'flash' and paste the code. It compiled fine, but my device HTC 8X does not turn on the flashlight even for a second. What I should do ?
The library & code I used :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Flashlight_V_0._1.Resources;
using Microsoft.Phone.Media;
using Windows.Phone.Media.Capture;
using Microsoft.Xna.Framework.Media;
using System.IO;
namespace Flashlight_V_0._1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
try
{
// get the AudioViceoCaptureDevice
var avDevice = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
}
else
{
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
}
}
I also tried this:
try
{
var _device = await AudioVideoCaptureDevice.OpenAsync(CameraSensorLocation.Back, AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First());
_device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
}
catch (Exception ex)
{
//
}
What am I doing wrong?
Sorry for late reply, got it ago but could not post.Sorry for that.
WP7/WP7.5 gives default to access all the sensors. But in WP8, you have to manually enable the sensors capability.
Go to the solution explorer.
Select the project.
Select Properties -> WMAppManifest.xml
Double Click on 'WMAppManifest.xml'
Select 'Capabilities'
Enable proper capability for app
To resolve my problem I had to enable two capabilities.
ID_CAP_ISV_CAMERA
ID_CAP_MICROPHONE
Thank YOU

Accessing UI from non-ui thread using dispatcher did not work

I am beginner to C# .net. I have simple app in wpf which access a listbox from user thread. in winforms i can use invokerequired, a equivalent for wpf using dispatcher did not help. My system also hangs for the buttons so debugging is though. Please provide solution for the below code. thanks in advance
private void Monitor_mtd()
{
while (AppStatus != 0)
{
if (flag2 == 1)
{
listBox1.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
new list1MtdDelegate(list1Mtd), "Best practice");
}
}
}
private delegate void list1MtdDelegate(string ls1);
private void list1Mtd(string ls1)
{
listBox1.Items.Add(ls1);
}
private void button1_Click_1(object sender, RoutedEventArgs e)
{
Monitor = new Thread(new ThreadStart(Monitor_mtd));
Monitor.Start();
flag1 = 1;
}
private void button2_Click(object sender, RoutedEventArgs e)
{
flag2 = 1;
}
There are a couple of issues that arise in your approach. Firstly, the way that you bind your data to the ListBox and secondly trying to update the ListBox from a user thread.
You can solve the binding of the ListBox by using an ObservableCollection so that the UI is updated with the necessary values (have a look at this post for more information on this). However, this also raises another problem and that is that the ObservableCollection cannot be called from another thread other than the one it is dispatching (see more on this here also). This means that you need another implementation for the ObservableCollection. Thomas Levesque made an AsyncObservableCollection that can be modified from any thread and still notify the UI when its modified.
I made a sample implementation that you can download here showing the full solution.

Resources