Programing arduino with java

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Program your Arduino in Java

SINTEF-9012/JArduino

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.markdown

Welcome to the JArduino project, powered by ThingML!

Browse the dist folder to get the latest JArduino distribution, which you can import as an Eclipse project. People interested in the concepts behind JArduino can read our paper «MDE to manage communications with and between resource-constrained systems». If you are more into the code, just try it out for real!

$ git clone https://github.com/SINTEF-9012/JArduino.git 

Before using JArduino, please make sure your Arduino board contains the JArduino firmware:

  1. Copy the JArduino folder (located in the distribution in jarduino.core/src/main/arduino/ into your arduino working directory at Arduino/libraries/
  2. Launch your Arduino environment
  3. File -> Examples -> JArduino -> JArduino firmware. It should open an Arduino program that you should upload to your board using the normal Arduino procedure.
  4. Your Arduino board is now ready for Jarduino. You can exit the Arduino environment forever and launch Eclipse. Just run the Java/JArduino program.

To test samples using the current version of JArduino (requires Maven + the Arduino board connect on the serial port of the computer):

$ cd JArduino $ mvn clean install 

To run some examples without IDE

$ cd jarduino.samples $ mvn exec:java -Dexec.mainClass="org.sintef.jarduino.gui.JArduinoGUI" 

Replace «org.sintef.jarduino.gui.JArduinoGUI» with your own main class

  1. Instead of JArduino folder, copy the JArduinoEthernet folder to Arduino IDE librairies folder
  2. Launch Arduino environment
  3. File -> Examples -> JArduinoEthernet -> JArduino firmware. It should open an Arduino program that you should 4. if you have associated the MAC address of your shield to a static IP in your router, please update the MAC address in the firmware (line 84). Otherwise, DHCP should manage everything. 5. upload to your board using the normal Arduino procedure.
  4. Your Arduino board is now ready for JarduinoEthernet. You can exit the Arduino environment forever and launch Eclipse. Just run the Java/JArduino program.

JArduinoEthernet does not need JArduino.serial maven dependency, don’t forget to remove it if you want to use JArduino from an Android application for instance.

You Can can now use the JArduino constructor to configure the IP of your device. Don’t forget to set the communication module to ethernet:

JArduino arduino = new BlinkEthernet(ip, JArduinoCom.Ethernet)

To run a sample using Ethernet:

mvn clean install exec:java -Dexec.mainClass="org.sintef.jarduino.examples.basic.BlinkEthernet" -Dexec.args=""

Android and Bluetooth usage

Читайте также:  Java integer parseint string int

To run these examples you need to have a recent android platform. Then you just have to go in the org.sintef.jarduino.samples.android where you can find a basic android application that make a blink on the pin13 of the Arduino and read the value on the pinA0. This application connects the android platform to the Arduino using a bluetooth adapter so you have to set the name of your bluetooth device into deviceName in the program.

private String deviceName = "NameOfYourBluetoothDevice";

Android Arduino GUI

You can also see the Android GUI in the folder org.sintef.samples.android.gui. Here also, you must set the bluetooth device name using the preference screen in order to connect to the Arduino. The preference screen can be reached using the «settings» button on the top of the screen.

In the top middle of the screen you can see the list of all the orders sent to the Arduino. In fact there are two lists. The «loop» list and the «setup» list. You can edit each one of those using the «Loop» or «Setup» option on the top of the screen and then writing orders using the GUI.

In the bottom middle of the screen see the responses sent from the Arduino to the Android pltaform.

If you click the button Run (Play), the orders of the setup list will be executed once, and the loop list orders will be executed infinitely. Pause: pauses the execution of the orders. If play is pressed while it is paused, it will continue. Stop: stops the execution. Clear: clear the two lists (loop and setup). Delay: a pop-up will be open to set the delay you wish. Save: save the two lists into the specified file. Load: load the two lists contained into the specified file. Ping: send a ping to the Arduino.

Читайте также:  Object array to class array java

When you click on a Pin Button (blue with white edges) a list of action is displayed and you can choose the one you want to perform. If you want to make an Analog write, a pop-up will be open to allow you to set the value you want to write.

Make also sure that you are performing an action supported by the Arduino. Unattended action will result in unattended results.

Источник

Работа с COM-портом Arduino из Java-приложения

Сап, хабр. Возможно, людям, начинающим изучать arduino, будет интересно, как легко и быстро организовать передачу информации между микроконтроллером и Java приложением. Данная связка открывает кучу интересных возможностей по сбору и обработке данных с датчиков, управлению различными свистелками-перделками, а также созданию своих первых IoT проектов.

Недавно на просторах интернета наткнулся на весьма простую библиотеку Java-Arduino Communication Library. Не найдя публикаций на эту тему здесь, решил поделиться с вами опытом использования. Для работы нам понадобятся установленные Arduino IDE, IntelliJ IDEA, Java SE Development Kit и, собственно, сам микроконтроллер (я тестировал на китайской Arduino Nano и Strela на базе Leonardo от Амперки, на обоих все все работало отлично).

Задача проста — создадим консольное приложение, которое при запуске устанавливает Serial-соединение с микроконтроллером и в бесконечном цикле ожидает ввода строки от пользователя. В зависимости от введенной строки возможны следующие варианты:

  • «on» — микроконтроллер включает встроенный светодиод;
  • «off» — микроконтроллер выключает встроенный светодиод;
  • «exit» — микроконтроллер выключает встроенный светодиод, и приложение завершает работу.

Скетч для микроконтроллера

Построение системы начнем с написания и загрузки скетча в Arduino Nano. Ничего сверхсложного. В блоке «setup» конфигурируем пин со светодиодом и Serial-порт, а в блоке «loop» слушаем Serial-порт на предмет пришедших байтов. В зависимости от полученного значения выполняем ту или иную операцию.

/*пин №13 связан со встроенным светодиодом на платах Uno, * Mega, Nano, Leonardo, Mini и др. */ #define LED_PIN = 13 void setup() < //открытие Serial-порта со скоростью 9600 бод/c Serial.begin(9600); //настройка пина со светодиодом в режим выхода pinMode(LED_PIN, OUTPUT); >void loop() < //если в буфере Serial-порта пришли байты (символы) и ожидают считывания if (Serial.available() != 0) < //то считываем один полученный байт (символ) byte b = Serial.read(); //если получен символ '1', то светодиод включается if (b == 49) digitalWrite(LED_PIN, HIGH); //если получен символ '0', то светодиод выключается if (b == 48) digitalWrite(LED_PIN, LOW); >

Небольшого пояснения и внимательности требует лишь проверка условий (b == 49) и (b == 48). Если не понимаете почему так, то добро пожаловать под спойлер:

Все дело в том, что при отправке на микроконтроллер по Serial-соединению символа (Chr) ‘1’ используется кодировка ASCII, в которой символ ‘1’ кодируется целочисленным десятичным значение (Dec) 49. При считывании символа микроконтроллером, значение символа ‘1’ присваивается целочисленной переменной byte b. То есть фактически значение переменной b равно 49.

Читайте также:  Wordpress template php files

Для проверки на этом этапе можно из встроенного в Arduino IDE монитора порта отправить 1 и 0. Если светодиод на плате не включается/выключается, то ищите ошибку у себя в скетче.

Java-приложение

Теперь запустим IntelliJ IDEA и создадимм новый Java-проект. Для работы потребуется подключить две дополнительные библиотеки: jSerialComm-1.3.11.jar и arduino.jar. Как добавить скаченные jar-архивы можно прочитать вот здесь.

Все приложение будет состоять из одного единственного класса:

import arduino.Arduino; import java.util.Scanner; public class AppMain < public static void main(String[] args) throws InterruptedException < Scanner scanner = new Scanner(System.in); Arduino arduino = new Arduino("COM52", 9600); boolean connected = arduino.openConnection(); System.out.println("Соединение установлено: " + connected); Thread.sleep(2000); label_1: while (scanner.hasNext()) < String s = scanner.nextLine(); switch (s) < case "on": arduino.serialWrite('1'); break; case "off": arduino.serialWrite('0'); break; case "exit": arduino.serialWrite('0'); arduino.closeConnection(); break label_1; default: System.out.println(s + " - не является командой"); break; >> > > 

Для работы с COM портом создается объект класcа Arduino. Конструктор принимает два параметра:

Далее необходимо установить соединение с помощью метода openConnection(). Метод возвращает true в случае успешного соединения. Выведем это значение в консоль, чтобы убедиться в правильности выполненных действий.

Важно: после открытия соединения необходимо сделать паузу с помощью метода Thread.sleep(), в данном случае 2000 миллисекунд. Arduino Nano оказался настоящим тугодумом по сравнению со Strela, отправлять данные которой можно было сразу же после установки соединения. Вполне возможно, что вашему контроллеру понадобится даже больше времени. Поэтому если соединение установлено, данные отправляются, но не приходят, то первым делом увеличьте величину паузы.

Теперь входим в бесконечный цикл и начинаем ожидать ввода от пользователя:

 label_1: while (scanner.hasNext()) < String s = scanner.nextLine(); switch (s) < case "on": arduino.serialWrite('1'); break; case "off": arduino.serialWrite('0'); break; case "exit": arduino.serialWrite('0'); arduino.closeConnection(); break label_1; default: System.out.println(s + " - не является командой"); break; >>

При введении очередной строки и нажатии «enter» выполняется ее чтение и сохранение в переменную String s. В зависимости от значения этой строки оператор switch отсылает на микроконтроллер символ ‘1’ или ‘0’ с помощью метода serialWrite(char c). Не забывайте, что когда микроконтроллер получит эти символы и сохранит их в целочисленную переменную, то вы получите 49, либо 48).

Вообще для пересылки данных можно использовать следующие перегруженные методы класса Arduino:

  1. public void serialWrite(String s);
  2. public void serialWrite(char c);
  3. public void serialWrite(String s,int noOfChars, int delay);
  4. public void serialWrite(char c, int delay);

При завершении программы желательно закрыть COM-port с помощью метода close.connection(), чтобы при повторном запуске программы не получить ошибку, связанную с тем, что COM-порт прежнему занят, а для выхода из бесконечного цикла, ожидающего ввод строки, используйте оператор break c указанием метки label_1, который позволяет выйти из цикла, перед которым стоит соответствующая метка:

case "exit": arduino.serialWrite('0'); arduino.closeConnection(); break label_1; 

На этом сегодня все. Надеюсь, статья окажется чем-то полезной для вас. В скором времени постараюсь написать следующую, в которой будет рассмотрена возможность не только отправки, но и получения данных с микроконтроллер на примере более прикладного и функционального приложения.

Источник

Оцените статью