Как передать данные через COM-порт в Java
Сегодня многие считают, что COM-порт уже умер, его не увидишь даже на материнских платах современных ПК, не говоря о ноутбуках. И для меня он тоже казался забытым, пока не взялся за программирование микроконтроллеров и, что интересно, почти у всех есть USART-порт и мне в голову пришла мысль подключить его (микроконтроллера) к ПК и передавать ему приветы.
Но, как оказалось, не так уж и просто сделать это из-за того, что ноутбук не имеет COM-порт, а Java знать не знала что это. Первую проблему решил быстро, купил конвертер COM-USB, установил драйвера и заработал. А что касается Java, вот тут стало интереснее. В интернете первое, что нашёл для работы с последовательным портом на Java, был RXTX.
Смотрите ещё:
Установка Rx Tx библиотек (Windows)
Установка JDK и Eclipse
И вот я сделал «Hello World». В данном примере я просто соединил Rx с Tx и отправленные данные приходят тоже мне :).
COM-порт — Пример программы на Java
package com.micro.pi.java.uart; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.TooManyListenersException; import gnu.io.CommPortIdentifier; import gnu.io.PortInUseException; import gnu.io.SerialPort; import gnu.io.SerialPortEvent; import gnu.io.SerialPortEventListener; import gnu.io.UnsupportedCommOperationException; public class JavaRxTx { private static SerialPort serialPort = null; public static void main(String[] args) { // получаем объект типа Enumeration, который содержит объекты типа // CommPortIdentifier для каждого порта в системе. Enumeration<?> portIdentifiers = CommPortIdentifier.getPortIdentifiers(); while (portIdentifiers.hasMoreElements()) { CommPortIdentifier commPortIdentifier = (CommPortIdentifier) portIdentifiers.nextElement(); // Проверяем, есть ли в этом списке последовательные порты if (commPortIdentifier.getPortType() == CommPortIdentifier.PORT_SERIAL) { System.out.println("Com port : " + commPortIdentifier.getName()); try { // Открываем порт serialPort = (SerialPort) commPortIdentifier.open(JavaRxTx.class.getName(), 2000); // Выставляем параметры serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_2, SerialPort.PARITY_NONE); // Выключаем аппаратное управление потоком serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE); // Включаем уведомления, когда входные данные доступны serialPort.notifyOnDataAvailable(true); // Включаем SerialPortEventListener serialPort.addEventListener(new SerialPortEventListener() { @Override public void serialEvent(SerialPortEvent event) { switch (event.getEventType()) { case SerialPortEvent.BI: case SerialPortEvent.OE: case SerialPortEvent.FE: case SerialPortEvent.PE: case SerialPortEvent.CD: case SerialPortEvent.CTS: case SerialPortEvent.DSR: case SerialPortEvent.RI: case SerialPortEvent.OUTPUT_BUFFER_EMPTY: break; case SerialPortEvent.DATA_AVAILABLE: InputStream inputStream; byte[] buffer; try { inputStream = serialPort.getInputStream(); buffer = new byte[1024]; int bytes = 0; while ((bytes = inputStream.read(buffer)) > 0) { System.out.print(new String(buffer, 0, bytes)); } } catch (IOException e) { e.printStackTrace(); } break; } } }); } catch (PortInUseException | UnsupportedCommOperationException | TooManyListenersException e) { e.printStackTrace(); } // Выходим из цикла потому, что мы использовали первый // попавшийся последовательный порт break; } } if (serialPort != null) { String message = "Hello world!!11"; try { // Передаём привет serialPort.getOutputStream().write(message.getBytes()); // Ждём немножко Thread.sleep(100); // Удаляем EventListener serialPort.removeEventListener(); // Закрываем порт serialPort.close(); } catch (Exception e) { e.printStackTrace(); } } else { System.out.println("Serial port object is null"); } } }
Результат
Stable Library ========================================= Native lib Version = RXTX-2.1-7 Java lib Version = RXTX-2.1-7 Com port : COM8 Hello world!!11
… [Trackback]
[…] Info to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Here you will find 61710 more Information to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Info to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Here you will find 61681 additional Information on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More Information here on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More Info here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More Information here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Here you will find 62299 more Information to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] There you will find 43674 additional Information to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Info on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More Information here on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More Information here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Information on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More here on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More Information here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Information on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More Information here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More on on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More Information here on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Information on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Info to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Info on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Here you can find 21441 more Info to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Info on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Find More Info here to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More on to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Information to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Read More on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Information on that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
… [Trackback]
[…] Information to that Topic: micro-pi.ru/com-порт-из-java-rxtxcomm-hello-world/ […]
маркетплейс аккаунтов перепродажа аккаунтов
маркетплейс аккаунтов соцсетей магазин аккаунтов социальных сетей
купить аккаунт с прокачкой гарантия при продаже аккаунтов
Social media account marketplace Buy Pre-made Account
Account Acquisition Account Selling Service
Profitable Account Sales Account market
Account Exchange Service Accounts market
Account Selling Platform https://buyaccounts001.com/
Secure Account Purchasing Platform Account exchange
account sale online account store
account purchase sell accounts
account market website for selling accounts
ready-made accounts for sale website for buying accounts
social media account marketplace buy accounts
account trading platform account selling platform
account acquisition account purchase
ready-made accounts for sale buy pre-made account
marketplace for ready-made accounts verified accounts for sale
account trading platform account buying service
account marketplace marketplace for ready-made accounts
social media account marketplace account market
account store sell accounts
sell account sell accounts
sell pre-made account buy and sell accounts
account store verified accounts for sale
account trading platform profitable account sales
social media account marketplace account store
marketplace for ready-made accounts buy-best-accounts.org
account trading service account market
profitable account sales https://social-accounts-marketplace.xyz
account selling platform https://buy-accounts-shop.pro/
website for selling accounts https://buy-accounts.live
database of accounts for sale https://social-accounts-marketplace.live
account market https://accounts-marketplace-best.pro/
маркетплейс аккаунтов akkaunty-na-prodazhu.pro
площадка для продажи аккаунтов akkaunt-magazin.online
маркетплейс аккаунтов магазины аккаунтов
продажа аккаунтов https://kupit-akkaunt.online
buy facebook accounts for advertising buy facebook accounts for ads
cheap facebook advertising account buy ad account facebook
facebook accounts to buy https://buy-ad-account.click
facebook account buy facebook accounts to buy
buy google ads accounts buy google ads accounts
buy verified google ads accounts https://buy-ads-invoice-account.top
google ads agency account buy buy-account-ads.work
buy google agency account https://buy-ads-agency-account.top
buy google ads account https://sell-ads-account.click
verified facebook business manager for sale https://buy-bm-account.org
buy facebook business manager accounts buy-business-manager-verified.org
buy facebook verified business manager https://verified-business-manager-for-sale.org/
buy tiktok ads account https://tiktok-ads-account-buy.org
tiktok ads agency account https://tiktok-ads-account-for-sale.org
buy tiktok ad account tiktok ads account buy
tiktok ads agency account https://buy-tiktok-business-account.org
RxFree Meds: RxFree Meds — viagra best online pharmacy
RxFree Meds: RxFree Meds — RxFree Meds
https://farmaciaasequible.com/# Farmacia Asequible
enclomiphene testosterone enclomiphene testosterone buy enclomiphene online
buy enclomiphene online: enclomiphene — enclomiphene testosterone
http://rxfreemeds.com/# generic viagra online pharmacy
enclomiphene citrate: enclomiphene testosterone — enclomiphene online
enclomiphene for sale: enclomiphene price — enclomiphene testosterone
buy medicines online in india: п»їlegitimate online pharmacies india — indian pharmacy online
IndoMeds USA: Online medicine order — world pharmacy india
https://medismartpharmacy.com/# online pharmacy coupons
indian pharmacy paypal: indian pharmacy online — IndoMeds USA
https://medismartpharmacy.shop/# Viagra capsules
MexiMeds Express: mexican online pharmacies prescription drugs — mexican rx online
IndoMeds USA cheapest online pharmacy india IndoMeds USA
mexican rx online: best online pharmacies in mexico — mexico drug stores pharmacies
MexiMeds Express: buying prescription drugs in mexico — buying prescription drugs in mexico
best online pharmacy ambien sildenafil citrate pharmacy lortab online pharmacy no prescription
https://indomedsusa.shop/# IndoMeds USA
Singulair: tylenol 3 pharmacy — wegmans pharmacy free lipitor
https://indomedsusa.shop/# IndoMeds USA
IndoMeds USA IndoMeds USA mail order pharmacy india
MexiMeds Express: MexiMeds Express — mexican drugstore online
MexiMeds Express mexican rx online mexican mail order pharmacies
zithromax pharmacy price: optum rx pharmacy — provigil pharmacy
buying prescription drugs in mexico online: mexican rx online — MexiMeds Express
pharmacy assistant certification online people’s pharmacy zyrtec mexican pharmacy weight loss
IndoMeds USA: online pharmacy india — IndoMeds USA
http://indomedsusa.com/# IndoMeds USA
pharmacies in canada that ship to the us: MediSmart Pharmacy — canadian pharmacy no scripts
can buy viagra pharmacy: online pharmacy propecia no prescription — online pharmacy viagra australia
low dose naltrexone online pharmacy: MediSmart Pharmacy — cymbalta pharmacy coupon
https://indomedsusa.com/# indian pharmacies safe
http://medismartpharmacy.com/# asacol online pharmacy
IndoMeds USA: IndoMeds USA — india pharmacy mail order
fincar pharmacy MediSmart Pharmacy pharmacy sell viagra
buy facebook ads account online account store accounts market
MexiMeds Express: best online pharmacies in mexico — buying from online mexican pharmacy
https://medismartpharmacy.com/# online pharmacy no prescription needed percocet
mexico pharmacies prescription drugs: reputable mexican pharmacies online — MexiMeds Express
MexiMeds Express MexiMeds Express best online pharmacies in mexico
russian pharmacy online cialis offshore pharmacy rx reliable pharmacy
world pharmacy india reputable indian pharmacies IndoMeds USA
http://medismartpharmacy.com/# levofloxacin pharmacy
buy fb account account buying platform online account store
https://indomedsusa.shop/# IndoMeds USA
Erythromycin MediSmart Pharmacy rx one pharmacy
https://indomedsusa.com/# IndoMeds USA
sterdex ordonnance PharmaDirecte pharmacie en ligne sans ordonnance viagra
https://clinicagaleno.com/# farmacia portugal online test covid
mascarillas protectoras farmacia online: Clinica Galeno — comprar paracetamol 1g sin receta
spotof sans ordonnance jouvence de l’abbГ© soury solution buvable achat cialis
https://clinicagaleno.shop/# se puede comprar levitra en farmacias sin receta
femannose en pharmacie sans ordonnance: PharmaDirecte — savon surgras cavailles
compra de farmacia online donde comprar alprazolam sin receta se puede comprar paidoterin sin receta
comprar venlafaxina sin receta: donde comprar viagra en bilbao sin receta — farmacia online alzira
nurofen farmacia online Clinica Galeno farmacia online sevilla
sro pharmacie sans ordonnance: doliprane enfant sans ordonnance — faut il une ordonnance pour du spasfon
https://ordinasalute.com/# tachifene 500 a cosa serve
https://ordinasalute.shop/# mascherine ffp2 bambini farmacia online
viagra homme achat en ligne: PharmaDirecte — pharmacie sans ordonnance fiable
mascarilla reutilizable farmacia online Clinica Galeno comprar diazepam sin receta en espaГ±a
https://tryggmed.shop/# tissekladd apotek
apotheek inloggen: medicijn online — belgische online apotheek
mobiltelefon rea: billig hudvГҐrd — Г¶ppet apotek
https://snabbapoteket.com/# apotek pcr test
http://snabbapoteket.com/# billigt serum
https://t.me/s/TopTg_arkada
apotek fГёflekk: TryggMed — flytende magnesium apotek
bestellen apotheek Medicijn Punt landelijke apotheek
http://zorgpakket.com/# europese apotheek
stГ¶dstrumpor apotek: Snabb Apoteket — kan Г¤gglossningstest visa fel
http://snabbapoteket.com/# skelning engelska
apotek ГҐpent 2 juledag: Trygg Med — apotek ГҐpen sГёndag
https://tryggmed.shop/# apotek. no
panthenol krem apotek: retinol krem apotek — aloe vera gel apotek
zink apotek SnabbApoteket african black soap apotek
https://snabbapoteket.com/# body hund apotek
billig choklad: Snabb Apoteket — tre bett pГҐ rad
apotek snorking: Trygg Med — rosemary oil apotek
rx pharmacy glendale: pharmacy online shopping — ExpressCareRx
https://indiamedshub.com/# top online pharmacy india
http://medimexicorx.com/# MediMexicoRx
fluoxetine online pharmacy viagra dubai pharmacy british pharmacy online
best india pharmacy: india pharmacy — best online pharmacy india
buy neurontin in mexico: cheap cialis mexico — MediMexicoRx
target pharmacy online refills online pharmacy ventolin online pharmacy ambien
MediMexicoRx: safe place to buy semaglutide online mexico — buy viagra from mexican pharmacy
https://indiamedshub.com/# online shopping pharmacy india
IndiaMedsHub: indian pharmacy paypal — india pharmacy mail order
modafinil mexico online: MediMexicoRx — legit mexico pharmacy shipping to USA
http://medimexicorx.com/# mexican mail order pharmacies
https://lexapro.pro/# where can i get lexapro brand medication
purchase generic Zoloft online discreetly buy Zoloft online buy Zoloft online without prescription USA
cheap Zoloft: buy Zoloft online — sertraline online
Propecia for hair loss online: buy cheap propecia for sale — generic Finasteride without prescription
https://lexapro.pro/# lexapro online
https://lexapro.pro/# Lexapro for depression online
purchase generic Accutane online discreetly: cheap Accutane — Isotretinoin From Canada
https://lexapro.pro/# generic for lexapro
cheap Accutane: cheap Accutane — isotretinoin online
generic Finasteride without prescription cheap Propecia Canada generic Finasteride without prescription
Isotretinoin From Canada USA-safe Accutane sourcing buy Accutane online
sertraline online: generic sertraline — Zoloft for sale
USA-safe Accutane sourcing: Isotretinoin From Canada — Isotretinoin From Canada
purchase generic Zoloft online discreetly cheap Zoloft Zoloft for sale
buy Zoloft online without prescription USA: buy Zoloft online without prescription USA — cheap Zoloft
Finasteride From Canada: Propecia for hair loss online — cost of propecia no prescription
generic Cialis from India Cialis without prescription generic Cialis from India
Isotretinoin From Canada cheap Accutane USA-safe Accutane sourcing
generic brand for lexapro: buy lexapro — Lexapro for depression online
https://lexapro.pro/# Lexapro for depression online
buy Cialis online cheap: buy Cialis online cheap — buy Cialis online cheap
sertraline online Zoloft Company buy Zoloft online
Tadalafil From India: cheap Cialis Canada — buy Cialis online cheap
https://zoloft.company/# buy Zoloft online
sertraline online: buy Zoloft online without prescription USA — Zoloft Company
generic sertraline: Zoloft Company — buy Zoloft online
http://isotretinoinfromcanada.com/# cheap Accutane
order corticosteroids without prescription ReliefMeds USA ReliefMeds USA
anti-inflammatory steroids online: Relief Meds USA — prednisone 300mg
http://clearmedsdirect.com/# order amoxicillin without prescription
anti-inflammatory steroids online: order corticosteroids without prescription — anti-inflammatory steroids online
https://wakemedsrx.com/# buy Modafinil online USA
amoxicillin 200 mg tablet order amoxicillin without prescription low-cost antibiotics delivered in USA
nootropic Modafinil shipped to USA: nootropic Modafinil shipped to USA — prescription-free Modafinil alternatives
wakefulness medication online no Rx: WakeMedsRX — nootropic Modafinil shipped to USA
https://clomidhubpharmacy.com/# Clomid Hub
safe Provigil online delivery service nootropic Modafinil shipped to USA affordable Modafinil for cognitive enhancement
prednisone 54899: order corticosteroids without prescription — prednisone 20mg
where to buy cheap clomid without rx: where can i get clomid prices — where buy generic clomid without a prescription
Clomid Hub: Clomid Hub — cheap clomid
https://clearmedsdirect.shop/# can you buy amoxicillin over the counter
nootropic Modafinil shipped to USA smart drugs online US pharmacy affordable Modafinil for cognitive enhancement
buy Modafinil online USA Modafinil for ADHD and narcolepsy Modafinil for ADHD and narcolepsy
amoxil generic: low-cost antibiotics delivered in USA — antibiotic treatment online no Rx
order Provigil without prescription prescription-free Modafinil alternatives safe Provigil online delivery service
CanadRx Nexus CanadRx Nexus canada pharmacy world
safe canadian pharmacies: onlinecanadianpharmacy — CanadRx Nexus
indian pharmacy paypal: IndiGenix Pharmacy — pharmacy website india
https://indigenixpharm.com/# IndiGenix Pharmacy
isotretinoin from mexico: safe mexican online pharmacy — buy propecia mexico
viagra pills from mexico: MexiCare Rx Hub — MexiCare Rx Hub
online pharmacy india: IndiGenix Pharmacy — IndiGenix Pharmacy
india online pharmacy: top 10 online pharmacy in india — IndiGenix Pharmacy
https://canadrxnexus.shop/# CanadRx Nexus
CanadRx Nexus: reputable canadian pharmacy — canadian drugstore online
CanadRx Nexus CanadRx Nexus CanadRx Nexus
IndiGenix Pharmacy: reputable indian pharmacies — indian pharmacy
buying drugs from canada: CanadRx Nexus — CanadRx Nexus
https://canadrxnexus.shop/# the canadian drugstore