# Presentation: 191229

## Robotics with the XBC ControllerSession 3

- Instructor: David Culp
- Email: _[culpd](mailto:culpd@cfbisd.edu)__[@](mailto:culpd@cfbisd.edu)__[cfbisd](mailto:culpd@cfbisd.edu)__[.](mailto:culpd@cfbisd.edu)__[edu](mailto:culpd@cfbisd.edu)_

## Learning Goals

- The student will learn about variables and data types in Interactive C, analog sensors, for-next loops, and IC library functions.

## A review of where we have been....

- Basic C programming...
- All C programs begin execution at the “main” function.
- Blocks of code are contained in curly braces.
- Example...
- void main()
- {
- printf(“Hello XBC”)
- }

## Slightly more advanced C programming

- Looping
- With an ‘If...then’ branch...
- Takes the form:
- if (<*expression*>)<*statement-1*>else <*statement-2*>
- <expression> = a test
- <statement-1> = a block of statements to execute if <expression> is TRUE
- else <statement-2> = an optional group of statements to execute if <expression> is FALSE.

## While loops.....

- While loops are the basic looping structure in C.
- Takes the form:
- while (<*expression*>)<*statement*>
- (<*expression*>) = a test
- <*statement> = *C program statements to execute if (<*expression*>) evaluates to TRUE
- Multiple statements can be contained in braces { ...}

## A real Botball example...

- The students robot had to drive forward only a certain distance as quickly as possible.
- An ingenious switch and string device was used.
- String was tied off to the table.
- When string became taught it activated a switch, C code detected this and shut the motors off.

## A real Botball example continued...

- while (digital(10) == 0) // is the switch triggered
-   {
-     fd(0);
-     fd(2);
- }
- ao(); // if yes stop

## If – Then and while example...

- void main()
- {
-     while(1)
-       {
-         if (a_button() == 1)
-           {
-             printf(“A BUTTON PRESSED!!!");
-         }// end if
-     }// end while
- }// end main

## Digital sensors

- Return either a 0 or a 1.
- Only two states.
- Buttons and touch switches are the most common.
- Accessed with the digital() function.
- digital(<*port#*);
- Port# = ports 8-15
- Returns a 0 or a 1

## Motor control

- motor(<*motor_#*>, <*speed*>)
- ao();
- Turn all motors off
- fd(<*motor_#*>);
- Turn on motor_# in a “forward” direction.
- bk(<*motor_#*>);
- Turn on motor_# in a “backwards” direction.
- off(<*motor_#*>);
- Turn off motor_#

## Analog sensors

- Analog sensors return a range of values.
- Examples:
- Light sensors
- Range finding sensors
- Temperature sensors
- Pressure sensors
- Voltage sensors
- Sound level sensors

## Analog sensor resolution

- The **resolution** of an analog sensor is the smallest change it can detect in the quantity that it is measuring.
- Analog sensors return a number defined by the number of bits of resolution.
- For example, an 8 bit sensor can return 256 different results (0-255).

## Analog functions...

- Extremely simple to use in Interactive C.
- Function definitions as they appear in the IC manual:
-  int analog(int p)
- Returns an 8 bit (0-255) reading.
- p = port number
- int analog12(int p)
- Returns a 12 bit (0-4095) reading.
- p = port number
- Ports 0 and 1 are floating (high impedance input used with active sensors such as IR range finder which output a positive voltage less than 5 volts)
- Ports 2-6 have ‘pull-up’ resistors to 5 volts for passive sensors.
**YOU SHOULD NOT CONNECT TO ANALOG PORT 7!**
- Reserved for battery voltage monitoring.
- power_level() returns a floating pt. voltage value

## Using the interaction window

- Plug an infrared (**IR**) range finding sensor into analog port 1.
- Sometimes called an “ET” sensor.
- Returns a number **related to** the range to the nearest object.
- Sends an IR beam out and measures the angle of the reflected beam.
- Is insensitive to the color of the target object
- Click on the IC tab called “interaction”

## Using the interaction window

- At the bottom of the interaction window is a place to type IC commands.
- Make certain your XBC is plugged in and turned on.
- Hold the IR range finding sensor about 10-12 inches from an object.
- Type “analog(1);” into the interaction window and press return.
- IC should return an 8 bit number.
- Experiment by holding the sensor at different ranges.
- Also try the analog12() function.

## IR Range Finder Continued...

- Notice the number is not a range and that the response is not quite linear.
- Low values indicate a large distance (d)
- Result is approximately 1/(d)^2 and is useable only up to 4 inches
- Objects closer than 4 inches will appear to be farther away.

## A program that constantly reports IR sensor readings...

- void main()
- {
-     while(1)
-       {
-         display_clear();
-         printf("Range value: %d", analog(1));
-         sleep(.25);
-     }
- }

## What is with the weird “printf” statement?

- printf is a whole lesson latter in the course.
- In our case the line:
-  printf("Range value: %d", analog(1));
- Simply prints the results of the “analog(1)” function call.
- %d is a place holder for that number.  It tells the compiler “Hey, an integer number is going to be printed in this spot!”

## A short assignment

- Modify the previous program so that a value is only printed to the screen if the user presses the “a” button on the Gameboy.
- Hint – most of the program will remain the same.
- Hint – You only need to add something just before the display_clear() function.
- Hint – we learned about it last session and in our review today.
**	****	***** See solution at end**

## Variables and Data Types

- Variables are “place holders” in C.  They hold data.
- Think of them as boxes that can hold information.
- We can change and access that information.
- In C you MUST tell the compiler what type of information you wish to store in a variable.

## Data types in C.

**16-bit Integers**
- 16-bit integers are signified by the type indicator int. They are signed integers, and may be valued from -32,768 to +32,767 decimal.
**32-bit Integers**
- 32-bit integers are signified by the type indicator long. They are signed integers, and may be valued from -2,147,483,648 to +2,147,483,647 decimal.

## More Data Types

**32-bit Floating Point Numbers**
- Floating point numbers are signified by the type indicator float. They have approximately seven decimal digits of precision and are valued from about 10^-38 to 10^38.
**8-bit Characters**
- Characters are an 8-bit number signified by the type indicator char. A character's value typically represents a printable symbol using the standard ASCII character code, but this is not necessary; characters can be used to refer to arbitrary 8-bit numbers.

## More on variables

- All variables MUST have a name.
- The name should be descriptive
- Names are case sensitive
- Underscore character allowed _
- Usually used to separate words
- range_to_object
- Letters, numbers and the underscore may be used, but may not start with a number
- C keywords such as if, while, for etc... cannot be used as names
- Must be declared at the top level of a block.

## An example of using variables....

- void main()
- { // Calibrating the IR range finder
-     float distance;
-     float max_squared = 200.0;
-     while(b_button() == 0)
-       {
-         distance = sqrt(max_squared/(float)analog(1));
-         display_clear();
-         printf("Range: %f", distance);
-         sleep(.25);
-     }
- }

## Things to notice

- The variables were declared at the TOP of main.
- Each variable had a descriptive name.
- We can use variables to store the return information from functions.

## Variable scope

- All variables have a “scope” or the area in which they take precedence.
- If declared within a function or as an argument to a function it is local to that function and not available outside of it.
- If declared outside of a function then it is global and available to all functions.
- Local variables take precedence if a local and global variable have the same name.

## Variable scope example.

- // These variables are global...
- int a=10;
- int b=20;
- int c=30;
- void main()
- {
-     int c=100; // This variable is local
-     int answer;  // so is this one
-     answer = a + b + c;
-     printf("Answer = %d", answer);
-     //prints 130 because it uses the LOCAL copy of c.
- }

## Things to notice....

- Two variables had the same name.
- int c was declared globally outside of main.
- int c was also declared locally inside of main
- The copy of c that was local to main was used in the calculation

## Special notes on using the LONG data type.

- If a number is defined as LONG then the character L must appear at the end to tell the compiler this is a special LONG integer.
- For example, this does not work:
- void main()
- {
-     long result;
-     result = result + 1000;
- }
- This does:
- void main()
- {
-     long result;
-     result = result + 1000L;
- }

## More on LONG data types

- Only basic arithmetic and comparison operations are allowed.
- Bitwise and boolean operations and division are not supported.

## For-next loops...

- The syntax of a for loop is the following:
- for (<*expr-1*>;<*expr-2*>;<*expr-3*>)<*statement*>
- <*expr-1*> is an assignment
- <*expr-2*> is a relational expression
- <*expr-3*> is an increment or decrement of some manner
- <*statement*> is a group of C statements to be executed each time through the loop if <*expr-2*> evaluates to TRUE.

## Example of counting to 100...

- void main()
- {
-     int count;
-     for (count = 0;count <=100; count++)
-       {
-         display_clear();
-         printf("%d", count);
-         sleep(.1);
-     }// end the for loop
- }

## A more practical example....

- The following program will smoothly and slowly position a servo.
- void main()
- {
-     int current_position;
-     int desired_position=128;
-     enable_servos();
-     for (current_position = 0;current_position<= desired_position; current_position+=5)
-       {
-         display_clear();
-         set_servo_position(0,current_position);
-         printf("%d", current_position);
-         sleep(.1);
-     }// end the for loop
- }

## IC library functions

- IC has many built in functions called library functions.
- How to find the library functions in the IC manual.
- Reading the IC library files.

## Project assignment

- Mount two IR distance sensors on your robot.
- Place one on the left plugged into port 0 and one on the right plugged into port 1.
- When either IR sensor senses something within 6 inches it should back up and turn away.
- Use variables in the program.
- Keep track of the number of “hits” on each side and print that to the screen.
- The user should be able to stop the program by pressing the “a” button.

## void main()
{// Plug the left motor into port 2 – the right motor into port 0
    int left_hits;  // keeps track of the number of hits on each side
    int right_hits;
    sleep(3.0);
    while( a_button() == 0)
      {
        fd(0);// get us going forward
        fd(2);

        //print the number of hits on each side
        display_clear();
        printf("Left hits: %d\n", left_hits);
        printf("Right hits: %d\n", right_hits);

        if(analog(0) > 200) // is something close to the left side?
          {
            left_hits++;  // increment our left hit count
            bk(0);        // back up
            bk(2);
            sleep(.5);
            fd(2);       // turn right
            sleep(.5);
        }// end if

        if(analog(1) > 200) // is something close to the right side?
          {
            right_hits++;  // increment our right hit count
            bk(0);         // back up
            bk(2);
            sleep(.5);
            fd(0);        // turn left
            sleep(.5);
        }//end if
    }// end while                       
} // end main

- {// **Plug the left motor into port 2 – the right motor into port 0**
-     int left_hits;  // keeps track of the number of hits on each side
-     int right_hits;
-     sleep(3.0);
-     while( a_button() == 0)
-       {
-         fd(0);// get us going forward
-         fd(2);
-         //print the number of hits on each side
-         display_clear();
-         printf("Left hits: %d\n", left_hits);
-         printf("Right hits: %d\n", right_hits);
-         if(analog(0) > 200) // is something close to the left side?
-           {
-             left_hits++;  // increment our left hit count
-             bk(0);        // back up
-             bk(2);
-             sleep(.5);
-             fd(2);       // turn right
-             sleep(.5);
-         }// end if
-         if(analog(1) > 200) // is something close to the right side?
-           {
-             right_hits++;  // increment our right hit count
-             bk(0);         // back up
-             bk(2);
-             sleep(.5);
-             fd(0);        // turn left
-             sleep(.5);
-         }//end if
-     }// end while
- } // end main

## Solution to ‘A Short Assignment’ - IR sensor readings when A button Pressed

- void main()
- {
-     while(1)
-       {
-         if(a_button()==1){
- 		  display_clear();
-            printf("Range value: %d", analog(1));
-            sleep(.25);
- 		  }
-        }
- }