Showing posts with label headers. Show all posts
Showing posts with label headers. Show all posts

Wednesday, June 25, 2014

Using Javascript with Bonescript to program the Beaglebone Black

In this blog so far I have used Python for all programming examples however we are not limited to Python.   We can use many different programming languages to program the Beaglebone Black.  The “Offical” language for the Beaglebone Black is Javascript with the BoneScript library.  BoneScript is a Node.js library that is optimized for the BeagleBone and features Arduino function calls.  Since I am more familiar with Javascript than Python, I figured I would give BoneScript a try. 

Whenever we first dive into a new language or environment, we usually show the typical “Hello World” example.  I know I dislike the Hello World example too but it does show the basics of how Node.js, JavaScript and the BeagleBone Black work together.  If you are familiar with Node.js and Javascript, you can skip the Hello World section.

Hello World:

We will begin by connecting to the BeagleBone Black.  You can connect to it using SSH or by connecting a monitor/keyboard/mouse to the BeagleBone Black.  Once you get connected, open up a file called helloworld.js and insert the following line of code:

console.log("Hello, I am trapped inside");

Now run the following command:

node helloworld.js

This should print out the line “Hello, I am trapped inside”.  The console.log function simply prints out the message to the console.  In this case the console is the Linux shell that we are in.  We used the node command, from Node.js, to execute our Javascript code. 

First BoneScript script:

Now that we got the Hello World example out of the way, let create something somewhat useful.  The BeagleBone Black has four onboard user LEDs.  Lets make one of the user LEDs blink.  Here is the code:

var b = require('bonescript');

var ledPin = "USR3";

b.pinMode(ledPin, b.OUTPUT);
var state = b.LOW;
b.digitalWrite(ledPin, state);

setInterval(toggle, 500);

function toggle() {
    if(state == b.LOW)
        state = b.HIGH;
    else
        state = b.LOW;
    b.digitalWrite(ledPin, state);
}

The require function loads Node.js libraries/modules, therefore the first line loads the BoneScript library.  Next we define a variable named ledPin that conatins the string “USR3” which refers to the onboard LED USR3.

We then use the pinMode function to set the ledPin to b.OUTPUT.  This allows us to write to the pin.  Setting a pin to b.INPUT, means we want to read from it.  We now define our state variable to b.LOW and use the digitalWrite function to set the ledPin to low which turns the led off.

Once we have the ledPin configured and turned off, we use the Javascript function setInterval to call the toggle function every half a second.

The toggle function checks to see what the state is (b.LOW or b.HIGH) and reverses it.  The function then uses the BoneScript function digitalWrite to set the ledPin to the new state.

If we run the application using Node.js, the USR3 led will blink on and off until you stop the application with Ctrl-C.

Controlling an LED with the push of a Button

Now that we know how to use the BoneScript library, lets do something that is actually useful.  Let’s connect a LED and a button to our BeagleBone Black and turn the LED on when then button is pressed.

First thing we need to do is to wire up the button and the LED.  Whenever you connect items to your BeagleBone black, it is a very good idea to disconnect the power first.  Using a solder-less breadboard and jumper cables, connect the ground rail of your breadboard to pin 1 of the P9 expansion header.  Then use another jumper to connect the power rail of your breadboard to pin 3 of the P9 expansion header.  This will connect your breadboard to both power and ground.

Now lets add the LED to our breadboard.  Connect the cathode end of the LED (shorter wire) to the ground rail of our breadboard and then connect the anode end of the LED (longer wire) to one of the rows on our breadboard.

Now take the 100 OHM resistor and connect one end to the row on the breadboard that the LED is connected to and the other end of the resistor to another row on the breadboard.  Finally run a jumper from pin 8 of the P8 expansion header to the row that the 100 OHM resistor is connected too.  Now that our LED is connected, lets connect the button.

You will want the button to straddle the middle section as show in the image below.  Using a jumper, connect the power rail of your breadboard to one end of the button.  Next connect the same end of the button to the ground rail of your breadboard using the 10K pulldown resistor.  Finally connect the other end of the button to pin 11 of the P8 expansion header.  The connections should look like this image but hopefully you did a neater job hooking up the wires then I did.



Now lets write our Bonescript code to make the LED turn on with the push of a button.

var b = require('bonescript');

var ledPin = "P8_8";
var buttonPin = "P8_11";

b.pinMode(ledPin, b.OUTPUT);
b.pinMode(buttonPin, b.INPUT);

b.attachInterrupt(buttonPin, true, b.CHANGE, buttonChange);

function buttonChange(button) {
    if(button.value == b.HIGH)
            state = b.HIGH;
        else
           state = b.LOW;
    b.digitalWrite(ledPin, state);
}

We begin by loading the Bonescript library and defining the ledPin and buttonPin variables that define what pins the LED and Button are connected to on the BeagleBone Black.  P8_8 defines that the LED is connected to pin 8 of the P8 header and P8_11 defines that the button is connected to pin 11 of the P8 header.

We use the pinMode function to set the ledPin to b.OUPUT which means we want to write to the pin.  We set the buttonPin to b.INPUT because we want to read the pin.

We then use the attachInterrupt function to define an interrupt whenever the buttonPin changes.  If we used b.RISING or b.FALLING instead of b.CHANGE, the interrupt would be triggered only when the pin went high or low.  The last argument in the attachInterrupt function defines the function to call when the interrupt is triggered; in this case the function to call is the buttonChange function.

The buttonChange function sets the led pin to either b.HIGH or b.LOW depending on the state of the button.


Using Node.js to load external Javascript files

To create really useful applications for the BeagleBone Black, like robots or home automation applications, we will need to use multiple files to organize our code but Javascript is not designed to include one Javascript file in another Javascript file.  Node.js can help us with this problem.   Lets begin by creating a Javascript file called hello.js that includes both a variable and a function that we will use in another Javascript file.

var name = "JON"

function sayHello() {
      console.log("Hello World");
}
module.exports.sayHello = sayHello;
module.exports.name = name;

This file defines the variable name and the function sayHello.  We then use module.exports to expose the internally scoped function and variable. 

Now lets look at how we would use the name variable and the sayHello function.

var hello = require("./hello.js")
console.log(hello.name);
hello.sayHello();

We begin by using the require function to include the hello.js file that we just wrote. We can then use the hello variable to access the name variable and the sayHello function.

Cloud9 IDE

I know the Angstrom distribution comes with a Javascript IDE called Cloud9 preinstalled (not sure about the other distributions).  To use Cloud9, open a web browser and enter the IP address of your BeagleBone Black with port 3000 as the URL.  For example, if the IP address of your BeagleBone Black is 10.0.1.18, the URL would look like this:  10.0.1.18:3000.  The IDE interface looks like this.



Personally, I do not really care for Cloud9 so I have not used it that much but I did want to mention it here in case you wanted to give it a try.

Conclusion


Personally I like Javascript but I do believe that I can do a lot more with Python, like including Bluetooth communication, than with Javascript however for projects that do not need access to external hardware components like Bluetooth adapters or cameras, I might give Javascript/BoneScript a try.

Sunday, May 18, 2014

My first working robot, It’s Alive

Over the weekend I successfully connected my BeagleBone Black to a Dagu Rover 5 Tracked Chassis using the Rover 5 motor driver board.  I was then able to write Python client/server scripts that allowed me to controller the robot over a Bluetooth RFComm connection.  You can see the video of my first successful test drive below.  The next few posts will document the steps it took to get this working.

Here is the video of my first successful test drive.  For those of you thinking that this is actually a remote controller vehicle and not a robot, you are right but this is the pretty huge step towards my goal of creating a robot because I want my robot to be mobile.


This post will describe how to connect the BeagleBone Black to the Motor driver board and the Rover 5 Tracked Chassis.   I am assuming that you have the basic understanding of the BeagleBone Black expansion headers as described in my “Playingwith LEDs” post and have set the Adafruit_BBIO Python library as described in my “I just got myBeagleBone Black, now what?” post.

Connecting the Motor Controller to your Tracked Chassis:
The chassis I choose is the Rover 5 Tracked Chassis that contains a battery holder, two DC motors and a quadrature encoder for each tread.  For the motor controller I chose the four channel Rover 5 Motor Driver Board. As you can probably tell by the names, these are kind of designed to work together which makes it a lot easier for a beginner like myself.  Below are pictures of the motor controller and the chassis.




In this section we will be connecting the encoder and the power for the motor from the chassis to the motor controller.  From each motor housing, there is a think black power cable for the motors and four small wires, each with female connectors, which go to the encoder.  These connectors are:
RED:  +5V for the encoder
BLACK:  Ground
WHITE:  Input signal A
YELLOW:  Input signal B
To connect the Chassis to the motor driver board, we connect the thick motor power cable from the motor housing to the motor output connector on the motor controller.  We will then connect the four encoder cables to the encoder connections on the motor driver board.  Make sure you do not cross up the red (5V) and the black (ground) wires as this could damage the encoders.  This image shows how I made the connections.



Connecting the BeagleBone Black to the Motor Controller:
Now that we have the chassis connected to the motor controller, lets connect the BeagleBone Black to the motor controller.  Remember to disconnect the power to the BeagleBone Black prior to connecting it to the motor controller.  We will want to connect two PWM pins and two digital pins from the BeagleBone Black to the motor controller.

We will be connecting PWM pins 13 and 19 from the P8 expansion header and the digital pins 14 and 16 also from the P8 expansion header to the motor controller.  The image below shows a close up of the BeagleBone Black with the yellow wires connected to the PWM pins and the green wires connected to the digital pins.

I am running PWM pin 13 and digital pin 14 to one encoder and PWM pin 19 and digital pin 16 to the other encoder.  You can see how the wires are connected here:


Running Power to the Motor Controller:
Now lets connect power to the motor controller.  We have two power inputs on our motor controller.  One input is for +5V for logic and the other is to power the motors.  The motor controller is rated for a maximum motor supply voltage of 12V.  I am using the 6AA battery holder that came with the chassis to supply the motor power.  Note:  Do not put the batteries in the battery holder until everything is connected.
On the motor controller board, one of the power inputs is labeled “Vbat” and the other is labeled “VCC”.  We will connect the 6AA battery holder to the power input labeled “Vbat”.   We will then run 5V (pin 7 of expansion header P9) and ground (pin 1 of expansion header P9) from the BeagleBone Black to the power input label “VCC” on the motor controller.
Now we can put the batteries in the battery holder and power up the BeagleBone Black.

Testing the Connection:
Now that we have everything connected and powered up, lets see if we have everything connected correctly.  Lets create a script called rovertest.py and add the following code to it:
#!/usr/bin/python

import Adafruit_BBIO.PWM as PWM
import time

pin = "P8_13"

PWM.start(pin,0)
for i in range(0, 100):
              PWM.set_duty_cycle(pin,75)
              time.sleep(.1)

PWM.stop(pin)
PWM.cleanup()

We need to make sure that the chassis is not on the ground when we run the script because we do not want the chassis to actually move since the BeagleBone Black is still connected to the computer.  What I did was to type in “python rovertest.py”, picked up the chassis and then pressed enter to run the script.  If everything is connected correctly, one of the tracks should run for 10 seconds and then stop.  To test the other track, change the ‘pin = “P8_13”’ line to ‘pin = “P8_19”’ and rerun the script.

The next post will cover how to connect and configure a Bluetooth adapter with the BeagleBone Black running Angstrom Linux.  This will give us the ability to control our robot remotely so we do not need to have our robot connected to a computer.

Part 2:  http://myroboticadventure.blogspot.com/2014/05/my-first-working-robot-its-alive-part-2.html
Part 3:  http://myroboticadventure.blogspot.com/2014/05/my-first-working-robot-its-alive-part-3.html

Monday, May 12, 2014

Playing with buttons

I should be getting my Rover 5 Motor Driver Board to go with my Rover 5 Chassis within the next day or so.  This means I can start (for the third time) building my first robot.  Hopefully this time I will have more success then my first two attempts.  Before the new board arrives I wanted to write a post that will show how to use Python with the Adafruit library to read the state of a button.

What we need:
For the experiments in this post we will need a breadboard, a push button, four solder-less jumpers and a 10K ohm resister.  All of these parts come with Make’s Getting started with the BeagleBone Black kit that I mention in my Introduction post.  The 10K ohm resistor is the resister with the brown-black-orange-(gold or silver) bands.  If you want to find out the value of your resistors but you are not familiar with the resistor color codes, I would recommend using this digikeypage.

Our BeagleBone:
Rather than rehashing the information about the BeagleBone’s Expansion Headers here, I recommend that you read the “Our BeagleBone” section of my last post “Playing with LEDs” if you are not familiar with the expansion headers.

The Breadboard:
Lets jump right in and connect our external components to our breadboard.  Keep in mind, that whenever you connect items to your BeagleBone Black, it is a good idea to disconnect the power to the BeagleBoard first.

Using a solder-less jumper, connect the ground rail of your breadboard to pin 1 of the P9 expansion header.  Then use another solder-less jumper to connect the power rail of your breadboard to pin 3 of the P9 expansion header.  This will connect your breadboard to both power and ground.

Now lets add the push button to the breadboard.  You will want the button to straddle the middle section as show in the image below.  Using a solder-less jumper, connect the power rail of your breadboard to one end of the button.  Next connect the same end of the button to the ground rail of your breadboard using the 10K pulldown resistor.  Finally connect the other end of the button to pin 11 of the P8 expansion header.  The connections should look like the following image but hopefully you did a neater job hooking up the wires then I did.



Power up and writing code:
New lets power up our BeagleBone and write some code to monitor our button.  This first example can be used to check the current state of the button.  Create a file called “button.py” and add the following code.

#!/usr/bin/python

import Adafruit_BBIO.GPIO as GPIO
import time

GPIO.setup("P8_11", GPIO.IN)
while True:
                            if GPIO.input("P8_11"):
                            print "The button was pressed"
          time.sleep(.01)

Now run the script with this command:

python button.py

If everything is connected correctly, when you press the button you should see “The button was pressed” message appearing on the screen.  If you hold the button down you will see lots of “The button was pressed” messages.

The script starts off by importing the Adafruit_BBIO.GPIO and time libraries that are needed.  The next line sets pin 11 on expansion header P8.  You saw in the last post “Playing with LEDs” that when we set the pin to GPIO.OUT we wrote data to the pin.  For this post we want to read data from the pin so we set the pin to GPIO.IN.

We then create an endless loop and within that loop we check pin 11 of expansion header P8 using the GPIO.input function.  This function returns true if the button is pressed and false if the button is not being pressed.  We then pause for one-tenth of a second and check again.

This script works great if you want to check the current state of a button but what if we wanted to wait for the button to be pressed.  We could create an endless loop and then break out of it when the GPIO.input() function returned true but that is kind of a messy if you ask me.  Luckily there is a better way.  Try this next script; it waits for the status of the button to reach a certain state and them moves on.

#!/usr/bin/python

import Adafruit_BBIO.GPIO as GPIO
import time

GPIO.setup("P8_11", GPIO.IN)
while True:
              GPIO.wait_for_edge("P8_11", GPIO.RISING)
              print "Button Pressed"
              GPIO.wait_for_edge("P8_11", GPIO.FALLING)
              print "Button Released"

The GPIO.wait_for_edge() function waits for the state of the button to change.  In this script we wait for the button to be pressed (GPIO.RISING) and then waits for the button to be released (GPIO.FALLING).  You could also use GPIO.BOTH to wait for any change in the button’s state.


Hopefully my motor driver board will arrive in the next day or so and I can begin trying to get a robot working.  Whether the project is a success or another failure, I will write a post explaining what I did and how it worked.

Sunday, May 11, 2014

Playing with LEDs

Now that I had my BeagleBone Black setup as documented in my first post, I wanted to start building ROBOTS.  This is where I wasted a lot of time and money because I really did not understand how the BeagleBone Black worked or what I really needed.  So rather than diving right into building robots, lets spend a little time trying to understand how we can program the BeagleBone Black to control an external component like an LED (Light-Emitting Diode).

For the experiments in this post you will need a breadboard, an LED, three solder-less jumper cables and one 100 ohm resister.  All of these parts come with Make’s Getting startedwith the BeagleBone Black kit that I mention in my Introduction post.  The 100 ohm resister is the resister with the Brown-Black-Brown-(gold or silver) bands.  If you want to find out the value of your resistors but you are not familiar with the resistor color codes, I would recommend using this digikeypage.

Our BeagleBone:
In this section we will take a look at our BeagleBone Black and explain how we would connect external components to it.  If you look at this image from the BeagleBone Black’s documentation, you will see that our BeagleBoard Black has two expansion headers, they are the black connection strips on either side of the board.  


If you look closely at the board itself, you will see that each expansion header is labeled with its name (P8 or P9).  You will also notice that one end of the expansion header is labeled with a 1 and a 2 while the other end is labeled with a 45 and 46.  These labels represent the pin numbers of the headers. 

Now lets look at the Cape expansion headers image that is also from the BeagleBone Black documentation.  This image shows you how each pin is labeled and also which pins connect to power and ground.



For our first LED projects, we will want to use one of the digital I/O pins because all we want to do is to turn the LED on or off.  This next image, once again from the BeagleBone Black documentation, shows the possible digital I/O pins.



For our first LED experiment we will be using pins 1 and 3 on expansion header P9 to supply the ground and power respectively to our breadboard.  We will also use pin 8 (labeled GPIO_67) on the P8 expansion header for our digital I/O that will control the LED.

The Breadboard:
Now lets connect our external components to our breadboard.  Whenever you connect items to your BeagleBone black, it is a very good idea to disconnect the power first. 

Using a solder-less jumper, connect the ground rail of your breadboard to pin 1 of the P9 expansion header.  Then use another solder-less jumper to connect the power rail of your breadboard to pin 3 of the P9 expansion header.  This will connect your breadboard to both power and ground.

Now lets add the LED to our breadboard.  Connect the cathode end of the LED (shorter wire) to the ground rail of our breadboard and then connect the anode end of the LED (longer wire) to one of the rows on our breadboard.

Now take the 100 OHM resistor and connect one end to the row on the breadboard that the LED is connected to and the other end of the resistor to another row on the breadboard.  Finally run a solder-less jumper from pin 8 of the P8 expansion header to the row that the 100 OHM resistor is connected too.

The connections should look similar to the following image but hopefully you were neater hooking up the wires then I was.


Power up and writing code:
Now lets power up our BeagleBone.   The recommended way to program the BeagleBone Black is to use Bonescript which is an extension of Javascript however I will be using Python with the Adafruit_BBIO library more throughout this blog.  Once I get better with bonescript, maybe I will start using it more.  If you following the Setup Python section of my last post you have the Adafruit_BBIO library setup, if not you will need to setup Adafruit_BBIO before going any further.

I would recommend creating a directory to keep your python scripts in, this way they are not scattered throughout your system.  In your scripts directory create a file called “ledon.py” and add the following code:

#!/usr/bin/python
import Adafruit_BBIO.GPIO as GPIO
import time

GPIO.setup("P8_8",GPIO.OUT)
GPIO.output("P8_8", GPIO.HIGH)
time.sleep(5)

Now run the script with this command:

python ledon.py

If everything is setup correctly, the led will light up for five seconds and then shutoff.  Lets take a look at how this short script works.  We start off by importing the Adafruit_BBIO.GPIO and time libraries that are needed.  The next line sets up pin 8 on expansion header P8.  GPIO.OUT defines that we want to write to this pin (output data).   If we wanted to read the pin (as if we had a button connected), we would use GPIO.IN like this:  GPIO.setup(“P8_8”,GPIO.IN).  We then set pin 8 to GPIO.HIGH, which turns the LED on (GPIO.LOW would turn the LED off).  Finally we wait five seconds and the script then ends which resets the pin turning the LED off.

If we set pin 8 to GPIO.HIGH to turn it on, then setting the pin to GPIO.LOW should turn the LED off.  Using this assumption lets create a script that will cause the LED to blink on and off.

#!/usr/bin/python
import Adafruit_BBIO.GPIO as GPIO
import time

GPIO.setup("P8_8",GPIO.OUT)
while True:
              GPIO.output("P8_8", GPIO.HIGH)
              time.sleep(.5)
              GPIO.output("P8_8", GPIO.LOW)
              time.sleep(.5)

If you save and run this script, your LED should blink on and off indefinitely until you stop the script.  From here you can experiment some more with your LED.  I am wondering if I can use something like this next winter to control my Christmas lights.  Maybe turn certain lights on or off at various time intervals.

Turning a LED on and off is a pretty cool first step but how about having the LED slowly get brighter.  Can we do this?  Yes we can.  We can use one of the PWM pins for analog writes.  The PWM pins are shown in this image that also comes with the BeagleBone Black documentation.



Power down your BeagleBone black and move the jumper from pin 8 of the P8 expansion header to pin 13.  Then run this script:

#!/usr/bin/python
import Adafruit_BBIO.PWM as PWM
import time

PWM.start("P8_13",0)
for i in range(0, 100):
              PWM.set_duty_cycle("P8_13",float(i))
              time.sleep(.1)

PWM.stop("P8_13")
PWM.cleanup()

Your LED will slowly get brighter until it reaches full brightness and then shuts off when the script ends. 


In my next post, I will show how we can read the state of a button with python and the Adafruit_BBIO library.  In the mean time have fun playing with the LED.