Tag Archives: video

Controlling an LED light using a mobile app and Bluetooth

This tutorial will show you how to control an LED light on an Arduino using a mobile app and a Bluetooth wireless connection.

Parts required

Here is what you’ll need:

  • An Android phone or iPhone
  • A free mobile app
  • Arduino Uno board
  • Breadboard
  • 220 Ohm resistor
  • 6 male-to-male jumper wires
  • HM-10 BLE Bluetooth 4.0 module (see bottom of page for exact model used in this tutorial)
  • An LED light
  • Arduino IDE software

Wiring it up

Wire up the project using jumper wires by following these instructions or checking out the circuit diagram and images below.

  1. Connect VCC on Bluetooth module to 3.3V on Arduino
  2. Connect GND on Bluetooth module to GND on Arduino
  3. Connect TXD on Bluetooth module to digital pin 7 on Arduino
  4. Connect RXD on Bluetooth module to digital pin 8 on Arduino
  5. Connect the long pin from the LED on the breadboard to digital pin 2 on Arduino
  6. Connect the short pin from the LED on the breadboard to a 220 Ohm resistor and from there to GND on the Arduino

Note: The STATE and EN pins on the Bluetooth module do not need to be connected to anything in this project.

Bluetooth

Here are some images showing the LED turned on and everything wired up.

IMG_1905

IMG_6092

IMG_5111

Arduino code

Create a new sketch in the Arduino IDE and add the following code. Then upload the sketch to your Arduino board.

#include <SoftwareSerial.h>
int led = 2;

SoftwareSerial Bluetooth(7, 8);

void setup() {  
  Serial.begin(9600);
  Bluetooth.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {  
  int command;
  
  if (Bluetooth.available()) {
    command = Bluetooth.read();  
    Serial.println("Input received:");
    if (command != 0)
    {
      // A non-zero input will turn on the LED
      Serial.println("0 / ON");
      digitalWrite(led, HIGH);
    }
    else
    {
      // A zero value input will turn off the LED
      Serial.println("1 / OFF");
      digitalWrite(led, LOW);
    }  
  }
}

Controlling the Arduino via Bluetooth

To connect your Android or iOS mobile device to the Arduino you will need to download a free app (or you could also make your own app) that can connect to the HM-10 Bluetooth module and send commands. You can search your device’s app store to find a free app that will work for this project but for this example we will use the free Bluetooth Terminal app on iOS.

Tip: If you search the iOS App Store or Google Play app store using the keywords “bluetooth arduino” or “bluetooth hm-10” you should be able to find a suitable app.

The steps below are for the Bluetooth Terminal app on iOS but will be similar for other apps on other devices:

  1. Open the app and connect to the Bluetooth module (in this case it is called CC41-A but the name will vary depending on the model you have).
    IMG_4901
  2. Tap ‘Select characteristic’ and then select FFE1 (at the bottom of the list).
    IMG_4902
  3. Select Decimal.
  4. Using the on-screen keypad, you can enter different decimal values. Enter 1 and tap the Send button. The LED light should turn on. Enter 0 and tap the Send button. The LED should then turn off. If you don’t see anything happen, click Tools > Serial Monitor in the Arduino IDE and then set the baud date to 9600 bauds. Check if any input is being received and displayed in the serial monitor when you send the 0 or 1 commands to the Arduino from the app.
    IMG_4903

Where to from here?

You can use Bluetooth to control other projects such as a robot or car. You can also try receiving data from the Arduino – eg. send sensor readings to your phone.

Which Bluetooth module should I use?

There are several different Bluetooth modules that should work with this tutorial. The one used in this project was purchased on eBay and is called “HM-10 CC2540 CC2541 BLE Bluetooth 4.0 Wireless Module“.

Methods in C#

A method, also known as a function, is a module of code that a programmer can create and then call on later on in the program. Many methods already exist in programming languages such as C# but the programmer also has the ability to make their own. A method will usually perform a single task. Many methods can work together to achieve a goal.

Methods should have descriptive names (they should represent an action and are usually in the form of a verb). Spaces cannot be used in method names and you should always avoid use of special characters eg. $%^!@. The method name itself should also not contain brackets because brackets are used for parameters. When you create a new method, the method name should be unique and not already exist in the language (it should not be a reserved word that is used for a statement or method).

Method names should follow a consistent naming convention throughout your code eg. using camel case or mixed case. Examples of suitable method names include CalculateScore, AddNumbers, MultiplyNumbers, GetUserDetails, etc.

Watch the video below and then scroll down for examples and sample code.

Creating methods

Lets break up the method into its different components and look at each component…

What is an access modifier?

Access modifiers include public and private (or just left empty). Public means other parts of the program can see and use this method. If we don’t want that we use private instead or no access modifier (leave it out).

What is a return type?

Methods are able to return a variable back to the code that called it known as the return type. If a method returns an integer value then the return type is an int and if a method returns a true or false value then the return type is a bool. Even if the method doesn’t return any value, it still has a return type. If the method doesn’t return a value, then its return type is void (which means nothing). You might notice that many functions have a return type of void.

What are parameters?

In the same way that methods can pass a variable back to the code that called it, the calling code can pass variables into the method. These variables are known as parameters. The variables that are passed into the method are identified in the parameter list part of the method (inside the brackets). When you specify a parameter you must specify the variable type and the name. If there are no parameters, then the brackets are left empty.

Below is an example of a method in C# for a calculator that is used to add two numbers together. There are two parameters in this method (separated by commas). The parameters in this method are num1 and num2. These are the two numbers that will be added together (they are of the float data type). Notice that the return type is also float meaning that the result of this method (the sum of num1 and num2) will be returned as a float value.

public static float AddNumbers(float num1, float num2)
 {
   float total = num1 + num2;
   return total;
 }

The method above will add two numbers together (the two parameters num1 and num2) and then return the answer as a float back to the part of the program that called the method.

The word static means that this particular method is associated with the class, not a specific instance (object) of that class. What this means is that you are able to call a static method without actually creating an object of the class.

Many methods have the word void in their declaration. The word void basically means that the method will not return any value to the part of the program that called it.

Using methods

Once you have created a method the next thing to do is use it. Using a method is known as calling or invoking a method. To call a method that was named AddNumbers, you would write:

AddNumbers();

If the method contained a parameter or multiple parameters (eg. the values 5 and 10), then they would be included inside the brackets like this:

AddNumbers(5,10);

The below example shows how to call a method and pass variables into the method. You do not need to write int inside the brackets where the function is called.

int number1 = 10;
int number2 = 30
AddNumbers(number1,number2);

When you call a method you do not need to provide the variable type with the variable that is being passed into the method. If the method AddNumbers() in the example code above returns a value, then it should be stored in a variable or used in a statement, for example:

int result = AddNumbers(5,10);

Sample code

Here is an example using parameters and a return type of void. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      AddNumbers(5, 10);
    }
    public static void AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      Console.WriteLine("The sum of the two numbers is " + total);
    }
  }
}

Here is an example using parameters and a return type of int. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers(5, 10);
      Console.WriteLine(answer);
    }
    public static int AddNumbers(int num1, int num2)
    {
      int total = num1 + num2;
      return total;
    }
  }
}

Here is an example using no parameters. The AddNumbers method is called from inside the Main method.

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int answer = AddNumbers();
      Console.WriteLine(answer);
    }
    public static int AddNumbers()
    {
      int total = 5 + 10;
      return total;
    }
  }
}

Foreach loops in C#

This tutorial explains how to use the foreach loop to go through each element in an array. A foreach loop is simpler and easier to use than a for loop if you want to loop through each and every element in an array. There is no need to use a counter, specify an increment, or a condition. The foreach loop will simply loop through every element in the array.

Foreach loops are written in a way that is easy to understand, for example:

foreach (string item in itemsList){
   Console.WriteLine(item);
}

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};

      // Store length of names array in variable
      int arrayLength = names.Length;

      // Go through each name in names array and display on new line
      foreach (string name in names) {
        Console.WriteLine(name);
      }
      // Wait for user input before quitting program
      Console.ReadLine();
    }
  }
}

Next tutorial: Methods

Arrays in C#

Arrays are basically a list of items of the same type that are grouped together in a single container. Unlike variables which can only contain one value at a time, arrays can contain many different values of the same type (eg. string, or integer). This tutorial explains how to create arrays, access elements in an array, and use for loops to work through the elements in arrays.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      // Create an array of string type
      string[] names = {"Jim","Kate","Sam","Sally"};
      // Create an array of int type
      int[] ages = {26,18,49,33};
      // Display second item in names array (array indexing starts at 0)
      Console.WriteLine(names[1]);
      // Display fourth item in ages array
      Console.WriteLine(ages[3]);
      // Store the names array's length (number of elements in array) in variable
      int arrayLength = names.Length;
      // Display names array's length
      Console.WriteLine(arrayLength);
      // Go through each element in names array and check if Sam exists in array
      for (int i = 0; i < arrayLength; i++) {
        if (names[i] == "Sam") {
          Console.WriteLine("Sam is here!");
        }
      }
    }
  }
}

Next tutorial: Foreach loops in C#

Do while loops in C#

A do while loop is a type of loop which repeats code while a certain condition evaluates to true. However, unlike a while loop which tests the condition first, a do while loop tests the condition after running instructions inside the loop. This means that the code inside the loop will always run at least once even if the condition evaluates to false. This is an example of post-test repetition.

Watch the video below and then scroll down to see the sample code.

Sample code

Take a look at the sample code below. The counter is set to 99 and the condition being tested is counter < 10. However, the code inside the loop runs the first time even though the condition evaluates to false because a do while loop runs the code inside the loop before testing the condition (meaning that the instructions inside the loop will always run at least once).

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int counter = 99;
      do
      {
        Console.WriteLine("Counter is: " + counter);
        counter++;
      } while(counter < 10);
      Console.ReadLine();
    }
  }

}

Next tutorial: Arrays in C#

For loops in C#

In this tutorial you will learn how to use the for loop to repeat sections of code in the C# language. For loops are useful for when you want to repeat code a certain number of times. They are also very useful for efficiently working through all the elements in an array or going through each character in a string. For loops have a built in counter, condition, and increment. Watch the video below and then scroll down for the sample code.

Sample code

Example 1 – using for loop as simple simple counted loop

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      for (int i = 0; i < 10; i++)
      {
        Console.WriteLine("Counter is: " + i);
      }
      Console.ReadLine();
    }
  }

}

Example 2 – using for loop to go through each character in string

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      string word = "dog";
      for (int i = 0; i < word.Length; i++)
      {
        if (word[i] == 'a')
        {
          Console.WriteLine("This word contains the letter a");
        }
      }
      Console.ReadLine();
    }
  }

}

Next tutorial: Do while loops in C#

Switch statements in C#

This tutorial explains how to write switch statements in C# language. Switch statements are used to select one from many different blocks of code. A switch statement can take a variable and check if its value matches one of many different specified values. Once the switch statement finds a matching case, it will run the code inside that case and the stop testing all the other cases.

Watch the video below and then scroll down to the sample code to see how switch statements work.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int myNumber = 5;
      switch (myNumber) {
        case 1:
          Console.WriteLine("The number is 1");
          break;
        case 2:
          Console.WriteLine("The number is 2");
          break;
        case 3:
          Console.WriteLine("The number is 3");
          break;
        default:
          Console.WriteLine("I don't know this number");
          break;
      }
    }
  }
}

Next tutorial: While loops in C#

Adding a UI to display the score in a 2D game with Unity

This tutorial continues on from the previous tutorial on adding collectables and scoring to a 2D Unity game. In the previous tutorial, we improved the points scoring system and added collectables (coins) of different values).

In this tutorial we will add a UI (user interface) which will display the number of coins collected to the user. The LevelManager script will be responsible for displaying and updating the score text on screen. Watch the video below and then scroll down for the sample code.

Sample code

Here is the sample C# code for the LevelManager script.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class LevelManager : MonoBehaviour {
  public float respawnDelay;
  public PlayerController gamePlayer;
  public int coins;
  public Text coinText;

  // Use this for initialization
  void Start () {
    gamePlayer = FindObjectOfType<PlayerController> ();
    coinText.text = "Coins: " + coins;
  }
  
  // Update is called once per frame
  void Update () {
  
  }

  public void Respawn(){
    StartCoroutine ("RespawnCoroutine");
  }

  public IEnumerator RespawnCoroutine(){
    gamePlayer.gameObject.SetActive (false);
    yield return new WaitForSeconds (respawnDelay);
    gamePlayer.transform.position = gamePlayer.respawnPoint;
    gamePlayer.gameObject.SetActive (true);
  }

  public void AddCoins(int numberOfCoins){
    coins += numberOfCoins;
    coinText.text = "Coins: " + coins;
  }
}

Physics2D materials and more 2D colliders in Unity

This video explains how to use Physics2D materials in Unity to add properties such as bounciness or friction to objects in your 2D game scene. We will also look at more 2D colliders in Unity including the box collider and polygon collider.

Next tutorial: More Physics2D materials

Adding physics and colliders to your 2D game in Unity

This video explains how to add physics and colliders to objects in a 2D game using Unity. In this tutorial, we will look at how to add the RigidBody2D component to an object in the game scene, as well as edge and circle colliders.

Next tutorial: Physics2D Materials and more 2D colliders

Introduction to 2D Game Design in Unity

Welcome to the 2D Game Design in Unity tutorial series. This first video in the series explains how to download the Unity software and set up your first 2D game project. You can download the Unity software from here and get started for free. This tutorial includes a step-by-step video (scroll down to watch).

After downloading and installing the Unity software on Mac or Windows, you can open Unity and create a new project.

Screen Shot 2017-04-14 at 2.15.48 pm

When you create a new project you will see something like the screen shown below. The main parts of the screen are the Hierarchy (which lists all the objects in the current game scene), the Scene window (where you can design the game world and place objects in your game), the Inspector panel (where you can edit the properties of objects in the current scene), and the Project panel (where you can add assets to use in your game project).

Screen Shot 2017-04-14 at 2.16.11 pm

Watch the video below for instructions on how to download and install Unity and begin creating your first 2D game project in Unity.

Next tutorial: Adding assets to your 2D game

Create a looping walk cycle animation in Adobe Flash / Animate

This tutorial explains how to create a looping walk cycle animation in Adobe Flash (Adobe Animate) like the one shown below.

WalkCycle

You can use the same technique for other types of internal animated loops. Watch the video below to find out how to do this using either the Adobe Flash or Adobe Animate software.

In this video I used the sprite sheet by soldiern at http://soldiern.deviantart.com/art/Sub-Zero-Sprite-Sheet-V2-210769129 (using Creative Commons CC3.0 license – https://creativecommons.org/licenses/by-sa/3.0/ ).

Creating your first iOS app

This tutorial will show you how to create a Temperature Converter app for iOS devices using Xamarin. We made the same app for Android in a previous tutorial and now we are going to make it for iOS devices. The app will look like this…

iosapp

Although we will be using Xamarin for designing and coding the app, you will still need to have XCode installed on your Mac device (click here for detailed installation instructions).

Watch the video below or scroll down to view the step-by-step instructions and sample code.

Video

Step 1

To get started, open Xamarin and begin a New Solution.

ios1

Step 2

Select App under iOS and then select Single View App (C#). Click on Next to continue.

ios2

Step 3 

Give your app a name. In this case, it will be called TempConverter. You also need to select a minimum iOS version you want to support. In this case, the target version is iOS 9.1. Make sure the target version is either an older or same version of iOS that you will be using to run the app on. Click Next to continue.

ios3

Step 4

Now just confirm the project and solution name (making sure it is not the same name as a solution that already exists in your projects folder) as well as the project folder location and click Create.

ios4

Step 5

Once the new solution has loaded, Xamarin will automatically open a file called AppDelegate.cs. Don’t worry about this file for now as we won’t really be changing anything there. The two files that we will be working with are the Main.storyboard file (for adding the buttons, text labels, and text boxes) and ViewController.cs (for coding the functionality).

ios5

Double-click the Main.storyboard file to open it. It may take a minute to load. The storyboard is where you will add your user interface elements such as buttons, text boxes and text labels. Choose the iPhone device that you want to use as the preview for your storyboard eg. iPhone 6.

ios6

Step 6

In the Toolbox panel (use the search box to find and add the Toolbox to your layout if you don’t see it there), scroll down until you see Label (you can also search in the Toolbox for the Label element.

Drag a Label element on to the phone screen where you would like to place it.

ios7

Step 7

Change the Text value in the Properties panel (on the Widgets tab) to ‘Enter temperature in degrees:’.

ios8

Step 8

Drag the edges of the Label element to resize it so that you can see all of the text.

ios9

You can also change the colour of the text, the font and alignment (eg. align to center) from the Properties panel.

ios10

Step 9

Drag a Text Field element from the Toolbox on to the screen under the text label. Change its Placeholder text to ‘Temperature in degrees’. Resize the Text Field and center-align the text.

ios11

Step 10

Drag two Button elements on to the screen and resize them to fit their text. Change the first button’s text to ‘Convert to Celsius’ and the second button’s text to ‘Convert to Fahrenheit’.

ios12

Step 11

The last element to add is the text label which will display the result of the temperature conversion. Drag a Label element on to the screen and change its default Text to 0, change its Colour and Font size/style. You can also change the Alignment to center.

ios13

Step 12

Now we need to name each of the screen elements so that they can be accessed by the code. Firstly, click on the temperature text field and change its Name to tempTextField.

ios14

Step 13

Now give the ‘Convert to Celsius’ button the Name cButton.

ios15

Also set the Name of the ‘Convert to Fahrenheit’ button to fButton.

ios16

Step 14

Lastly, click on the text label which will display the conversion result and change its Name to resultLabel. Now is a good time to save the Main.storyboard file (Click File > Save).

ios17

Step 15

Now its time to do some coding. Open the ViewController.cs file. In this file, click inside the ViewDidLoad method and add the code highlighted below. This code will add a button touch event that will occur when the user touches to Convert to Celsius button. When we create the cButton.TouchUpInside event it will also automatically create a new method CButton_TouchUpInside which will contain the code that will convert a temperature to Celsius.

ios18

Step 16

We now need to also create a button touch event for the Convert to Fahrenheit button and a method that will contain its code.

ios19

Step 17

Now let’s add the code for the FButton_TouchUpInside method first. This method will be called when the Convert to Fahrenheit button is pressed by the user. Add the highlighted code below. Firstly, a float variable called temp is created to store the temperature value that the user enters into the text field as a float value. Then a variable called fResult will convert the temperature from Celsius to Fahrenheit and store the result as a float value. Lastly, the text on the resultLabel element will display the result and the text ‘degrees Fahrenheit’ at the end of the sentence eg. ’68 degrees Fahrenheit’.

ios20

Note: You may need to resize the fResult label element in the Main.storyboard file so that it can fit the result and text.

Step 18

We can now add the code for the Convert to CButton_TouchUpInside method to run the conversion when the Convert to Celsius button is pressed. Add the highlighted code to this method shown below. Then save your code (File > Save).

ios21

Step 19

Now go back to the Main.storyboard file and select the Text Field element. In the Properties panel and on the Widget tab, scroll down and change the Keyboard Type to Decimal Pad so that numbers with decimal place can be typed in and the most suitable keypad is displayed. Save the file.

ios22

Step 20

At this point, the app will work and will allow the user to type in a temperature (as a whole or decimal number) and convert it to either Celsius or Fahrenheit. However, after the user has typed in a number they should be able to hid the keyboard if it is no longer needed.

Before testing the app we will add a little piece of code that will allow the keypad to be dismissed by the user when it is no longer needed. To do this, go back to the ViewController.cs file and start typing the highlighted line of code (where it is shown below). As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code. This will create a new override method called TouchesBegan. Inside this method we will add some code to dismiss the keyboard.

ios23
As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code.

Add the following code inside the new override method called TouchesBegan to allow the keyboard to be dismissed when typing has been completed by the user. Then save the file.

ios24

Finishing up

All of the coding is done. Congratulations – you have made your first iOS app using Xamarin and the C# programming language! Remember to save your files.Now just select a type of iPhone model you would like to test this app on and click on the Build button to start testing/emulating the app.

ios25

And this is what the completed app should look like…

ios26

What next?

Test your app thoroughly. Are there any problems with your app? Does it crash under some circumstances? Is there any way it could be improved. Jump into the next tutorial to see how this app can be improved.

Sample code

You can download the sample code for the ViewController.cs file here:

using System;

using UIKit;

namespace TempConverter
{
  public partial class ViewController : UIViewController
  {
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.e

      cButton.TouchUpInside+= CButton_TouchUpInside;

      fButton.TouchUpInside+= FButton_TouchUpInside;

    }

    void FButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse(tempTextField.Text);
      float fResult = temp * 1.8f + 32f;
      resultLabel.Text = fResult.ToString () + " degrees Fahrenheit";
    }

    void CButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse (tempTextField.Text);
      float cResult = (temp - 32f) / 1.8f;
      resultLabel.Text = cResult.ToString () + " degrees Celsius";
    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
      
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt)
    {
      base.TouchesBegan (touches, evt);

      this.View.EndEditing (true);
    }
  }
}

Publishing your Android app

This tutorial explains how to publish your app and create an .APK file that can be installed on an Android phone. For this tutorial, we will be using the CookieClicker app. You might also want to change the app icon and details before publishing your app.

Watch the video below or scroll down to read the step-by-step instructions.

Video

Step 1

To get started, open the solution that you wish to publish in Xamarin. You will need to create an Android Signing Key before you can publish your app. To do this, click on the Xamarin Studio Community menu and select Preferences (this might be on the File menu in Windows).

p1

Step 2

In the Preferences dialog, click on Android Signing Keys (under Publishing) and click on Create New Key.

p2

Step 3

Give your new signing certificate an alias (name) and create a password (at least 6 characters long). Then select the validity length (how many years the certificate will be valid for) and fill in at least of the text boxes with something (eg. just provide your name or your city name). Click on OK to continue.

p3a

You should then see your new signing key/certificate in the list of Android Signing Keys. Click on OK to exit the Preferences dialog.

p3b

Step 4

Select the Project menu and change your Active Configuration to Release. This will allow you to publish your app (you can change this back to Debug after you have published your app so you can return back to coding and testing your apps).

p4

Step 5

Select the Build menu and then click Archive for Publishing.

p5

Step 6

Now click on Sign and Distribute.

p6

Then select Ad-Hoc to save the app file (the .apk file) to your computer. Click on Next.

p7

Step 7

Select your signing key from the list and click Next.

p8

Then confirm you are happy with the app details and file size and click Publish.

p9

Step 8

Lastly, choose where to save your .apk file and click on Save. You can now share this file online or copy it to your phone (either by USB cable or email). You can also upload it to the Google Play store for other people to download.

p10

Step 9

After you have published your app, remember to change the project’s active configuration back to Debug by clicking on the Project menu > Active Configuration > Debug.

Important note

If you decide to upload your app to the Google Play store you must make sure that you do not violate any copyright laws (eg. check that you are not using other people’s images or sound files and that you app is not the same as an existing app). Also, make sure you have your parents’ permission before uploading any apps to the Google Play store.

Making a Cookie Clicker game for Android

For our second Android app project, we will create the most pointless but addictive game in the world…a cookie clicker! A basic version of it will look like the image shown below, but you can extend this game as much as you like. You will also learn how to add image buttons to your app screens.

cc1

Watch the video below or scroll down to read the step-by-step instructions and view the sample code.

Video

Step 1

You will need to create a new Android App solution in Xamarin called CookieClicker. Click on New Solution (or File > New Solution) to get started.

cc2

Step 2

Choose Android App as the type of new solution and then click Next.

cc3

Step 3

Set the App Name to CookieClicker (one word – no spaced). Choose Modern Development as the Targeted Platform using the default theme and click on Next.

cc4

Step 4

Keep the project and solution names as CookieClicker, select a project location to store your files in and click on Create.

cc5

Step 5

Open the MainActivity.cs file (if it does not automatically open) and delete the lines of code highlighted below. These lines of code won’t be needed for this project.

cc6
Click to see larger version of this image.

Step 6

Now open the Main.axml file located in the Resources > layout folder.

cc7

Step 7

Click on the button that says “Hello World, Click Me!”. We won’t need this button so it can be deleted. Either click on it and press the Delete key on your keyboard, or right-click the button and select Delete.

cc8

Step 8

From the Toolbox (if you don’t see it, you can search for the Toolbox from the search bar), scroll down under Images & Media and drag an ImageButton element on to the phone screen.

cc9

Step 9

Now you will need to download a cookie image to your computer (preferably a PNG image file with a transparent background). A free public-domain image has been provided below. Click on the image to open the full-size version and then save the image to a folder on your computer and name it cookie.png.

Click to open the full-size image. Image from: https://pixabay.com/en/chocolate-chip-cookies-dessert-304801/ (CC0 Public Domain - free for commercial use, no attribution required)
Click to open the full-size image. Image from: https://pixabay.com/en/chocolate-chip-cookies-dessert-304801/ (CC0 Public Domain – free for commercial use, no attribution required)

Step 10

Select the ‘drawable’ folder inside the Resources folder and click on the small cog icon. Then select Add > Add Files from Folder.

cc10

Step 11

Select the folder that contains the cookie image file and click on Open.

cc11

Step 12

Select the cookie.png file (or whatever yours is called) and make sure the checkbox is checked. Then click on OK.

cc12

Step 13

Make sure you select Copy the file to the directory and then click on OK.

cc13

Step 14

Now you should see cookie.png in the drawable folder.

cc14

Step 15

Click on the ImageButton element on the phone screen and change the Src property to @drawable/cookie (you do not need to include the .png file extension).

cc15

Step 16

Now we need to make sure the image fits properly on the screen. Click on the drop-down arrow next to the Scale Type property and change it to fitCenter.

cc16a

You can then also click on the ImageButton and drag the little circle up to change the height of the image. You can also change the width of the image this way. Alternatively, go to the Layout tab on the Properties panel and change the width and height values there eg. 435dp for the height. Note: sizes of elements are measured using the ‘dp’ unit on Android.

cc16b

cc16c

If you go to the Source tab, your code for the Main.axml file might look like the code shown below. However, your code could be a little different so don’t change the code here unless you are sure you know what you are doing.

cc16d

Step 17

In the Designer view, drag a Text (Large) element on to the phone screen under the ImageButton. This will be used to display the number of clicks.cc17

Step 18

From the Widget tab on the Properties panel, change the Text value from Large Text to 0 clicks. At the same time, change its Id from @+id/textView1 to @+id/cookieTextView . You can also change the Gravity value to center so the text is centered.

cc18

Step 19

Click on the ImageButton element (the cookie) and change its Id from @+id/imageButton1 to @+id/cookieImageButton – now you need to save the Main.axml file.

cc19

Step 20

Now we can add the code! Open the MainActivity.cs file and create an integer variables called clicks that is given an initial integer value of 0. This variable will be created inside the MainActivity class, as highlighted below.

cc20

Step 21

We also need to define the ImageButton element and the TextView element in the code. This is highlighted in the lines below. Make sure to use the correct names for each element.

cc21

Step 22

Inside the OnCreate method (under the SetContentView (Resource.Layout.Main); line), we need to now setup the ImageButton and TextView element.

cc22

Step 23

The next thing you need to do is create a click event for the cookie ImageButton by adding the line cookieImageButton.Click+= CookieImageButton_Click; – this will create a new method called CookieImageButton_Click which will contain the code that will increase the number of clicks and display the number of clicks each time the ImageButton is tapped.

cc23

Step 24 

Inside the CookieImageButton_Click method, add the following two highlighted lines of code. The clicks++; line will increase the clicks variable by 1 each time the button is tapped, and the next line of code is responsible for converting the clicks variable value to a string and displaying the clicks variable’s value on the screen as well as the text “clicks!” at the end eg. 25 clicks!

cc24a

Now save your work. All of the coding is done! Now you could extend this app by adding extra buttons to purchase items when a certain number of cookies are clicked (using if statements) or increase the number of cookies by a different amount. You could add extra text labels or buttons too. However, let’s test that this app works properly first. Click on the Build button after selecting a virtual device to run the app on (if you don’t know how to do this, refer to the previous tutorial – Creating your first Android app with Xamarin).

cc25a

cc25b

Here is the source code for the MainActivity.cs file:

using Android.App;
using Android.Widget;
using Android.OS;

namespace CookieClicker
{
  [Activity (Label = "CookieClicker", MainLauncher = true, Icon = "@midmap-hdpi/icon")]
  public class MainActivity : Activity
  {
    int clicks = 0;

    ImageButton cookieImageButton;
    TextView cookieTextView;

    protected override void OnCreate (Bundle savedInstanceState)
    {
      base.OnCreate (savedInstanceState);

      // Set our view from the "main" layout resource
      SetContentView (Resource.Layout.Main);

      cookieImageButton = FindViewById<ImageButton> (CookieClicker.Resource.Id.cookieImageButton);
      cookieTextView = FindViewById<TextView> (CookieClicker.Resource.Id.cookieTextView);

      cookieImageButton.Click+= CookieImageButton_Click;

    }

    void CookieImageButton_Click (object sender, System.EventArgs e)
    {
      clicks++;
      cookieTextView.Text = clicks.ToString () + " clicks!";
    }
  }
}