Как передать данные через 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
http://lipipharm.com/# USA-based pharmacy Lipitor delivery
LipiPharm lipitor controlled substance LipiPharm
SemagluPharm Semaglu Pharm Semaglu Pharm
rate canadian pharmacies: Canada Pharm Global — canadian pharmacy ratings
https://canadapharmglobal.shop/# canadian pharmacy meds reviews
http://indiapharmglobal.com/# India Pharm Global
canadian pharmacy no scripts Canada Pharm Global canadian 24 hour pharmacy
http://canadapharmglobal.com/# trusted canadian pharmacy
https://medsfrommexico.com/# mexican mail order pharmacies
https://indiapharmglobal.shop/# India Pharm Global
India Pharm Global India Pharm Global India Pharm Global
http://canadapharmglobal.com/# canadian pharmacy uk delivery
canadian pharmacy review: canadian pharmacies online — legitimate canadian mail order pharmacy
https://canadapharmglobal.shop/# canadian pharmacy tampa
augmentin bustine costo: EFarmaciaIt — EFarmaciaIt
https://papafarma.shop/# diu mirena precio barcelona
Rask Apotek: Rask Apotek — tannkrem apotek
http://raskapotek.com/# Rask Apotek
blodtrycksmedicin gravid: Svenska Pharma — Svenska Pharma
https://papafarma.com/# Papa Farma
Г¶ka testosteron apotek: Svenska Pharma — blodtrycksmГ¤tning apotek
https://papafarma.shop/# Papa Farma
http://efarmaciait.com/# farmaci online miglior prezzo
rГ¶d i ansiktet hГ¶gt blodtryck Svenska Pharma hГ¶rapparat prisjakt
the pharmacy malaga: Papa Farma — wegovy donde comprar
https://svenskapharma.com/# Svenska Pharma
EFarmaciaIt EFarmaciaIt EFarmaciaIt
que es una drogueria en espaГ±a: fatmacia — Papa Farma
http://raskapotek.com/# Rask Apotek
venta farmacias diu mirena y dolor de piernas Papa Farma
prospecto de movicol: Papa Farma — farmacia a domicilio sevilla
https://efarmaciait.com/# EFarmaciaIt
Svenska Pharma eye primer bäst i test apotek spruta
veterinario cadiz 33: Papa Farma — antibiotica spanje
Rask Apotek: hurtigtest hiv apotek — elektrolytter tabletter apotek
Papa Farma: innova fisio — Papa Farma
https://efarmaciait.shop/# EFarmaciaIt
EFarmaciaIt: vsl3 bustine a cosa serve — EFarmaciaIt
https://raskapotek.com/# Rask Apotek
opiniones farmacia direct: Papa Farma — Papa Farma
Papa Farma: Papa Farma — Papa Farma
Svenska Pharma Svenska Pharma beställ medicin på nätet
https://efarmaciait.shop/# diflucan 200 serve ricetta
med rx pharmacy PharmaConnectUSA Pharma Connect USA
MedicijnPunt: Medicijn Punt — pharma online
https://pharmaconnectusa.shop/# prescription discount
Pharma Jetzt: medikamente preisvergleich testsieger — PharmaJetzt
MedicijnPunt: Medicijn Punt — medicijnen online
PharmaConnectUSA: Forzest — PharmaConnectUSA
https://pharmajetzt.com/# PharmaJetzt
welche online apotheke ist am gГјnstigsten: online apothke — onlineapothele
apotheken internet: apo med — PharmaJetzt
http://medicijnpunt.com/# landelijke apotheek
Pharma Confiance acheter cialis original en ligne sans ordonnance french pharmacy online
https://pharmajetzt.shop/# PharmaJetzt
pilulier de poche: new pharma avis — cialis sans ordonnance pharmacie france
http://pharmajetzt.com/# Pharma Jetzt
Pharma Confiance: filorga logo — achat de god
viagra en pharmacie francaise: parapharmacie la moins chГЁre paris — Pharma Confiance
https://pharmajetzt.shop/# bad steben apotheke
https://medicijnpunt.com/# MedicijnPunt
Pharma Confiance dose amoxicilline par kg bГ©bГ© Pharma Confiance
achat viagra espagne pharmacie: livraison medicament avec ordonnance — Pharma Confiance
http://pharmaconfiance.com/# Pharma Confiance
Pharma Confiance: Pharma Confiance — cialis et doliprane
http://pharmaconfiance.com/# ketoconazole gel sachet
dГ©ambulateur avantages et inconvГ©nients: quelle pharmacie.fr — test verre d’eau candidose
online apotheke shop Pharma Jetzt welche online apotheke ist die gГјnstigste
https://pharmaconnectusa.com/# estrace online pharmacy
https://pharmaconfiance.com/# saxenda pharmacie
shopapotjeke: PharmaJetzt — apotal.de versandapotheke
pzn suche: apotheke internet versandkostenfrei — online apotheke germany
souhaiter une bonne fin de grossesse: Pharma Confiance — prix god
diurГ©tique pour chien sans ordonnance Pharma Confiance ketoprofene 200 posologie
united pharmacy naltrexone: drug store — how much does viagra cost at a pharmacy
https://pharmaconnectusa.shop/# Pharma Connect USA
Pharma Connect USA: pharmacy online 365 review — PharmaConnectUSA
http://pharmaconfiance.com/# monuril vente libre
Pharma Jetzt: internet apotheke deutschland — medikamente per click
Medicijn Punt: apotheek recept — medicijnen kopen online
alpesh pharmacy store charlotte nc PharmaConnectUSA PharmaConnectUSA
http://pharmaconnectusa.com/# viagra dubai pharmacy
online pharmacy not requiring prescription: PharmaConnectUSA — Pharma Connect USA
MedicijnPunt: Medicijn Punt — apotheke
http://pharmajetzt.com/# apotheke online kaufen
Pharma Connect USA: Pharma Connect USA — viagra at guardian pharmacy
sildГ©nafil 50 mg prix en pharmacie en france: Pharma Confiance — Pharma Confiance
http://medicijnpunt.com/# nieuwe pharma
online-apotheke versandkostenfrei ab 10 euro: PharmaJetzt — PharmaJetzt
Medicijn Punt: apteka online holandia — Medicijn Punt
MedicijnPunt: Medicijn Punt — Medicijn Punt
Pharma Confiance: Pharma Confiance — Pharma Confiance
http://medicijnpunt.com/# MedicijnPunt
mijn apotheek: MedicijnPunt — online apotheek goedkoper
Pharma Confiance: pharmacie d’argouges — meilleur livre homГ©opathie
http://pharmajetzt.com/# Pharma Jetzt