TETRIX PRIZM And Arduino IDE Reference Guide

Transcription

TETRIX PRIZM andArduino IDEReference GuideUnderstanding common PRIZM commands andfunctions in the Arduino Software (IDE)69955

Content creation by Aaron Locke.Desktop publishing by Todd McGeorge. 2018 Pitsco, Inc., 915 E. Jefferson, Pittsburg, KS 66762All rights reserved. This product and related documentation are protected by copyright and are distributed under licenses restricting theiruse, copying, and distribution. No part of this product or related documentation may be reproduced in any form by any means withoutprior written authorization of Pitsco, Inc.All other product names mentioned herein might be the trademarks of their respective owners.V1.006/18

Table of ContentsPRIZM Controller Commands.2LED Commands.3PRIZM Status Commands.3DC Motor Commands.4DC Motor Encoder Commands.5-7Servo Commands.8-9Sensor Commands.10Logic Commands. 11-12Loop Commands. 13-14Variable Commands. 15-16Function Commands. 17-18Time Commands.19Serial Monitor Commands.20

TETRIX PRIZM and Arduino IDE Reference GuideCommandSyntaxPRIZM Controller CommandsPurposeLocation in SketchInclude the PRIZM library#include PRIZM.h Includes the PRIZM library inthe sketch so that Arduino canrecognize PRIZM functions. Usually goes before the voidsetup() command.Instantiate PRIZMPRIZM prizm; Instantiates the PRIZM object so itsfunctions can be used. Usually goes before the voidsetup() command. Initializes the PRIZM controller. Usually is one of the firstcommands in the void setup()section.PRIZM beginprizm.PrizmBegin(); Must come before any prizm.commands. Terminates the program runningon PRIZM and resets the PRIZMcontroller.PRIZM endprizm.PrizmEnd();This sketch shows the proper use and placement of the PRIZM controller commands.2 Usually is found somewhere in themain loop to stop the program. At times it might be necessary tohave this command in the voidsetup() section. For example, in the void setup()section, you could read thebattery voltage, and if it is toolow, you could stop the programbefore it has a chance to doanything else.

LED and PRIZM Status CommandsCommandSyntaxTETRIX PRIZM and Arduino IDE Reference GuidePurposeTurn on red LEDprizm.setRedLED(HIGH); Turn on PRIZM’s red LEDTurn off red LEDprizm.setRedLED(LOW); Turn off PRIZM’s red LEDTurn on green LEDprizm.setGreenLED(HIGH); Turn on PRIZM’s green LEDTurn off green LEDprizm.setGreenLED(LOW); Turn off PRIZM’s green LEDLocation in Sketch Usually, LED control commandsare found in the void loop()section of a sketch. In some situations, they could beused in the void setup() sectionbefore the sketch enters themain loop.This sketch shows how the LED commands can be used to manipulate PRIZM’s red and green LEDs.CommandRead the state of PRIZM’sStart buttonRead the voltage ofthe battery attached teryVoltage();Purpose Determines if PRIZM’s green Startbutton is pressed or not. Returns an integer value of 1 ifpressed and 0 if not pressed. Determines the voltage of thebattery attached to PRIZM. Returns an integer value(ex: 915 9.15 volts).Location in Sketch Can be used anywhere in asketch. Can be used anywhere in asketch.Although this is not a full sketch, these example statements show how the battery voltage and Start button commands can be used.3

TETRIX PRIZM and Arduino IDE Reference GuideCommandSyntaxDC Motor CommandsPurposeLocation inSketch Sets the power and direction of aspecified motor to make it rotateat a certain rate.Set DC motor powerprizm.setMotorPower(motor#, power); Range is from -100 to 100.motor# 1 or 2 Value of 0 indicates a coastingstop.power -100 to 100 or 125 Value of 125 indicates a hardbraking stop. Usually found in thevoid loop() sectionof a sketch. Often found incalled functions. Negative values reverse thedirection. Sets the power and direction ofboth motors to make them rotateat a certain rate.Set all DC motor powerssimultaneouslyprizm.setMotorPowers(power1, power2);power -100 to 100 or 125 Range is from -100 to 100. Value of 0 indicates a coastingstop. Value of 125 indicates a hardbraking stop. Usually found in thevoid loop() sectionof a sketch. Often found incalled functions. Negative values reverse thedirection. Inverts the rotation of the specifiedmotor.prizm.setMotorInvert(motor#, 1);Invert motor directionmotor# 1 or 2 Is used when two motors opposeeach other so that positive powervalues cause the same direction ofmotion. Usually found inthe void setup()section of a sketch. Value of 1 indicates invert while 0indicates no invert.This sketch uses DC motor commands to move a robot forward, pivot a robot, and stop a robot using different motor power levels.4

TETRIX PRIZM and Arduino IDE Reference GuideDC Motor Encoder CommandsCommandSyntaxPurposeLocation inSketch Precisely sets the speedof a motor in degrees persecond.prizm.setMotorSpeed(motor#, speed);Set the rotational speedof a DC motormotor# 1 or 2speed -720 to 720TorqueNADO accuracy: -630 to 630 Max speed is 720degrees per second, or2 rps. For TorqueNADO , amore accurate range is-630 to 630 degrees persecond. Usually foundin the voidloop() sectionof a sketch. Often foundin calledfunctions. Rotational speed will beconstant no matter thebattery voltage. Precisely sets the speedsof both motors indegrees per second.prizm.setMotorSpeeds(speed1, speed2);Set the rotational speedsof both DC motorssimultaneouslyspeed -720 to 720TorqueNADO accuracy: -630 to 630 Max speed is 720degrees per second, or2 rps. For TorqueNADO, a moreaccurate range is -630 to630 degrees per second. Rotational speed will beconstant no matter thebattery voltage.prizm.setMotorTarget(motor#, speed, target);Set a DC motor to atarget position at adesignated speedmotor# 1 or 2speed -720 to 720target -2147483648 to 2147483647Set both DC motorsto target positionssimultaneously atdesignated speeds Tells a motor to rotatea designated count at adesignated speed andthen stop in a holdingposition. Each count represents1/4 of a degree. Maximum rotation is2,147,483,647 counts,which is 536,870,912degrees or 1,491,308rotations.prizm.setMotorTargets(speed1, target1, speed2, target2); Tells both motors torotate designated countsat designated speedsand then stop in aholding position.speed -720 to 720 Each count represents1/4 of a degree.target -2147483648 to 2147483647 Maximum rotation is2,147,483,647 counts,which is 536,870,912degrees or 1,491,308rotations. Usually foundin the voidloop() sectionof a sketch. Often foundin calledfunctions. Usually foundin the voidloop() sectionof a sketch. Often foundin calledfunctions. Usually foundin the voidloop() sectionof a sketch. Often foundin calledfunctions.5

TETRIX PRIZM and Arduino IDE Reference GuideCommandSyntaxprizm.setMotorDegree(motor#, speed, degrees);Rotate a DC motor adesignated number ofdegrees at a designatedspeedRotate both DC motorsa designated number ofdegrees at designatedspeedsmotor# 1 or 2DC Motor Encoder CommandsPurpose Tells a motor to rotate adesignated number ofdegrees at a designatedspeed and then stop in aholding position.degrees -536870912 to 536870911 Maximum rotation is536,870,911 degrees,which is 1,491,308rotations.prizm.setMotorDegrees(speed1, degrees1, speed2,degrees2); Tells both motors torotate designatednumbers of degrees atdesignated speeds andthen stop in a holdingposition.speed -720 to 720speed -720 to 720degrees -536870912 to 536870911 Maximum rotation is536,870,911 degrees,which is 1,491,308rotations. Determines if a motoris busy carrying out amotor positioning taskfrom another command.prizm.readMotorBusy(motor#);Read motor busy statusmotor# 1 or 2 Can be used to keep aprogram from movingto the next commanduntil a motor is finishedcarrying out the previouspositioning task. Will return 1 for busy or 0for hold position. Eliminates the need touse a delay() commandto wait for the motor tocomplete its task.Location inSketch Usually found inthe void loop()section of asketch. Often found incalled functions. Usually found inthe void loop()section of asketch. Often found incalled functions. Usually found inthe void loop()section of asketch or a calledfunction. Often follows amotor positioningcommand as partof a loop to waitfor the motor tostop spinning. Reads the count value ofthe designated encoder. Values range from-2,147,483,648 ead encoder countencoder# 1 or 2 Clockwise rotationadds to the countand counterclockwiserotation subtracts fromthe count. Four encoder countsequal one degree ofrotation. 1,140 encoder countsequal one full motorrotation. Encoder counts start at 0at power-up and reset.6 Often foundin conditionalstatementsand loops thatperform a taskbased on theencoder count.

DC Motor Encoder CommandsCommandSyntaxTETRIX PRIZM and Arduino IDE Reference GuidePurposeLocation in Sketch Reads the degrees of rotationfor the designated encoder. Values range from-536,870,912 to d encoder degreesencoder# 1 or 2 Clockwise rotation adds to thecount and counterclockwiserotation subtracts from thecount. Often found in conditionalstatements and loops thatperform a task based onthe encoder count. 360 degrees equal one fullmotor rotation. Encoder counts start at 0 atpower-up and reset.prizm.resetEncoder(encoder#); Resets the encoder count backto 0. Often found after anencoder positioning taskhas completed and thecounter needs to be resetfor a new task. Resets the count for bothencoders back to 0. Often found after encoderpositioning tasks havecompleted and bothencoders need to be resetfor a new task.Reset an encoder countencoder# 1 or 2Reset both encodercountsprizm.resetEncoders();This sketch uses encoders to accurately move a robot specific distances at specific speeds.7

TETRIX PRIZM and Arduino IDE Reference GuideCommandSyntaxprizm.setServoSpeed(servo#, speed);Set servo motor speedservo# 1 to 6speed 0 to 100Set all servo motor speedssimultaneouslyprizm.setServoSpeeds(speed1, speed2,speed3, speed4, speed5, speed6);speed 0 to 100prizm.setServoPosition(servo#, degrees);Set standard servo motorpositionServo CommandsPurpose Sets the speed of a singleservo. The servo will default to a maxspeed of 100% if the servospeed is not set. Servo speed will remain thesame throughout the programuntil changed. Sets the speed of up to sixpossible servos attached toPRIZM at the same time. Servos will default to a maxspeed of 100% if a servo speedis not set. Servo speed will remain thesame throughout the programuntil changed. Sets the angular position of asingle servo.servo# 1 to 6Set all standard servomotor positionssimultaneously Often found in thevoid setup() sectionof a sketch to controlthe speed of a servothroughout theprogram. Often found in thevoid setup() sectionof a sketch to controlthe speed of a servothroughout theprogram. Can be found in thevoid setup() sectionto set the initialposition of a servo. Most often used in thevoid loop() section ofa sketch.degrees 0 to 180prizm.setServoPositions(degrees1,degrees2, degrees3, degrees4, degrees5,degrees6);Location in Sketch Sets the angular position of allstandard servos attached toPRIZM at the same time. Can be found in thevoid setup() sectionto set the initialposition of all servos. Can be used in thevoid loop() sectionof a sketch to movemultiple servossimultaneously.degrees 0 to 180 Reads the last position thatwas sent to a servo and returnsan integer value between 0and 180.prizm.readServoPosition(servo#);Read standard servopositionservo# 1 to 6returned value integer 0 to 180 This command doesn’t readthe actual position of theservo. It returns what was lastcommanded and assumes theservo made it to that position. The actual servo positionand returned value could bedifferent depending on theservo speed and whetherappropriate time was allowedfor the servo to reach thatposition. Useful for synchronizing twoservos. Useful for storing a servoposition for use later.8 Most often used in thevoid loop() section ofa sketch.

TETRIX PRIZM and Arduino IDE Reference GuideServo CommandsCommandSet continuous rotation(CR) stateSyntaxPurposeprizm.setCRServoState(CRservo#, state); Sets the on/off condition anddirection of a continuousrotation servo.CRservo# 1 or 2 A state value of -100 is acounterclockwise spin.state -100, 0, or 100 A state value of 100 is aclockwise spin.Location in Sketch Most often used in thevoid loop() section ofa sketch. A state value of 0 is off.This sketch uses servo commands to move servos to different positions and to rotate a continuous rotation servo.9

TETRIX PRIZM and Arduino IDE Reference GuideCommandSyntaxSensor CommandsPurposeLocation in Sketch Reads the digital output of the LineFinder Sensor.prizm.readLineSensor(port#) Value of 0 means light was reflected(light-colored surface).port# D2-D5 or A1-A3 Value of 1 means light was notreflected (dark-colored surface).Read line sensor Can be connected to any digitalport (D2-D5) or any analog portsconfigured as digital inputs (A1-A3).Read ultrasonic sensor incentimetersRead ultrasonic sensor ininchesprizm.readSonicSensorCM(port#) Is used to determine distance to anobject.port# D2-D5 or A1-A3 Reads the output of the UltrasonicSensor in centimeters (3-400 cm) orinches (2-150 in.) as an integer.prizm.readSonicSensorIN(port#)port# D2-D5 or A1-A3 Most often usedin the void loop()section of a sketch. Often used in aconditional or whileloop. Can be connected to any digitalport (D2-D5) or any analog portsconfigured as digital inputs (A1-A3).This sketch uses the Line Finder and Ultrasonic Sensors to follow a line until an obstacle is detected. When an obstacle is detected, therobot stops and waits for the obstacle to be removed before it continues following the line.10

TETRIX PRIZM and Arduino IDE Reference GuideLogic CommandsCommandSyntaxif(condition){do this;}If statementif(condition){ Runs a command or series ofcommands if a certain conditionis true. If the condition within theparentheses is true, then thestatements within the bracketsare run.if(condition){ Conditional logic statement thattests for a single condition.do this;}else {do this;}if(condition1){do this;}else if(condition2) {do this;If-else if statementLocation in Sketch Conditional logic statement thattests for a single condition.}do this;If-else statementPurpose Runs a command or seriesof commands if a certaincondition is true and runs adifferent command or series ofcommands if the condition isfalse. Most often used in the voidloop() section of a sketch or in acalled function. Conditional logic statement thattests for multiple conditions. Runs a command or series ofcommands depending on whichcondition is met.}else {do this;}equal to: not equal to: ! Comparison operatorsless than: less than or equal to: greater than: greater than or equal to: AndOrcomparison1 && comparison2comparison1 comparison2 Is used in comparisonexpressions to compare onevalue/variable on the left withanother value/variable on theright. Note: A single equal sign isused to assign a value. Twoequal signs are required forcomparison. Usually found in conditionalstatements and loop statementswhere they are used todetermine a condition. In both conditional and loopstatements, comparisons arefound inside parentheses. Logical operator that combinestwo or more comparisonexpressions into one. Both comparison expressionsmust be true for the overallexpression to be true. Logical operator that combinestwo or more comparisonexpressions into one. Usually found in conditionalstatements and loop statementsinside parentheses where theyare used to combine multiplecomparison statements. One or more comparisonexpressions must be true for theoverall expression to be true.11

TETRIX PRIZM and Arduino IDE Reference GuideCommandSyntaxLogic CommandsPurposeLocation in SketchThis sketch uses conditional statements to keep a robot from driving into an obstacle. Two variables are declared at the beginningto set an obstacle distance and a warning distance. The main loop starts with an if-else statement to determine if an obstacle is outof range, and a nested if statement (the second if statement) turns the green LED on if an obstacle is within the warning distance.Continuing in the true part of the if-else statement, the robot will drive forward at 35% power with the red LED off.The else part of the if-else statement is the false condition, meaning an obstacle has been detected within range. The LEDs arechanged to indicate the obstacle is detected, and the robot performs a slight pivot turn.The final if statement checks for two conditions using the or logical operator, and if either condition is true, the PRIZM ends, and theprogram is over. But as long as both conditions are false, the program repeats the main loop.12

TETRIX PRIZM and Arduino IDE Reference GuideLoop CommandsCommandMain loopSyntaxvoid loop() {}Purpose Contains the section of code that runsrepeatedly. No conditions must be met for this loop torun.Location in Sketch Comes after the void setup()section. Repeats a series of commands while thecondition inside the parentheses is met. The condition is tested before the loopruns.While loopwhile(condition){} If the condition inside the while loopparentheses is false, the loop will not run. While loops will repeat forever untilsomething changes – either a testedvariable in the condition or an externalfactor such as sensor data. Is similar to a while loop except thecondition is checked at the end of the loopinstead of the beginning.Do-while loopdo{} while (condition); Will repeat forever until the condition at theend of the loop is met. Can be understood as “do these things andthen, if a condition is true, do those thingsagain.” Do-while loops always run at least onetime. Is used to repeat a set of commands adesignated number of times. Most often used in the voidloop() section of a sketch or in acalled function. Is often used to gradually change the statusof an output device. A counter is usually used to terminatethe loop when a given condition for thatcounter is met.For loopfor (initialization; condition;increment) {} For loops are composed of threestatements: initialization, condition, andincrement. The initialization declares a variable foruse in the loop as a certain type and setsits initial value. The condition declares what must betrue for the loop to repeat. The increment changes the initializedvariable so the condition can be checkedagain, and the loop is repeated or exited.13

TETRIX PRIZM and Arduino IDE Reference GuideCommandSyntaxLoop CommandsPurposeLocation in SketchThis sketch utilizes four loops (main loop, for loop, while loop, and do-while loop) to keep a robot from crashing into an obstacle. Thefor loop gradually brings the robot up to speed as i increases by one each iteration of the loop up to 100% power. The while loop hasthe robot drive straight while the Ultrasonic Sensor reading is greater than 25 cm. When an obstacle is detected, the motors stop. Thedo-while loop pivots the robot until the obstacle is at least 100 cm away from the robot. When this happens, the robot stops and themain loop repeats, starting the entire process over again.14

TETRIX PRIZM and Arduino IDE Reference GuideVariable CommandsCommandSyntaxint variable value;Declare aninteger variableExamples:int minDist 0;int maxDist 600;Purpose Declares an integer type variableand sets its value. Variable names can be any letter/number combination that isn’t usedfor another command, function, orvalue in the Arduino IDE. Integer range is -32,768 and 32,768. Declares a long type variable andsets its value.long variable value;Declare a longvariableExamples:long speedOfLight 186000L;long E mass*speedOfLight*speedOfLight; Variable names can be any letter/number combination that isn’t usedfor another command, function, orvalue in the Arduino IDE. Long range is -2,147,483,648 to2,147,483,647. If doing math with integers, atleast one of the numbers must befollowed by an L, forcing it to be along variable. Declares a decimal number with 6-7decimal places of precision.float variable value;Declare afloating-pointvariableExamples:float x 3.14float circ x*10.16Location in Sketch Variable names can be any letter/number combination that isn’t usedfor another command, function, orvalue in the Arduino IDE. Floating-point decimals are oftenused for math applications wheredecimals matter. However, becauseTETRIX applications utilize integervalues, floating-point values mustbe converted to integers beforethey can be outputted to a devicesuch as a motor, servo, or encoder. When and where a variablecan be used depends on wherethe variable is declared in thesketch. Global variables: Are declared outside of afunction (including the voidsetup() and void loop()functions). Can be used anywhere in thesketch. Are generally declared beforethe void setup() section. Local variables: Are declared inside thefunction they belong to. Keeps other functions frominadvertently modifyingvariables used by anotherfunction. Can be declared in a for loopand is used only in that forloop. Assigns a value to a variable.variable value;Examples:dist prizm.readSonicSensorCM(3);Set a variablerate 2.54;x x 1;voltage prizm.readBatteryVoltage();circ 2*3.14*rad; A single equal sign assigns value,whereas a double equal signcompares one value to another. Make sure that the value assignedis of the same type as the declaredvariable. For example, if you have aninteger variable x equal to 1 andan integer value y equal to 2,and you set an integer variable zequal to x/y, then even though1/2 is equal to 0.5, z will beassigned a value of 0 because z isan integer variable. Global variables: Can happen anywhere in thesketch. Are generally manipulatedin the void loop() section orother functions. Local variables: Can happen only in thefunction they are declared in.15

TETRIX PRIZM and Arduino IDE Reference GuideCommandSyntaxVariable CommandsPurposeLocation in SketchThis sketch calculates the velocity of a robot in inches per second as it drives toward a finish line and then indicates the calculatedvelocity by flashing the red LED. The program uses both global and local variables to accomplish its tasks.16

TETRIX PRIZM and Arduino IDE Reference GuideFunction CommandsCommandSyntaxPurposeLocation in Sketch Allows user to create modularsections of code. Is useful for defining a repetitivetask so the code has to be writtenonly one time.void functionName() {Declare a calledfunction}functionName: any alpha-numericcombination that isn’t an ArduinoIDE command or variable name. Is useful for testing/troubleshooting code so specificsegments of the code can beisolated. Makes code more efficient,compact, and organized. Variables used in a called functionmust be global variables or localvariables for that function. Called functions must be declaredoutside the brackets for the voidsetup() and void loop() sections. They are commonly placed afterthe closing bracket for the voidloop() section. The void setup() and void loop()sections can be consideredfunctions. Calls a function to perform aspecific task.Call a functionPass values to acalled functionfunctionName(); Jumps out of the current locationin the sketch to run the calledfunction and then returns towhere the function was called.functionName(value1, valueX); Is used to pass variables or otherinformation to a called function.values: can be variables of any type,or other data to pass Values must be received bythe called function when it isdeclared.void functionName(value1, valueX) {Receive valuesfor a calledfunction}Returnreturn variableName; Can be anywhere in a sketchincluding within another function. Can be anywhere in a sketchincluding within another function. Is used to receive values passedfrom another function/section foruse within the function. Values are received in theparentheses of a called function. Returns a value from a function towhere the function was called. End of a called function.This sketch uses a called function to multiply two variables that are passed into it, and then it returns and displays the product of thetwo variables.17

TETRIX PRIZM and Arduino IDE Reference GuideCommandSyntaxFunction CommandsPurposeLocation in SketchThis sketch randomly chooses a direction and as long as there are no obstacles in that direction, the robot will move that direction.There are four called functions. Two of the functions (aboutTurn and forward) are called from two different locations in the mainloop.18

TETRIX PRIZM and Arduino IDE Reference GuideTime CommandsCommandSyntaxPurposeLocation in Sketch Pauses the program fordesignated time.Delay inmillisecondsdelay(milliseconds); Can be used to pause theprogram while another taskcompletes. Can be used anywhere in thesketch. 1 second equals 1,000milliseconds. Recalls the number ofmilliseconds that have expiredsince the program began running.Current timeindex Can be used to determine thetime between two eventsmillis() Can be used to time events/actions without pausing theprogram like a delay does. Itallows input or output actions tooccur during the designated timeinterval. Can be used anywhere in thesketch.This sketch uses the millis() command to display the days, hours, minutes, and seconds since the program started running in a0:00:00:00 format.19

TETRIX PRIZM and Arduino IDE Reference GuideCommandSet up serial monitorSyntaxSerial Monitor CommandsPurposeLocation in SketchSerial.begin(baud); Configures the serial monitor so itcan be used.baud: the data rate in bits persecond for data transmission Is used to communicate betweenPRIZM and a computer or otherdevice. Most often found in thevoid setup() section of asketch. A typical baud rate forcommunicating between PRIZMand a computer is 9600. Fasterbaud rates are possible but notnecessary.Display information in theserial monitorSerial.print(); Displays data, variables, sensordata, and text in the serial monitorassociated with the Arduino IDE. Can be used anywhereafter the Serial.begin()command. Is useful for debugging code,monitoring sensor data, checkingcalculations, and so on. Information to display should becontained inside the parentheses. Text-based information needs to besurrounded by quotes.Add a new line in theserial monitorSerial.println(); Starts a new line in the serialmonitor after displaying what is inparentheses. Can be used anywhereafter the Serial.begin()command.This sketch reads the data from the Ultrasonic Sensor and outputs it to the serial monitor. Data is outputted in the form of## Centimeters every 200 milliseconds.20

TETRIX PRIZM andArduino IDEReference GuideUnderstanding common PRIZM commands andfunctions in the Arduino Software (IDE)Call Toll-Free800 835 0686Visit Us Online atPitsco.com

TETRIX PRIZM and Arduino IDE Reference Guide DC Motor Commands 4. Command Syntax Purpose Location in Sketch Set the rotational speed of a DC motor prizm.setMotorSpeed(motor#, speed); motor# 1 or 2 speed -720 to 720 TorqueNADO accuracy: -630 to