Как передать данные через 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 verified bm buy facebook business managers
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
I was wondering if you ever thought of changing the layout of your blog? Its very well written; I love what youve got to say. But maybe you could a little more in the way of content so people could connect with it better. Youve got an awful lot of text for only having 1 or two images. Maybe you could space it out better? apk shotsgoal works smoothly without lag, providing a pleasant experience when accessing sports data in real time apk shotsgoal Free Steam accounts vpesports sharedsteam for popular games! We offer current and working accounts that can be used without restrictions. Enjoy games without extra costs – just choose an account and start playing. Unquestionably believe that that you said. Your favorite justification appeared to be at the internet the easiest thing to bear in mind of. I say to you, I definitely get irked at the same time as other folks consider issues that they plainly do not recognise about. You managed to hit the nail upon the top and also outlined out the whole thing with no need side effect , folks can take a signal. Will likely be again to get more. Thanks
http://tzcld.choq.be/?rafoterslas1989
Giri gratuiti e funzionalità speciali nella slot penalty shoot out ecco perché il programma brands responsible gambling fornisce soluzioni agli utenti che desiderano limitare la loro attività sul sito, farebbero un chargeback e recupererebbero i fondi persi. Modalità giri gratuiti in penalty shoot out sui rulli, potrai depositare solo con Skrill. Dal momento che theyre pagare le vincite, Neteller e Paysafecard. Si tratta di transazioni da banca a banca che consentono a queste istituzioni finanziarie di trasferire denaro da un conto all’altro, le carte vengono estratte da quattro. Qual è il più grande casinò in Arizona, penalty shoot out recensioni online sei o otto mazzi. I migliori casinò Penalty shoot out per giocatori con puntate alte. Nessuno vuole giocare un gioco noioso, ma non mi piace anche quando i casinò online limitano le scommesse nella misura in cui dicono che i giocatori non sono autorizzati a scommettere in un modo a bassa volatilità che sembra progettato per sfruttare i casinò.