This is part 4 of my tutorial on designing an Android Phone Bluetooth App using the Android/Processing language. The App sends information to an Arduino via Bluetooth after pressing a button on the phone. The RGB LED attached to the Arduino Uno (or compatible board) will change colour depending on the button being pressed on the phone. The Arduino gains Bluetooth capabilities through the Seeedstudio Bluetooth shield (which can be found here).
Parts 1-3 of the tutorial were designed to take you step-by-step through designing the app. If you are wondering what you missed, here is a summary:
In Part 4, we simplify and strip down the App so that it will only sends a specific String to the Arduino via Bluetooth. The String sent to the Arduino depends on the Button being pressed. The code has been cleaned up and has many comments to help you understand what is going on. You should be able to run this sketch without having to go back through parts one, two or three of the tutorial. This fourth part of the tutorial was designed for those people who want the final end product, and are happy to work it out for themselves. I hope this serves you well. I will therefore assume that you have already setup your phone and have downloaded all the neccesary drivers, libraries, SDKs and IDEs. If not, then here are a few quick links:
If you are a bit lost and want want a bit more information then please go through parts one, two and three of this tutorial. Make sure that you have selected the Bluetooth permissions as per the following:
Android > Sketch permissions (as per the picture below)
Make sure that BLUETOOTH and BLUETOOTH_ADMIN are selected (as per the picture below). Then press the OK button.
Then copy and paste the following sketch into the processing/android IDE:
/* BluetoothApp2: Written by ScottC on 1st April 2013 using Processing version 2.0b8 Tested on a Samsung Galaxy SII, with Android version 2.3.4 Android ADK - API 10 SDK platform Apwidgets version: r44 : http://code.google.com/p/apwidgets/ */
/*------------------------------------------------------------------------------ IMPORT statements required for this sketch -----------------------------------------------------------------------------*/ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter;
/*------------------------------------------------------------------------------ GLOBAL Variables to be used between a number of classes. -----------------------------------------------------------------------------*/ publicint[] bg={0,80,0}; public BluetoothDevice btShield = null; public BluetoothSocket btSocket = null; public OutputStream btOutputStream = null; public APWidgetContainer widgetContainer=null; public Connect2BtDevice ConBTdevice=new Connect2BtDevice();
/*------------------------------------------------------------------------------ The following variables are used to setup the Buttons used in the GUI of the phone. It includes the variables that determine the - text on the buttons - the number of buttons - the letters that will be sent to Arduino when the buttons are pressed - the colour that the background will change to when the buttons are pressed - the dimensions of the buttons (width and height) - The gap between each button -----------------------------------------------------------------------------*/ String[] buttonText = { "RED", "GREEN", "BLUE", "OFF"}; //Button Labels String[] sendLetter={"r","g","b","x"}; //Letters to send when button pressed int n= buttonText.length; //Number of buttons int[][] buttonColour = { {255,10,10}, {10,255,10}, {10,10,255}, {0,0,0} }; //The Background colour on phone when button pressed
APButton[] guiBtns = new APButton[n]; //Array of buttons int gap=10; //gap between buttons int buttonWidth=0; //initialising the variable to hold the WIDTH of each button int buttonHeight=0; //initialising the variable to hold the HEIGHT of each button
/*------------------------------------------------------------------------------ The setup() method is used to connect to the Bluetooth Device, and setup the GUI on the phone. -----------------------------------------------------------------------------*/ void setup(){ new Thread(ConBTdevice).start(); //Connect to SeeedBTSlave device orientation(LANDSCAPE); //Make GUI appear in landscape mode
//Setup the WidgetContainer and work out the size of each button widgetContainer = new APWidgetContainer(this); buttonWidth=((width/n)-(n*(gap/2))); //button width depends on screen width buttonHeight=(height/2); //button height depends on screen height
//Add ALL buttons to the widgetContainer. for(int i=0; i<n;i++){ guiBtns[i]= new APButton(((buttonWidth*i)+(gap*(i+1))), gap, buttonWidth, buttonHeight, buttonText[i]); widgetContainer.addWidget(guiBtns[i]); } }
/*------------------------------------------------------------------------------ The draw() method is only used to change the colour of the phone's background -----------------------------------------------------------------------------*/ void draw(){ background(bg[0],bg[1],bg[2]); }
/*------------------------------------------------------------------------------ onClickWidget is called when a button is clicked/touched, which will change the colour of the background, and send a specific letter to the Arduino. The Arduino will use this letter to change the colour of the RGB LED -----------------------------------------------------------------------------*/ void onClickWidget(APWidget widget){ String letrToSend="";
/*Identify the button that was pressed, Change the phone background colout accordingly and choose the letter to send */ for(int i=0; i<n;i++){ if(widget==guiBtns[i]){ ConBTdevice.changeBackground(buttonColour[i][0], buttonColour[i][1], buttonColour[i][2]); letrToSend=sendLetter[i]; } }
/* Send the chosen letter to the Arduino/Bluetooth Shield */ if(ConBTdevice!=null){ ConBTdevice.write(letrToSend); } }
/*============================================================================== CLASS: Connect2BtDevice implements Runnable - used to connect to remote bluetooth device and send values to the Arduino ==================================================================================*/ publicclassConnect2BtDevice implements Runnable{
/*------------------------------------------------------------------------------ DEFAULT CONSTRUCTOR: Connect2BtDevice() - Create a BroadcastReceiver (registered in run() method). - Get the default Bluetooth Adapter - Enable the adapter (if it is not already enabled). - Discover available Bluetooth devices to connect to -----------------------------------------------------------------------------*/ public Connect2BtDevice(){ broadcastBtDevices = new btBroadcastReceiver(); getBtAdapter(); enableBtAdapter(); discoverBtDevices(); }
/*------------------------------------------------------------------------------ run() method - used to register the broadcast receiver only -----------------------------------------------------------------------------*/ @Override publicvoid run() { registerReceiver(broadcastBtDevices, new IntentFilter(BluetoothDevice.ACTION_FOUND)); }
/*------------------------------------------------------------------------------ getBtAdapter() method - get the default Bluetooth adapter -----------------------------------------------------------------------------*/ void getBtAdapter(){ btAdapter = BluetoothAdapter.getDefaultAdapter(); }
/*------------------------------------------------------------------------------ enableBtAdapter() method - Enable the default Bluetooth Adapter if it isn't already enabled -----------------------------------------------------------------------------*/ void enableBtAdapter(){ if (!btAdapter.isEnabled()) { btAdapter.enable(); } }
/*------------------------------------------------------------------------------ discoverBtDevices() method - Discover other Bluetooth devices within range (ie SeeedBTSlave device) -----------------------------------------------------------------------------*/ void discoverBtDevices(){ while(!btAdapter.isEnabled()){ //Wait until the Bluetooth Adapter is enabled before continuing } if (!btAdapter.isDiscovering()){ btAdapter.startDiscovery(); } }
/*------------------------------------------------------------------------------ connect2Bt() method: called by the btBroadcastReceiver - Create a BluetoothSocket with the discovered Bluetooth device - Change background to yellow at this step - Connect to the discovered Bluetooth device through the BluetoothSocket - Wait until socket connects then - Attach an outputStream to the BluetoothSocket to communicate with Bluetooth device. (ie. Bluetooth Shield on the the Arduino) - Write a "g" string through the outputStream to change the colour of the LED to green and change the phone background colour to green also. A green screen and green LED suggests a successful connection, plus the Bluetooth shield's onboard LED starts flashing green slowly (1 per second), which also confirms the successful connection. -----------------------------------------------------------------------------*/ void connect2Bt(){ try{ btSocket = btShield.createRfcommSocketToServiceRecord(uuid); changeBackground(255,255,0); //YELLOW Background try{ btSocket.connect(); while(btSocket==null){ //Do nothing } try { btOutputStream = btSocket.getOutputStream(); changeBackground(0,255,0); //Green Background write("g"); //Green LED (Successful connection) }catch (IOException e) { Log.e("ConnectToBluetooth", "Error when getting output Stream"); } }catch(IOException e){ Log.e("ConnectToBluetooth", "Error with Socket Connection"); changeBackground(255,0,0); //Red background } }catch(IOException e){ Log.e("ConnectToBluetooth", "Error with Socket Creation"); changeBackground(255,0,0); //Red background try{ btSocket.close(); //try to close the socket }catch(IOException closeException){ Log.e("ConnectToBluetooth", "Error Closing socket"); }return; } }
/*------------------------------------------------------------------------------ write(String str) method - Allows you to write a String to the remote Bluetooth Device -----------------------------------------------------------------------------*/ publicvoid write(String str) { try { btOutputStream.write(stringToBytes(str)); } catch (IOException e) { Log.e("Writing to Stream", "Error when writing to btOutputStream"); } }
/*------------------------------------------------------------------------------ byte[] stringToBytes(String str) method - Used by the write() method - This method is used to convert a String to a byte[] array - This code snippet is from Byron: http://www.javacodegeeks.com/2010/11/java-best-practices-char-to-byte-and.html -----------------------------------------------------------------------------*/ public byte[] stringToBytes(String str) { char[] buffer = str.toCharArray(); byte[] b = new byte[buffer.length << 1]; for(int i = 0; i < buffer.length; i++) { int bpos = i << 1; b[bpos] = (byte) ((buffer[i]&0xFF00)>>8); b[bpos + 1] = (byte) (buffer[i]&0x00FF); } return b; }
/*------------------------------------------------------------------------------ cancel() method - Can be called to close the Bluetooth Socket -----------------------------------------------------------------------------*/ publicvoid cancel() { try { btSocket.close(); } catch (IOException e){ } }
/*------------------------------------------------------------------------------ changeBackground(int bg0, int bg1, int bg2) method - A method to change the background colour of the phone screen -----------------------------------------------------------------------------*/ void changeBackground(int bg0, int bg1, int bg2){ bg[0] = bg0; bg[1] = bg1; bg[2] = bg2; } }
/*============================================================================== CLASS: btBroadcastReceiver extends BroadcastReceiver - Broadcasts a notification when the "SeeedBTSlave" is discovered/found. - Use this notification as a trigger to connect to the remote Bluetooth device ==================================================================================*/ publicclassbtBroadcastReceiver extends BroadcastReceiver { @Override publicvoid onReceive(Context context, Intent intent) { String action=intent.getAction(); /* Notification that BluetoothDevice is FOUND */ if(BluetoothDevice.ACTION_FOUND.equals(action)){ /* Get the discovered device Name */ String discoveredDeviceName = intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
/* If the discovered Bluetooth device Name =SeeedBTSlave then CONNECT */ if(discoveredDeviceName.equals("SeeedBTSlave")){ /* Get a handle on the discovered device */ btShield = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); /* Connect to the discovered device. */ ConBTdevice.connect2Bt(); } } } }
Here is a picture of the components used in this sketch:
Please take notice of the Jumper pin placement on the Bluetooth Shield. This ensures communication between the Arduino and Bluetooth Shield, and is reflected in the Arduino code further down this page. The Arduino transmits information to the Bluetooth Shield on Digital pin 7, and therefore the Bluetooth Shield receivesinformation from the Arduino on Digital pin 7. On the other hand, the Bluetooth shield transmits and the Arduino receives information on Digital pin 6 (see picture below). This serial communication between the Arduino and the Bluetooth Shield occurs through the SoftwareSeriallibrary. This is different from the Serial library used in some of my other tutorials (often to display information in the Serial Monitor). The Arduino UNO's Serial pins are 0 (RX) and 1 (TX). It is worth looking at the Arduino Serialpage if you happen to have an Arduino Leonardo, because there are some differences that you should take into consideration when running this sketch.
Make sure that your Arduino has the following code installed and running BEFORE you launch the Android/Processing Sketch on your Android Device. If you don't do it in this order, your Android phone will not discover the Bluetooth Device attached to the Arduino, and you will waste a lot of time. Make sure that the Bluetooth shield is flashing it's red/green LEDs. Once you see this alternating red/green LED display, launch the Android/Processing sketch on the Android device. When you see the chainable RGB LED turn from white to green, you know you have a successful connection. You may then press the GUI buttons on the Android phone to change the colour of the LED to either Red, Green, Blue or Off.
Arduino Sketch 3: Bluetooth RGB Colour Changer (with OFF option)
/* This project combines the code from a few different sources. This project was put together by ScottC on the 15/01/2013 http://arduinobasics.blogspot.com/
Bluetooth slave code by Steve Chang - downloaded from : http://www.seeedstudio.com/wiki/index.php?title=Bluetooth_Shield
Grove Chainable RGB code can be found here : http://www.seeedstudio.com/wiki/Grove_-_Chainable_RGB_LED#Introduction
Updated on 25 March 2013: Receive 'x' to turn off RGB LED.
*/
#include <SoftwareSerial.h> //Software Serial Port
#define RxD 6 // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD) #define TxD 7 // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)
#define DEBUG_ENABLED 1
int Clkpin = 9; //RGB LED Clock Pin (Digital 9) int Datapin = 8; //RGB LED Data Pin (Digital 8)
SoftwareSerial blueToothSerial(RxD,TxD); /*----------------------SETUP----------------------------*/void setup() { Serial.begin(9600); // Allow Serial communication via USB cable to computer (if required) pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6 pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7 pinMode(13,OUTPUT); // Use onboard LED if required. setupBlueToothConnection(); //Used to initialise the Bluetooth shield
pinMode(Datapin, OUTPUT); // Setup the RGB LED Data Pin pinMode(Clkpin, OUTPUT); // Setup the RGB LED Clock pin
} /*----------------------LOOP----------------------------*/void loop() { digitalWrite(13,LOW); //Turn off the onboard Arduino LED char recvChar; while(1){ if(blueToothSerial.available()){//check if there's any data sent from the remote bluetooth shield recvChar = blueToothSerial.read(); Serial.print(recvChar); // Print the character received to the Serial Monitor (if required)
//If the character received = 'r' , then change the RGB led to display a RED colour if(recvChar=='r'){ Send32Zero(); // begin DataDealWithAndSend(255, 0, 0); // first node data Send32Zero(); // send to update data }
//If the character received = 'g' , then change the RGB led to display a GREEN colour if(recvChar=='g'){ Send32Zero(); // begin DataDealWithAndSend(0, 255, 0); // first node data Send32Zero(); // send to update data }
//If the character received = 'b' , then change the RGB led to display a BLUE colour if(recvChar=='b'){ Send32Zero(); // begin DataDealWithAndSend(0, 0, 255); // first node data Send32Zero(); // send to update data }
//If the character received = 'x' , then turn RGB led OFF if(recvChar=='x'){ Send32Zero(); // begin DataDealWithAndSend(0, 0, 0); // first node data Send32Zero(); // send to update data } }
//You can use the following code to deal with any information coming from the Computer (serial monitor) if(Serial.available()){ recvChar = Serial.read();
//This will send value obtained (recvChar) to the phone. The value will be displayed on the phone. blueToothSerial.print(recvChar); } } }
//The following code is necessary to setup the bluetooth shield ------copy and paste---------------- void setupBlueToothConnection() { blueToothSerial.begin(38400); //Set BluetoothBee BaudRate to default baud rate 38400 blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode blueToothSerial.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave" blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here delay(2000); // This delay is required. blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable Serial.println("The slave bluetooth is inquirable!"); delay(2000); // This delay is required. blueToothSerial.flush(); }
//The following code snippets are used update the colour of the RGB LED-----copy and paste------------ void ClkProduce(void){ digitalWrite(Clkpin, LOW); delayMicroseconds(20); digitalWrite(Clkpin, HIGH); delayMicroseconds(20); } void Send32Zero(void){ unsignedchar i; for (i=0; i<32; i++){ digitalWrite(Datapin, LOW); ClkProduce(); } }
Please note that this Arduino code/project will work with SeeedStudio's Bluetooth Shield. You may need to modify the Arduino Code (lines 95-107) to coincide with your own bluetooth shield. I got the code snippet within the my setupBlueToothConnection() method from some example code from Steve Chang which was found on SeeedStudio's Bluetooth Shield Wiki page. Here is some other useful information in relation to setting up this Bluetooth Shield that could be of help in your project (here).
Much of the code used within the Android/Processing sketch was made possible through constant reference to these sites:
And I would also like to thank Pauline303 who made the suggestion within the Processing Forums to use APWidgets Library for my Buttons in the App. The Arduino and Processing Forums are always a great place to get help in a short amount of time.
The bluetooth shield used in this project is a great way to detach the Arduino from your computer. What is even better, is that the shield allows you to control your arduino from your mobile phone or other bluetooth enabled device through simple Serial commands. In this tutorial we will connect a Grove Chainable RGB LED to the bluetooth shield directly, and send simple commands using the Bluetooth SPP app on a Samsung Galaxy S2 to change the colour of the LED (Red , Green and Blue)
/* This project combines the code from a few different sources. This project was put together by ScottC on the 15/01/2013 http://arduinobasics.blogspot.com/
Bluetooth slave code by Steve Chang - downloaded from : http://www.seeedstudio.com/wiki/index.php?title=Bluetooth_Shield
Grove Chainable RGB code can be found here : http://www.seeedstudio.com/wiki/Grove_-_Chainable_RGB_LED#Introduction
*/
#include <SoftwareSerial.h> //Software Serial Port
#define uint8 unsigned char #define uint16 unsigned int #define uint32 unsigned long int
#define RxD 6 // This is the pin that the Bluetooth (BT_TX) will transmit to the Arduino (RxD) #define TxD 7 // This is the pin that the Bluetooth (BT_RX) will receive from the Arduino (TxD)
#define DEBUG_ENABLED 1
int Clkpin = 9; //RGB LED Clock Pin (Digital 9) int Datapin = 8; //RGB LED Data Pin (Digital 8)
SoftwareSerial blueToothSerial(RxD,TxD);
/*----------------------SETUP----------------------------*/ void setup() { Serial.begin(9600); // Allow Serial communication via USB cable to computer (if required) pinMode(RxD, INPUT); // Setup the Arduino to receive INPUT from the bluetooth shield on Digital Pin 6 pinMode(TxD, OUTPUT); // Setup the Arduino to send data (OUTPUT) to the bluetooth shield on Digital Pin 7 pinMode(13,OUTPUT); // Use onboard LED if required. setupBlueToothConnection(); //Used to initialise the Bluetooth shield
pinMode(Datapin, OUTPUT); // Setup the RGB LED Data Pin pinMode(Clkpin, OUTPUT); // Setup the RGB LED Clock pin
}
/*----------------------LOOP----------------------------*/ void loop() { digitalWrite(13,LOW); //Turn off the onboard Arduino LED char recvChar; while(1){ if(blueToothSerial.available()){//check if there's any data sent from the remote bluetooth shield recvChar = blueToothSerial.read(); Serial.print(recvChar); // Print the character received to the Serial Monitor (if required)
//If the character received = 'r' , then change the RGB led to display a RED colour if(recvChar=='r'){ Send32Zero(); // begin DataDealWithAndSend(255, 0, 0); // first node data Send32Zero(); // send to update data }
//If the character received = 'g' , then change the RGB led to display a GREEN colour if(recvChar=='g'){ Send32Zero(); // begin DataDealWithAndSend(0, 255, 0); // first node data Send32Zero(); // send to update data }
//If the character received = 'b' , then change the RGB led to display a BLUE colour if(recvChar=='b'){ Send32Zero(); // begin DataDealWithAndSend(0, 0, 255); // first node data Send32Zero(); // send to update data } }
//You can use the following code to deal with any information coming from the Computer (serial monitor) if(Serial.available()){ recvChar = Serial.read();
//This will send value obtained (recvChar) to the phone. The value will be displayed on the phone. blueToothSerial.print(recvChar); } } }
//The following code is necessary to setup the bluetooth shield ------copy and paste---------------- void setupBlueToothConnection() { blueToothSerial.begin(38400); //Set BluetoothBee BaudRate to default baud rate 38400 blueToothSerial.print("\r\n+STWMOD=0\r\n"); //set the bluetooth work in slave mode blueToothSerial.print("\r\n+STNA=SeeedBTSlave\r\n"); //set the bluetooth name as "SeeedBTSlave" blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit Paired device to connect me blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here delay(2000); // This delay is required. blueToothSerial.print("\r\n+INQ=1\r\n"); //make the slave bluetooth inquirable Serial.println("The slave bluetooth is inquirable!"); delay(2000); // This delay is required. blueToothSerial.flush(); }
//The following code snippets are used update the colour of the RGB LED-----copy and paste------------ void ClkProduce(void){ digitalWrite(Clkpin, LOW); delayMicroseconds(20); digitalWrite(Clkpin, HIGH); delayMicroseconds(20); }
You don't need to download a library to get this project running. But if you plan to use bluetooth shields to get 2 Arduinos to communicate to each other, then I would advise that you download the library files (which are just examples) from the Seeedstudio site : here.
Visit this site to setup your phone or laptop for bluetooth communication to the shield - here
The app used on my Samsung Galaxy S2 phone was "Bluetooth SPP"
You will initially need to enter a pin of '0000' to establish a connection to the Bluetooth shield - which will appear as "SeeedBTSlave" or whatever text you place on line 90 of the Arduino code above.
Warning !
Not all phones are compatible with the bluetooth shield. If you have used this shield before - please let me know what phone you used - so that we can build a list and inform others whether their phone is likely to work with this project or not. Obviously - those phones that do not have bluetooth within - will not work :). And I have not tried any other apps either
I got it to work very easily with my Samsung Galaxy S2 using the free Bluetooth SPP app from the google play store.
This was fun, but I want to make my own app ! Have a look at my latest 4-part tutorial which takes you step-by-step through the process of building your own app using the Processing/Android IDE. You can build your own GUI interface on your Android Phone and get it to communicate via Bluetooth to your Arduino/Bluetooth Shield. Click on the links below for more information:
Description: A 3-axis accelerometer sits at the heart of this project to provide a nifty little motion detector. Want to know who is stealing from the cookie jar? Want a simple home intrusion detector? Or to test your partner's driving skills? Then have a look at this:
Overlay the Seeed Studio Base Shield onto the Freetronics Eleven (or compatible Arduino).
Use a Universal Cable to attach a Seeed Studio Grove Button to Analog Pin 0 on the Base Shield. The socket is located directly above the Freetronics Eleven Power plug, and next to the Reset button on the Base Shield. Please note that Analog Pin 1 is not used by the Grove Button.
Use a universal Cable to attache a Seeed Studio Grove Buzzer to Analog Pin 1 on the Base Shield. This is the socket next to the one used in Step 2.
Solder the female header pins to the Protoboard. Overlay the protoboard onto the Base Shield to create a third layer. I created this layer to tidy up the project and make it a little bit more portable. You could just wire up another breadboard on the side.
Stick a mini-breadboard (4.5cm x 3.5cm) onto the protoboard. This allows you to use the protoboard for other projects.
Solder the male headers to the 3-axis accelerometer, and then place it centrally onto the breadboard.
You need 5 wires to connect:
GND on protoboard to GND on accelerometer
5V on protoboard to VIN on accelerometer
Analog Pin 3 on protoboard to X on accelerometer
Analog Pin 4 on protoboard to Y on accelerometer
Analog Pin 5 on protoboard to Z on accelerometer
Connect digital pin 8 to an LED and 330 ohm resistor on the breadboard,
Use a wire to connect the resistor mentioned above to GND on the protoboard
Connect the USB cable from your computer to the Freetronics Eleven, and upload the Arduino Sketch to the board.
Disconnect the USB cable, and then power the Freetronics Eleven using a 9V battery and clip.
When you press the button, it will sound 3 warning sounds before it becomes activated.
If it detects a vibration or motion that exceeds the tolerance level, it will alarm. The alarm will continue until you either press the Grove button - which resets and reactivates the device or you can press the Reset button on the Base Shield to Stop monitoring for motion.
//Motion Detector Alarm - Written by ScottC on 2/08/2012
//Global Variables and constants constint buttonPin = A0; // button Pin connected to Analog 0 constint buzzerPin = A1; // buzzer Pin connected to Analog 1
//Accelerometer Pins constint x = A3; // X pin connected to Analog 3 constint y = A4; // Y pin connected to Analog 4 constint z = A5; // Z pin connected to Analog 5
//Alarm LED constint ledPin = 8; // LED connected to Digital 8
int tolerance=20; // Sensitivity of the Alarm boolean calibrated=false; // When accelerometer is calibrated - changes to true boolean moveDetected=false; // When motion is detected - changes to true
//Accelerometer limits int xMin; //Minimum x Value int xMax; //Maximum x Value int xVal; //Current x Value
int yMin; //Minimum y Value int yMax; //Maximum y Value int yVal; //Current y Value
int zMin; //Minimum z Value int zMax; //Maximum z Value int zVal; //Current z Value
void setup(){ //Begin Serial communication Serial.begin(38400);
//Initilise LED Pin pinMode(ledPin, OUTPUT);
}
void loop(){ // If the button is pressed, initialise and recalibrate the Accelerometer limits. if(analogRead(buttonPin)>500){ calibrateAccel(); }
// Once the accelerometer is calibrated - check for movement if(calibrated){ if(checkMotion()){ moveDetected=true; } }
// If motion is detected - sound the alarm ! if(moveDetected){ Serial.println("ALARM"); ALARM(); delay(1000); }
}
//This is the function used to sound the buzzer void buzz(int reps, int rate){ for(int i=0; i<reps; i++){ analogWrite(buzzerPin,900); delay(100); analogWrite(buzzerPin,0); delay(rate); } }
// Function used to calibrate the Accelerometer void calibrateAccel(){ // reset alarm moveDetected=false;
//End of calibration sequence sound. ARMED. buzz(3,40); printValues(); //Only useful when connected to computer- using serial monitor. calibrated=true;
}
//Function used to detect motion. Tolerance variable adjusts the sensitivity of movement detected. boolean checkMotion(){ boolean tempB=false; xVal = analogRead(x); yVal = analogRead(y); zVal = analogRead(z);
// Prints the Sensor limits identified during Accelerometer calibration. // Prints to the Serial monitor. void printValues(){ Serial.print("xMin="); Serial.print(xMin); Serial.print(", xMax="); Serial.print(xMax); Serial.println();
This project makes use of the Grove OLED 96x96 display to present a mini-slideshow. Pictures on your computer are transferred to the OLED via a Processing script, and will cycle through them as many times as you choose.
void setup() { //Allow communication to OLED Wire.begin();
//Allow Serial communication between Freetronics Eleven and Computer Serial.begin(28800);
//Initialise the OLED SeeedGrayOled.init(); //Clear the OLED display SeeedGrayOled.clearDisplay(); //Set to vertical mode - horizontal mode doesn't work with this example SeeedGrayOled.setVerticalMode();
}
void loop(){ //Listen for Serial comunication while (Serial.available()>0) { // Read data and send directly to the OLED sendMyData(Serial.read()); counter++;
//When counter reaches 4608 pixels, the picture is complete. if(counter>4607){ //Insert delay to allow viewing of picture. delay(4000); Serial.println("End of Transmission");
//Reset the counter for the next picture counter=0; } } }
// This function was adapted from the SEEED Gray OLED driver so that // character bytes could be sent directly to the OLED. void sendMyData(unsignedchar Data){ Wire.beginTransmission(SeeedGrayOLED_Address); // begin I2C transmission Wire.send(SeeedGrayOLED_Data_Mode); // data mode Wire.send(Data); Wire.endTransmission(); }
// This function was adapted from the SEEED Gray OLED driver so that // commands could be sent directly to the OLED. // NOT USED IN THIS EXAMPLE *********************** void sendMyCommand(unsignedchar Cmd){ Wire.beginTransmission(SeeedGrayOLED_Address); // begin I2C communication Wire.send(SeeedGrayOLED_Command_Mode); // Set OLED Command mode Wire.send(Cmd); Wire.endTransmission(); // End I2C communication }
import processing.serial.*; /* Needed for Serial Communication */
/* Global variables */ Serial comPort; String [] comPortList; String comPortString; PImage img; char[] tempGrey=newchar[4609]; int startOffset=0; ArrayList picNames; int curLoop=1; int totalPics=0; int curPicNum=0; boolean toggleSend=true; boolean sendBouncer=true;
//Change maxLoops to a number > 1 if you want the pictures to loop. int maxLoops=1;
void setup() { //The size of the display is critical (must match the OLED) size(96, 96); //setup Serial comPortList = Serial.list(); if(comPortList.length>0){ //baud rates greater than 28800 may produce unexpected results comPort = new Serial(this, comPortList[0], 28800); comPort.bufferUntil('\n'); } else{ println("NO COM PORTS AVAILABLE"); }
//Create an Array of pictures picNames=new ArrayList(); picNames.add("Picture1.bmp"); picNames.add("Picture2.bmp"); picNames.add("Picture3.bmp"); picNames.add("Picture4.bmp"); // for more pictures just keep adding them to the list. //The actual pictures must be located in the data folder of this project. //Select Sketch/Add File to add the files to this folder. //Make sure that the name of pictures match the names above.
//Get the total number of pictures added totalPics=picNames.size(); }
sendImage((String)picNames.get(curPicNum)); //Send the picture to the OLED toggleSend=false; //temporarily stop sending any more pictures until authorised curPicNum++; //increment in preparation for the next picture
if(curPicNum==totalPics){ curPicNum=0; //go back to the first picture curLoop++; //increment the loop counter } if(curLoop>maxLoops){ sendBouncer=false; //Stop any further looping println("ANIMATION COMPLETE"); } } }
void sendImage(String imgName){ img = loadImage(imgName); image(img,0,0,width,height); loadPixels(); int counter=0; for (int x = 0; x < width; x=x+2) { for (int y = 0; y < height; y++) { counter++; int PixLoc = x + y*height; // this reads down then across2. //Left pixel nibble int Pix1=(round((red(pixels[PixLoc])*0.222+green(pixels[PixLoc])*0.707+blue(pixels[PixLoc])*0.071)))/16; //Right pixel nibble int Pix2=(round((red(pixels[PixLoc+1])*0.222+green(pixels[PixLoc+1])*0.707+blue(pixels[PixLoc+1])*0.071)))/16; //Shift the byte <<4 for the left pixel nibble int PixShift1=Pix1<<4; //Combine both nibbles to form a byte int PixFin = PixShift1+Pix2; byte PixByteFin=byte(PixFin); //Assign this byte to the tempGrey array tempGrey[counter] = char(PixByteFin); } } sendSerial(tempGrey); //Send the image data through the Serial COM Port/ }
//This function will send the byte/Char array to the Freetronics //Eleven or Arduino. void sendSerial(char[] Data){ for(int i=0; i<4608; i++){ //Needs an offset to get picture to align to screen properly //only needs to do this once. if(startOffset==0){ i=i+6; startOffset++; } //Send the picture data to the Freetronics Eleven / Arduino comPort.write(Data[i]); } }
//This function will wait for a response from the Freetronics //Eleven or Arduino before sending any further pictures. void serialEvent (Serial myPort) { // get the ASCII string: String inString = myPort.readStringUntil('\n'); if (inString != null) { println(inString); toggleSend=true; // Allow the next picture to be sent } }
Please note: that you must use the Arduino IDE version 023 until Seeed Studio update their driver for this OLED. Their current driver is not compatible with later versions of Arduino IDE.