Как передать данные через 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
Заказала эксклюзивную композицию — выполнили безупречно!
букет невесты томск
Ваш букет стал главным украшением нашего вечера — восхитительные сочетания!
букет цветов томск
Курьер — само очарование: вежливый, аккуратный, с прекрасным настроением.
заказать цветы с доставкой в томске
Цветы пришли в другой город свежими — вы мастера!
розы купить в томске
Сестра визжала от восторга — лучший сюрприз!
доставка цветов томск
Роскошные каллы! Элегантные и стильные!
доставка цветов томск
Изумительные розы! Бутоны упругие, лепестки свежайшие!
букет невесты томск
Любовь без слов — ваши цветы!
букеты томск
Очаровательные нарциссы! Весеннее настроение в вазе!
розы томск
Прекрасные эустомы!Нежные и изящные
гипсофилы цена букета
Ваши розы сорта «эквадор» — действительно королевского размера!
купить 101 розу
«Зимняя сказка» среди лета — освежили!
купить цветы в томске
I truly want to thank you for sharing such straightforward and practical information. Not everyone feels comfortable handling fixes, but posts like this make it more approachable. I paired this suggestions with some basic care tips I discovered just a short while ago, and it really boosted my confidence in managing minor household tasks on my own. Posts of this kind often give me the push I need to take on small but essential tasks I might otherwise delay. I find that sharing such experiences motivates others as well, making house care a more collective learning journey. I found this perspective quite interesting and it made me reflect on similar experiences I’ve had.
Розовые пионовидные розы — нежность и пышность, как у невесты!
купить букет роз томск
Прекрасные бархатцы! Теплые осенние краски!
букет пионов
Быстрая доставка! Курьер очень вежливый!
заказ цветов томск
Восхитительные хризантемы! Экзотично и красиво!
купить пионы томск
Великолепные композиции с фруктами! Сочные краски!
букет из хризантем
Идеальный букет для мамы! Слезы радости!
купить розы в томске
Восхитительные ранункулюсы! Нежные и пушистые!
букет цветов томск
Восхитительные целозии! Бархатные и необычные!
розы купить в томске
Спасибо за мгновенную обработку заказа! Я только закрыла страницу оплаты, а мне уже позвонили для подтверждения. Это скорость!
купить 101 розу в томске
Заказывала розы с доставкой в офис. Курьер был очень деликатен и не привлек лишнего внимания, что было важно для сюрприза.
купить розы Томск
Великолепные подсолнухи!Солнце в вазе!
свадебный букет
Ваши посты с историями о розах вдохновили на подарок бабушке — она обожает цветы с смыслом!
доставка цветов в томске
Фото на сайте просто не передают всей красоты! Букет вживую оказался даже больше и роскошнее. Аромат стоял на всю квартиру. Обязательно закажу снова.
пионовидные розы Томск
Восхитительные клематисы!Пышные и красивые!
доставка цветов томск
Ваши фото процессов сборки вдохновляют на заказ! Выбрала такие же розы на День влюбленных — получилось даже лучше, чем на картинке!
розы купить в томске
Невероятно красивые пионы!Пышные и нежные!
доставка цветов томск
Быстрая доставка по всему Томску!Очень доволен!
заказать цветы томск
Великолепные ирисы!Элегантные и изысканные!
цветы
Спасибо за пост про розы для учителя! Заказала на 1 сентября — классный руководитель был тронут!
заказать цветы с доставкой в томске
Спасибо за новогодние идеи в соцсетях! Букет с золотыми шарами стал главным украшением праздничного стола!
доставка цветов в томске
Спасибо за лёгкий и приятный процесс выбора. Фотографии точные, описания подробные. Не возникает чувства uncertainty.
розы томск
Роскошные букеты с фруктами!Оригинально!
цветы томск
Невероятно красивые букеты для фотосессии!Ярко!
доставка цветов в томске
Ваши видео с отзывами клиентов такие живые! Заказала розы на Новый год — все соответствовало описанию!
букет невесты
zithromax prescription in canada: buy zithromax online — cheap zithromax
https://everlastrx.shop/# how to order Cialis online legally
Швабра для мытья полов с системой распыления моющего средства показала отличный результат!
химчистка ковров
gabapentin capsules for nerve pain: order gabapentin discreetly — NeuroCare Direct
trusted Stromectol source online Stromectol ivermectin tablets for humans USA Stromectol ivermectin tablets for humans USA
online pharmacy Prednisone fast delivery: how to get Prednisone legally online — online pharmacy Prednisone fast delivery
https://predniwellonline.com/# online pharmacy Prednisone fast delivery
Prednisone tablets online USA: Prednisone without prescription USA — Prednisone tablets online USA
gabapentin and menopause: Neurontin online without prescription USA — fluoxetine online
generic ivermectin online pharmacy low-cost ivermectin for Americans trusted Stromectol source online
Neurontin online without prescription USA: generic gabapentin pharmacy USA — neuropathic pain relief treatment online
gabapentin capsules for nerve pain: generic gabapentin pharmacy USA — affordable Neurontin medication USA
online pharmacy Prednisone fast delivery how to get Prednisone legally online how to get Prednisone legally online
https://medivermonline.com/# Stromectol ivermectin tablets for humans USA
FDA-approved gabapentin alternative: gabapentin capsules for nerve pain — generic gabapentin pharmacy USA
order gabapentin discreetly: neuropathic pain relief treatment online — Neurontin online without prescription USA
how to order Cialis online legally: discreet delivery for ED medication — EverLastRx
online pharmacy Prednisone fast delivery prednisone without a prescription PredniWell Online
https://everlastrx.com/# generic tadalafil from canada
http://predniwellonline.com/# how to get Prednisone legally online
low-cost ivermectin for Americans: Stromectol ivermectin tablets for humans USA — generic ivermectin online pharmacy
online pharmacy Prednisone fast delivery Prednisone without prescription USA online pharmacy Prednisone fast delivery
Prednisone tablets online USA how to get Prednisone legally online how to get Prednisone legally online
FDA-approved gabapentin alternative: gabapentin capsules for nerve pain — gabapentin capsules for nerve pain
https://medivermonline.com/# generic ivermectin online pharmacy
trusted Stromectol source online
generic ivermectin online pharmacy: Stromectol ivermectin tablets for humans USA — Stromectol ivermectin tablets for humans USA
discreet delivery for ED medication how to order Cialis online legally Tadalafil tablets
https://medivermonline.com/# Mediverm Online
Mediverm Online
https://medivermonline.shop/# Stromectol ivermectin tablets for humans USA
generic ivermectin online pharmacy
EverLastRx: how to order Cialis online legally — cheap tadalafil tablets
https://everlastrx.shop/# how to order Cialis online legally
NeuroCare Direct affordable Neurontin medication USA generic gabapentin pharmacy USA
Mediverm Online: order Stromectol discreet shipping USA — order Stromectol discreet shipping USA
https://britpharmonline.shop/# buy sildenafil tablets UK
UK online antibiotic service: Amoxicillin online UK — UK online antibiotic service
generic amoxicillin amoxicillin uk amoxicillin uk
order steroid medication safely online: cheap prednisolone in UK — buy prednisolone
UK online antibiotic service UK online antibiotic service UK online antibiotic service
http://britmedsdirect.com/# UK online pharmacy without prescription
viagra: viagra — viagra uk
order ED pills online UK: order ED pills online UK — BritPharm Online
https://britmedsdirect.com/# pharmacy online UK
online pharmacy: BritMeds Direct — UK online pharmacy without prescription
British online pharmacy Viagra: buy sildenafil tablets UK — buy viagra
generic Amoxicillin pharmacy UK buy penicillin alternative online UK online antibiotic service
http://britmedsdirect.com/# online pharmacy
Prednisolone tablets UK online: Prednisolone tablets UK online — order steroid medication safely online
UK online pharmacy without prescription Brit Meds Direct order medication online legally in the UK
http://britpharmonline.com/# Viagra online UK
http://britpharmonline.com/# viagra uk
generic amoxicillin: buy penicillin alternative online — buy amoxicillin
buy propecia: safe online medication store — ZenCareMeds
ZenCareMeds promo code for canadian pharmacy meds trusted online pharmacy USA
MedicoSur: mexican pharmacy — mexico pharmacy
https://medicosur.com/# mexico pharmacy
https://tadalifepharmacy.com/# trusted online pharmacy for ED meds
mexico pharmacy MedicoSur mexico pharmacy
safe online medication store online pharmacy order medicine discreetly USA
mexico pharmacy: mexican pharmacy — mexican pharmacy
https://tadalifepharmacy.shop/# trusted online pharmacy for ED meds
http://zencaremeds.com/# ZenCare Meds com
Cialis online USA trusted online pharmacy for ED meds trusted online pharmacy for ED meds
MedicoSur: mexican pharmacy — mexican pharmacy
http://medicosur.com/# mexican pharmacy
cialis safe online pharmacy for Cialis affordable Cialis with fast delivery
buy propecia: order medicine discreetly USA — affordable online pharmacy for Americans
discreet ED pills delivery in the US: safe online pharmacy for Cialis — Cialis online USA
http://zencaremeds.com/# buy amoxil
https://tadalifepharmacy.shop/# safe online pharmacy for Cialis
trusted online pharmacy for ED meds: TadaLife Pharmacy — TadaLife Pharmacy
tadalafil tablets without prescription [url=https://tadalifepharmacy.com/#]buy cialis online[/url] buy cialis online
affordable Cialis with fast delivery: generic Cialis online pharmacy — generic Cialis online pharmacy
order medicine discreetly USA: ZenCare Meds com — safe reliable canadian pharmacy
discreet ED pills delivery in the US generic Cialis online pharmacy trusted online pharmacy for ED meds
mexican pharmacy: mexico pharmacy — mexico pharmacy