Hubert Ward

Hubert Ward

  • NA
  • 1
  • 738

Whats wrong with this c# code,using serial port instudio15

Oct 3 2015 2:07 PM
I have created a form in visual studio 15.
I have written this very simple routine to transmit a string to my pic micro. The pic, displays the string it has received on the LCD and then echos the string back to my form in visual studio. The pic also sends two bytes of data, integers to visual studio.
I then change one of the bytes in visual studio then send the changed byte.
The pic receives the changed value and displays it on the LCD. 
The cycle then repeats.
However, everything works fine except it is not consistent; there are times when the number of bytes received by visual studio are 5 and not three so I see the number10 which I think is the ascii for \n the end of line character. There are also times when it gives two wrong bytes. I think it depends on how many characters I transmit in the string.
I am adding the code I am using. I hope someone can see what is wrong with the code and give me some suggestions.  I don't want an over complex code as |I don't need to give the user the chance to use any other serial port that what is set.
I really want to know what is wrong with the code; please help if you can. I have programmed in C before but this is my first attempt with visual studio and c#
Thanking you in advanced
Hubert 
 


using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.IO;

using System.Text;

using System.Threading.Tasks;

using System.Windows.Forms;


namespace repairedcomms

{

public partial class Form1 : Form

{


int[] data2 = new int[10];

int comsin;

float pressure;

string message1;

string message2;

public Form1()

{

InitializeComponent();

serialPort1.Open();

}


private void button1_Click(object sender, EventArgs e)

{

string outmessage = textInBox.Text.ToString();

serialPort1.RtsEnable = true;

serialPort1.DiscardInBuffer();

serialPort1.WriteLine(outmessage);

displayTextIn.Text = serialPort1.ReadLine();

serialPort1.RtsEnable = false;

serialPort1.DiscardOutBuffer();

}


private void dataInButton_Click(object sender, EventArgs e)

{

serialPort1.RtsEnable = true;

int datalength = serialPort1.BytesToRead;

byte[] data1 = new byte[datalength]; //this creates aan array

comsin = serialPort1.Read(data1, 0, datalength);

message1 = data1[1].ToString();

pressure = data1[2];

pressure = pressure / 100;

displayDataIn.Text = message1;

secondDataIn.Text = pressure.ToString();

serialPort1.DiscardInBuffer();

}


private void button2_Click(object sender, EventArgs e)

{

message2 = newPressureSetting.Value.ToString();

displayDataIn.Text = message2;

serialPort1.WriteLine(message2);

serialPort1.DiscardInBuffer();

}

}

}