background image

EXPERIMENT MANUAL

620141

-03-

0

90

8

16

Franckh-Kosmos Verlags-GmbH & Co. KG, Pfizerstr. 5-7, 70184 Stuttgart, Germany   |    +49 (0) 711 2191-0    |   www.kosmos.de 

Thames & Kosmos, 301 Friendship St., Providence, RI, 02903, USA    |   1-800-587-2872    |   www.thamesandkosmos.com 

Thames & Kosmos UK Ltd, Goudhurst, Kent, TN17 2QZ , United Kingdom   |   01580 212000    |   www.thamesandkosmos.co.uk

CodeGamer manual cover english.indd   1

8/9/16   10:04 AM

Summary of Contents for Code Gamer

Page 1: ...uttgart Germany 49 0 711 2191 0 www kosmos de Thames Kosmos 301 Friendship St Providence RI 02903 USA 1 800 587 2872 www thamesandkosmos com Thames Kosmos UK Ltd Goudhurst Kent TN17 2QZ United Kingdom 01580 212000 www thamesandkosmos co uk CodeGamer manual cover english indd 1 8 9 16 10 04 AM ...

Page 2: ...niki Würzburg Illustrations Michael Schlegel komuniki Würzburg Manual photos picsfive all pushpins askaja all paper clips Jaimie Duplass all tape strips all fotolia com 8vFanl p 61 bottom right hopsalka p 61 top krista p 2 bottom left p 21 bottom right tepic p 20 bottom all iStockphoto com Designua p 38 bottom shutterstock com leejeongsoo p 35 bottom theSOARnet p 38 top Petr Kratochvil p 33 top al...

Page 3: ...ntity Item No 15 Housing for motion sensor 1 717 998 718 002 16 Breadboard 1 717 996 17 Jumper wires 10 717 990 male female 18 Jumper wires 10 717 989 male male 19 Resistors 330 Ohm 5 717 991 20 LEDs yellow 1 each 717 994 green 717 993 blue 717 995 red 717 992 21 Cable USB to Micro USB 1 717 988 22 Lithium polymer battery 800 mAh 1 717 987 not shown You will also need Smartphone or tablet with And...

Page 4: ...ial monitor 28 The for loop 30 Sensors 32 Project 8 Thermometer 33 Project 9 Finger disco 36 Project 10 Cheep 38 Project 11 Random sounds 39 Project 12 Siren 40 Project 13 Musical scale 43 Project 14 Sensor organ 44 Project 15 The serial plotter 46 Project 16 Clap switch 47 Project 17 Drawer monitor 48 Project 18 Looking inside the fridge 53 Project 19 Ghostly eyes 55 Common Error Messages 62 Note...

Page 5: ...e of the wheel into the rotation encoder hole The rotation encoder is attached to the interaction board and marked there 3 Connect the battery to the interaction board The attachment is on the bottom side The battery s plug is shaped in such a way that it can only be connected in the correct polarity direction Do not force it 4 Now place the battery in the lower housing of the interaction board In...

Page 6: ...tach the gray rubber feet onto the bottom of each button To do this simply insert the thinner side of the rubber foot into the recess on the bottom of the button Then insert the button plate into the right upper gamepad housing Be sure that the buttons are positioned correctly You know that everything is correctly placed when you feel an explicit trigger point when the buttons are pushed Then atta...

Page 7: ...ll you which blank space in the code they will complete Use your gamepad to control the characters in the game To do this you must have Bluetooth activated on your tablet or smartphone Start the app and switch on the gamepad by sliding the switch at the upper edge to the ON position The connection will then be made automatically in a few seconds Once the connection is active the control elements a...

Page 8: ... and forth to activate its abilities We will let you find out on your own how to activate the special abilities of the other sensorbots Play the game once through and take a look at the other contents of the app in the main menu You will find a lot there about your experiment kit and the topic of programming We hope you have a lot of fun experimenting with code The World of the Microcontroller Wel...

Page 9: ... called GPIO pins That s an abbreviation for General Purpose Input Output These GPIO pins can be used for both inputs and outputs And that s just what you need here 1 INPUT You can connect an input pin to a sensor for example This will monitor the outside world and send information about the surroundings temperature or brightness to the processor via fluctuating levels of electrical voltage In you...

Page 10: ...ou will be asked for a contribution The Arduino project which promotes the development of the Arduino software is largely financed by these kinds of donations You can also download the software for free without making a donation by clicking on Just Download Windows 1 Open the explorer 2 Go to the downloads folder 3 Double click the kosmobits_archive zip file to open it 4 Select all the files and f...

Page 11: ...n loop are invoked over and over in an endless loop That is why it s called a loop function You can visualize this idea a little more clearly in a flow diagram The program always proceeds in the direction of the arrows from switching on to setup to loop and then back to loop again and again You could upload this program right away to your KosmoDuino if you wanted But since there are no instruction...

Page 12: ...ill soon see that it isn t hard to understand at all But before we can see what the program does we have to upload it to the KosmoDuino Follow the instructions below to learn how to do this New Open Upload Save Status line Window for further explanations Verify If you did everything correctly the following messages should appear in sequence in the status line 1 Compiling sketch 2 Uploading 3 Uploa...

Page 13: ...his scope Copy error messages Did everything work Great If so you will now see a little green LED the onboard LED blinking on and off on the KosmoDuino Opening the sample programs All sample programs can be opened directly so you can bypass typing them in by hand You will find them in the Arduino environment in this menu File Examples KosmoBits EXPLANATION Now it s time to really understand the pr...

Page 14: ...ou keep a clear overview and it promotes order in the program Also you can pack frequently used sequences of instructions into a single function Instead of repeating the same text in the program code every time you can simply invoke the corresponding function Just as with the definition of a variable to define a function you have to start with an example In this case let s take void This is the so...

Page 15: ... can probably understand this one without any help Right the LED is switched off again Then the KosmoDuino waits another half a second delay 500 And then Then it starts all over again from the beginning loop is a special function in the Arduino programming It repeats endlessly All commands in loop are carried out over and over in an endless loop This is known as the main loop This makes loop the m...

Page 16: ... INPUT_PULLUP void loop switchValue digitalRead switchPin digitalWrite ledPin switchValue delay 50 THE PLAN Upload the sketch to your KosmoDuino as described on page 10 After uploading the LED will light up If you then bring the two free jumper wire contacts together and make them touch the LED will stop shining THE PROGRAM So what does the program do int ledPin 13 int switchPin 9 int switchValue ...

Page 17: ...Duino 2 male male jumper wires PREPARATION Connect one jumper wire to pin 9 and the other to one of the GND pins int ledPin 13 int switchPin 9 int switchValue HIGH void setup pinMode ledPin OUTPUT pinMode switchPin INPUT_PULLUP void loop switchValue digitalRead switchPin if switchValue LOW digitalWrite ledPin HIGH else digitalWrite ledPin LOW delay 50 THE PROGRAM Upload the sketch to your KosmoDui...

Page 18: ... are responding here is switchValue LOW You can understand that as a question Is the switch value equal to LOW You can evaluate the answer to that with the if instruction If the switchValue is equal to LOW if switchValue LOW the program code in the first pair of curly brackets is carried out digitalWrite ledPin HIGH The LED is switched on Otherwise else the part in the second pair of curly bracket...

Page 19: ...illustration NOTE To upload a program to the microcontroller you will insert the USB cable into the USB port on the KosmoDuino The USB terminal on the interaction board is only for charging the battery 1 2 Upload program Charge battery Two buttons button 1 and button 2 A multicolored LED NeoPixel A rotating wheel rotary encoder A speaker buzzer And most important A socket for connecting the KosmoB...

Page 20: ...of your NeoPixel you will need four number values one for the brightness and three for the primary colors red green and blue These values will be saved in the corresponding variables red green blue and brightness The various colors will be produced by mixing these three basic colors You will be setting the corresponding number value to determine how strongly each of the colors in this mixture will...

Page 21: ...l be linking with the include instruction will already be handling it for you In the main loop the first thing to do is set the brightness brightness 50 The highest level of brightness is set with a value of 255 with 0 the NeoPixel remains dark Then the various colors are produced one after the other To do that you will be assigning the red green and blue variables different values The line pixel ...

Page 22: ...NeoPixels To be able to use the tools that this kind of library can make available to you you have to include the corresponding library in your own program You do this with the help of the include instruction include KosmoBits_Pixel h includes the KosmoBits_Pixel library for example Some libraries however use functions from other libraries They have to be additionally included such as in the Kosmo...

Page 23: ...f you get really close or use a magnifying lens If you look carefully at the NeoPixel on the interaction board you will be able to see three different regions as long as it isn t shining Each region can only produce one single color red green or blue With the help of the setColor method you can tell the NeoPixel how brightly you want each of the different regions to shine Experiment with mixing to...

Page 24: ...oBits_Pixel object You are defining that here const int button1 KOSMOBITS_BUTTON_1_PIN const int button2 KOSMOBITS_BUTTON_2_PIN int red 0 int green 0 int blue 0 const int brightness 50 KosmoBits_Pixel pixel First we want the NeoPixel to stay dark If you press button 1 the NeoPixel will glow red while if you press button 2 it will glow blue If you press both at the same time it glows purple THE PRO...

Page 25: ...r 50 milliseconds void setup pinMode button1 INPUT pinMode button2 INPUT void loop if digitalRead button1 LOW red 255 else red 0 if digitalRead button2 LOW blue 255 else blue 0 pixel setColor red green blue brightness delay 50 WHAT ACTUALLY HAPPENS WHEN YOU UPLOAD SOMETHING When you upload a program to your KosmoDuino actually a whole lot of things happen The microcontroller does not really unders...

Page 26: ...lways easy to find error in an if statement is instead of the double equal sign to use a single equal sign For example instead of if a b the incorrect statement would be if a b In the case of this if statement the value of a is assigned the value b If that value is greater than zero true the block of text in the curly brackets is executed The parts of the program in the curly brackets will only be...

Page 27: ... block else if to check another condition if the first one is not fulfilled if instruction with else block if Condition 1 The following is only carried out if the condition is fulfilled Instruction 1 Instruction 2 else if Condition 2 This block is carried out if the condition is not fulfilled Instruction 3 Instruction 4 else This block is carried out if none of the previously checked conditions ar...

Page 28: ...self as a starting value Finally pixel setColor 0 0 255 brightness makes the NeoPixel glow blue void setup pinMode buttonPin INPUT randomSeed analogRead 12 Starting value for random generator pixel setColor 0 0 255 brightness Blue signals operational readiness void loop if digitalRead buttonPin LOW roll You start by including the familiar libraries and add a KosmoBits_Pixel to address the NeoPixel...

Page 29: ...dicated number of times If number has the value of 1 it will be 1 time If number has the value of 2 then 2 times and so on What s happening inside the curly brackets Exactly The NeoPixel lights up in green for the length of time indicated by blinkDuration and then switches off for the length of time indicated by blinkPause In brief The NeoPixel blinks green a single time But since the for loop is ...

Page 30: ... the transmission rate correctly At the bottom right in the serial monitor you will find a drop down list with a 115200 baud option Select that and you should see one Hello after another appear in the window A click on the magnifying glass at the upper right will launch the serial monitor If the wrong baud rate is set 9600 baud in this case you will only see a jumble of symbols Once the right tran...

Page 31: ... newly determined measurement readings You will learn about that in the project Thermometer on page 33 Unlike with Serial print you always get a new line with the Serial println output Hello Hello Hello Hello Hello Hello Hello Hello Hello Hello 115200 Baud Senden No line ending NOTE If you try to load a program to your KosmoDuino while the serial monitor is open you may sometimes get an error mess...

Page 32: ... loop body is carried out i is raised by 1 again and so on and so forth If i finally has the value of 19 the loop body is carried out one more time and i is then increased to the value of 20 The test condition is then no longer met and the loop is abandoned How often has the loop body now been carried out It has been carried out for the following values of the counter variable i 0 1 2 3 19 The num...

Page 33: ...opposite direction Outputs the numbers 42 41 40 1 for int i 42 i 1 i Serial println i The loop starts with the value of 42 It keeps running through as long as i has a value that is greater or equal to 1 The i means that i is reduced by 1 after each pass through the loop In other words it counts backwards Outputs the numbers 2 4 6 42 for int i 2 i 42 i i 2 Serial println i You can actually use any ...

Page 34: ... of electrical voltage The microcontroller can then read this voltage through one of the pins A lot of the pins can do a lot more than distinguish on from off They can also measures different voltage levels That s what is handled by the order analogRead which lets you determine the voltage at a pin The result is a numerical value from 0 to 1023 The higher the voltage arriving at a pin the greater ...

Page 35: ...readings Place your finger on the black dot sticking up out of the sensor housing You should see the measurement readings change It won t yet look like a temperature reading though You still have to convert the measurement readings into temperatures The KosmoBits library can help you with that It includes a function for that very task called thermistor_measurement_in_celsius To use this function y...

Page 36: ...orPin KOSMOBITS_SENSOR_PIN void setup pinMode sensorPin INPUT Serial begin 115200 Enable output via serial monitor void loop int measurement analogRead sensorPin float celsius thermistor_measurement_in_ celsius measurement Convert measurement into degrees Celsius Serial print celsius Celsius value is output Serial println degrees Celsius Output of Degrees Celsius and line break delay 1000 34 PROJE...

Page 37: ...ypical and symbols For multiplication use a star For division use a simple forward slash By the way you can also use the previous value of a variable to calculate something new with it There is even an abbreviation for the frequently used calculation step i i 1 CALCULATING IN THE PROGRAM Addition plus int x x is a whole number x 1 4 x has the value 5 Subtraction minus x 5 3 x has the value 2 Multi...

Page 38: ...ing the pixel in order to be able to control the NeoPixel To be able to recognize deviations from a resting state you still have to define the restingValue variable The resting average will be saved there include Adafruit_NeoPixel h include KosmoBits_Pins h include KosmoBits_Pixel h const int sensorPin KOSMOBITS_SENSOR_PIN KosmoBits_Pixel pixel int restingValue 0 In fact the sensor merely measures...

Page 39: ...e average from that the total must be divided by the number of readings That happens in the average average N line Finally return average returns the calculated average It s simple pinMode sensorPin INPUT sets the sensorPin as the input pin Finally the resting value is calculated and stored in the restingValue variable In the main loop a current sensor value is first read and saved in value Now it...

Page 40: ...ing to do void loop tone buzzerPin 440 delay 500 noTone buzzerPin delay 500 This time you won t have to do anything in setup The composition of the loop will probably look familiar to you It matches the Blink program which was the very first program that you uploaded to your KosmoDuino But this time instead of making an LED blink you will be making sounds These two commands will help tone buzzerPi...

Page 41: ...lay dauer ensures that the tone is played for the duration indicated by duration include KosmoBits_Pins h const int buzzerPin KOSMOBITS_BUZZER_PIN void setup randomSeed analogRead 12 void loop int freq random 110 1000 int duration random 10 150 tone buzzerPin freq delay duration SOUND When the air pushing against our ear drums vibrates back and forth we perceive it as sound The faster the air vibr...

Page 42: ...is output void setup Nothing to do here void loop tone buzzerPin freq 1 delay DELAY freq Short for freq freq 1 if freq FREQ_MAX freq FREQ_MIN This time you won t have to do anything in setup The main loop starts by outputting a sound with the frequency freq 1 After a pause of length DELAY the frequency freq is raised by 1 with freq The if instruction then checks whether the maximum frequency has b...

Page 43: ... with 0 rather than 1 INDEX 0 1 2 3 n VALUES Value 0 Value 1 Value 2 Value 3 Value n In general an array is created as follows type arrayName length You can also assign values to an array by specifying the individual values in curly brackets The type specifies which type of data can be saved in the array int float etc The number of values that can be stored in an array is known as its length int m...

Page 44: ...can now address the individual values via their index you can easily do this with a for loop values is an array of length 100 int sum 0 for int index 0 index 100 index sum sum values index With the first pass through the loop the value values 0 is added to sum Then index is raised by 1 and the next value is added This is repeated until the last value values 99 has been added In the next project yo...

Page 45: ...8 i tone buzzerPin scale i freqRoot delay 500 noTone buzzerPin void loop Nothing is done here This time everything is happening in setup In the for loop the variable i is counted up from 0 to 7 For each value of i then the i th note of the scale is output with tone buzzerPin scale i freqRoot As described above the frequency of the root chord freqRoot is multiplied by the corresponding frequency re...

Page 46: ...lating how far the controller has to be tipped in order to play the highest or the lowest note You can adjust these values to suit your own preferences later on You will be using the scaling constant later on to determine the pitch from a measurement reading dividing practically the entire measurement range into 9 portions The motion sensor is quite sensitive so the readings will fluctuate a littl...

Page 47: ...scale noteIndex freqRoot delay 10 else noTone buzzerPin delay 1 back to 0 The array is filled from the beginning again Then it s a matter of determining the average of the last 10 measurements To do that the average variable is first set to 0 In the for loop then all the values saved in the value array are added to average To calculate the average from that the result has to be divided by the numb...

Page 48: ...n A new window will open with some crazy looking things happening Now try to make various sounds such as whistling or singing You will see how the image changes in the serial plotter The scale along the left edge makes it easy to read the magnitude of the values delivered by the sensor In the example shown here you can see that 0 is the lowest value That should be obvious after all analogRead woul...

Page 49: ...witch If the value set there is exceeded by the measurement reading the switch toggles over either from on to off or vice versa In the on variable you will be storing the current state of the NeoPixel If it is on the variable is assigned the value true otherwise it is assigned the value false At the beginning of the program the NeoPixel is off bool on false THE PROGRAM In the main loop the sound s...

Page 50: ...losed again it will count as drawer was opened b If you push button 2 the NeoPixel will show you how often it was opened PREPARATION MEASURING SENSOR VALUES To know whether the drawer has been opened or not you will be using the light sensor It measures the brightness of the light that falls on it As long as your KosmoDuino is in the darkness the reading that it takes will be low If the drawer is ...

Page 51: ...fferent things happen in the main loop depending on the mode For that purpose we are using enum Mode to define a so called enumeration type a variable of the Mode type can only take the values written between the curly brackets IDLE COUNTDOWN etc Next we define the mode variable in which the current operating mode is stored We begin in IDLE mode The DARK_VALUE constant specifies the lowest light s...

Page 52: ...erent loop functions may be invoked The switch mode instruction handles that introducing a case differentiation For each case or possible mode value a different function is invoked If mode has the value IDLE loopIdle is invoked If mode has the value COUNTDOWN loopCountdown is invoked etc The break instruction is important here for breaking off the treatment of a case and ending the case differenti...

Page 53: ...Otherwise loopIdle is quit and the main loop is invoked again It in turn invokes loopIdle again since the mode hasn t changed IN IDLE When in its idle state the drawer monitor is waiting for button 1 to be pushed before it starts monitoring What s responsible for that is the loopIdle function which is invoked by the main loop in IDLE mode COUNTDOWN Here too you will be familiar with most of the co...

Page 54: ...an intruder Maybe after all you opened it yourself That task is handled by loopOpen This function is invoked from the main loop whenever mode has the value OPEN We start by checking button 2 If it is pressed the monitoring result is output by invoking the output function If button 2 is not pressed the brightness is checked in the else if part If it is now dark the drawer was closed again counter i...

Page 55: ...it would normally be inserted In other words the wires must not be allowed to cross THE PLAN You will be using the light sensor to measure the brightness inside the fridge and you will have the NeoPixel light up on the interaction board in accordance with the measured level of brightness But how can you have a display outside the fridge for the brightness on the inside Easy You will use extension ...

Page 56: ... without any help In brief In setup you set the sensor pin mode and switch off the NeoPixel In the main loop you use the light sensor to measure the brightness and store the reading in the brightness variable Since the brightness value must not be greater than 255 with pixel setColor limit the brightness value to 255 with the help of the if instruction Now you just need to place the sensor in the ...

Page 57: ...gs One jumper wire connects one GND pin with the strip of the breadboard One jumper wire connects pin 11 of the KosmoDuino with hole j 57 of the breadboard One jumper wire connects pin 6 of the KosmoDuino with hole j 51 of the breadboard The resistors connect the strip and hole a 57 along with the strip and hole a 51 The long leg of the red LED is inserted in hole f 57 the short one in e 57 Place ...

Page 58: ...sible value If the random number is greater than 900 write 3000 random values into the buzzerPin with analogWrite buzzerPin random 0 256 in the adjacent for loop That will produce the hissing sound in the speaker The random numbers to be produced with the help of the random function are evenly distributed That means that every possible number will occur just as often as any other over a long perio...

Page 59: ...d build on it The CodeGamer kit and the KosmoBits system give you a good start because in addition to the actual microcontroller you already have a breadboard some LEDs jumper wires and of course sensors With the help of the battery you will even be able to operate the entire setup independently of a computer and without any extra parts The battery has a pretty high capacity You will notice that b...

Page 60: ...ad All these versions mean the same thing it s just the formatting that changes And yet in the first example you can see the structure of the program at a glance It is easier to read the code That is why it makes sense to indent the program code whenever it begins a new block Also as a rule each individual instruction should get its own line The Arduino environment will help you with this and usua...

Page 61: ...ly consists of an electromagnet and a magnetically activated switch If the electromagnet is turned on it activates the switch If the magnet is turned on again it moves the switch back to the off setting The important thing is that this kind of relay involves the actual movement of something namely the switch On September 9 1947 the technicians responsible for the Mark II were looking for the sourc...

Page 62: ...cities around the world These are like a cross between a meeting place and a community workshop They are places where the makers can compare notes present their latest ideas give each other advice and have access to shared parts and tools There are also more and more Maker Faires popping up around the world which allow makers to present themselves to a larger public They also typically offer an ar...

Page 63: ...then heated to the melting point in a nozzle In molten form the plastic is computer guided to a certain location and then squirted out The plastic then cools and hardens Drop by drop layer by layer even complicated and intricate structures can be built in this way Devices capable of doing this kind of thing have existed for a while but it is only in the last few years that they have become afforda...

Page 64: ...ared in this scope error does not name a type EXAMPLE EXAMPLE EXAMPLE In function int average2 DoubleClap 86 error expected before token for int i 0 i N i exit status 1 expected before token error pinnMode was not declared in this scope pinnMode A1 INPUT error KosmoBits_Pixel does not name a type KosmoBits_Pixel pixel include Adafruit_NeoPixel h include KosmoBits_Pixel h SOLUTION SOLUTION SOLUTION...

Page 65: ... t open device COM4 The system cannot find the file specified Low memory available stability problems may occur EXAMPLE int array 1000 That is too large SOLUTION SOLUTION SOLUTION SOLUTION Change your program by using a smaller array Close the serial monitor and re upload the program Use the USB cable to connect your computer to the KosmoDuino via the USB port Select a different port Your program ...

Page 66: ...64 NOTES CodeGamer manual inside english indd 64 7 19 16 12 33 PM ...

Reviews: