RPi-NodeRed OLED IP Address Display

Please copy and paste the entire code block below into the node-red clipboard import window.

[{"id":"a1ae5e26.b300a","type":"String","z":"e0e44734.95d078","name":"OLED","display":"4fe1da30.5141a4","x":690,"y":220,"wires":[]},{"id":"60037f1d.3914b","type":"function","z":"e0e44734.95d078","name":"Format Message","func":"msg.payload={\nx:1,  \ny:50,\ntext:\"IP \"+msg.payload+\":1880\"\n}\n\nreturn msg;","outputs":1,"noerr":0,"x":520,"y":220,"wires":[["a1ae5e26.b300a"]]},{"id":"8971c892.2fa0f8","type":"change","z":"e0e44734.95d078","name":"IP","rules":[{"t":"set","p":"payload","pt":"msg","to":"payload[0].address","tot":"msg"}],"action":"","property":"","from":"","to":"","reg":false,"x":350,"y":220,"wires":[["60037f1d.3914b"]]},{"id":"974cfafc.e526d8","type":"inject","z":"e0e44734.95d078","name":"","topic":"","payload":"10","payloadType":"num","repeat":"60","crontab":"","once":true,"onceDelay":0.1,"x":90,"y":220,"wires":[["8c7a8725.02fa58"]]},{"id":"8c7a8725.02fa58","type":"hostip","z":"e0e44734.95d078","name":"Host IP","x":220,"y":220,"wires":[["8971c892.2fa0f8"]]},{"id":"8f95bb29.b800d8","type":"comment","z":"e0e44734.95d078","name":"Display IP address on the mini OLED display","info":"","x":300,"y":180,"wires":[]},{"id":"4fe1da30.5141a4","type":"oled-config","z":"","name":"","width":"128","height":"64","address":"3c"}]

RPi Node-Red: Buzzer

Parts List:

Piezoelectric Buzzer

What is a Piezoelectric Buzzer?

A piezoelectric buzzer is a buzzer that is activated with an oscillating electric signal.  This means to produce a tone the buzzer must be turned on and off many times per second. The faster the the buzzer is turned on and off the higher the pitch is produced.  We can achieve this using a pulse width modulated signal (PWM). With a PWM signal we can specify the frequency in hertz (cycles per second).

Getting Started:

Setting up the Hardware

Using jumper wires connect the I/O pin of the buzzer to GPIO16, the GND pin to GND (ground), and the VCC pin to VCC.

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag two inject nodes and a Raspberry Pi output node into the flow area.

Double click on the Raspberry Pi output node to open its configuration menu.  Set the Pin to GPIO16.  Set Type to PWM output.  Set Frequency to 100 Hz.  You can Name the node anything, I chose “buzzer”.

Double click one of the inject nodes.  Use the dropdown menu to change the Payload data type number, type a 1 in the textbox.  Name the inject node “on”.

Double click the unmodified inject node.  Use the drop down menu to change the Payload data type to number, type a 0 in the text box.  Name this node “off”.

1 and 0 correspond for to values of a binary digit(bit) true and false, high and low, on and off respectively.  These are called Boolean values and are a fundamental data type in Computer Science.

Connect the inject nodes to the output node and then deploy the flow.

If everything has worked correctly pressing the “on” button should cause a sound to come from the buzzer and the “off” button should stop that sound.

Leveling The Nozzle

 

If you find one of your nozzles is at a different level than the other the easiest way to fix this problem is to either file or sand down the nozzle to the same level as the other

The best way to do this is to use sandpaper and level the build plate like normal except using sandpaper as the leveling paper but if you don’t have any sandpaper around then you can use a file

Engineering the Community Engagement Process

The community engagement process can be a daunting task to start.

Student preparation means that you have created a safe learning environment and helped students maintain a growth mindset.  This means primarily that you constantly celebrate speech patterns that support a growth mindset.  It also means that they have “played” with enough technology to feel that they have the ability to creatively apply it in a variety of situations.  Activities in the kits will help with this, but so do icebreakers that involve working together and connecting with others.  Make sure to include time to play and try stuff – don’t rush tech skills training.  Teach the design thinking process, and guide them along every step of the way. The process is pregnant with opportunities to practice communication and teamwork skills.

 

 

We will have guides to help with the communication skills. The most important one that students should practice is the skill of listening. Below is a graphic showing other skills that should be taught as needed.   We work with communication experts to get tips and tricks for the best ways to help guide students as they go through this.   It is important that you introduce topics when there is a context for learning about it.

Introduce the Design Thinking process developed at Stanford and presented well in this crash course PDF.  I have modified the design they use here to reflect a general T3 alliance project.  We introduce the mini-grant proposal as a step right before a prototype phase.  This is only necessary when the cost of building the prototype exceeds what you have on hand and consider consumable.

Program preparation:

The most important thing a program can do to support the community engagement process is cutting through the red tape that exists in any institution.  Things that a program needs to do to prep, finding an appropriate learning space, preparing for local field trips, managing the finances for small-scale projects, helping with background checks for community members, managing equipment, and hiring capable staff with some sort of computer science background.  Perhaps the most important aspect of a program is being ready to support student ideas for projects with immediate financial backing.  The mini grant / deliverables process is very important.

 

Community preparation:

The community has always been key for societies to raise their youth.  In many native cultures, there are stories of youth getting their first fish, or game animal, bringing it back to the village and being celebrated for the contribution they made to the survival of the community.

Learn your elevator pitch and be ready to tell anyone you meet about the what T3 alliance is about in under a minute.  An “elevator pitch” is a term used to describe what you would say if you were in an elevator with an important job prospect or grant manager.  They don’t know of you, so you have 60 seconds to sell your idea.   You are leaving them with an opening to ask more, and possibly get involved.   The image below shows an idea for redesigning our website – but it can be broken down into the pitch – the three big bubbles showing what we do and how it turns into studnet involvement in STEM career fields.

Once they are interested, outline what a specific commitment might look like and develop the relationship with attunement to safety, communication, and set up at least 3 opportunities for interaction.   The first interaction does not need to be done in person, but it’s better if it can be.  Here is an example of an interview we filmed for a possible client partnership with the Upward Bound Programs at UH Hilo and an astronomy project.

The second interaction should be somewhere around the testing phase.  Once a project is developed. they should work together to analyze results to see if it fits the client’s needs.  The last interaction should be a celebration of some sort.  Presenting a completed project to an appreciative community member is an incredible experience for a group of students.   If a potential client understands and can support this, then move forward, if not, gently separate yourself from the relationship.

GO Time:

Here are a few tips:

1: Remember why you are doing this – details can pop up that will frustrate you.

  1. Start small – Upward bound office, someone at the university, STEM friends, Non-Profits, Government organizations are all potential sites where you could find projects.  Small and safe is a good first step.  Over time, it will get more complicated.  Every small success for a group of students builds confidence.  We used selfie stations to get kids feeling the process.
  1. Teach when they need to know.  Don’t teach writing skills until they need to write a proposal.  As soon as you want them to use a video camera – teach what they need to know to produce the video you want them to have for a deliverable.  Context is everything!

4.  Trust the PROCESS.  The design thinking process is a step by step guide.  If you always come back to that you will be able to help every student redirect their actions.

 

 

Makerbot Desktop – Outdated Software Method

Slicing Software Installation and Setup

To use the QIDI Tech 1 Dual Extruder  you will need some software installed locally on a laptop/desktop computer.

The software we are using right now is this version of Makerbot Desktop  It will not work with “Makerbot Print” so please use Makerbot Desktop.

Once you have installed “Makerbot Desktop” open it and click on the “Prepare” tab at the top, you do not need to create a Makerbot account.

You need to to also go to “Devices” at the top and set your “Type of Device” to “Replicator (Dual)”

Now you can import a STL file

Now click on “Export Print File” and save the print file to a SD card connected to your computer.

Once the file is on the SD card you should eject it and plug it into the 3D printer.  Then proceed to print the file through the menu system on the printer.

3D Printing: Design – Nametags

Overview

In this lesson, you will learn how to create a personal 3D nametag using TinkerCAD

Before you start

  • Have an internet connected laptop/desktop
  • Has already created a TinkerCAD account
  • Has familiarity with TinkerCAD controls
  • Mouse (optional)

Procedure

  1. Starting with an empty workplace, find and place the ‘Box’ object from the right panel to act as the primary base of the nametag.
    • Decrease the height of the box by dragging one of the ‘white’ boxes located on the top surface of the box.

    • To change the length of the box, drag one of the ‘black’ boxes located on each side of the box.

  1. Find and place the object ‘Text’ from the right panel to act as your name.
    • You can change the height of the ‘text’ object by dragging the top ‘white’ box (Similar to the previous step).

    • You can change the text from the shapes options window located in the top right. For demonstration purposes, we will leave it at ‘TEXT’.

  1. Finally, find and place the object ‘Tube’ from the right panel to act as your nametag’s hook.
    • Similar to the previous steps, you can adjust the position and size of the object by dragging the small white/black boxes.

  1. Once you have finished placing and resizing your objects, select all objects by hitting the command ‘Ctrl+A’
    • You should see all of the objects highlighted. From there, click on the ‘Group’ tool at the top toolbar, and it will group all individual objects into a single one.

Complete!

You have successfully created a personal nametag! Try out different creations by adding more shapes, resizing objects, and more.

RPi Node-Red: Push Button+ RGB LED or Buzzer

Parts List:

1x RGB LED

1x Push Button

1x Piezoelectric Buzzer

Getting Started:

Setting up the Hardware

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag one Raspberry Pi input node and five Raspberry Pi output nodes into the flow area.

Double click on the Raspberry Pi input node to open its configuration menu.  Set the Pin to GPIO25.  Name the node “Button”. Set the Resistor to “pulldown”.

Button Input Node

 

Double click on the unmodified Raspberry Pi output node.  Set Pin to GPIO16.  Set Type to PWM output.  Set Frequency to 100.  Name the node “buzzer”.

Buzzer Out Node

For this step, we are going to setup the output nodes for each RGB node. Double click on one of the Raspberry Pi output nodes.  Set the Red Pin to GPIO13Green Pin to GPIO19, and Blue Pin to GPIO26. Check the box to Initialise pin state?  select low (0) from the drop down menu.  Name each node with its respective “Red, Green, Blue”.

Red Out Node

Green Out Node

Blue Out Node

Wire each output node to the single input node and deploy the flow.

If everything is working properly the LED should illuminate and the buzzer should activate for a short period of time after the button has been pressed.  To deactivate either the buzzer or LED simply delete the wire in Node-Red connecting the associated node with the Button node.

Whats Next?

  • What other combinations can you make with items in your kit?

RPi Node-Red: PIR + RGB LED or Buzzer

Parts List:

1x RGB LED

1x PIR

1x Piezoelectric Buzzer

Getting Started:

Setting up the Hardware

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag one Raspberry Pi input node and five Raspberry Pi output nodes into the flow area.

Double click on the Raspberry Pi input node to open its configuration menu.  Set the Pin to GPIO20.  Name the node “PIR”.

Double click on the unmodified Raspberry Pi output node.  Set Pin to GPIO16.  Set Type to PWM output.  Set Frequency to 100.  Name the node “buzzer”.

Buzzer Out Node

For this step, we are going to setup the output nodes for each RGB node. Double click on one of the Raspberry Pi output nodes.  Set the Red Pin to GPIO13Green Pin to GPIO19, and Blue Pin to GPIO26. Check the box to Initialise pin state?  select low (0) from the drop down menu.  Name each node with its respective “Red, Green, Blue”.

Red Out Node

Green Out Node

Blue Out Node

Wire each output node to the single input node and deploy the flow.

If everything is working properly the LED should illuminate and the buzzer should activate for a short period of time after the PIR has detected movement.  To deactivate either the buzzer or LED simply delete the wire in Node-Red connecting the associated node with the PIR node.

Whats Next?

  • What other combinations can you make with items in your kit?

RPi Node-Red: RGB LED

Parts List:

1x RGB LED Board

4x Female-Female Jumper Wires

Getting Started:

Setting up the hardware:

Connecting the RGB LED Module

Setting up on Node-Red:

Have three out nodes, each representing one of the three outputs. For each out node, have two inject nodes (on and off)

Setting up Out Nodes

Configure Red output to GPIO13 (pin 33)

 

Configure Green output to GPIO19 (pin 35)

Configure Blue output to GPIO26 (pin 37)

 

Setting up Inject Nodes:

Configure ‘off’ switch for inject node – Set payload to 0

Configure ‘on’ switch for inject node – Set payload to 1

Deploy the flow

RPi Node-Red: Push Button

Parts List:

Push Button

3x Female-Female Jumper Wires

What is a Push Button?

A push button is a momentarily activated button.  When the button mechanism is fully depressed an internal electrical connection is made and this newly made connection can be read as the activation of the button.

Getting Started:

 

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880.  Drag a Raspberry Pi input node and a Debug node into the flow area.

Double click on the Raspberry Pi input node to open its configuration menu.  Set the Pin to GPIO25.  Set Resistor? to pulldown.  You can Name the node anything, I chose “button”.

The debug node can be left with it’s default settings, wire the button node to the debug node and deploy the flow.

If everything has been put together correctly you should see the number under the button node in the Node-Red flow change from a 0 to a 1 when the button is activated and from 1 to 0 when the button is deactivated.  You should also be able to see a record of the button activation in the debug tab of Node-Red.

Whats Next?

RPi Node-Red: automatically running node-red, as root

This tutorial shows you how to have node-red start and run as root instead of a normal user.

This is necessary for the RGB Matrix node: node-red-contrib-easybotics-led-matrix

Open a terminal and paste in the following lines:

sudo systemctl enable nodered.service
sudo npm config set unsafe-perm true

Now Node-Red will start automatically when the Raspberry Pi boots up.
The second line tells npm that we intended to run it as root; and that its okay to install nodes in protected directories.

The systemd service that we enabled is really just a type of script that lives in a file somewhere.

So if we want to change the user that runs node-red, we need to edit the file, this can be done with this fancy one liner:

d=/lib/systemd/system/nodered.service && sudo sed "s/User=pi/User=root/;s/Group=pi/Group=root/" $d > tmp && sudo mv -f tmp $d

When pasted into the terminal and ran, this bash expression will edit the nodered.service file and change the user to ‘root’.

If you have flows and nodes that you wish to keep, you can use this command to edit your node-red settings to keep using your old home-directory:
But be warned, this one line will only work after node-red has run atleast once as root; seeing as this is when the settings file it is editing is created.
An easy way to ensure this is to reboot after doing the one liner above, and then run the one liner below; and then finally reboot again.

d=/root/.node-red/settings.js && sudo sed "/.*userDir:*./c\userDir: '\/home\/pi\/.node-red\/'," $d > tmp && sudo mv -f tmp $d

Some nodes, such as the led-matrix require the soundcard to be disaabled
there’s a command for that too:

d=/boot/config.txt && sudo sed "/.*dtparam=audio=on*./c\dtparam=audio=off" $d > tmp && sudo cp -f tmp $d

 

Selfie station example project

Here is an example of an applied design thinking project done with a class of 17 students at the University of Hawaii Hilo Upward Bound T³ Alliance during the summer of 2018.  Node Red and physical Raspberry Pi setup instructions can be found on this post.

Students had mastered the skills associated with basic physical computing and Node Red.  They were capable of setting up a button, an LED Ring, using a sonic sensor, a PIR sensor, and a small camera.  They had been able to combine all these components using Node Red and were capable of generating emails that sent a photo.

I asked around for a person or group at the university that might be interested in a device that could take photos and have them emailed instantly.    Eventually I found the perfect potential client in Shara Mahoe, the director of new student services.    She was planning a scavenger hunt for the new student orientation day later in the summer when 600 freshmen appear and nervously try to find their way around the large UH Hilo campus.  She listened to my description of what the students in our T3alliance program were able to do and how design thinking process worked.   Once she understood what was involved, she signed up to be a client.

Shara and a colleague showed up in my classroom the next day and I interviewed her in front of the class.  She described her day and what she hoped it would feel like to new students.  She listed out 5 locations around the University that could use a selfie station and asked my students if they could find a solution that would work.  I had previously broken the students up with an ice breaker activity and they now found themselves choosing one of the sites around campus to design a selfie station.  As a team, they discussed what they had heard Shara speak about and filled out the first section of the guide questions associated with the “empathy” stage of the design thinking process.

We took a quick walking field trip to each location and the students finished the “define” phase, where they articulated exactly what was needed and what the constraints were, and moved into a brainstorming “ideation” phase.  Students were tempted to think there was just one type of solution to the selfie station problem, but they sketched out three different ideas. When this was finished they chose a “prototype” design they wanted to build and they wrote out a mini grant proposal.  

When the proposal is complete, we submitted it to the Upward Bound director for approval.  We prepared ahead for this type of project with wires, and buttons and extra raspberry pi devices with cameras and power supplies.  After the proposal was approved we handed out and checked off the items that had been requested on each proposal. The students got right to work building the prototype selfie stations.

We instructors restrained ourselves from helping too much and let the teams figure out how to build their designs.  When students would ask for help, we would respond with a question.  Eventually, the students learned to frame their questions in such a way as to be able to google the answer.  We helped in the areas where a skill had not been introduced, such as soldering, or learning to “remote” into the pi.  The teams were responsible for building the prototype, writing the code that controlled it, and recording and editing a short video.

Several days later, Shara met with us to see the results. The students walked around the campus with her demonstrating the way their selfie stations worked and noting what things could be improved. One team had an opportunity to radically modify their design because it didn’t take into account the safety considerations necessary when a crowd of students would moving past a certain area.

The students were beaming when Shara thanked the group.  She appreciated their efforts and asked them to sign their work so that new students at the school knew who had built these stations.  Each group modified and perfected the design and the instructions.

As part of the initial mini grant application, The teams had been responsible for writing user instructions, making a video about the project and writing a short report about the progress of the project. 

Setting up Node Red for a Selfie Station

Here is the Node Red setup for a Selfie Station where a button is pushed, a LED light ring turns on, a photo is taken, which is then emailed to a dedicated email.  Its very similar to this project that was done by teams of students at UH Hilo.

Step 1.  Set up the light ring so that it turns on and off after a message is sent:

In this case – we wanted the light ring to turn on with the color red, and then turn to a different color white and then turn off.  To achieve this we used a trigger node.  The first one was set to 8 seconds.

The second trigger node was almost identical, except that the “send” command was white, and the “then send” command was black.

Step 2.  Connect the camera node with a delay:  In this case we chose 9 seconds because it was in the middle of the time when the light ring is white.  When the signal is sent – the light rings should go off and then the camera light should come on.

You will want double click on the camera node and change the file mode from generate to buffermode. You can also change the properties of the photo here.

Step 3.  Check that you ended up getting your photo by looking in the pictures photo on your pi.  Grab the send email node from the sidebar.

Move the email node after the photo node.

You will want to have a special gmail that you have set up to receive emails from node red.  We set up one that was named especially for the project.  Once you are logged in to the account you will need to follow the link for getting emails from “less secure sources.”  The screen you will get to after being logged into the gmail account looks like this: You will want to toggle the button to allow less secure apps.

Open the properties tab for the email node – enter the new email you just created and made less secure into the who “To” field.  Enter the email that you want the data to be sent from into the “Userid” field.   This does not need to be a “less secure” email.  It could even be an email with the specific name of the pi where it will be placed.

Test it out and check your email to see that it worked.  

Step 4: Switch the input to a button (or any other trigger device).  We used a button and connected one side to 5v power, and the other side to GPIO12. Set the resistor to “pulldown” and check the box for read initial state of pin on deploy.

When its working a push of the button should change the “0” to a “1” right below the pin node.  When the button is released it should change back.  Connect up the nodes and push a button to take a photo and send it!

 

The button can be swapped out for a different type of sensor such as the PIR or sonic motion sensor, just be careful that the sensitivity isn’t set too high, or else you could find yourself with a lot of emails!

If you actually want to set this pi up somewhere (like we did in this project) you will want to configure it to auto start Node Red when the pi is powered on.  As long as the pi is in an environment where it has permission to log into the wifi, it should work.

 

RPi Node-Red Auto Start

When deploying a Raspberry Pi as a permanent/semi permanent installation is will be useful to have Node-Red start persistently, in the case of power failure, etc.

Open a terminal and paste the following command

sudo systemctl enable nodered.service

Now Node-Red will start automatically when the Raspberry Pi boots up.

(Archive) RPi Node-Red: DHT11 Temperature and Humidity Sensor

Please wire up your DHT11 sensor as below:

To be able to use the DHT11 temperature and humidity sensor we will have to install the Node-Red node and the BCM2835 library to support it, the easiest way is explained below.

First open a terminal  window and copy and paste the entire code block and press enter.

#install bcm2835 library
cd ~/
curl http://www.airspayce.com/mikem/bcm2835/bcm2835-1.56.tar.gz > bcm2835-1.56.tar.gz
tar zxvf bcm2835-1.56.tar.gz
cd bcm2835-1.56
./configure
make
sudo make check
sudo make install

#install node
cd ~/
sudo npm install --unsafe-perm -g node-dht-sensor
sudo npm install --unsafe-perm -g node-red-contrib-dht-sensor

After the commands finish running press enter again to make sure the last one has been run.

Restart your raspberry pi, start Node-Red and search for “dht” you should find a node called “rpi dht22” this indicates that the node has been installed correctly.

The node must be setup as in the below image – make sure you select DHT11

RPi Node-Red: Sonic Sensor (HC-SR04)

Goal:

Read distance measurements from the sonic sensor within Node-Red

What You Will Learn:

  • Basic Circuit Prototyping
  • Basic Node-Red Programming

What You Need to Know:

Parts List:

HC-SR04 Ultrasonic Range Finder

4x Female – Female Jumper Wires

What is a Sonic Sensor?

It is a sensor that works based on the principles of echo location.  The sensor is able to emit ultrasonic pulses and read ultrasonic pulses, using this timing information along with the speed of sound and some math we can extrapolate distance to the surface the pulses have reflected against.

\text{distance} = \frac{\text{(time)}\text{(speed of sound)}}{2}

Thankfully the node we will be using will take care of the math for us.

Getting Started:

Setting up the Hardware

I would suggest wiring it exactly as it is in the diagram, using 4 female to female jumper wires to allow you to point the sensor around freely.

Setting up Node-Red

Start Node-Red and navigate to 127.0.0.1:1880  using the web browser.  Drag the “rpi srf” node and a “debug” node into the flow area.

Double click the “rpi srf” node to open its configuration settings.  Set Pins to “16,18” (which corespond to GPIO 23,24).  The programmer of this node decided that it was better to use the Raspberry Pi’s board pinout rather than the BCM standard, this web page shows both.

Next, open the “debug” nodes configuration settings.  Check the debug window and node status options.  This will display the last sent message beneath the debug node.

Link the nodes together and deploy the flow.

If everything has gone together properly, you should get numbers appearing below the “debug” node.  These are distance measurements in centimeters, you can change the frequency of the measurements within the “rpi srf” node or see the entire measurement history in the debug tab.

RPi Scratch 2 + GPIO Introduction

Goal:

Using a button control a sprite within Scratch 2 and then to turn an LED on and off.

What You Will Learn:

  • Control the GPIO with Scratch 2
  • Wire a button with a pull down resistor

Parts List

  • Breadboard
  • Push Button
  • 10k Ohm Resistor
  • 1k Ohm Resistor
  • LED
  • Some Jumper Wires

What is a Breadboard?

A breadboard is a prototyping platform that allows the easy creation of circuits without having to solder.  Each row of the breadboard is connected internally (not across the middle break). This mean that putting something into position 1a and 1b connects them electrically together while something plugged into position 1a and 2a are electrically isolated.  

The power rails on the left and right hand side of the breadboard are connected in a column and can be an easy way to access ground of power if you choose to route it there.  The color red and by extension the red column is often used for power while blue is often associated with ground and thus used for a ground connection.

What is a Resistor?

A resistor is an electrical component that has a specific value of resistance measured in ohms.  Resistors are used to restrict the amount of current in a circuit or facilitate a drop in voltage.  Its value of resistance can be read in ohms using the colored bands on the body of the resistor.

What is an LED?

An LED is a light emitting diode.  Diode’s are a class of electronic components that are designed to only allow current to pass through them in one direction.  This means that LEDs are polar meaning they have an anode (positive) and a cathode (negative). Current must flow into the anode and the cathode must be attached to ground.  

There are several methods of identifying the anode and cathode:

Look at the lengths of the pins, If the LEDs’ pin have not been modified the longer pin is the anode and the shorter pin is the cathode
Look at the sides of the LED a portion of the case will be flat the pin on that flat side is the cathode
Look inside of the bulb, each pin is connected to a flat piece of metal internally.  The pin that is attached to the larger piece is the cathode
An LED must have a current limiting resistor between it and ground or between it and power.  An unprotected LED will pull more and more current until it burns itself out. The value of the resistor will have an effect on the LEDs’ luminosity.  The higher the value of resistance the resistor has the less current will get to the LED and thus the dimmer the bulb will shine. The amount of current can be calculated in milliamps with Ohm’s Law, using the value in ohm’s for resistance

\text{current} = \frac{\text{voltage}}{\text{resistance}}

Getting Started:

Setting up the Hardware

When placing the button in the breadboard make sure that the pins are securely placed, it can be difficult.  Also note that the kinked leg of the LED in the diagram refers to the anode (positive) pin.

Setting up Scratch 2

Click on the Raspberry Pi icon in the upper left corner of the screen, click on Programming look for the cat icon and then click on Scratch 2.

Once the  Scratch 2 window opens click on More Block and then Add an extension.

Click on Pi GPIO to select it and then click on OK.

Now that we’ve added the blocks we need to communicate with the GPIO, Click on the Events tab and drag the “When flag clicked” block into the block area on the right hand side of the window.  

Click on the More Blocks tab and “set gpio __ to __” blocks to the “when flag clicked” block.  Fill in the blanks with 25 to input.

Next click on the Control tab and add a “forever” block to the bottom of the program.

Staying within the Control tab place an “if __ then” block inside of the “forever” block.

Next click on the More Blocks tab, place the “gpio __ is high?” block inside the “if __ then” block (place the left edge inside the hexagon).  Fill in the blank with 25.

Click on the Looks tab and place the “say Hello! For 2 seconds” block into the body of the “if __ then” block.

This is now a complete program, if you click on the green flag to start it, when you press the button on your breadboard the sprite will say “hello” for two seconds.

Now let’s also control the LED with the button as well.  Click on the More Blocks tab and drag a “set gpio __ to __” block above the “forever” block.  Fill in the blanks with 12 and output low.  This ensures that the LED will be off when the program starts.

Place a “set gpio __ to __” block before the “say Hello! For 2 seconds” block and one directly after.  In the first block fill in 12 and output high, in the second block fill in 12 and output low.

Now if you activate your program by clicking the flag, the button should activate both the sprite and blink the LED.

Whats Next?

  • Can you change the duration of the hello message and LED activation?
  • Can you make the LED blink a second time per button activation?

RPi Minecraft Cannon

Goal:

Using Minecraft’s API and the Python programming language, spawn a cannon that’s orientation and launch trajectory can be adjusted in real time.

What You Will Learn:

  • Introduction to Github

What is GitHub?

GitHub is an online repository that offers version control.  It is most often used for computer code and interacted with using a command line tool called git.

Getting Started:

Open a terminal either using the icon or the keyboard shortcut CTRL+ALT+t.

When opening the terminal like this we are placed in the home directory.  In RPi: Minecraft + Python Introduction we created a directory named code in the home directory.  We will now navigate into that directory using cd (change directory). Enter the following into the terminal.

cd code

You may have noticed that the prompt that was previously

pi@raspberrypi:~ $

Has now become

pi@raspberrypi:~/code $

It is informing you of the directory you are currently in, also known as the current working directory.  Remember that ~ (tilde) refers to the home directory.

 

Now that we are in our code directory, lets use git to download the cannon code from this GitHub repository

git clone https://github.com/martinohanlon/minecraft-cannon.git

Now the code has been cloned from the specified github repository into the current working directory.  Lets inspect ours with the ls (lists all files and directories)

ls

You should notice that a new directory “minecraft-cannon” has been created.  Lets navigate into the directory using cd and then inspect the contents using ls

cd minecraft-code

ls

There are several files and directories here, feel free to explore them using cd.  

Note that,

cd ..

will move your current working directory “up” one or backwards into the directory containing the current directory.

At this point we need to launch Minecraft and get into a game.

Once Minecraft is open, click Start Game then join a preexisting world or Create New.  

Back in the terminal we want Python to execute the “minecraft-cannon.py”.  If you left the directory we downloaded with git you can get back there with the following

cd ~/code/minecraft-cannon

Then,

python minecraft-cannon.py

this instructs the Raspberry Pi to use Python to run the “minecraft-cannon.py” file.

Your prompt in the terminal should have changed to

Stuffaboutcode.com Cannon >>

You can now use the following list of special commands to create, aim and fire a cannon in the running Minecraft game.

  • start
  • rotate [0-360]
  • tilt [0-90]
  • fire
  • exit

Start  spawns a cannon, exit an active cannon.  Using start multiple times in a row will construct multiple cannons however only the most recently made cannon can be controlled with the other commands.  You do not need to include the square brackets when typing the commands. 

Whats Next?

  • RPi: Minecraft Clock
  • RPi: Minecraft Snake

Article adapted from source

RPi Minecraft + Python Introduction

Goal:

Interact with Minecraft using the Python programming language and Minecraft’s application programming interface(API).

What You Will Learn:

  • Basic Python Programming
  • Use of the Minecraft API

What is an API?

To put it simply an API is a well defined method of interacting with some kind of software.  Think of it like the rules to a game, the rules dictate how the game is played and how you are able to interact with the game state.

What is Python?

Python is an interpreted programming language that is designed to be easy to learn and easy to use.  Python has many available libraries for the Raspberry Pi and is a very useful tool on the platform. Keep in mind that python uses white space (spaces, tabs, etc) to format and organize it’s instructions, take close care when typing to avoid these sometimes unobvious mistakes.

Getting Started:

Open a terminal either clicking the icon on the top bar or using the keyboard shortcut CTRL+ALT+t.

We are going to make a folder to store help organize the code we will be writing.  Enter the following into a terminal

mkdir ~/code

The mkdir command creates a new directory at the specified location, in this case “~/code”.

The “code” directory is created at the “~/” location ~ or tilde is a shortcut for the home directory.  We can verify the success of the command by entering

ls

In the terminal (this command lists all files and directories), or using a file explorer.

Next, open Thonny Python IDE by navigating to the Raspberry Pi icon in the upper left side of the desktop, click on Programming  and look at the bottom of the list for Thonny Python IDE.

Click on File and select New.

Click on File and Save As “minecraft_python.py” in the code folder we created earlier(/home/pi/code).

Now we are ready to start programming in Python.

Into your empty Python file type

import mcpi.minecraft as minecraft
import mcpi.block as block
from time import sleep

The “import” keyword load a specific code module.  The “as” keyword allows you to rename a code module to something else.  The “from” keyword allows you to load a submodule as it’s own module.

Currently this python program does nothing exciting however lets learn how to execute the program. You can either use they keyboard shortcut F5 or click on the green play icon.

After program execution the shell at the bottom of the window should have some lines of text appear, however nothing should else should happen.

Now type the following into your program

mc = minecraft.Minecraft.create()

mc.postToChat("Hello, world!")
sleep(5)

The first line creates an object that is connected to running an instance of Minecraft.  Setting it equal to mc lets us access the Minecraft game using mc within the code. The second line uses the mc object and a method “postToChat” to send text to the games chat.  The third line delays the program for the specified number of seconds, in this case 5 seconds.

Before running the code this time, we need to open Minecraft and enter a new world.  Click on the Raspberry Pi icon in the upper left, click on Games and then Minecraft Pi.

Once Minecraft is open, click Start Game then join a preexisting world or Create New.  

Using the tab key to free your mouse from the Minecraft window, run the code and switch back to the Minecraft window.  “Hello, world!” should appear in the chat.

Going back to the code, type in the following

playerPos = mc.player.getPos()
mc.player.setPos(playerPos.x, playerPos.y + 50, playerPos.z)
mc.postToChat("Don’t look down!")
sleep(5)

The position of the players head is stored in the playerPos object.  The players new position is then set relative to the previous position (In Minecraft you stand on the XZ plane with the Y axis being vertical).

 

Running this code will in addition to the previous action of sending text to the chat but then teleport the player 50 blocks vertically of their current position.

 

It is ideal to type in code whenever possible as it helps with learning however this next section is rather large and copy-paste will make quick work.

playerTilePos = mc.player.getTilePos()
blockBelowPlayerType = mc.getBlock(playerTilePos.x, playerTilePos.y - 1, playerTilePos.z)
mc.setBlock(playerTilePos.x + 1, playerTilePos.y + 1, playerTilePos.z, blockBelowPlayerType)
mc.setBlock(playerTilePos.x, playerTilePos.y + 1, playerTilePos.z + 1, blockBelowPlayerType)
mc.setBlock(playerTilePos.x - 1, playerTilePos.y + 1, playerTilePos.z, blockBelowPlayerType)
mc.setBlock(playerTilePos.x, playerTilePos.y + 1, playerTilePos.z - 1, blockBelowPlayerType)
mc.postToChat("Trapped you")
sleep(5)

mc.setBlock(playerTilePos.x + 1, playerTilePos.y + 1, playerTilePos.z, block.AIR)
mc.postToChat("Be free!")
sleep(5)

Notice that a different method is called to identify the position of the tile the player is standing in.  The setBlock method allows a single block specified with an (X,Y,Z) coordinate and a block

After running the code try to look back and see if you can identify what each line is doing.

Now add the following to your code.

mc.setBlocks(playerTilePos.x - 25, playerTilePos.y - 1, playerTilePos.z - 25, playerTilePos.x + 25, playerTilePos.y - 1, playerTilePos.z + 25, block.DIAMOND_BLOCK)
mc.postToChat("Now that's a big diamond floor!")

Notice that the setBlocks method unlike the setBlock method can take a range of X, Y, and Z coordinates.

Running the code this time in addition to the previous actions will change the blocks in a 50 x 50 x 1 shape 1 block beneath the players feet.

Whats Next?

  • Modify the code, move the player in different directions.  
  • Add additional blocks to the trap.
  • Try changing DIAMOND_BLOCK to another block type, a list of the block types can be found in the API documentation, about halfway down the page
  • Inspect the API documentation to see how else you can interact with Minecraft using Python

Article and code adapted from source