Shop OBEX P1 Docs P2 Docs Learn Events
Any C# 2010 Experts on the Forums? — Parallax Forums

Any C# 2010 Experts on the Forums?

NWCCTVNWCCTV Posts: 3,629
edited 2012-09-09 11:22 in General Discussion
I am looking for a C# 2010 novice or expert that can maybe help me out a bit. I know this is not a C# Forum, but waiting on an answer on the MS forums can be daunting.

I have written a program that opens Comm port and communicates to my BS2 BoeBot. I am stuck at the portion I need to get my Servos to move and I am wondering if anyone may have some sample code that I can play with to try and get it to work. Here is what I have that does not work: I am stuck at the _port.WriteLine portion.
do {
    in_data = _port.ReadLine();
} while (!(in_data == "RDY"));

_port.WriteLine("!" + Constants.vbLf + servo1 + Constants.vbLf + servo2);

Comments

  • msrobotsmsrobots Posts: 3,709
    edited 2012-07-27 23:18
    well,

    I do not really understand what you are trying to do - but PLEASE consider the following advice.

    EDIT: I stand corrected ... there is no UNTIL in C# ... so the following is edited to correct it

    There are tons of way to write loops in C# but please remember the differences between 'do...while' and 'while' .


    Example: (edited)
    while(condition)
    {
        whatever;
    }
    

    will not run at all if condition is not met - it is head-controled - hence the condition belongs on the top
    do
    {
      whatever;
    }
    while (condition)
    

    will run at least once - it is foot-controled - hence the condition on the end

    I hope that helps you.

    If not - please post more of your code - I program in c# since 1998 (beta 1) for a living and can fix any problem for sure.

    Enjoy!

    Mike
  • msrobotsmsrobots Posts: 3,709
    edited 2012-07-27 23:53
    hm.

    after reading my post i think it might be still unclear

    so what you need to do is
    do 
    {
             in_data = _port.ReadLine();
    } 
    while (in_data != "RDY");
    
    _port.WriteLine("!" + Constants.vbLf + servo1 + Constants.vbLf + servo2);
    

    EDIT: I stand corrected ... there is no UNTIL in c#


    Enjoy!

    Mike
  • Dr_AculaDr_Acula Posts: 5,484
    edited 2012-07-28 07:00
    I do a lot of programming in vb.net 2010 and it has a lot of things in common with C# (including needing to really understand well the difference between "do while" and "loop... until" as explained by msrobots).

    Anyway, one thing I have found very useful is a program to sniff what is going on with the serial ports, so you can actually see your bytes going out and coming in. Program attached. Should be fairly simple to install and run.
  • Mike GMike G Posts: 2,702
    edited 2012-07-28 08:01
    I agree with Dr_Acula, a port sniffer is a great debugging tool. It helps to verify what is being sent over the serial port is what you expect.

    However, the do...until loop is a little confusing. First off, the ReadLine() method assumes a delimiter character is received in the serial buffer - something like control, linefeed - 0x0D, 0x0A. It is unclear from your post if the BOE sends end of line.

    When execution drops into the do...until loop, it will not exist until it sees a "RDY". You could be stuck in an infinite loop. I believe your question is less about C# and more about understanding the logic to accomplish the task at hand.

    2 Solutions
    1) Use the DataReceived event of the SerialPort object to handle incoming serial data.
    2) Poll the serial port every x seconds to check for data received.

    DataReceived w/ example code
    http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx

    Serial Port object w/ example code
    http://msdn.microsoft.com/en-us/library/30swa673
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-28 11:59
    msrobots, What I am trying to do is convert the code from this thread http://forums.parallax.com/showthread.php?96973-VB-Express-to-Stamp-Template&highlight=visual+basic

    post # 8 to C#. I thought I had the most of it down but after going through it this morning I am seeing more errors, If you could convert this for me and send it back I would appreciate it. The "RDY" part is on the Stamp side. I am able to get the commuication working and have the "Hello World" from the first example working.

    The ""do until" is throwing a "while expected" error.

    To look at the "Real Objective". I have this project completed in VB 2010. However, the goal is to use this in conjunction with MS Robotics Studio 4.0. With the latest release of MSRS, VB is not supported for the dssnewservice command. Only C# and BOO. The dssnewservice command MUST be utilized when creating a new Manifest that can be used within MSRS. Does this all make more sense now?

    Below is the code I have come up with to move the Servos using 2 Trackbars.

    [code][private
    void trackBar1_Scroll(object sender, EventArgs e)
    {

    // Set the window title text each time a scroll occurs.

    this.Text = "Value: " + trackBar1.Value;

    this.Servo1 = trackBar1.Value;
    }
     

    private void trackBar2_Scroll(object sender, EventArgs e)
    {

    // Set the window title text each time a scroll occurs.

    this.Text = "Value: " + trackBar2.Value;

    this.Servo2 = trackBar2.Value;
    }
    /CODE]
  • msrobotsmsrobots Posts: 3,709
    edited 2012-07-28 15:05
    NWCCTV,

    to much spin and vb lately ... I have to correct myself... there s no until in c#. So the valid forms are:

    while(condition)
    {
    whatever;
    }

    and

    do
    {
    whatever;
    }
    while (condition)

    so your loop is correct as is. SORRY...

    there is a nice vb-to-c# converter online. Try this to translate your program.

    Enjoy!

    Mike
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-28 15:48
    I have tried that site and also tried Sharp. For the most part the conversions went OK. However, the portion I am stuck at is the Trackbar issue. I know I am communicating with the BoeBot because when I click on the port open in Debug mode of the program, I am unable to send BS2 program as I get the "No Basic Stamp Found" error message. http://forums.parallax.com/showthrea...t=visual+basic post #8 shows the VB script for this. I have tried several variations of the code that was converted with no luck. It is only the Trackbar code where I am stuck at.
  • Mike GMike G Posts: 2,702
    edited 2012-07-29 10:34
    Attached is a very simple serial port console application that monitors the serial port for "RDY" on the DataReceived thread. The main execution branch simulates sending a servo command only if the listener (BS2) is ready.

    Use the same idea with the Slider controls events. Check the ready flag before sending the servo command.

    SerialPortConsole.zip

    Post your source code for help!
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-29 10:38
    Great. Thanks for this. I have some things to take care of today and will work on this when I return.
  • Mike GMike G Posts: 2,702
    edited 2012-07-29 11:19
    Make sure to set the COM Port and baud in the App.Config file.
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-29 11:34
    Here is a copy of my current code. I have some items commented out at the bottom because I got tired of copying/pasting. Basically what this does is it uses the examples from the previous linked thread for VB To Stamp. I have combined all of it into one form. Everything works and I am able to communicate with the stamp with no issues. The "RDY" command sent from the stamp works without a hitch. I can see the light on my Com Port adapter (Parallax Version) blinking constantly when I Debug, so I know it is trying to send the data. The only issue I am having is with the Trackbars actually being able to move the Servos. I tried a bit of code downloaded from the Internet last night but it seems to make the Debug hang and I have to restart the whole thing after each Debug. When I return later today I will mess around with the code you sent. I do not want to implement all of it since it is only the Trackbars that I am having issues with. Thanks for the help.
    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;
    using Microsoft.VisualBasic;
     
    namespace BS2_Serial_Port
    {
        public partial class Form1 : Form
        {
            public string in_data;
            public int Servo1;
            public int Servo2;
            public int Byte;
    
            public Form1()
            {
                InitializeComponent();
            }
            private void button1_Click(object sender, EventArgs e)
            {
                serialPort1.PortName = "COM1";
                serialPort1.BaudRate = 4800;
                serialPort1.Open();
                if (serialPort1.IsOpen)
                {
                    button1.Enabled = false;
                    button1.Enabled = true;
                }
            }
            private void button2_Click(object sender, EventArgs e)
            {
                textBox1.Text = serialPort1.ReadExisting();
            }
            private void textBox1_TextChanged(object sender, EventArgs e)
            {
            }
            private void button3_Click(object sender, EventArgs e)
            {
                serialPort1.Close();
            }
            private void Form1_Load(object sender, EventArgs e)
            { }
     
            private void data_in(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
            {
            }
    
            private void button4_Click(object sender, EventArgs e)
            {
                Application.Exit();
            }
    
            private void textBox2_Changed(object sender, EventArgs e)
            {
            }
     
            private void button5_Click(object sender, EventArgs e)
            {
                //   button5.Enabled = false;
                if
                    (textBox2.Text != String.Empty)
                    serialPort1.WriteLine(textBox2.Text);
            }
                //     button5.Enabled = true;
    
            
    
             
            private void trackBar1_Scroll(object sender, EventArgs e)
            {
                
                  do {
                 in_data = serialPort1.ReadLine();
                    } while (!(in_data == "RDY"));
               // serialPort1.WriteLine("!" + Constants.vbLf + Servo1 + Constants.vbLf + Servo2);
                            
                
                serialPort1.WriteLine(trackBar1.Value + "s");
                serialPort1.WriteLine("0s");
            }
        }
    }
              //      private void Form1_Load(object sender, EventArgs e)
                
               // serialPort1.Open();
               // 
                
                        
                    
         
    //do {
    // in_data = _port.ReadLine();
    //} while (!(in_data == "RDY"));
    //_port.WriteLine("!" + Constants.vbLf + servo1 + Constants.vbLf + servo2);
     
    
       
                
                
               
    
  • Mike GMike G Posts: 2,702
    edited 2012-07-29 15:11
    NWCCTV, the current logic checks for the string "RDY" 0x13, 0x10 in the serial port buffer on every TrackBar Scroll event. If the string is found, a servo command is sent. If the string is not found - well - we keep looping. The problem with this logic is there can (and will) be many scroll events fired which clogs up the system.

    The posted console application gets around this in an asynchronous manor by setting a flag when it sees "RDY" 0x13, 0x10. That's like cocking the gun. Now we're ready to fire. Pulling the trigger and fire the command then immediately resets the flag. While the gun is cocked no position commands are accepted.

    A better approach is a request-response scheme. Send a position command and wait for an acknowledge response from the BS2.
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-29 15:45
    Makes sense. I am in the middle of a couple other projects (work happens!!!!) When I am done I will give this a try and see how it goes. If it works then my main problem is solved. I was hoping to implement it within my current program but that is not essential at this time as the ultimate goal was to make the servos work via C# and Basic Stamp. I then need to convert to MSRS 4.0 which is a whole different matter. The older versions of MSRS allowed creating a new service using VB. The latest version only supports C# and I believe BOO. Thanks again for the help. I will keep you posted on how it goes.
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-29 17:02
    So am I suppose to add a new form to this with the Servo commands or what? I am getting a connect but the command prompt is throwing a constant loop of "send servo command" the only way to make it stop is to close or turn off my BoeBot. Is this correct or am I doing something wrong?
  • Mike GMike G Posts: 2,702
    edited 2012-07-29 17:34
    NWCCTV, The console application is always listening for a the RDY message from the BoeBot. When it sees the RDY, it simulates a servo command by writing "Send Servo command" to the console window. It makes perfect sense that turning off the BoeBot stops the "Send servo command" message.
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-29 18:40
    OK. I thought I was doing something wrong. So do I just input the Trackbar commands in the same program, deifferent form or what?
  • Mike GMike G Posts: 2,702
    edited 2012-07-30 06:50
    First, why does the BoeBot continuously send "RDY" 0x13, 0x10? Is it waiting for a command?

    As written, the serial port buffer does not flush until a slider is moved. Plus only the last "RDY" 0x13, 0x10 is flushed. If the TrackBar is not moved, eventually the serial port buffer will overrun. This is a logic bug!

    The console application gets around overflow exceptions by capturing everything on the serial port, parsing, and invoking logic.

    The application source is easily copied into a Win form but you must understand the concepts presented. I specifically wrote the console app to provide an example of consuming the Data_Received event in the context of your query.

    I would design a much different communication protocol - Request/Response or Command/Acknowledgement
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-30 07:57
    If you take a look at this thread http://forums.parallax.com/showthrea...t=visual+basic post number 8 you will get the idea. Yes, it is known that there are issues but the bottom line was just to familiarize the user with the concept. I just want to get this going for now and can work any bugs out later. This works in VB but like I said, I am having trouble porting over to C#.
  • Mike GMike G Posts: 2,702
    edited 2012-07-30 09:02
    If you take a look at this thread http://forums.parallax.com/showthrea...t=visual+basic post number 8 you will get the idea.
    I did. Post 8 details how to subscribe to the DataReceived event of the SerialPort object. Below, the data_in() delegate checks for the presence of "RDY" 0x13, 0x10 when the DataReceived events fires. If the string, "RDY" 0x13, 0x10, is found, the global values of servo1 and servo2 are written to the COM Port. The global values of servo1 and servo2 are set in the TrackBar.Scroll event handler.
    Private Sub data_in(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
    
            Do
                in_data = _port.ReadLine()
            Loop Until in_data = "RDY"
    
            _port.WriteLine("!" & vbLf & servo1 & vbLf & servo2)
    
        End Sub
    

    I did much the same in the console application... only in C#. Plus I made the code modular for copy and paste purposes.

    The code you posted polls the serial port when the user moves the TrackBar control. Which is nothing like post #8.
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-30 09:44
    This is where I am getting confused. Do I copy the entire console app to my Form to get the trackbars to turn the Servos? Would it not be easier to add a Form to the console app and place my trackbar commands in that? Also, What code do I need in the call to the trackbars? That is the part I am having issues with.

    I can code in VB OK, just not in C#. I wish Microsoft would have left well enough alone and kept the VB support in MSRS 4.0. They seem to think that everyone should change because they do not like the way things work.
  • Mike GMike G Posts: 2,702
    edited 2012-07-30 11:25
    Honestly NWCCTV, you are missing fundamental concepts. You actually have all the code needed to complete the task. I think it's time for you to figure this thing out on your own. Please ask if you have a specific question about the code or function.
    Do I copy the entire console app to my Form to get the trackbars to turn the Servos?
    No, just copy the factory class, event assignment, and handlers.
    Would it not be easier to add a Form to the console app and place my trackbar commands in that?
    No, just copy the code to your existing Win form.
    Also, What code do I need in the call to the trackbars?
    The trackbar value can be accessed through the value property; trackbar.Value.

    The scroll event should be assigned through a delegate when the form is initialized.
    this.trackBar1.Scroll += new System.EventHandler(this.trackBar1_Scroll);
    

    You have the option to roll your own or have the editor stub out the assignment and event handler by double clicking the Scroll event from the TrackBar properties window.
    I can code in VB OK, just not in C#. I wish Microsoft would have left well enough alone and kept the VB support in MSRS 4.0. They seem to think that everyone should change because they do not like the way things work.
    VB.NET and C# build the same intermediate code and target the same .NET framework. VB is a bit more verbose than C# and the editors have different features. However, the framework objects are the same regardless of the language used to invoke the objects.

    I know older versions of MSRS handled VB.NET. It looks like MS recommends the C# editor with MSRS 4.0.
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-07-30 14:50
    OK. I think I understand now. I will work on it and let you know if I get stuck again.

    And yes, MSRS 4.0 only allows creating new services in C#. Although, If you type in the new service help, it shows VB in the /language function.

    Thanks a bunch for your assistance,
  • NWCCTVNWCCTV Posts: 3,629
    edited 2012-08-01 22:11
    Thank you Jeff, AKA Unsoundcode. for creating the solution to this problem without reinventing the wheel. Your assistance has helped me move on with my project. Thank you also to Mike G for the lesson in clearing the com ports, etc.
  • jazzedjazzed Posts: 11,803
    edited 2012-08-02 11:28
    In the past I've used some .net reverse engineering tools that will translate VB code to C#. It won't add comments though.
    http://www.reflector.net/ Use the free trial first.
  • willsmannarwillsmannar Posts: 1
    edited 2012-09-09 11:22
    msrobots wrote: »
    NWCCTV,

    to much spin and vb lately ... I have to correct myself... there s no until in c#. So the valid forms are:

    while(condition)
    {
    whatever;
    }

    and

    do
    {
    whatever;
    }
    while (condition)

    so your loop is correct as is. SORRY...

    there is a nice vb-to-c# converter online. Try this to translate your program.

    Enjoy!

    Mike

    Check the following link , it will give yo the different types of loops in vb.net.

    http://vb.net-informations.com/programflow/vb.net_Program_Flow_Control_tutorials.htm

    also the website has lot of vb.net-c# parllal programs .

    wills.
Sign In or Register to comment.