Presentation is loading. Please wait.

Presentation is loading. Please wait.

RobotC – A Tutorial II Show: http://www.youtube.com/watch?v=5diNw4AUPjA to capture interest.

Similar presentations


Presentation on theme: "RobotC – A Tutorial II Show: http://www.youtube.com/watch?v=5diNw4AUPjA to capture interest."— Presentation transcript:

1 RobotC – A Tutorial II Show: to capture interest.

2 Learning from yesterday
The IDE Functions and usage of various panels Top Menubar Side Functions panel Code Window Error Window Compiling/Downloading the code Running the program C Programming Syntax Capitalization Whitespaces Comments Variables Boolean Algebra REVISION Yesterday, we learned about the IDE, including the various panels used and how to compile, download, and run the program. We also learned a bit about the C programming Syntax and Control Structures

3 Learning from yesterday
Control Structures Tasks Functions If-Else/Switch While/For Today we are going to look at specific commands and options available in RobotC for controlling the NXT REVISION

4 SECTION 3 Section Overview Reserved Words Sensor Configuration
Motors Timers LCD Display Sensor Configuration Debugger Usage Tasks Functions If-Else/Switch While/For SECTION 3 Today we will be talking about Reserved Words, Sensor Configuration, and using the Debugger

5 ROBOTC FEATURES Overview
RobotC has a variety of commands, interfaces and options which deal specifically with robots. Some of these are Reserved words like motor, timers (keywords) Sensor interfaces Live debugger ROBOTC FEATURES Talk about how Robot C is different from regular ANSI C because it has built in functionality dealing with robots: Motors, Timers, Sensor interfaces, and live debugger.

6 ROBOTC FEATURES Keywords
RobotC has a variety of keywords which are used for issuing specific commands to the NXT controller As it is not possible to cover all the commands in detail here, only the main ones will be discussed. Explore the rest of the options by using the help available within the programming environment or online version (as explained earlier) ROBOTC FEATURES Encourage students to view online help for more information on this section.

7 ROBOTC FEATURES Motors
Motor control – Turn on/off at a certain power level General Syntax motor[output] = power; Parameters Output – Determine the motor to affect. This can be motorA, motorB, motorC This command just gives power to the 3 output ports A, B, C in a certain fashion. This can also be fed to a circuit to control other devices Power – Determines the power at which the motor is to be run. This can take any integer value from -100 (full reverse) to 100 (full forward) Examples motor[motorA] = 60; //Run motor A at 60% power motor[motorB] = -50; //Run motor B in reverse at 50% motor[motorC] = 100; //Run motor C at full power forward ROBOTC FEATURES Motor control is obtained by using the motor keyword with the syntax as indicated. The two parameters are which output port to control (A, B, C) and the power level to provide. Go over the examples (read the comments)

8 Motors – 5 minute activity
Using the simple motor command, try to write a program that spins the RoboCar as fast as possible How fast does it rotate? (RPM) ROBOTC FEATURES Ask students to attempt this 5 minute activity.

9 Motors – 5 minute activity
How did you do? Here is one solution: task main() { motor[motorA] = 100; motor[motorB] = -100; while(true) ; } …where you turn both motors at full power, opposite direction. At this point, just take a moment to think of all the other factors which may have affected your spin rate (battery power, weight imbalance, friction, etc) Robust code accounts for as many uncertainties as possible ROBOTC FEATURES Discuss the “correct” code as well as ask for other ideas on how to do this. Talk about how many different factors go into the speed at which the robot spins, and ask them to remember these items when it comes to programming for the hovercraft.

10 ROBOTC FEATURES Timers – Wait Timers
The wait commands allow you to insert delays into your program. Its like starting a stop watch and pause the execution of your program. The pause in execution means that the next command will not be executed till after the timer expires. However, the actions due to the commands already issued will continue. There are two commands related to this wait1Msec(wait_time); wait10Msec(wait_time); Parameters wait_time – Refers to the time for which the program pauses before proceeding to the next step. The units are either milliseconds (1/1000 of sec) or 10s of milliseconds (1/100 of sec) ROBOTC FEATURES The wait command allows you to wait for a specified number of milliseconds.

11 ROBOTC FEATURES Timers – Examples
The following examples uses the wait function to allow the motors to operate for 1 second at a time. ROBOTC FEATURES Explain the code by reading the comments.

12 Motors – 5 minute activity
Using the encoder command, try to write a program that rolls the car forward a distance of approximately 2 feet ROBOTC FEATURES Ask students to conduct this 5 minute activity.

13 Motors – 5 minute activity
How did you do? Does your code look something like this? task main() { motor[motorA] = 100; motor[motorB] = -100; wait1Msec(2000); // however long it takes to go 2ft } ROBOTC FEATURES Explain that this code will run both motor A and B at 75% power until one of them reaches 1080 degrees. Ask for other implementations.

14 ROBOTC FEATURES LCD Display
The LCD display on the NXT is a 6 line display that can be controlled via functions in RobotC. It can support a display of 16 characters per line The display is an extremely useful resource during the debugging phase, for observing the values of various inputs and outputs. If left unmodified, the LCD will display the readings of the input sensors and the output power level of the motors. ROBOTC FEATURES Discuss the LCD display as a valuable debugging tool when you’re actually running code on it. If you don’t have anything specific running on the LCD, it will display the sensor readings and output power levels.

15 LCD Display - Functions
Two functions that may be useful to access the LCD are nxtDisplayStringAt(xPos,yPos,text,var1,var2,var3) – print text eraseDisplay() – clear the NXT display Parameters xPos - Number of pixels away from the left of the display that you want your string to be printed at. yPos - This integer value is the number of pixels away from the bottom of the display that you want your string to be printed at. text - The text parameter is what shows up on the screen. This will be a string enclosed in quotes up to 16 characters. You may also display up to 3 variables in this string by adding %d, %f (conversion specifications) up to three times. var1, var2, var3 - These (optional) parameters define which variables will be displayed to the screen and each must correspond to a separate %d, %f within the text parameter. ROBOTC FEATURES The LCD display function’s syntax is shown in the slide. The parameters are xPosition, yPosition, text, and 3 variable entries, as outlined in the next few slides.

16 ROBOTC FEATURES Motors - Encoder
Each standard Lego motor has an inbuilt encoder that can be used to measure the amount the motor has turned by, or turn the motor by a specific number of degrees General Syntax (to obtain the reading) myVar = nMotorEncoder[output] General Syntax (set the turning amount) nMotorEncoderTarget[output] = numCounts Parameters output – Determine the motor to affect. numCounts – The number of encoder counts that the motor must turn before stopping myVar – a variable that gets assigned the current value of the encoder ROBOTC FEATURES Servo control is obtained by using the motor encoder keyword with the syntax as indicated. The two parameters are which output port to control (A, B, C) and the number of degrees to turn.

17 ROBOTC FEATURES Motors - Encoder
Encoder Example (To turn to desired value by setting) // Set degrees that motor A must turn to 1000 nMotorEncoderTarget[motorA] = 1000; // Turn on Motor A. It will automatically stop // after turning for the desired amount motor[motorA] = 75; ROBOTC FEATURES Go over the examples (read the comments) Motor A will turn to 1000 degrees at 75% power. Encoder Example (To turn to desired value by observation) // Turn on motorA until it has turned 1000 degrees motor[motorA] = 75; while(nMotorEncoder[motorA] <= 1000) ; motor[motorA] = 0; // requires explicit stop

18 Motors – 10 minute activity
Write a creative programming solution to navigate the following course – without using any sensors. Based on what you have already learned ROBOTC FEATURES 2 ft 1 ft Ask the students to conduct this 10 minute activity. 2 ft

19 Motors – 10 minute activity
Here are a couple of suggestions Go straight for a fixed time (calculated by trial and error) Then turn right and go further straight for some more time (again calculated by trial and error) Then turn left and go straight OR Measure the circumference of the wheel to get how much the car will travel in one revolution. Use this number and the distances mentioned on the track to get the desired number of revolutions before turning Set the encoder accordingly and GO! Mix the above 2 methods ROBOTC FEATURES Here are suggested ways of going about this problem, although the students may have other ideas.

20 ROBOTC FEATURES Sensor Interface
RobotC has an extremely powerful sensor interface which may be used to communicate with Lego and other third party sensors. Ideally, RobotC sensor interface provides an enormous degree of freedom to the programmer. It provides several options for configuring the sensor ports to Read the raw value – Mainly used for self designed sensors Communicate via the I2C interface – Mainly used by third party providers Work using standard protocols and thresholds with the standard Lego sensors ROBOTC FEATURES The sensors for the NXT provide three main modes of execution – raw value, I2C (digital) sensors, and standard calibration for LEGO sensors

21 Sensor Interface - Accessing
The sensor interface in RobotC may be accessed through the Robot Menu on top of the IDE. The steps for accessing the sensor menu are as follows ROBOTC FEATURES Click on the Robot Button on the top menubar and select the Motors and Sensors Setup box Perform the steps listed on the screen. The next slide shows the result.

22 Sensor Interface - Accessing
Click on the management tab. This brings up the options to select the kind of sensors that are displayed ROBOTC FEATURES Ensure that the screen looks the same way, and then go to the sensor tab. Tick the bottom 3 boxes. Unless you want to use old RCX Sensors

23 Sensor Interface - Accessing
A popup will occur as depicted. Choose the A/D sensor tab. A/D stands for Analog to Digital ROBOTC FEATURES Discuss the various areas of the application, and ask students to play with the values to see what sensors are built-in Type of sensors You can configure up to 4 sensors Fields for specifying the names of the sensors

24 Sensor Interface - Accessing
Give a name to the sensors you intend to use and configure it to a certain type from the drop box ROBOTC FEATURES Now have the students change to the values shown on the screen. Type of sensors This one is being configured as SONAR names given to the three sensors

25 Sensor Interface - Accessing
Click on OK. This will create some auto-generated lines of code at the top of the program. This means that the sensors have been configured for use in the program. ROBOTC FEATURES Allow students to see what code is auto generated at the top of the code window Observe, No line numbers Auto-generated code. DO NOT EDIT THIS Given sensor names

26 Sensor Interface - Accessing
After configuration, using the sensor values in the program is a trivial task — two methods of obtaining the sensor values: myVar = SensorValue(sensor_name) myVar = SensorRaw(sensor_name) The first method returns the configured sensor value. Second one returns the raw value. Parameters sensor_name – This denotes the name assigned to the sensor in the configuration step Both may be used to obtain sensor readings (either raw or calibrated) The choice of method depends upon intended use ROBOTC FEATURES Now that we have configured the sensors, we need to get sensor readings. There are two methods – Raw values and Configured Values.

27 ROBOTC FEATURES Sensor Interface
Each sensor after configuration has two types of values Raw value – This is the raw value that the NXT observes based on the voltage across the input port. Every sensor has a raw value reading. Varies between (10 bits) Sensor Value – Obtained after application of thresholds to the raw value based on the configuration. Range depends on the configuration. More apt as per application Example: For a sensor configured as a touch sensor ROBOTC FEATURES Here we discuss the difference between raw and calculated (calibrated) values. The main difference is that the range is changed to a more appropriate value. For example, a range of doesn’t make sense for a touch sensor that just needs to say “on” or “off”. That is why the sensor value shows only 0 or 1, while the raw value is spread over a much larger range. Raw Value 0-512 Sensor Value 1 State Released Pressed

28 ROBOTC FEATURES Sensors – 10 min activity
Configure the sensor on port 1 to be a light sensor. Write a snippet of code that looks at the sensor reading and displays a “Light!” or “Dark!” message on the NXT screen when the light sensor is over a light or dark surface. ROBOTC FEATURES Ask the students to do this 10 minute activity

29 ROBOTC FEATURES Sensors – 10 min activity
Did your program look like this?? ROBOTC FEATURES Explain that the top few lines are the auto generated code. Then mention that the first line (wait) allows the sensors to initialize and then so long the light sensor value is >45%, Light! Is shown on the NXT, and vice versa.

30 ROBOTC FEATURES Debugging
Debugging is one of the most difficult parts of writing code Fortunately, RobotC has an extremely powerful debugger, much better than other languages for similar functions ROBOTC FEATURES Explain that much of the time spent programming the NXT is actually spent debugging problematic code.

31 Debugger – Not Compiler
Debugging generally refers to solving logical fallacies in the code. The compiler will give ERROR messages ONLY for syntax errors. You cannot run a code with syntax errors The compiler does highlight potential logical flaws in the form of WARNINGS and INFO messages. But these MAY or MAY NOT be the source of the logical problems. It is a good practice to make sure you have fixed all warning and info messages as well. ROBOTC FEATURES Make the distinction that the compiler is designed to point out errors in SYNTAX, not logical fallacies or issues with misassigned variables. Do point out, however, that the compiler will point out some logical flaws, but not all.

32 ROBOTC FEATURES Debugging - Options
Compiling and loading the program on the brick will enable several new debug options which were previously disabled or inactive Each of these windows is significant for a particular kind of error tracking The most important ones are 1. Global Variables 2. NXT Devices 3. Task Status ROBOTC FEATURES In this screen, we are highlighting how to get to various debugging windows. The global variables, NXT devices, and Task Status are the most important, and you can select them one at a time from this toolbar.

33 ROBOTC FEATURES Debugging - Example
Consider the example on the next slide for the purpose of debugging There are intentionally created errors in that program Lets see if they can be identified using the debugger ROBOTC FEATURES

34 ROBOTC FEATURES The X’s you see are pointed out by the compiler, but before we get to those errors, we have an issue with our variables not being what they need to be. Say “Let’s use the debugger to find out”.

35 ROBOTC FEATURES Debugging
What errors can be identified from here?? This variable is not being updated, so mustn’t be assigned ROBOTC FEATURES Upon looking at the debugging windows, we observe that the variable light sensor is not being updated, so it must not actually be getting assigned. We also notice that two variables have the same value for whatever reason. Let us go back to the code. These variables have identical values assigned, but according to sensors; they should be different More clues …

36 Lets see how accurate we were
variable light_sensor is not assigned ROBOTC FEATURES variable dist_sensor is getting light_sensor reading Let’s see if we can track down our errors. We see that the light sensor variable is not assigned. We also see that we are giving the distance sensor the wrong reading. Thus we were correctly able to identify all errors

37 ROBOTC FEATURES Debugging
Lets see how the debugger looks with the corrected programs ROBOTC FEATURES All seem good and in correspondence When we look at the debugger again, we see that we are in sync. PERFECT!!!

38 Lets correct the program
Observe the color of these X’s. Recall from yesterday. These are simple information messages. Why do you think they are reported? The compiler is trying to tell you that though you have declared and assigned these variables, you have not used them anywhere in the program. So it is trying to save your memory and flag potential errors. Sometimes, you tend to declare a variable with the intention of using it but end up using the wrong variable with a similar name. This can lead to really unpredictable results. One of the most difficult logical errors to catch ROBOTC FEATURES Now that all our variables work the way we want, we should go back and look at the compiler error. Ask the students why they might be getting the errors. Then point out that the values are not used anywhere.

39 ROBOTC FEATURES Debugging
One of the major sources of problems is disconnection of an input sensor from the port, either due to a loose connection, or inadvertent connection to the wrong port In this example, the light sensor from port A is connected mistakenly to port C Observe how the raw value of port A is saturated at 1023 while there is an undesired value on port C ROBOTC FEATURES The most common source of errors are loose connections or misdefined variables.

40 ROBOTC FEATURES Debugging
One common problem with many codes is missing timing delays. Such mistakes cause a lot of confusion and undesirable results These are difficult to catch by using the debugging techniques discussed They can be better examined by using the step by step debugger of RobotC ROBOTC FEATURES Once you read the slide, talk about how we will go step by step to figure out what’s going on. These commands allow step by step execution, hence giving more control for analysis

41 ROBOTC FEATURES Debugging - Example
Consider a program that moves the car forward till the light sensor reading is above a threshold (i.e. it is bright). If it sees a shadow, or darkness, i.e. the value of the light sensor drops, it backs up for some distance and then tries again ROBOTC FEATURES This program has the error that as soon as the car sees the black line or black shadow, it stops rather than going back. Read the program description and the problem description. The next slide will start using the line-by-line debugger.

42 ROBOTC FEATURES Debugging - Example
Lets try to use the debugger stepping to solve the problem. We can see that if we select continuous update of the values, then the green line moves extremely fast and we are unable to understand anything. ROBOTC FEATURES Before we press anything, the values are being updated constantly, and the green line moves very quickly. In order to make sense of it, we need to somehow slow the system down.

43 ROBOTC FEATURES Debugging - Example
The way around this is to suspend the program by clicking the suspend button. This pauses the execution of the program leaving all the variables and sensors intact The sensor readings and motor tachometer readings keep getting updated even in the suspend mode ROBOTC FEATURES Then click the step into button. This will cause the green line to be replaced by a yellow one which will stay on a specific statement You are now using the stepping mode of the debugger We can use the suspend button to stop the program and then use the step into button to navigate the program line by line.

44 ROBOTC FEATURES Debugging - Example
Each successive pressing of the Step Into button will advance the program step by step ROBOTC FEATURES Every time you hit Step Into, the next appropriate statement will execute.

45 ROBOTC FEATURES Debugging - Example
Going through a few iterations in a stepwise manner, we can see that reason for the car to not back up is the lack of delay while running in the reverse direction This can be rectified by adding a simple delay command after issuing the commands for the car to go backward ROBOTC FEATURES When we go through the program step by step, we realize that we didn’t give the motors time to reverse.

46 ROBOTC FEATURES Common Errors What is the error in the code below?
There is no break statement. So all statements after case 2 will execute! So even though the motors are supposed to run at 20% power only, they will instantly cycle through 20%, 30% and finally 100%. So you will always see motors turned on at full power ROBOTC FEATURES Ask what the error is in the code on the screen. The explanation is provided in the animated portion.

47 ROBOTC FEATURES Common Errors What is the error in the code below?
In the if condition, the variable has to be checked to be equal to 30. So == should be used (binary operator) In the current form, the variable will be assigned the value 30 inside the if. This overall operation returns 30, which in Boolean terms is true. So motors will always run at 20% power ROBOTC FEATURES Ask what the error is in the code on the screen. The explanation is provided in the animated portion.

48 SECTION SUMMARY Summary In the final section, you learned
RobotC specific keywords and usage Sensor configuration and usage Use of the debugger and various methods of debugging This completes the basic tutorial on RobotC. You should now be familiar enough with the basic concepts to build sufficiently complex systems SECTION SUMMARY In conclusion, today we have covered some Robot-C specific areas including keywords, sensor configuration, and the various methods of debugging.

49 SECTION SUMMARY Help In case you need help
Have a look at Use the in-built help in the IDE Ask Google If you are still stuck, ask your TF/TA!!! …and like mentioned initially, always remember - your design and needs should guide the language and not the other way around!! SECTION SUMMARY

50 Questions??? QUESTIONS

51 Exercise Write a program make the RoboCar go around in circles of a certain fixed radius (say 1 ft) EXERCISE

52 Exercise Write a program make the RoboCar go straight for 2 feet, turn around, return to the start position, and repeat once more. EXERCISE

53 SECTION SUMMARY Exercise
Write a program that will move the RoboCar forward until it sees a second black line, then turn around three times and stop. SECTION SUMMARY

54 Backup Slides BACKUP SLIDES

55 Motors - Synchronization
Synchronization – Used to ensure movement of both motors in synchronization (either same speed or different) When the motors are not perfectly aligned, the program makes adjustments to their power to bring them together again. General Syntax (3 steps) nSyncedMotors = syncPair; nSyncedTurnRatio = ratio; motor[output] = power; Parameters syncPair – Denotes the pair of motors to synchronize. This can take values synchAB, synchAC, synchCB, synchCA and synchBA, synchNone. The first of these denotes the master and the second one the slave ratio – A value between +100 to -100 denotes the ratio of the speeds between the master and the slave. Negative denotes the opposite direction ROBOTC FEATURES

56 Motors - Synchronization
Synchronization Example // Synchronize motor A and B with A being the master and B being the slave nSyncedMotors = synchAB; // Specify the turn ratio. nSyncedTurnRatio = 50; // This means that the power of the slave motor (B here) must be 50% of the power to A // Specify the power of the master motor (motor A) motor[motorA] = 75; ROBOTC FEATURES

57 ROBOTC FEATURES Motors - Other
There are a variety of other degrees of control which can be implemented in motors. May not be useful in the immediate context but good to know. Use the help menu to get elaborated details bFloatDuringInactiveMotorPWM - Indicates whether to float the motor inputs or apply immediate brakes when attempting to stop nMotorRunState[] - Contains the state (idle, ramping up or down, steady state, holding encoder position while stopped) of a motor. bMotorReflected[] - Boolean flag to indicate whether motor direction should be ‘flipped’ or ‘reflected’ from the normal. nMotorPIDSpeedCtrl - Turn on the PID controller for that motor. ROBOTC FEATURES

58 Motors – PID Controller
Turn on the PID controller for that motor. The PID control adjusts the actual amount of power sent to a motor to match the desired value, specified in the program. General Syntax nMotorPIDSpeedCtrl[output] = optionValue; Parameters Output – Determine the motor to affect. optionValue – Enable or disable PID control for the given motor. This can take the value mtrNoReg to disable the PID or mtrSpeedReg to enable to PID Examples nMotorPIDSpeedCtrl[motorA] = mtrSpeedReg; motor[motorA] = 60; //Run motor A at 60 power level, regardless of the conditions ROBOTC FEATURES

59 Motors – 10 minute activity
Try the following activities Turn on the PID controller for the motors. Run the motors at speeds less than 100 (say 50%). Try varying the weight on the car by adding or removing something. Does it still run at the same speed? Do you see the PID controller working? Repeat the activity done before (of spinning the car) by synchronizing the two motors in opposite direction ROBOTC FEATURES

60 Sensor Interface - Advanced
In case the type of sensor need to be changed dynamically, based on some other input parameters, there are several other methods to configure sensors, const tSensors sensor_name = sensor_port; SensorType[sensor_name] = sensor_type; Parameters Sensor_port – The input port to which the sensor is connected (S1, S2, S3 or S4) Sensor_type – The type of configuration for the sensor (similar to dropdown menu on the previous slides) Example const tSensors myOtherTouchSensor = S3; SensorType[myOtherTouchSensor] = sensorTouch; This command configures the input from port 3 to behave as a touch sensor input ROBOTC FEATURES

61 Debugging – Sensor values revisited
Recall the previous discussion about the difference between the raw value and the sensor value. In the following example, the same light sensor was connected to port 1 and under identical circumstances configured as an ‘active light sensor’ and a Sound sensor. It can be clearly seen that despite the raw value being the same (as expected, due to the same circumstances), the sensor value is different, because it is configured differently ROBOTC FEATURES

62 Exercise Write a program that has the capability of navigating the given maze using just a touch sensor and the internal capability of the Lego motor to measure the angle. (Hint: its not as complex as it looks) start EXERCISE finish

63 Exercise Can this navigation be done using just a single light sensor (no line to follow here)? If yes, how? If not, then under what conditions or with what modifications to the maze would it be possible? start EXERCISE finish

64 SECTION SUMMARY Exercise
Write a program that is capable of following a thin black line (around 1”) on a black background. Your program should be robust enough to do this task regardless of the shape that the line makes. The fastest team wins! SECTION SUMMARY

65 SECTION SUMMARY Exercise
If the line was 4” thick instead of 1”. How can you improve your program? Can it go faster now? Does your logic change? SECTION SUMMARY


Download ppt "RobotC – A Tutorial II Show: http://www.youtube.com/watch?v=5diNw4AUPjA to capture interest."

Similar presentations


Ads by Google