tag:blogger.com,1999:blog-90076015626061570162024-03-13T14:20:03.312+00:00<Stuff about="code" />about = (stuff == 'code')Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.comBlogger136125tag:blogger.com,1999:blog-9007601562606157016.post-77576658764504389322018-06-17T21:23:00.000+01:002018-06-17T21:23:44.003+01:00Pi Camera stop motion animationIn preparation for a Raspberry Pi event I decided to create a simple GUI for creating stop motion animations using the Pi camera module to use for a demo.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-h3scK7pf8AQ/Wya8eWgS7kI/AAAAAAAAbp0/MwQrsW5Leg4PvL6-06Nv-QHGSMQZ961YgCLcBGAs/s1600/picamera_setup.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="1578" data-original-width="1600" height="315" src="https://4.bp.blogspot.com/-h3scK7pf8AQ/Wya8eWgS7kI/AAAAAAAAbp0/MwQrsW5Leg4PvL6-06Nv-QHGSMQZ961YgCLcBGAs/s320/picamera_setup.jpg" width="320" /></a></div>
<br />
Its a really simple application, you start it up, you click "take image", you re-position the scene, you click "take image" and so on until you are happy with your animation and you click "save" to store it as an animated gif.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-tfPhGpyoAlg/Wya8MKEPKLI/AAAAAAAAbps/St_t6bpLodwMNGHCRysLKMMZI-hvXUaTgCLcBGAs/s1600/Df5PZAGXUAA3IM7.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="493" data-original-width="468" height="320" src="https://1.bp.blogspot.com/-tfPhGpyoAlg/Wya8MKEPKLI/AAAAAAAAbps/St_t6bpLodwMNGHCRysLKMMZI-hvXUaTgCLcBGAs/s320/Df5PZAGXUAA3IM7.jpg" width="303" /></a></div>
<span id="goog_1990565738"></span><span id="goog_1990565739"></span><br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-OCzezlRx2jE/Wya84rtsmkI/AAAAAAAAbqA/DXrkZ_vXq1QLLcmIhnuyFfAlmo5L4RbmgCLcBGAs/s1600/animation1529238449.919678.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="480" data-original-width="640" height="240" src="https://1.bp.blogspot.com/-OCzezlRx2jE/Wya84rtsmkI/AAAAAAAAbqA/DXrkZ_vXq1QLLcmIhnuyFfAlmo5L4RbmgCLcBGAs/s320/animation1529238449.919678.gif" width="320" /></a></div>
<br />
You can find the source code at <a href="https://goo.gl/4Xvu7b">goo.gl/4Xvu7b</a>.<br />
<br />
<b>Install</b>
<br />
1. Connect a camera module<br />
2. Enable the camera (Menu > Preferences > Raspberry Pi Configuration, Interfaces, Camera)<br />
3. Open a terminal (Menu > Accessories > Terminal), install the modules and download the code:<br />
<pre class="prettyprint">sudo pip3 install guizero
sudo pip3 install imageio
wget -O guizero_stopmotion.py https://goo.gl/zMTjas</pre>
4. Run the program:
<br />
<pre class="prettyprint">python3 guizero_stopmotion.py</pre>
<br />
<b>A couple of "interesting" things about this project</b><br />
<b><br /></b>
The gui was created using <a href="https://lawsie.github.io/guizero/">guizero</a> which is a super simple to use library for creating GUI's, definitely have a look.<br />
<br />
Most of the work was finding a way to create animated gifs in Python and working with images in memory rather than stored on disk<br />
<br />
When the image is captured from the camera it isn't stored to a file, it is stored in a numpy array, this means each frame is only stored in memory making it faster:<br />
<pre class="prettyprint"># create the camera
camera = PiCamera(resolution="640x480")
camera_output = PiRGBArray(camera)
...
# capture the image
camera.capture(camera_output, "rgb")
# append the camera image to the list as a numpy array
animation.images.append(camera_output.array)</pre>
The python module imageio is used to create the gif by passing the frames as a list, but again rather than being written to disk each time it is created as an in memory BytesIO stream:<br />
<pre class="prettyprint">gif_output = BytesIO()
imageio.mimsave(gif_output, animation.images, format="gif")</pre>
When the animated gif is displayed in guizero the BytesIO stream has to be open into a PIL Image.<br />
<pre class="prettyprint">animation.image = Image.open(gif_output)</pre>
<br />
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com2tag:blogger.com,1999:blog-9007601562606157016.post-23957411642520854772018-06-09T21:58:00.000+01:002018-06-17T21:24:00.086+01:00Get the weather using PythonI recently spent a hour or so hacking a lucky cat so that it would only wave when it was sunny.<br />
<blockquote class="twitter-tweet" data-lang="en">
<div dir="ltr" lang="en">
At <a href="https://twitter.com/Raspberry_Pi?ref_src=twsrc%5Etfw">@Raspberry_Pi</a> 's MakerDay I hacked a lucky cat so it only waves when it's sunny. <a href="https://t.co/JUED5nYadt">pic.twitter.com/JUED5nYadt</a></div>
— Martin O'Hanlon (@martinohanlon) <a href="https://twitter.com/martinohanlon/status/1005342439874486273?ref_src=twsrc%5Etfw">June 9, 2018</a></blockquote>
<script async="" charset="utf-8" src="https://platform.twitter.com/widgets.js"></script>
It did this by pulling the weather data from <a href="https://openweathermap.org/">Open Weather Map</a> using the Python module <a href="https://github.com/csparpa/pyowm">pyowm</a>.<br />
<br />
<b>1.</b> <a href="https://home.openweathermap.org/users/sign_up">Sign up for a free API key in Open Weather Map</a>.<br />
<br />
<b>2.</b> Install the pyown Python module, open a <b>Terminal</b> or <b>Command Prompt</b> and run:<br />
<br />
<i>Windows</i><br />
<pre class="prettyprint">pip install pyown</pre>
<br />
<i>Raspberry Pi / Linux</i><br />
<pre class="prettyprint">sudo pip3 install pyown</pre>
<br />
<i>MacOS</i><br />
<pre class="prettyprint">pip3 install pyown</pre>
<br />
<b>3.</b> Create a Python program using the following code, inserting your API key:
<br />
<pre class="prettyprint">import pyowm
owm = pyowm.OWM('put api key here')
observation = owm.weather_at_place('Cambridge,GB')
w = observation.get_weather()
clouds = w.get_clouds()
wind = w.get_wind()
humidity = w.get_humidity()
temp = w.get_temperature('celsius')
print("{}, {}, {}, {}".format(clouds, wind, humidity, temp)
</pre>
<br />
Note - it can take up to 60 minutes for your API key to be activated.<br />
<br />
There is a lot more information which can be pulled back - have a look at the <a href="https://pyowm.readthedocs.io/en/latest/pyowm.webapi25.html#module-pyowm.webapi25.weather">weather module documentation</a> for more details.<br />
<br />
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com0tag:blogger.com,1999:blog-9007601562606157016.post-65135976638259244412018-03-04T08:20:00.001+00:002018-06-17T21:24:00.117+01:00Python - Creating shortcutsI was recently working on the <a href="https://mu.readthedocs.io/">mu</a> project (a Python IDE for beginners), which is super easy to install using pip, but there is no way to automate the creation of desktop and menu shortcuts.<br />
<div>
<br /></div>
<div>
This seemed like a really big miss, shortcuts are the usual way for people (and certainly beginners to launch applications).</div>
<div>
<br /></div>
<div>
So I set to creating a really simple way of creating shortcuts for Python applications.</div>
<div>
<br /></div>
<div>
Enter <a href="http://shortcut.readthedocs.io/en/latest/">shortcut</a>, a X platform (Windows, MacOS, Linux, Raspberry Pi) Python module for automatically creating shortcuts.</div>
<div>
<br /></div>
<div>
Its really simple to <a href="http://shortcut.readthedocs.io/en/latest/#install">install</a> and <a href="http://shortcut.readthedocs.io/en/latest/app.html">use</a>:</div>
<pre class="prettyprint">pip3 install shortcut
shortcut name_of_app</pre>
<div>
It will find the location of the app and create desktop and menu shortcuts for it.</div>
<div>
<br />
There is also a <a href="http://shortcut.readthedocs.io/en/latest/api.html">Python API</a> which can be used to do the same:</div>
<pre class="prettyprint">from shortcut import ShortCutter
s = ShortCutter()
s.create_desktop_shortcut("python")
s.create_menu_shortcut("python")
</pre>
<div>
You will find documentation at <a href="http://shortcut.readthedocs.io/en/latest">shortcut.readthedocs.io</a> and code at <a href="https://github.com/martinohanlon/shortcut">github.com/martinohanlon/shortcut</a>.</div>
<div>
<br /></div>
Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com1tag:blogger.com,1999:blog-9007601562606157016.post-33333133315095645262017-12-29T22:47:00.001+00:002018-06-03T08:06:25.375+01:00Setup Raspberry Pi Samba shareI almost always setup a samba share on every Raspberry Pi I install, it allows me to easily share files and work on my projects - so I thought I had better write down how I do it.
<br />
Install samba:<br />
<pre class="prettyprint">sudo apt-get install samba</pre>
Modify the Samba config file to add a share called pihome which points to the /home/pi directory:<br />
<pre class="prettyprint">sudo nano /etc/samba/smb.conf</pre>
Scroll to the bottom and add the following:<br />
<br />
<pre class="prettyprint">protocol = SMB2
[pihome]
comment= Pi Home
path=/home/pi
browseable=Yes
writeable=Yes
only guest=no
create mask=0644
directory mask=0755
public=no</pre>
<br />
Setup a samba password for the Pi user:<br />
<pre class="prettyprint">sudo smbpasswd -a pi</pre>
Restart the samba service:<br />
<pre class="prettyprint">sudo service smbd restart</pre>
You should now be able to connect to your Pi using the address:<br />
<pre class="prettyprint">//ip_address_of_pi/pihome</pre>
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com0tag:blogger.com,1999:blog-9007601562606157016.post-65032799792796202422017-11-15T20:56:00.001+00:002017-11-15T20:57:28.569+00:00Slack command line streamI thought a Slack console might be useful, a very simple client I could display on an always on screen, so I did some experimenting with the <a href="https://slackapi.github.io/python-slackclient/">Slack Developer Kit for Python</a> and made a super simple command line program which streams messages.<br />
<br />
It is most definitely a starting point rather than a finished solution, but someone might find it useful.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-2gv3ZRpt1DE/Wgyp-uZjnAI/AAAAAAAAYfw/QK7ST9EwHjE-LGMJ2YclPWJ16xUjeB5MwCLcBGAs/s1600/commandlineslack2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="371" data-original-width="640" height="185" src="https://2.bp.blogspot.com/-2gv3ZRpt1DE/Wgyp-uZjnAI/AAAAAAAAYfw/QK7ST9EwHjE-LGMJ2YclPWJ16xUjeB5MwCLcBGAs/s320/commandlineslack2.png" width="320" /></a></div>
<br />
<b>Setup</b> (assuming you are using a Raspberry Pi / Linux computer, although it will work on Windows as well).<br />
<br />
1. Generate a <a href="https://api.slack.com/custom-integrations/legacy-tokens">security token</a> for the slack group you want to stream.<br />
<br />
<div>
2. Create an environment variable SLACK_API_TOKEN and put your security token in it.<br />
<br />
Edit /etc/profile adding the export to the bottom:
<br />
<pre class="prettyprint">sudo nano /etc/profile
export SLACK_API_TOKEN=[my super long token]</pre>
</div>
<div>
3. Install slackclient and colorama using pip:<br />
<pre class="prettyprint">sudo pip3 install colorama
sudo pip3 install slackclient</pre>
</div>
<div>
4. Download the <a href="https://gist.github.com/martinohanlon/477b6ea4c3bdc679ddff92dfc3bff4a7">slack_stream.py from gist</a>:<br />
<pre class="prettyprint">wget https://gist.githubusercontent.com/martinohanlon/477b6ea4c3bdc679ddff92dfc3bff4a7/raw/8ec39d08a9501b25d381ac3b008e9cf7be92377a/slack_streamer.py
</pre>
</div>
<div>
5. Run it:<br />
<pre class="prettyprint">python3 slack_streamer.py</pre>
</div>
Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com2tag:blogger.com,1999:blog-9007601562606157016.post-60148657208452945422017-07-07T15:37:00.002+01:002017-07-07T16:55:17.492+01:00Python Bluetooth RFCOMM Client ServerAs part of the <a href="http://www.stuffaboutcode.com/2017/04/bluedot-bluetooth-remote-for-raspberry.html">Blue Dot</a> project I needed to create a simple Bluetooth client / server library so that the communication could be managed. This library, <a href="http://bluedot.readthedocs.io/en/latest/btcommapi.html">btcomm</a>, is part of bluedot but its not exclusive and can be used for Bluetooth communication in Python.<br />
<br />
It uses a 2 way RFCOMM communication - you can send messages to and from 2 devices, 1 being the server which waits for connections, 1 being the client which makes a connection.<br />
<br />
<b>Install the library</b><br />
<pre class="prettyprint">sudo apt-get install python3-dbus
sudo pip3 install bluedot
</pre>
<br />
<b>Pairing</b><br />
<br />
The 2 devices you which want to communicate between will need to be paired, the Blue Dot documentation describes <a href="http://bluedot.readthedocs.io/en/latest/pairpipi.html">how to pair 2 raspberry pi's</a> which might be useful.<br />
<br />
<b>Simple Client / Server Example</b><br />
<div>
<span class="n">Lets create a simple example, a server which waits for connections and when it receives data it echo's it back to the client.</span></div>
<div>
<span class="n"></span><span class="n"><br /></span>
<span class="n">Create a new Python program and save it as btserver.py:</span><span class="n"><br />
</span><br />
<pre class="prettyprint"><span class="n">from bluedot.btcomm import BluetoothServer
from signal import pause
def data_received(data):
print(data)
s.send(data)
s = BluetoothServer(data_received)
pause()</span></pre>
</div>
<div>
<span class="n"><br /></span>
<span class="n">Create a 2nd program and save it as btclient.py:</span></div>
<pre class="prettyprint">from bluedot.btcomm import BluetoothClient
from signal import pause
def data_received(data):
print(data)
c = BluetoothClient("nameofyourserver", data_received)
c.send("helloworld")
pause()
</pre>
<div>
<span class="n"><br /></span></div>
Run the server and then run the client, the client should connect and "Hello World" will be sent to the server and displayed on the screen, the server will then send the same "Hello World" message back to the client, which will print it to the screen.<br />
<br />
<b>Adapter</b><br />
<br />
There is also a useful API for accessing the Bluetooth adapter allowing you to get its current status, power it on/off, make it discoverable or find the devices its paired with.<br />
<pre class="prettyprint">from bluedot.btcomm import BluetoothAdapter
a = BluetoothAdapter()
print("Powered = {}".format(a.powered))
print(a.paired_devices)
a.allow_pairing()</pre>
<br />
<b>Documentation</b><br />
<b></b><br />
There is comprehensive documentation for the <a href="http://bluedot.readthedocs.io/en/latest/btcommapi.html">btcomm library</a>, which describes the API and how to use it.<br />
<br />
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com0tag:blogger.com,1999:blog-9007601562606157016.post-50549240998282897052017-07-04T21:53:00.001+01:002017-07-04T21:53:49.849+01:00Mac OS - Check Java version before running scriptI needed to check what version of Java was installed on a Mac before running my program, so with the help of <a href="https://stackoverflow.com/questions/7334754/correct-way-to-check-java-version-from-bash-script">stackoverflow</a> and a few other resources I pulled together the following bash script which checks to see if the version of Java is greater than 1.8 before continuing.<br />
<pre class="prettyprint">
# Work out the JAVA version we are working with:
JAVA_VER_MAJOR=""
JAVA_VER_MINOR=""
JAVA_VER_BUILD=""
# Based on: http://stackoverflow.com/a/32026447
for token in $(java -version 2>&1 | grep -i version)
do
if [[ $token =~ \"([[:digit:]])\.([[:digit:]])\.(.*)\" ]]
then
JAVA_VER_MAJOR=${BASH_REMATCH[1]}
JAVA_VER_MINOR=${BASH_REMATCH[2]}
JAVA_VER_BUILD=${BASH_REMATCH[3]}
break
fi
done
#check version is greater than 1.7 (i.e. at least 1.8)
if [ "$JAVA_VER_MAJOR" -gt "1" ]; then
echo start your program
elif [ "$JAVA_VER_MINOR" -gt "7" ]; then
echo start your program
else
echo ERROR - Java needs to be updated.
echo Currently installed version is $JAVA_VER_MAJOR.$JAVA_VER_MINOR - 1.8 is required
fi
</pre>Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com2tag:blogger.com,1999:blog-9007601562606157016.post-36949586222088149742017-05-05T18:07:00.000+01:002017-05-05T18:08:14.555+01:00Raspberry Pi Touchscreen PortraitI recently wanted to turn my Raspberry Pi Official Touchscreen portrait (i.e. sideways!), which turns out is a bit of pain. <br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-yW0iFK-t9Do/WQyxOFw1EHI/AAAAAAAAWUk/_kYxUNEYEfoqvDrq5n_vE3xIotfjaM97QCLcB/s1600/IMG_20170501_174954646_HDR.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://2.bp.blogspot.com/-yW0iFK-t9Do/WQyxOFw1EHI/AAAAAAAAWUk/_kYxUNEYEfoqvDrq5n_vE3xIotfjaM97QCLcB/s320/IMG_20170501_174954646_HDR.jpg" width="180" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
Turning the display is relatively easy but making the touch work is more difficult - there was a <a href="https://www.raspberrypi.org/forums/viewtopic.php?p=1084567#p1084567">set of instructions on the Raspberry Pi forum</a>, but a <a href="https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=172025">recent update to Jessie meant they no longer worked</a>, so I pulled this set of instructions together:<br />
<br />
<b>Install xinput:</b><br />
<pre class="prettyprint">sudo apt-get install xinput</pre>
<b>Rotate the display by editing config.txt:</b><br />
<pre class="prettyprint">sudo nano /boot/config.txt</pre>
.. add this to the buttom of the file:<br />
<pre class="prettyprint">display_rotate=1</pre>
Use Ctrl X, Yes to Save<br />
<b>Create a script to rotate the touchscreen:</b><br />
<pre class="prettyprint">nano /home/pi/touch_rotate.sh</pre>
.. add the following command<br />
<pre class="prettyprint">xinput --set-prop 'FT5406 memory based driver' 'Coordinate Transformation Matrix' 0 1 0 -1 0 1 0 0 1</pre>
<b>Make the script executable:</b><br />
<pre class="prettyprint">chmod +x touch_rotate.sh</pre>
<b>Make the script run when the GUI starts by editing autostart:
</b><br />
<pre class="prettyprint">sudo nano ~/.config/lxsession/LXDE-pi/autostart</pre>
.. add this to the bottom to run your script<br />
<pre class="prettyprint">@/home/pi/touch_rotate.sh</pre>
<b>Reboot:
</b><br />
<pre class="prettyprint">sudo reboot</pre>
Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com10tag:blogger.com,1999:blog-9007601562606157016.post-64679368604772647032017-04-24T22:09:00.000+01:002017-04-25T09:26:16.154+01:00Blue Dot - a bluetooth remote for Raspberry Pi<a href="http://bluedot.readthedocs.io/">Blue Dot</a> is a really simple way to add Bluetooth remote control to your Raspberry Pi projects.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-5fuLlNxOhuI/WP25p5nYGWI/AAAAAAAAWKo/kksw5EvrxYw3Cqh6k8l0jyO02Yx5TK2-ACLcB/s1600/blue_dot_feature.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="156" src="https://2.bp.blogspot.com/-5fuLlNxOhuI/WP25p5nYGWI/AAAAAAAAWKo/kksw5EvrxYw3Cqh6k8l0jyO02Yx5TK2-ACLcB/s320/blue_dot_feature.png" width="320" /></a></div>
<br />
I created Blue Dot after being asked many times at <a href="https://www.raspberrypi.org/picademy/">Picademy</a> “how can I get rid of all these wires?”.
<br />
<br />
Blue dot is an <a href="https://play.google.com/store/apps/details?id=com.stuffaboutcode.bluedot">android app</a> (client) and really easy to use <a href="http://bluedot.readthedocs.io/">Python library</a> which allows you to wirelessly control your Python projects, whether that is a <a href="http://bluedot.readthedocs.io/en/latest/recipes.html#flash-an-led">light switch</a>, <a href="http://bluedot.readthedocs.io/en/latest/recipes.html#remote-camera">remote camera</a>, <a href="http://bluedot.readthedocs.io/en/latest/recipes.html#robot">robot</a> or anything else you can think of!<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen="" class="YOUTUBE-iframe-video" data-thumbnail-src="https://i.ytimg.com/vi/eW9oEPySF58/0.jpg" frameborder="0" height="266" src="https://www.youtube.com/embed/eW9oEPySF58?feature=player_embedded" width="320"></iframe></div>
<br />
See the <a href="http://bluedot.readthedocs.io/en/latest/gettingstarted.html">getting started guide</a> for more info on 'getting started', or follow the tutorial below.<br />
<br />
<b>Installation & Use</b><br />
These instructions assume your Raspberry Pi is running the latest version of <a href="https://www.raspberrypi.org/downloads/raspbian/">Raspbian with Pixel</a>.<br />
<br />
You will need a Raspberry Pi with built-in Bluetooth (such as the Pi 3 or Pi Zero W) or a Raspberry Pi and a USB Bluetooth dongle.<br />
<br />
<b>Get the app</b><br />
Download and install the <a href="https://play.google.com/store/apps/details?id=com.stuffaboutcode.bluedot">Blue Dot app</a> from the google play store.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-gtXe25GACiY/WP26p2QkB6I/AAAAAAAAWK0/59d98Tijgsc5GfNI-_nvebVwUxU9-ZDAACLcB/s1600/bluedotandroid.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://1.bp.blogspot.com/-gtXe25GACiY/WP26p2QkB6I/AAAAAAAAWK0/59d98Tijgsc5GfNI-_nvebVwUxU9-ZDAACLcB/s320/bluedotandroid.png" width="186" /></a></div>
<br />
If you are wondering why there is no iOS app? Its because iOS doesn't support Bluetooth serial comms; you can only really talk to 'standard devices' (cars, speakers, fitness trackers, etc).<br />
<br />
<b>
Python library</b><br />
Open a terminal (Menu > Accessories > Terminal) and type:<br />
<pre class="prettyprint">sudo apt-get install python3-dbus
sudo pip3 install bluedot</pre>
Or if you need to use Python 2 (please dont tho!):<br />
<pre class="prettyprint">sudo apt-get install python-dbus
sudo pip install bluedot</pre>
<br />
<b>
Pairing</b><br />
In order to communicate over Bluetooth securely you need to pair your phone to your Raspberry Pi.<br />
<br />
On your Android phone:<br />
<ol>
<li>Open Settings</li>
<li>Select Bluetooth</li>
<li>This will make your phone Discoverable</li>
</ol>
Using your Raspberry Pi<br />
<ol>
<li>Click the bluetooth icon on the taskbar</li>
<li>Turn on Bluetooth (if its off)</li>
<li>Click Make Discoverable</li>
<li>Click Add Device</li>
<li>Your phone will appear in the list, select it and click Pair</li>
<li>Enter a PIN code</li>
</ol>
On your Android phone<br />
<ol>
<li>Enter the same PIN code when prompted</li>
<li>Click Ok</li>
</ol>
<b>Code</b><br />
The simplest way to use the Blue Dot is as a button:<br />
<ol>
<li>Open Python 3 (Menu > Programming > Python 3)</li>
<li>Create a new file (File > New File)</li>
<li>The following code, will start up the Blue Dot, and wait for it to be pressed:</li>
<div>
<pre class="prettyprint">from bluedot import BlueDot
bd = BlueDot()
bd.wait_for_press()
print("You pressed the blue dot!")</pre>
</div>
<li>Save your program (File > Save) as mydot.py</li>
<li>Run your program (Run > Run Module)</li>
<li>Open the Blue Dot app</li>
<li>Connect to your Raspberry Pi</li>
<li>Press the Blue Dot</li>
</ol>
As well as waiting for something to happen you can also call functions when the button is pressed, released or the position its pressed moves.<br />
<pre class="prettyprint">from bluedot import BlueDot
from signal import pause
def say_hello():
print("Hello World")
def say_goodbye():
print("goodbye")
bd = BlueDot()
bd.when_pressed = say_hello
bd.when_released = say_goodbye
pause()</pre>
By using the position of where the button is pressed you can use the Blue Dot like a joystick:<br />
<pre class="prettyprint">from bluedot import BlueDot
from signal import pause
def dpad(pos):
if pos.top:
print("up")
elif pos.bottom:
print("down")
elif pos.left:
print("left")
elif pos.right:
print("right")
elif pos.middle:
print("fire")
bd = BlueDot()
bd.when_pressed = dpad
pause()</pre>
Add to this <a href="http://gpiozero.readthedocs.io/en/stable/api_boards.html#robot">gpiozero's Robot</a> functions, you can create a Bluetooth controlled robot with very little code.<br />
<pre class="prettyprint">from bluedot import BlueDot
from gpiozero import Robot
from signal import pause
bd = BlueDot()
robot = Robot(left=(lfpin, lbpin), right=(rfpin, rbpin))
def move(pos):
if pos.top:
robot.forward()
elif pos.bottom:
robot.backward()
elif pos.left:
robot.left()
elif pos.right:
robot.right()
def stop():
robot.stop()
bd.when_pressed = move
bd.when_moved = move
bd.when_released = stop
pause()</pre>
Check out the <a href="http://bluedot.readthedocs.io/">Blue Dot documentation</a> for more information and ideas - you really can do a lot with a simple circle :)Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com19tag:blogger.com,1999:blog-9007601562606157016.post-70881901840088430362017-01-05T21:44:00.000+00:002017-03-07T10:41:29.967+00:00Raspberry Pi - 4 digit 7 Segment display, gpiozeroI recently picked up some '<a href="https://shop.pimoroni.com/products/retro-4-digit-led-display">retro 4 digit LED displays</a>' from <a href="https://www.pimoroni.com/">pimoroni</a>, noticing there was no support in <a href="http://gpiozero.readthedocs.io/">gpiozero</a> for 7 segment displays (either <a href="http://www.stuffaboutcode.com/2016/10/raspberry-pi-7-segment-display-gpiozero.html">single</a> or multi digit) I decided to add them and create a <a href="https://github.com/RPi-Distro/python-gpiozero/pull/488">pull request</a>. <br />
<br />
This builds on the code I created for driving <a href="http://www.stuffaboutcode.com/2016/10/raspberry-pi-7-segment-display-gpiozero.html">single 7 segment displays</a>.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-xqiy-pxPhBw/WG66IFcY3TI/AAAAAAAAVCk/ll4Bx41jekQ3--PiGSmydUtYHPWDpdjrgCLcB/s1600/7seg_leds.PNG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="162" src="https://2.bp.blogspot.com/-xqiy-pxPhBw/WG66IFcY3TI/AAAAAAAAVCk/ll4Bx41jekQ3--PiGSmydUtYHPWDpdjrgCLcB/s320/7seg_leds.PNG" width="320" /></a></div>
<br />
Hopefully the PR will get added into a gpiozero release soon, but until then add this <a href="https://gist.github.com/martinohanlon/23a8a67bc3c68988fbb492b3d5d42ca5">code</a> to your project and use the following to drive your display.<br />
<pre class="prettyprint">#setup the pins
#these are the pins the LED are connected too
# (in the order A, B, C, D, E, F, G, decimal point)
LED_PINS = (7, 22, 25, 17, 8, 27, 4, 24)
#these are the pins the digits are connected too
DIGIT_PINS = (23, 18, 15, 14)
#create the multi seven segment display
# use active_high=True when digit pins are cathode (ground)
multi_sev = MultiSevenSegmentDisplay(LED_PINS, DIGIT_PINS,
active_high=True)
#display your message
multi_sev.display("LEDS")
#turn off the display using
multi_sev.off()</pre>
The display function works by plexing the display, turning the LEDs on one at a time, so quickly it tricks the eye into thinking the display is showing 1 message.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen="" class="YOUTUBE-iframe-video" data-thumbnail-src="https://i.ytimg.com/vi/jeg5sjdHCYM/0.jpg" frameborder="0" height="266" src="https://www.youtube.com/embed/jeg5sjdHCYM?feature=player_embedded" width="320"></iframe></div>
<br />
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com0tag:blogger.com,1999:blog-9007601562606157016.post-9345322029650932032016-12-08T22:43:00.001+00:002017-01-10T16:11:46.712+00:00Raspberry Pi - bash memory split checkI needed a bash script which would only launch a program on a Raspberry Pi if there was enough memory dedicated to the GPU.<br />
<br />
I pulled this script together which checks to see if there is at least 128 MB dedicated to the GPU before starting the program.<br />
<br />
<pre class="prettyprint">#!/bin/bash
#check there is enough gpu memory to start
#get the gpu memory and output to a file called gpu_mem
vcgencmd get_mem gpu > gpu_mem
source gpu_mem
#strip last char from the output (i.e. 64M)
gpu=${gpu%?}
if (( $gpu >= 128 )); then
./launch_program
else
echo "The program needs at least 128MB of memory allocated to the GPU"
echo "Use sudo raspi-config (Advanced Options > Memory Split) to change"
fi
#remove the gpu_mem file
rm gpu_mem</pre>
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com1tag:blogger.com,1999:blog-9007601562606157016.post-71974006872008216272016-11-29T18:12:00.000+00:002017-01-10T16:15:32.604+00:00Compile Allegro 5.x for Raspberry PiI am in the process of porting <a href="http://www.stuffaboutcode.com/2016/06/mayhem-2-open-source-cave-shooter.html">Mayhem 2</a> to Allegro 5 (with the help of <a href="https://github.com/karjonas">Jonas Karlsson</a>), and wanted to compile the latest version of Allegro on the Pi, as only an older version is available through apt.<br />
<b><br /></b>
<b>Install the dependencies</b><br />
<pre class="prettyprint">sudo apt-get install build-essential git cmake cmake-curses-gui xorg-dev libgl1-mesa-dev libglu-dev libpng-dev libcurl4-nss-dev libfreetype6-dev libjpeg-dev libvorbis-dev libopenal-dev libphysfs-dev libgtk2.0-dev libpulse-dev libflac-dev libdumb1-dev</pre>
<b>Get the Code</b><br />
<pre class="prettyprint">git clone https://github.com/liballeg/allegro5.git
cd allegro5</pre>
<b>Check out the version you want</b> - see <a href="https://github.com/liballeg/allegro5/branches/all">here</a> for a list of versions<br />
<pre class="prettyprint">git checkout 5.2.1</pre>
<b>Build it
</b><br />
<pre class="prettyprint">
mkdir build
cd build
cmake .. -DCMAKE_TOOLCHAIN_FILE=../cmake/Toolchain-raspberrypi.cmake
make</pre>
<b>Install it
</b><br />
<pre class="prettyprint">sudo make install
export PKG_CONFIG_PATH=/home/pi/allegro5/build/lib/pkgconfig
sudo ldconfig</pre>
Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com0tag:blogger.com,1999:blog-9007601562606157016.post-14261844571017154422016-10-24T22:13:00.000+01:002017-03-07T10:40:56.703+00:00Raspberry Pi, 7 Segment Display, gpiozeroI've been working on an <a href="https://github.com/RPi-Distro/python-gpiozero/pull/488">update</a> to <a href="http://gpiozero.readthedocs.io/en/v1.3.1/">gpiozero</a> to add a 7 segment display - hopefully this will make it into gpiozero soon, but until then if you want to use a 7 segment display with your Raspberry Pi you can follow the details below.<br />
<br />
<i>Update - I have updated this to support single and <a href="http://www.stuffaboutcode.com/2017/01/raspberry-pi-4-digit-7-segment-display.html">multiple digit 7 segment displays</a>.</i><br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-l4o5WvjlXIE/WAzGoY3wSsI/AAAAAAAAT5w/7zS6pw_7gNcCOaIcAteAMg3o6GjnsLjKACLcB/s1600/7segment.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://3.bp.blogspot.com/-l4o5WvjlXIE/WAzGoY3wSsI/AAAAAAAAT5w/7zS6pw_7gNcCOaIcAteAMg3o6GjnsLjKACLcB/s320/7segment.jpg" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<b>Wire it up</b></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
The seven segment display will have 7 pins to connect the digit's LEDs, 1 pin to connect the decimal point LED and 1 pin which is the common pin.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
The LED pins should connect to 8 GPIO pins depending on whether your 7 segment display is a common-anode or a common-cathode the common pin should connect to either a 3.3v pin or the ground. Your also going to need a suitable resistor (probably a 330) between your GPIO and LED pins.</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<table align="center" cellpadding="0" cellspacing="0" class="tr-caption-container" style="margin-left: auto; margin-right: auto; text-align: center;"><tbody>
<tr><td style="text-align: center;"><a href="https://2.bp.blogspot.com/-ImvkAWeqcic/WA51BA5ZOTI/AAAAAAAAT7c/i_7pdgcO5vsw1pe90eMciv8sOsWugv0eACLcB/s1600/7segment_bb.png" imageanchor="1" style="margin-left: auto; margin-right: auto;"><img border="0" height="320" src="https://2.bp.blogspot.com/-ImvkAWeqcic/WA51BA5ZOTI/AAAAAAAAT7c/i_7pdgcO5vsw1pe90eMciv8sOsWugv0eACLcB/s320/7segment_bb.png" width="229" /></a></td></tr>
<tr><td class="tr-caption" style="text-align: center;">Wired up as a common-anode</td></tr>
</tbody></table>
<div class="separator" style="clear: both; text-align: left;">
<b>Code</b></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
Create a new program and add the following to the top of the your program (this is the class which will allow you to control the display).</div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<pre class="prettyprint">from gpiozero import LEDBoard, OutputDeviceError, LEDCollection
class SevenSegmentDisplay(LEDBoard):
"""
Extends :class:`LEDBoard` for a 7 segment LED display
7 segment displays have either 7 or 8 pins, 7 pins for the digit display
and an optional 8th pin for a decimal point. 7 segment displays
typically have either a common anode or common cathode pin, when
using a common anode display 'active_high' should be set to False.
Instances of this class can be used to display characters or control
individual leds on the display. For example::
from gpiozero import SevenSegmentDisplay
seven = SevenSegmentDisplay(1,2,3,4,5,6,7,8,active_high=False)
seven.display("7")
:param int \*pins:
Specify the GPIO pins that the 7 segment display is attached to.
Pins should be in the LED segment order A,B,C,D,E,F,G,decimal_point
(the decimal_point is optional).
:param bool pwm:
If ``True``, construct :class:`PWMLED` instances for each pin. If
``False`` (the default), construct regular :class:`LED` instances. This
parameter can only be specified as a keyword parameter.
:param bool active_high:
If ``True`` (the default), the :meth:`on` method will set all the
associated pins to HIGH. If ``False``, the :meth:`on` method will set
all pins to LOW (the :meth:`off` method always does the opposite). This
parameter can only be specified as a keyword parameter.
:param bool initial_value:
If ``False`` (the default), all LEDs will be off initially. If
``None``, each device will be left in whatever state the pin is found
in when configured for output (warning: this can be on). If ``True``,
the device will be switched on initially. This parameter can only be
specified as a keyword parameter.
"""
def __init__(self, *pins, **kwargs):
# 7 segment displays must have 7 or 8 pins
if len(pins) < 7 or len(pins) > 8:
raise ValueError('SevenSegmentDisplay must have 7 or 8 pins')
# Don't allow 7 segments to contain collections
for pin in pins:
assert not isinstance(pin, LEDCollection)
pwm = kwargs.pop('pwm', False)
active_high = kwargs.pop('active_high', True)
initial_value = kwargs.pop('initial_value', False)
if kwargs:
raise TypeError('unexpected keyword argument: %s' % kwargs.popitem()[0])
self._layouts = {
'1': (False, True, True, False, False, False, False),
'2': (True, True, False, True, True, False, True),
'3': (True, True, True, True, False, False, True),
'4': (False, True, True, False, False, True, True),
'5': (True, False, True, True, False, True, True),
'6': (True, False, True, True, True, True, True),
'7': (True, True, True, False, False, False, False),
'8': (True, True, True, True, True, True, True),
'9': (True, True, True, True, False, True, True),
'0': (True, True, True, True, True, True, False),
'A': (True, True, True, False, True, True, True),
'B': (False, False, True, True, True, True, True),
'C': (True, False, False, True, True, True, False),
'D': (False, True, True, True, True, False, True),
'E': (True, False, False, True, True, True, True),
'F': (True, False, False, False, True, True, True),
'G': (True, False, True, True, True, True, False),
'H': (False, True, True, False, True, True, True),
'I': (False, False, False, False, True, True, False),
'J': (False, True, True, True, True, False, False),
'K': (True, False, True, False, True, True, True),
'L': (False, False, False, True, True, True, False),
'M': (True, False, True, False, True, False, False),
'N': (True, True, True, False, True, True, False),
'O': (True, True, True, True, True, True, False),
'P': (True, True, False, False, True, True, True),
'Q': (True, True, False, True, False, True, True),
'R': (True, True, False, False, True, True, False),
'S': (True, False, True, True, False, True, True),
'T': (False, False, False, True, True, True, True),
'U': (False, False, True, True, True, False, False),
'V': (False, True, True, True, True, True, False),
'W': (False, True, False, True, False, True, False),
'X': (False, True, True, False, True, True, True),
'Y': (False, True, True, True, False, True, True),
'Z': (True, True, False, True, True, False, True),
'-': (False, False, False, False, False, False, True),
' ': (False, False, False, False, False, False, False),
'=': (False, False, False, True, False, False, True)
}
super(SevenSegmentDisplay, self).__init__(*pins, pwm=pwm, active_high=active_high, initial_value=initial_value)
def display(self, char):
"""
Display a character on the 7 segment display
:param string char:
A single character to be displayed
"""
char = str(char).upper()
if len(char) > 1:
raise ValueError('only a single character can be displayed')
if char not in self._layouts:
raise ValueError('there is no layout for character - %s' % char)
layout = self._layouts[char]
for led in range(7):
self[led].value = layout[led]
def display_hex(self, hexnumber):
"""
Display a hex number (0-F) on the 7 segment display
:param int hexnumber:
The number to be displayed in hex
"""
self.display(hex(hexnumber)[2:])
@property
def decimal_point(self):
"""
Represents the status of the decimal point led
"""
# does the 7seg display have a decimal point (i.e pin 8)
if len(self) > 7:
return self[7].value
else:
raise OutputDeviceError('there is no 8th pin for the decimal point')
@decimal_point.setter
def decimal_point(self, value):
"""
Sets the status of the decimal point led
"""
if len(self) > 7:
self[7].value = value
else:
raise OutputDeviceError('there is no 8th pin for the decimal point')
def set_char_layout(self, char, layout):
"""
Create or update a custom character layout, which can be used with the
`display` method.
:param string char:
A single character to be displayed
:param tuple layout:
A 7 bool tuple of LED values in the segment order A, B, C, D, E, F, G
"""
char = str(char).upper()
if len(char) != 1:
raise ValueError('only a single character can be used in a layout')
if len(layout) != 7:
raise ValueError('a character layout must have 7 segments')
self._layouts[char] = layout</pre>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<b>Create the display</b></div>
<div class="separator" style="clear: both; text-align: left;">
Create an instance on the 7 segment display object, you need to pass the pins in the order, A,B,C,D,E,F,G,Decimal Point.</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-gJ3oQE1isRE/WA52VfzvwSI/AAAAAAAAT7o/d55nVUMI5oEe0DFG6C_T08XLacIsd9qcACLcB/s1600/7seg_pinouts.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://3.bp.blogspot.com/-gJ3oQE1isRE/WA52VfzvwSI/AAAAAAAAT7o/d55nVUMI5oEe0DFG6C_T08XLacIsd9qcACLcB/s320/7seg_pinouts.png" width="217" /></a></div>
<pre class="prettyprint">seven_seg = SevenSegmentDisplay(20, 21, 6, 22, 27, 18, 15, 13)</pre>
<div class="separator" style="clear: both; text-align: left;">
If you have a common-anode display you will also need to set the active_high parameter to False:</div>
<pre class="prettyprint">seven_seg = SevenSegmentDisplay(20, 21, 6, 22, 27, 18, 15, 13,
active_high=False)</pre>
<div class="separator" style="clear: both; text-align: left;">
<b>Display a character</b></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
You can show a character on the display using the .display() method.</div>
<pre class="prettyprint">seven_seg.display("8")</pre>
<div class="separator" style="clear: both; text-align: left;">
<b>Add a new character</b></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
You can add your own characters to the display, using the .set_char_layout() method passing the character and a tuple of 7 booleans for each of the LEDs in order A,B,C,D,E,F,G.</div>
<pre class="prettyprint">seven_seg.set_char_layout("_", (False, False, False, True, False, False, False))
seven_seg.display("_")</pre>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<b>Decimal point</b></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
You can turn the decimal point on by setting the .decimal_point property.</div>
<pre class="prettyprint">seven_seg.decimal_point = True</pre>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com5tag:blogger.com,1999:blog-9007601562606157016.post-74389340642743275652016-09-20T20:03:00.000+01:002016-09-20T20:33:39.524+01:00Microbit making Minecraft EarthquakesIn this tutorial you are going to connect your Microbit up to your Raspberry Pi and program them so that when your Microbit is shaken it creates an earthquake in Minecraft.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-a9W_j-3Dzig/V-GM0hU5q7I/AAAAAAAAS3M/XeH9FklRXHY3p8mHXxGkOgyAlOqypyUOgCLcB/s1600/ezgif.com-optimize.gif" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="222" src="https://4.bp.blogspot.com/-a9W_j-3Dzig/V-GM0hU5q7I/AAAAAAAAS3M/XeH9FklRXHY3p8mHXxGkOgyAlOqypyUOgCLcB/s400/ezgif.com-optimize.gif" width="400" /></a></div>
<br />
This is part of a workshop I delivered at <a href="http://2016.pyconuk.org/">PyConUK 2016</a> - <a href="https://drive.google.com/open?id=1VElMfrxKNG5qnwfQ0mx5o8-IeuYRfRatxlRqzInn6GE">download the complete worksheet</a>.<br />
<br />
You are going to connect your micro:bit’s pins to the Raspberry Pi gpio pins using some cables and crocodile clips; programs on the micro@bit and Raspberry Pi will make Steve shake in Minecraft.<br />
<br />
<b>Install mu</b><br />
To put you python program on your Micro:bit you will need the editor <a href="https://github.com/mu-editor/mu">mu</a>.<br />
<br />
Open a Terminal (Menu > Accessories > Terminal) and type:<br />
<pre class="prettyprint">sudo apt-get update
sudo apt-get install mu
</pre>
<b>Angry micro:bit</b><br />
The first task is to program your micro:bit so it gets angry when it's shaken.<br />
<ul>
<li>Connect your micro:bit to the Raspberry Pi using the USB cable.</li>
<li>Open mu to create a new Python program for your micro:bit by clicking on Menu > Programming > mu.</li>
<li>Click New and type the following code into the editor.</li>
</ul>
<pre class="prettyprint">from microbit import *
while True:
if accelerometer.current_gesture() == "shake":
display.show(Image.ANGRY)
else:
display.show(Image.HAPPY)</pre>
<ul>
<li>Click Flash to put your program on your micro:bit.</li>
</ul>
When the yellow light on the back of your micro:bit stops flashing your program will run.<br />
You should see a happy face on your micro:bit - until it’s shaken!<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-JKN7pZ0qb0g/V-D-tj_UvVI/AAAAAAAAS2o/SxpXnaUC9gcP1wXXl-L9-TzxdHzsaC1-wCLcB/s1600/mbhappy.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="163" src="https://3.bp.blogspot.com/-JKN7pZ0qb0g/V-D-tj_UvVI/AAAAAAAAS2o/SxpXnaUC9gcP1wXXl-L9-TzxdHzsaC1-wCLcB/s200/mbhappy.png" width="200" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both;">
<span style="color: red;">Any errors will be scrolled on your micro:bit’s leds; if you get an error check your code carefully.</span></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div class="separator" style="clear: both; text-align: left;">
<b>Pins</b></div>
Now you need to finish your micro:bit program so that it turns pin 0 on and off when it's shaken<br />
<ul>
<li>Go back to Mu and modify your program so that it turns pins 0 on (1) and off (0) when shaken.</li>
</ul>
<pre class="prettyprint">from microbit import *
while True:
if accelerometer.current_gesture() == "shake":
display.show(Image.ANGRY)
<b>pin0.write_digital(1)</b>
else:
display.show(Image.HAPPY)
<b>pin0.write_digital(0)</b></pre>
<ul>
<li>Click Flash to put your program on your micro:bit.</li>
</ul>
<b>Connect it up</b><br />
Next you will use a jumper cable and a crocodile clip to connect your micro:bit to the Raspberry Pi.<br />
<ul>
<li>Connect the jumper cable to GPIO17 on the Raspberry Pi</li>
<li>Clip the crocodile clip to the end of the jumper cable</li>
<li>Clip the other end of the crocodile clip to pin0 on the micro:bit</li>
</ul>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-ZuzXVU0KuAo/V-GEqV0YyhI/AAAAAAAAS24/NfKl9mmPgpQLIAMEt1F58Ik66mZ7ObDkgCLcB/s1600/IMGP6235_crop.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="250" src="https://2.bp.blogspot.com/-ZuzXVU0KuAo/V-GEqV0YyhI/AAAAAAAAS24/NfKl9mmPgpQLIAMEt1F58Ik66mZ7ObDkgCLcB/s400/IMGP6235_crop.JPG" width="400" /></a><a href="https://3.bp.blogspot.com/-Qb9qfvsetIw/V-GFLBiDUtI/AAAAAAAAS28/ee5haoVBCVs53ZoUGwwzPNFkvY2h15ycACLcB/s1600/Raspberry-Pi-GPIO-Layout-Model-B-Plus-rotated-2700x900.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="106" src="https://3.bp.blogspot.com/-Qb9qfvsetIw/V-GFLBiDUtI/AAAAAAAAS28/ee5haoVBCVs53ZoUGwwzPNFkvY2h15ycACLcB/s320/Raspberry-Pi-GPIO-Layout-Model-B-Plus-rotated-2700x900.png" width="320" /></a></div>
<div>
<br /></div>
<b>Shake Steve</b><br />
You now need to create your Minecraft program to shake Steve when the micro:bit is shaken and pin0 is set to 1.<br />
<ul>
<li>Click Menu > Games > Minecraft: Pi Edition to run the game.</li>
<li>Click Start Game, then click Create New (or choose an existing one) to enter a world:</li>
<li>Press ESC to go back to the Minecraft menu but leave the game playing.</li>
<li>Open Python IDLE by clicking Menu > Programming > Python 3.</li>
<li>Use File > New Window to create a new program and save it as ‘mc_micro.py’.</li>
<li>Type the following code into the program to import the modules you will need</li>
</ul>
<pre class="prettyprint">from mcpi.minecraft import Minecraft
from gpiozero import DigitalInputDevice
from time import sleep</pre>
<ul>
<li>Create a connection to Minecraft using the code.</li>
</ul>
<pre class="prettyprint">mc = Minecraft.create()</pre>
<ul>
<li>Post a message to the chat window.</li>
</ul>
<pre class="prettyprint">mc.postToChat("Micromine bitcraft earthquake")</pre>
<ul>
<li>Run your program by clicking Run > Run Module.</li>
</ul>
<div>
You should see your message appear in the Minecraft chat window.</div>
<div>
<br /></div>
<div>
<div>
<span style="color: red;">Any errors will be displayed in the Python Shell in red.</span></div>
</div>
<div>
<br /></div>
<div>
<div>
Update your program to shake Steve, by adding the following code at the bottom of your program.</div>
<div>
<ul>
<li>Create a pin which is connected to Pi GPIO 17 and micro:bit pin 0.</li>
</ul>
</div>
<pre class="prettyprint">pin0 = DigitalInputDevice(17)</pre>
<div>
<ul>
<li>Create a loop which constants gets Steve’s position.</li>
</ul>
</div>
<pre class="prettyprint">while True:
sleep(0.1)
pos = mc.player.getPos()</pre>
<div>
<ul>
<li>If pin0 is on (1) it adds 0.5 to Steve’s height (y).</li>
</ul>
</div>
<pre class="prettyprint"> if pin0.value == 1:
pos.y = pos.y + 0.5
mc.player.setPos(pos)</pre>
<div>
<ul>
<li>Run your program by clicking Run > Run Module.</li>
</ul>
</div>
<div>
Shake your micro:bit and Steve will be shaken in Minecraft.</div>
</div>
<div>
<br /></div>
<div>
<b>Challenges</b></div>
<div>
Can you change the program so that it creates a more realistic earthquake by adding random values to the x, y, z values.</div>
<div>
<br /></div>
<div>
Complete the <a href="https://drive.google.com/open?id=1VElMfrxKNG5qnwfQ0mx5o8-IeuYRfRatxlRqzInn6GE">worksheet</a> from <a href="http://2016.pyconuk.org/">PyConUK 2016</a> which includes using the micro:bit buttons to makes blocks disappear and appear.</div>
<div>
<br /></div>
Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com3tag:blogger.com,1999:blog-9007601562606157016.post-74574201260393834382016-06-17T20:00:00.000+01:002016-06-17T20:00:23.852+01:00Mayhem 2 - an open source cave shooterI recently <a href="http://www.stuffaboutcode.com/2016/04/mayhem-classic-amiga-game-ported-to.html">ported an abandoned version the classic amiga game, Mayhem, to the Raspberry Pi</a> - I did this exclusively so I could play the game with my friend, Lee, using <a href="http://retropie.org/">RetroPie</a>.<br />
<br />
Since then myself and Lee, an artist for sumo digital, have been modding the game, adding new levels, features and controls - it now really is Mayhem <b>2</b>.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-tCZamlHJVZk/V2O4jkOWvoI/AAAAAAAARzA/-CSahDZTSoAWEtuCAhBvsAAGmN1XEuT2gCLcB/s1600/Mayhem2pg.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="240" src="https://3.bp.blogspot.com/-tCZamlHJVZk/V2O4jkOWvoI/AAAAAAAARzA/-CSahDZTSoAWEtuCAhBvsAAGmN1XEuT2gCLcB/s320/Mayhem2pg.jpg" width="320" /></a></div>
<br />
Mayhem 2 is available for <a href="https://github.com/martinohanlon/mayhem">Windows</a> and <a href="https://github.com/martinohanlon/mayhem-pi">Raspberry Pi</a>.<br />
<br />
I'm hoping there will be lots more features and changes to the game over the coming months, if anyone has any idea's or would like to contribute it would be great to hear from you.<br />
<br />
<b>Gameplay</b><br />
<br />
Mayhem 2 is a multiplayer (2 - 4) flight shooter with a really simple objective - destroy your opponents before they destroy you.<br />
<br />
Your ship has limited fuel which will run down when you boost, if you run out you will be unable to control your ship, to refuel, land on any flat surface.<br />
<br />
You can protect yourself from attack using your shields which will stop all bullets, be careful though your shields run down quickly and you wont be able to boost while your shields are on. <br />
<br />
Power -ups are dropped (sometimes) when a player is destroyed (by either crashing or being shot) and when collected will give you a temporary boost such as a triple-shot weapon, better shields or more thrust.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen="" class="YOUTUBE-iframe-video" data-thumbnail-src="https://i.ytimg.com/vi/oxAzUuwuleM/0.jpg" frameborder="0" height="266" src="https://www.youtube.com/embed/oxAzUuwuleM?feature=player_embedded" width="320"></iframe></div>
<br />
New levels have been added including new ones with no edges, where you can seamlessly fly across the edge of the map.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen="" class="YOUTUBE-iframe-video" data-thumbnail-src="https://i.ytimg.com/vi/E3mho6J6OG8/0.jpg" frameborder="0" height="266" src="https://www.youtube.com/embed/E3mho6J6OG8?feature=player_embedded" width="320"></iframe></div>
<br />
<b>Options</b><br />
<br />
Levels 1-3 are the original game levels, all other levels are new to Mayhem 2.<br />
<br />
DCA are anti spaceship guns which will fire at the player if they get too close.<br />
<br />
Wall collision can be turned off for new players to get used to the controls and playing the game.<br />
<br />
<b>Controls</b><br />
<br />
Mayhem 2 supports joystick and keyboard control, joystick controls can be configured via the main menu.<br />
<br />
Default joystick controls, assume an "xbox / ps like" joystick:<br />
<br />
<table><thead>
<tr><th>Control</th><th>Action</th></tr>
</thead><tbody>
<tr><td>Stick 1</td><td>Left / Right</td></tr>
<tr><td>Button 1 (A)</td><td>Thrust</td></tr>
<tr><td>Button 2 (B)</td><td>Shield</td></tr>
<tr><td>Button 6 (RB)</td><td>Fire</td></tr>
</tbody></table>
<br />
If joysticks are connected, they are used as the players controls, if there are less than 4 joysticks connected, keys are used for the rest of the players in order:<br />
<br />
<table><thead>
<tr><th>Key</th><th>Left</th><th>Right</th><th>Shield</th><th>Thrust</th><th>Fire</th></tr>
</thead><tbody>
<tr><td>1</td><td>z</td><td>x</td><td>c</td><td>v</td><td>g</td></tr>
<tr><td>2</td><td>left</td><td>right</td><td>pad del</td><td>pad 0</td><td>pad enter</td></tr>
<tr><td>3</td><td>b</td><td>n</td><td>,</td><td>m</td><td>l</td></tr>
<tr><td>4</td><td>y</td><td>u</td><td>o</td><td>i</td><td>0</td></tr>
</tbody></table>
<br />
<b>Install</b><br />
<br />
<b><i>For windows:</i></b><br />
<br />
Download the zip file from <a href="https://github.com/martinohanlon/mayhem/archive/master.zip">https://github.com/martinohanlon/mayhem/archive/master.zip</a>, open and copy mayhem-master to a folder. <br />
<br />
Double click Mayhem2.exe in the mayhem-master folder. <br />
<br />
Note - You maybe presented with message saying that the application was stopped from starting as it is unrecognised, click 'more info' and and choose 'run anyway'. <br />
<div>
<b><br /></b></div>
<b><i>For Raspberry Pi:</i></b><br />
<br />
Open a terminal and type:<br />
<pre class="prettyprint">sudo apt-get install liballegro4.4 liballegro4-dev
git clone https://github.com/martinohanlon/mayhem-pi</pre>
Run using:<br />
<pre class="prettyprint">cd mayhem-pi
./start</pre>
<b>Code</b><br />
<br />
The full source code is available on GitHub for <a href="https://github.com/martinohanlon/mayhem">Windows</a> and <a href="https://github.com/martinohanlon/mayhem-pi">Raspberry Pi</a>.<br />
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com4tag:blogger.com,1999:blog-9007601562606157016.post-90155389876324724012016-05-19T12:40:00.000+01:002016-05-19T23:05:04.425+01:00Raspberry Pi - Playing a Sound File with PythonA question I get asked a lot in Picademy is how to I play a sound file using Python.<br />
<br />
Using just whats on the standard Raspbian image the easiest way, IMO, is to use Pygame.<br />
<br />
This small code snippet below shows you how. Just put the wav file in the same place as your program.<br />
<br />
<pre class="prettyprint">import pygame
from time import sleep
#Initialise pygame and the mixer
pygame.init()
pygame.mixer.init()
#load the sound file
mysound = pygame.mixer.Sound("mysound.wav")
#play the sound file for 10 seconds and then stop it
mysound.play()
time.sleep(10)
mysound.stop()</pre>
<br />
You will have to use wav files, as opposed to other sounds files such as mp3, ogg, etc - use <a href="http://media.io/">media.io</a> to convert them.Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com5tag:blogger.com,1999:blog-9007601562606157016.post-70035101594686276852016-04-12T21:53:00.002+01:002016-07-12T12:44:06.123+01:00Mayhem, Amiga game, ported to Raspberry Pi<i>Update - I've taken Mayhem forward to create <a href="http://www.stuffaboutcode.com/2016/06/mayhem-2-open-source-cave-shooter.html">Mayhem 2</a>.</i><br />
<br />
I had a <a href="https://en.wikipedia.org/wiki/Amiga">Commodore Amiga</a> and a game I played, a lot, was <a href="http://www.lemonamiga.com/games/details.php?id=2972">Mayhem</a>, its a multiplayer (2-4) shooter - imagine multiplayer asteroids, with gravity, fuel and shields!<br />
<br />
It was ported to the PC in 2002 by <a href="https://github.com/devpack">devpack</a> who released the code in 2011 on <a href="https://github.com/devpack/mayhem">github</a> and <a href="https://code.google.com/archive/p/mayhem/">google code</a> which is where I picked it up and ported it to the Raspberry Pi.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen="" class="YOUTUBE-iframe-video" data-thumbnail-src="https://i.ytimg.com/vi/Vxozz0Ijdr0/0.jpg" frameborder="0" height="266" src="https://www.youtube.com/embed/Vxozz0Ijdr0?feature=player_embedded" width="320"></iframe></div>
<div style="text-align: center;">
This is the port, but check out the <a href="https://www.youtube.com/watch?v=fs30DLGxqhs">original Amiga game</a>.</div>
<br />
I got some help from the <a href="https://www.raspberrypi.org/forums/viewtopic.php?f=33&t=142284&">Raspberry Pi forums in getting it to compile</a> then it was case of sorting out a few case sensitive filename bugs (it was original written for Windows!) and tracking down a bug in the original code which was causing a memory access error and segmentation fault.<br />
<br />
The code is on <a href="http://github.com/martinohanlon/mayhem-pi">github.com/martinohanlon/mayhem-pi</a>.<br />
<br />
<b>Install
</b><br />
<pre class="prettyprint">sudo apt-get install liballegro4.4 liballegro4-dev
git clone https://github.com/martinohanlon/mayhem-pi</pre>
<br />
<b>Run
</b><br />
<pre class="prettyprint">cd mayhem-pi
./start</pre>
<br />
<b>Keys</b><br />
Player 1 - z, x, c, v, g<br />
Player 2 - left, right, pad del, pad 0, pad enter<br />
Player 3 - b, n, 'comma', m, l<br />
Player 4 - y, u, o, i, 0<br />
Change level - 1, 2, 3<br />
<br />
<b>Compile</b><br />
If you want to modify the game, I've got a couple of things on my <a href="https://github.com/martinohanlon/mayhem-pi/issues">list</a>, you can recompile it with.<br />
<pre class="prettyprint">cd mayhem-pi
make
</pre>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://2.bp.blogspot.com/-8mzWgliks38/Vw1XRa3bW1I/AAAAAAAAQ6w/QZi1kLiRPEw2ttU5io_X0DYodfTlScPEQCLcB/s1600/mayhem.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="243" src="https://2.bp.blogspot.com/-8mzWgliks38/Vw1XRa3bW1I/AAAAAAAAQ6w/QZi1kLiRPEw2ttU5io_X0DYodfTlScPEQCLcB/s320/mayhem.JPG" width="320" /></a></div>
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com2tag:blogger.com,1999:blog-9007601562606157016.post-91537342313888659722016-03-27T14:58:00.000+01:002016-04-04T12:04:44.845+01:00Raspberry Pi - Take screenshots of MinecraftIf you going to take a screenshot of Minecraft: Pi edition (or anything else for that matter), I really like a command line utility called <a href="https://github.com/AndrewFromMelbourne/raspi2png">raspi2png</a>, its simple and screenshots images which have been created using the GPU (like games) as well.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-w1kF0mppwME/VvfmLxp9UTI/AAAAAAAAQqQ/Dim4wdRiGxoIKDVS7J8gQggK5R2dl7e-Q/s1600/myscreenshot.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="180" src="https://3.bp.blogspot.com/-w1kF0mppwME/VvfmLxp9UTI/AAAAAAAAQqQ/Dim4wdRiGxoIKDVS7J8gQggK5R2dl7e-Q/s320/myscreenshot.png" width="320" /></a></div>
<br />
<b>Download</b><br />
Open a terminal and clone the repository from github:<br />
<pre class="prettyprint">cd ~
git clone https://github.com/AndrewFromMelbourne/raspi2png</pre>
<br />
<b>Use</b><br />
Change directory to raspi2png and run the program's help to show all the options:
<br />
<pre class="prettyprint">cd ~/raspi2png
./raspi2png --help
</pre>
<pre class="prettyprint">
Usage: raspi2png [--pngname name] [--width <width>] [--height <height>] [--compression <level>]
[--delay <delay>] [--display <number>] [--stdout] [--help]
--pngname,-p - name of png file to create (default is snapshot.png)
--height,-h - image height (default is screen height)
--width,-w - image width (default is screen width)
--compression,-c - PNG compression level (0 - 9)
--delay,-d - delay in seconds (default 0)
--display,-D - Raspberry Pi display number (default 0)
--stdout,-s - write file to stdout
--help,-H - print this usage information</number></delay></level></height></width></pre>
<br />
To take screenshot you have to use the -p option and pass an image filename:
<br />
<pre class="prettyprint">./raspi2png -p myscreenshot.png</pre>
Another really useful option is -d to delay when to take the picture, this enables you to get the screen ready for a shot - to take a picture delayed by 10 seconds:
<br />
<pre class="prettyprint">./raspi2png -p mydelayedshot.png -d 10</pre>
The image files will be created in the ~/raspi2png directory - if you want them in a different directory use a full path:
<br />
<pre class="prettyprint">./raspi2png -p /home/pi/mydir/myscreenshot.png</pre>
If you use a filename which already exists raspi2png will overwrite the file without warning and the old image will be lost.<br />
<br />
<i>Fyi - I wrote this blog post using a Raspberry Pi 3... First time I've used a Pi to write about a Pi - thats progress!</i>Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com6tag:blogger.com,1999:blog-9007601562606157016.post-84817858808717400462016-03-25T18:15:00.001+00:002016-04-04T12:53:33.609+01:00Microbit - get data from USBAs part of my <a href="http://www.stuffaboutcode.com/2015/12/minecraft-microbit-and-x-wing.html">Minecraft, a Microbit and an X-Wing</a> project, I used the USB to read data from the Microbit's accelerometer and buttons to make the X-Wing move.<br />
<br />
<a href="https://www.blogger.com/">@NCSComputing</a> on twitter has started re-using the code to make other things happen, so thought it would be a good idea to write up how it works, so others can do the same.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://3.bp.blogspot.com/-H-LYgnZFcJA/VvV9bsQnasI/AAAAAAAAQok/uNkPidgVxPoTx8dixOlb5nOMg2i7CSdvA/s1600/CeLdEExWoAAkUWQ.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="178" src="https://3.bp.blogspot.com/-H-LYgnZFcJA/VvV9bsQnasI/AAAAAAAAQok/uNkPidgVxPoTx8dixOlb5nOMg2i7CSdvA/s320/CeLdEExWoAAkUWQ.jpg" width="320" /></a></div>
<br />
To make this work you need one program which runs on the Microbit and prints data and a second runs on your computer (a Raspberry Pi, PC, Mac, anything with a USB port) which reads the data via a serial connection.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-IWvgUUFD0Mk/VvV87XDq-pI/AAAAAAAAQoc/ZgSSIJfJB4E_uwD6nR6g67OL6RD3kbbeA/s1600/IMG_20160325_175730786_HDR.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="179" src="https://1.bp.blogspot.com/-IWvgUUFD0Mk/VvV87XDq-pI/AAAAAAAAQoc/ZgSSIJfJB4E_uwD6nR6g67OL6RD3kbbeA/s320/IMG_20160325_175730786_HDR.jpg" width="320" /></a></div>
<br />
See <a href="https://github.com/martinohanlon/microbit-serial">github.com/martinohanlon/microbit-serial</a> for the code for both of these programs.<br />
<br />
<b>The Microbit</b><br />
The <a href="https://github.com/martinohanlon/microbit-serial/blob/master/microbitreaddata.py">microbitreaddata.py</a> python program runs on the Microbit, gets the data and prints it to the output, which in this case is the USB serial connection, and should be flashed to your computer using the <a href="https://www.microbit.co.uk/create-code">Python editor</a>:<br />
<pre class="prettyprint">from microbit import *
REFRESH = 500
def get_data():
x, y, z = accelerometer.get_x(), accelerometer.get_y(), accelerometer.get_z()
a, b = button_a.was_pressed(), button_b.was_pressed()
print(x, y, z, a, b)
def run():
while True:
sleep(REFRESH)
get_data()
display.show('M')
run()
</pre>
<br />
<b>Your Computer</b><br />
The <a href="https://github.com/martinohanlon/microbit-serial/blob/master/clientreaddata.py">clientreaddata.py</a> python program runs on the computer and reads the data using <a href="http://pyserial.readthedocs.org/en/latest/pyserial.html#installation">pyserial</a>:<br />
<pre class="prettyprint">import serial
#the port will depend on your computer
#for a raspberry pi it will probably be /dev/ttyACM0
#PORT = "/dev/ttyACM0"
#for windows it will be COM(something)
PORT = "COM3"
BAUD = 115200
s = serial.Serial(PORT)
s.baudrate = BAUD
s.parity = serial.PARITY_NONE
s.databits = serial.EIGHTBITS
s.stopbits = serial.STOPBITS_ONE
try:
while True:
#read a line from the microbit, decode it and
# strip the whitespace at the end
data = s.readline().rstrip()
#split the accelerometer data into x, y, z
data_s = data.split(" ")
x, y, z = data_s[0], data_s[1], data_s[2]
a, b = data_s[3], data_s[4]
print(x,y,z)
print(a,b)
finally:
s.close()
</pre>
The values of the accelerometer will be put into the variables x, y, z and the buttons in a & b.<br />
<br />
<b>Setting the PORT</b><br />
You will have to change the <a href="https://github.com/martinohanlon/microbit-serial/blob/master/clientreaddata.py#L5">PORT variable in the clientreaddata.py program</a> to the comm port that the Microbit is connected to on your computer.<br />
<br />
For a Raspberry Pi it is probably "/dev/ttyACM0", in the event it isn't, unplug the Microbit and run:<br />
<pre class="prettyprint">ls /dev/tty*</pre>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://1.bp.blogspot.com/-RqxGt4uYWoM/VvV-rozcSRI/AAAAAAAAQo8/y9vqZ8M8w_cZiei24xs-4eHVWrIiq61Dg/s1600/microbitpiport.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="192" src="https://1.bp.blogspot.com/-RqxGt4uYWoM/VvV-rozcSRI/AAAAAAAAQo8/y9vqZ8M8w_cZiei24xs-4eHVWrIiq61Dg/s320/microbitpiport.JPG" width="320" /></a></div>
<br />
Then plug the Microbit and run the command again, the new device which appears will be the port of your Microbit.<br />
<br />
For Windows it will be "COM#", the # being a number, the easiest way is to look in <a href="http://lmgtfy.com/?q=open+windows+device+manager">Device Manager</a> for the "mBed Serial Port (COM#)"<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="https://4.bp.blogspot.com/-YNrYFYa1H2M/VvV9ltDzVVI/AAAAAAAAQos/czCQXWynpe0mHmZTjkY4bJh1lS0jiA_Tg/s1600/microbit-windowscommport.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="265" src="https://4.bp.blogspot.com/-YNrYFYa1H2M/VvV9ltDzVVI/AAAAAAAAQos/czCQXWynpe0mHmZTjkY4bJh1lS0jiA_Tg/s320/microbit-windowscommport.JPG" width="320" /></a></div>
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com3tag:blogger.com,1999:blog-9007601562606157016.post-8859716772125871972016-03-25T08:03:00.000+00:002016-03-29T10:25:01.692+01:00Raspberry Pi gpiozero holdable buttonThe current release of <a href="https://gpiozero.readthedocs.org/">gpiozero</a> doesn't have the support to hold a button down e.g. when a button is pressed and then held down for 1 second something happens.<br />
<br />
This is really useful when building hardware projects and you want 1 button to do 2 things, say turn something on when pressed, and turn off when held down.<br />
<br />
I needed this for a project so I thought I would create a new HoldableButton class using gpiozero. Hopefully this will be <a href="https://github.com/RPi-Distro/python-gpiozero/issues/115">incorporated into gpiozero</a>, but until then you can use the class below.<br />
<br />
The code is also available <a href="https://gist.github.com/martinohanlon/20cee570d6ea4ca0b7ad">here</a> as a gist.<br />
<br />
You will need to add the HoldableButton class to your Python program:<br />
<pre class="prettyprint">from gpiozero import Button
from threading import Timer
class HoldableButton(Button):
def __init__(self, pin=None, pull_up=True, bounce_time=None,
hold_time=1, repeat=False):
super(HoldableButton, self).__init__(pin, pull_up, bounce_time)
# Set Button when_pressed and when_released to call local functions
# cant use super() as it doesn't support setters
Button.when_pressed.fset(self, self._when_button_pressed)
Button.when_released.fset(self, self._when_button_released)
self._when_held = None
self._when_pressed = None
self._when_released = None
self._is_held = False
self.hold_time = hold_time
self.repeat = repeat
self._held_timer = None
#override button when_pressed and when_released
@property
def when_pressed(self):
return self._when_pressed
@when_pressed.setter
def when_pressed(self, value):
self._when_pressed = value
@property
def when_released(self):
return self._when_released
@when_released.setter
def when_released(self, value):
self._when_released = value
@property
def when_held(self):
return self._when_held
@when_held.setter
def when_held(self, value):
self._when_held = value
@property
def is_held(self):
return self._is_held
def _when_button_pressed(self):
self._start_hold()
if self._when_pressed != None:
self._when_pressed()
def _when_button_released(self):
self._is_held = False
self._stop_hold()
if self._when_released != None:
self.when_released()
def _start_hold(self):
self._held_timer = Timer(self.hold_time, self._button_held)
self._held_timer.start()
def _stop_hold(self):
if self._held_timer != None:
self._held_timer.cancel()
def _button_held(self):
self._is_held = True
if self._when_held != None:
if self.repeat and self.is_pressed:
self._start_hold()
self._when_held()</pre>
Using the HoldableButton class is pretty simple, similar to the gpiozero <a href="https://gpiozero.readthedocs.org/en/v1.1.0/api_input.html#button">Button</a> class and can be swapped for the Button class with no other changes.<br />
<pre class="prettyprint">holdbutton = HoldableButton(pin, hold_time = 1, repeat = False)</pre>
You have to pass a <b>pin</b> number and optional hold_time and repeat values:<br />
<ul>
<li>hold_time - is the number of seconds after the button is pressed before the button is consider 'held'</li>
<li>repeat - is a boolean and if set to True will occur 'button held' events to be repeated after each hold_time</li>
</ul>
You can use all the same methods and properties of the <a href="https://gpiozero.readthedocs.org/en/v1.1.0/api_input.html#button">Button</a> class, when_pressed, when_released, is_pressed, etc.<br />
<br />
There are 2 additional properties <b>is_held</b>, which will return a boolean stating whether the button has been held down for the 'hold_time' and <b>when_held</b> which when assigned a function will cause the function to be called when the button is held down.<br />
<pre class="prettyprint">def myheldfunction():
print("button held")
holdbutton.when_held = myheldfunction</pre>
Now when a button is held down, the function will be called and "button held" printed.Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com0tag:blogger.com,1999:blog-9007601562606157016.post-30383115269899476122016-02-02T21:08:00.000+00:002016-08-14T22:04:14.686+01:00Microbit - a Bop-it game in PythonI wanted to create a simple game for the Microbit and after bring brought an <a href="http://amzn.to/1PPYkzw">R2D2 Bop-it game</a> I thought I would make one whereby you have to press the A and B buttons in time.<br />
<div>
<br /></div>
<div>
Lets start by importing the microbit and random libraries:</div>
<pre class="prettyprint">from microbit import *
import random</pre>
<div>
Create some constants, one for the SPEED which is the amount of time in between each bop for each level, and one for the LEVELUP's which is the amount of points at each level:</div>
<pre class="prettyprint">SPEED = {0: 1000, 1: 750, 2: 650, 3: 600, 4: 550, 5: 500}
LEVELUP = (5, 10, 15, 20, 25, 30)</pre>
<div>
Create 4 functions which when caused will show A, B, a tick and a cross:</div>
<pre class="prettyprint">def show_a():
display.clear()
display.show("A")
def show_b():
display.clear()
display.show("B")
def show_tick():
display.clear()
display.set_pixel(0, 3, 9)
display.set_pixel(1, 4, 9)
display.set_pixel(2, 3, 9)
display.set_pixel(3, 2, 9)
display.set_pixel(4, 1, 9)
def show_cross():
display.clear()
display.show("X")</pre>
<div>
Create a function which will wait for the button to be pressed, returning True if it is and False if it isn't:</div>
<pre class="prettyprint">def wait_for_button(rightbutton, wrongbutton):
rightpressed = False
wrongpressed = False
started = running_time()
now = running_time()
while now - started < SPEED[level]:
if rightbutton.is_pressed():
rightpressed = True
if wrongbutton.is_pressed():
wrongpressed = True
now = running_time()
if rightpressed == True and wrongpressed == False:
return True
else:
return False</pre>
<div>
Set 3 variables for the level, the score and one which will be set to True when the game is over:</div>
<pre class="prettyprint">level = 0
score = 0
gameover = False</pre>
<div>
Scroll "BopBit" on the screen to show its the start of the game:</div>
<pre class="prettyprint">display.scroll("BopBit")</pre>
<div>
Loop until the game is over:</div>
<pre class="prettyprint">while gameover == False:</pre>
<div>
Randomly pick an action (either A or B), show it on the screen and wait for a button to be pressed:</div>
<pre class="prettyprint"> success = False
#randomly pick an A or B button
action = random.randint(0, 1)
#wait for the button to be pressed
if action == 0:
show_a()
success = wait_for_button(button_a, button_b)
elif action == 1:
show_b()
success = wait_for_button(button_b, button_a)
</pre>
<div>
If the player pressed the right button in time show a tick and increase the score or show a cross:</div>
<pre class="prettyprint"> if success:
show_tick()
score = score + 1
#if the score is a levelup score increase the level
if score in LEVELUP:
level = level + 1
else:
show_cross()
gameover = True</pre>
<div>
Wait for a small amount of time (half the current speed):</div>
<pre class="prettyprint"> sleep(int(SPEED[level] / 2))</pre>
<div>
After the game is over, sleep for 1 second, and display the players score on a loop:</div>
<pre class="prettyprint">sleep(1000)
while True:
display.scroll("{} points".format(score))</pre>
<div>
You can view the <a href="https://github.com/martinohanlon/microbit-micropython/blob/master/examples/bopbit.py">complete code</a> in my <a href="https://github.com/martinohanlon/microbit-micropython">Microbit MicroPython examples repository</a> on github.</div>
<div>
<br />
How about taking it further by adding new actions such as shaking or a connecting up a speaker and adding a sound track,<br />
<br /></div>
Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com3tag:blogger.com,1999:blog-9007601562606157016.post-9614589073184012672016-01-18T00:19:00.000+00:002016-12-05T13:32:32.796+00:00Pocket PiGRRL - Battery MonitorI recently made myself an <a href="https://learn.adafruit.com/pocket-pigrrl/overview">Adafruit Pocket PiGRRL</a> and I wanted to modify it so it would warn me when the battery was running low - there is a small red LED but its hidden inside the case!<br />
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-zxmeapplwwg/VpKHvJXWiWI/AAAAAAAAP2o/kBv1esu-FUE/s1600/IMG_20160106_213746797.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://4.bp.blogspot.com/-zxmeapplwwg/VpKHvJXWiWI/AAAAAAAAP2o/kBv1esu-FUE/s320/IMG_20160106_213746797.jpg" width="227" /></a></div>
<div>
<div>
<br /></div>
<div>
The plan was to create a program which would sense the battery getting low and put a warning icon on the top left of screen giving me time to shutdown the Pi properly or plug it in.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-UEa808dRUck/VpwZiPbDxTI/AAAAAAAAP6Y/u0A27x9-R7o/s1600/IMGP4581.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="236" src="https://3.bp.blogspot.com/-UEa808dRUck/VpwZiPbDxTI/AAAAAAAAP6Y/u0A27x9-R7o/s320/IMGP4581.JPG" width="320" /></a></div>
<div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-BkGyZwmfoHc/VpwrXvIHn6I/AAAAAAAAP74/oX4mioAtMQI/s1600/lowbatticon.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://4.bp.blogspot.com/-BkGyZwmfoHc/VpwrXvIHn6I/AAAAAAAAP74/oX4mioAtMQI/s1600/lowbatticon.jpg" /></a></div>
<br /></div>
<div>
TLDR - just scroll down to install Grrl Battery Monitor.</div>
<div>
<br /></div>
<div>
I started with the software as I, foolishly, thought this would be the hardest part, the problem with creating an icon is that is has to go over the top of everything regardless of what is on the screen (command prompt, emulators, emulation station, everything) or what hardware was rendering it.</div>
<div>
<br /></div>
<div>
My first plan was that I could use <a href="http://picamera.readthedocs.org/en/release-1.10/">Picamera</a>'s overlay function which I knew used the GPU to output directly to the screen, and with a bit of help from <a href="https://twitter.com/waveform80">Dave Jones</a> who put together a <a href="https://gist.github.com/waveform80/b13f7d78e6671c133984">prototype</a>, it was looking good, but while the icon appeared on top of emulators and the command prompt, it didnt write over emulation station.</div>
<div>
<br /></div>
<div>
I came across <a href="http://raspberrycompote.blogspot.co.uk/2012/12/low-level-graphics-on-raspberry-pi-part_9509.html">Low Level Graphics on Raspberry Pi</a> which walks you through writing graphics directly to the <a href="https://en.wikipedia.org/wiki/Linux_framebuffer">Linux framebuffer</a> using C, this was a lot lower level than I hoped to get into but it would definitely write my icon over anything that was on the screen - using this I wrote a <a href="https://github.com/martinohanlon/grrl-bat-monitor/blob/master/grrl_bat_mon.c">program</a> to create an icon on the screen when a GPIO pin was triggered.</div>
<div>
<br /></div>
<div>
Next I needed to be able to read from the <a href="https://learn.adafruit.com/adafruit-powerboost-1000c-load-share-usb-charge-boost/overview">power booster</a> when the battery was running low, my original plan was to use the LBO (low battery output) pin, but this proved to be way more difficult than I expected, read this <a href="http://forums.adafruit.com/viewtopic.php?f=19&t=87713">post on Adafruit's forum</a> if your really interested.</div>
<div>
<br /></div>
<div>
I ended up connecting a wire to the low battery warning led (red) on the power booster and using this to switch a transistor which connected a GPIO to ground.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-d-QIEnZth0o/VpwhhIrOAYI/AAAAAAAAP6o/GI0uM5f3eVk/s1600/IMGP4584.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="313" src="https://3.bp.blogspot.com/-d-QIEnZth0o/VpwhhIrOAYI/AAAAAAAAP6o/GI0uM5f3eVk/s320/IMGP4584.JPG" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div>
Its been frustrating but I am really pleased with how it worked out - if you want to add the batter monitor to your own Pocket PiGRRL follow the instructions below.</div>
<div>
<br /></div>
<div>
<b>Install Grrl Battery Monitor</b></div>
<div>
<b><br /></b></div>
<div>
You will need a few parts:</div>
<div>
<ul>
<li>Some wire</li>
<li>2N3904 NPN transistor</li>
<li>47k resistor</li>
<li>Strip board</li>
</ul>
<div>
<i>Note - if you are doing this on a PiGRRL 2 with a Pi 3, be sure to check out Christian's comments about the <a href="http://www.stuffaboutcode.com/2016/01/pocket-pigrrl-battery-monitor.html?showComment=1473048626905#c1441985850678463142">pin to use</a> and <a href="http://www.stuffaboutcode.com/2016/01/pocket-pigrrl-battery-monitor.html?showComment=1472960188243#c2350592785972375454">wiring-pi install</a> before starting.</i></div>
</div>
<div>
<br /></div>
<div>
1. Open up your Pi GRRL and connect a small length of wire to the red (low power) led on the power booster.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-M47krZP3lF0/VpwiVu7rfkI/AAAAAAAAP6w/6_GdKkjh8O8/s1600/redledsolderpoint.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="290" src="https://2.bp.blogspot.com/-M47krZP3lF0/VpwiVu7rfkI/AAAAAAAAP6w/6_GdKkjh8O8/s320/redledsolderpoint.jpg" width="320" /></a></div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-dfHx2XJzdcU/Vpwj8vF2WvI/AAAAAAAAP64/a_QSP4-jbzw/s1600/redledwire.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="258" src="https://1.bp.blogspot.com/-dfHx2XJzdcU/Vpwj8vF2WvI/AAAAAAAAP64/a_QSP4-jbzw/s320/redledwire.jpg" width="320" /></a></div>
<div>
<br /></div>
<div>
2. Solder the components to the strip board. including 2 lengths of wire which will connect to GPIO 19 and GND.</div>
<div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-yaIJxnwoXgQ/VpwlEeEaePI/AAAAAAAAP7M/TeF2ZHSIFdo/s1600/stripboard2.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="293" src="https://1.bp.blogspot.com/-yaIJxnwoXgQ/VpwlEeEaePI/AAAAAAAAP7M/TeF2ZHSIFdo/s320/stripboard2.jpg" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-fPs_qnGAOpk/VpwlFq3SdLI/AAAAAAAAP7U/k1Ad__aSfqs/s1600/stripboard.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="274" src="https://2.bp.blogspot.com/-fPs_qnGAOpk/VpwlFq3SdLI/AAAAAAAAP7U/k1Ad__aSfqs/s320/stripboard.JPG" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
</div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-rIUu9hRJqIg/VpwlEUoBIBI/AAAAAAAAP7A/43hnYoXLS9g/s1600/stripboard3.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="143" src="https://1.bp.blogspot.com/-rIUu9hRJqIg/VpwlEUoBIBI/AAAAAAAAP7A/43hnYoXLS9g/s320/stripboard3.JPG" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: left;">
<br /></div>
<div>
3. Flip over your Pi and solder the GPIO and GND wires to the underside of the Pi's GPIO header.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-qulqX1_dJoA/Vpwm5tOYIyI/AAAAAAAAP7c/K_ja4QJGZiI/s1600/soldertopi.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="299" src="https://2.bp.blogspot.com/-qulqX1_dJoA/Vpwm5tOYIyI/AAAAAAAAP7c/K_ja4QJGZiI/s320/soldertopi.JPG" width="320" /></a></div>
<div class="separator" style="clear: both; text-align: center;">
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://2.bp.blogspot.com/-Q7e8akZzEME/VpwnXD5Kf8I/AAAAAAAAP7k/iGVhavqxge0/s1600/soldertopi2.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="288" src="https://2.bp.blogspot.com/-Q7e8akZzEME/VpwnXD5Kf8I/AAAAAAAAP7k/iGVhavqxge0/s320/soldertopi2.JPG" width="320" /></a></div>
<div style="text-align: center;">
<i>The yellow wire is for my <a href="http://www.stuffaboutcode.com/2016/01/pocket-pigrrl-adding-mute.html">mute / un-mute amp function</a>.</i></div>
<div>
<br /></div>
<div>
4, Solder the wire from the low power (red) led to the strip board.</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-EDu5UbAwJrM/VpwoZphBLQI/AAAAAAAAP7s/F11qMgj_cL8/s1600/redledsolder.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="245" src="https://4.bp.blogspot.com/-EDu5UbAwJrM/VpwoZphBLQI/AAAAAAAAP7s/F11qMgj_cL8/s320/redledsolder.jpg" width="320" /></a></div>
<div>
<br /></div>
<div>
5. Stick the strip board to the case in-between the power booster and the amp with a bit of glue and put your PiGRRL back together.</div>
</div>
<div>
<br /></div>
<div>
6. Download the program from <a href="https://github.com/martinohanlon/grrl-bat-monitor">github.com/martinohanlon/grrl-bat-monitor</a></div>
<pre class="prettyprint">cd ~
git clone https://github.com/martinohanlon/grrl-bat-monitor</pre>
<div>
7. Make the program run at boot by editing /etc/rc.local</div>
<pre class="prettyprint">sudo nano /etc/rc.local</pre>
<div>
Scroll down and add the command under '/usr/local/bin/retrogame &' but before 'exit 0':</div>
<pre class="prettyprint">/home/pi/grrl-bat-monitor/grrl_bat_mon &</pre>
<div>
8. Reboot and test!</div>
<div>
<br /></div>
Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com19tag:blogger.com,1999:blog-9007601562606157016.post-65390450859303672862016-01-10T16:47:00.001+00:002017-04-24T09:11:24.656+01:00Pocket PiGRRL - adding a muteI recently made myself a <a href="https://learn.adafruit.com/pocket-pigrrl/overview">Pocket PiGRRL</a> based on Adafruit's tutorial - it really is a great machine and a brilliant learning experience.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://1.bp.blogspot.com/-l5Gu7NkfOD4/VpKHv8ZIYjI/AAAAAAAAP2g/8M82qR3jH6E/s1600/IMG_20160106_213808996.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="320" src="https://1.bp.blogspot.com/-l5Gu7NkfOD4/VpKHv8ZIYjI/AAAAAAAAP2g/8M82qR3jH6E/s320/IMG_20160106_213808996.jpg" width="222" /></a></div>
<br />
There was one aspect though that I didn't like, the speaker hisses, not particularly loud and when your playing a game its not that noticeable but if you have got the volume down it is really annoying. Its all down the Raspberry Pi's noisy analogue audio out so there isn't a great deal you can do to clean it up.<br />
<br />
My solution was to add the ability to shutdown the amp, effectively muting it when I didn't want any sound.<br />
<br />
The PAM8302A amp breakout board has a shutdown (SD) pin which when a ground (logic zero) is connected it puts the amp into idle mode, muting the amp and reducing power consumption.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-44qFwNoKRiw/VpKHw5CA7RI/AAAAAAAAP28/yG0-p-Fvf94/s1600/gaming_secure_pam8302.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="262" src="https://4.bp.blogspot.com/-44qFwNoKRiw/VpKHw5CA7RI/AAAAAAAAP28/yG0-p-Fvf94/s320/gaming_secure_pam8302.jpg" width="320" /></a></div>
<br />
I soldered a piece of wire between GPIO 26 on the bottom of the A+ and the shutdown pin on the PAM8302A ampl.<br />
<br />
<i>Note - a few people have noted in the comments that on other models of PiGrrl (such as the Pi Grrl 2) GPIO 26 is already used and have suggested changing this to GPIO 7.</i><br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-DNheNa8EVh8/VpKHv0XKvOI/AAAAAAAAP24/B1Rririrz9A/s1600/IMG_20160108_204432090.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="194" src="https://4.bp.blogspot.com/-DNheNa8EVh8/VpKHv0XKvOI/AAAAAAAAP24/B1Rririrz9A/s320/IMG_20160108_204432090.jpg" width="320" /></a></div>
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-v_B4NjgG9GY/VpKHw6y1HuI/AAAAAAAAP3A/xAkKnoM4l70/s1600/IMG_20160108_204531426.jpg" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="183" src="https://3.bp.blogspot.com/-v_B4NjgG9GY/VpKHw6y1HuI/AAAAAAAAP3A/xAkKnoM4l70/s320/IMG_20160108_204531426.jpg" width="320" /></a></div>
<br />
This gave me a way of triggering the shutdown pin next I needed some software and a way of running it.<br />
<br />
Using this <a href="https://weekendengineer.wordpress.com/2014/09/15/adding-an-apps-tab-in-emulationstation/">tutorial</a> as the basis I added an 'Apps' tab to emulation station where I could run 2 scripts to mute and unmute the amp.<br />
<br />
If you want to configure your Pocket PiGRRL to do the same, you can follow the instructions below.<br />
<br />
<b>Download and install wiring pi</b><br />
The software uses wiringpi's gpio command line utility, so <a href="http://wiringpi.com/download-and-install/">download and install</a> it.<br />
<br />
<b>Configure emulation station</b><br />
Copy the emulation station default settings file to the pi user's emulation station configuration:<br />
<pre class="prettyprint">cp /etc/emulationstation/es_systems.cfg ~/.emulationstation/</pre>
Add the 'apps' tab to the settings file:<br />
<pre class="prettyprint">nano ~/.emulationstation/es_systems.cfg</pre>
Scroll down to the bottom and add the following before the </systemList> text:<br />
<pre class="prettyprint"> <system>
<fullname>Applications</fullname>
<name>Apps</name>
<path>~/RetroPie/roms/apps</path>
<extension>.sh .SH .py .PY</extension>
<command>%ROM%</command>
<platform>apps</platform>
<theme>esconfig</theme>
</system></pre>
Save and exit using Ctrl X.<br />
<br />
Make a directory in roms to hold the scripts:<br />
<pre class="prettyprint">mkdir ~/RetroPie/roms/apps</pre>
Create a script to mute the amp by setting GPIO 26 to low (0):<br />
<pre class="prettyprint">nano ~/RetroPie/roms/apps/mute_amp.sh
gpio -g mode 26 out
gpio -g write 26 0</pre>
And an unmute script:<br />
<pre class="prettyprint">nano ~/RetroPie/roms/apps/unmute_amp.sh
gpio -g mode 26 out
gpio -g write 26 1</pre>
Make the scripts executable:<br />
<pre class="prettyprint">chmod +x ~/RetroPie/roms/apps/mute_amp.sh
chmod +x ~/RetroPie/roms/apps/unmute_amp.sh</pre>
You can now test the scripts by running them:<br />
<pre class="prettyprint">~/RetroPie/roms/apps/mute_amp.sh
~/RetroPie/roms/apps/unmute_amp.sh</pre>
Reboot and the Apps tab will appear in emulation station with 2 options to mute and unmute the amp.<br />
<br />
I wanted the amp to be muted by default, so I added the script to be run at boot by editing /etc/rc.local:<br />
<pre class="prettyprint">sudo nano /etc/rc.local</pre>
Scroll down and add the unmute command under '/usr/local/bin/retrogame &' but before 'exit 0':<br />
<pre class="prettyprint">/home/pi/RetroPie/roms/apps/mute_amp.sh &</pre>
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com21tag:blogger.com,1999:blog-9007601562606157016.post-24019810525229489032015-12-18T13:52:00.000+00:002016-02-02T21:09:13.207+00:00Minecraft, a Microbit and an X-WingI was having a chat with <a href="https://twitter.com/whaleygeek">David Whale</a>, my co-author of <a href="http://eu.wiley.com/WileyCDA/WileyTitle/productCd-111894691X.html">Adventures in Minecraft</a> and he remarked that wouldn't it be cool if you could control something in Minecraft using the Microbit. (Btw - you should definitely check out David's virtual <a href="https://github.com/whaleygeek/mc_microbit">Minecraft Microbit</a>.)<br />
<br />
I settled on the idea of using the Microbit's accelerometer to control an object flying through Minecraft. What object, well it had to be the X-Wing, from my previous <a href="http://www.stuffaboutcode.com/2015/03/minecraft-star-wars.html">Minecraft - Star Wars</a> project.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://3.bp.blogspot.com/-aJZ3PfkNHG8/VnQL9UGdCFI/AAAAAAAAPjw/lIWoTrM2R80/s1600/minecraft_microbit.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="180" src="http://3.bp.blogspot.com/-aJZ3PfkNHG8/VnQL9UGdCFI/AAAAAAAAPjw/lIWoTrM2R80/s320/minecraft_microbit.JPG" width="320" /></a></div>
<br />
The A button starts and stops the X-Wing, by tilting the Microbit left and right you can turn and the B button drops blocks of TNT which create craters where they land.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen="" class="YOUTUBE-iframe-video" data-thumbnail-src="https://i.ytimg.com/vi/59KqWVwj_Cc/0.jpg" frameborder="0" height="266" src="https://www.youtube.com/embed/59KqWVwj_Cc?feature=player_embedded" width="320"></iframe></div>
<br />
There are 2 python programs:<br />
<ol>
<li><a href="https://github.com/martinohanlon/microbit-micropython/blob/master/examples/mcfly/microbitreaddata.py">microbitreaddata.py</a> - this runs on the Microbit and reads the status of the buttons and accelerometer </li>
<li><a href="https://github.com/martinohanlon/microbit-micropython/blob/master/examples/mcfly/mcfly.py">mcfly.py</a> - this runs on your computer (I used a Windows PC running Raspberry Juice and full Minecraft, but it would work on a Raspberry Pi as well) which reads the data from the Microbit and makes all the calls to move the X-Wing in Minecraft.</li>
</ol>
You will find the full code and my other Microbit MicroPython examples at <a href="https://github.com/martinohanlon/microbit-micropython">github.com/martinohanlon/microbit-micropython</a>.<br />
<br />Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com6tag:blogger.com,1999:blog-9007601562606157016.post-44849067084264938182015-11-30T18:41:00.001+00:002016-02-02T21:09:13.215+00:00MicroBit Magic 8 Ball with MicroPythonI wanted to create something with the MicroBit which used the on-board accelerometer and I settled on a <a href="https://en.wikipedia.org/wiki/Magic_8-Ball">Magic 8 Ball</a>, the fortune-telling pool ball which when shaken and asked a question it provides, a, often cryptic, response.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<iframe allowfullscreen="" class="YOUTUBE-iframe-video" data-thumbnail-src="https://i.ytimg.com/vi/b-8cRJiEKbo/0.jpg" frameborder="0" height="266" src="https://www.youtube.com/embed/b-8cRJiEKbo?feature=player_embedded" width="320"></iframe></div>
<div>
<br /></div>
<div>
The program works out whether the MicroBit has been shaken by:</div>
<div>
<ul>
<li>Reading the x, y, z values from the accelerometer in a loop and adding them together to get a total force exposed</li>
<li>Getting the difference between the last reading and the current reading</li>
<li>If the difference is greater than a threshold, you assume the MicroBit has been shaken</li>
</ul>
<div>
I wrapped this into a function wait_for_shake, which perhaps not unsurprisingly blocks until the MicroBit is shaken!</div>
<pre class="prettyprint">import microbit
TOLERANCE = 3000
def get_accel_total():
x = microbit.accelerometer.get_x()
y = microbit.accelerometer.get_y()
z = microbit.accelerometer.get_z()
return x + y + z
def wait_for_shake():
shaken = False
last = get_accel_total()
while not shaken:
this = get_accel_total()
diff = last - this
if diff < 0: diff = diff * -1
if diff > TOLERANCE:
shaken = True
last = this
microbit.sleep(50)</pre>
<div>
Its not 'very' sophisticated but it works.<br />
<br />
Once I had this working it pretty simple to add a loop which waited for the MicroBit to be shaken and scrolled a random message on the LED screen.<br />
<pre class="prettyprint">MESSAGES = ["It is certain", "Dont count on it", "Ask again"]
while True:
microbit.display.print("8")
wait_for_shake()
microbit.display.clear()
microbit.sleep(2000)
message = microbit.random(len(MESSAGES))
microbit.display.scroll(MESSAGES[message])</pre>
If you want to add your own messages, just add them to the MESSAGES list.<br />
<br />
You can find the code <a href="https://github.com/martinohanlon/microbit-micropython/blob/master/examples/8ball.py">here</a> and other examples in my <a href="https://github.com/martinohanlon/microbit-micropython">microbit-micropython GitHub repository</a>.<br />
<br />
<div class="separator" style="clear: both; text-align: center;">
<a href="http://4.bp.blogspot.com/-sC1swRCSexw/VlyXwJmMJKI/AAAAAAAAPYA/E0WDddsrhts/s1600/8ballmicrobit.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="242" src="http://4.bp.blogspot.com/-sC1swRCSexw/VlyXwJmMJKI/AAAAAAAAPYA/E0WDddsrhts/s320/8ballmicrobit.JPG" width="320" /></a></div>
<br /></div>
</div>
Martin O'Hanlonhttp://www.blogger.com/profile/03047799173301971515noreply@blogger.com0