Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Задани на лабораторные работы. ПРК / Professional Microsoft Robotics Developer Studio

.pdf
Скачиваний:
126
Добавлен:
20.04.2015
Размер:
16.82 Mб
Скачать

www.it-ebooks.info

Chapter 17: Writing New Hardware Services

Then you can use the methods in your code, as in the following example for the Integrator robot, which handles output devices:

///<summary>

///SetActuators Handler

///</summary>

///<param name=”update”></param>

///<returns></returns>

///NOTE: Do NOT send commands to Motors or Reserved Pins this way! [ServiceHandler(ServiceHandlerBehavior.Exclusive)]

public virtual IEnumerator<ITask> SetActuatorsHandler(

brick.SetActuators update)

{

foreach (brick.Device d in update.Body.Outputs)

{

// Only Digital devices are handled here if (util.IsDigitalDevice(d))

{

if (d.Function == brick.DeviceFunctions.LED)

{

_state.LEDs = util.UpdateBitmask(_state.LEDs, LEDIds, d.HardwareIdentifer, d.State);

}

// Now set the pin util.UpdateDeviceStateInList(_state.Actuators,

d.HardwareIdentifer, d.State); _control.SetPin(d.Pin, d.State);

}

}

update.ResponsePort.Post(DefaultUpdateResponseType.Instance); yield break;

}

This code sets output pins using SetPin (which is discussed later), but along the way it checks for LEDs so that it can maintain the state of the LEDs property. It also has to update the device list in the state to reflect the changes. These tasks are made easier by the utility functions.

Adding Embedded Resources

It is not possible to include embedded resources, i.e., XSLT files, in a Proxy DLL. An XSLT file for displaying the generic brick state is included with the solution, but it does not appear in the Proxy. This file has to be manually copied over to any new implementation of the generic brick and added as an embedded resource in the new service.

Note that all service implementations based on the generic brick use the same data type for their state — GenericBrickState. Therefore, the XSLT file can be identical for all robots based on the generic brick. Even the name of the robot can be read from the state.

The XSLT file supplied with this chapter includes code to collapse the Drive Power, Sensors, and Actuators sections of the page. This JavaScript was shamelessly copied from the MRDS Debug and Trace Messages page. The resulting output looks like Figure 17-1 for the Integrator robot discussed in the next section.

753

www.it-ebooks.info

Part IV: Robotics Hardware

Figure 17-1

In Figure 17-1, the Drive Power section has already been collapsed, which you can tell from the small down-arrow next to the heading. The Sensors and Actuators sections show all of the devices that are defined for the robot, including their current values. Note that for simplicity, the state of digital devices is shown as 1 or 0 instead of true or false. The Value field is always maintained in sync with the State field for digital devices, and this is one reason why.

The Integrator Robot

The Integrator robot from Picblok (www.picblokcorporation.com) is designed for use in teaching basic robotics. It uses a PICAXE chip as its onboard controller, and in elementary courses on robotics it is programmed directly in BASIC.

By plugging in a ZX-Bluetooth module from Innovative Experiment Co. Ltd (www.inexglobal.com), the robot can be controlled remotely. Other Bluetooth modules are available that would work just as well. This one is quite cheap, although it is fixed at 9600 baud.

An Integrator robot is shown in Figure 17-2 (on the left). They come in a variety of colors with a clear plastic lid so you can see the circuit board (and in particular the LEDs) inside. The “face” has infrared LEDs and an IR sensor to detect obstacles, as well as two LEDs that flash menacingly when an obstacle is detected. The robot on the right in Figure 17-2 is shown without the lid, and the Bluetooth module has been removed (it fits inside the lid); the PICAXE-18X microcontroller is on a daughterboard in the center of this picture. It is an 18-pin chip based on the Microchip PIC16F88 and runs at 8 mHz.

754

www.it-ebooks.info

Chapter 17: Writing New Hardware Services

Figure 17-2

The PICAXE-18X has a total of eight outputs and five input pins. The pinout for the chip is shown in Figure 17-3. Note that although most of the I/O pins are reconfigurable on the chip, the PICAXE firmware assigns fixed functions to the majority of them.

PICAXE-18X

ADC 2 / Input 2

 

1

 

18

 

Input 1 / ADC 1

 

 

 

Serial Out

 

2

17

 

Input 0 / ADC 0 / Infrain

 

 

Serial In

 

3

16

 

Input 7 / Keyboard data

 

 

Reset

 

4

15

 

Input 6 / Keyboard clock

 

 

OV

 

5

14

 

V

 

 

Output O

 

6

13

 

Output 7

 

 

Output 1 / i2c sda

 

7

12

 

Output 6

 

 

Output 2

 

8

11

 

Output 5

 

 

Output 3 / pwm 3

 

9

10

 

Output 4 / i2c scl

 

 

 

 

 

 

 

 

 

Figure 17-3

The Inex ZX-Bluetooth module enables the robot to operate wirelessly. This connects to the Input 2 pin and Output 4 pin on the PICAXE — not the pins marked Serial In and Serial Out in Figure 17-3, which are used to program the chip. (There is no particular reason for this choice of pins. They were just available pins.)

The ZX module runs at a fixed baud rate of 9600. Serial communication uses the SerIn and SerOut commands in BASIC. These commands do bit banging — that is, they input and output individual bits on the specified pins. Consequently, they are not 100% reliable, and the chip cannot perform other tasks while it is doing serial I/O.

Because it is a very simple robot, the motors can only be on or off; there is no speed control. Enough hardware is built into the robot to enable it to do simple tasks, and programs can easily be downloaded to its flash memory.

755

www.it-ebooks.info

Part IV: Robotics Hardware

Integrator Robot Monitor Program

All robots controlled using MRDS must have an onboard “monitor” program to communicate with the MRDS services running on your PC. (Or they must have their own onboard PC running MRDS.) This is explained in Chapter 13.

The first step in setting up new robot hardware, therefore, is to develop the monitor program, unless one already exists. (The Hemisson robot discussed later in the chapter already has a built-in monitor program so this step is not required.)

PICAXE Programming Editor

The Integrator uses a PICAXE chip, and a free integrated development environment (IDE) for this chip can be downloaded from the website (www.picaxe.co.uk). The PICAXE Programming Editor uses a simplified version of BASIC. A sample screenshot is shown in Figure 17-4. It also has a Flowchart mode in which you can create programs by using block diagrams, and a Logic mode for creating circuit diagrams, but these are not relevant so they are not shown.

Figure 17-4

A simulator is built into the PICAXE Programming Editor. This is useful for teaching students about microcontrollers, but it is also very handy for debugging because you can step through your code one line at a time; view all of the registers and output pins; change the values on input pins; and simulate serial I/O. You can also adjust the execution speed to run your program in “slow motion.”

756

www.it-ebooks.info

Chapter 17: Writing New Hardware Services

Downloading programs to the chip is very simple. The programming cable has a standard 9-pin serial connector on one end that you plug into a serial port on your PC, and a 3.5mm stereo plug on the other end that plugs into the back of the robot. From the editor menu, you click PICAXE Run, or click the Run icon, or press F5 to start the download. As soon as the download is complete, the program begins executing on the robot.

This is not a tutorial on programming PICAXE chips. You should find the commented code provided with this chapter easy enough to read. Full documentation for the PICAXE family, including the BASIC dialect that it uses, is available from the PICAXE website.

Pin Assignments

To write the code, you need to know the pin assignments for the various I/O devices. The PICAXE refers to pins by number. However, the numbers of the pins used by the output functions (High, Low, Outpins, Outpinx, SerOut) overlap with the numbers used for the input functions (Pins, Pinx, SerIn).

Because there are only 18 pins on the chip, and some of these are required for power, ground, reset, and the serial port for programming, there are only five inputs instead of eight. The Integrator robot pin assignments are shown in the following table. Please note that the term pin here is a logical pin number, not a physical pin number on the chip.

Pin

Input

Output

 

 

 

0

Infrared Remote Control

Left Motor Backward

1

Microphone

Left Motor Forward

2

Bluetooth Serial In (Reserved)

Right Motor Backward

3

(Unavailable)

Right Motor Forward

4

(Unavailable)

Bluetooth Serial Out (Reserved)

5

(Unavailable)

LED 1 (Available for use)

6

IR Obstacle Sensor

LED 2 (Available for use)

7

(Available for use)

Buzzer

 

 

 

Notice that the motors are controlled using four pins. There is no speed control — only forward, backward, and stop — for each motor. (Although the PIC16F88 chip has PWM commands and onboard timers, these cannot be used on the PICAXE due to the way that the serial I/O is implemented, so it is not possible to modulate the speed of the motors.)

The Main Loop

You can look at the source code for the monitor program even if you do not have the PICAXE editor because it is an ASCII text file: ProMRDS\Chapter17\Integrator\Monitor\Monitor.bas.

The code begins by setting the clock frequency on the microcontroller to 8 mHz. This is necessary in order to use the ZX-Bluetooth module, which runs at 9600 baud, because the maximum baud rate in the

757

www.it-ebooks.info

Part IV: Robotics Hardware

PICAXE firmware is 4800 at the default clock speed of 4 mHz. By doubling the clock speed, the baud rate also doubles. This is an important “trick”:

Start:

IMPORTANT NOTE:

The clock frequency is 4 mHz by default.

Changing it to 8 mHz is necessary to double

the baud rate from the maximum on a PICAXE

of 4800 to 9600.

The ZX-Bluetooth module has a fixed baud

rate of 9600.

If this is the first time you have loaded the

program, you might have to change your config

in the Programming Editor to 8 mHz or you will

not be able to download.

SetFreq m8

‘ Perform a soft reset initially b0 = “#”

pause 20

goto SoftReset

In the PICAXE editor, you can set the clock speed for downloading. It defaults to 4 mHz. Once you have downloaded a program that sets the speed to 8 mHz, you will have to change the configuration to match or any subsequent attempt to download will fail.

The code now enters the MainLoop, which it executes forever (or at least until you turn the power off). It spends most of its time waiting for a new character to arrive at the serial input via Bluetooth. It then executes the equivalent of a large switch statement based on the command (character) that it received. The code for the MainLoop is as follows:

MainLoop:

Read from serial port serin SERIAL_IN,T9600_8,cmd

Keep a copy of the command

This allows the original command to be echoed b6 = cmd

Convert to uppercase for ease of human use if cmd > 95 then

cmd = cmd & %01011111 endif

Select the command based on the ASCII code.

For efficiency, these should be in the order

that they are most commonly used.

NOTE: Using digits (numeric keypad) might be

good for a user on a keyboard, but it can make

758

www.it-ebooks.info

Chapter 17: Writing New Hardware Services

the protocol “fragile”. If a command is missed,

its parameter will be read as a command!

if cmd=” “ or cmd=CR then cmdStop if cmd=”W” then cmdForward

if cmd=”D” then cmdRight if cmd=”A” then cmdLeft

if cmd=”,” or cmd=”<” then cmdRotateLeft if cmd=”.” or cmd=”>” then cmdRotateRight if cmd=”[“ or cmd=”{“ then cmdBackLeft if cmd=”]” or cmd=”}” then cmdBackRight if cmd=”S” then cmdBackward

if cmd=”I” then ReadPins if cmd=”P” then ReadPin if cmd=”H” then SetPin if cmd=”L” then SetPin if cmd=”O” then SetPins if cmd=”X” then Execute if cmd=”B” then Beep

if cmd=”V” then Version if cmd=”+” then SoftReset

Beep on invalid command high BUZZER

pause 75 low BUZZER pause 10

Send back an error message

serout SERIAL_OUT,T9600_8,(“? Invalid”,CR,LF)

goto MainLoop

If the character does not match any of the known commands, then the program beeps the buzzer and returns an error message. Error messages all begin with a question mark. This is the last section of code before returning to the top of the MainLoop. Note that BUZZER and SERIAL_OUT are symbolic values that are defined at the top of the program to enhance maintainability.

The monitor program was initially designed and tested by using HyperTerminal. This enabled the code to be tested prior to writing the MRDS services. One consequence of this approach is that the robot can actually be driven using the keyboard. In particular, the A, S, D, and W keys are used to control the motors. These keys are commonly used in first-person shooter games, so most children are familiar with them. The spacebar and Enter keys both cause the robot to stop.

The commands are not case-sensitive. (The code in MainLoop takes care of converting to uppercase.) To acknowledge a command, the Integrator echoes back the command followed by a carriage return (CR) and linefeed (LF). When you are using a terminal emulator, this is very handy because you can see the commands that you typed and each one appears on a new line in the emulator window.

759

www.it-ebooks.info

Part IV: Robotics Hardware

Protocol Commands

The “protocol” is extremely simple, and consequently it is not robust if communication is unreliable. Most commands consist of a single character. A few commands have a parameter, which is one or two hexadecimal digits. The full list of Integrator Protocol commands is provided in the following table:

Code

Parameter

Meaning

 

 

 

Space or CR

 

Stop

A

 

Turn Left Forwards1

B

 

Beep (Takes 200 ms to execute)

D

 

Turn Right Forwards1

H

Pin (0-7)

High (Set pin to 1)

I

 

Input (Read all pins)

L

Pin (0-7)

Low (Set pin to 0)

O

xx (Two hex digits)

Output (Write to all pins)

 

 

Note: This command is dangerous because it sets

 

 

the motors and also interferes with the operation of the

 

 

Bluetooth module.

P

Pin (0-7)

Pin Input

S

 

Drive Backward

V

 

Version (Displays version string)

W

 

Drive Forward

X

Behavior

Execute Behavior

 

L

Back up, Rotate Left (90 degrees)

 

R

Back up, Rotate Right (90 degrees)

 

U

Back up, Do U-Turn (180 degrees)

 

 

Note: The turn angles are only approximate

 

Behavior xx

Execute Behavior with Parameter (in hex)

 

Axx

Anti-Clockwise (Rotate Left2) xx units

 

Bxx

Backward xx units

 

Cxx

Clockwise (Rotate Right2) xx units

 

Fxx

Forward xx units

 

 

Note: The units in all cases are arbitrary

, or <

 

Rotate Left2

. or >

 

Rotate Right2

 

 

 

760

www.it-ebooks.info

 

 

 

Chapter 17: Writing New Hardware Services

 

 

 

 

 

Code

Parameter

Meaning

 

 

 

 

 

[ or {

 

Turn Left Backwards1

 

] or }

 

Turn Right Backwards1

 

+

 

Soft Reset

 

 

 

 

1Turn operations are performed by leaving one motor off and turning on the other motor in the appropriate direction so the robot pivots around the stationary wheel. There are four ways this can be done: Two methods move the robot forward and the other two move the robot backward.

2Rotate (spin) operations are performed by running the motors in opposite directions. There are only two possibilities: clockwise (right) or counterclockwise (left).

There is no point including all of the source code for command processing here. A couple of the command routines illustrate how the monitor program works. The version command, for example, returns a string that describes the robot and includes a version number:

Display the Monitor version

NOTE: Make sure to update the version number if this

code is changed.

Version:

serout SERIAL_OUT,T9600_8,(“RobotA Integrator V1.0”,CR,LF) goto MainLoop

The Brick service can use this information (if necessary) to adjust the way that it communicates with the brick and accommodate different revisions of the firmware.

Obviously, there must be commands to make the robot move. Because the Integrator doesn’t support speed control of the wheels, only a small set of motion operations are available. The code to move forward is as follows:

cmdForward: Gosub SendAck

Gosub ForwardMotors goto MainLoop

PICAXE BASIC commands are not case-sensitive.

The subroutine SendAck sends an acknowledgment back to the PC. It consists of the character that was received, followed by a carriage return and linefeed. When you are using HyperTerminal, this displays each command that you type on a new line. Then the ForwardMotors subroutine is called, and finally the code jumps back to the top of MainLoop.

You must configure the editor for the number of subroutines that you want to use in your code. For Monitor.bas, it must be set to 256. In addition, you cannot nest subroutines more than four levels deep because there is a limited amount of stack space. It is therefore common practice to use GoTo, rather than GoSub, and simply jump around in the code. This is not good coding practice, but it’s a matter of necessity.

761

www.it-ebooks.info

Part IV: Robotics Hardware

The ForwardMotors subroutine is quite short. It is implemented as a subroutine because it is used from more than one place in the code:

‘ Drive forwards ForwardMotors:

low 0 high 1 low 2 high 3 Return

The following table shows how the motors can be controlled using the four direction control pins: 0, 1, 2, and 3. There are nine possible combinations of motor directions that make sense. Another seven combinations make no sense because they would require a motor to go both forward and backward at the same time.

 

Left Motor

Right Motor

 

 

 

 

 

 

 

 

Function

Reverse Pin 0

Forward Pin 1

Reverse Pin 2

Forward Pin 3

Code

 

 

 

 

 

 

 

Stop

Low

Low

Low

Low

CR/SP

Forward

Low

High

Low

High

W

Backward

High

Low

High

Low

S

Turn Left

Low

Low

Low

High

A

Turn Right

Low

High

Low

Low

D

Rotate Left

High

Low

Low

High

<

Rotate Right

Low

High

High

Low

>

Back Left

High

Low

Low

Low

[

Back Right

Low

Low

High

Low

]

 

 

 

 

 

 

 

Other functions commonly used on a microcontroller are setting and reading pins (digital outputs and inputs). These two operations both require a parameter to be supplied in the command. This is read using the GetHex routine. The value is returned in a register, which has a symbolic name of param set at the top of the program to make the code more readable. The SetPin routine is as follows:

Set a single Pin

Set to high or low based on command (H or L)

Requires a pin number as parameter

SetPin:

gosub GetHex

if param > 7 then

serout SERIAL_OUT,T9600_8,(“? Bad Pin”,CR,LF) goto MainLoop

else

serout SERIAL_OUT,T9600_8,(cmd,CR,LF)

762