Pages: 1 [2]   Go Down
Author Topic: C# joystick interface  (Read 4356 times)
0 Members and 1 Guest are viewing this topic.
Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

The SetText() method in my code is how the serial read thread communicates with the user interface thread.

Get rid of all the stuff you are doing in Read() (with the data read from the serial port). Move that code to the SetText() method (in the else block).

The new data for the graph will then be available for you to use. If all you want is the x, y values, there is no reason to store all 7 values in an array.
Logged

Offline Offline
Sr. Member
****
Karma: 1
Posts: 486
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

i will eventually use all 7 values jsut not yet; i have to get it to work first smiley

ok after i move the splitting code, do i still sue message as the string to split? or "text" ?
Logged

http://dduino.blogspot.com all my Arduino/electronic projects!!!

{NEW} Getting Started, Learning, Reference + FAQ PDF!!:
[url]http://ar

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

In the SetText function, the data is pointed to by text.
Logged

Offline Offline
Sr. Member
****
Karma: 1
Posts: 486
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

im confused.
Logged

http://dduino.blogspot.com all my Arduino/electronic projects!!!

{NEW} Getting Started, Learning, Reference + FAQ PDF!!:
[url]http://ar

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

When you call SetText(), you pass it some data, through its argument list. The data you are passing it is a string, referred to by the name message.

In the SetText() function, that same data is referred to as text. If you want to continue to refer to it as message, change the variable name in the function declaration.
Logged

Offline Offline
Sr. Member
****
Karma: 1
Posts: 486
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

if text is the correct string for splitting, why: Input string was not in a correct format exception?
Logged

http://dduino.blogspot.com all my Arduino/electronic projects!!!

{NEW} Getting Started, Learning, Reference + FAQ PDF!!:
[url]http://ar

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Please post the specific message you are seeing. Please post the code you have (at least the SetText() function).

Adding a Console.WriteLine() statement to output what is in text might provide a clue.
Logged

Offline Offline
Sr. Member
****
Karma: 1
Posts: 486
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
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.receiveText.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.receiveText.Text += text;
this.receiveText.Text += "\n";

                //Handle data recieved; something like: 1023,1023,1023,1,1,1,1,     
                string[] split = text.Split(new Char[] { ',' });

                int cntwrite = 0;
                foreach (string s in split)
                {
                    if (s.Trim() != "")
                    {
                        int c = Int32.Parse(s);
                        JoyData[cntwrite] = c; //adds each new value split(s) from SerRead string to JoyData array
                        ++cntwrite;
                        if (cntwrite > 6) //reset cntwrite for next time serial data is recieved
                        {
                            cntwrite = 0;
                        }
                    }
                }
                this.SetText("X:");
                this.SetText(JoyData[0].ToString() + Environment.NewLine);
                this.SetText("Y:");
                this.SetText(JoyData[1].ToString() + Environment.NewLine);
                this.SetText("S:");
                this.SetText(JoyData[2].ToString() + Environment.NewLine);
                this.SetText(Environment.NewLine);
}

if i take out the splitting code, it works fine


* format exception.JPG (120.03 KB, 1144x838 - viewed 26 times.)
Logged

http://dduino.blogspot.com all my Arduino/electronic projects!!!

{NEW} Getting Started, Learning, Reference + FAQ PDF!!:
[url]http://ar

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
                this.SetText("X:");
                this.SetText(JoyData[0].ToString() + Environment.NewLine);
                this.SetText("Y:");
                this.SetText(JoyData[1].ToString() + Environment.NewLine);
                this.SetText("S:");
                this.SetText(JoyData[2].ToString() + Environment.NewLine);
                this.SetText(Environment.NewLine);
There is no reason to call the SetText() function from the user interface thread.

Code:
this.receiveText.Text += "X: ";
this.receiveText.Text += JoyData[0].ToString();
this.receiveText.Text += "\n";
this.receiveText.Text += "Y: ";
this.receiveText.Text += JoyData[1].ToString();
this.receiveText.Text += "\n";
this.receiveText.Text += "S: ";
this.receiveText.Text += JoyData[2].ToString();
this.receiveText.Text += "\n";
Logged

Offline Offline
Sr. Member
****
Karma: 1
Posts: 486
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

it was just there a  debugger; it doesn't make a difference with the error
Logged

http://dduino.blogspot.com all my Arduino/electronic projects!!!

{NEW} Getting Started, Learning, Reference + FAQ PDF!!:
[url]http://ar

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Quote
it doesn't make a difference with the error
It did for me.

Code:
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.receiveText.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
                this.receiveText.Text += "Text: ";
                this.receiveText.Text += text;
                this.receiveText.Text += Environment.NewLine;

                //Handle data recieved; something like:
// 1023,1023,1023,1,1,1,1,     
                string[] split = text.Split(new Char[] { ',' });

                int[] JoyData = new int[7];
                int cntwrite = 0;
                foreach (string s in split)
                {
                    if (s.Trim() != "")
                    {
                        int c = Int32.Parse(s);
                        JoyData[cntwrite] = c;
                        ++cntwrite;
                        if (cntwrite > 6)
                        {
                            cntwrite = 0;
                        }
                    }
                }

                this.receiveText.Text += "X: ";
                this.receiveText.Text += JoyData[0].ToString();
                this.receiveText.Text += Environment.NewLine;
                this.receiveText.Text += "Y: ";
                this.receiveText.Text += JoyData[1].ToString();
                this.receiveText.Text += Environment.NewLine;
                this.receiveText.Text += "S: ";
                this.receiveText.Text += JoyData[2].ToString();
                this.receiveText.Text += Environment.NewLine;
            }
}
Worked fine for me.
Logged

Offline Offline
Sr. Member
****
Karma: 1
Posts: 486
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

ok awesome, but the graph still doesnt update. i moved the graph under SetText and now it updates the dot the first time a serial command is received and split, but the second time serial data is received it doesn't change the dot:
Code:
namespace CommunicateWithArduino
{
public partial class Form1 : Form
{
public static System.IO.Ports.SerialPort port;
delegate void SetTextCallback(string text);

// This BackgroundWorker is used to demonstrate the
// preferred way of performing asynchronous operations.
private BackgroundWorker hardWorker;

private Thread readThread = null;

        int[] JoyData = new int[7];

public Form1()
{
InitializeComponent();
hardWorker = new BackgroundWorker();
}

private void btnConnect_Click(object sender, EventArgs e)
{
System.ComponentModel.IContainer components =
new System.ComponentModel.Container();
port = new System.IO.Ports.SerialPort(components);
port.PortName = comPort.SelectedItem.ToString();
port.BaudRate = Int32.Parse(baudRate.SelectedItem.ToString());
port.DtrEnable = true;
port.ReadTimeout = 5000;
port.WriteTimeout = 500;
port.Open();

readThread = new Thread(new ThreadStart(this.Read));
readThread.Start();
this.hardWorker.RunWorkerAsync();

btnConnect.Text = "<Connected>";

btnConnect.Enabled = false;
comPort.Enabled = false;
sendBtn.Enabled = true;

 
}

private void Form1_Load(object sender, EventArgs e)
{
foreach (string s in SerialPort.GetPortNames())
{
comPort.Items.Add(s);
}
comPort.SelectedIndex = 0;

baudRate.Items.Add("2400");
baudRate.Items.Add("4800");
baudRate.Items.Add("9600");
baudRate.Items.Add("14400");
baudRate.Items.Add("19200");
baudRate.Items.Add("28800");
baudRate.Items.Add("38400");
baudRate.Items.Add("57600");
baudRate.Items.Add("115200");

baudRate.SelectedIndex = 2;
}

private void sendBtn_Click(object sender, EventArgs e)
{
if (port.IsOpen)
{
port.Write(sendText.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.receiveText.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.receiveText.Text += text;
this.receiveText.Text += "\n";

                //Handle data recieved; something like: 1023,1023,1023,1,1,1,1,     
                string[] split = text.Split(new Char[] { ',' });

                int cntwrite = 0;
                foreach (string s in split)
                {
                    if (s.Trim() != "")
                    {
                        int c = Int32.Parse(s);
                        JoyData[cntwrite] = c; //adds each new value split(s) from SerRead string to JoyData array
                        ++cntwrite;
                        if (cntwrite > 6) //reset cntwrite for next time serial data is recieved
                        {
                            cntwrite = 0;
                        }
                    }
                }
                //
                //Graph
                //         
                int x = JoyData[0] / 2;
                int y = JoyData[1] / 2;

                Bitmap bmp = new Bitmap(512, 512);
                Graphics g = Graphics.FromImage(bmp);
                //draw axis lines
                g.DrawLine(new Pen(Color.Black, 2), 0, 240, 512, 240);
                g.DrawLine(new Pen(Color.Black, 2), 253, 0, 253, 512);
                // let's draw a coordinate
                g.DrawString("•", new Font("Calibri", 18), new SolidBrush(Color.Red), y - 12, x - 30);

                PictureBox display = new PictureBox();
                display.Width = 512;
                display.Height = 512;
                this.Controls.Add(display);
                display.Location = new Point(500, 5);
                display.Image = bmp;
}
}

public void Read()
{
while (port.IsOpen)
{
try
{
string message = port.ReadLine();
this.SetText(message);
}
catch (TimeoutException) { }
}
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
readThread.Abort();

port.Close();
}
}
}
Logged

http://dduino.blogspot.com all my Arduino/electronic projects!!!

{NEW} Getting Started, Learning, Reference + FAQ PDF!!:
[url]http://ar

Seattle, WA USA
Offline Offline
Brattain Member
*****
Karma: 601
Posts: 48543
Seattle, WA USA
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
                Bitmap bmp = new Bitmap(512, 512);
                Graphics g = Graphics.FromImage(bmp);
                //draw axis lines
                g.DrawLine(new Pen(Color.Black, 2), 0, 240, 512, 240);
                g.DrawLine(new Pen(Color.Black, 2), 253, 0, 253, 512);
The first two lines should define class level variables.

The next two should be in the Form_Load method, so they are done once.

Code:
                PictureBox display = new PictureBox();
                display.Width = 512;
                display.Height = 512;
                this.Controls.Add(display);
                display.Location = new Point(500, 5);
                display.Image = bmp;
All this code should be elsewhere, too. Most likely the Form_load() method. You don't want to do this every time serial data is received.
Logged

Offline Offline
Sr. Member
****
Karma: 1
Posts: 486
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

haha funny how this works smiley i was messing around with my code before you just posted, and did all of that, but it still doesn't work. it will display the X and Y axis when the form starts, but then it should write the dot to screen after splitting the incoming serial data; no dots are displayed on the screen though. ive tried display.Update(); etc and no luck. then i tried "this.Refresh();" under SetText after writing the new dot for X/Y and it works!!! see pic below.
can i make it so that it gets rid of the previous dots so theirs not dots all over?
also the x any y axis' are flipped(like left is right etc), any tips?

Code:
namespace CommunicateWithArduino
{
public partial class Form1 : Form
{
public static System.IO.Ports.SerialPort port;
delegate void SetTextCallback(string text);

// This BackgroundWorker is used to demonstrate the
// preferred way of performing asynchronous operations.
private BackgroundWorker hardWorker;

private Thread readThread = null;

        int[] JoyData = new int[7];

        private static Bitmap bmp = new Bitmap(512, 512);
        Graphics g = Graphics.FromImage(bmp);
        private PictureBox display = new PictureBox();

public Form1()
{
InitializeComponent();
hardWorker = new BackgroundWorker();
}

private void btnConnect_Click(object sender, EventArgs e)
{
System.ComponentModel.IContainer components =
new System.ComponentModel.Container();
port = new System.IO.Ports.SerialPort(components);
port.PortName = comPort.SelectedItem.ToString();
port.BaudRate = Int32.Parse(baudRate.SelectedItem.ToString());
port.DtrEnable = true;
port.ReadTimeout = 5000;
port.WriteTimeout = 500;
port.Open();

readThread = new Thread(new ThreadStart(this.Read));
readThread.Start();
this.hardWorker.RunWorkerAsync();

btnConnect.Text = "<Connected>";

btnConnect.Enabled = false;
comPort.Enabled = false;
sendBtn.Enabled = true;
}
private void Form1_Load(object sender, EventArgs e)
{
foreach (string s in SerialPort.GetPortNames())
{
comPort.Items.Add(s);
}
comPort.SelectedIndex = 0;

baudRate.Items.Add("2400");
baudRate.Items.Add("4800");
baudRate.Items.Add("9600");
baudRate.Items.Add("14400");
baudRate.Items.Add("19200");
baudRate.Items.Add("28800");
baudRate.Items.Add("38400");
baudRate.Items.Add("57600");
baudRate.Items.Add("115200");

baudRate.SelectedIndex = 2;

            //draw axis lines
            g.DrawLine(new Pen(Color.Black, 2), 0, 240, 512, 240);
            g.DrawLine(new Pen(Color.Black, 2), 253, 0, 253, 512);

            PictureBox display = new PictureBox();
            display.Width = 512;
            display.Height = 512;
            this.Controls.Add(display);
            display.Location = new Point(500, 5);
            display.Image = bmp;
}

private void sendBtn_Click(object sender, EventArgs e)
{
if (port.IsOpen)
{
port.Write(sendText.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.receiveText.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.receiveText.Text += text;
this.receiveText.Text += "\n";

                //Handle data recieved; something like: 1023,1023,1023,1,1,1,1,     
                string[] split = text.Split(new Char[] { ',' });

                int cntwrite = 0;
                foreach (string s in split)
                {
                    if (s.Trim() != "")
                    {
                        int c = Int32.Parse(s);
                        JoyData[cntwrite] = c; //adds each new value split(s) from SerRead string to JoyData array
                        ++cntwrite;
                        if (cntwrite > 6) //reset cntwrite for next time serial data is recieved
                        {
                            cntwrite = 0;
                        }
                    }
                }
                //Graph
                int x = JoyData[0] / 2;
                int y = JoyData[1] / 2;       
                // let's draw a coordinate
                g.DrawString("•", new Font("Calibri", 18), new SolidBrush(Color.Red), x - 12, y - 30);
                this.Refresh();
            }
}

public void Read()
{
while (port.IsOpen)
{
try
{
string message = port.ReadLine();
this.SetText(message);
}
catch (TimeoutException) { }
}
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
readThread.Abort();

port.Close();
}
}
}

And really, Thanks alot !!


* Firstsuccess.JPG (54.57 KB, 1037x560 - viewed 28 times.)
« Last Edit: November 13, 2011, 08:04:22 pm by sirbow2 » Logged

http://dduino.blogspot.com all my Arduino/electronic projects!!!

{NEW} Getting Started, Learning, Reference + FAQ PDF!!:
[url]http://ar

Pages: 1 [2]   Go Up
Jump to: