Labview for lego mindstorms

Обновлено: 28.03.2024

Auto-suggest helps you quickly narrow down your search results by suggesting possible matches as you type.

LabVIEW for LEGO MINDSTORMS

(Special MINDSTORMS specific version of LabVIEW - Educators)

NI LabVIEW for LEGO MINDSTORMS software is a new education-focused version of LabVIEW 2012 SP1. Developed specifically for high school students to use with the LEGO Education robotics platform in classrooms or after-school robotics competitions, LabVIEW for LEGO MINDSTORMS is a teaching tool that helps students visually control and program MINDSTORMS EV3/NXT robots. The desktop software turns any LEGO MINDSTORMS Education set into a full-feature science and engineering learning station, preparing students for university courses and engineering careers where LabVIEW is already used.

NOTE: LVLM 2012 does not inlcude EV3 support by default. To add EV3 support first download LVLM then install the LabVIEW Module for LEGO MINDSTORMS below.

This software is available as single-seat for personal use, or campus bundles for primary and secondary schools and afterschool competitions. Download a 30-day trial version, and purchase a license to activate your trial into the full software.

Once you have LabVIEW for LEGO MINDSTORMS 2012 you will need to install the LabVIEW Module for LEGO MINDSTOMRS 2012 to add EV3 support.

(MINDSTORMS Programming Software that ships with MINDSTORMS retail, supports EV3 & NXT)

NI Partnered with LEGO to create the EV3 programming langugage. The home version of the EV3 software is avalible for free download. EV3 software support both LEGO MINDSTORMS EV3 as well as the NXT. This software is recomended for developers under 13 years old.

LabVIEW Toolkit for LEGO MINDSTORMS

(MINDSTORMS Add On for Existing LabVIEW Licence - Industry / University / Hobbyist)

With the LabVIEW Module for LEGO MINDSTORMS, you can use LabVIEW to control and program the LEGO MINDSTORMS EV3/NXT. If you already have a LabVIEW license for yourself or your company, you can install the one of the modules below as an add-on to LabVIEW.

LV4E 2012
LVLM 2012

Table Legend - LabVIEW Revision Features

Note: The colors in the table above indicate the features available for each version of this LabVIEW add-on.

If you are working with young students or are completely new to programming you can get started using the EV3 Software designed by National Instruments and powered by LabVIEW.

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

Is there a version for x64 labview?

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

The NXT Module is only avalible in 32bit.

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

For what reason that when I try to install the LEGO NXT Mindstorm 2013 module, it asks for LabVIEW 2012 SP1, while I just installed LabVIEW 2013?? I downloaded directly from the NI website and I am sure I am on the right site. Tried few times. This does not make any sense! Want to hear from NI representatives. Please FIX!

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

Same problem, please fix it asap.

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

Same problem here.

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

Howdy everyone, we've reposted the NXT 2013 download and all should be resolved now, please download and let us know if you have any trouble

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

It's working now, thanx.

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

Yes, it is good now. Thank you!

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

Is there a demo version of LabVIEW Mindstorms for Mac OSX anywhere in existence? I've tried downloading the Windoze version and installing it under WINE/Crossover on my Mac, but it just throws 'not enough memory' errors and quits, although I've got 12GB of RAM free. I really don't want to buy without trying first …

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

Unfortunatly we donot have evaluation versions of LabVIEW for Mac.

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

Where would I, as a private person not connected with education or schools in any way at all, buy the Mac version anyway? You don't seem to sell it on the NI site, and I've searched for hours on the net and followed the links from this site to education sites in my country (Australia) and elsewhere, and all I can find is LabVIEW for Education and LabVIEW Student Edition, not specifically LabVIEW Mindstorms, and even then I get the impression that they only sell to schools, though I could be wrong.

There's almost no information on these sites as to what distinguishes these different versions, and the only info I can find that's at all useful is the various demos that people have generously put up on YouTube for LabVIEW Mindstorms.

All I want is the Mac version single seat licence that isn't expensive like the full versions of LabVIEW proper, and which I can buy online (and preferably download) and use at home (in Australia). It really shouldn't be this hard …

Btw, why is there no Mac demo? That seems like quite a serious omission …

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend
  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

I have the beta developers kit for the EV3 Education version. Will a formal version for Lego education Licensed software be made available?

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

I have a NI LabView for Education license I bougth on 2012. I would like if there is any update to be able to use it with EV3 or I'd have to buy a new license

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

Just download the free LabVIEW Module for LEGO MINDSTORMS 2012, and you can install it on top of your LabVIEW for Education 2012 licence for EV3 support.

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend
  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

I bought on 2012 but I can see that is the 2010 version, so I can't install this patch.

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

I have the licensed version of the EV3 education software as well as the Beta developers kit from NI for making VIXs which runs on top of this. I was told by NI a Lego specific verion, not a LV version, would be released in the 2nd quarter.

Are there still plans to release the final version of the Developer's kit for the Lego Version of software?

  • Mark as Read
  • Mark as New
  • Bookmark
  • Email to a Friend

I've been waiting for several months now for NI to provide an update to LabVIEW for Lego Mindstorms to work with my EV3 Brick and, now that they've done it, I can't instal it. The link in the email pointed to a download page for Windoze only, typically of NI with their awful Mac support, so I came to this page. But I can't instal the latest version of the LabVIEW Lego Mindstorms module for Mac OS X from the link above. It seems to be just a patch anyway, and its installer tells me that I need to instal the 'SP1' first, whatever that is, and I can't find that anywhere on the NI site for download.

I bought LabVIEW for Lego Mindstorms 2012 Mac a few months ago on CD, and didn't know there was supposed to be an 'SP1' and, not being a Windoze user, not very sure what an 'SP1' is to start with. I'm guessing it stands for 'Service Pack' as on Windoze.

The NI website is by far the most complex and messy site I've ever seen, so hard to find anything. Searches just bring up more of these patches, not the 'SPs' or modules themselves … arrggghhh!

Здравствуйте. В своих статьях я хочу Вас познакомить с основами программирования микрокомпьютера LEGO NXT Mindstorms 2.0. Для разработки приложений я буду использовать платформы Microsoft Robotics Developer Studio 4 (MRDS 4) и National Instruments LabVIEW (NI LabVIEW). Будут рассматриваться и реализовываться задачи автоматического и автоматизированного управления мобильными роботами. Двигаться мы будем от простого к сложному.


Предвосхищая некоторые вопросы и комментарии читателей.

Почему именно NXT Mindstorms 2.0? Потому-что для своих проектов данный набор мне показался наиболее подходящим, т.к. микрокомпьютер NXT полностью совместим с платформами MRDS 4 и NI LabVIEW, а так же данный набор является очень гибким в плане сборки различных конфигураций роботов — затрачивается минимум времени на сборку робота.

Почему платформы MRDS 4 и NI LabVIEW? Так сложилось исторически. Обучаясь на старших курсах университета стояла задача в разработке учебных курсов с использованием данных платформ. К тому же платформы обладают достаточной простотой в освоении и функциональностью, с их использованием можно написать программу непосредственно для управления роботом, разработать интерфейс пользователя и провести тестирование в виртуальной среде (в случае с MRDS 4).

Да кому вообще нужны эти ваши уроки, в сети и так куча проектов по робототехнике! С использованием данной связки (NXT+MRDS 4/NI LabVIEW) учебных статей практически нет, в основном используется родная среда программирования, а в ней совсем все тривиально. Всем кому интересны робототехника, программирование и у кого есть набор NXT (а таких не мало), возрастная аудитория любая.

Графические языки программирования это зло, а те кто на них программируют еретики! Графические языки программирования коими и являются MRDS 4 и NI LabVIEW несомненно имеют свои минусы, например ориентированность под узкие задачи, но все же в функциональности они мало уступают текстовым языкам, тем более NI LabVIEW изначально разрабатывался как язык легкий в освоении для решения научных и инженерных задач, для этого в нем присутствует множество необходимых библиотек и инструментов. По-этому для решения наших задач данные графические языки являются наиболее подходящими. И не надо нас за это сжигать на костре презирать.

Все это выглядит по-детски и вообще не серьезно! Когда задача состоит в реализации алгоритмов, в обучении основам и принципам программирования, робототехники, систем реального времени без углубления в схемотехнику и протоколы, то это очень подходящий инструмент хоть и не дешевый (касаемо набора NXT). Хотя для этих же целей неплохо подойдут наборы на базе Arduino, но совместимости с MRDS 4 и NI LabVIEW у данного контроллера почти нет, а в данных платформах есть свои прелести.

Технологии, которые используются, являются продуктом загнивающих капиталистических стран, а автор враг народа и пособник западных заговорщиков! К сожалению, большинство технологий в области электроники и вычислительной техники родом с запада, буду очень рад если мне укажут на аналогичные технологии исконно отечественного производства. А пока будем использовать то, что имеем. И не надо на меня за это сообщать спецслужбам держать зла.

Краткий обзор платформ MRDS 4 и NI LabVIEW.

Внесу некоторую ясность в терминологию. Под платформой, в данном случае, имеется ввиду совокупность различных инструментов, например язык VPL в MRDS, а так же среда выполнения приложений, т.е. непосредственной компиляции приложений в исполняемые (*.exe) файлы нету.

  • блочной диаграммы, описывающей логику работы виртуального прибора;
  • лицевой панели, описывающей интерфейс пользователя виртуального прибора.

Краткий обзор набора LEGO NXT Mindstorms 2.0.


Рисунок 1 — Микрокомпьютер NXT с подключенными датчиками и приводами

И конечно же в наборе находятся разнообразные детали LEGO в форм-факторе LEGO Technic из которых будут собраны исполнительные механизмы и несущая конструкция.


Рисунок 2 — Детали в форм-факторе LEGO Technic

Пишем первое приложение.

Напишем первое приложение. Пусть, классически, данное приложение выводит текст “Hello, World!”. Реализация будет происходить поочередно в MRDS 4 и NI LabVIEW, в процессе будем рассматривать специфику каждой платформы.

Предварительно инсталлируем платформы MRDS 4 и NI LabVIEW, в случае с MRDS 4 инсталляция должна проводится в папку путь к которой не состоит из кириллицы (русских букв), учетная запись пользователя так-же должна состоять только из латинских букв.

1. Платформа MRDS 4.

Запускаем среду VPL (Меню Пуск — Все Программы — Microsoft Robotics Developer Studio 4 — Visual Programming Language). Данная среда позволяет разрабатывать приложения на языке VPL, проводить тестирование в виртуальной среде VSE. Программа в VPL представляет собой диаграмму, состоящую из соединенных между собой блоков. В открывшемся окне, помимо стандартной панели команд и меню, присутствует 5 основных окон:

  1. Basic Activities – содержит базовые блоки, которые реализуют такие операторы как константа, переменная, условие и т.д.;
  2. Services – содержит блоки, предоставляющие доступ к функционалу платформы MRDS, например блоки для взаимодействия с какой-либо аппаратной составляющей робота, или блоки для вызова диалогового окна;
  3. Project – объединяет диаграммы входящие в проект, а так же различные конфигурационные файлы;
  4. Properties – содержит свойства выделенного блока;
  5. Diagrams window – содержит, непосредственно, диаграмму (исходный код) приложения.


Рисунок 3 — Среда программирования VPL

Выполним следующую последовательность действий:

  1. добавим блоки Data (из окна Basic Activities) и блок сервиса Simple Dialog (из окна Services),
  2. в блок Data введем “Hello, World!” (без кавычек) и выберем тип данных String,
  3. соединим блок Data с блоком Simple Dialog, появиться диалоговое окно,
  4. далее, все выполняем как на рисунках


Рисунок 4 — Окно Connections


Рисунок 5 — Окно Data Connections


Рисунок 6 — Законченный вид диаграммы


2. Платформа NI LabVIEW.

На данной платформе все реализуется, практически, идентично. Запустим среду LabVIEW. Перед нами появиться два окна, первое — Front Panel, предназначено для реализации интерфейса пользователя (внешнего вида виртуального прибора), второе — Block Diagram, для реализации логики программы.


Рисунок 8 — Окна среды LabVIEW

Мы будем использовать окно Block Diagram. Выполним следующие шаги:

  1. в окне Block Diagram вызовем контекстное меню, нажатием правой кнопкой мыши,
  2. в появившемся окне перейдем по вкладкам, как на рисунке и выберем String Constant,

Среда программирования Lego Mindstorms EV3 была разработана компанией National Instruments. В ее основе лежит мощная среда инженерного программирования LabVIEW.

Среда программирования Lego Mindstorms EV3

редактор Lego Mindstorms EV3

Программирование является визуальным и осуществляется перетаскиванием пиктограмм (иконок) в рабочее окно.

Графический интерфейс языка программирования EV3 поддерживает большинство структур программирования и дает возможность создавать сложные алгоритмические конструкции.

Обзор среды программирования EV3

Двойным нажатием левой кнопки мыши на иконку LEGO MINDSTORMS Education EV3 запускаем среду программирования EV3. У меня установлено программное обеспечение для педагога т.к. оно дает больше возможностей.

Программное обеспечение для педагога

ПО для педагога

После того, как среда программирования запустится сразу появляется окно — «Что нового в этой версии». Можно прочитать и лучше в левом нижнем углу поставить галочку у надписи «Do not show again for this version».

Теперь каждый раз при запуске ПО это окно не будет появляться. Запустив приложение, мы попадаем в основное окно под названием «Лобби». В окно «Лобби» легко перейти если нажать кнопку «Лобби» в верхнем левом углу.

Лобби

что такое Лобби

Внешний вид кнопки похож на панель управления микрокомпьютера EV3. Также в левой верхней части находятся кнопки меню:

  • Файл
  • Редактировать
  • Инструменты
  • Справка

В правой верхней части окна «Лобби» можно увидеть логотип «LabVIEW» и значки:

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

На данный момент в установленной версии есть семь ярлыков из которых четыре активированы и три являются неактивными.

Активные ярлыки:

  • Начало работы
  • Новый проект
  • Руководство (самоучитель)
  • Инструкции по сборке

Неактивные ярлыки:

  • Конструкторские проекты
  • Космическое задание
  • Окружающий мир

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

Учебные материалы

материалы для обучения

Также в левом нижнем углу находится кнопка «Просмотр», позволяющая переходить в основное меню и кнопка «Поиск», помогающая по заданным критериям осуществлять поиск проектов.

This guide helps users who are used to working with LEGO® MINDSTORMS® Education EV3 become familiar with using blocks in MakeCode.

Snap together the blocks

Just like in LabView, blocks in the MakeCode editor can be dragged from the cabinet and snapped together to create a sequence of program instructions.

Take a look a the LabView program below: it starts, turns on motor A, waits a second, and finally stops motor A.

sequence of block

The blocks in MakeCode have similar functions and go together in the same way: they snap into the ||loops:on start|| block and then connect to each other vertically.

Any block program can be converted to JavaScript and you can edit it as lines of code too.

Download to the EV3

Before you actually run your program on the EV3 Brick, you can first try it in the simulator. The MakeCode editor includes a simulator in the browser for you to test your code. You can make changes to your program and check them out it the simulator to make sure your code works the way want. The similator knows when you modify your code and it restarts automatically to run the new code.

Once you’re ready to transfer your program to the EV3 Brick, click the |Download| button and follow the instructions.

Single motors

This program controls a large motor on port A in several different ways. It sets just the speed and then sets speed for: an amount of time, angle of movement, and a number of rotations.

Single motor blocks

Рулевого управления

Блоки рулевого управления позволяют синхронизировать два мотора в точной скорости. They can also specify the duration, angle, or number of rotations for the motors to turn.

Блоки рулевого управления

The turn ratio range is -200, 200 unlike LabView who used -100,100.

The tank blocks control the speed of two motors. These are commonly used for a differential drive robot. The blocks can also specify the duration, angle, or number of rotations.

Tank block

Coasting and braking

By default, all motors coast when any command used to move finishes. You can keep them from coasting with the ||motors:set brake|| block.

Brake block

Inverting and regulating motors

If you wan to change the direction that a motor turns, use the ||motors:set inverted|| block.

Brake block

By default, the speed of motors is regulated. This means that if your robot goes up a hill, the regulator will adjust the power to match the desired speed. You can disable this feature using ||motors:set regulated|| .

Brake block

Кирпич

The Brick category has a number of blocks to display graphics on the brick screen.

brick image

brick status light

Waiting (pausing)

It is quite common to have to wait for a task to finish or for a sensor state to change, such as when a touch button pressed. The ||loops:pause|| and ||sensors:pause until|| blocks provide a way for your program to wait for a period of time.

pause for time

pause for touch

pause for distance

You can also use the ||loops:pause until|| block to wait on any boolean expression. As your program runs, it waits until the condition (expression) inside becomes true.

Loops

Single loop

While loop

Переменные

Variable block

Concurrent loops

You can start up multiple ||loops:forever|| loops that run at the same time. Actually, only the code in just one of the loops is really running at any exact moment in time. Each loop, though, gets a turn to run all of its code and this makes them run concurrently.

Multiple loops running at the same time

Conditional

The ||logic:if|| block allows you to run different code depending on whether some condition (boolean expression) is true or false . Also, this is similar to the ||loops:switch|| block.

Brake block

Random

The ||math:pick random|| block returns a random number selected from a range of numbers.

Controlling LEGO Mindstorms NXT motors and sensors from a myRIO using LabVIEW to create a robot base.

How to Use LEGO Mindstorms NXT with LabVIEW and myRIO

Things used in this project

Hardware components

Software apps and online services

Hand tools and fabrication machines

Story

I will explain in this tutorial how to control LEGO Mindstorms NXT components from a myRIO running LabVIEW code.

I did this project a while ago during my studies and I thought it might interest some people. During an internship at the University Transilvania of Brașov in Romania I had to work on a concept of robot for cleaning solar panels. I had at my disposal a myRIO running LabVIEW and LEGO Mindstorms NXT components. In order to make everything work together I had to "hack" those components to be able to control them from the myRIO.

This tutorial assumes you already have a basic knowledge on how LabVIEW works. It is divided in two parts:

  • NXT motor with encoder
  • NXT ultrasonic range sensor
  • NXT touch sensor

myRIO is a device developed by National Instruments. It’s an embedded hardware device, mostly destined to students for educational purpose. In order to teach engineering and to be used like a controller. As it's everything but cheap I don't expect this tutorial reach hobbyist but could be useful to students.

Check it to know the name of the pins!

Architecture

The device includes several inputs/outputs (analog and digital), two jack connectors (that act like input/output), ground connectors, 5V and 3.3V supply. myRIO also have an integrated 3-axis accelerometer and four programmable leds.

For the rest of the tutorial I would be referring to any digital input/output by "DIO" followed the number of the pin, and to any analog intput by "AI" followed by the number of the pin.

FPGA

myRIO includes a FPGA (Field Programmable Gate Array). Contrary to standard chips, the FPGA is a component which is physically modified to imitate logic gates in order to process the code. The main difference is the speed of execution (44MHz), superior to the real time processor, and the possibility to execute real parallel codes. However before every execution the program needs a long compilation time.

LEGO NXT Wire

The Lego Mindstorm devices use a modified cable based on the RJ12 connector. The position of the latch is modified to make it incompatible with standard RJ12

In order to use the NXT devices, it’s important to be able to create those wires. A regular RJ12 sockets crimping tool can be used.

The RJ12 connectors on the NXT control brick act like this:

  • Pin 1 : PWM output signal 1
  • Pin 2 : PWM output signal 2
  • Pin 3 : Ground
  • Pin 4 : 4.3V power supply
  • Pin 5 : Input value (digital or analogic)
  • Pin 6 : Input value (digital or analogic)

For each component I will detail the wiring of the RJ12 connector and the myRIO pins associate to it in my project (useful for the code and the PCB).

Wiring

The motors we will talk about are the ones included in the Lego NXT Mindstorm kit, often called "NXT Motor". Like the NXT sensors, the servomotor use a modified RJ12 cable, composed of 6 wires.

  • Wire 1 – White : Motor supply 1
  • Wire 2 – Black : Motor supply 2
  • Wire 3 – Red : Ground
  • Wire 4 – Green : Encoder supply(4.3V)
  • Wire 5 – Yellow : Tach 1(Encoder 1 value)
  • Wire 6 – Blue : Tach 2 (Encoder2 value)

The nominal power supply for the motor is 9V. Applying this voltage to one or the other motor supply allow to control the direction of rotation.

Mechanical Characteristics of the Motor

  • Nominal voltage : 9V
  • Nominal speed : 170Rpm(Rotations per minute)
  • Current : 60mA

Characteristics when motor blocked (with 9V):

  • Torque to counter : 50 N.cm
  • Current : 2A

Due to the high current, and even if the motor is protected by a thermistor, the motor will be damaged is the shaft is blocked for more than few seconds.

1 / 2 • Dependency of the rotation speed from the applied voltage (from INFORMATION TECHNOLOGY AND DEVELOPMENT OF EDUCATION ITRO 2016)

PWM

In order to control the speed and the load of the motor, PWM (Pulse Width Modulation) technic is used. The power signal supplying the motor is a square signal alternating between high pulse and a 0V state. The width of the pulse, proportionally to the width of the whole period (call duty cycle) gives the percentage of the "voltage used by the motor". For example 9V supply with a duty cycle of 50% will act like a 4, 5V supply.

Rotary Encoders

A quadratic encoder is integrated in each motor. Two wires (one for each light sensor) give information about the actual position of the motor and are used to control it. This technology uses a disc rotating with the motor. A led illuminates through the holes of two tracks, and on the other side a photo sensor changes states when the encoder rotates.

Here are the pins used by the encoders:

  • Encoder Motor 1 : pin 23 and 25: DIO6 and DIO7
  • Encoder Motor 2 : pin 27 and 29: DIO8 and DIO9

H-Bridge Board

Because myRIO can’t deliver 9V supply and handle directly the current needed for the motor, an electronic card with an H-bridge has to be crafted.

The H-bridge used in this tutorial is the famous L298.

One H-bridge can control up to two motors. The pin ENABLE allows the motor to turn, and the two pins OUTPUT control the direction.

By applying a PWM to one of the input, and by supplying the enable and the other input we allow the motor speed to be controlled. To invert the direction, the other input need to be put down.

Applying the PWM on the enable is less effective. Indeed, the motor will act half powered (when pulse is high) and totally not-powered (pulse down). This reduces the load of the motor.

The card is based on the schematic of the Motor Driver 2A Dual L298 H-Bridge for Arduino. Each board can handle two motors. Four leds allow the user to know if the motor is powered supplied and for which direction. Schematics and files can be found at the end.

The board is made to be directly connected to the myRIO outputs. A connector on the board allows connecting other devices to the myRIO through the board (because the board takes all the space for the outputs on the myRIO).

The pins used for motor power supply and H-bridge control are listed below (9V) :

  • Input 1 : pin 13 : DIO1
  • Input 2 : pin 15 : DIO2
  • Enable A : pin 11 : DIO0
  • Enable B : pin 17 : DIO3
  • Input 3 : pin 19 DIO4
  • Input 4 : pin 21 DIO5

In order to control 4 motors in my project (2 NXT motors for driving, a NXT motor for controlling the arm angle and a standard DC motor to rotate a brush) I needed 2 PCBs (as each one can command 2 motors). I won't explain how to make a PCB as internet is full of tutorials on how to do it. Special thanks to Assoc Prof Dr. Petru Cotfas for the PCB design (available at the end).

Current S ensing

You can measure the current going through the DC motor by reading the SNS0 and SNS1 pins. On each channel will be a voltage proportional to the measured current, which can be read as a normal analog input, on the analog inputs A0 and A1. It is calibrated to be 3.3V when the channel is delivering its maximum possible current that is 2A.

  • Current sensing Motor 1: AI0
  • Current sensing Motor 2: AI1

NXT Ultrasonic Sensor

As its name suggest, an ultrasonic sensor use ultrasound to measure the distance to an obstacle. The principle is very simple: an ultrasonic wave is sent by the sensor, and will collide on every object in front of it. The wave will then come back to the sensor, and the time between the sending and the receiving is proportional to the distance to the object. The drawbacks of this technology are the inability to measure very close object (there is a “dead zone”) and the impossibility to use multiple ultrasonic sensors in the same time (they will disturb each other).

Wiring

  • Wire 1 – White : +9V powersupply
  • Wire 2 – Black : Ground
  • Wire 3 – Red : Ground
  • Wire 4 – Green : +4.3V powersupply
  • Wire 5 – Yellow : I2C Clockline (SCL)
  • Wire 6 – Blue : I2C Data line(SDA)

Characteristics

Here the characteristics of the sensor:

  • Range : From 0 to 255 cm (theory range, real range is from 4cm to 255cm due to the “dead zone”)
  • Accuracy : +/- 3cm
  • Directivity : Cone of approx.30°

The sensor is more efficient with hard and large surface objects. Soft and curved objects give a worse reading.

The sensor can be used in different mode: single shot or continuous mode. By default the sensor is in continuous mode, and it’s continuously making new measurements that are registered on the first memory slot. In single shot mode, new measurements are made when asked, and stored in every memory slots (8 available, which means it’s possible to store maximum 8 values). For this application, we only use continuous reading mode.

Accuracy Test

Static Test

Test made with a static sensor, the object used as a target is a small cardboard box (14.5 cm x 9.5 cm x 6 cm).

From the results above it can be deducted (for a static use), that for small distance the accuracy is good (for a non-industrial sensor) and not very accurate at the very beginning of the range (measured value bigger than real value).

Dynamic Test

Test made by moving slowly the sensor to a wall in continuous reading mode (speed of approximately 30cm/s).

From the results above, it can be deducted that some areas are not accurate, especially between 25cm and 50cm where the sensor can return the value of 48cm. Also on all the range the sensor returns sometime the error value (255).

Communication

The sensor uses the I2C protocol to communicate. This is a protocol Slave/Master that uses 2 wires : one for clock and one for data. The wire for data can be reversed to transmit data from the master or from the slave during the communication.

  • SCL (Clock) : DIO12 (ConnectorMXP B)
  • SDA (Data) : DIO13 (ConnectorMXP B)

Also the I2C protocol used by NXT is a little bit different than standard I2C. First the frequency is not the same as standard speed nor high speed I2C; it’s around 9600hz (measured value around 11khz). Furthermore to communicate with this sensor you will need to add an extra pulse without data after any Repeated Start.

Mistakes to Avoid

One of the problem by using myRIO was that some digital Input/Output from myRIO are using a pull-up resistor of low resistance (the DIO 14 and 15 from the connector A and B). The sensor wasn’t able to pull down the line enough to transmit data, it’s important to use other DIO, which are using a bigger resistor.

Also the sensor need 4V for its I2C communication and myRIO delivers only 3.3V. It’s enough to make the communication works, but it’s also possible to use a board that allowsI2C between devices with different voltages.

Information Delivered

The device returns a value: a 8 bits integer directly proportional to the distance (the value in decimal is the distance in centimeters). Except for the value 255, which means nothing in sight (out of range) or an error.

NXT Touch Sensor

The touch sensor is a very basic sensor. It’s a digital sensor that is either on high or low state.

The wiring is made as follow:

  • Black : ground
  • Green : 4.3V supply
  • White :

When high (4, 9 V) sensor not activated

The myRIO is the robot controller and is programmed using LabVIEW. Its program is split into two parts: a part of the code running on the FPGA (for the advantages and drawbacks see FPGA section above), and the other part of the code running in the Real-Time controller, a "standard" processor.

FPGA Code Overview

The code on the FPGA mostly consists of a while loop for each actuator/sensor.

Читайте также: