+ All Categories
Home > Documents > arduino.ua controlled cars are... · Web viewArduino Robots вы можете построить...

arduino.ua controlled cars are... · Web viewArduino Robots вы можете построить...

Date post: 29-Dec-2019
Category:
Upload: others
View: 3 times
Download: 0 times
Share this document with a friend
28
Remote controlled cars are fun, sure, but self-driving robotic cars are even more fun. In this tutorial, we’ll build a four-wheeled robot that can drive around and avoid obstacles. I purchased this complete 4WD kit from AliExpress, but you could easily buy most of these components from an electronics store and put it together yourself. I recommend reading through all of the instructions before you start, as that will make some things clear that might be confusing on the first time through. Also, this may look like a very long, advanced project due to the length of the instructions, but it’s actually pretty simple. No need to be intimidated – this is a beginner level project that you can get some satisfying results with, then build upon as you learn more. Don’t like this style of robot? Here’s some more Arduino robots you could easily build instead.8 Arduino Robots You Can Build for Less than $125 8 Arduino Robots You Can Build for Less than $125READ MORE Here’s what we have, after taking everything out of the packaging: Автомобили с дистанционным управлением - это весело, конечно, но самоходные роботизированные автомобили еще веселее. В этом уроке мы построим четырехколесный робот, который может двигаться и избегать препятствий. Я приобрел этот комплект из 4WD от AliExpress, но вы можете легко купить большинство этих компонентов из магазина электроники и собрать его вместе. Я рекомендую прочитать все инструкции перед тем, как вы начнете, поскольку это сделает некоторые вещи ясными, которые могут сбивать с толку в первый раз. Кроме того, это может выглядеть очень длинным, продвинутым проектом из-за длины инструкций, но на самом деле это довольно просто. Не нужно пугаться - это проект уровня начинающих, с которым вы можете получить некоторые удовлетворительные результаты, а затем опираясь на то, как вы узнаете больше. Не нравится этот стиль робота? Вот еще несколько роботов Arduino, которые вы могли бы легко создать вместо этого. Arduino Robots вы можете построить менее чем за $ 125 8 Arduino Robots, которые вы можете построить за $ 125READ БОЛЬШЕ Вот что мы имеем, взяв все из упаковки:
Transcript

Remote controlled cars are fun, sure, but self-driving robotic cars are even more fun. In this tutorial, we’ll build a four-wheeled robot that can drive around and avoid obstacles. I purchased this complete 4WD kit from AliExpress, but you could easily buy most of these components from an electronics store and put it together yourself.

I recommend reading through all of the instructions before you start, as that will make some things clear that might be confusing on the first time through. Also, this may look like a very long, advanced project due to the length of the instructions, but it’s actually pretty simple. No need to be intimidated – this is a beginner level project that you can get some satisfying results with, then build upon as you learn more. Don’t like this style of robot? Here’s some more Arduino robots you could easily build instead.8 Arduino Robots You Can Build for Less than $125 8 Arduino Robots You Can Build for Less than $125READ MORE

Here’s what we have, after taking everything out of the packaging:

Автомобили с дистанционным управлением - это весело, конечно, но самоходные роботизированные автомобили еще веселее. В этом уроке мы построим четырехколесный робот, который может двигаться и избегать препятствий. Я приобрел этот комплект из 4WD от AliExpress, но вы можете легко купить большинство этих компонентов из магазина электроники и собрать его вместе.Я рекомендую прочитать все инструкции перед тем, как вы начнете, поскольку это сделает некоторые вещи ясными, которые могут сбивать с толку в первый раз. Кроме того, это может выглядеть очень длинным, продвинутым проектом из-за длины инструкций, но на самом деле это довольно просто. Не нужно пугаться - это проект уровня начинающих, с которым вы можете получить некоторые удовлетворительные результаты, а затем опираясь на то, как вы узнаете больше. Не нравится этот стиль робота? Вот еще несколько роботов Arduino, которые вы могли бы легко создать вместо этого. Arduino Robots вы можете построить менее чем за $ 125 8 Arduino Robots, которые вы можете построить за $ 125READ БОЛЬШЕВот что мы имеем, взяв все из упаковки:

To get started, we’ll attach the motors and the H bridge (the card that delivers power to the motors) to the lower part of the chassis. First, attach the four metal brackets (they’re rectangular, drilled blocks of metal) to each motor using two long bolts and two nuts.

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

You’ll need to make sure that they’re attached correctly, so check out the image below to make sure that the side of the block with two drilled holes will face downward. Note that the wires on each motor are pointing toward the center of the chassis.

Вам нужно убедиться, что они установлены правильно, поэтому проверьте изображение ниже, чтобы убедиться, что сторона блока с двумя просверленными отверстиями будет направлена вниз. Обратите внимание, что провода на каждом двигателе направлены к центру шасси.

Now each motor can be attached to the chassis by using two short bolts in the bottom of each metal bracket. Here’s a view of the bottom of the chassis so you can see where the bolts need to be:

Теперь каждый двигатель может быть прикреплен к шасси с помощью двух коротких болтов в нижней части каждого металлического кронштейна. Вот вид нижней части корпуса, чтобы вы могли видеть, где должны быть болты:

The next step is to secure the H bridge (that’s the red board, in my kit) to the chassis. You may want to wait until all of the wires are attached to the H bridge before doing this, but that’s up to you (I found it to be easier). A quick note: my kit was missing a number of fasteners, so I used electrical tape to secure the bridge. However, you can see here where the bolts and nuts would have gone:

Следующий шаг - обеспечить мост H (это красная доска в моем комплекте) на шасси. Вы можете подождать до тех пор, пока все провода не будут прикреплены к мосту H до этого, но это зависит от вас (я нашел, что это будет проще). Быстрое замечание: в моем комплекте отсутствовало несколько крепежных элементов, поэтому я использовал изоленту для крепления моста. Однако вы можете увидеть здесь, где болты и гайки ушли бы:

Now that the H bridge has been attached, you can start wiring up the power supply. Because the six-AA battery holder comes with a DC adapter, you’ll need to either cut off the end (which I did) or run jumper wires to the batteries themselves.

Теперь, когда мост H был присоединен, вы можете начать подключение источника питания. Поскольку держатель батареи с шестиядерным аккумулятором поставляется с адаптером постоянного тока, вам необходимо либо отрезать конец (что я и сделал), либо проложить провода перемычек к самим батареям.

No matter how you decide to do it, you’ll run the positive wire to the port labelled “VMS” and the negative wire to the one labelled “GND” on the bridge. Screw down the fasteners and make sure they’re secure. Then, you’ll connect the motor wires. On both sides, there’s a set of two ports; one is labelled “MOTORA” and the other “MOTORB.” Both red wires on each side will go into the centermost green port, and both black wires will go into the outermost. This picture should make it more clear:

Независимо от того, как вы решите это сделать, вы запустите положительный провод в порт с надписью «VMS» и отрицательный провод до отметки «GND» на мосту. Отвинтите крепежные детали и убедитесь, что они защищены. Затем вы подключите провода двигателя. С обеих сторон есть набор из двух портов; один обозначается как «MOTORA», а другой «MOTORB». Оба красных провода с каждой стороны войдут в самый зеленый зеленый порт, и оба черных провода войдут в самый отдаленный. Эта картина должна сделать ее более ясной:

I found that I had to strip some of the housing off of the motor wires to get this to work. Now that you have the motors and the power supply all wired up, slide the wheels onto the motor drive shafts, and attach the four copper shafts in the locations show in the picture below (each copper shaft needs one small bolt). This robot is starting to take shape!

Я обнаружил, что мне пришлось снять часть корпуса проводов электродвигателя, чтобы заставить это работать. Теперь, когда у вас есть все двигатели и источник питания, подключите колеса к валам двигателя и прикрепите четыре медных вала в местах, показанных на рисунке ниже (для каждого медного вала нужен один маленький болт). Этот робот начинает складываться!

Now, set that part of the chassis aside and grab the other one which will sit on top. The next step is to attach the Arduino—again, I had to use electrical tape, but you should be able to better secure yours with some bolts and nuts.

Теперь отложите часть шасси и возьмите другую, которая будет сидеть сверху. Следующий шаг - снова прикрепить Arduino, мне пришлось использовать изоленту, но вы должны быть в состоянии лучше закрепить свои болты и гайки.

The next step requires the micro servo, the black crosspiece, the servo holder (which consists of three black plastic pieces), and some small screws. Use one of the larger sharp screws in the kit to attach the black crosspiece to the micro servo:

Следующий шаг требует микросервер, черная перемычка, держатель сервопривода (который состоит из трех черных пластиковых деталей) и некоторые маленькие винты. Используйте один из более крупных острых винтов в комплекте для крепления черной перемычки к микросервису:

Then flip the servo upside down into the black plastic ring of the holder. Make sure that the wires coming out of the servo are facing in the same direction as the longer part of the holder (again, see the image below), and use four tiny screws to secure the crossbar (there are four holes in the holder that align with the holes on the crossbar).

Затем переверните сервопривод вверх дном в черное пластиковое кольцо держателя. Убедитесь, что провода, выходящие из сервопривода, обращены в том же направлении, что и более длинная часть держателя (см. Изображение ниже), и используйте четыре крошечных винта для крепления перекладины (в держателе имеется четыре отверстия, выровнять с отверстиями на перекладине)

Here’s what it looks like after it’s attached:

Вот как он выглядит после того, как он подключен:

Finally, take the other two pieces of the servo holder and snap them onto the servo (there are grooves in the side pieces that match the plastic tab on the servo).

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

Now that the servo holder is complete, it can be mounted to the chassis.

Теперь, когда держатель сервопривода завершен, его можно установить на шасси.

Here’s where the bolts go:

Вот где болты идут:

It’s time to give our robot some eyes. Attach the ultrasonic sensor to the servo holder using two zip ties.

Пришло время дать нашему роботу какие-то глаза. Прикрепите ультразвуковой датчик к держателю сервопривода, используя две застежки-молнии.

If you’re working from the same kit as I am, you’ll have received an Arduino sensor shield. We won’t be using it in this build, but you can pop it on top of the UNO now if you want (as I have in the image below). Just align the pins on the bottom of the shield with the I/O ports on the Arduino and press down to connect them. You don’t need it at the moment, but shields can come in handy.The Top 4 Arduino Shields To Superpower Your Projects The Top 4 Arduino Shields To Superpower Your ProjectsYou’ve bought an Arduino starter kit, you’ve followed all the basic guides, but now you’ve hit a stumbling block - you need more bits and bobs to realise your electronics dream. Luckily, if you have...READ MORE

Если вы работаете из того же набора, что и я, вы получите щит датчика Arduino. Мы не будем использовать его в этой сборке, но теперь вы можете поместить его поверх UNO, если хотите (как на изображении ниже). Просто выровняйте контакты в нижней части экрана с портами ввода / вывода на Arduino и нажмите вниз, чтобы соединить их. В настоящий момент вам это не нужно, но щиты могут пригодиться. Лучшие 4 щита Arduino для сверхдержавы ваших проектов Лучшие 4 щита Arduino для сверхдержавы ваших проектов Вы купили комплект для начинающих Arduino, вы следовали всем основным но теперь вы попали в камнем преткновения - вам нужно больше бит и бобы, чтобы реализовать мечту вашей электроники. К счастью, если у вас есть ... ПОДРОБНЕЕ

Whether you connect a sensor shield or not, you’ll now need four wires to connect the ultrasonic sensor to the Arduino. There are four pins on the sensor, VCC, GND, TRIG, and ECHO. Connect VCC to the 5V pin on the Arduino, GND to GND, and TRIG and ECHO to I/O pins 12 and 13.

Now grab the lower part of the chassis, and connect six jumper wires to the I/O pins of the H bridge (they’re marked ENA, IN1, IN2, IN3, IN4, and ENB). Take note of which color wires are connected to which ports, as you’ll need to know later.

Независимо от того, подключен ли сенсорный экран или нет, теперь вам потребуется четыре провода для подключения ультразвукового датчика к Arduino. На датчике есть четыре контакта, VCC, GND, TRIG и ECHO. Подключите VCC к выходу 5V на разъемах Arduino, GND to GND и TRIG и ECHO к выводам ввода / вывода 12 и 13.Теперь возьмите нижнюю часть шасси и соедините шесть проводов перемычек с выводами ввода / вывода моста H (они обозначены ENA, IN1, IN2, IN3, IN4 и ENB). Обратите внимание, какие цветовые провода подключены к портам, о чем вам нужно будет знать позже.

Now it’s time to start putting this thing together. Grab the upper part of the chassis and set it on top of the copper shafts connected to the lower part, and pull the wires attached to the H bridge through the hole in the center of the chassis. Connect the six wires to I/O ports as follows:

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

· ENA to I/O port 11

· ENB to I/O port 10

· A1 to I/O port 5

· A2 to I/O port 6

· B1 to I/O port 4

· B2 to I/O port 3

Now, use four short screws to attach the upper part of the chassis to the copper shafts. Set the six-AA battery holder on top of the chassis (screw it down if you can), attach the 9V cell holder to the Arduino, and this bot is ready to rock!

Теперь используйте четыре коротких винта, чтобы прикрепить верхнюю часть шасси к медным валам. Установите держатель батарейки шести AA на верхнюю часть корпуса (привинтите его, если можете), прикрепите держатель 9V к Arduino, и этот бот готов к скале!

Well, almost ready to rock. It doesn’t have quite enough personality yet.

Ну, почти готов качать. Пока этого недостаточно.

There we go. Now to give it a brain. Let’s do some programming.

The first thing we’ll do is test to make sure that the bridge and motors are hooked up correctly. Here’s a quick sketch that will tell the bot to drive forward for half a second, drive backward for half a second, then turn left and right:

Мы идем. Теперь, чтобы дать ему мозг. Давайте сделаем некоторое программирование.Первое, что мы сделаем, это проверить, чтобы убедиться, что мост и моторы подключены правильно. Вот быстрый эскиз, который подскажет боту двигаться вперед на полсекунды, проехать назад на полсекунды, затем повернуть влево и вправо:

// Motor A pins (enableA = enable motor, pinA1 = forward, pinA2 = backward)

int enableA = 11;

int pinA1 = 6;

int pinA2 = 5;

//Motor B pins (enabledB = enable motor, pinB2 = forward, pinB2 = backward)

int enableB = 10;

int pinB1 = 4;

int pinB2 = 3;

//This lets you run the loop a single time for testing

boolean run = true;

void setup() {

pinMode(enableA, OUTPUT);

pinMode(pinA1, OUTPUT);

pinMode(pinA2, OUTPUT);

pinMode(enableB, OUTPUT);

pinMode(pinB1, OUTPUT);

pinMode(pinB2, OUTPUT);

}

void loop() {

if (run) {

delay(2000);

enableMotors();

//Go forward

forward(200);

//Go backward

backward(200);

//Turn left

turnLeft(400);

coast(200);

//Turn right

turnRight(400);

coast(200);

//This stops the loop

run = false;

}

}

//Define high-level H-bridge commands

void enableMotors()

{

motorAOn();

motorBOn();

}

void disableMotors()

{

motorAOff();

motorBOff();

}

void forward(int time)

{

motorAForward();

motorBForward();

delay(time);

}

void backward(int time)

{

motorABackward();

motorBBackward();

delay(time);

}

void turnLeft(int time)

{

motorABackward();

motorBForward();

delay(time);

}

void turnRight(int time)

{

motorAForward();

motorBBackward();

delay(time);

}

void coast(int time)

{

motorACoast();

motorBCoast();

delay(time);

}

void brake(int time)

{

motorABrake();

motorBBrake();

delay(time);

}

//Define low-level H-bridge commands

//enable motors

void motorAOn()

{

digitalWrite(enableA, HIGH);

}

void motorBOn()

{

digitalWrite(enableB, HIGH);

}

//disable motors

void motorAOff()

{

digitalWrite(enableB, LOW);

}

void motorBOff()

{

digitalWrite(enableA, LOW);

}

//motor A controls

void motorAForward()

{

digitalWrite(pinA1, HIGH);

digitalWrite(pinA2, LOW);

}

void motorABackward()

{

digitalWrite(pinA1, LOW);

digitalWrite(pinA2, HIGH);

}

//motor B controls

void motorBForward()

{

digitalWrite(pinB1, HIGH);

digitalWrite(pinB2, LOW);

}

void motorBBackward()

{

digitalWrite(pinB1, LOW);

digitalWrite(pinB2, HIGH);

}

//coasting and braking

void motorACoast()

{

digitalWrite(pinA1, LOW);

digitalWrite(pinA2, LOW);

}

void motorABrake()

{

digitalWrite(pinA1, HIGH);

digitalWrite(pinA2, HIGH);

}

void motorBCoast()

{

digitalWrite(pinB1, LOW);

digitalWrite(pinB2, LOW);

}

void motorBBrake()

{

digitalWrite(pinB1, HIGH);

digitalWrite(pinB2, HIGH);

}

view raw4wd-robot-test.ino hosted with ❤ by GitHub

That’s a lot of code for a simple test, but defining all of those functions makes it easier to tweak later. (Big thanks to Billwaa for his blog post on using the H-bridge for defining these functions.) If something went wrong, check all of your connections and that the wires are connected to the correct pins. If everything worked, it’s time to move onto the sensor test. To use the ultrasonic sensor, you’ll want to download the NewPing library, and then use Sketch > Include Library > Add .ZIP Library… to load the library.

Это много кода для простого теста, но определение всех этих функций упрощает настройку позже. (Большое спасибо Billwaa за сообщение в блоге об использовании H-моста для определения этих функций.) Если что-то пошло не так, проверьте все ваши соединения и подключите провода к правильным контактам. Если все сработает, пришло время перейти на тест датчика. Чтобы использовать ультразвуковой датчик, вам нужно загрузить библиотеку NewPing, а затем использовать Sketch> Include Library> Добавить .ZIP Library ... для загрузки библиотеки.

Make sure that you see the include statement at the top of your sketch; if you don’t, hit Sketch > Include Library > NewPing. Once you’ve done that, load up the following sketch:

Убедитесь, что вы видите инструкцию include в верхней части эскиза; если вы этого не сделаете, нажмите Sketch> Include Library> NewPing. После того, как вы это сделали, загрузите следующий эскиз:

#include

//Tell the Arduino where the sensor is hooked up

NewPing sonar(12, 13);

long inches;

void setup() {

//Activate the serial monitor so you can see the output of the sensor

Serial.begin(9600);

}

void loop() {

delay(50);

//Ping the sensor to determine distance in inches

inches = sonar.ping_in();

//Print the distance in inches to the serial monitor

Serial.print(inches);

Serial.print(" in.");

Serial.print("\n");

}

view rawnewping_demo.ino hosted with ❤ by GitHub

Upload the sketch, and open up the serial monitor using Tools > Serial Monitor. You should see a rapidly updating sequence of numbers. Hold your hand in front of the sensor and see if that number changes. Move your hand in and out, and you should get a measurement of how far away your hand is from the sensor.

Загрузите эскиз и откройте последовательный монитор с помощью «Инструменты»> «Серийный монитор». Вы должны увидеть быстро обновляющуюся последовательность чисел. Держите руку перед датчиком и проверьте, не изменилось ли это число. Перемещайте свою руку и выходите, и вы должны измерить, насколько далеко ваша рука от датчика.

If everything worked correctly, it’s time to put it all together and let this thing run! Here’s the code for the robot now. As you can probably tell, this is basically the two test sketches put together with an added if statement to control the robot’s behavior. We’ve given it a very simple obstacle-avoidance behavior: if it detects something less than four inches away, it will backup, turn left, and start moving again. Here’s a video of the bot in action.

Если все работает правильно, пришло время собрать все вместе и позволить этой вещи работать! Вот код для робота. Как вы, вероятно, можете сказать, это в основном два эскиза тестов, которые вместе с добавленным оператором if управляют поведением робота. Мы дали ему очень простое поведение при предотвращении препятствий: если он обнаруживает что-то менее чем в четырех дюймах, он будет делать резервную копию, повернуть налево и начать движение снова. Вот видео бота в действии.


Recommended