Getting Garbage data like "??" rather than actual string while receiving data from microcontroller

  • Thread starter Thread starter Abinashhota
  • Start date Start date
A

Abinashhota

Guest
Hi Team,

I am using PSOC Microcontroller to receive data to my window application(C#.NET).

When i tried to receive data i am getting garbage data rather than the actual string. But when i tried with Tera Term or Putty i am getting my required string (ON,OFF) rather than "??".

Below is my c# program.

I am using RS 232 Serial-USB Converter.

Please let me know any issue is in my program.


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using System.Threading;

namespace WindowsApplication14
{
public partial class Form1 : Form
{
SerialPort _serialPort;

// delegate is used to write to a UI control from a non-UI thread
private delegate void SetTextDeleg(string text);
//private delegate void StringTextDel(string txt);

public Form1()
{
InitializeComponent();
}

private void btnStart_Click(object sender, EventArgs e)
{
// Makes sure serial port is open before trying to write
try
{
if (!_serialPort.IsOpen)
_serialPort.Open();

_serialPort.Write("SI\r\n");
}
catch (Exception ex)
{
MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
}
}

private void Form1_Load(object sender, EventArgs e)
{
// all of the options for a serial device
// can be sent through the constructor of the SerialPort class
// PortName = "COM1", Baud Rate = 19200, Parity = None,
// Data Bits = 8, Stop Bits = One, Handshake = None
_serialPort = new SerialPort();
_serialPort.PortName="COM7";
_serialPort.BaudRate = 9600;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
//_serialPort = new SerialPort("COM7", 19200, Parity.None, 8, StopBits.One);
_serialPort.Handshake = Handshake.None;
_serialPort.DataReceived += new SerialDataReceivedEventHandler(sp_DataReceived);
_serialPort.ReadTimeout = 100000;
_serialPort.WriteTimeout = 100000;
_serialPort.Open();
}

void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string str = sp.ReadExisting();

//int i = sp.ReadByte();
// str = str + " size = " + i;
//MessageBox.Show(str);
//Thread.Sleep(500);
//str = _serialPort.ReadLine();
/*------------------------*/


/*------------------------*/
this.BeginInvoke(new SetTextDeleg(si_DataReceived), new object[] { str });
}

private void si_DataReceived(string data)
{
textBox3.Text = data.Trim();
}

private void btn_LED_Click(object sender, EventArgs e)
{
if (!_serialPort.IsOpen)
_serialPort.Open();

_serialPort.Write(txt_LED.Text);
// _serialPort.ReadLine();

}
}
}

Output

------------

Continue reading...
 
Back
Top