Its been almost 4 years since I've programmed in c# so I'm really rusty. I was given a project to create a program that will be able to read the vibration from an external Vibration Sensor connected via 2x micro usb cable. I am able to obtain the vibration x,y values from the external device however; I now need to plot the raw data obtained in a graph showing amplitude vs time Example Picture given!show raw data amplitude vs time. I also need to be able to grab these plotted points in the graph and export them to excel or any other means of storage for later analysis. Can you guys please help or point me in the right direction. Thanks Vibration results
Code example `
using Hardware.PR49;
using System;
using System.Collections.Generic;
using System.Threading;
namespace PR49SensorExample
{
class Program
{
static void Main(string[] args)
{
var task = PR49Detection.GetSerialPortSensorInfos();
if (!task.Wait(5000))
{
Console.WriteLine("Searching PR49 timed out.");
return;
}
var all49 = task.Result;
if (all49.Count == 0)
{
Console.WriteLine("No PR49 connected.");
return;
}
var port = all49[0].Port;
var sensor = new SerialDevice49(port);
var sources = sensor.SignalSources;
var xAxisSource = sources[0];
var yAxisSource = sources[1];
var xData = new List<double>();
var yData = new List<double>();
try
{
sensor.Connect();
sensor.StartDAQ();
}
catch
{
Console.WriteLine("Failed to connect or start sensor.");
return;
}
while (xData.Count < 20000)
{
xData.AddRange(xAxisSource.ReadDecodedData());
yData.AddRange(yAxisSource.ReadDecodedData());
Console.WriteLine($"data points: X: {xData.Count}, Y: {yData.Count}");
Thread.Sleep(200);
}
try
{
sensor.StopDAQ();
sensor.Disconnect();
}
catch
{
Console.WriteLine("Failed to stop or disconnect sensor.");
return;
}
Console.WriteLine("\nSensor stopped.");
Console.ReadKey();
}
}
}
`
Related
I start learning Netduino short time ago. At now, I want to use it with MS5803 30BAR sensor. This Components communicate with I2C Protocol. I learned this protocol a little bit but not enough.
I wrote introducing of code. When I came main code, I did not do anything. My code is below.
Can anybody help about this matter? I will be so pleased :)
public class Program
{
public static void Main()
{
// Configuration of MS5803 30BA
I2CDevice i2c = new I2CDevice(new I2CDevice.Configuration(0x76>>1, 400));
byte[] read = new byte[1];
I2CDevice.I2CTransaction[] i2cTx = new I2CDevice.I2CTransaction[1];
i2cTx[0] = I2CDevice.CreateReadTransaction(read);
// ???
}
}
It looks like you're missing the I2C.Execute call. Without knowing anything about the device you're communicating with this will at least start the transmission.
Try to add this line after you create the read transaction.
i2c.Execute(i2cTX[0],500);
byte[] returnByte = new byte[3];
var readX = new I2CDevice.I2CTransaction[] {I2CDevice.CreateReadTransaction(returnByte) };
int executed = 0;
I2CDevice i2c = new I2CDevice(new I2CDevice.Configuration(0x76, 400));
executed = i2c.Execute(readX, 400);
if (executed == 0)
{
//Debug.Print("Read FAIL!");
}
else
{
//Debug.Print("Read SUCCESS!");
}
//throw new Exception("I2C transaction failed");
//you will need to do some bit shifting with the readX array to get your values.
}
Here an excellent document on netMF i2c: https://www.ghielectronics.com/docs/12/i2c
The device data sheet:
http://www.amsys-sensor.eu/sheets/amsys.en.ms5803_30ba.pdf
I am using NAudio for a screen recording software I am designing and I need to know if it's possible to not only control the specific application's volume but also display a VU Meter for the application's sound.
I've Googled all over the place and it seems I can only get a VU Meter for the devices currently on my computer and set the volume for those devices.
Even though I am using NAudio, I am open to other solutions.
I asked the question in more detail after this question. I have since found the answer so I will leave the answer here for those who stumble upon it. Trying to use NAudio & CSCore has gotten me quite familiar with so please ask if you need further assistance.
This block of code uses CSCore and is a modified and commented version of the answer found here:Getting individual windows application current volume output level as visualized in audio Mixer
class PeakClass
{
static int CurrentProcessID = 0000;
private static void Main(string[] args)
{
//Basically gets your default audio device and session attached to it
using (var sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render))
{
using (var sessionEnumerator = sessionManager.GetSessionEnumerator())
{
//This will go through a list of all processes uses the device
//the code got two line above.
foreach (var session in sessionEnumerator)
{
//This block of code will get the peak value(value needed for VU Meter)
//For whatever process you need it for (I believe you can also check by name
//but I found that less reliable)
using (var session2 = session.QueryInterface<AudioSessionControl2>())
{
if(session2.ProcessID == CurrentProcessID)
{
using (var audioMeterInformation = session.QueryInterface<AudioMeterInformation>())
{
Console.WriteLine(audioMeterInformation.GetPeakValue());
}
}
}
//Uncomment this block of code if you need the peak values
//of all the processes
//
//using (var audioMeterInformation = session.QueryInterface<AudioMeterInformation>())
//{
// Console.WriteLine(audioMeterInformation.GetPeakValue());
//}
}
}
}
}
private static AudioSessionManager2 GetDefaultAudioSessionManager2(DataFlow dataFlow)
{
using (var enumerator = new MMDeviceEnumerator())
{
using (var device = enumerator.GetDefaultAudioEndpoint(dataFlow, Role.Multimedia))
{
Console.WriteLine("DefaultDevice: " + device.FriendlyName);
var sessionManager = AudioSessionManager2.FromMMDevice(device);
return sessionManager;
}
}
}
}
The following code block will allow you to change the volume of the device using NAudio
MMDevice VUDevice;
public void SetVolume(float vol)
{
if(vol > 0)
{
VUDevice.AudioEndpointVolume.Mute = false;
VUDevice.AudioEndpointVolume.MasterVolumeLevelScalar = vol;
}
else
{
VUDevice.AudioEndpointVolume.Mute = true;
}
Console.WriteLine(vol);
}
I have code from two different libraries only to answer the question I posted directly which was how to both set the volume and get VU Meter values (peak values). CSCore and NAudio are very similar so most of the code here is interchangeable.
I'm trying to experiment with the ACR122 card reader on Windows 8 using the Device Programming sample for C# that ships with the SDK. When I start the sample I don't see the card reader in the list of available devices.
I don't think this is a general driver problem because the tools for configuring the reader (precompiled binaries) list the reader and allow to connecting to it.
I'm new to C# and .NET. I would be glad if anyone could give me some advice on determining what's wrong. If you need more information I will happily provide you with it.
I'm no expert either, I'm currently working with the ACR122U reader and the samples didn't work perfectly for me either. But, I was able to write a little C# program so i can read/write small amounts of text (converted to hexadecimal) onto a Smart Card.
So I suggest you try to write it yourself, like I did, I'll give you some code which got me started (I used the pcsc-sharp dll):
using PCSC;
namespace SmartcardCheck
{
class Program
{
static void Main(string[] args)
{
using (var context = new SCardContext())
{
context.Establish(SCardScope.System);
string[] readerNames = null;
try
{
// retrieve all reader names
readerNames = context.GetReaders();
// get the card status of each reader that is currently connected
foreach (var readerName in readerNames)
{
using (var reader = new SCardReader(context))
{
Console.WriteLine("Trying to connect to reader {0}.", readerName);
var sc = reader.Connect(readerName, SCardShareMode.Shared, SCardProtocol.Any);
if (sc == SCardError.Success)
{
DisplayReaderStatus(reader);
}
else
{
Console.WriteLine("No card inserted or reader is reserved exclusively by another application.");
Console.WriteLine("Error message: {0}\n", SCardHelper.StringifyError(sc));
}
}
}
}
catch (Exception)
{
if (readerNames == null)
{
Console.WriteLine("No readers found.");
return;
}
}
Console.ReadKey();
}
}
}
}
Hope it helps you :)
The ACR122 is not seen by Windows as an NFC (proximity) device, it is a smart card device which has the capability to read NFC cards. To use it within Modern Apps or via the WinRT API's you'll actually need to use Windows 8.1 which has introduced support for smart cards.
I'm attempting to write a C# library which looks at all available USB serial ports on a Raspberry Pi so that I can enumerate, identify and communicate with a set of Arduinos connected to the Pi via a USB hub.
I am able to make this work on my windows machine (several Arduinos connected to my desktop computer) and have even been able to make it work on my Pi however, I am struggling to understand how to generalize the fix.
If I attempt to run the program by itself on the Pi, I am able to open the serial port and send data however, I cannot receive anything from the Arduinos: I get timeout exceptions. I understand that Mono's implementation of SerialPort is limited and I must use SerialPort.ReadByte() instead of Readline() and the data received events (my solution is based on code from HowToSystemIOPorts). My Serial port enumeration is using a method outlined in another stack exchange response here.
My timeout is currently set to 4 seconds, which is several orders of magnitude longer than I expect to receive the message.
After a lot of googling, I came across mention of using minicom to initialize the serial port here, which to my surprise allowed me to receive data from the Arduino. The biggest drawback is that I need to initialize the port using minicom and leave the process opening each time I boot the Pi. I also can't seem to figure out how to make this work with multiple Arduinos.
Here is what I have tried so far:
Updated the Pi firmware and software to their latest versions
Attempted to use both an Arduino MEGA 2560 R3 and Arduino UNO
Changed the owner of the tty* ports (ttyACM0 and ttyUSB0 in this case) to both my user and group
Successfully configured the port via minicom, left the process running and start the program and read/wrote data. A manual process which only seems to work for one Arduino at a time
Successfully run the program in Windows without fault
Verified the Arduinos are recognized by the Pi running "dmesg | grep tty"
Here is what I hope to solve:
Automatic setup/initialization of the Arduino serial ports. Whether through a shell script run before the main program or within Mono code so that the code below can run as intended.
Here is my connection code:
public bool StartArduinoComms()
{
string[] ports = GetPortNames();
foreach (string port in ports)
{
mLogger.LogMessage(ProsthesisCore.Utility.Logger.LoggerChannels.Arduino, string.Format("Found serial port {0}", port));
}
bool foundCorrectArduino = false;
var idPacket = new ArduinoMessageBase();
idPacket.ID = ArduinoMessageValues.kIdentifyValue;
string jsonOutput = Newtonsoft.Json.JsonConvert.SerializeObject(idPacket);
foreach (string port in ports)
{
SerialPort serialPort = new SerialPort(port, kArduinoCommsBaudRate);
serialPort.Parity = Parity.None;
serialPort.DataBits = 8;
serialPort.StopBits = StopBits.One;
//Only check unopened ports
if (!serialPort.IsOpen)
{
serialPort.Open();
//Disable telemtry just incase
var toggle = new { ID = ArduinoMessageValues.kTelemetryEnableValue, EN = false };
string disableTelem = Newtonsoft.Json.JsonConvert.SerializeObject(toggle);
serialPort.Write(disableTelem);
//Discard any built up data
serialPort.DiscardInBuffer();
serialPort.Write(jsonOutput);
serialPort.ReadTimeout = kIDTimeoutMilliseconds;
string response = string.Empty;
for (int i = 0; i < kNumRetries; ++i)
{
try
{
//This is guaranteed to timeout if not configured through minicom
response = ReadLine(serialPort);
break;
}
//Catch case where the serial port is unavailable. MOve to next port
catch (TimeoutException)
{
continue;
}
}
if (!string.IsNullOrEmpty(response))
{
//Perform response validation
}
else
{
//Got no response
}
if (!foundCorrectArduino)
{
serialPort.Close();
}
}
}
return foundCorrectArduino;
}
/// <summary>
/// From https://stackoverflow.com/questions/434494/serial-port-rs232-in-mono-for-multiple-platforms
/// </summary>
/// <returns></returns>
private static string[] GetPortNames()
{
int p = (int)Environment.OSVersion.Platform;
List<string> serial_ports = new List<string>();
// Are we on Unix?
if (p == 4 || p == 128 || p == 6)
{
string[] ttys = System.IO.Directory.GetFiles("/dev/", "tty*");
foreach (string dev in ttys)
{
//Arduino MEGAs show up as ttyACM due to their different USB<->RS232 chips
if (dev.StartsWith("/dev/ttyS") || dev.StartsWith("/dev/ttyUSB") || dev.StartsWith("/dev/ttyACM"))
{
serial_ports.Add(dev);
}
}
}
else
{
serial_ports.AddRange(SerialPort.GetPortNames());
}
return serial_ports.ToArray();
}
Have a look at stty command. It will let you set/read teminal settings
http://linux.about.com/od/lna_guide/a/gdelna38t01.htm will give a rundown on it's use.
It would be easier to call out to than minicom, and the settings stay on the device.
I have done something like the same as you before.
I had to read and write data through USB Serial adapter, and didnt use minicom.
It may not be god code but i found that inorder to read the data I could create a new thread and have that check for data, my code include a lot of stuff but basicly i did this:
System.Threading.Thread newThread;
newThread = new System.Threading.Thread(this.check_get_data);
and the check_get_data method
public void check_get_data ()
{
byte tmpByte = 0;
while (m_objSerialPort.BytesToRead != 0) {
tmpByte = (byte)m_objSerialPort.ReadByte ();
DoSomethingWithByte(tmpByte);
Thread.Sleep(20);
}
}
this is currently running with two usbserials. dont know if it helps but hope you find your solution
I have a WPF application for broadcasting video using Microsoft.expression.encoder and framework 4.0, but i got a delay of 15 sec while broadcasting.Is there any suggestion to reduce the delay while broadcasting.
below is the Code
using Microsoft.Expression.Encoder.Live;
using Microsoft.Expression.Encoder;
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
EncoderDevice video = null;
EncoderDevice audio = null;
GetSelectedVideoAndAudioDevices(out video, out audio);
StopJob();
if (video == null)
{
return;
}
StopJob();
_job = new LiveJob();
if (video != null && audio != null)
{
//StopJob();
_deviceSource = null;
_deviceSource = _job.AddDeviceSource(video, audio);
_job.ActivateSource(_deviceSource);
// Finds and applys a smooth streaming preset
//_job.ApplyPreset(LivePresets.VC1HighSpeedBroadband4x3);
// Creates the publishing format for the job
PullBroadcastPublishFormat format = new PullBroadcastPublishFormat();
format.BroadcastPort = 9090;
format.MaximumNumberOfConnections = 50;
// Adds the publishing format to the job
_job.PublishFormats.Add(format);
// Starts encoding
_job.StartEncoding();
}
//webCamCtrl.StartCapture();
}
catch (Exception ex)
{
WriteLogFile(this.GetType().Name, "button1_Click", ex.Message.ToString());
}
}
I am using MediaElement to show the webcam both on my server and client systems.
on Client Side
try
{
theMainWindow.getServerIPAddress();
IP = theMainWindow.machineIP;
MediaElement1.Source = new Uri("http://" + IP + ":9090/");
}
catch (Exception ex)
{
}
you could propably use IIS Smooth Streaming to start playback with lower bitrate material and gradually increase it as your client buffer fills up. Silverlight has builtin support for Smooth Streaming and the same could be implemented by hand in WPF (at least theoritecally).
Is there any particular thing stopping you from using SL on client side?