Lego nxt mindstorms bluetooth

NXT Bluetooth Communication Tutorial

To begin this tutorial, we will start by demonstrating how to connect your Lego NXT Brick to a computer over Bluetooth. A computer running Windows 10 is required because the code supplied was written using the updated Serial Port class for Windows 10, and therefore is different and incompatible from the Serial Port class that is used in earlier versions of Windows.

Pairing the LEGO NXT Brick with a PC

Note: If your computer does not already have Bluetooth capabilities, you will need to purchase a Bluetooth dongle. Any Bluetooth dongle should work. This tutorial uses the Abe Bluetooth dongle that was made for the Lego NXT; however, these are discontinued and most Bluetooth dongles will work. The Lego NXT already has built in Bluetooth capabilities.

Turn on your LEGO NXT and navigate Main Menu > Bluetooth >Visibility > Visible and Enter on the brick (orange button).(Note: Make sure your brick remains on for the whole process.)

With the Bluetooth dongle plugged into a USB port on your computer, use the search menu to look for “Bluetooth Settings”. Your computer will automatically search for discoverable Bluetooth devices and you should see a device labeled “NXT” in the search results list. Select it and click “Pair”.

Set a pairing key (default “1234” is fine) on your NXT Brick and then enter it on your PC when Windows prompts you for the pairing key

Connecting the NXT Brick with BricxCC

Connecting to Bluetooth via BricxCC may be a pain sometimes. At times it connects easily, other times it won’t connect at all.

In the “Find Brick” window, under the “Port” menu you should find an option that starts with “BTH::NXT::” and then is followed by some numbers. Select that choice.

Leave “Firmware” as is (standard) and click “OK”. (Note: At this point, the NXT Brick should display a diamond shape next to the Bluetooth sign in the upper left hand corner of the display to signal that is connected with another Bluetooth device)

Testing the Bluetooth Connection in BrixCC

The Bluetooth connection can be tested in BrixCC once the LEGO NXT has been connected to BrixCC as instructed in the previous section. To do so:

Here’s a video on what it should look like: https://youtu.be/DZpp9yBOnfc

Sending Direct Commands to NXT over Bluetooth

LEGO includes the LEGO Mindstorms NXT Communication Protocol programmed into all NXT Bricks through the firmware. This communication protocol lies above the Bluetooth communication protocol. It allows for direct commands to the NXT Brick. These commands are structured as byte arrays with hexadecimal encoding.
Note: See documentation for more commands and details about the LEGO NXT Communication Protocol NXT Direct Commands

There are several methods you can you go about sending direct commands. There are programs that allow you to send data to certain COM ports, but most of these are only good for testing and not writing programs that utilize the COM ports. This tutorial will demonstrate the use of the C-plus-plus Serial Port class in Windows that can be used to write programs that send data to COM ports, thus allowing the user to send direct commands to the NXT Brick with a C-plus-plus program.

/* Alvaro Pintado [email protected] Objective: This program opens up a COM port for Bluetooth communication with a LEGO NXT Brick. The program sends direct commands in the form of byte arrays to be interpreted through the LEGO Mindstorms NXT Communication Protocol. Notes: -When writing commands to the LEGO NXT, it is advised that you do not request a response in order to avoid the time delay of the Bluetooth chipping switching modes from receiving to transmitting (30 - 60 ms). Unfortunately, I was unable to get that command byte working as the hexadecimal encoding used in the Serial Port class only encodes integers up to 127. For my application, the latency was not a significant issue (and won't be in most applications). If the user would like to experiment with sending commands that are over 127, they should look into changing the encoding for the Serial Port class to a different encoding scheme such as UTF-8. */ // Necessary header files and namespaces in order to use the Serial Port Class #using #include #include using namespace System; using namespace System::IO::Ports; using namespace System::Threading; using namespace std; int main() { //Settings for COM Port Int32 baudRate = 9600; Int32 readTimeout = 500; // time limit for attempting to write to port before exiting Int32 writeTimeout = 500; // time limit for attempting to read from port before exiting //Requests Port Number from user Console::Write("Enter NXT Port and press Enter: "); String^ portNum = Console::ReadLine(); Console::WriteLine("Opening COM port . "); Console::WriteLine(); //Creates Serial Port object named "NXT" for communication over Bluetooth SerialPort^ NXT = gcnew SerialPort(portNum, baudRate, Parity::None, 8, StopBits::One); //creates Serial Port object named "NXT" NXT->ReadTimeout = readTimeout; // sets read timeout NXT->WriteTimeout = writeTimeout; //sets write timeout // Opens port for communication with NXT Brick over Bluetooth NXT->Open(); Console::WriteLine(portNum + " opened for Bluetooth communication."); Console::WriteLine(); Sleep(3000); // Byte array for a direct command to the NXT Brick to play a tone // Byte 00: Least Significant Byte: 12th byte // Byte 01: Most Significant Bit: 0th Byte // Byte 02: Command response requested: 0x80 for response, 0x00 for no response // Byte 03: Mode byte: 0x04 for controlling a motor // Byte 04: Power set in percentages: 0x64 is 100 (hex) // Byte 05: Output mode byte: 0x07 for all ON // Byte 06: Regulation mode byte: 0x00 for idle // Byte 07: Turn ratio: 0x00 // Byte 08: Motor run state: 0x20 for running // Byte 09 - 13: Tacho limit: 0x00 0x00 0x00 0x00 for running forever // See LEGO Mindstorms NXT Communication Protocol documentation for details // motorA = 0, motor b = 1, motor c = 1 wchar_t motorL = [left motor port]; wchar_t motorR = [right motor port]; cli::arraywchar_t, 1>^ driveL = { 0x0C, 0x00, 0x00, 0x04, motorL, 0x64, 0x07, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00 }; cli::arraywchar_t, 1>^ driveR = { 0x0C, 0x00, 0x00, 0x04, motorR, 0x64, 0x07, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00 }; cli::arraywchar_t, 1>^ stopL = { 0x0C, 0x00, 0x00, 0x04, motorL, 0x00, 0x07, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00 }; cli::arraywchar_t, 1>^ stopR = { 0x0C, 0x00, 0x00, 0x04, motorR, 0x00, 0x07, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00 }; //Writes direct command to the NXT Brick to drive two motors forward Console::WriteLine("Drive forward for 1 second"); Sleep(5000); NXT->Write(driveL, 0, 14); NXT->Write(driveR, 0, 14); Sleep(1000); //Writes direct command to the NXT Brick to stop two motors Console::WriteLine("Stop motors"); Sleep(1000); NXT->Write(stopL, 0, 14); NXT->Write(stopR, 0, 14); //Closes the port and exits the program Console::WriteLine("Closing program. "); Sleep(5000); NXT->Close(); exit(0); } 

Under the “COM Ports” menu are the current COM Ports assigned to different devices. Find the Outgoing Port for the NXT and take note of it. It will be used later in the tutorial.

Build and run the the solution, when prompted, enter the COM port that the NXT Brick is currently utilizing

The NXT should then drive as demonstrated in the video: https://www.youtube.com/watch?v=pnJPoHl106c

Final Words

This tutorial covers Bluetooth communication with the NXT Brick, and gives a sample program written in C++ with Visual Studio 15 to show how to create programs that communicate with the NXT Brick over Bluetooth.

Based off the sample code, the user should be able to implement the Serial Port Class in their own program to control the NXT Brick over Bluetooth for other applications.

Except where otherwise noted, content on this wiki is licensed under the following license: GNU Free Documentation License 1.3

Источник

Дистанционное управление NXT через Bluetooth

На прошедшем недавно V открытом городском фестивале технического творчества учащихся в ДПиШ г.Челябинска был один вид соревнований, связанный с дистанционным управлением роботом. В связи с этим, я задался вопросом, как управлять роботом удобнее всего?

Варианта возможно всего два:

Требования к программе выделим следующие:

  • Возможность поворота и одновременно движения вперед;
  • Возможность двигать дополнительным мотором, кроме двух ведущих;
  • Удобство использования.

Самая распространенная ОС на устройствах, имеющихся у нас в наличии – Андройд. Поэтому и рассматриваться будут приложения для этой ОС. Ну и рассмотрим только бесплатные приложения.

В первую очередь, что нам предлагает Google Play.

  1. NXT Remote Control от автора Jacek Fedorynski.
    Страница в Google Play.
    Внешний вид приложения, подключенного к NXT:
    Достоинства: небольшой размер (45 Кб), возможность регулировки мощности.
    Недостатки: нельзя одновременно ехать вперед и влево. Нет возможности управлять третьим мотором.
    Итог: не подходит.
  2. NXT Controller Plus от Lukas Dilik.
    Страница в Google Play.
    Внешний вид приложения:
    Достоинства: возможность работы с датчиками (все 4 порта одновременно), плавные повороты. Небольшой размер (233 Кб).
    Недостатки: По-прежнему нет возможности управлять третьим мотором.
    Итог: не подходит.
  3. NXT Remote by iCount от iCount.pl.
    Страница в Google Play.
    Внешний вид приложения:
    От предыдущего отличается только тем, что нет возможности работы с датчиками.
    Итог: не подходит.
  4. NXT GSensor Remote от Ferdinand Stueckler.
    Страница в Google Play.
    Внешний вид приложения:
    Особенностью приложения является то, что управление роботом осуществляется с помощью наклона смартфона (планшета) в нужную сторону. Это забавно, но очень не практично. Нет управления третьим мотором.
    Итог: не подходит.

Подведем небольшой итог. Среди рассмотренных бесплатных приложений ни одно не удовлетворяет всем условиям. Использовать их для соревнований нельзя.

Обратимся к платным приложениям. Установкой и апробацией их не занимался, поэтому только информация, получаемая из Google Play.

  1. NxtRemote от SmartphoneRemote .
    Страница в Google Play.
    Внешний вид приложения:
    С помощью данной программы возможно следующее:
    Управление всеми моторами;
    Считывание показаний всех сенсоров;
    Считывание списка программ и запуск нужной.
    Стоимость: 122,38 руб.
    Итог: подходит.

Другие платные приложения не рассматриваю, поскольку не нашел среди них ни одного, удовлетворяющего всем условиям.

Среди рассмотренных бесплатных приложений не нашлось ни одного, подходящего по всем параметрам. Надо либо покупать приложение. либо писать свое. На просторах интернета встретил несколько статей, каким образом осуществляется взаимодействие. Будем работать в этом направлении.

Управление с компьютера рассмотрим в следующей статье.

Источник

Bluetooth-connection between Android and Lego Mindstorm NXT

Does anybody know, how to build a bluetooth connection between Android and LEGO-Mindstorm-NXT? The connection between two NXTs works fine. But the other Connection-type likes not so easy. I am working with the LeJOS Firmware 0.85 and the Android SDK Tools (2.2 Froyo).

See below in my answer how does it works. By the first run or the first connect to the NXTs, the Smartphone will be automaticly pair to the NXT and ask you to the key from the nxt to pair with it.

2 Answers 2

So i’ve solved it and will show all how does it works, because i’ve seen that a lot of people have problems with that.

The class includes 4 functions:

  • Bluetooth enable if not enabled before -> enableBT()
  • Connect to 2 NXTs -> connectToNXTs()
  • Write Message to one of the NXTs -> writeMessage(byte msg, String nxt)
  • Read Message from one of the NXTs -> readMessage(String nxt)

Here is the code for the android device (BT_comm.java):

package de.joen.android.CubeScan; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.UUID; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.util.Log; public class BT_Comm < //Target NXTs for communication final String nxt2 = "00:16:53:04:52:3A"; final String nxt1 = "00:16:53:07:AA:F6"; BluetoothAdapter localAdapter; BluetoothSocket socket_nxt1, socket_nxt2; boolean success = false; // Enables Bluetooth if not enabled public void enableBT()< localAdapter = BluetoothAdapter.getDefaultAdapter(); // If Bluetooth not enable then do it if (!localAdapter.isEnabled()) < localAdapter.enable(); while(!(localAdapter.isEnabled())); >> // Connect to both NXTs public boolean connectToNXTs() < // Get the BluetoothDevice of the NXT BluetoothDevice nxt_2 = localAdapter.getRemoteDevice(nxt2); BluetoothDevice nxt_1 = localAdapter.getRemoteDevice(nxt1); // Try to connect to the nxt try < socket_nxt2 = nxt_2.createRfcommSocketToServiceRecord(UUID .fromString("00001101-0000-1000-8000-00805F9B34FB")); socket_nxt1 = nxt_1.createRfcommSocketToServiceRecord(UUID .fromString("00001101-0000-1000-8000-00805F9B34FB")); socket_nxt2.connect(); socket_nxt1.connect(); success = true; >catch (IOException e) < Log.d("Bluetooth","Err: Device not found or cannot connect"); success=false; >return success; > public void writeMessage(byte msg, String nxt) throws InterruptedException < BluetoothSocket connSock; // Swith nxt socket if (nxt.equals("nxt2")) < connSock=socket_nxt2; >else if(nxt.equals("nxt1")) < connSock = socket_nxt1; >else < connSock=null; >if (connSock!=null) < try < OutputStreamWriter out = new OutputStreamWriter(connSock.getOutputStream()); out.write(msg); out.flush(); Thread.sleep(1000); >catch (IOException e) < // TODO: Auto-generated catch block e.printStackTrace(); >> else < // Error >> public int readMessage(String nxt) < BluetoothSocket connSock; int n; // Swith nxt socket if (nxt.equals("nxt2")) < connSock=socket_nxt2; >else if (nxt.equals("nxt1")) < connSock=socket_nxt1; >else < connSock=null; >if (connSock!=null) < try < InputStreamReader in = new InputStreamReader(connSock.getInputStream()); n = in.read(); return n; >catch (IOException e) < // TODO: Auto-generated catch block e.printStackTrace(); return -1; >> else < // Error return -1; >> > 

To get messages from the Android Smartphone you must have a read call on the NXT-side. Here is the code from the NXT-side wich will accept the connection from the Smartphone and read messages from it:

Boolean isrunning = true; // Main loop while (true) < LCD.drawString(waiting,0,0); LCD.refresh(); // Listen for incoming connection NXTConnection btc = Bluetooth.waitForConnection(); btc.setIOMode(NXTConnection.RAW); LCD.clear(); LCD.drawString(connected,0,0); LCD.refresh(); // The InputStream for read data DataInputStream dis = btc.openDataInputStream(); // Loop for read data while (isrunning) < Byte n = dis.readByte(); LCD.clear(); LCD.drawInt(n, 4, 4); >dis.close(); // Wait for data to drain Thread.sleep(100); LCD.clear(); LCD.drawString(closing,0,0); LCD.refresh(); btc.close(); LCD.clear(); > 

Hope this will help others.

Источник

Читайте также:  При включении блютуз наушников нет звука
Оцените статью
Adblock
detector