Click here to Skip to main content
15,888,461 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to write a C# Form App. that will communicate with Arduino via Serial port and control the motors connected to the Arduino., and also receive a byte from Arduino and display a Message. My problem is i can't do both the writing and reading simultenously. i have to stop one to perform the other. Here is my code.
C#
 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.Ports;

namespace Securino
{
    public partial class Form1 : Form
    {
        SerialPort port = new SerialPort();
        
        public Form1()
        {

            InitializeComponent();
            port.PortName = "COM2";
            port.BaudRate = 9600;
            port.Open();
           // listen();
                  
        }

        private void button1_Click(object sender, EventArgs e)
        {
            port.Write("l");
            
        }

        private void button2_Click(object sender, EventArgs e)
        {
            port.Write("r");
        }

        private void button3_Click(object sender, EventArgs e)
        {
            port.Write("f");

        }

        private void button4_Click(object sender, EventArgs e)
        {
            port.Write("o");
        }

        private void button5_Click(object sender, EventArgs e)
        {
            port.Write("c");
        }

        private void button6_Click(object sender, EventArgs e)
        {
            port.Write("x");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void button7_Click(object sender, EventArgs e)
        {
            
            Console.WriteLine("listening");
            int ch = port.ReadChar();
            if (ch == 65)
            {
                MessageBox.Show("INTRUDER DETECTED");
            }
        }
        }
        

        
    }
Posted
Comments
Richard MacCutchan 1-Jun-15 4:10am    
That is correct.

1 solution

Each SerialPort is working like this.
But you can do the following :

You could (for example) build a Timer-Method which is called each 100ms.
This method do the port.write for you if there is data to write and it asks if there is data to read in the port and if 'yes' it reads the data.
With this solution your keystrokes have to be written to a kind of buffer and not longer to the port directly.

I suggested a Timer because it is the easiest way to do this.
You could also do this with a BackgroundWorker or a Task.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900