Serial port

Fernando
Hello, I was making some tests, and I noticed that the serial port control
from vbnet is too slow under wince!

Is there a better (faster) way to read data from the serial port?

Thank you all
Fernando

Fernando
I'll explain a little more the situation: 

with the serial port open and receiving continuesly  data (4800 bps, 300
bytes per second), the rest of the application slows down. I have a main
loop where I increment a variable and print it each time the loop begins,
and without the serial port (or the device not sending data) it goes around
10 times per second in the loop. With the serial data enabled, it goes 1 or
2 times per second.

I tried to set the rxthreshold to bug numbers, like 300 bytes or more, but
is the same... 

Could this problem be a limitation of the platform more than a problem?

Thanks all, hope somebody can help me... the most sad thing is that this is
happening with just one comm, and I need to use the three of them :S

Edje11
4800bps is what we used back in the 70's.
Should be no problem at all for the arm.
Made you can show use some code.

domodom
I'm not a vb.net genius, but i heard some things about the poor performance
of stream drivers used by a managed application (vb.net or c#).
I wonder if a solution couldn't be to write an unmanaged dll in c to
administer the serial port and export functions to exchange data with the
managed application. 

It's the idea I have, but I never made such a thing (it's for these reasons
I write my applications in c/c++)

domodom

Fernando
Hi Edje and domodom,
I solved this issue... the ActiveSync connection was slowing down that much
the application! I closed the link and the application runs ok!

My imstake.. :$

By the way... domodom, how would be to write an unmanaged dll in C? its
interesting but I dont have a clue... and it sure could be useful for some
things.

Thank you all!!!
Again!

domodom
Hello Fernando, 
Someone contacted me on my website to have advices to write a c#
application that use serial port. It's the guy who sent me the c# version
of my GPIO sample application.
If it is possible for you, could you post your application here (or just
the interesting part of your source code ?)
Best regards
Domodom

Fernando
Hi domodom, 

The code I'm posting is defined inside a class (that is because I will use
the three serial ports, each one for a different type of device)...

First of all, I create the serial port control:

    Private WithEvents sp As New System.IO.Ports.SerialPort

In the class constructor, I initialize the serial port:

        Try
            With sp
                .PortName = "COM2"
                .BaudRate = 4800
                .Parity = IO.Ports.Parity.Odd
                .StopBits = IO.Ports.StopBits.One
                .ReceivedBytesThreshold = 20
                .DiscardNull = False
                .Open()
            End With
        Catch ex As Exception
            _mensajes = "ERROR PUERTO"
        End Try

Then, the event handlers:

   Private Sub sp_DataReceived(ByVal sender As Object, ByVal e As
System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
        Dim cantidad As Integer
        cantidad = sp.BytesToRead
        sp.Read(datos_rx, 0, cantidad)
        RECEPCION(cantidad)
    End Sub

    Private Sub sp_ErrorReceived(ByVal sender As Object, ByVal e As
System.IO.Ports.SerialErrorReceivedEventArgs) Handles sp.ErrorReceived
        sp.DiscardInBuffer()
    End Sub

The sub RECEPCION reads the data and tries to find the header of the rx
frame, then process the data... etc

Hope it helps! Just ask if you need more about this.

andrés barré
private void serialPort1_DataReceived(object sender,
System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            byte ini = 126;
            byte[] escopo = new byte[1];
            {
                do
                {
                    serialPort1.Read(escopo, 0, 1);  // lon
                } while (!(escopo[0] == ini));

                {
                    serialPort1.Read(xbeeByte.rxbbee1, 0,
serialPort1.BytesToRead);  // NI    0, 85
                    EncodingXbeeData();
                    serialPort1.DiscardInBuffer();   // <<<!!!!!
                }
            }
        }

fernando...  fijate en el discart bufer...  si no haces eso  s blokea
despues de un tiempo!


andres

Fernando
Hi Andres (te escribo en ingles para que de paso si le sirve a alguien,
bienvenido sea)

Your system blocks after some time if you dont discard the buffer? How much
time does it take to hang? that's one of the tests I have to do, actually I
have it running now...

If you let me, I want to mark some things in your code... you are waiting
for certain data "inside the interrupt"... what is better, from my point of
view, is read all the data present in the buffer, store it in another
buffer, and then in the main loop process the buffer, search for the start
byte, etc.

that way, when you exit the interrupt, the read buffer is totally readed
and no need to flush the buffer.

What do you think?
Saludos!
Fernando (Argentina, y vos?)

david
hi can any body helpe im trying to make an aplication that can read the
serial port, so im trying to execute the comtest but i cant do it work

here is the steps i made:

i compile the comtest example with this line: 

arm-linux-gcc -o comtest comtest.c
it made a file call comtest

and after that i send the file comtest to the mini

and now i trying to execute with this line
./comtest

but this is the messeage mistake:

Unable to open device
streero() is no No such file or directory


what can i do? 

pd: yo tambien hablo español soy de colombia jejeje

Fernando
hola David (muchos latinoamericanos eh!! :)  )

I cant help with linux... did you try in the linux forum?

andrés barré
hola fernado.

if… without doubts better and but it is ordered to do it of the way that
you indicate, but as they run by ways I am using separated it thus, so that
it did not give problems me

si...  sin dudas es mejor y mas ordenado hacerlo de la manera que indicas,
mas como corren por vias separadas  lo estoy usando asi , por que no me dio
problemas

as far as the time that was blocked.? it watches does not pay attention to
him. but I am solved when it cleaned bufer

en cuanto al tiempo que se bloqueaba..?  mira  no le preste atencion .. 
mas se me soluciono cuando  limpiaba el bufer

and if I am using to the program at the moment to verify it 4 units xbee
that they pertencen to an alignment system, and transmit the data of his 2
sensors ccd and a clinometer of 2 axes each head 


;.  argentino tambien .  solo que viviendo en brasil.. o  playas lindas!!!!
 jejejj

Fernando
Saludos David!! :)
Ojala podamos ayudarnos mutuamente...

domodom
Hello Fernando, 
Thank you very much to have posted your code with your explanations.
I will try to find time to write a tutorial on my web site.
domodom

Fernando
Whenever you want Domodom, if you need anything else for this or other
tutorial, just let me know. I will be glad to help you in whatever I can.
Fernando

MexFer
Hi Fernando Im interested in the complete source code cause Im new with the
VB programming and the serial port issues so I would like to see your full
code as a guide so I can develop my own codes and learn about, if you could
make an attachment it could help me a lot.

Thanks

Fernando
Hi MexFer,
what you see is the complete source for getting data from the serial port.
The rest of the code (like the RECEPCION sub) is the code for doing
something with the received data, but that depend of your application.

If you write the above code, you will be reading data from the serial port
:)

Did you try to do something with it already?

Regards,
Fernando

MexFer
=O not really I thought there should me something else =P, Im going to read
it and try to understand it =).
By the way by naming "COM2" the port name you are using the fisical com2
(Serial TTL of the board?)

Thanks

Fernando
Yes, COM2 the serial port that is available in the board. You can use it in
TTL levels (in CON2) or RS232 levels (from the DB9).

Regards, you are welcome.
Fernando

MexFer
Well I have a problem this is the code Im using I do some changes cause my
VB get me some errors...

Public Class Form1

    Private WithEvents sp As New System.IO.Ports.SerialPort

    Dim datos_rx() As Char 'I got an error that this variables werent 
    Dim _mensajes As String ' declared

    Private Sub sp_DataReceived(ByVal sender As Object, ByVal e As
System.IO.Ports.SerialDataReceivedEventArgs) Handles sp.DataReceived
        Dim cantidad As Integer
        cantidad = sp.BytesToRead
        sp.Read(datos_rx, 0, cantidad)
        TextBox1.Text = cantidad ' I want to put the data in a text box.
    End Sub

    Private Sub sp_ErrorReceived(ByVal sender As Object, ByVal e As
System.IO.Ports.SerialErrorReceivedEventArgs) Handles sp.ErrorReceived
        sp.DiscardInBuffer()
    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles TextBox1.TextChanged

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

        Try
            With sp
                .PortName = "COM2"
                .BaudRate = 4800
                .Parity = IO.Ports.Parity.Odd
                .StopBits = IO.Ports.StopBits.One
                .ReceivedBytesThreshold = 1 
                .DiscardNull = False
                .Open()
            End With
        Catch ex As Exception
            _mensajes = "ERROR PUERTO"
        End Try

    End Sub
End Class

Nothing happens, I dont know if everything is ok, from the CPU I use this
conf:
 Baud Rate: 4800
 Port: COM1
 Parity: Odd
 Data Bits: 8
 Stop Bits: 1
 Software Flow Control: None
 Hardware Flow Control:  ¿? Dunno exacty what to put here...

Hope this info is complete and hope you can help me.

Thanks

davef
Just a couple of minor things, as I am no VB expert.

You seem to be wanting to use COM2 in the code, but try to conf. COM1
(typo)?

Hardware flow control: None (for RS232)

Fernando
Hi MexFer,
in your code you are writing to your textbox the quantity ("cantidad" in
spanish), of bytes that were available in the serial port.

declare datos_rx as a buffer of byte (not char) and give it a size (1024,
for example).

You should have no problem.

Did you debug to see if your serial port is opened or is throwing and
exception?

Fernando

ToonCoolMan
Attachment: Serialsample.zip (44.8 KB)
Hi everyone. I want to share some code from me.

This code is work 100% for WinCE6 and I atteched a project for everyone.

Public Class Form1

    Delegate Sub InvokeDelegate()

    Private Sub serialPort1_DataReceived(ByVal sender As System.Object,
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles
serialPort1.DataReceived
        ' Declare Thread Function
        textBox1.BeginInvoke(New InvokeDelegate(AddressOf updateTextbox))
    End Sub

    Private Sub updateTextbox()
        Dim tmp As String
        ' Get value from SerialPort
        tmp = serialPort1.ReadExisting
        ' Set text to TextBox
        textBox1.Text = textBox1.Text + tmp
    End Sub

MexFer
Hi thanks everyone for your answers.  =)

-------------------------------------------------------------------------
For "davef":

Yep I try changing to COM1 and still not working.
--------------------------------------------------------------------------

For "Fernando":

I made the change you suggest, the code remain the same just I change this:

Dim datos_rx() As Char

for this:

Dim datos_rx(1024) as Byte

Dunno exactly if I made right with you try to explain me:
"declare datos_rx as a buffer of byte (not char) and give it a size (1024,
for example)."

Im not very familiar with the VB language  =P

First I made some tests between two computers running a SerialData program
and it works once I learn about a little bit I try to use the FriendlyARM
board.
-------------------------------------------------------------------------

For "ToonCoolMan":

From the code you attach I get some errors... I copy the code from the
Form1.vb and paste it into a new project I manually add a serialport, a
timer and a textbox and I get some error messages before generate:
at cmdConnect.Click, cmdDisconnect.Click and cmdSend.Click
the error is the same in the three cases:
"Handles clause requires a WithEvents variable defined in the containing
type or one of its base types"

The three errors are marked as when you type something wrong in word xD
then I put the mouse on top and appears the error messege I type above.


From the code you type on the message I copy it and paste it into a new
project, add a serialport and a textbox, generate it and run it on my
platform board (Wince 6.0) and doesnt work either   =S
-------------------------------------------------------------------------


Thanks everyone for your comments and help, hope with your help I could get
more info about what Im doing wrong.

Thanks, nice day. ^^

MexFer
Update.

I get the message errors from the cmdConnect and so right =) 
kinda newbie stuff (wich is normal cause Im newbie in VB xD )

Goin to see if it works in the board.  =)

MexFer
Update2.

I use the program attached by "ToonCoolMan"
I was able to generate and run the exe between my computer and the board
and doesnt work, so I try the program with the serial cable bypassed RX
with TX with an UTP cable so the same data send will be recieved by my
board and it works but if I then connect the cable with the computer doesnt
work.
Im using a crossed serial cable,
Could it be something between the exe from my FriendlyARM board and the exe
Im using from the computer ??

Thanks, and have a nice day.

Fernando
Hi MexFer,

I didn't understand completely what's your situation right now... joining
the TX and RX terminals of the mini2440 you receive what you are sending,
or this happens in the PC and not in the mini board?

MexFer
Joinin TX and RX on the mini2440 works fine with the program Im using but
if I connect the mini with the pc the same program doesnt work ... =S

Fernando
Did you try to do the same, on the PC side? joining rx and tx...

MexFer
Yes, it works fine while I test em individualy but when I join them with
the serial cable it doesnt work, I think it could be the serial cable
itself but first I test it between 2 cpus and works fine.

Thanks.

Fernando
Yes, sure is the cable.
Check if pin 2 and 3 are crossed.

Fernando

MexFer
The cable is fine, TX is crossed with RX and viceversa... dunno what else
could be  =S

Fernando
Did you check voltage levels? Are you sure you are using in both TTL levels
or in both RS232 levels?

Are you sure both comms are configured exactly the same?

Besides this, I think that there are no more things that can be the
problem. 

Fernando

Mc_bimi
Hey David! 
I have the same problem as yours. Did you manage to solve it?
Does anyone know which is the problem?
Thanks in advance.
Mc_bimi

david
i could put it to work serial port using the C examples, i modified the
code to it could use the com1 instead of com0, put the cables on this port
and it works!.

i hope this can help you!!

tungnh
I need example code about serial port from vistual studio 2005 ( C# ) it
work for win ce 6.0 anyone help me ?

MexFer
Well first of all thanks for everything but the problem was the desktop cpu
I was using I switch to another to communicate with the friendlyarm and it
works, but something strange I notice is that it works using the serial
cable that comes with the board wich I tested and its not a crossed serial
cable so I dont know how could this be  =P.
Hope you can help me to understand that issue, besides that it works fine
=)
In the mean time Im going to try to communicate using the CON2 port wich
uses 3.3 TTL (I guess) with a Microchip PIC18F and the serial protocol,
hope I could handle it.

Thanks.

davef
MexFer

Are the connectors on the ends of the cable supplied with the kit both the
same?

MexFer
davef:

Yes, both are female.

davef
Well I'll be darn . . . I would have thought it was a cross-over cable as
well.

Mc_bimi
Hey David!! 
Thank you for your answer!! 
you only modified the comtest.c code and  you got it. That's nice!
I'll try!!(espero que funcione! jeje) lets see if I am capable! 
Mc_bimi (Spain)

david
ok Mc_bimi cualquier cosa me dices jajaja

D@niel T.
Fernando perdon que me meta en su conversación solo quiero ayudar un poco.

Aunque no trabajo con esta placa si he trabajado con otras placas
y he desarrollado muchos proyectos usando el puerto serie desde hace mas de
12 años 1ero usando VB6 y actualmente usando VB.Net y bien si reconosco que
la velocidad de VB.Net es menor que haciendo la aplciacion en VB6 pero no
tanto.

Tengo un proyecto embbedido en la MoBo Alix1C usando XPe con el framework
2.0 y usando dos puertos seriales al mismo tiempo el uso del procesador no
pasa del 20% y el sistema se siente bastante bien.

Ha donde quiero llegar con todo esto?
bueno pues que cuando recien empece con VB.Net hace unos...
mas bien desde VS2000 me di cuenta que usand el evento DataReceived la
captura serial era muy muy lenta, pero como asi lo venia haciendo con VB6
no me quedo otra que dejarlo asi, despues modifique mi codigo para que en
ves de usar el evento DataReceived(en VB6 OnComm) dice una clase que en un
Hilo estubiera todo el tiempo revisando si hay datos en el pueto serie, es
decir dejame ver si me explico mejor con un pedazo de codigo.

Private Sub LeeDatos()
    Dim strDatos As String = ""
    Do While 1
        Try
            If Not m_oPuerto.IsOpen Then Exit Do
            strDatos = m_oPuerto.ReadLine()
            RaiseEvent RecibeDatos(strDatos & m_oPuerto.NewLine, False)
        Catch ex1 As System.TimeoutException
            Try
                If m_oPuerto.BytesToRead > 0 Then
                    If m_intSendLenMax > 0 Then
                        If m_oPuerto.BytesToRead >= m_intSendLenMax Then
                            'El caracter de Nueva Linea no llega asi que se
envian los datos recabados en el buffer
                            strDatos = m_oPuerto.ReadExisting
                            RaiseEvent RecibeDatos(strDatos, True)
                        End If
                    End If
                End If
            End Try
        End Try
    Loop
End Sub

El metodo LeeDatos esta corriendo en un Hilo por separado y como uedes ver
es infinito hasta que se cierre el puerto.
en la linea strDatos = m_oPuerto.ReadLine() el sistema se espera hasta que
el carcter definido en la propiedad NewLine llege al puerto entonces
continua, e spro esta razon que tiene que ser ejecutado en un Thread si no
tu sistema se dentendria, bueno en caso de que tu caracter no llege en un
tiempo dado pr la propiedad ReadTimeout se genera un error la
System.TimeoutException y en tonces el codigo toma otra ruta haora se
pregunta si han llegado almenos X numero de bytes al buffer y en caso de
que asi sea los lee en caso contrario vuelve a esperar otro tiempo para que
llege el caracter de nueva linea, se que esto es medio complicado y
engorroso pero asi obtiene un rendimiento 5 veces o mas superior.

espero que no te confunda mas y disculpa mi ingnorancia en la ortografia y
en lo demas pero no soy letrado como dicen por aca.

Saludos 
D@niel T. 
Mexico D.F.

Fernando
Buen dia Daniel!
Muchs gracias por tus comentarios sobre como resolviste el tema del puerto
serie, y te cuento que yo tambien lo termine resolviendo de esa manera hace
varias semanas!! :)

Es bueno saber que la manera en que lo resolvi tambien fue una que le dio
resultados a otras personas. yo tambien vengo de trabajar durante muchos
años con VB6, y hace solo algunos meses me pase a VBNET. Como decis vos, la
lectura del puerto serie en los eventos generados era realmente muy lenta.
Mas cuando estaba recibiendo de 3 puertos series datos ininterrumpidamente.
A partir de haber creado el hilo de lectura del puerto serie el programa
corre muy pero muy bien.

Si bien ya lo tenia resueslto, agradezco mucho tu aporte, ya que esto es
muy importante en los foros. Estoy pensando en crear un grupo de facebook
por ejemplo para poder compartir este tipo de informacion, ya que veo que
hay muchos hispanos que participamos de los foros.

Muchas gracias de nuevo, saludos.
Fernando

david
Me gustaria ver ese grupo en el facebook!! jajaja y q se vea un poquito de
español por aca tambien jajaja

Fernando
Bueno acabo de crear el grupo, quien quiera unirse busqueme en facebook,
Fernando Blaha. Les mando luego la invitacion.
Saludos!!

Anurag Mishra
ToonCoolMan, thanks a lot for the code attached,.. it works.
You saved a lot of my time :) Thanks again.

Diego
Hola Fernando, yo soy de Argentina también, mas especificamente de San
Martin, Bs. As. 
Hace poco que adqurí mi placa, en realidad no es una mini sinó un TQ2440 de
Boradcon. Pero muchas cosas de las que utilizan aca me son útiles.
Espero que nos mantengamos en contacto. 
Saludos

Fernando
Hola Diego, te dejo mi mail: fb@blaha.com.ar
Yo estoy en Villa Urquiza, asi que estamos cerca.
La compraste para algo en particular la placa, o solo para "jugar"?
Saludos

Beyazit
Hi everyone...
I've a problem..I wrote a program about serial communication for s3c6410
series..I'm using ttl port..When I start the program com2,com3,com4 and
com5 is active and I'm connecting my device to com2 ttl port..But there is
no signal, no action..when I try the test program it says I/O
exception..please help me..

Beyazit
and also I wanna load the prolific serial to usb converter driver to my
embedde pc..I downloaded the driver from the prolific website..But I have
no idea how can I load it...

Fernando
I suggest you make a consult to domdom... he is the light out there for
many os uf :)

http://www.domodom.fr/spip/index.php
I know he was working with the 6410 and I think he said that he had some
issues with the serial ports...

Beyazit
thank you...

nvh
Attachment: Serialsample.zip (44.8 KB)
Hi all,

I have downloaded a sample about SerialCom of ThaiEasyElectronic. When i
run .exe file in my board, it get an error: "An error message cannot be
displayed because an optional resource assembly containing it cannot be
found"

Can you help me solve this issue, thanks.

mukesh prajapat
for tonncoolman
hello,you should use the different events  for different module such as
receive,send and connect,dissconnect
use same data binding given in the code ...

thanx

mukesh prajapat
And if u require complete software with source code then you may be contact
at prajapat89@gmail.com