Lesson goal: Turn an LED on or off using the mouse and the distance formula

Previous: Turn an LED on and off | Home | Next: Make an LED flash

This lesson will allow you to experiment with the mouse, some LEDs and the distance formula.

Let's draw a circle at some random position on the screen. If we move the mouse cursor within the circle, let's turn an LED on. If we move outside of the circle, let's turn it off.

You'll have to think about what it means for an $(x,y)$ point (the position of the mouse cursor) to be inside of a circle.

mousex() and mousey()
Move the mouse over a dotted box for more information.

Now you try. Can you figure out how to turn the LED on and off by moving the mouse inside and outside of the circle?

Type your code here:

See your results here:

In this exercise, you'll need the same circuit as in this lesson.

Note that this code will not run! Fix the d= line to compute the distance between the point (xr,yr), which is the center of the circle, and (xm,ym), which is where the mouse is. Then fix the two if statements that follow, to turn the LED on if d is within the radius of the circle, and turn it off if not. Dismiss.

Show a friend, family member, or teacher what you've done!

Here is a share link to your code:

Does your code work? Want to run it on your iPhone?

Here's your code:

  1. Use [Control]-[C] (Windows) or [⌘]-[C] (MacOS) to copy your code.

  2. Paste it using [Control]-[V] (Windows) or [⌘]-[V] (MacOS) into this page

  3. Then click the "Use on iPhone" button that you'll see.