CCA Programming and Electronics, Fall 2014

Instructor: Michael Shiloh
mshiloh@cca.edu
Office hours: Mondays  11-11:30 or by appointment

Tutors:

Jump to current homework assignment

Week 6 October 13 2014

  • Questions?
  • Reminder: What is policy on late homework? How is attendance taken?

For() loops and arrays

  • Do Problem (1) of Assignment 6
  • Explain arrays
  • Do Problem (2) of Assignment 6
  • Review arrays again

While() loops

  • Convert Melody tutorial to while loop
  • Convert Knight Rider tutorial to while loop

Processing graphing concepts

  • Do Problem (3) of Assignment 6
  • Explain frame rate
  • Do Problem (4) of Assignment 6

More practice

  • Problems 4, 5, and 6 from Jon’s assignment 6

Week 7 October 20 2014

  1. Arduino to Processing communication (graph)
  2. Objects

Homework

Assignment 7

  • Car class
  • Review graph
  • Control RGB

Week 8 October 27 2014

  • Review
    void setup()
    void draw()
    void loop()
    int x;
    float pi;
    width;
    height;
    • The difference between a test section and an assignment in a for() loop
    • Nested for() loops
  • Do problems 2 and 3 of Assignment 8 (create your own  Ball class)
  • Walk through Problem 4 ()
  • Do problems 4 and 5
  • Review: logical AND, OR, and NOT
  • Two potentiometers and Arduino

Homework due Week 9 November 3 2014

  1. If you did not finish them in class, do problems 2 through 6 of Assignment 8. A link to the assignment is here.
  2. In class you learned how to connect two potentiometers to Arduino. Draw the schematic for this. You may use a CAD program such as Fritzing (www.fritzing.org) or do this by hand, but it must be accurate and neat.
  3. Open this Processing example:
    Examples -> Libraries -> Minim -> PlayAFile
    This is a new Processing feature, the ability to play sound files.  We will use this example to review some concepts about classes and objects.

    1. The player class has a number of member functions, e.g. player.play(), just like your Car and Ball classes had member functions (drive(), display(), etc.). Identify 3 other functions that are members of the player class.
    2. Research the map() function. You’ve seen this before in the Arduino graph example. You can learn more about map() by reading the reference page at https://processing.org/reference/map_.html. Explain, to the best of your ability, what this line does:
      float x1 = map( i, 0, player.bufferSize(), 0, width );
    3. Explain, to the best of your ability, what the function player.right.get() does.
    4. Pong (and other games) sound clip can be found at http://opengameart.org in .ogg format. Since Minim can’t play files in this format, I have converted these files to .mp3 format, which you can download from here. Modify the program to play this sound clip instead. Include a listing of the Processing sketch in your homework.
  4. Next week in class we will create a pong game. You will need to know how to send multiple values from Arduino and how to read them in processing.
    1. Open this Arduino example:
      File -> Examples -> Communication -> SerialCallResponse
    2. This example uses 3 sensors: two analog sensors and one pushbutton. We will ignore the second analog sensor, and just use the light sensor and the button on the Proto Snap for the first and third sensor. Modify the Arduino sketch as necessary to read the light sensor and the button. Upload the Arduino sketch.
    3. Copy and paste the Processing sketch into a new Processing window. Run it. Don’t forget that you might have to change the serial port number in the line:
      String portName = Serial.list()[0];
      Verify that the circle moves when you shine light on the light sensor and turns black when you press the button.
    4. Modify the Processing sketch so it draws a rectangle (Pong paddle) instead of a circle. You can ignore the second sensor value since we don’t have a second sensor. Use the first sensor value to control the Y position, similar to the original game of Pong (https://en.wikipedia.org/wiki/Pong). Make your paddle a reasonable size and offset it a bit from the wall, just like the original Pong.
    5. Modify the Processing sketch so when you press the button on Proto Snap, the paddle changes to red.
    6. Include a listing of both your Processing and Arduino sketches in your homework.
  5. Bring in a cheap Halloween electronic decoration or toy. We will learn how to control this from your Arduino.

Week 9 November 3 2014

Announcements and Issues

  • Homework confusion
  • Project?

Review last week’s homework

  • LED question: default values, common anode, where to measure
  • With screenshots and code, please indicate which problem they belong to
  • Other questions?

Lab

  1. Pong
    1. Move paddle with potentiometers
      1. Wire up two potentiometers like we did in class last week
      2. Use SerialCallResponse to get the data from the two potentiometers
      3. Create a Paddle class to move the paddles according to the data from the potentiometers
      4. Integrate this with your Ball class to create the framework for Pong (don’t deal with hitting the paddle yet)

Homework due Week 10 November 10 2014

In this homework assignment you will create a simple game of Pong using your Arduino and Processing.

  • Your program must be clear, well organized, and well documented using comments
  • Your name must be in the file name of the program, something like michael_shiloh_pong_november_6_2014.pde
  • Your name also must be a comment in the first line of your program
  • Send me only your program .pde as an attachment. I will not give credit for anything else. If you are uncertain ask me before Sunday night

There seems to be some confusion so let me try to make this clear:

  1. Your homework is entirely on the blog. You should not refer to anything in Moodle.
  2. Send me ONLY .pde files.  Any homework sent as a .zip file will not be accepted.
  1. Create a Paddle class to move the paddles according to the data from the potentiometers
    1. Start with your earlier Car class
    2. A Paddle doesn’t drive across the screen; instead it moves up and down the screen, changing Y position but never changing X position. Instead of the Car’s drive() function you will need to create the Paddle’s function to change the Y position. You might call this the changeY() function. Unlike Car.drive() which drove automatically, Paddle.changeY() will need to be told what value to change the Y position to. This is similar to the Car() constructor, where you initialized the color, location, and speed by passing the information to the function:
      Car(color tempC, float tempXpos, float tempYpos, float tempXspeed)  {
        c = tempC;
        xpos = tempXpos;
        ypos = tempYpos;
        xspeed = tempXspeed;
      }
      

      But this time you need to change the Paddle’s Y position, so you might have something like this:

      changeY(float tempYpos)  {
        ypos = tempYpos;
      
      }
      

      Before you go further test this. You should be able to create paddles in different locations, and then to move them around by calling your Paddle.changeY() function.

    3. Now you need to integrate your Paddle class with the code from the Processing part of SerialCallResponse, so that you can move your paddles using the potentiometers. After SerialCallResponse does all the work to sort out the data from Arduino, what does it do with the resulting numbers? The answer is right here:
      // If we have 3 bytes:
      if (serialCount > 2 ) {
        xpos = serialInArray[0];
        ypos = serialInArray[1];
        fgcolor = serialInArray[2];
      

      Now in our case we don’t have an xpos, ypos, and fgcolor (remember that was for the ball), but instead we have the paddle Y positions, so instead you might have something like this:

      if (serialCount > 2 ) {
        leftPaddle.changeY (serialInArray[0]);
        rightPaddle.changeY (serialInArray[1]);
      

      Before you go further test this. Create two paddles, one each on the left and right hand sides of the screen, and then test that you can move them up and down by turning the potentiometers. Make sure each potentiometer moves only one paddle.

  2. The next step is to add a Ball from your Ball class. Initialize the ball to the middle of the screen, with some arbitrary x and y speeds. You will need to call the Ball’s draw() and drive() functions in your draw() function. Test this: the ball should appear in the middle of the screen and just “drive” to one side and vanish. The ball will bounce off the walls; that’s fine. We’ll adjust this later.
  3. Now you need to figure out when a ball hits a paddle.
    1. How do you know the position of the ball? It’s buried within the Ball object and is not visible outside, especially not to the Paddle object. You need to create a new function for the Ball class which reports (returns) its coordinates. Add the following two functions to your Ball class:
        
        float reportX() {
          return(xpos);
        }
        
        float reportY() {
          return(ypos);
        }
      

      Note that this is the first time we’ve created a function that doesn’t start with the word void! That’s because void signifies that a function doesn’t return (or report) anything, and this is the first time we are creating a function that does return something, namely, the ball’s location. Note also the new keyword return.
      Now in your draw() function add this line:

        println(ball.reportX() + "\t" + ball.reportY());
      

      Test. You will see no change on your canvas, but the message section of processing should show the ball’s position. You might want to turn off the printing of the Arduino numbers. Don’t delete that line, just make it a comment so that you can turn it back on later if you wish:

        //println(xpos + "\t" + ypos + "\t" + fgcolor);
      

      Don’t proceed until this is working properly and you understand how return() works.

    2. Now that you know how to get the ball’s location, you can send that information to the Paddle and have the paddle report whether it’s hit the ball or not. You’ll need to add a new function to the Paddle class, perhaps named detectContact(). This new function needs to be given information, namely the ball’s location, and it needs to return information, a TRUE or FALSE depending on whether the paddle hit the ball. The function might be something like:
      boolean detectContact(float x, float y){
        if (( x > xpos) && 
            (x < (xpos+10)) && 
            (y>ypos) && 
            (y<(ypos+30))){
          return true;
        } else {
          return false;
        }
      }

      The numbers 10 and 30 are the width and height of my paddle; it would be better to store these as variables within the Paddle object.

      This function is imperfect, because it doesn’t take into account the diameter of the ball. This is good enough for now.

      Finally you can use this new function along with the ball’s new function to detect hits. In your draw function you might have something like this:

      if (leftPaddle.detectContact(ball.reportX(), 
          ball.reportY()) == true {
        println("you hit the ball with the left paddle");
      }
      if (rightPaddle.detectContact(ball.reportX(),
          ball.reportY()) == true {
        println("you hit the ball with the right paddle");
      }
    3. If the ball hits a paddle, make the ball bounce off the paddleYou’ll need to add a bounce() function to the Ball object. I’ll let you figure out what that bounce() function should do, but here is how you might use it in the main draw() function:
      if (leftPaddle.detectContact(ball.reportX(), 
          ball.reportY()) == true ) {
        println("you hit the ball with the left paddle");
        ball.bounce();
      }
      if (rightPaddle.detectContact(ball.reportX(), 
          ball.reportY()) == true ) {
        println("you hit the ball with the right paddle");
        ball.bounce();
      }
    4. If the ball doesn’t hits a paddle, don’t let the ball bounce off the wallThat should be easy; just remove the code in the Ball drive() function that bounces off the walls. Retain the code that bounces off the ceiling, however.
  4. Now that you can detect the ball hitting the paddle, it’s time to keep score. This is actually a little tricky, because you need to keep track of which wall the ball hit. Try something like this:
    1. Add to the Ball class two new variables, perhaps hitLeftWall and hitRightWall. Make these variables boolean, which means that can have only two values, true or false. Initialize both variables to false:
      boolean hitLeftWall = false;
       boolean hitRightWall = false;

      We call variables like this flags, for reasons which should be apparent soon.
    2. In the Ball drive() function, if the ball hits either wall, set the appropriate flag to true and stop the ball:
      if (xpos > width) {
      hitRightWall = true;
      xspeed = 0;
      }
      if (xpos < 0) {
      hitLeftWall = true;
      xspeed = 0;
      }
    3. Add a pair of new functions to the Ball class to report whether either wall has been hit, perhaps something like
      boolean reportHitLeftWall() {
        return hitLeftWall;
      }
       
      boolean reportHitRightWall() {
        return hitRightWall;
      }
    4. In the draw() function, if the ball hits the wall, give a score to the opposing side
    5. Create a pair of variables to keep track of the score, and update them when a player misses the ball:
      if (ball.reportHitLeftWall() == true) {
        rightScore++;
        println("Left score is " + leftScore + 
          "  Right score is " + rightScore );
      }
      if (ball.reportHitRightWall() == true) {
        leftScore++;
        println("Left score is " + leftScore + 
          "  Right score is " + rightScore );
      }

      You will need to make these variables global by declaring them outside of any function.

    6. Finally make a new ball when a player misses the ball, so that the ball starts over again in the middle of the screen:
      if (ball.reportHitLeftWall() == true) {
         rightScore++;
         println("Left score is " + leftScore + 
           "  Right score is " + rightScore );
         ball = new Ball(color(255,0,0),width/2,height/2,-2,-2);
       }
       if (ball.reportHitRightWall() == true) {
         leftScore++;
         println("Left score is " + leftScore + 
           "  Right score is " + rightScore );
         ball = new Ball(color(255,0,0),width/2,height/2,2,-2);
       }
  5. Email your finished Pong game to me by the deadline

Week 10 November 10, 2014

How to interface Arduino to arbitrary electronics

Relays

arduino5VRelay_schem

5V relay 9007-05-00 datasheet

Homework due Week 11 November 17 2014

You will create an Instructable, teaching others how to hack into a cheap electronic toy the way you did in class.

  1. Many Instructables are of quite poor quality. I will be holding you to a high standard. Study the following Instructables which I consider to be excellent Instructables:
    1. http://www.instructables.com/id/Electronic-Tribble-Fuzzy-Logic-Type/?ALLSTEPS. This has much more theory than I would ask of you.
    2. http://www.instructables.com/id/Car-Horn-Prank-Box/?ALLSTEPS
    3. http://www.instructables.com/id/Tyree-the-Smiling-Tail-Wagging-Sensor-Less-3d-P/?ALLSTEPS
    4. http://www.instructables.com/id/Arduino-controlled-animatronic-wooden-head-readin/?ALLSTEPS, although I don’t like the way the code is included. I’ll find a better way to do this. Notice the way hand sketches are used to clarify some steps. Sometimes hand sketches can be clearer than photographs since they can emphasize the important things.
    5. http://www.instructables.com/id/Arduino-Vocal-Effects-Box/?ALLSTEPS. code is much better here. This is a very complex project and I don’t expect yours to have this much complexity.
    6. http://www.instructables.com/id/Time-Lapse-Photography/?ALLSTEPS this is probably closer to what yours will look like
  2. Make your first attempt at writing the Instructable. I will provide feedback and you will revise this the following week.
    1. You will need to create an account at Instructables
    2. Make sure you address all of these points, although not necessarily as separate items or in this order:
      • Description of project
      • Parts list
      • Tools list
      • Theory
      • Schematic (you may use CAD programs such as www.fritzing.org, https://upverter.com/tour/, http://123d.circuits.io/, or in fact any drawing software.)
      • Arduino and/or Processing code
      • Construction details, including photographs and possibly video
      • Video of finished result
      • You may add other items as necessary
  3. Pay great attention to your writing and organization. Your Instructable must be clear, well written, and understandable (basically the rules we’ve used for homework all along.)
  4. Email me only a link to your Instructable. Do not print anything out. Do not send me any files or attachments.

Week 11 November 17, 2014

Transistors

2N7000 datasheet
12N10L datasheet

What is the difference between transistors and relays?

  • Relays provide complete electrical isolation, transistors must have a common ground
    • Slight risk to Arduino/laptop/human if used with high voltage
  • Only works if control of toy is to ground
  • Transistors only work with DC; relays work with AC or DC
  • Relays typically can control less current compared to a similarly sized transistor
  • Relays typically require more current to control
  • Relays contain moving parts and thus are more prone to failure
  • Relays are too slow to do PWM and thus can not be used to dim lights or control the speed of a motor

What is a motor?

Lab: Arduino/Transistor/Motor

Lab: Improve your Instructable

Homework due Week 12 November 24, 2014

Your homework this week is to improve your Instructable. I spoke to each of you in class so you know what specific shortcomings you had. With only a few exceptions, every one of you could improve the quality of your Instructable.

  1. Review the Instructables that I gave you as a guide. How does yours compare to those? I will be judging yours using those examples as my standard of excellence.
  2. I will grade you based on how well you addressed all the points in the assignment, your writing clarity and organization, and how well a novice could follow your Instructable.
  3. As I noted last week, pasting code into an Instructable does not look good. An easy way to improve this is to use pastebin:
    1. Visit pastebin.com and create a new paste. Give it a title, perhaps the same as your Instructable.
    2. Paste in your code and click “Submit”
    3. Copy the URL of your paste. It will look something like this: http://pastebin.com/Q6hPzZsV#
    4. Go back to Instructables to where your code is. Remove the code and add a sentence like “get the code from here”. Highlight the word “here” and click on the link symbol (looks like two links of a chain) to add a link. Paste the URL you copied. This will make a link to your paste from your Instructable.
    5. Do this for both your Arduino code and your Processing code, if you have both.
  4. Send me a link to your improved Instructable

Week 12 November 24, 2014

Announcements

  • Tutors
  • Please bring in Assignment 7 I forgot to enter in gradebook!
  • Evaluations: either do them at home or you will have to do them during lab time next week
  • What did I say about printing programs?

Review

  • In our projects, current will almost always be less than an amp!
  • Conventional current flows from positive to negative, and conventional current is what we always use.

Lecture

Lab

  • Wire up 2 switches, 1 led
  • Desired behavior:
    • Press and hold 1 switch to make LED get brighter
    • Press and hold other switch to dim LED
    • Tap either switch to change state (i.e. if LED is on turn it off; if it’s off turn it on

Homework due Week 13 December 1, 2014 and Week 14 December 8, 2014

  1. Finish the lab assignment and hand in the documentation. Since the Hybrid Lab is closed over the Thanksgiving break, this part will be due on Week 14 December 8, 2014. Do not expect to work on this during class on Week 13, as we will be working on a new lab assignment.
    1. The lab I assigned this week had many challenging elements which I mentioned only briefly. You will have to research and figure out many things on your own. This is part of the assignment. There is much information available online, but you will have to integrate ideas from a number of different sources.
    2. Provide a schematic of your circuit. As always, this may be either hand-drawn or made on computer, as long as it is neat, clear, and complete. You may email me your schematic, either as a PDF or a JPG file.
    3. Email me your code. Rules:
      1. Send only .PDE file(s) for any Processing sketches and the .INO file(s) for any Arduino sketches as attachment(s). No other format will be accepted.
      2. Include your name and the assignment due date in the name of the file.
      3. Explain what your code does with comments
      4. Code must be neat, clear, and well organized
  2. Answer the following questions. This part will be due on Week 13 December 1, 2014. You may email me your answers:
    1. What flows through a resistor in an active circuit?
    2. What flows through an LED in an active circuit?
    3. What flows through a battery in an active circuit?
    4. What units do we use to quantify this flow in a circuit?
    5. What causes electrons to want to move from one place to another?
    6. What do we call the difference of potential energy between two points?
    7. What units do we use to quantify the difference in potential energy between two points?
    8. How do we measure the difference of potential energy between two points?
    9. What is Current?
    10. What is Voltage?
    11. What is Ohm’s law?
    12. Is Ohm’s law true for every electronic component?
    13. Suppose I have a 9 V battery, an LED, and a 1 K ohm resistor in series. Suppose I calculate the current as I = 9/1k. What’s wrong with this?
    14. What is KCL?
    15. What is KVL
    16. Is KCL always true? KVL?
    17. Every component in an active circuit gets warm. How can we calculate the amount of power that is creating this heat?
    18. Does power flow through a circuit?
    19. Does voltage flow through a circuit?
    20. From now on you are not allowed to use the terms “electricity” “voltage”, “current”, “power”, and “energy” in vague ways! They mean specific quantities.
    21. Given: a 9 V battery, an LED, and two identical resistors all in series. The voltage drop on the LED is 1.90 V.
      1. Draw the schematic, indicating all known values and quantities
      2. Calculate the voltage drop on each resistor
    22. If the resistors from the previous question are different, you can not calculate the voltage drop on each resistor. Why not?
    23. Given: a 9 V battery, an LED, and two different resistors. The two resistors are in parallel, and these two resistors are in series with all the other components. The voltage drop on the LED is 1.90 V.
      1. Draw the schematic, indicating all known values and quantities
      2. Calculate the voltage drop on each resistor.
      3. Why can you calculate the voltage drop even though the resistors are different?
    24. Given: a 9 V battery, an LED, and two identical resistors. The two resistors are in parallel, and these two resistors are in series with all the other components. The voltage drop on the LED is 1.90 V.
      1. Draw the schematic, indicating all known values and quantities
      2. Calculate the voltage drop on each resistor.
      3. Calculate the current through each resistor
      4. Calculate the power dissipated by each resistor
      5. Calculate the power dissipated by the LED
    25. What is .987 k ohm to the nearest ohm?
    26. Draw the schematic symbol for a diode, a light dependent resistor, and an LED. Explain what each component does.

Week 13 December 1, 2014

Review

  • What have we learned? (participatory exercise)
  • Software too!

Clarifications

  • Difference between schematic and pictoral diagram
  • Relay schematic: which is coil, which is switch
  • Voltage and current
    • How to determine voltage to a toy (or other item)
    • How to determine current to a motor (or other item)
    • Arduino current limits
    • Relay specifications
    • Transistor current limits

New material

  • Evaluations
  • Springs
    • Fr = -KX
    • A = F/M
    • Damping

Simple spring, no class

A spring class example

Full class example allowing multiple springs at https://processing.org/examples/springs.html

Lab

  • Use a potentiometer and a pushbutton to interact with a simple spring

Homework due Week 14 December 8, 2014

There is no additional homework assigned this week, but remember that on
November 24 I assigned homework that is due next week. This will be your last assignment.

Week 14 December 8, 2014

  • Evalutations
  • Interface: Art Using Technology Using Art show Friday December 12 7:00pm – 10:00pm, Oliver Art Center, CCA Oakland (Facebook event)
  • Review questions
  • Solution to 2 switch light control assignment

  • Open questions
  • Lab

    • Finish springs lab
    • Work on your own project
    Print Friendly
    Creative Commons License
    This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.

    Leave a Reply

    Your email address will not be published. Required fields are marked *