Как передать данные через 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
buy facebook ads account online account store accounts market
buy fb account account buying platform online account store
RelaxMeds USA Tizanidine tablets shipped to USA cheap muscle relaxer online USA
microdosing semaglutide for inflammation: rybelsus weight loss cost — how to combat semaglutide fatigue
AsthmaFree Pharmacy: ventolin usa — AsthmaFree Pharmacy
AsthmaFree Pharmacy: open rybelsus bottle — taking rybelsus
AsthmaFree Pharmacy: price of ventolin — AsthmaFree Pharmacy
semaglutide one month results: 50 units of semaglutide — best time of day to inject semaglutide
Slot gacor Beta138: Beta138 — Beta138
Live casino Indonesia: Login Beta138 — Link alternatif Beta138
Judi online deposit pulsa: Judi online deposit pulsa — Slot jackpot terbesar Indonesia
GK88: Rut ti?n nhanh GK88 — Rut ti?n nhanh GK88
https://1winphili.company/# Online gambling platform Jollibet
Swerte99 slots: Swerte99 casino — Swerte99 casino
Link alternatif Beta138: Situs judi resmi berlisensi — Withdraw cepat Beta138
Swerte99 bonus: Swerte99 slots — Swerte99 app
Swerte99 bonus: Swerte99 login — Swerte99 casino
https://1winphili.company/# Online gambling platform Jollibet
Ca cu?c tr?c tuy?n GK88: Khuy?n mai GK88 — Slot game d?i thu?ng
Slot gacor Beta138: Bandar bola resmi — Slot gacor Beta138
Online casino Jollibet Philippines: jollibet login — jollibet
1winphili: Online betting Philippines — Online betting Philippines
indian pharmacies safe: india pharmacy mail order — indianpharmacy com
Mexican Pharmacy Hub: Mexican Pharmacy Hub — buy cheap meds from a mexican pharmacy
https://medidirectusa.shop/# MediDirect USA
top online pharmacy india: Indian Meds One — Indian Meds One
https://indianmedsone.com/# indianpharmacy com
MediDirect USA: MediDirect USA — allmed rx specialty pharmacy
Indian Meds One: india pharmacy mail order — Indian Meds One
india pharmacy mail order: best india pharmacy — Indian Meds One
indian pharmacy paypal: Indian Meds One — Indian Meds One
Mexican Pharmacy Hub: safe place to buy semaglutide online mexico — Mexican Pharmacy Hub
Indian Meds One: online shopping pharmacy india — Online medicine order
Mexican Pharmacy Hub: Mexican Pharmacy Hub — Mexican Pharmacy Hub
http://medidirectusa.com/# MediDirect USA
cheap viagra pharmacy: 15 rx pharmacy — nabp pharmacy viagra
Mexican Pharmacy Hub: Mexican Pharmacy Hub — Mexican Pharmacy Hub
https://mexicanpharmacyhub.com/# mexico drug stores pharmacies
MediDirect USA: ventolin uk pharmacy — MediDirect USA
Indian Meds One: Indian Meds One — pharmacy website india
cost less pharmacy: oxycontin online pharmacy — MediDirect USA
Mexican Pharmacy Hub: accutane mexico buy online — Mexican Pharmacy Hub
Заказала эксклюзивную композицию — выполнили безупречно!
букет невесты томск
Ваш букет стал главным украшением нашего вечера — восхитительные сочетания!
букет цветов томск
SildenaPeak: SildenaPeak — SildenaPeak
http://kamameds.com/# KamaMeds
sildenafil 100mg tablets canada: viagra tablet — viagra price australia
Kamagra oral jelly USA availability: Fast-acting ED solution with discreet packaging — Safe access to generic ED medication
recreational cialis: best place to get cialis without pesricption — Tadalify
maximpeptide tadalafil review: maximum dose of tadalafil — what does cialis look like
денежные выплаты военным
cialis tablets: canadian pharmacy cialis — Tadalify
Tadalify: cialis pricing — what are the side effects of cialis
SildenaPeak: soft tabs viagra — generic viagra canada pharmacy
how much is sildenafil: viagra discount canada — SildenaPeak
australia viagra over the counter: best sildenafil brand — generic sildenafil 20mg cost
Kamagra reviews from US customers: Kamagra oral jelly USA availability — Compare Kamagra with branded alternatives
SildenaPeak: buy sildenafil 20 mg online — order generic viagra from canada
cialis advertisement: max dosage of cialis — Tadalify
Tadalify: Tadalify — cialis generic best price
Kamagra oral jelly USA availability: Kamagra reviews from US customers — Fast-acting ED solution with discreet packaging
SildenaPeak: SildenaPeak — female viagra
Tadalify: tadalafil lowest price — best price on generic cialis
ED treatment without doctor visits: Men’s sexual health solutions online — Fast-acting ED solution with discreet packaging
ED treatment without doctor visits: Non-prescription ED tablets discreetly shipped — Online sources for Kamagra in the United States
viagra 30 mg: can i buy viagra from canada — SildenaPeak
buy cialis on line: Tadalify — Tadalify
Safe access to generic ED medication: Online sources for Kamagra in the United States — Fast-acting ED solution with discreet packaging
Курьер — само очарование: вежливый, аккуратный, с прекрасным настроением.
заказать цветы с доставкой в томске
SildenaPeak: generic viagra 100mg cost — SildenaPeak
Tadalify: Tadalify — Tadalify
Safe access to generic ED medication: Non-prescription ED tablets discreetly shipped — Fast-acting ED solution with discreet packaging
best reviewed tadalafil site: canadian pharmacy tadalafil 20mg — Tadalify
viagra 4 tablet: sildenafil prescription nz — purchasing viagra
prednisone tablets: SteroidCare Pharmacy — prednisone 5 mg tablet cost
discovery collection
ivermectin for swine: IverGrove — IverGrove
IverGrove: ivermectin hookworm — IverGrove
Цветы пришли в другой город свежими — вы мастера!
розы купить в томске
Сестра визжала от восторга — лучший сюрприз!
доставка цветов томск
IverGrove: ivermectin for cats dosage in ml — ivermectin canada buy
ivermectin bottle: IverGrove — tab ivermectin 12 mg
prednisone 20 mg pill: prednisone tablets india — SteroidCare Pharmacy
prednisone buy cheap prednisone canada buy prednisone no prescription
furosemide 100 mg: CardioMeds Express — lasix 40mg
Роскошные каллы! Элегантные и стильные!
доставка цветов томск
Изумительные розы! Бутоны упругие, лепестки свежайшие!
букет невесты томск
FertiCare Online: where can i buy generic clomid now — FertiCare Online
clomid pill clomid order FertiCare Online
https://cardiomedsexpress.com/# CardioMeds Express
acquistare farmaci senza ricetta: Farmaci Diretti — farmaci senza ricetta elenco
viagra generico in farmacia costo: Potenza Facile — kamagra senza ricetta in farmacia
comprare farmaci online con ricetta medicinali senza prescrizione medica Farmacie online sicure
https://farmacidiretti.com/# farmacia online piГ№ conveniente
acquistare farmaci senza ricetta: farmacia online cialis Italia — top farmacia online
viagra ordine telefonico: PotenzaFacile — esiste il viagra generico in farmacia
farmacia online senza ricetta: Pillole Subito — migliori farmacie online 2024
migliori farmacie online 2024 consegna rapida in tutta Italia acquisto farmaci con ricetta
Farmacie online sicure: Pillole Subito — farmacia online
farmacie online autorizzate elenco: consegna rapida in tutta Italia — migliori farmacie online 2024
farmacie online affidabili farmaci senza ricetta online acquisto farmaci con ricetta
Любовь без слов — ваши цветы!
букеты томск
Очаровательные нарциссы! Весеннее настроение в вазе!
розы томск
Прекрасные эустомы!Нежные и изящные
гипсофилы цена букета
acquisto farmaci con ricetta: kamagra oral jelly spedizione discreta — comprare farmaci online all’estero
Ваши розы сорта «эквадор» — действительно королевского размера!
купить 101 розу
farmacie online affidabili consegna rapida in tutta Italia Farmacie on line spedizione gratuita
Farmacie on line spedizione gratuita: sildenafil generico senza ricetta — acquistare farmaci senza ricetta
https://potenzafacile.com/# kamagra senza ricetta in farmacia
migliori farmacie online 2024: ForzaIntima — top farmacia online
BharatMeds Direct: online pharmacy india — indian pharmacy online
pharmacy website india: BharatMeds Direct — BharatMeds Direct
india online pharmacy: indian pharmacy online — Online medicine home delivery
https://maplemedsdirect.shop/# MapleMeds Direct
BorderMeds Express: BorderMeds Express — mexican pharmacy for americans
india pharmacy mail order online pharmacy india pharmacy website india
clomid online pharmacy uk: MapleMeds Direct — MapleMeds Direct
MapleMeds Direct: pharmacy store layout design — tamiflu pharmacy
MapleMeds Direct: metronidazole singapore pharmacy — MapleMeds Direct
«Зимняя сказка» среди лета — освежили!
купить цветы в томске
BorderMeds Express: real mexican pharmacy USA shipping — trusted mexico pharmacy with US shipping
reputable indian online pharmacy: BharatMeds Direct — BharatMeds Direct
MapleMeds Direct: oxymorphone online pharmacy — MapleMeds Direct
BorderMeds Express modafinil mexico online amoxicillin mexico online pharmacy
https://bharatmedsdirect.shop/# Online medicine home delivery
mexico pharmacy: BorderMeds Express — buy neurontin in mexico
BorderMeds Express: BorderMeds Express — BorderMeds Express
mexican mail order pharmacies: BorderMeds Express — BorderMeds Express
safe place to buy semaglutide online mexico BorderMeds Express BorderMeds Express