当前位置:网站首页>Arduino hexapod robot

Arduino hexapod robot

2022-07-06 00:33:00 acktomas

Arduino Hexapod robot part one — Mechanism and wiring

Look at the original

This article comes from DevicePlus.com Translation of English website .

 Insert picture description here

Hexapod robot is one of the coolest robots , But it's usually expensive . One reason is that they are made up of many parts , And use 18 Servo , These need to be powered and driven by some microcontrollers . In this tutorial , I will show how to use 3D Print all components and use only 12 A servo to build your own Arduino Hexapod robot , Or for short Ardupod. are you ready? ? Let's start !

Hardware

  • • Arduino UNO ( Or other compatible Arduino Development board )
  • • Adafruit 16 passageway PWM Expansion board ( Or module ; however , This expansion board is strongly recommended here , Because its prototype area is very small )
  • • 12 A micro servo with metal gears (MG90S Or other products of the same specification )
  • • 4.8V or 6V The battery ( Nickel hydrogen 、 Lithium ion, etc )
  • • 60 individual M3 Bolt +120 Nuts and washers ( Only for the body , For the installation of other parts, you need to add another )
  • • 6 Same ballpoint pen spring
  • • HC-SR04 Ultrasonic ranging module ( Optional )

Software

  • • Arduino IDE
  • • SolidWorks Or others 3D Modeling software
  • Github – Here you can find all the for printing Arduino The source code and 3D Model

Other tools

  • • 3D The printer
  • • It is highly recommended to use a multimeter 、 Other tools such as soldering iron and electric drill

Design

As mentioned above , The hexapod robot designed this time only needs 12 A servo to move six legs . This means that each leg is equipped with only two servos , It has two degrees of freedom (DOF). Compared with the usual three servos per leg , This method has several advantages . We will need less power and less processing time to drive the servo . however , Removing a servo also means that we sacrifice a degree of freedom , Therefore, it will be more challenging to program the robot to crawl stably .

In order to make up for the defect caused by the lack of a servo , All legs have a mechanical system that can convert the angular motion of the servo into linear motion of the legs .

The mechanism contains a spring . The function of the spring is to compensate all errors caused in the printing process . in addition , Springs can also provide more powerful support , Thus, it helps to achieve a more natural crawling movement . You can get springs anywhere . such as , The small spring in the ballpoint pen can be used here , But you may need to trim the length a little . Please make sure that the spring you get can be compressed , And enough to support the weight of the robot . Besides , Before you start printing components , Please make sure that the spring is suitable for the printed parts leg_1 and leg_1_seg_1( For details, see Github ).

assemble

Next , Welcome to the hardest part of this article : Assemble the legs . Whether in construction or programming , This is a fairly high-level project . We will assume that the people who intend to build this robot have basic operating skills for using equipment such as electric drills and soldering irons .

 Insert picture description here

chart 1: Overview of leg assembly

 Insert picture description here

chart 2: Leg assembly details

arduino hexapod

chart 3: Assembled legs

When assembling the legs , Please always remember to place a gasket between every two plastic parts that need to be moved up and down . You may need to use an electric drill to adjust the size of the hole , Ensure that the bolt can rotate freely . meanwhile , Please note that each bolt requires two nuts .

qqqq
chart 4: Connect the leg joints : Plastic parts ( black ) And metal parts ( Light grey )

This is very important to maintain the normal operation of the whole support system . When assembling the legs , Please make sure not to tighten the bottom nut too tightly , And adjust it so that the plastic parts can still move freely . then , The top nut should be tightened as tightly as possible . The bottom nut ensures the free movement of all parts , The top nut ensures the fastening connection of all parts . If your nut is too loose , Then the legs will become very unstable ; If you tighten it too tightly , It will bring unnecessary load to the servo . It may take several attempts to adjust the legs . This is the most important part of this tutorial , So please make sure to complete this step correctly .

Servo through a small “ Triangular arm ” To fix in place , This triangular arm is usually used to connect the servo gear shaft to any object you want to move . however , under these circumstances , The position of the triangle arm will be fixed , So that when the servo is running , It will also move by itself , So that the legs move .

Please make sure you use metal gear servo , Instead of plastic gear servo ! If plastic gears are used in this application , Not only is the strength lower than that of metal , And its gear may be damaged soon .

arduino hexapod

chart 5: Servo attachment details . Ensure that the triangle arm is fixed in place .

The servo support is divided into three parts , Make it easier to print . Suppose the parts are made of acrylonitrile butadiene styrene (ABS) Printed , Then acetone can be used to slightly dissolve ABS, Then stick the three parts together , Then dry it . perhaps , If you have the conditions to use higher quality 3D The printer , You can also print out the whole part at one time .

arduino hexapod

chart 6: Servo support assembly details

The rest of the hexapod robot is less complicated : The fuselage body is composed of two plates , We can install all the necessary electronic equipment on it 、 Batteries and sensors . You can set the hole for installing electronic equipment before printing , You can also drill after printing . All parts and printed instructions can be found in Github Get on the .

 Insert picture description here

chart 7: Assembled body :“A” For the upper plate ,“B” For the bottom plate . You can also see the ultrasonic sensor installed on the servo .

success ! Come here , You have completed the assembly of the robot , Completed the most difficult part of this tutorial . If something goes wrong , Please don't worry , Try again . If necessary, , Please try to fine tune the print , Then check whether it is effective .

connection

up to now , This is the simplest part , Because we will use Adafruit PWM Expand the board to complete most of the work . We connect the expansion board to Arduino, Then connect the servo to the expansion board . If the module you use cannot be directly connected to Arduino, Only need to SDA、SCL as well as V+ Connect to Arduino The corresponding pin is ok ( See the following figure for details ).

You may have noticed , Here is a place to place the capacitor , But there is no capacitor . Never mind , This is intentional ! When many servos are running at the same time , The peak current will reach a few amperes . Capacitors will be used to eliminate these spikes . You may need this kind of capacitor to ensure that the power supply of all servos is stable . For this purpose , Electrolytic capacitors are the most suitable , But the choice of capacitance value depends more on speculation , Rather than exact scientific calculations . Generally speaking , The larger the capacitance, the better . The voltage of the capacitor should be slightly higher than the battery voltage , therefore , If you use 6V The battery supplies power to all servos , that 6.3V 4700µF It should be able to meet the needs .

arduino hexapod

chart 8: Wiring diagram

On the expansion board , You will also notice that there is a separate power terminal . That's because Arduino It cannot provide enough current to run more than one or two servos at a time , You need to connect the battery to this terminal and Arduino Power input (VIN and GND Pin ).

this is it , The basic wiring has been completed ! if necessary , You can also add more modules and sensors , For example, ultrasonic range finder .

arduino hexapod

chart 9: Wiring details : It is recommended to tie all servo cables connected to the same leg . such , You will know which cable leads to which servo . and , It will also look more beautiful than a tangled cable .

 Insert picture description here

chart 10: with HC-SR04 Wiring diagram of ultrasonic sensor

In this tutorial , I will add an ultrasonic sensor , So that the robot can move when there are obstacles nearby . Why I choose HC-SR04, Because they are very cheap , And easy to communicate with Arduino Use it together . and , This particular sensor is shaped like an eye , You can use this to distinguish what the robot is looking at !

I installed the sensor on an additional servo ( For installation details, see Figure 7). Wiring the sensor is also very simple , Just be careful not to VCC The pin is directly connected to the battery ! If you are using 6V The battery , This connection may damage the sensor . take VCC Pin to Arduino 5V Output terminal , And will GND Connect to GND. You can use TRIG and ECHO The pin is connected to any remaining digital pin , But remember to set them appropriately in your code . I connect them to pins 3(TRIG) And pins 2(ECHO) On , Because I want to keep the pin when I need a serial port 0 and 1 To break off .

Conclusion

Now? , You should have finished assembling all the hardware . Before turning on the power , It is strongly recommended that you test and confirm each established connection .

I hope you haven't encountered any thorny problems so far . If you have any suggestions for improving the design , Please be there. Github Communicate with me on ! Please continue to pay attention to the second part of this project , We will enter the next stage , Further study and analysis of inverse dynamics , And for this magical Arduino Hexagonal robot ( perhaps Ardupod ) Programming .

Arduino Hexapod robot part II : Programming

This article comes from DevicePlus.com Translation of English website .

Click here to read the first part of this article >

 Insert picture description here

In the second part of this project , We will continue with the relatively easy content of the project — Programming . There are usually two different ways to program a hexapod robot . The first is just to figure out a series of servo operations for the robot to walk forward . obviously , This is a difficult but rarely effective work — The code you designed cannot be directly applied to another hexapod robot . So the second kind is called Inverse kinematics The new method came into being . But first of all , We need to improve the on-board microcontroller .

Hardware

  • • Arduino Mega
  • • Adafruit 16 passageway PWM Expansion board ( Or module ; however , This expansion board is strongly recommended here , Because its prototype area is very small )
  • • 12 A micro servo with metal gears (MG90S Or other products of the same specification )
  • • 4.8V or 6V The battery ( Nickel hydrogen 、 Lithium ion, etc )
  • • 60 individual M3 Bolt +120 Nuts and washers ( Only for the body , For the installation of other parts, you need to add another )
  • • 6 Same ballpoint pen spring
  • • HC-SR04 Ultrasonic ranging module ( Optional )

Software

  • • Arduino IDE
  • Github – Here you can find all the for printing Arduino The source code and 3D Model

UNO -> Mega

In the last article , We suggest using Arduino UNO. however , In the use of UNO I encountered a problem : It doesn't have enough SRAM Memory for all calculations required for the normal operation of the inverse kinematics model . Most of these calculations use Floating point numbers To complete . Each number will occupy 4 Bytes of memory , Twice the integer . It doesn't look much , however UNO Only 2kB Of RAM, Some of them will also be occupied by global variables . If we reserve for all global variables and other local variables 0.5kB, Then there will be 1.5kB Available memory for , This is only for 384 Floating point numbers occupy .384 It may look a lot , But for 1K The amount of data generated by the model is not enough ( Please read below “ Algorithm ” Some of the reasons are found ). So we must find a way to get more memory .

The simplest way to achieve this is to UNO Change to MEGA.MEGA and UNO Is compatible , Therefore, there is no need to modify the schematic diagram . in addition , Use MEGA Not only can we get more than four times for the calculation part RAM, It also means that more than eight times of flash memory will be available for our program storage . We probably won't use everything , But it's always good to have more reserved space . The following is the improved Fritzing Schematic diagram , If you are using Arduino MEGA The latest version (Rev 3), The replacement process is simple , Disconnect from UNO Then connect MEGA The process is the same . The following schematic diagram is for reference .

arduino hexapod

chart 1:PWM Schematic diagram of the improved expansion board

arduino hexapod

chart 2:PWM Module and HC-SR04 Schematic diagram of improved ultrasonic sensor

Now? , Let's explore some physical principles 、 A lot of mathematical knowledge and a small amount of code are used .

Introduction to inverse kinematics

Some people may remember , In high school , There is a part of physics class called “ kinematics ”. In short , This is a target object in the field of mechanics ( Or a point ) Description of motion . This means in kinematics , You will use mathematical formulas and models to analyze the known motion of a single point . seeing the name of a thing one thinks of its function , Inverse kinematics (IK) On the contrary : Through a series of mathematical formulas to deduce and create motion .

In robotics , The commonly used algorithm can only calculate the motion of all joints according to the corresponding endpoint motion . Now? , You can clearly see the advantages of inverse kinematics in the difficult problem of servo motion programming —— It is universal . In theory , Only one algorithm can handle any motion performed by the robot . From the user's point of view , It's very easy to use — You just need to tell the robot to turn left 90°, Then go straight 1 Just rice , Without considering the position of each servo .

Model

In the above paragraphs , A word keeps appearing : One ( mathematics ) Model . Although it sounds difficult , But for the hexapod robot project , The model is very simple : Any position that a robot can reach mechanically can be defined by a set of seven points . One for the body , The other six are for the legs . If you checked AP_Utils library ( Can be found in GitHub Get on the ), Especially inside AP_Utils.h, You will see the definition of these points ( Included in other content ):

struct body {
float x;
float y;
float z;
float facing;
};


struct leg {
uint8_t number;
bool move;
float phi;
float z;
};

You can see in AP_Utils Class, they are declared as private structures .

body origin;
leg legs[6];

There are two reasons for privatizing these structures :

  1. Users should not have the right to modify these values at will . These structures exist to track the current position of the robot , therefore , These structures will change only when the robot really produces motion . If the user wants to change the current origin z coordinate , It can lead to IK The model changes unpredictably — This is obviously not desirable .
  2. Usually , Minimize the number of common functions and variables in a class , Is a good programming habit ( Especially in C++ in ). So doing so can improve security , And benefit API Easy implementation of .

if necessary , We can visualize these points . Now? , Our whole robot is represented by seven points ( chart 3).

 Insert picture description here

chart 3:IK Graphical representation of the model . In short , This is the hexapod robot “ Think ” What it looks like . The red dot is the body , The blue dot is the leg .

These structures are used to track the position of all legs and the position of the robot itself . You may have noticed , The position of the leg is defined by only two coordinates :phi and z. This is because each leg has only two degrees of freedom , Therefore, it can only move along two axes . Now it can pass through the body xy and z Coordinates to define all positions . Of each leg phi and z The range of coordinates is -1 To 1, And only the position of the legs relative to the body is determined . Although this complexity seems unnecessary now , But in fact, it's better than calculating the weight of each leg after each exercise xy and z Coordinates are much easier .phi Coordinates represent horizontal motion ,z Indicates vertical motion .

arduino hexapod
chart 4: with phi Axis and z Leg details of the shaft

Algorithm

Now? , We have a simple enough mathematical expression for robots , But I haven't done anything with it yet . The next step is to study how to realize the servo operation by only modifying the model . The program we need to complete is to take the input as a set of point coordinates , And convert it into servo operation .

At this time, another problem arises , This time, , Just replace with another Arduino Unable to resolve . When starting servo , We may need to make most of the servo work at the same time . however ,Arduino( And all related AVRs) You can only perform one task at a time . This means that if we want to run the servo smoothly , You need to start one by one . If you just run the servo directly from one end to the other , The whole process will be very unstable .

One way to solve this problem is to calculate all servo positions in advance , Then iterate over the data , And set all servo . because Arduino MEGA The clock frequency of is 16MHz, Therefore, although all servos operate discretely in a small increment in the actual process , But the overall performance of the operation process is continuous and smooth . Although they are just a collection of still images , But this is consistent with the effect of continuous motion produced in the video . The human brain cannot process visual information quickly . If we add one after every position change 50 Millisecond delay , Obviously , Servo operation is actually composed of small increments .

This is also what we have to replace Arduino Why . If we want to run every servo , Then we need a lot of memory to store the coordinates just calculated . If we run all the servos , We will need 600 A floating-point number to store the motion coordinates , Because every servo needs at least 50 Only three positions can produce smooth and continuous operation .600 Floating point number is about 2.3 kB Of RAM— That's more than UNO The capacity of .

stay AP_Utils In the library , What converts the position to servo operation is traceLeg() and setLegs() function .traceLeg() Function only calculates : When the end of the target is provided phi and z Coordinates , It will create a path in the form of an array of coordinates . Paths can have many shapes , The current support is linear ( A simple straight line from one point to another )、 Arcs and elliptical arcs . The latter two paths can make walking easier . The second function setLegs() Based on the traceLeg To move all specified outriggers , however , All this is hidden from regular users . The focus of the whole scheme is to make it as convenient for users as possible . End users will not need to set up directly setLegs() , Just call the function directly related to walking .

Now we're starting to get in IK The last step of programming , That is, real walking . We have finished all the basic work : We created a model to track everything , We can run multiple servos , It can even make the servo operation relatively smooth and continuous . In the following , The number of outriggers corresponds to the number in the figure below :

arduino hexapod

chart 5: Outrigger number

The numbering system is also consistent with the code you find in the Library .

Let's start with simple operations : Turn around on the field . Usually , When setting a new position for the outrigger , You must ensure that three of your legs are on the ground . The reason behind this is obvious — Unless you can move the outrigger very fast , Otherwise, the robot will lose stability and fall . We can turn the robot in several steps :

1. Put the outrigger 0、2 and 4 Move to phi At the maximum coordinate ( Maximum horizontal angle ).

 Insert picture description here
chart 6: Turn to step 1( Legs 0、2 and 4)

2. Right outrigger 1、3 and 5 Do the same .

arduino hexapod
chart 7: Turn to step 2( Legs 1、3 and 5)

3. Turn your body . This step is passed along with step 1-3 It is completed by running the servo in all horizontal directions in the opposite direction . Because all the outriggers are on the ground and cannot move , So only the body can move .

 Insert picture description here
chart 8: Turn to step 3

Repeat these steps , Robots can turn 80°. Of course , As long as it is not kept in the process phi Axis maximum coordinate position , Steering less than this angle can be achieved . Thanks to the traceLeg() The clever algorithm behind the function , We don't have to calculate any of the outriggers z Coordinate value — These calculations will be performed automatically , And form the shape of a circle or ellipse . You can observe this process in the following video .

The last step is walking . say concretely , We hope it can at least move forward . There are many walking algorithms for hexapod robots , But most algorithms are based on outriggers with three degrees of freedom . Our outrigger has only two degrees of freedom , So we have to do some design by ourselves . Although the method I proposed did not achieve the expected speed , But this method is the easiest to program , And it is easy to observe the phenomenon in the process .

1. First , Legs 0 and 3 Move forward

arduino hexapod

chart 9: Walking steps 1( Legs 0 and 3)

2. then , Legs 2 and 5 Move in the same direction

 Insert picture description here
chart 10: Walking steps 2( Legs 2 and 5)

3. Right outrigger 1 and 4 Do the same

arduino hexapod

chart 11: Walking steps 4( Legs 1 and 4)

4. Now? , Move your body forward , Start repeating the whole process .

 Insert picture description here

chart 12: Walking steps 4

You can watch the whole sport in the following video :

Basic obstacle avoidance function

You may have noticed , Part of the library is dedicated to SR04 Ultrasonic range finder . This is to get some information about the environment of the robot . Of course , A fixed sensor is not enough , So in the last article, we also installed a sensor on an additional servo .

I believe that most people who try to build hexapod robots have a certain understanding of the working principle of ultrasonic rangefinder . For the interface with this sensor, I suggest you use AP_Utils::sr04_median function . It can provide all SR04 The most accurate result of function . You can even output data in units , At present, it can support mm 、 Centimeters and meters !

Important note : Please note that , You need to Adafruit PWM Driver library to AP_Utils function , You can click here download . When the download is complete , And others Arduino Install it like the Library .

Here is a very simple “ independent ” Examples of patterns , Used everything we have discussed so far : walk 、 Turn and from SR04 Read the distance in . If you read this article carefully , Then you should be able to fully understand the most important part of the following code . More details about all functions , Please refer to the Library folder or GitHub On the page README.md file .

Arduino Code :

#include <AP_Utils.h>



//define the pins that the SR04 is connected to

#define TRIG 3

#define ECHO 2



//create an instance of AP_Utils class

AP_Utils ardupod;

//you will have to supply your own offsets here

//see examples/calibration.ino for details

int offsets[16] = {5, 0, 0, -7, 10, -3, 6, -4, 3, -5, 10, -3, 0, 0, 0, 0};



void setup() {

 //reset the robot

 ardupod.begin(offsets);

}



void loop() {

 //take one step directly forward

 ardupod.walk(0, 1);

 //if an obstacle is closer than 20 cm, we have to turn

 if(sr04_median(TRIG, ECHO, CM, 100, 500) < 20.0) {

   //turn 90 degrees to the right

   ardupod.turn(90);

 }

}

Conclusion

Congratulations on completing one of the most challenging projects ! Be good at it ! Trying to make your own Ardupod Before walking , Please make sure to run... In the sample folder at the same time calibration.ino and servo_test.ino. This is essential for setting up all servos correctly , In this way, the servo will not be damaged ! In the next article , We may explore this project for the last time , To improve some points with poor mechanical properties , as well as , what's more , Add some improved functions , For example, remote control .

Arduino Hexapod The first 3 part : Remote control

Look at the original

arduino Hexapod

In the third and final part of this series , We will add the last part of the robot : The remote control . Besides , Minor improvements have been made to the outriggers , Therefore, they are more stable on any surface of the substrate . First , We will slightly modify the leg mechanism , And then HC-05 Bluetooth is connected to Arduino Conduct wireless control . Last , We will write a processing application , So we don't have to ArduPod Use written commands for every move of .

If you are new to this project , Please refer to section... Of this project before proceeding 1 Section and section 2 part :Arduino Hexapod PART 1- Mechanics and Wiring and Arduino Hexapod PART 2: Programming.

Hardware

  • The first 1 part Medium ArduPod
  • HC-05 Bluetooth module
  • 1 kΩ Resistance and 1.8 kΩ( or 2.2 kΩ) resistance

Software

  • Arduino IDE
  • Processing 3.2.3
  • GitHub – Contains the latest source code
  • Release 1.0.0 – perhaps , You can download it here v1.0.0 Source code . In case GitHub The code on gets significant API Interrupt update , These should still work the way described here

Tools

  • Soldering iron

Improve the legs

The biggest problem I personally encounter when using a hexapod robot is that the legs are really unstable on a smooth surface . This can usually be easily solved by adding some non slip material to the legs , But the surface contacting the ground is too small . Making the area of the legs touching the ground larger will help prevent slipping and improve the overall stability of the legs .

arduino Hexapod

chart 1. Old leg ( Left ) And new legs ( Right )

In the diagram above , You can see that a bottom support is added to the legs . Just like other parts , This is using black ABS Of 3D Printed on the printer . This model can be compared with mine GitHub On Find the rest of the .

arduino Hexapod

chart 2. New parts added to the legs . Pay attention to the dark green anti slip layer at the bottom .

Now we can add a non slip layer to our feet . I used a green gel pad . It will not slide even under very light load . If you can't get this exact material , There is little alternative ( For example, rubber ). Try to see which robot is best for you . Then cut six circles from the material and stick them to the feet , We're done !

The next improvement I made is a little more complicated than my feet . In the current system , The steering gear is only connected to the legs in one place . This will create a weak point in the structure , This weak point must bear most of the load , And it may break at some time . In the figure 3 in , You can see the current attachment system and the new attachment system next to it .

arduino Hexapod

chart 3. Old accessory system ( Left ) And new accessory system ( Right )

Please note that , The new part allows the server to be installed in two locations : On shaft ( Same as before ) And the other side of the server . When a small cushion with a knob is stuck to the steering gear , It will provide additional support for the steering gear . Now the server is connected at two points , Distribute the load between them . The result is better motion control .

wireless Arduino

Now that we have let go of our legs , Let's connect HC-05 Bluetooth module , It can control robots wirelessly . Because all controls have been controlled by Arduino Handle , So our main task is to send orders to them .

About how to relate to Arduino There are several main options for wireless communication :

  1. RF modules Rf module —— This is the most basic ( And the cheapest ) Wireless communication mode . Usually , They are in a single radio band (433、868 or 915 MHz) Run in , And a lot of settings need to be made from the client . Their main advantage is long range ( It can reach hundreds of meters ) And relatively low power consumption .
  2. LoRa – LoRa The module is the same as the above RF The module is similar to , However, special modulation is used to achieve a higher range at the same power consumption ( Up to kilometers ). Of course , This is at the cost of very slow transmission speed , At most, it can only be measured in hundreds of bits per second .
  3. WiFi - WiFi Modules are allowed Arduino Connect to Internet It's a quick and easy way to , however , The scope is usually quite limited . Besides , Their power consumption can be very high .
  4. GSM – This is the technology that makes your mobile phone work properly .GSM Modules have great advantages over other options : As long as there is a signal, you can communicate , Even if Arduino And the target PC Hundreds of kilometers away .GSM The biggest disadvantage is that it requires a lot of electricity —— on certain conditions , Current consumption can rise to a few amperes , Therefore, it is difficult to use only battery power .
  5. ZigBee technology ——XBee Modules are usually more expensive than the other options here , But they are easy to communicate with Arduino Connect . They were developed as a substitute for Bluetooth , Their usual range can reach 75 m.
  6. bluetooth —— This is what I decided to use in this project . Bluetooth is very easy to use , under these circumstances , Its limited scope is not a big problem : We really don't want to ArduPod Take a major adventure and start exploring areas tens of meters away from the computer . Besides , Most smartphones have Bluetooth , If you decide to write a Smartphone Application at any time , It can be done easily .

therefore , We will use Bluetooth in this project . I use the HC-05 Bluetooth module , Mainly because it is the most affordable on the market 、 The most common one . Because the function of this module is similar to serial COM port , So it will HC-05 Connect to Arduino Very easy to , Like the one below Fritzing The schematic diagram shows .

arduino Hexapod

chart 4. HC-05 Bluetooth module and Arduino Mega Wiring diagram

arduino Hexapod

chart 5. take HC-05 The Bluetooth module is connected to Arduino Mega.

The module consists of Arduino Power supply .HC-05 TX The pin is directly connected to Arduino Upper RX1 Pin . However , because HC-05 The logic level is 3.3 V, and Arduino With 5 V function ,HC-05 RX There must be a simple voltage divider on the pin to reduce the voltage .R1 The value should be 1 kΩ,R2 The value of can be 1.8 kΩ or 2.2 kΩ. I use the 2.2 kΩ, Because I can't find any 1.8 kΩ resistor , But the module should work well with any of them .

here ,Arduino I don't know that it communicates through Bluetooth module . From its point of view , This is exactly the same as when connected by cable . That's why we don't need to be in Arduino Make any settings , Because the module will handle everything —— At least in the most common case .

The next step is to set up HC-05 Bluetooth module . I use PC There is no built-in Bluetooth interface , So I have to use USB Bluetooth adapter .

about Windows 10, See the previous tutorial , It provides a way to HC-05 Connect to PC Step by step guide for : Make your own Arduino RFID Door lock - The first 2 part ; First step : Connect Bluetooth

First , We must put PC Pair with Bluetooth module .

  • Connect the adapter to PC, After installing the driver , Find... In the control panel “ Devices and printers ” window . then , Connect HC-05 by Arduino Power up .HC-05 On the red LED Will start flashing quickly . It means HC-05 Currently not connected to any other device .
  • stay “ Devices and printers ” in , single click “ Add equipment ”, Your computer should automatically find HC-05. click the icon , When prompted “ Select the pairing option ” At the window , Choose the middle one (“ Enter the pairing code of the device ”).HC-05 The default pairing code for is 1234. It's not so safe , however , We can change the code at any time . Besides , Control the hexapod robot How much security is actually required ?
  • After successfully adding the device ,HC-05 Upper LED It should now flash every two seconds - This means that it is connected to another device .

here , It's best to verify that everything is connected correctly . start-up Arduino IDE, And upload the following sketch :

void setup() {

 Serial1.begin(9600);

 while(!Serial1);

 Serial1.println("Hello world!");

}



String input;

void loop() {

 if(Serial1.available() > 0) {

   input = Serial1.readString();

   Serial1.println(input);

 }

}

After uploading , go back to “ Devices and printers ”, Find us before and PC Paired HC-05 modular . Right click HC-05 Icon and go to “ Hardware ” tab . There? , You will find the assigned module COM Port number Windows. This will be what we will use with ArduPod communication COM port . return Arduino IDE, stay Menu > Tools > Ports Choose the right COM Port and start the serial monitor . Enter a few characters , Then press Enter. These characters will be sent to the COM port , And shall serve as Arduino Response return for .

Is everything normal so far ? very good ! Now we're done “ difficult ” Things about , Let's turn to something more interesting : stay Processing Write a graphic application in .

Processing

Because you are reading this article , I assume you have a basic understanding of processing languages . Even though Processing Looks like it's with Arduino The language is very similar —— Even if Set up and loop / draw The main functions are the same —— But they're not the same .Arduino Language is almost the same as C++ identical , and Processing be based on Java. therefore , Even if the grammar is similar , There are also significant differences between the two . I will try my best to describe the application I created below .

obviously , We want the application to have a beautiful graphical user interface (GUI). because Processing Focus on drawing shapes ( So the name of the main loop function - draw), This is really easy for graphic designers . However , My skills in this field are almost nonexistent , So I will turn to the library to help me create a cool looking GUI.

Some processing libraries offer different designs , But my personal favorite is controlP5 library . You can view this website , Learn more about libraries Information . Besides , The library is full of examples of almost everything . Another useful thing you can find on this site is complete JavaDoc Reference resources . The download version on the website is a little out of date , So I strongly recommend that you use the processing library manager . At the time of writing , We will use the latest processing version ,Processing 3.2.3 . The application and source code can be found in my GitHub Found on the .

Now let's take a look at the actual appearance of the application .

arduino Hexapod

chart 6. ArdupodRemote Processing Applications

Um. , This is quite a lot of control , isn't it? ? There is a big grey mysterious box on the left , There are many buttons to press , There is a strange thing on the right , It looks a bit like radar . As you can see , I marked all the parts with red numbers , This is the function of each control :

  1. ** Serial output :** This is the main source of information for you to understand the actual situation . All content displayed on the serial port and notifications from the application itself will be written here .

  2. ** Serial port input and command prompt :** If you want to send something directly to the serial port , You can enter... Here , Send back . This is mainly used for debugging applications , But if you absolutely need to send content directly to the robot , It still exists .

  3. ** Ultrasonic scanner :** Personally, I think this is the coolest feature . When you press “ scanning ” Button ( Numbers 7) when , The ultrasonic sensor will rotate 180 Degrees and measure the distance at each degree . Distance data is sent to the application , Then you can visualize .

arduino Hexapod

chart 7. Sample scan output . The scanning area is a narrow corridor .

Even without a camera , This is a quick and easy way to understand the surrounding environment .

  1. ** Manual sensor rotation :** Speak for themselves ; This slider allows you to set the servo with ultrasonic sensor to a specific position .

  2. ** Distance output :** Every time the distance is measured , The results will be displayed here .

  3. ** Measurement button :** When pressed , The sensor will make a distance measurement and display it in the distance output field .

  4. ** Scan button :** As mentioned above , This will start ultrasonic scanning of the surrounding area .

  5. **COM Port selection :** After launching the application , You must choose the appropriate COM Ports for all communications . All that is available COM Ports will be displayed here .

  6. ** Connect button :** Choose the right one COM After the port , Press this button to connect . If something goes wrong , Errors will be printed in the serial output area to help you fix the errors .

  7. ** Disconnect button :** If you need to disconnect from the port for some reason , This is the button for you .

  8. ** Motion control :** This is the actual reason why applications exist .W Forward ,S back off ,A and D Turn left and right . It's that simple ! These buttons can be clicked or pressed on the keyboard . When clicked , Robots will take a step in the right direction . When you press and hold the key on the keyboard , The robot will continue to move in this direction , Until you release the current button or press the new button .

As you may have guessed , This application is much more complex than it really needs . I can't explain everything line by line , So we'll look at the most important parts of the code : Control event handling 、 Serial communication and Arduino End .

Control event handling

In the use of GUI When programming applications , The first thing we need to ask is “ What happens when you click a button ?” Fortunately, ,controlP5 Ku handled most of the things for us . Let's take a look at a simple scenario in the following code :

import controlP5.*;



ControlP5 cp5;

void setup() {

 size(400,400);

 cp5 = new ControlP5(this);

 

 cp5.addButton("click me!")

    .setValue(0)

    .setColorForeground(color(215, 0, 0))

    .setColorBackground(color(175, 0, 0))

    .setColorActive(color(255, 0, 0))

    .setPosition(100,100)

    .setSize(200,200)

    ;

}



public void controlEvent(ControlEvent theEvent) {

 if(theEvent.getController().getName().equals("click me!")) {

   println("Why would you trust a big red button?!");

 }

}



void draw() {}

arduino Hexapod

chart 8. controlP5 Example

First , We have to import the library and create controlP5 Class . then , stay Set up Function , Let's create a name “click me!” New button for . The last part is controlEvent function . Every time any controlP5 This function will be called when the element creates an event —— In our case , Every time you click a button . Then we can check which element caused this event , If it's our “ Click on the I !” Button , It will print some text .controlP5 The library is full of examples of how to use the many control elements it provides , So we will take a quick look at the actual content of the remote control application .

The basic event processing is exactly the same as the above example —— Use controlEvent function . In addition, there are two functions *——keyPressed and keyReleased*, They handle keys W、A、S and D The input of , To allow movement control using the keyboard . You might notice , Unlike the example , stay setup No control element is set in the function . All of these have been moved to the name guiElements In the second tab of , And use setupGui Function call . therefore , Lord ardupodRemote There is less code in the tab . Usually , Separating code blocks that deal with different things is a good programming practice , Because it's easier to read and understand the code .

Now we have a basic understanding of the working principle of graphics and controls , We can try to figure out how to understand all the data that will be transmitted through the serial port .

Serial communication and status code

We have set up Bluetooth on both sides , But we still need to create something “ agreement ” For both parties to follow , And we need it to be as short and fast as possible . Because all the data coming in through the serial port is interpreted as String data type , I created a very simple “ Data packets ” structure .“in” Data packets (Arduino Send to PC Data packets of ) The structure of is as follows :

XY Payload

The first two characters X and Y Is the status code of the packet , They let applications know Payload What types of information are included . for example , If the application receives *“82Starting PWM …” Data packets , It will write the following contents in the serial port output box :“[INFO] [SETUP] Starting PWM …”*. All the codes currently implemented are shown in the following table .

0
1[ Echoes ]
2[ Set up ]
3[ trace ]
4[SR04]
5[ Pulse width modulation ]
6[ error ]
7[ Warning ]
8[ Information ]
9>
10[ command ]
11[ Applications ]

Please note that , In the application , Code 40 Reserved for scanning data , Code 41 For single distance measurement .

“ Output ” Data packets ( The application is sent to Arduino Data packets of ) The structure of is simplified a little :

Xpayload

Same as before , First character X Will decide how to handle the payload . However , This time, , We will only use a few commands .

t Turn the sensor to Location specified in the payload
m Measuring distance
n Start scanning
w[s] go / Walk forward
a[s] turn / Turn left
s[s] go / back off
d[s] Turn right / Turn right

Arduino aspect

up to now , We try to connect Bluetooth to Arduino and PC. We also wrote a cool GUI Applications for , And created a with Arduino Communication protocol , But there are still some things missing : We may be sending data , but Arduino I haven't listened yet . We need to Arduino Run a program , This program will periodically check the serial port , If there is data available , It is processed . Let's take a look at the sketch we used to verify the Bluetooth connection .

void setup() {
 Serial1.begin(9600);
 while(!Serial1);
 Serial1.println("01Hello sir!");
}


String input;

void loop() {
 if(Serial1.available() > 0) {
   input = Serial1.readString();
   switch(input.charAt(0)) {
     case ‘n’:
       //ultrasonic scan
     case ‘m’:
       //measure distance
     //and so on...

   }
 }
}

Once we're in Input There is data in the variable , We can use it to do all kinds of things . for example , If we want to check the type of command that just arrived , We can use input.charAt(0). This built-in function will return a string input First character of , This character will correspond to a command in the above table .

Please note that , Usually , Every time you want to upload a new sketch to Arduino when , You must disconnect HC-05 modular , however , Because we use Arduino Mega, We have 4 Separate hardware serial ports are available ! therefore , We just need to connect Bluetooth to one of the other Bluetooth , We can use them at the same time .

Another thing to remember is , Via Bluetooth Arduino Connect to PC May not always reset Arduino, This is related to the adoption of USB The connection is different . Start correctly , You must press... Manually Arduino Upper RESET Button !

Conclusion

Hexapod It's a rather complicated project . As usual , There's room for improvement . at present , The only sensor on board is the ultrasonic range finder , But because of Arduino Mega With so much free processing power , We can add other sensors to get more advanced functions .

this is it —— You finished. ArduPod The last tutorial of ! The three part tutorial should be as comprehensive as possible . If you have any questions or suggestions for improvement , Please feel free to check my GitHub On Share your thoughts . You can go to ArduPod In the repository “ problem ” Tab and open a new question . When you're involved , If you like this project , You can leave a star here . Of course , You decide to build your own ArduPod, Remember to share your creation with the world !

原网站

版权声明
本文为[acktomas]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060022589813.html