can't read data from serial port (in c#) [duplicate] - c#

This question already has answers here:
SerialPort not receiving any data
(3 answers)
Closed 8 years ago.
I wanna read from my sensors' data from serial ports, and i can read the name of the ports but i can't receive data from them... i'm new in #c and serial port coding, thanks before~
And here's my try:
using System;
using System.ComponentModel;
using System.Collections;
using System.Diagnostics;
using System.IO;
using System.IO.Ports;
using System.Text;
using System.Security;
using System.Security.Permissions;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class Program
{
//----------------------------------------------------- GLOBAL PARAMETER ------------------------------------------------------
//---serial port objects
static private List <SerialPort> _serialPort = new List<SerialPort>();
//---serial port read buffer
static private List <byte[]> _buffer = new List<byte[]>();
//---length of the port list
static private int _length;
//--------------------------------------------------- INIT FUNCTIONS ----------------------------------------------------------
//---init main function
static private void initFunction(){
//create the serial port objs
createPortObj();
//create the buffers
createBuffer();
//init a clock
//init the ports' name
return;
}
//---Set the port objs
static private void setPortOption(int i) {
SerialPort tPort = _serialPort[i];
//set options
tPort.BaudRate = 9600;
tPort.Parity = Parity.None;
tPort.StopBits = StopBits.One;
tPort.DataBits = 8;
tPort.Handshake = Handshake.None;
//set the datareceived function
//tPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
tPort.DataReceived += DataReceivedHandler;
tPort.Open();
return;
}
//---Create the port objs
static private void createPortObj(){
// Get a list of serial port names.
string[] _names = SerialPort.GetPortNames();
_length = _names.Length;
//create the objs
for(int i=0; i < _length; i++)
{
Console.WriteLine(_names[i]);
//create the port objects
_serialPort.Add(new SerialPort(_names[i]));
//init the port object
setPortOption(i);
}
return;
}
//---Create the buffer
static private void createBuffer() {
//create buffer for each port obj
for (int i = 0; i < _length; i++){
byte[] bufferOne = new Byte[_serialPort[i].BytesToRead];
_buffer.Add(bufferOne);
}
return;
}
//-------------------------------------------------- FEATURED FUNCTION ----------------------------------------------------
//---Transmit the code
//---Data received handler
static public void DataReceivedHandler(Object sender, SerialDataReceivedEventArgs e){
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
//Receive the data from serial ports
for (int i=0; i<_length; i++){
int temp;
temp = _serialPort[i].Read(_buffer[i], 100, _buffer[i].Length);
Console.WriteLine(temp);
}
return;
}
//-------------------------------------------------- RETRIVE FUNCTION ----------------------------------------------------
//---Retrive the source
static private void retriveFunction(){
//close the serial ports
foreach (SerialPort port in _serialPort){
port.Close();
}
return;
}
//-------------------------------------------------- MAIN -----------------------------------------------------------------
//---main function
static void Main(string[] args){
//init function, and open the
initFunction();
int[] num = new int[_length];
for (int i = 0; i < _length; i++){
num[i] = _serialPort[i].Read(_buffer[i], 0, _buffer[i].Length);
}
//check the result of the read function
Console.Write(num[0]);
//on serial port receiving
//retrive the source
retriveFunction();
Console.ReadLine();
}
}
}
thanks again~

I think your code is not wait for data receive.Before your sensors sends back data,your code is finish,program is end,you should handle data in a new thread or in DataReceived event.

Related

C # Serial.read is reading the characters correctly, even with the wrong BaudRate

I'm creating a software in C # that must read the serial port and when recognizing a String (String already known sent by the arduino with BaudRate 38400) it must inform the baudRate used in the reading.
My problem is that no matter what value I put in C # BaudRate, it still recognizes the data correctly.
I tried to change the baudRate on the Arduino, but the result is always the same.
For example, the arduino sends the word "Hello" to a baudRate of 38400. The C # should read the serial port and when recognizing the word Hello (which should only appear with the correct BaudRate) it should display the used baudRate and end the function . However, even setting the baud rate to 1200, 2400 ... etc, ... C # always reads the word "Hello".
On the arduino serial monitor, when I change the speed, the characters are scrambled when I select a different speed than the one configured (as it should happen in C #).
I need C # to receive the scrambled serial data when the baudRate is incorrect.
Snippet of C# code:
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 System.IO;
using System.IO.Ports;
namespace Baud
{
public partial class frmSerial : Form
{
public static System.IO.Ports.SerialPort serialPort1;
//private delegate void LineReceivedEvent(string line);
public frmSerial()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
Int32[] lista_bauds = new Int32[] { 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200 };
Boolean connected = false;
System.ComponentModel.IContainer components = new System.ComponentModel.Container();
serialPort1 = new System.IO.Ports.SerialPort(components); // Creating the new object.
for (int i = 0; i < lista_bauds.Length & connected == false; i++)
{
Console.WriteLine(lista_bauds[i]);
string ReceivedData = "";
serialPort1.PortName = "COM" + numCom.Value.ToString(); // Setting what port number.
serialPort1.BaudRate = 1200; // Setting baudrate.
serialPort1.ReadTimeout = 4000;
//serialPort1.DtrEnable = true; // Enable the Data Terminal Ready
serialPort1.Open(); // Open the port for use.
try
{
if (serialPort1.IsOpen == true)
{
ReceivedData = serialPort1.ReadExisting();
Console.WriteLine(ReceivedData);
if (ReceivedData.Equals("Hello") == true)
{
txtDatasend.Text = "Conectado com BaudRate de" + lista_bauds[i]; ;
Console.WriteLine(ReceivedData);
connected = true;
btnConnect.Text = "Conectar";
serialPort1.Close();
}
else
{
serialPort1.Close();
}
}
}
catch (Exception)
{
throw;
}
}
numCom.Enabled = false;
}
private void btnSend_Click(object sender, EventArgs e)
{
// Sends the text as a byte.
serialPort1.Write(new byte[] { Convert.ToByte(txtDatasend.Text) }, 0, 1);
}
}
}
Heres the arduino code:
int LED_Pin = 13; // LED connected to digital pin 13
void setup()
{
Serial.begin(38400); // Configure the baudrate and data format for serial transmission
pinMode(LED_Pin,OUTPUT); // Pin13 as Output
digitalWrite(LED_Pin,LOW); // Pin13 LED OFF
}
void loop()
{
Serial.println("Autenticar"); // Send the String,Use Serial.println() because we have used SerialPort.ReadLine() on C# side
// SerialPort.ReadLine() on C# side will return only after receiving '/n' character
Blink_LED(); // Blink LED to indicate transmission
}
//Function to Blink LED 13
void Blink_LED()
{
digitalWrite(LED_Pin,HIGH);
delay(100);
digitalWrite(LED_Pin,LOW);
delay(100);
}

How to convert a byte array to sound without headers c#?

I am using NAudio in my project to record sounds from the microphone. I want to convert the sounds to a byte array and then play them back. I am not using windows Forms instead i am doing it in a console application.
//get all the devices that can record audio
private List<WaveInCapabilities> sources = new List<WaveInCapabilities>();
private List<string> Devices = new List<string>();
private List<string> Channels = new List<string>();
public void GetMicDevices()
{
//get the capabilities of all the devices
for(int i = 0; i < WaveIn.DeviceCount; i++)
{
sources.Add(WaveIn.GetCapabilities(i));
}
foreach(var i in sources)
{
Devices.Add(i.ProductName);
Channels.Add(i.Channels.ToString());
}
}
private WaveInEvent source = null;
public void StartMic()
{
//set the device number
int DeviceNum = 0;
source = new WaveInEvent();
//set the device number
source.DeviceNumber = DeviceNum;
//create the waveFormat num of channels for the device
source.WaveFormat = new WaveFormat(44100, WaveIn.GetCapabilities(DeviceNum).Channels);
//start the mic
source.StartRecording();
}
//convert the sound into a byte array
//play the sound from the byte array
I've made some changes to your code and mostly used a memory stream, a Source_DataAvailable event
here is the full working code :
using NAudio.Utils;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp2
{
class Program
{
private static List<WaveInCapabilities> sources = new List<WaveInCapabilities>();
private static List<string> Devices = new List<string>();
private static List<string> Channels = new List<string>();
static WaveInEvent source;
static WaveOut _waveOut;
static WaveFileWriter writer;
static Stream memoryStream;
static WaveFormat _waveFormat;
static void Main(string[] args)
{
if (memoryStream == null)
memoryStream = new MemoryStream();
GetMicDevices();
StartMic();
}
/// <summary>
/// get all the devices that can record audio
/// </summary>
public static void GetMicDevices()
{
//get the capabilities of all the devices
for (int i = 0; i < WaveIn.DeviceCount; i++)
{
sources.Add(WaveIn.GetCapabilities(i));
}
foreach (var i in sources)
{
Devices.Add(i.ProductName);
Channels.Add(i.Channels.ToString());
}
}
public static void StartMic()
{
//set the device number
int DeviceNum = 0;
source = new WaveInEvent();
source.DataAvailable += Source_DataAvailable;
source.RecordingStopped += Source_RecordingStopped;
//set the device number
source.DeviceNumber = DeviceNum;
//create the waveFormat num of channels for the device
_waveFormat= new WaveFormat(44100, WaveIn.GetCapabilities(DeviceNum).Channels);
source.WaveFormat = _waveFormat;
writer = new WaveFileWriter(new IgnoreDisposeStream(memoryStream), _waveFormat);
//start the mic
Console.WriteLine("Start Rec");
source.StartRecording();
//record for 3 seconds
Thread.Sleep(3000);
//stop the mic
source.StopRecording();
Console.WriteLine("End Rec");
//play test
Console.WriteLine("Play test");
//play the sound from the byte array
IWaveProvider provider = new RawSourceWaveStream(
memoryStream, _waveFormat);
_waveOut = new WaveOut();
_waveOut.Init(provider);
_waveOut.Play();
Console.WriteLine("Press a key to exit");
Console.ReadKey();
}
private static void Source_RecordingStopped(object sender, StoppedEventArgs e)
{
source.Dispose();
source = null;
if (writer != null)
{
writer.Close();
writer = null;
}
}
private static void Source_DataAvailable(object sender, WaveInEventArgs e)
{ //convert the sound into a byte array
writer.Write(e.Buffer, 0, e.BytesRecorded);
}
}
}

code not reading from serial port

Good day,
I have tried everything to read a few strings from my xbee module on csharp.
but my code keeps telling me the serial port is not open when it reaches the event handler. any help would be appreciated greatly. thanks string display = myserial.ReadLine();
using System;
using System.Management;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
namespace ConsoleApplication2
{
class Program
{
public static SerialPort myserial = new SerialPort();
public string display;
static void Main(string[] args)
{
string[] ports = SerialPort.GetPortNames();
foreach (string p in ports)
{
Console.WriteLine(p);
}
SerialPort myserial = new SerialPort();
myserial.BaudRate = 9600;
myserial.Parity = Parity.None;
myserial.StopBits = StopBits.One;
myserial.DataBits = 8;
myserial.Handshake = Handshake.None;
myserial.RtsEnable = true;
myserial.DtrEnable = true;
myserial.ReadTimeout = 100000;
myserial.PortName = "COM3";
myserial.ReadTimeout = 10000;
myserial.DataReceived += new SerialDataReceivedEventHandler(DataRecievedHandler);
myserial.Open();
if (myserial != null)
{
if (myserial.IsOpen)
{
Console.WriteLine("connected");
}
}
Console.ReadLine();
}
static void DataRecievedHandler(object sender, SerialDataReceivedEventArgs e)
{
string display = myserial.ReadLine();
}
}
}
Your problem is that you have an ambiguity in your code. 2 Variables with the same name.
The class variable that you declare outside the main:
class Program
{
public static SerialPort myserial = new SerialPort();
and the variable inside the main method:
static void Main(string[] args)
{
SerialPort myserial = new SerialPort();
Inside the method the compiler will take the local variable myserial. You open it and register the event:
myserial.DataReceived += new SerialDataReceivedEventHandler(DataRecievedHandler);
So far everything is fine. But outside the Main method this SerialPort myserial does not exist. That means when you try to access myserial inside the DataRecievedHandler method the compiler "thinks" that you mean the first variable on class level! But this SerialPort has never been opened! Therefore it gives you the error.
You can solve it by using the sender object inside the event. Since the open SerialPort fires this event:
static void DataRecievedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort port = sender as SerialPort;
if(port != null)
{
string display = port.ReadLine();
}
}
Note: This variable display exist only inside the DataRecievedHandler method. You cannot use it in the main. Because you declare it again. This is a local variable which is not the same as you have declared on class level! remove the string and the class level variable will be used:
make it:
display = port.ReadLine();
2.
You can also solve it by simply removing the declaration of the SerialPort myserial variable inside the Main method. Probably would be simpler ;)
Just remove this line inside the Main method:
SerialPort myserial = new SerialPort();

Can't read the Fairbank scale weight properly

I tried to connect the scale and retrieve the weight from visual studio 2013, but it's wire that sometimes I can get the exacted weight and sometimes I couldn't. I was not sure what's wrong with the code. Can someone help? My code is listed below
using System;
using System.IO.Ports;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows;
using System.Data.SqlClient;
using System.Collections;
using System.Threading;
namespace PortDataReceived
{
class PortData
{
public static void Main(string[] args)
{
try
{
string lineOne = "One";
string lineTwo = "Two";
char CarriageReturn = (char)0x0D;
string final = lineOne + CarriageReturn.ToString() + lineTwo + CarriageReturn.ToString();// define the hexvalues to the printer
SerialPort mySerialPort = new SerialPort("COM3");//initiate the new object and tell that we r using COM1
mySerialPort.BaudRate = 9600;
//mySerialPort.Parity = Parity.Odd;
//mySerialPort.StopBits = StopBits.Two;
//mySerialPort.DataBits = 7;
mySerialPort.Parity = Parity.Odd;
mySerialPort.StopBits = StopBits.Two;
mySerialPort.DataBits = 7;
mySerialPort.Handshake = Handshake.None;
mySerialPort.ReadTimeout = 20;
mySerialPort.WriteTimeout = 50;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
//those r all the setting based on the scale requirement
/*foreach (string port in System.IO.Ports.SerialPort.GetPortNames())
{
Console.WriteLine(port);
}*/
while (true)
{
mySerialPort.Open();
mySerialPort.Write(final);
mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
Console.WriteLine("Press any key to continue...");
Console.WriteLine();
Console.ReadKey();
}
//mySerialPort.Close();
}
catch (System.IO.IOException e)
{
if (e.Source != null)
Console.WriteLine("IOException source: {0}", e.Source);
throw;
}
}
private static void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
Console.ReadKey();
}
}
}
Often with serial communication, you have to read multiple times, and concatenate each read, until you finally detect you've read the part that shows you've received it all. Detecting the end may be based on a specific count of bytes received, or it might be looking for a particular byte or sequence of bytes. But it's up to you to make that determination, and to continue reading until that condition is fulfilled. When you first read, there may be characters waiting, but the device has not sent them all yet, so you will have to read again almost immediately after your first read. You're dealing with a stream. The handler event fires when the stream starts, but it doesn't know how long the stream will flow.
This blog post discusses this and some other common serial port issues:
http://blogs.msdn.com/b/bclteam/archive/2006/10/10/top-5-serialport-tips-_5b00_kim-hamilton_5d00_.aspx

Socket Timeout at runtime [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hey guys I am new at the subject of Sockets
and I really need you help.
I am doing system of server and clients (like chat)
but something diffrent, I am doing it with Windows Form Application
in my server : I have list of sockets of all pepole that connect to the server, that already get acception from the server.
And I wanna to do a Timer that every X seconds it will runs on my List and check if the person is still connection I mean in that , that the person still connect on the internet and still can get packages and if not to remove him from the list.
someone can help me in c# how do it??
now at the server if someone is Exit the program Or if the internet is logout how i can check if the Client is out
and if yes so Close his connection?
i Read about TimeOut but how use it??? if it usfull?
Server:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Server
{
public partial class Form1 : Form
{
Socket sck;
static List<Socket> acc;
static List<Thread> thr;
//List<UserAt> thr;
static int port = 9000;
static IPAddress ip;
static Thread NewCon;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
acc = new List<Socket>();
//thr = new List<UserAt>();
thr = new List<Thread>();
NewCon = new Thread(getNewConnection);
//Console.WriteLine("please enter your host port ");
string inputPort = "9000";
try
{
port = Convert.ToInt32(inputPort);
}
catch
{
port = 9000;
}
ip = IPAddress.Parse("127.0.0.1");
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(ip, port));
sck.Listen(0);
NewCon.Start();
}
/// <summary>
/// get new connection from client
/// </summary>
public void getNewConnection()
{
while (true)
{
acc.Add(sck.Accept());
var t = new Thread(() => ReciveMessage(acc.Count-1));
t.Start();
thr.Add(t);
/* UserAt a = new UserAt();
a.index = acc.Count - 1;
a.thread = new Thread(() => ReciveMessage(a.index));
a.thread.Start();
thr.Add(a);
* */
}
}
public void ReciveMessage(int index)
{
while (true)
{
try
{
Thread.Sleep(500);
byte[] Buffer = new byte[255];
int rec = acc[index].Receive(Buffer, 0, Buffer.Length, 0);
Array.Resize(ref Buffer, rec);
//MessageBox.Show(Encoding.Default.GetString(Buffer));
//listBox1.Items.Add(Encoding.Default.GetString(Buffer));
SetText(Encoding.Default.GetString(Buffer));
}
catch
{
// thr[index].thread.Abort();
/*thr.RemoveAt(index);
for (int i = index+1; i < thr.Count;i++ )
{
thr[i].index -= 1;
}*/
break;
}
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.listBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.listBox1.Items.Add(text);
}
}
public string getIp()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
}
}
Client
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
static string name = "";
static int port = 9000;
static IPAddress ip;
static Socket sck;
public Form1()
{
InitializeComponent();
}
public void ReciveMessage()
{
while (true)
{
Thread.Sleep(500);
byte[] Buffer = new byte[255];
int rec = sck.Receive(Buffer, 0, Buffer.Length, 0);
Array.Resize(ref Buffer, rec);
SetText(Encoding.Default.GetString(Buffer));
//MyChat.Items.Add(Encoding.Default.GetString(Buffer));
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.MyChat.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.MyChat.Items.Add(text);
}
}
private void Login_Click(object sender, EventArgs e)
{
name = UserName.Text;
ip = IPAddress.Parse("127.0.0.1");
string inputPort = "9000";
try
{
port = Convert.ToInt32(inputPort);
}
catch
{
port = 9000;
}
try
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Connect(new IPEndPoint(ip, port));
ReciveMes.Enabled = true;
byte[] conmsg = Encoding.Default.GetBytes("<" + name + ">" + " connected");
sck.Send(conmsg, 0, conmsg.Length, 0);
SendToServer.Enabled = true;
}
catch
{
MessageBox.Show("חיבור נכשל");
}
}
private void SendToServer_Click(object sender, EventArgs e)
{
byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + MyMessage.Text);
sck.Send(sdata, sdata.Length, 0);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(SendToServer.Enabled)
{
byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + "Is Quit");
sck.Send(sdata, sdata.Length, 0);
}
}
}
}

Categories

Resources