Copyright 2016 - Ingenius Worlds All Rigth Reserved
Wednesday, 16 September 2015 01:45

COMUNICACIÓN RS232 CON C# Featured

Written by 
Rate this item
(0 votes)
Csharp Csharp

COMUNICACIÓN RS232 CON CSHARP

Para comenzar con un grupo de manuales con respecto a la parte de Software, con el fin de realizar una colaboración a la comunidad del Internet nosotros IW, tras algo de experiencia obtenida en desarrollos tanto de Firmware y de Software nos atrevemos a realizar nuestro manual, esperando que sea de utilidad para las personas que deciden trabajar en esta área, o están cursando por cursos universitarios, como se explica no aplica para personas expertas pero en un buen momento estos sacarán a muchas personas de algunos apuros, así que comencemos.

Plataforma

La plataforma que utilizaremos en este apartado será C# (Csharp), para esto podemos utilizar la versión libre Express, ya que no requiere de muchos recursos es ligera, suficiente para la práctica que realizaremos, para esto podemos ingresar a la página de Microsoft para realizar la descarga, se puede hacer uso de la última Versión que esté disponible, en nuestro caso lo realizaremos con la versión 2010. (https://www.visualstudio.com/downloads/download-visual-studio-vs)

Iniciando

Para iniciar abramos la aplicación descargada, claro que previamente teníamos que haberla instalado en este caso no tiene ninguna configuración especial así que no explicaremos esa parte.

Bueno crearemos nuestro proyecto, vamos a File - New Project, como se muestra en la figura:

Luego nos muestra la pantalla para configuración de nuestro proyecto, en la cual seleccionamos Windows Forms Application, y en la parte infrerior colocamos un nombre a nuestro proyecto, en este caso le pondremos RS232CSharp, seguido de esto ponemos Ok.

Como observamos se nos abrió nuestra aplicación, con un formulario vacio con el nombre Form1, en la parte derecha observamos el cuadro de propiedades, y el explorador de proyectos, y en la parte izquierda tenemos el Cuadro de Herramientas.

 

Ahora si en este momento nos dedicaremos a la parte de la transmisión Serial, comencemos con una breve introducción.

Comunicación RS232 Serial

Como introducción podríamos decir que uno de los modos de comunicación más utilizados en la parte de dispositivos, industrias, Microcontroladores, Plc, es la comunicación RS232, o algunas de sus derivaciones.

En esta caso la comunicación RS232 nace luego de ver que la comunicación utilizando el puerto Paralelo DB25, requería de muchos cables, aunque no dejaba de ser esta última mucho mas rápida, entonces la comunicación RS232 propone una transmisión por 3 cables los cuales son Transmisor, Receptor y Gnd.

 

En el transcurso de los tiempos ha evolucionado obteniendo nuevos tipos de transmisión como son: RS422, RS485, en los cuales existen variaciones en los límites de voltaje que utilizan para la transmisión, y de estas anteriores se generan modos de transmisión como Profibus para Plcs, es decir evolucionan utilizando el mismo principio del RS232, y la transmisión por Usb de igual manera.

La transmisión RS232 envia datos en 8 bits aunque existen variaciones de 9 o 10, en este caso la estándar necesita los siguientes parámetros que se configuran por software.

Nombre de Puerto: COM (Las siglas usadas para este modo de transmisión)

Baudios: Representa la velocidad de Comunicación (En los métodos de comunicación que tenemos para el RS232 existe transmisión Síncrona y Asíncrona la transmisión que utilizaremos es la Asíncrona para lo cual se utiliza la velocidad de emisor y receptor para que lleguen a comprenderse).

Paridad: None (Generalmente utilizada)

Bit Data= 8 bits.

Estos son los parámetros necesarios para poder realizar una comunicación.

Configuración Csharp

Ahora retomamos nuestro proyecto, y vamos a la pestaña de Herramientas (Toolbox), y buscamos la pestaña Componentes (Components), y seleccionamos el componente SerialPort.

Figura 5

Al colocarlo vamos a la aplicación y vemos que nos apareció un componente con el nombre serialPort1, demos clic sobre este componente y vamos a la parte de sus propiedades, en la cual colocaremos los parámetros como el nombre de puerto, baudios, etc.

 

Para verificar que puertos son los que disponemos accesibles para nuestra comunicación serial vamos a Inicio - Mi Pc - Clic derecho - Propiedades, luego en esta pantalla seleccionamos Device Manager, y en la pestaña Ports, visualizamos los puertos que tenemos.

 

En este caso podemos colocar cualquiera dentro de nuestra aplicación, ahora lo que realizaremos es configurar nuestro proyecto para que envíe Información por el puerto Serial, para comenzar realizaremos un Hola Mundo.

Demos doble click sobre el formulario Form1 en la parte central y aparecera nuestro programa o código.

 

Como vemos en la figura tenemos el método Form1_Load(), este método se inicializa el momento en que el formulario termina de cargarse, en este caso podríamos hacer uso para realizar configuraciones iniciales de nuestro programa, o en otros casos podemos utilizar el constructor Form1(), que también arranca apenas se invoca la clase.

En este momento colocaremos dentro de nuestro Form1_Load, el código para abrir el puerto serial apenas se abra la aplicación, nos queda la aplicación de esta manera:

 

Como vemos tenemos la apertura del puerto dentro de un Try - Catch, este nos sirve en el caso de que la aplicación o la apertura del puerto serial contenga algún error grave no cierre la aplicación sino que muestre el mensaje que se encuentra dentro del catch, aunque se tienen diferentes opciones como Finally, pero excepciones revisaremos en otro apartado.

Ahora colocaremos un botón en nuestro formulario para enviar un dato por la línea serial.

A este botón configuremoslo sus propiedades:

Name: btn_send

Text: Enviar Dato

Damos doble clic sobre el botón para acceder a su evento click (Un evento se puede llamar a una señal que genera cualquier tipo de componente en reacción a algún tipo de interacción con el mismo), en este caso estaremos en el evento Double Click.

 

Ahora colocaremos la siguiente línea para enviar "HOLA MUNDO":

serialPort1.Write("HOLA MUNDO");

Como podemos observar es bastante sencillo para el envio de información serialmente, también poseemos envio de datos con Enter, y la manera en la que se cierra el puerto.

serialPort1.WriteLine("HOLA MUNDO");

serialPort1.Close();

Bueno en el siguiente apartado explicaremos la recepción de datos, y como manipularlos, espero les haya sido de utilidad.

Read 297758 times Last modified on Monday, 21 September 2015 19:10
Polivio

Ingeniero Sistemas

Tecnólogo en Automatización y Control Industrial

Website: www.ingeniusworlds.com

557674 comments

  • Comment Link Austin Saturday, 28 May 2016 23:50 posted by Austin

    Sorry, I'm busy at the moment http://www.vroomdigital.ie/order-nizagara-online.pdf concentrate order nizagara online pressed However, Pettitte damaged the federal prosecutors’ case when he testified during Clemens’ 2012 perjury and obstruction of Congress trial that it was “50-50” that he misunderstood his longtime teammate’s HGH comments.
    http://www.doorhan-vrata.cz/buy-flagyl-er-750mg-online.pdf rude malicious where can i buy flagyl over counter rainbow The Fat Man, the official name for the nuclear bomb that finally persuaded Japan to surrender, ending the Second World War, killed an estimated 40,000 people in an instant, and many more died in the months that followed.
    http://www.akcepamatky.cz/buy-atorvastatin.pdf complication dad buy atorvastatin canada reduction along Alex Rodriguez had a chance to be the hero in the 11th, coming to bat with two out and the go-ahead run at third base. The embattled slugger, on the field hours after appealing a 211-game suspension related to the Biogenesis PED scandal, grounded out to third, finishing 1-for-5 with a walk, He went 3-for-11 with two walks and a hit-by-pitch in his first series back from offseason hip surgery as the Yankees fell to 0-3 since his return.
    http://mindstormme.com/silvitra-cheap-price.pdf joyful purchase silvitra hurts "People spit at me in the street," Griffith told The Associated Press in 1993, recalling the days after Paret's death. "We stayed in a hotel. Every time there was a knock on the door, I would run into the next room. I was so scared."

  • Comment Link Randy Saturday, 28 May 2016 23:50 posted by Randy

    Cool site goodluck :) http://heartiq.com/zyban-generic-wellbutrin.pdf spring irritating weight loss on wellbutrin sr 300 mg till Kali has undergone intensive therapy and takes special medication flown in from Germany, but doctors said it was the speed with which her mother, Traci Hardig, brought her to the hospital that made all the difference.
    http://www.bkmech.com.vn/cheapest-place-to-buy-lexapro.pdf fashion draft is generic lexapro cheaper consequences Preparation with an honest friend will certainly help you highlight any weaknesses in your body language. Dropping into your university careers centre may also be a good idea, as many universities will offer mock interviews and C.V advice.
    http://www.capoeiracdoperth.com.au/order-propranolol-no-prescription.pdf five order propranolol no prescription producing writer The military and interim government, in turn, have rejected releasing Morsi or other detained Brotherhood leaders, a step the Europeans have called for and that Islamists have said could improve the atmosphere. Instead, they appear determined to prosecute detained Brotherhood members for crimes purportedly committed during Morsi's presidency and for violence after his fall.
    http://spahikari.pl/buying-valtrex-canada.pdf spurt beasts valtrex buy online canada abide Baby milk formula has become a hugely sensitive product in China after at least six children died, and 300,000 others were sickened, by formula laced with the industrial chemical melamine in 2008. The company at the heart of that scandal, Sanlu, was 43pc owned by Fonterra.

  • Comment Link Dallas Saturday, 28 May 2016 23:50 posted by Dallas

    We were at school together http://mantlebrewery.com/buy-venlafaxine-er.pdf ave buy venlafaxine xr rifle horace Unfortunately NY and Co don't ship to the UK so if you want to recreate Eva's ensemble you'll need to look to the British high street for similar styles. Never fear, we have taken the leg work out of it and have assembled our top floral picks below. Phase Eight have an incredibly similar style, as does Ted Baker but head to Oasis and Asos for a bargain.
    http://www.sorsovolunteer.org/buy-generic-valtrex-online.pdf hay fashioned valtrex online respectful bean The latest spike in U.S. gasoline prices coincides with anearly 9 percent rise in U.S. crude oil costs over the past twoweeks. Gasoline prices could jump an additional 15 cents due tothe rise in oil costs, EIA head Adam Sieminski told Reutersafter testifying.
    http://www.windowstoreplastics.co.uk/zoloft-reviews-uk.pdf objected buy zoloft uk thirsty Those were the days when the Cowboys were America’s Team. That nickname should be put in storage for now. But, hey, the Cowboys are still tied for first in the NFC East with a 2-3 record. Maybe it was a moral victory.
    http://www.doorhan-vrata.cz/buy-flagyl-er-750mg-online.pdf spacious reared cheap generic flagyl quarrel CULVER CITY, Calif. - They ripped him for his Oscar hosting performance, for his varied roles, for his poetry, the sexuality of his screen characters and his artistic paintings. They even knocked his grandmother.

  • Comment Link Phillip Saturday, 28 May 2016 23:50 posted by Phillip

    Directory enquiries http://www.iiabel.be/index.php/differin-gel-amazon-uk.pdf develop differin cream canada soot The baggage-handling side of the business makes bothsoftware to track luggage and mechanical equipment such asconveyor belts. It has installed more than 300 baggage-handlingsystems at airports all over the world.
    http://www.bkmech.com.vn/cheapest-place-to-buy-lexapro.pdf richard is generic lexapro cheaper ghosts Diplomats say the more than 16,000 peacekeepers are struggling with equipment problems, poor training of some contingents and the reluctance of some governments like Egypt to send their soldiers into dangerous areas.
    http://www.windowstoreplastics.co.uk/zoloft-reviews-uk.pdf surprisingly sertraline uk price define Finally, if a lack of parental investment won’t stop a would-be millionaire next door, it’s likely our nation’s ongoing student loan crisis will. The amount of debt per student with loans is $28,000 for graduates of the class of 2013 (Fidelity Investments claims $35,000 if you count credit card bills and loans from parents). Faced with a tab like this, at least some members of Generation Y have understandably concluded they can’t afford to take on much in the way of financial risk. A survey earlier this year by a group called Young Invincibles found 23 percent of those with private student loans claiming they would like to start their own entrepreneurial endeavor, but that the amount they need to pay back to less-than-flexible lenders is stopping them.
    http://www.macgowans.de/index.php/where-can-i-purchase-tretinoin-cream.pdf ant deadly purchase retin-a online
    abode Wesson's sons -- Adrian, Serafino and Dorian -- told ABC News correspondent Jay Schadler that only now, years after the crime, could they see their father for what he was: psychotic, delusional and narcissistic.

  • Comment Link Tyson Saturday, 28 May 2016 23:50 posted by Tyson

    What qualifications have you got? http://mantlebrewery.com/buy-venlafaxine-er.pdf lent effexor xr for generalized anxiety disorder bald agreed I also wonder about what the smartphone numbers really tell us for other reasons. 4G prices tend to be higher than DSL or cable broadband. In addition, unlike landline Internet, 4G plans almost universally come with data caps. Thus, I strongly suspect that if you were to look at the Internet have-nots you'd see the vast majority are the poor--the ones most in need of Internet access.
    http://www.morpho-b.com/buy-cheap-generic-zithromax.pdf adopt buy cheap generic zithromax mallet Asked about why the vaccine contained pork gelatine, Mr Davies said: "Fluenz is a live flu vaccine - the viruses need to be bound to something in order to make the vaccine work - the best thing to bind them to is a protein and the best protein to use is one that has been derived from gelatine.
    http://project-pop.com/purchase-paroxetine-online.pdf move airport buy paxil cr online announce dollars Celebrity Cruises announced Tuesday is was cancelling the remainder of a seven-night cruise to Alaska after mechanical issues forced a cruise ship carrying more than 3,100 passengers and crew members to return to port in Ketchikan.
    http://blog.staffnurse.com/buy-amoxicillin-cheap.pdf stern buy trimox online pausing required The court hearings and traffic police who whistle and wave police sticks to stop cars prove that there is relative law and order in the city. Although explosions can go off any moment at any place, you can still feel peace as you drive on the well-lit streets of Mogadishu as late as midnight.

  • Comment Link Clifton Saturday, 28 May 2016 23:50 posted by Clifton

    I can't get a dialling tone http://instadashapp.com/cheap-glucophage.pdf publcation purchase metformin 500 mg philadelphia On this week's Daily News Fifth Yankees Podcast, Mark Feinsand sits down with reliever Dave Robertson to chat about his recent shoulder injury, Mariano Rivera's impressive September workload, the Yankees' chances of reaching the postseason as well as last week's rookie hazing.
    http://www.capoeiracdoperth.com.au/order-propranolol-no-prescription.pdf jan order propranolol no prescription wishes lateral While Virgin Records laid its roots in Britain's burgeoningrock scene, it widened its portfolio to represent a variety ofartists spanning musical genres, such as R&B star Mariah Carey,pop band Spice Girls and French electro-dance duo Daft Punk.
    http://www.bridgeviewhouse.com/neurontin-100-milligrams.pdf heron buy gabapentin online usa blob Normally at a wedding, all eyes are on the bride and that's how it should be. But we have to say, at Denise Welch's nuptials we're way more distracted by Jill Halfpenny's gorgeous dress. The lucky girl has got her hands on a totally lust worthy frock from the Christopher Kane Pre-fall 2013 collection and you can too by clicking the link (right) to buy from Parisian concept store, Colette.
    http://blog.staffnurse.com/buy-amoxicillin-cheap.pdf mast silly where to buy amoxicillin for dogs spell sniff "I feel sorry for him sometimes. He's trying so hard to belike Chavez, but that's simply an impossible task. I canunderstand why he's doing it, but he can't spend his entiresix-year term like that," a senior government insider toldReuters.

  • Comment Link Randal Saturday, 28 May 2016 23:50 posted by Randal

    What do you want to do when you've finished? http://heartiq.com/is-propranolol-prescription-only.pdf considerable propranolol 60 mg for migraines glide village "They are putting up barriers that sound reasonable, thatsound like they care about women who are having abortions. Butin fact they are just trying to put up a wall of regulations andrequirements that are impossible to meet," Kromenaker said.
    http://project-pop.com/zithromax-where-can-i-buy.pdf parsley buy generic zithromax azithromycin root Even rising interest rates may not clip the wings of thestock rally. According to a recent S&P Dow Jones Indices report,"rising rates have clearly not been bad for stocks over the lasttwo decades. In three rising-rate periods since 1993, the S&P500 Index gained an average monthly return of 0.96 percent,compared with 0.82 percent during falling-rate periods."
    http://vonfluestudio.com/buy-orlistat-120mg-capsules.pdf organic proof order orlistat lighting heroism Gold was down 5.4 percent for the week, the worst sinceJune, after heavy selling linked to the expectations of a Fedrollback and an easing of tensions over Syria. Gold was quotedat $1,308.74 an ounce, down 0.9 percent, and has nowdeclined by about 21 percent this year after 12 consecutiveannual gains.
    http://spahikari.pl/buying-valtrex-canada.pdf jury console how to get off valtrex date happened The company changed hands a number of times until it wentpublic in 2001. Previous owners have included Imasco, a unit ofImperial Tobacco, and a consortium of private-equity firmsincluding KKR and Bain Capital.

  • Comment Link Roger Saturday, 28 May 2016 23:50 posted by Roger

    I came here to work http://www.iiabel.be/index.php/differin-gel-amazon-uk.pdf independent bitter differin gel coupon card contemporary curt Fifty-seven percent said the leaks about the surveillance program would not affect the ability of the United States to prevent terrorist attacks while 30 percent said the disclosures would weaken government efforts to prevent terrorism.
    http://frock.ie/cozaar-potassium-supplements.pdf done cozaar tablets beef discussing The drugmaker said on Thursday that updated data from aclinical study showed its experimental product, sapacitabine,has activity against a majority of ovarian cancer samples takenfrom patients, including resistant tumors. The drug is currentlybeing tested in late-stage studies as a as front-line treatmentfor acute myeloid leukemia in the elderly.
    http://www.howtowriteanything.com/propecia-uk-cheap.pdf forms digestion propecia uk cheap cuckoo Mercer County Superior Court judge Mary Jacobson ruled that the state must recognize gay marriages in order to guarantee equal protections to same-sex couples according to the New Jersey Constitution. Same-sex marriages can begin on Oct. 21.
    http://thewrightcareer.com/renova-purchase-online.pdf sheer balanced can you buy tretinoin cream over the counter
    nails 5. All images submitted must be the work of the individual submitting them and must not have been published elsewhere or have won a prize in any other photographic competition. It is the responsibility of each entrant to ensure that any images they submit have been taken with the permission of the subject and do not infringe the copyright of any third party or any laws. Entrants must warrant that the photograph they are submitting is their own work and that they own the copyright for it.

  • Comment Link Rolland Saturday, 28 May 2016 23:50 posted by Rolland

    When do you want me to start? http://exploringsolutionspast.org/buy-promethazine-syrup.pdf forbes phenergan buy online uk shilling A panel of independent advisors to the FDA will review Perjeta's risks and benefits on Thursday, September 12. The FDA, which takes the panel's recommendations into account, is expected to decide on the drug's approval by October 31.
    http://vonfluestudio.com/buy-orlistat-120mg-capsules.pdf wretched ski order orlistat bondage offended Brent crude headed towards $110 a barrel after strong datafrom China. Activity in China's services sector expanded at thefastest pace in six months in September as demand grew,cementing a modest pick-up in the world's second-largesteconomy.
    http://thewrightcareer.com/renova-purchase-online.pdf ocean buy obagi tretinoin cream online channel Among notable earnings reports Friday, NRG Energy is expected to report a second-quarter loss of seven cents a share on revenue of $3.23 billion, according to analysts surveyed by FactSet Research.
    http://www.doorhan-vrata.cz/buy-flagyl-er-750mg-online.pdf elastic buy metronidazole 500mg for humans instinct “I went out to The Rock, where we train new probies, recently,” says Ruane. “I asked which of them would like to swap me their probie spot for my 43-year pension. Not one hand went up. I knew then that the equipment had changed over the years, but the hearts of the men who do this wonderful job had not. I have no idea what I’ll do with my time when I leave, but I will be leaving this job in very good hands.”

  • Comment Link Mohammad Saturday, 28 May 2016 23:50 posted by Mohammad

    I'm in my first year at university http://www.naturcom.fi/glycomet-sr-500-mg-used.pdf planned christian glycomet sr tablets about After Cabrera hit a two-run homer in the first inning and a run-scoring single in the third, Yost chose to give Cabrera a free pass in the fifth inning with a runner on third and Fielder followed with an inning-ending groundout. Cabrera has eight homers in 13 games.
    http://heartiq.com/is-propranolol-prescription-only.pdf maintenance contract propranolol buying honeycomb examples The al Qaeda statement's authenticity could not be independently confirmed but it was posted on a website commonly used by militants and its style was consistent with earlier statements by the terror network.
    http://blog.staffnurse.com/buy-tretinoin-cream-005.pdf pear divide buy renova online canada fury It now sees net income of between 820 million euros and 850million euros ($1.11-$1.15 billion), compared with a previoustarget for 890-920 million, and an operating margin of around8.5 percent, down from near 9 percent.
    http://www.macgowans.de/index.php/where-can-i-purchase-tretinoin-cream.pdf firing hobble purchase retin-a online
    useful Rosa is recovering faster. "I'm very well… At first it was a bit painful, but little by little, I'm getting better. I hope that in the UK, people will get to know that the best surgeon in the world is in Barcelona."

Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.