Arduino project 7 – buttons

arduino project with an LED and two buttons

two buttons and a light

The next arduino project in the book is the first to use input: it uses two buttons and an LED, so that pushing one button will turn the light on and the other turns it off again.  Still a simple idea, but one that illustrates how input can be used in a program to control a light, and could be extended theoretically to control any components by pushbutton input.

The loop part of the program is straightforward:

void loop(){
   if (digitalRead(inputPin1)==LOW){
     digitalWrite(ledPin,LOW); //turn LED off
 }
 else if (digitalRead(inputPin2)==LOW){
   digitalWrite(ledPin, HIGH);//turn LED on
 }
}

It was strange to be back writing in Java again with its curly braces and semicolons, not to mention having to declare variable types, but I’m finding it easier these days to switch between the two – and of course indenting comes through habit having dealt with Python so much!

What does frustrate me now is that theoretically I should be able to code a set of pelican crossing lights triggered by pressing a button, and I’m sure that I could reasonably easily figure out the code to use, but the knowledge I don’t have is how to join the components together, as the project book tells you what to use and where but not why or how they work. Comments like “there is one component that might seem out of place…” really don’t help, as its assuming more knowledge of the circuit than I have.

I’m starting to make a point of looking at the circuit diagram supplied as well as the schematic of the construction, but I’ve no idea when resistors are needed or what size to use, or when a capacitor or transistor is needed, and I would not be able to create my own project, although I’d be quite happy following the sorts of instructions I’ve come across so far, which are of the type of put X here and Y there and Z goes in this spot.  To be honest, I’m not sure what sort of time I’d have to learn any more about these components, although I have come to enjoy my weekly soldering sessions (last week I made a battery powered gadget that responds to sound by flashing lights on and off, and the timer I made the week before has somehow started working correctly – previously it wasn’t beeping when the time was complete, but just when it was turned off).

What I have gained over the summer, however, is a deeper understanding of what circuit boards are (I even looked up how to make them!), what the different components are, the skill needed to assemble and solder them and the sorts of things that can be done with an arduino and a handful of bits.

There are still four more projects in the book, and there are plenty more arduino books out there, but with summer drawing to a close I’m not sure how much time I’ll have to devote to playing with electronics.  My interest has only grown over the few weeks I’ve been playing, however, and I’ll be doing my best not to abandon the arduino and the soldering iron.

I may even try playing with bits and doing some research to see if I can mock up the three traffic lights, two pedestrian lights and button that would be needed for a pelican crossing prototype!

In the meantime, the weekend’s task has to be to get the Pi up and running and see what I can do with that, so I’m off to tidy my desk up a bit to make room.

 

Python codeword project

Another project I’ve been thinking of (for many, many years, actually, since I first came across the puzzle type) is a program to help solve codeword puzzles.  These are the ones that look like crosswords, except that each square has a number and each number stands for a letter of the alphabet, so you have to crack the code to solve the puzzle.  I love these puzzles but don’t like trying a letter out, changing my mind and having to scrub them back out of the book, so my idea is to create something that will replicate the grid on screen and allow you to type in a number and letter and have the program automatically replace for you, with a reset button for each number if you change your mind.

I think I’ve even made a half-hearted attempt to get going before, but never really got very far, but having seen the listings for python games using the console, including Reversi and tic-tac-toe (or othello and naughts and crosses if you prefer) I’ve realised that it’s worth making a start in console mode to get the basic functionality sorted, with a better interface as a future development.

I’ve had a frustrating time at some points in this project, but I’ve also learned a lot. There were two main learning foci – data structures and classes.  With data structures I think I hit problems because I was thinking too much about two dimensional arrays to store the grid, but in Python I have a list  of lists – the grid looks like [[codeword, codeword, codeword],[codeword, codeword, codeword]] where each of the inner lists represents one line in the grid and each object in that list is an object of a new class I’ve defined.

Python offers a useful way to iterate through lists: you simply call

for <element> in <list>:

and then you can run through them, for example:

for e in self.square:
    for f in e:
        if f.number==num:
            f.setLetter(let)

This cycles through all the elements in the main list, all the elements within that element, and if the number matches it sets the chosen letter.

The codeword object contains three attributes: it has a number, a letter and a boolean called fixed, which enables me to lock a letter/number combination when I’m sure it’s right (or if it’s one of those given as part of the original puzzle).

codeword console in action, showing grid drawn and redrawn

codeword console in action

So far I can display the grid in the console, change, lock, unlock or reset letters and redraw the grid to display any changes.  The next stage will be to provide a key, which shows which letters have been assigned and which are still available to use.

Then I need to tie the engine to an interface, as the console display makes it hard to see the words properly and it’s tiresome to have to type commands directly into the console rather than clicking on buttons.

The idea of writing classes and functions to deal with different aspects of the project is to make it modular, so that I can replace my current codeword object with a similar object that will respond to the same calls but display things differently, so that it’s easier to replace/modify small areas of code rather than having to write the whole lot again, but in Python you can define more than one class in the same file, and indeed have your main program code there as well, whereas in Java it’s usual to have one class per file and import them all.

I haven’t mastered the art of modules yet to include code from other files that I have created, but then I haven’t really needed to, as my entire project is only 134 lines long, including comments and whitespace.

There’s still plenty of room for improvement: as well as the interface upgrade, it’s also possible to provide an option to save and restore games, and the method of inputting the grid needs to be streamlined – at the moment I have to type the numbers in for each line separated by a space, with 0 for a blank.  A check is made that I’ve entered the right number of values for the line, but not that they’re correct, and any mistake means restarting.

Still, I’ve made a working prototype that’s proven the possibility, and had fun developing my thinking skills in the process.  I’m also starting to remember some of what I learned about interfaces to objects, encapsulation and various other topics.  I had an issue with Python’s typing at one point as it doesn’t need its variable types declared, and I was getting muddled between ints and strings, but it just means it’s down to me to watch what I’m doing rather than relying on the language to enforce type or flag up problems.

I’m constantly reminded, though, that it helps to understand what’s going on and what the principles are, and so the importance of understanding theory as well as having practical experience, and how each feeds into the other constantly.

I’ve provided the code below, if anyone’s interested in looking – it’s very much a Work in Progress, and probably very clumsy and muddled in places, so be warned!

codeword puzzle assistant

Virtual pet version 2

Time I returned to my virtual pet!  While I have written a detailed specification for the project, I decided to put in an intermediate stage when creating, so in this version there is no day or night, and the algorithms for the change in the variables aren’t completely worked out yet.  I do now have three variables for the pet: health, happiness and hunger.  Each has its own way of interacting with it: feeding, medicine and a ball to play with.  The player has to keep hunger down and happiness and health up in order to have the pet survive.  Health and happiness link to each other – an unhappy pet loses health faster, and vice versa.

virtual pet code version 2

code for version 2

I worked in Scratch originally for version 2, then when I could see repeated code I used BYOB features to pull out that repeated code and make it into a new block, complete with a passed in parameter.  This avoided the repetition as each requirement for death meant broadcasting a message explaining the reason, making the pet disappear and then stopping the script.

I found it straightforward to create my new block, including passing in a message to say why the pet died, and I also like the way that BYOB will change the colour of nested blocks, making it easier to see how they are put together.

Adding a timer to the game made it a little more interesting, as now it will record the length of time the previous pet lasted, but I still need to do a lot of work on the graphics, in order to have the pet show visually what his problems are.  Once I’ve done that, it may be possible to remove all displayed variables from on screen, to make the player look carefully at the sprite rather than just checking the numbers.

die block, including a passed in parameter

custom made “die” block

While the code for the project is becoming more complicated, it is still fairly straightforward, with one script per sprite.  Breaking into more than one script could lead to complications as different scripts running at the same time could interfere with each other, so I’m trying to be careful – for example I could have scripts to run animations for different interactions, but it might be possible to run two or more at the same time, with unintended results.

The project is coming along nicely, so now I need to reproduce this version in App Inventor. I also need to look back at the specification I wrote to see how it fits in with what I’ve done so far and then move on to develop it further, including day/night settings.

I’m still not happy with the gameplay and amount of interaction compared to feedback.  It’s a playable game, but without enough real challenge or interest yet to keep a player interested.  Thinking back to the original tamagotchi, that would beep for attention, and there were mini-games to play.  It was also a much longer-lived game, lasting for days and even weeks.  That’s not possible in Scratch, as it has no file-saving capabilities, but it would be possible in an android app, which is more likely to be the end format of this project.

It would also be possible in a Python project, which is something else I might try at some stage – that would make it usable on a PC, rather than on a mobile device.

Before I do much more with coding, though, I need to work on developing graphics and sound, as a game is so much more than just programming in the behaviours.

 

Resources in a flash!

I’ve been busy over the past few days getting ready for the start of the new term in a more practical, immediate way, but today I’ve decided it’s time for another play.  I’m ambivalent about using Flash: it’s brilliant fun, and produces some good products, but it’s fiddly with little help for debugging, it feels like a dead end, and with no support for iOS, Android withdrawing support and with HTML 5 coming up, I’m not sure it will be around for much longer.

However, I have dabbled in it, both animating and coding, and it seemed an ideal way to combine the work I’ve been doing in a useful way.

I’ve been using Cam Studio, Audacity and MoviePlus to make screen capture videos with narration, to help my students use Serif MoviePlus, and the result is a collection of nine videos, the shortest 40 seconds (trimming and splitting) and the longest 4:30 (transform effects).  I wanted a way to tie all the videos together for ease of selection.

I could use powerpoint of course; in fact I already have a hyperlinked powerpoint on MoviePlus which I’ll probably add the videos to at some stage, but I wanted to try building a flash project to house the videos.  It’s based on chapter 7 of Adobe Flash CS4 Professional Classroom in a Book, which has a project showing how to link videos together.

I used the adobe encoder to encode the videos into Flash format, then examined the finished project from chapter 7, which I worked through a few months ago.  The code for the buttons was very straightforward, so I created a graphic for a button and put together a version just to check out that it would work.

first try at flash embedded movie

first version of flash resource to play tutorial vids

I was pleased with the result: I have a screen with a button on it.  The button is animated for mouseover and mousedown, and when pressed it activates the appropriate video, complete with playback skin containing video and volume controls.  The button is too large, and the project itself probably too small to contain all buttons plus the video playback, but the principle has been well and truly proven.

Time to create all the button graphics then!

I used Drawplus to create the original buttons, then adjusted size and position for the different button states in Flash, but I wasn’t happy with the results – the text on the buttons looks rather blurry, and I think next time I’ll try creating them directly in Flash, or have a closer look at the export settings.  I had a reminder of some of the problems I’ve found with Flash: it can be rather fiddly at times, and really doesn’t like being messed with – I’ve found it’s far easier to spend a few minutes planning and do exactly what I want from the beginning, rather than to rush in and try to fix things on the fly.  I also remembered eventually that it’s far easier to use layers to separate elements on the page.  I did use a little maths to get the elements to line up properly and adjust the size of the finished project to accommodate all the elements.

completed design - nearly working, just one problem

finished product (looks good, not quite working yet)

This is the finished project: I have 9 buttons plus a video window, and clicking on any of the buttons brings up the associated video.  The only problem for a while (and it was a fairly major one, to be honest!) was that as I switched from one video to the next the sound from the previous one would keep playing.

Still, the code itself was remarkably simple:

startButton1.addEventListener(MouseEvent.CLICK,clickListener1);
function clickListener1(event:MouseEvent):void {
     gotoAndStop("startvid");
}

This is placed on the actions layer, in the first frame of the timeline, and repeated for each button, changing the name of the button, the number of the clickListener and the name of the frame to move to.    The action in frame 40 is just stop(); – there’s no actual animation in the project between frame 1 and frame 40, but I left the space there just in case I decide to include any.

partial timeline showing named frames

part of the timeline, showing named frames

This is my timeline, showing that I’ve named frames for each video.  Each button listener function sends the playhead to the appropriate frame, and the video inside its control starts playing automatically.  The timeline stops on the first frame of the section, but the rest are there as padding so I can see the name of the frame.

So I’ve learned a lot on this project so far, and while it’s been time consuming the learning has been worth the time spent and next time round I’ll be more confident in what I’m doing and so will work faster.

A little playing around to tidy up the project miraculously seemed to fix the sound problem, so I now have a finished resource (or set of resources) ready for use, plus the confidence that comes from tackling a project and making it all work, plus a template that I can use again and again to link videos together (I’ve had students say: “Your video was useful, Miss, but I did have to play it over and over and keep stopping it!”).

In the meantime, I’ll also dig out my hyperlinked powerpoint and try not to fall asleep adding the videos to it!

 

App Inventor – automatic texts

The design of the notext app is very simple - a message to explain what it does and a box to type in a new message to send

The screen layout is simple

Today I was trying out a new book called App Inventor – Create your own Android Apps, which starts with the tutorials from the app inventor site but with more background explanation then continues to introduce further concepts via example apps.  The first of the new apps is called No Texting While Driving, and the authors are anxious to explain that this app was thought up by a new student during a session to introduce app inventor, and developed by the group as the session went on.  A similar app has since been developed commercially; whether it was inspired by this student’s original idea or not is not known.

The purpose of the app is to provide an automatic message in reply to any texts received while the app is open – this may simply say “I’m driving and will contact you when I’m free” or can be edited to a custom message.

Instructions are given to develop the app further in order to read the incoming message and sender details out loud and provide a geographical location with the outgoing message so the recipient knows where you are, but I didn’t continue that far as I was anxious to test out the main functionality.

blocks for the beginning of the no texting while driving app

The beginning of the NoText app

I found the instructions themselves fairly straightforward to follow, and good explanations are given as to how things work, but I did find it easiest to skip straight to the pictures showing the assembled blocks, referring to the table of components where necessary to find out what section a block was in.

The app seemed to work fairly well, with the only issue being changing the message to be sent – my version ended up sending any new message in addition to the old message, rather than replacing it.

Still, I was impressed with the ease of connecting to the text message system in order to read and reply to incoming messages, and feel that the system really is simple enough that having seen many of these concepts in use once it’s easy to adapt them for your own uses.

The book looks like it continues with many more interesting apps, such as using a barcode scanner, geographical locations, animated apps, games, quizzes and a chapter on web APIs for anyone who’s really serious about app design.

I do, however, find it fiddly at times to get app inventor up and running, particularly the code editor, as on my main machine it seems to get nowhere and on my laptop it takes a while to load – not ideal when in a classroom setting. Still, I would love to have App Inventor available for computer club sessions, and maybe for the coursework task from OCR if it proves reliable enough.

 

Electronic timer project

assembled timer - lots of LEDs!

assembled timer – all hand soldered in

Time for more soldering – delayed from the weekend due to real life commitments, but eventually I managed to get the soldering iron out, this time for the kitchen timer kit from Maplin.

A couple of hours’ work assembled all components, including a buzzer, 16 LEDs, an integrated chip, resistors and capacitors, the battery box was connected and the whole thing screwed together – so it was time for the moment of truth!

completed timer with LEDs showing

completed timer with LEDs showing

Yes, it all works, I’m pleased to say.  I now have a working kitchen timer that I made myself from components.  The push button sets the time, then the lights gradually go out until at the end they light up in a pattern.  The buzzer sounds when the timer is turned off.

This was a simpler kit than the radio (which I still haven’t found a power supply to test) but on the whole probably a little more fiddly, owing to the size of the LEDs and the sheer number of them.  I figured out how to make electronics easier – make the circuit boards bigger so that the soldering is less fiddly, but I suspect the experts would disagree and tell me it’s just experience! I’m currently using the 30 watt size soldering iron.  They do make smaller sizes, and I suspect that if I end up doing a lot more electronic soldering I’ll splash out for a smaller, more delicate one – and a proper soldering stand, as it’s nervewracking having a hot soldering iron sitting on the desk not properly secured.

What I don’t know yet is how to make a circuit board – I suspect it’s something to do with etching, and beyond both my capabilities and tools – but on the whole I’m a lot happier with the idea of assembling electronic components and programming them than I was at the start of the summer.

Python – high score table

code for high score part 1

high score code part 1

I’m returning to the high score table task, seeing what I can do with it.  Here I feel my lack of practice probably helps me to see the issues more clearly than if I was a fluent programmer (well, that’s how I’m comforting myself, anyway!).

A reminder of the problem: it’s based on the third task in the specimen paper from OCR GCSE computing, where the requirement is for a high score table to store names and scores for up to 10 players, and be able to write these to a file and read them back in.  I’ve adapted the task a little, so it may well exceed the stated requirements, but then I’m also coming at the code with a hammer rather than a scalpel, I suspect!

I’ve decided to store the high scores in a list of lists, so it will take the format [[335, “Fred Bloggs”],[387, “George Smith”],[938, “Sarah Jones”]], where the first entry relates to the score and the second to the name of the scorer in each case.

Functions that I need to build are:

get_high_score(hstable) returns the highest score and player name

display_high_scores(hstable) prints out the list of scores and names

add_high_score(hstable, score, name) will add a high score to the table if it qualifies

delete_high_score(hstable, name) removes this person and their score from the table

delete_name(hstable, score) removes this score and the associated person from the table

get_high_score(hstable, name) returns the highest score of that person

get_name(hstable, score) returns the name of the person who scored that score

high score code part 2

high score code part 2

I also need to find a way to sort the list so that the scorers are in order from highest score to lowest score.  A little research came up with the way to sort the list by one of the attributes of the inner lists, and a way to reverse that list, by using hstable.sort(key=lambda x: x[0]) then hstable.reverse() – there was supposed to be a way to combine those two commands but the system refused to co-operate on it.

Working out that the easiest way to add a record to the table in the right place if it qualified was to add it to the list, sort the list and then remove the last item if it was more than 10 items long, things quickly fell into place.

The only thing that I had real trouble with was retrieving a saved file, which stubbornly refused to work.  I could check the file had saved correctly, but it refused to load back in.  The console was a real lifesaver, as I could run the file and then type in lines in the console to check the code on the fly.

One other quirk was that when I removed a name from the list two of the three occurrences would be removed.  I could then run the same command again to remove the third occurrence – no idea why it won’t remove all three the first time until I have time to go through step by step.

Generally, though, I’m happy I have a program that will do most of what it’s supposed to, and could quite easily be adapted to be a class for use in a games program.  At this point I think I need to double check the use of the terms functions and methods!

I found that if I got stuck I could generally find the solution somewhere on the web, as long as I knew roughly what I was trying to do, but I’m not sure students new to programming would find it quite so easy.  This is partly why I’m trying to find all the pitfalls and work them out at this stage, so I can make sure they have the best chance of knowing everything they need.  Still, the ability to use class documentation and help systems is invaluable for anyone intending to do any serious coding.