Day 10, Arduino. Blinky lights 1

https://app.arduino.cc/sketches

New stuff Arduino microcontrollers.

Arduino Microcontrollers

These are small, cheap, limited computers that do ONLY and exactly what you program them to do.

They have a bunch of pins to read inputs and write outputs.

The inputs could be buttons, switches, dials, sensors, keyboards, etc.

The outputs could be lights, speakers, screens, motors, servos, etc.

The trick is, YOU pretty much have to do everything yourself.

The magic is, You can pretty much do anything as long as you can find parts and figure out how to use them.

How it works.

When an Arduino (like most "micro-controllers") starts up, there is some code which only runs once.
For example, various pins need to be put in input or output mode. Various setting and setup code needs to be done. But it only needs to happen once when the device is powered on. This is done in a setup() function.

After the setup() function is complete, the device is free to run for ever, as long as it has power, by running an infinite loop in a section of code called the loop() function. An example might be, as long as the device is running:
  1. Read a temperature sensor, storing the value to a variable
  2. Convert the data in the variable from Celsius to Fahrenheit
  3. Write the converted value to a screen
  4. Start the loop again from the top

Programming Arduinos

You are getting pretty good at programming in Python.

These microcontrollers, however, don't understand Python. They only understand "machine language" which is generated by a program called a "compiler." In Arduino's case, the compiler that generates machine language Arduino understands is called C++

C++ is a bit harder than Python because Python has a lot of nice features that C++ does not. But you will be ok.
Your main concern is that C++ "syntax" is a little different.

... But really, it's not THAT different. You will recognize a lot of it just by looking.

Some helpful lego pieces

You are going to be asked to work with your team to accomplish some tasks with your Arduino. Here are some code snippets that might help.

Turning on one light that is connected to pin 5, waiting 10 seconds, then turning it back off for 10 seconds, over and over in a loop.
void setup() {

  pinMode(5, OUTPUT);  // put pin 5 into "output" mode

}


void loop() {
 
  digitalWrite(5, HIGH);   // turn pin 5 on so the light lights up
  delay(10000);            // wait 10 seconds
  digitalWrite(5, LOW);    // turn pin 5 off so the light goes dark
  delay(10000);            // wait 10 seconds

}


With two lights, turn one on for 1 second, then off while turning on the other light for 1 second, over and over in a loop so the light blinks back and forth between the two lights. The lights are connected to pins 8 and 9.
void setup() {

  pinMode(8, OUTPUT);  // put pin 8 into "output" mode
  pinMode(9, OUTPUT);  // put pin 9 into "output" mode

}


void loop() {
 
  digitalWrite(8, HIGH);  // turn pin 8 on so the light lights up
  delay(1000);            // wait 1 seconds
  digitalWrite(8, LOW);   // turn pin 8 off so the light goes dark


  digitalWrite(9, HIGH);  // turn pin 9 on so the light lights up
  delay(1000);            // wait 1 seconds
  digitalWrite(9, LOW);   // turn pin 9 off so the light goes dark

}


Declaring and using variables, looks like this.
int my_delay = 1000 ;
int the_pin_i_care_about = 8 ;

void setup() {

  pinMode(the_pin_i_care_about, OUTPUT);

}

void loop() {

	float things_and_stuff = 52.5425 ;
	char[] my_words = "Tacos and Tacos" ;
 
  digitalWrite(the_pin_i_care_about, HIGH);
  delay(my_delay);
  digitalWrite(the_pin_i_care_about, LOW);

}

Day 9, Functions.

Cheatsheet pdf download

Last time we did some programming, you had to use loops to upgrade your shape-drawing program. Here's MY solution: https://codehs.com/sandbox/id/9-draw-with-loop-menu-WYCgJ6

Now for the new stuff. Functions.

Void functions

You might notice that you are repeating chunks of code several times.

We started off drawing 4 squares by hand:
https://codehs.com/sandbox/id/3-example-4-sq-variables-gzC6mc

Then we "refactored" our code, improving it using "for" loops:
https://codehs.com/sandbox/id/4-squares-with-for-loop-3uiX5p

But we are STILL typing THIS every time we want to draw a square:
pendown()
for i in range(4):
   forward(square_size)
   right(90)

It might be nice to take that logic (that chunk of code that does a thing) and put it into a function. Then, any time we want to draw a square, we can just call our function.

def draw_square(size):
  pendown()
    for iterations in range(4):
      forward(size)
      right(90)
    penup()

Check out this example, we've made a function that draws a square. It takes an "argument" (which I've named size) so the function knows how big the square should be. The function simply draws the square and returns back to the program that called it, not returning any data back. We call this a "void" function because it doesn't return any data.
https://codehs.com/sandbox/id/13-ex-4sq-loop-function-1oWY8j

Functions that return a value

Void functions DO things but don't send data back to the code that called them.

Sometimes you want a function that does some things quitely and returns some kind of answer.

An example might be a function that turns a secret message into a code and "returns" the coded message.
https://codehs.com/sandbox/id/secret-coder-5r0a3r

Another example might be a function that does some math and returns the answer back to the "main" program.
https://codehs.com/sandbox/id/calculator-with-functions-Toaokj

Assignment 5

Day 8, Loops.

Cheatsheet pdf download

Last week, you had to make

Here's my solution (not THE solution): https://codehs.com/sandbox/id/7-conditionals-and-io-wbaBep

Now for the new stuff. Loops.
You ever notice that some lines of code are repetitious?

For loop drawing a square: https://codehs.com/sandbox/id/12-draw-with-loop-simple-hrdY9w

For loop basics and math: https://codehs.com/sandbox/id/13-math-with-for-loops-QhHaNf

While loop drawing a spiral: https://codehs.com/sandbox/id/10-while-loop-spiral-VRlw4p

While loop guessing game: https://codehs.com/sandbox/id/11-while-loop-guess-num-HBLhvA

Nested loops: https://codehs.com/sandbox/id/example-nested-loops-fvGNUh

Assignment 4.

Day 5, Intro to Radio Signals (Days 6 and 7, wildlife tracking with radios)

Day 4, Input and Output, Conditional statements (if/else)

Cheatsheet pdf download

Last week, you had to upgrade a centered square program to a centered RECTANGLE. Here's MY solution, which isn't the ONLY way:

https://codehs.com/sandbox/id/6-rectangle-centered-hfgPI4

Ok, let's roll with the new. Input and output.

Output. Just about every programming language and environment has a way to produce "output." Usually we mean printing text to the screen but it could be a special tiny display, blinky lights, motors, or even an entirely different system over the network. Moving the turtle IS a form of output.

In the CodeHS Python sandbox (and most Python environments) the print() function outputs text to the console.

print("Who approaches the Bridge of Death must answer me these questions three!")

Input. Just about every programming language and environment has a way to read "input." Usually we mean "keyboard input" from the user, but input could be from a sensor or an entirely different system over a network.

In the CodeHS Python sandbox (and most Python environments) the input() function reads text from the keyboard.

The input() function takes 1 optional argument, which is the thing you want to ask the user to type.

input("What is your name? ")

The input() function returns whatever the user typed, and you can capture what the user typed in a variable.

print("Who approaches the Bridge of Death must answer me these questions three!")
user_name = input("What is your name? ")
user_quest = input("What is your quest? ")
user_fav_color = input("What is your favourite color? ")

Conditional statements, flow control, if / else statements

You are used to programs executing from top to bottom. "Conditional statements" give you control over the flow of execution.

With if, elif, and else statements you can decide which parts of your code runs, or doesn't run, based on conditions YOU set. If the user wants to draw a square that's nonsensically big:

square_size = input("How big do you want me to draw the square? ")
if(square_size > 200):
  print("Sorry, that's too big. Bye.")
  exit()
# the rest of the program ...

Notice that the "block" of code in the if statement is indented. You can use as many spaces as you want to indent, as long as they are all the same in that block. The theory is that the indentation helps the code be more human-readable. Indentation matters in Python, in many languges it does not.

Here are some "comparison operators."

< 	less than
> 	greater than
== 	equal to
!= 	not equal to
>= 	greater than or equal to
<= 	less than or equal to

Examples of simple if statements:

if(user_age <= 15):
  print("sorry, you aren't old enough to drive this car.")
if(user_height < 40):
  print("Sorry, you aren't tall enough to ride this ride.")  
if(favorite_animal == "Cat"):
  print("Wrong! Dogs rule, cats drool.")  

Example of if/elif/else statements (elif is Pythonese for "Else If"):

print("Welcome to the Magic Animal Chooser!")
print("Answer the following questions to find your magic animal.")

color = input("What is your favorite color? (red, blue, green): ")

if color == "red":
  print("You are a fiery DRAGON!")
elif color == "blue":
  print("You are a wise DOLPHIN!")
elif color == "green":
  print("You are a sneaky CHAMELEON!"")
else:
  print("Hmm, that's a unique choice! You must be a MYSTICAL UNICORN!")

Check out this code sample of if, if/elif, and else statements controlling the flow of a program's execution. Actually read it, run it several times. Read the code, see the flow.
https://codehs.com/sandbox/id/8-conditionals-demo-uNaw3g

Assignment 4 Write a program that can asks the user what they want to draw: circle, rectangle, or square.

When the user choses a shape, ask the user appropriate questions so your program has enough information to draw the shape. Draw the shape the user chose with the information the user provided.

Look at this example: https://codehs.com/sandbox/id/7-conditionals-and-io-wbaBep/run

Use your knowledge from the last 4 classes to create something like this.

Here is the assignment https://codehs.com/lms/assignment/167982083

Day 3, Using math to automatically calcualte values of variables.

Last week, you had to draw an Equalateral Triangle. Here's my solution, including my mistake.

https://codehs.com/sandbox/id/5-example-eq-triangle-xl8lEa

Ok, Back to drawing a square. But can you center it?

https://codehs.com/sandbox/id/4-example-centered-square-7uyCEc

Assignment 3
You know how to draw. You know how to draw a square.
You know how to draw a square using variables.
We even talked about how to use math and variables to center the square automatically.
But.
Can you make a centered rectangle?
Yeah, you heard me right. It just got real. Write a Python Turtle script in your CodeHS sandbox that centers a rectangle on the 0,0 dead center point. You can pick the rectangle height, but the width should be automatically calculated by your script to be double the height. The rectangle should end up twice as wide as tall like the example below.
Here's the assignment: https://codehs.com/lms/assignment/166887795

Day 2, Variables.

Class handout cheatsheet here

Last week, you had to draw four squares. Here is MY solution.

https://codehs.com/sandbox/id/2-example-4-squares-wd1s6S

Here's the same 4 square code, but now with variables.

https://codehs.com/sandbox/id/3-example-4-sq-variables-gzC6mc

Assignment 2, use Turtle to draw an equalateral triangle using at least one Variable.
Remember, programming is about solving real-world problems more than it is about code.
So make sure you understand "equalateral triangles" BEFORE you start writing code.

Day 1, introduction to programming and how to control the Turtle.

Class handout cheatsheet here

Python code to draw one square. The code is run (we say "executed") from top to bottom. Comments help explain your code to other humans.

https://codehs.com/sandbox/id/1-example-square-wrgCzt

Assignment 1. Draw 4 squares, one in each quadrant.










Down the road a ways... Ignore this stuff for now....

Let's talk about functions. Here's the worst calcualtor in the world.
https://codehs.com/sandbox/id/python-3-N8TI1R

Turtle squares with functions.
https://pythonsandbox.com/code/pythonsandbox_u119704_yv6fF1B7052Tpx2lawgZfbll_v2.py

templogger.txt
dial.txt
blink.txt
servolight.txt