Home
TI Submission - TI E2E Community
Contents
1. kok kok k k fn HalAccSetRange HalAccSetRange HAL_ACC_RANGE_8G brief Set the range of the accelerometer param range HAL_ACC_RANGE_2G HAL_ACC_RANGE_4G HAL_ACC_RANGE_8G S 36 Sp return None void HalAccSetRange uint8 range t accRange range switch accRange t case HAL_ACC_RANGE_2G accSensorConfig ADXL345_RANGE_16_G accSensorOff ACC REG CTRL OFF 2G break case HAL ACC RANGE 46 accSensorConfig ACC REG CTRL ON 4G accSensorOff ACC REG CTRL OFF 4G break case HAL ACC RANGE 86 accSensorConfig ACC REG CTRL ON 8G accSensorOff ACC REG CTRL OFF 8G 53 break default Should not get here break range t adxl range ADXL345 RANGE 2 6 void setRange range t range Red the data format register to preserve bits uint8 registerPointer HalSensorReadReg ADXL345 REG DATA FORMAT uint8 amp registerPointer 1 uint8 format registerPointer Update the data rate format amp format range Make sure that the FULL RES bit is enabled for range scaling format 0x08 Write the register back to the IC uint8 value pointer value pointer format HalSensorWriteReg ADXL345 REG DATA FORMAT amp value_pointer 1 Keep track of the current range to a
2. KKK fn HalIRTempTurnOoff brief Turn the sensor off return none EEEE EEEE EEEE EEE EEE EEEE 9k SR okokeok SK EEEE EEEE EE EEEE EEE EEE EE EE E E E E E E E E E E E E E K E E K K k K K kK k K K k k Kk k kK Kk KK k k kK Kk void HalIRTempTurnOff void HalIRTempSelect if HalSensorWriteReg TMP006 REG ADDR CONFIG configSensorOff IRTEMP REG LEN 61 d irtSensorState 006 OFF HalDcDcControl ST IRTEMP false double sqrti double long double x0 350 long double x1 0 for int i 0 i 15 1 1 0 5 x0 x x0 x x1 return x0 EE EEE SESE fn HalIRTempRead brief Read the sensor voltage and sensor temperature registers param Voltage and temperature in raw format 2 2 bytes return TRUE if valid data SR 5k 9 9k 9k 9k SK SR PK K SK SK PK SR K K k k PRR KR K Kk K Kk k kK kK R bool HalIRTempRead uint8 pBuf int32 UTCTime uint16 v uinti16 t bool success if irtSensorState 006 DATA READY return FALSE HalIRTempSelect Read the sensor registers su
3. Wearable Circadian Rhythm Monitor North Carolina State University TI Innovation Challenge 2015 Tl university program Project Report Team Leader Jonathan Howell jjhowel2 ncsu edu Team Members David Le dkle ncsu edu David Brown dwbrown3 ncsu edu Advising Professor Dr John Muth muth ncsu edu Video Provide link to video that you ve uploaded to www ti com videos ti com videos was not working when we submitted http youtu be iny3Fk3ennc Texas Instruments Mentor if applicable Date 5 20 2015 Qty List all Tl analog IC 1 Explain where it was used in the project and TI processor part 2 What specific features or performance made this number and URL component well suited to the design 1 CC2541 The Texas Instruments CC2541 Microcontroller was chosen for our http www ti com produc application because the MCU features a Bluetooth Low Energy U CC2541 description transmitter receiver SoC Using the CC2541 was advantageous to us because it reduced the number of components needed for BLE connectivity rather than adding an additional IC just for BLE communication 1 TMP006 The Texas Instruments 006 thermocouple sensor was chosen http www ti com produc for skin temperature measurement The 006 operates at 3 3V t TMP006 description and obtains skin temperature measurements by absorbing IR energy emitted from an object it is p
4. trim String light RowData 2 replace trim String utc RowData 3 replace trim if type equals Visible 121 Log d TAG IN HERE type Log d TAG IN HERE UTC double Long parseLong utc Log d TAG IN HERE VISLIGHT Float parseFloat light data add new GraphViewData double Long parseLong utc Double parseDouble light catch IOException ex H handle exception finally try reader close catch IOException e H handle exception GraphView graphView new LineGraphView this Visible Light lux graphView setCustomLabelFormatter new CustomLabelFormatter Override public String formatLabel double value boolean isValueX if isValueX return getDateCurrentTimeZone long value return null GraphViewData input new GraphViewData data size for int i 0 i lt input length i input i data get i H add data graphView addSeries new GraphViewSeries input set view port start 2 size 40 graphView setViewPort 2 40 graphView setScrollable true H optional activate scaling zooming graphView setScalable true LinearLayout layout LinearLayout findViewByld R id graph1 layout addView graphView private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getInstance TimeZone tz TimeZone getDefault calendar setTimelnMillis t
5. uint8 amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAM DATA 1 registerPointer 28 address_LSB READ_FRAM_FROM_ADDRESS BYTE1 amp i2c pg addr amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAM DATA 2 registerPointer address 15 READ ERAN FROM ADDRESS BYTE1 amp i2c pg addr amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAM DATA 3 registerPointer address 15 READ ERAN FROM ADDRESS BYTE1 amp i2c pg addr amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAM DATA 4 registerPointer address 15 READ ERAN FROM ADDRESS BYTE1 amp i2c pg addr amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAM DATA 5 registerPointer address 15 READ ERAN FROM ADDRESS BYTE1 amp i2c pg addr amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAM DATA 6 registerPointer address 15 READ ERAN FROM ADDRESS BYTE1 amp i2c pg addr amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAM DATA 7 registerPointer address 15 READ ERAN FROM ADDRESS BYTE1 amp i2c pg addr amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAM DATA 8 registerPointer address 15 READ ERAN FROM ADDRESS BYTE1 amp i2c pg addr amp address MSB ui
6. Qparam address The device address of the destination device return Return true if the connection is initiated successfully The connection result is reported asynchronously through the hi code BluetoothGattCallback onConnectionStateChange android bluetooth BluetoothGatt int int callback public boolean connect final String address if mBluetoothAdapter null address null Log w TAG BluetoothAdapter not initialized or unspecified address return false H Previously connected device Try to reconnect if mBluetoothDeviceAddress null amp amp address equals mBluetoothDeviceAddress amp amp mBluetoothGatt null 74 Log d TAG Trying to use an existing mBluetoothGatt for connection if mBluetoothGatt connect mConnectionState STATE CONNECTING return true else return false final BluetoothDevice device mBluetoothAdapter getRemoteDevice address if device null Log w TAG Device not found Unable to connect return false We want to directly connect to the device so we are setting the autoConnect H parameter to false mBluetoothGatt device connectGatt this false mGattCallback Log d TAG Trying to create a new connection mBluetoothDeviceAddress address mConnectionState STATE CONNECTING return true Disconnects an existing connection or cancel a pending connection The disconnection result is report
7. Override public void run mScanning false mBluetoothAdapter stopLeScan mLeScanCallback invalidateOptionsMenu SCAN PERIOD mScanning true mBluetoothAdapter startL eScan mLeScanCallback else mScanning false mBluetoothAdapter stopLeScan mLeScanCallback invalidateOptionsMenu JI Adapter for holding devices found through scanning private class LeDeviceListAdapter extends BaseAdapter private ArrayList lt BluetoothDevice gt mLeDevices private LayoutlInflater minflator public LeDeviceListAdapter super mLeDevices new ArrayList lt BluetoothDevice gt minflator DeviceScanActivity this getLayoutlnflater public void addDevice BluetoothDevice device if mLeDevices contains device mLeDevices add device public BluetoothDevice getDevice int position return mLeDevices get position public void clear mLeDevices clear Override public int getCount return mLeDevices size Override public Object getltem int i return mLeDevices get i Override public long getltemld int i return i Override public View getView int i View view ViewGroup viewGroup 92 ViewHolder viewHolder II General ListView optimization code if view null view mlnflator inflate R layout listitem device null viewHolder new ViewHolder viewHolder deviceAddress TextView view findViewByld R id d
8. if this getX other getX 0 1 InitOptionSelect java package com example android bluetoothlegatt import java io FileWriter import java io IOException import java text SimpleDateFormat import java util ArrayList import java util Calendar import java util Date import java util HashMap import java util Hashtable import java util List import java util TimeZone import java util UUID import com opencsv CSVWriter import android app Activity import android bluetooth BluetoothAdapter import android bluetooth BluetoothDevice import android bluetooth BluetoothGatt import android bluetooth BluetoothGattCallback import android bluetooth BluetoothGattCharacteristic import android bluetooth BluetoothGattDescriptor import android bluetooth BluetoothGattService import android bluetooth BluetoothManager import android content BroadcastReceiver import android content ComponentName import android content Context import android content Intent import android content IntentFilter import android content ServiceConnection 94 import android os Bundle import android os Handler import android os IBinder import android util Log import android view View import android widget Button import android widget ExpandableListView import android widget SimpleExpandableListAdapter import android widget TextView public class InitOptionSelect extends Activi
9. import android content Intent import android content pm PackageManager import android os Bundle import android os Handler import android view Layoutlnflater import android view Menu import android view Menultem import android view View import android view ViewGroup import android widget BaseAdapter import android widget ListView import android widget TextView import android widget Toast import java util ArrayList Activity for scanning and displaying available Bluetooth LE devices public class DeviceScanActivity extends ListActivity 89 private LeDeviceListAdapter mLeDeviceListAdapter private BluetoothAdapter mBluetoothAdapter private boolean mScanning private Handler mHandler private static final int REQUEST ENABLE BT 1 1 Stops scanning after 10 seconds private static final long SCAN PERIOD 10000 Override public void onCreate Bundle savedInstanceState super onCreate savedinstanceState getActionBar setTitle R string title_devices mHandler new Handler 1 Use this check to determine whether BLE is supported on the device Then you can selectively disable BLE related features if IgetPackageManager hasSystemFeature PackageManager FEATURE BLUETOOTH LE Toast makeText this R string ble not supported Toast LENGTH SHORT show finish II Initializes a Bluetooth adapter For API level 18 and above get a reference to BluetoothAdapter thro
10. try reader close catch IOException e H handle exception GraphView graphView new LineGraphView this Beats Per Minute graphView setCustomLabelFormatter new CustomLabelFormatter Override public String formatLabel double value boolean isValueX if isValueX return getDateCurrentTimeZone long value return null GraphViewData input new GraphViewData data size for int i 0 i lt input length i input i data get i H add data graphView addSeries new GraphViewSeries input set view port start 2 size 40 graphView setViewPort 2 40 graphView setScrollable true II optional activate scaling zooming graphView setScalable true LinearLayout layout LinearLayout findViewByld R id graph1 layout addView graphView private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getInstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timestamp 1000 calendar add Calendar MILLISECOND 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone catch Exception e return int num 150 78 double v 0 for int i 0 i lt num i v 0 2 d BPM Objjava package com example android bluetoothlegatt import java io Serializable import java
11. file Environment getExternalStorageDirectory file II file sdcard file BufferedReader reader null try reader new BufferedReader new FileReader file catch FileNotFoundException e1 TODO Auto generated catch block e1 printStackTrace try String line while line reader readLine null String RowData line split String type RowData 0 replace trim String date RowData 1 replace trim String light RowData 2 replace trim String utc RowData 3 replace trim if type equals IR Log d TAG IN HERE type Log d TAG IN HERE UTC double Long parseLong utc Log d TAG IN HERE IRLIGHT Double parseDouble light data add new GraphViewData double Long parseLong utc 110 Double parseDouble light catch IOException ex H handle exception finally try reader close catch IOException e H handle exception GraphView graphView new LineGraphView this IR Light graphView setCustomLabelFormatter new CustomLabelFormatter Override public String formatLabel double value boolean isValueX if isValueX return getDateCurrentTimeZone long value return null GraphViewData input new GraphViewData data size for int i 0 i lt input length i input i data get i H add data graphView addSeries new GraphVi
12. Interpret MSB as signed return upperByte 8 lowerByte private static Integer shortUnsignedAtOffset byte c int offset Integer lowerByte int c offset amp OxFF Integer upperByte int c offset 1 amp OxFF Interpret MSB as signed return upperByte 8 lowerByte UVLIGHT GRAPHER java package com example android bluetoothlegatt import java io BufferedReader import java io FileNotFoundException import java io FileReader import java io IOException import java io InputStream import java io InputStreamReader import java text SimpleDateFormat import java util ArrayList import java util Calendar import java util Date import java util TimeZone import com jjoe64 graphview CustomLabelFormatter import com jjoe64 graphview GraphView import com jjoe64 graphview GraphView GraphViewData import com jjoe64 graphview GraphViewSeries import com jjoe64 graphview LineGraphView import android app Activity import android os Bundle import android os Environment import android util Log import android widget LinearLayout public class UVLIGHT GRAPHER extends Activity private final static String TAG UVLIGHT_GRAPHER class getSimpleName String file String H getintent getSerializableExtra EXTRAS FILE String file sdcard abc csv public static String file protected void onCreate Bundle savedinstanceState 118 super onC
13. filterVal lt 0 0 filterVal 0 01 smoothedVal data 1 0 filterVal smoothedVal filterVal return smoothedVal uint8 SI1143 ReadRESPONSE void uint8 registerPointer HalSensorReadReg SI1143 REG RESPONSE uint8 amp registerPointer BYTE1 return registerPointer uint16 511143 ReadVisible void uint16 registerPointer HalSensorReadReg SI1143 REG ALS VIS DATAO uint8 amp registerPointer BYTE2 return registerPointer 16 511143 ReadIR void 5 uint16 registerPointer HalSensorReadReg SI1143 REG ALS IR DATAO uint8 amp registerPointer BYTE2 return registerPointer uint16 511143 ReadPS1 void uint16 registerPointer HalSensorReadReg SI1143 REG 51 DATAO uint8 amp registerPointer BYTE2 return registerPointer uint16 511143 ReadPS2 void uint16 registerPointer HalSensorReadReg SI1143 REG PS2 DATAO uint8 amp registerPointer BYTE2 return registerPointer uint16 511143 ReadPS3 void uint16 registerPointer 45 HalSensorReadReg SI1143 REG PS3 DATAO uint8 amp registerPointer BYTE2 return registerPointer uint16 511143 ReadAUX void uint16 registerPointer HalSensorReadReg SI1143 REG AUX DATAO uint8 amp registerPointer BYTE2 return registerPointer bool constrain int x int a int b f if x a 88 x lt b return x if x lt return a return b UT
14. BluetoothManager bluetoothManager BluetoothManager getSystemService Context BLUETOOTH SERVICE mBtAdapter bluetoothManager getAdapter device mBtAdapter getRemoteDevice mDeviceAddress gatt device connectGatt this false mGattCallback realTimeXdata TextView find ViewByld R id xData _realTimeYdata TextView findViewByld R id yData _realTimeZdata TextView findViewByld R id zData realTimeVISdata TextView findViewByld R id visibleData _realTimelRdata TextView find ViewByld R id irData _realTimeUVdata TextView findViewByld R id uvData _realTimeTempdata TextView findViewByld R id temperature final Button button_syncTime Button findViewByld R id SyncTime final Button button_syncData Button findViewByld R id SyncData final Button button_RealTime Button findViewByld R id RealTime H intent new Intent this Grapher class button_syncTime setOnClickListener new View OnClickListener public void onClick View v button syncData setEnabled false Calendar c Calendar getlnstance month 7 c get Calendar MONTH 101 Log d TAG MONTH byte month day 7 c get Calendar DAY OF MONTH String year string c get Calendar YEAR year string year string substring year string length 2 year string length Log d TAG year string year Integer parselnt year string hour c get Calendar HOUR DAY min c
15. FRAM c amp FRAM h The FM24V10 IC is as external memory for our device The fram is used to store all our sensor data and is later read when requested by a phone device during ble synchronization Functions void READ CURRENT DATA int32 address uint8 FRAM DATA This function reads 11 bytes of fram space the amount our protocol takes starting from the address given to it This function takes in a 32 bit integer address for from from 0 to 131065 and a pointer to an array to store the read fram data into void WRITE SENSORDATA FRAM int32 address uint8 data array Operation The FRAM is accessed at many different times throughout device operation The device is written to whenever the sensors of our device poll and record data When storing data the fram address is written to once it is written to the fram pointer which keeps the address of the next point to write to is incremented With our particular FRAM there are two different pages holding 64Kb of memory If an address goes over 64Kb depending on the page it rolls over ie page 1 rolls to page 2 of memory while page 2 rolls back to 1 The fram is read whenever a phone requests to offload the fram onto the phone When the data is offloaded the offloaded memory in fram is cleared and the pointer to the read address of the fram is incremented as well UTC Code UTCTime c amp UTCTime h For our device we implemented a Unix Time Clock function This is used to calculate the exact
16. RowData 3 replace trim if type equals Accelerometer Log d TAG IN HERE type Log d TAG IN HERE UTC double Long parseLong utc Log d TAG IN HERE MAG Double parseDouble magnitude data add new GraphViewData double Long parseLong utc Double parseDouble magnitude catch IOException ex H handle exception finally try reader close catch IOException e H handle exception GraphView graphView new LineGraphView this Motion magnitude m s 2 graphView setCustomLabelFormatter new CustomLabelFormatter Override public String formatLabel double value boolean isValueX if isValueX return getDateCurrentTimeZone long value return null GraphViewData input new GraphViewData data size for int i 0 i lt input length i input i data get i H add data graphView addSeries new GraphViewSeries input set view port start 2 size 40 graphView setViewPort 2 40 graphView setScrollable true 68 H optional activate scaling zooming graphView setScalable true LinearLayout layout LinearLayout findViewByld R id graph1 layout addView graphView private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getlnstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timestamp 1000 calendar add Calendar MILLISECOND 0 Simpl
17. System Architecture 3 Hardware Design 3 1 Sensor Subsystem 3 2 Power Management Subsystem 3 3 Microcontroller Memory and Bluetooth Transmission Subsystem 4 Software Design 4 1 MCU Firmware Design 4 2 MCU Application Layer 4 3 Android Application User Interface and Software Design 5 Mechanical Design 5 1 Assembly 5 2 Device User Interface 6 Testing Results amp Conclusions 7 Future Work amp Recommendations Appendix A Schematic Appendix B Board Layout Appendix C Bill of Materials Appendix D Project Costs Appendix E User Manual Appendix F Bluetooth Low Energy UUID Table Appendix G Datasheets and References Appendix H CC2541 Firmware File Descriptions Appendix Android Application File Descriptions Appendix J CC2541 Firmware Source Code Appendix K Android Application Source Code Tables and Figures Figure 1 System Architecture Figure 2 Hardware Block Diagram Figure 3 Splash Screen and Device Selection Screen Figure 4 Syncing Screen and Real Time Screen Figure 5 Data Selection Screen and Data Graph Screen Figure 6 Enclosure Diagram Figure 7 3D Printed Enclosure 1 Project Description Among the growing popularity and excitement surrounding the wearable fitness sleep tracker market a need for a cheaper and more accurate device has emerged The purpose of this project was to produce a functional prototype which will effectively monitor an individual s circadian rhythm
18. blood stream While this process is repeated for 20 seconds for every 5 CPU cycles within this 20 seconds the data of the reflectance is being recorded and averaged then put into a comparator array An algorithm is then run on this array where the current index is compared to the last IR calculation and the next IR calculation If the algorithm detects that this middle data is a valley and the other two points are peaks the counter for the detected heartbeats is incremented Once the 20 seconds is over the BPMCounter is multiplied by 3 to scale it up to a minute of heart beats This data is then copied into the 11 byte holder array which will be used to copy into FRAM The array data holder format in big endian is shown below Header UTCmsb1 UTCmsb2 UTCIsb1 UTCIsb2 0 0 BPM MSB1 BPM MSB2 BPM LSB1 BPM LSB2 Note The Header value for any 511143 is always 3 This value is used for our Bluetooth communication between MCU and Phone as the phone will be able to decode which data it is by the header 006 hal irtemp c amp hal irtemp h The TMPO06 is used for temperature measurements for this device The following functions are used to make the TMP006 sensor operational Functions Void HallRTempSelect This function is used for the MCU to initialize an i2c connection between the CC2541 and the TMP006 sensor void HallRTempTurnOn This function turns the TMP006 on and into an idle state void HallRTempTurnOff This functi
19. comma separated value file is generated and stored on your phone with the title set to the current date and time of your Android device These CSV files can be used in several ways a CSV files can be read by the Circadian Rhythm Analyzer application b CSV files can be emailed and later viewed on a computer with a spreadsheet program c CSV files can be shared with your treating physician for further analysis Turn off Bluetooth Low Energy on your Circadian Rhythm Monitor by holding down the button on the device for approximately 5 seconds until the BLE indicator light turns solid then release the button Turning off BLE on your device will provide you with better battery life Viewing Real Time Data 1 2 3 Open the Circadian Rhythm Analyzer application on your Android device Select Sync Phone On your Circadian Rhythm Monitor push the button in the upper left corner to turn on Bluetooth Low Energy connectivity Your Circadian Rhythm Monitor should now show up on your phone as an available device to connect to If it does not select Sync in the upper right corner of the application Select the device On the next screen select Real Time Data will be displayed on the bottom of the same screen Heart rate will not be available in real time due to Bluetooth Low Energy limiting connectivity in order to save power Turn off Bluetooth Low Energy on your Circadian Rhythm Monitor by holding down the button on the devi
20. define REG CTRL GSEL TDTE Directional Tap 1 On ei ei define ACC REG CTRL GSEL WUFE Wake Up peg Aa define REG CTRL GSEL Tilt Position 1 On Range 2G define ACC REG CTRL ON 2G ACC REG CTRL PC define ACC REG CTRL OFF 2G 9 50 Range 4G define ACC REG CTRL ON 4G ACC REG CTRL PC ACC REG CTRL GSEL LO define ACC REG CTRL OFF 4G ACC REG CTRL GSEL LO Range 8G define ACC REG CTRL ON 8G ACC REG CTRL PC ACC REG CTRL GSEL HI define ACC REG CTRL OFF 8G ACC REG CTRL GSEL HI define SENSORS GRAVITY EARTH 9 80665F Earth s gravity in m s 2 define SENSORS GRAVITY MOON 1 6F The moon s gravity in m s 2 define SENSORS GRAVITY SUN 275 0F The sun s gravity in m s 2 define SENSORS GRAVITY STANDARD SENSORS GRAVITY EARTH define ADXL345 REG DEVID 0x00 Device ID define ADXL345 REG THRESH TAP 0x1D Tap threshold define ADXL345 REG OFSX 0 1 X axis offset define ADXL345 REG OFSY x1F Y axis offset define ADXL345_REG_OFSZ 0 20 Z axis offset define ADXL345 REG DUR 0x21 Tap duration define ADXL345 REG LATENT 0x22 Tap latency define ADXL345 REG WINDOW 0x23 Tap window define ADXL345 REG THRESH ACT 0x24 Activity threshold define ADXL345 REG THRESH INACT 0x25 Inactivity threshold define ADXL345 REG TIME INACT 0x26 Inactivity time define ADXL345 REG ACT INACT CTL 0x27 Axis enable control for activity and in
21. device does not have a RTC built into it 4 2 MCU Application Layer In the application layer of our device we implemented the firmware which enabled the use of our sensors to communicate with the CC2541 using I2C protocol The sensors that run on I2C protocol are the ADXL345 used for acceleration and movement measurements the 511132 used for visual IR and UV light measurements the 006 used for ambient temperature measurements and the SI1143 which is used for the heart rate monitoring by using an array of Red and IR LEDs with the optical sensor for pulse oximetry In addition to these sensors we implemented firmware for a FM24V10 FRAM IC which communicates to our MCU using I2C and provides our device the use of 128KB of external FRAM In regards to overall implementation and integration of our system using these sensors software was written in the MCU application layer to initialize and poll our sensors in specified intervals to gather the sensor data and store it to FRAM Software code for polling our sensors was written with the limitation of our 128KB FRAM in mind With 128KB of FRAM and all data being 11 bytes it was decided that the accelerometer was polled every 1 minute and all other sensors every 15 minutes This gave us a total of 60 motion samples an hour while giving us 4 samples of light temperature and heart rate every 15 minutes In addition to all the software and hardware integration code we implemented a UTC clock
22. include hal drivers h include bcomdef h include OSAL h include OSAL PwrMgr h include OnBoard h include hal adc h include hal led h include hal keys h include hal i2c h include gatt h include hci h include gapgattserver h include gattservapp h dif defined PLUS BROADCASTER include peripheralBroadcaster 1 lt include peripheral h endif include gapbondmgr h if defined FEATURE_OAD include oad h include oad_target h endif Services include st_util h include devinfoservice st h 41 include irtempservice h include accelerometerservice h include humidityservice h include magnetometerservice h include barometerservice h include gyroservice h include testservice h include simplekeys h include ccservice h Sensor drivers include sensorTag h include hal sensor h include hal irtemp h include hal acc h include hal humi h include hal mag h include hal bar hi include hal gyro h include stdio h define 1 1 define BYTE2 2 Change I2C Address to SI1143 void 511143 Select HalI2CInit SI1143 I2C ADDRESS i2cClock 533KHZ int SI1143 begin uint8 registerPointer 1 511146 Select bool success HalSensorReadReg SI1143 REG PART ID uint8 amp registerPointer BYTE1 printf nREGISTERPOINTER x n registerPointer if success if registerPoint
23. keys h include hal i2c h include gatt h include hci h include gapgattserver h include gattservapp h iif defined PLUS BROADCASTER include peripheralBroadcaster h 1 lt include peripheral h endif include gapbondmgr h if defined FEATURE_OAD include oad h include oad target h endif Services include st_util h include devinfoservice st h include irtempservice h include accelerometerservice h include humidityservice h include magnetometerservice h include barometerservice h include gyroservice h include testservice h include simplekeys h include ccservice h Sensor drivers include sensorTag h 32 include hal sensor h include hal irtemp h include hal acc h include hal humi h include hal mag h include hal bar h include hal gyro h include stdio h define 1 1 define BYTE2 2 void 511132 WriteParameters char target char parameters void 511132 Select HalI2CInit SI1132 I2C ADDRESS i2cClock 533KHZ int SI1132 begin uint8 registerPointer SI1132 Select bool success HalSensorReadReg SI1132 REG PARTID uint8 amp registerPointer printf nREGISTERPOINTER x n registerPointer if success if registerPointer 0x32 printf 1 return 1 look for SI1132 DEVICE FOUND Reset SI1132 Registers printf 0 return 0 void SI1132 RESETFUNCTION uint8 v
24. out of battery simply recharge it with the included mini USB and remember to sync the new date and time using the Circadian Rhythm Analyzer application Failure to resync the time will prevent the Circadian Rhythm Monitor from gathering data 18 Appendix F Bluetooth Low Energy UUID Table Bluetooth Low Energy Protocol is used for the MCU on our device to communicate with a phone synchronizing with it For debugging purposes there are Bluetooth profiles and services created for each of our sensors as well as FRAM However our actual application only needs to worry about the timeservice and framservice Bluetooth profiles The following list contains the UUID for each of the sensor s Bluetooth services ADXL345 Service UUID accelerometerservice c ADXL345 Data UUID TMP006 Service UUID irtempservice c TMP006 Data UUID 511132 Service UUID SI1132service c 511132 Data UUID 511143 Service UUID bpmservice c 511143 Data UUID FRAM Service UUID framservice c FRAM Service Data UUID TIME Service UUID TIME MONTH UUID TIME DAY UUID TIME YEAR UUID TIME HOUR UUID TIME MIN UUID Operation F000AA10 0451 4000 B000 00000000 0000 As stated above the only profiles our application is truly dependent on are the services under the Time Service and the FRAM service The Time service is important because when the MCU and phone connect via Bluetooth the phone writes to the time service s UUIDs DD10 DD17 which are month day year ho
25. replace trim if type equals Temperature Log d TAG IN HERE type Log d TAG IN HERE UTC double Long parseLong utc Log d TAG IN HERE SKINTEMP Double parseDouble skin_temp data add new GraphViewData double Long parseLong utc Double parseDouble skin_temp 114 catch IOException ex H handle exception finally try reader close catch IOException H handle exception GraphView graphView new LineGraphView this Skin Temperature Fahrenheit graphView setCustomLabelFormatter new CustomLabelFormatter Override public String formatLabel double value boolean isValueX if isValueX return getDateCurrentTimeZone long value return null GraphViewData input new GraphViewData data size for int i 0 i lt input length i input i data get i H add data graphView addSeries new GraphViewSeries input set view port start 2 size 40 graphView setViewPort 2 40 graphView setScrollable true H optional activate scaling zooming graphView setScalable true LinearLayout layout LinearLayout findViewByld R id graph1 layout addView graphView private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getInstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timestamp 1000 calendar add Calendar MILLISECON
26. second getDateCurrentTimeZone corrected_UTC String third String valueOf mag String fourth String valueOf UTC String entries first second third fourth split writer writeNext entries break case 2 LIGHT Log d TAG getDateCurrentTimeZone long UTC LIGHT DATA data_ string LIGHT_Obj light data new LIGHT_Obj UTC data_string if realTime true _realTimeVISdata setText Visible Light light data getVIS lux _realTimelRdata setText IR Light light data getlR _realTimeUVdata setText UV Light light data getUV else float visible light data getVIS float light data getIR float uv light data getUV H Check for small values if visible lt 0 001 ir lt 0 001 uv lt 0 001 break JI LIGHT DATA HOLDER add light data II CSV CSV CSV String first Visible String second getDateCurrentTimeZone corrected UTC String third Float toString visible String fourth String valueOf UTC String entries first second third fourth split writer writeNext entries II CSV CSV CSV String first2 IR String second2 getDateCurrentTimeZone corrected UTC String third2 Float toString ir String fourth2 String valueOf UTC String entries2 first2 second2 third2 fourth2 split writer writeNext entrie
27. synchronized with and transmitted to an appropriate peripheral device post processing is performed and the data is displayed in either data vs time formatting or as raw measurements in a csv file The system enables an individual to conveniently view data on their smartphone and continually log data in hopes of drawing conclusions about how they can improve the quality and regularity of their sleep and circadian rhythm 3 Hardware Design The following diagram shows a very high level view of our system and each of its components The individual components and the necessary supporting circuitry can be seen in Appendix A Schematic The PCB layout of our final iteration of our system can be seen in Appendix B Board Layout Additionally the necessary Bill of Materials and the project cost can be seen in Appendix C Bill of Materials and Appendix D Project Costs Mini USB Battery Charger LiPo Battery Buck Converter Switching Regulator CC2541 Microcontroller BLE Antenna Sensors Accelerometer Heart Rate Sensor Ambient UV Light Sensor Skin Temperature Sensor Figure 2 Hardware Block Diagram 3 1 Sensor Subsystem Accelerometer The Analog Devices ADXL345 3 axis accelerometer was used as the motion sensor The ADXL345 operates with a 3 3V supply voltage The component was chosen for several reasons including ultra low power consumption 1 C interfacing and digital output data Heart Rate The Silicon
28. text SimpleDateFormat import java util Calendar import java util Date import java util TimeZone public class BPM_Obj implements Serializable private String date private String data public BPM_Obj Integer UTC String data this date getDateCurrentTimeZone UTC this data data private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getlnstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timestamp 1000 calendar add Calendar MILLISECOND 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone Exception e return CopyOfGrapher java package com example android bluetoothlegatt import java util ArrayList import com jjoe64 graphview GraphView import com jjoe64 graphview GraphView GraphViewData import com jjoe64 graphview GraphViewSeries import com jjoe64 graphview LineGraphView import android app Activity import android os Bundle import android util Log import android widget LinearLayout public class CopyOfGrapher extends Activity private ArrayLists ADXL_Obj gt ADXL DATA Iprivate ArrayList lt LIGHT_Obj gt LIGHT DATA ArrayList lt LIGHT_Obj gt getIntent getSerializableExtra light data ArrayList lt BPM_Obj gt BPM DATA ArrayList lt BPM_Obj gt getIntent getSerializableExt
29. the previously selected device name and address and maintains the connection to the selected device It also performs various error handling throughout sortData Takes the input data and parses through it to determine its header data fields and time Time is then converted from UTC to a meaningful value Using the header bit the code determines which type of data it is light motion etc and calls the relevant data type _Obj to convert the raw data into meaningful data If all data checks out then it is added to the end of the CSV file created in onCreate and if Real Time is selected updates the corresponding value on the display getDateCurrentTimeZone Used to convert from UTC into meaningful Date and Time onCreate Sets up and maintains BLE connection and parameters It also determines actions from buttonclicks BluetoothGattCharacteristic and readCharacteristicValue Necessary BLE methods used for connection and reading data from the device real_time Reads the values of specific BLE characteristics motion light and temperature sync_counter Reads the value of the FRAM BLE characteristic sorts the value based on the header and increments a counter to show the progress sync_timer Reads the value of the each of the respective time BLE characteristics month day year hour minute This section of code is associated with init_option_select xml AndroidManifest xml The main purpose of this section is to
30. which gets the current time and date upon phone mcu synchronization and stores it into Unix Time Code format This was done in order to compensate for not having a RTC implemented in our design 4 3 Android Application User Interface and Software Design Software was written for Android OS devices using java The Android application serves as the primary user interface for interacting with their device and collected data The application provides two modes of data collection analysis a real time mode and a synchronize store more The following diagrams demonstrates the use of the Android application aS F 04 fH 12 12 PM Sync Phone Read CSV File Select a file below 2014 12 05 13 48 circadianrhythm csv 2014 12 04 19 30 circadianrhythm csv Figure 3 Splash Screen and Device Selection Screen The initial screen a user is presented with allows them to select between syncing the phone or viewing the collected data stored on the Android Device e Sync Phone allows the user to synchronize the device s date and time settings to match the Android Device synchronize the data from device to the Android device or enable real time data viewing e Read CSV File allows the user to select an available CSV file stored on the Android device s memory Upon selecting Sync Phone the user is presented with the next screen listing devices that implement Bluetooth Low Energy A device listed as Circadian Rhythm should be selecte
31. 1 value pointer 0x84 HalSensorWriteReg SI1143 REG MEAS RATE amp value pointer BYTE1 value pointer 0x08 HalSensorWriteReg SI1143 REG ALS RATE amp value pointer BYTE1 value pointer 0x08 HalSensorWriteReg SI1143 REG PS RATE amp value_pointer BYTE1 43 Current setting for LEDs pulsed while taking readings PS LED21 Setting for LEDs 1 amp 2 LED 2 is high nibble each LED has 16 possible 0 F in hex possible settings read the value pointer 0x38 HalSensorWriteReg SI1143 REG PS LED21 amp value pointer BYTE1 value pointer 0x03 HalSensorWriteReg SI1143 REG PS LED3 amp value_pointer BYTE1 Serial print PS LED21 Serial println getReg PulsePlug PS LED21 BIN Serial print CHLIST Serial println readParam 0x01 BIN SI1143 WriteParameters SI1143 PARAM CH LIST 0x77 writeParam PulsePlug PARAM CH LIST 0x77 all measurements on increasing PARAM PS ADC GAIN will increase the LED on time and ADC window you will see increase in brightness of visible LED s ADC output amp noise datasheet warns not to go beyond 4 because chip or LEDs may be damaged SI1143 WriteParameters SI1143 PARAM PS ADC GAIN 0x00 writeParam PulsePlug PARAM PS ADC GAIN 0x00 You can select which LEDs are energized for each reading The settings below turn on only the LED that normally would be read ie LED1 is pulsed and read first then LED2 is pulsed and r
32. 12SEL PS2NONE 0x00 511132 PARAM PSLED12SEL PS2LED1 0x10 511132 PARAM PSLED12SEL PS2LED2 0x20 SI1132 PARAM PSLED12SEL PS2LED3 0x40 511132 PARAM PSLED12SEL PS1NONE 0x00 511132 PARAM PSLED12SEL 511 1 0x01 511132 PARAM PSLED12SEL 511 2 0x02 511132 PARAM PSLED12SEL 511 0x04 SI1132 PARAM PSLED3SEL 0x03 SI1132 PARAM PSENCODE 0x05 511132 PARAM ALSENCODE 0x06 SI1132 PARAM PS1ADCMUX 0x07 SI1132 PARAM PS2ADCMUX 0x08 SI1132 PARAM PS3ADCMUX 0x09 511132 PARAM PSADCOUNTER x A 511132 PARAM PSADCGAIN 511132 PARAM PSADCMISC 0x0C SI1132 PARAM PSADCMISC RANGE 0x20 SI1132 PARAM PSADCMISC PSMODE 0x04 511132 PARAM ALSIRADCMUX OxOE 511132 PARAM AUXADCMUX SI1132 PARAM ALSVISADCOUNTER 0x10 511132 PARAM ALSVISADCGAIN 0x11 30 define define define define define define define define define SI1132 PARAM ALSVISADCMISC 0x12 SI1132 PARAM ALSVISADCMISC VISRANGE 0x20 511132 PARAM ALSIRADCOUNTER Ox1D SI1132 PARAM ALSIRADCGAIN 0x1E 511132 PARAM ALSIRADCMISC x1F SI1132 PARAM ALSIRADCMISC RANGE 0x20 SI1132 PARAM ADCCOUNTER 511CLK 0x70 SI1132 PARAM ADCMUX SMALLIR 0x00 SI1132 PARAM ADCMUX LARGEIR 0x03 REGISTERS define define define define define define define define define define define define define define define define define define define define define define define define define define define define define define define define define define defi
33. 3 Select this sensor on the I2C bus HalIRTempSelect Read the data ready bit success HalSensorReadReg TMP006 REG ADDR CONFIG uint8 amp v IRTEMP REG LEN if v amp DATA RDY BIT amp amp success return irtSensorState irtSensorState 006 DATA READY OR OE S R ERER IR fn HalIRTempTest brief Run a sensor self test return TRUE if passed FALSE if failed bool HalIRTempTest void t uint16 val Select this sensor on the I2C bus HalIRTempSelect Check manufacturer ID ST_ASSERT HalSensorReadReg TMP006_REG_MANF_ID uint8 amp val IRTEMP_REG_LEN val LO_UINT16 val lt lt 8 HI_UINT16 val ST_ASSERT val TMP006_VAL_MANF_ID Reset sensor ST_ASSERT HalSensorWriteReg TMP006_REG_ADDR_CONFIG configSensorReset IRTEMP_REG_LEN Check config register reset ST_ASSERT HalSensorReadReg TMP006_REG_ADDR_CONFIG uint8 amp val IRTEMP_REG_LEN val LO_UINT16 val lt lt 8 HI_UINT16 val ST_ASSERT val 006 VAL CONFIG RESET Turn sensor off ST ASSERT HalSensorWriteReg TMPO006 REG ADDR CONFIG configSensorOff IRTEMP REG LEN Check config r
34. 4 define 006 TREF 298 15 define 006 A2 0 00001678 define TMP006 A1 0 00175 define 006 50 6 4 static IRTemperature States t irtSensorState 006 OFF 0x80 0x00 Sensor reset 0x00 0x80 Sensor standby 0x70 0x00 Conversion time 0 25 sec static uint8 configSensorReset 2 static uint8 configSensorOff 2 static uint8 configSensorOn 2 60 Public functions SR Se REEL EAE ook i E OR ORI UK SENE fn HALIRTempInit brief Initialise the temperature sensor driver return none sk sk sk k 5k 5 KR KOR R kk ke kk kk ek KOR void HALIRTempInit void d irtSensorState 006 OFF HallIRTempTurnOff OR Oe fn HalIRTempTurnOn brief Turn the sensor on return none ee es kk void HalIRTempTurnOn void t HalDcDcControl ST_IRTEMP true HalIRTempSelect if HalSensorWriteReg TMP 06_REG_ADDR_CONFIG configSensorOn IRTEMP_REG_LEN d irtSensorState 006 IDLE
35. 4 graphview GraphView import com jjoe64 graphview GraphView GraphViewData import com jjoe64 graphview GraphViewSeries import com jjoe64 graphview LineGraphView import android app Activity import android content Intent import android os Bundle import android os Environment import android util Log import android view View import android widget AdapterView import android widget ArrayAdapter import android widget Button import android widget ExpandableListView import android widget LinearLayout import android widget ListView import android widget TextView public class csv data selector extends Activity public static String filename null public static String EXTRAS FILE NAME private final static String TAG csv data selector class getSimpleName protected void onCreate Bundle savedinstanceState super onCreate savedinstanceState setContentView R layout csv_dataviews Bundle extras csv data selector this getlntent getExtras filename extras getString EXTRAS FILE public void onClick View if v getld R id viewADXL Intent ADXLintent new Intent this ADXL_GRAPHER class ADXLintent putExtra EXTRAS FILE filename startActivity ADXLintent 81 Jelse if v getld R id viewVISLIGHT Intent LIGHTintent new Intent this VISLIGHT_GRAPHER class LIGHTintent putExtra EXTRAS FILE filename startActivity LIGHTintent else if
36. 43 REG PARAM WR define SI1143 REG COMMAND define SI1143 REG RESPONSE define 511143 REG IRQ STATUS define SI1143 REG ALS VIS DATAO define 511143 REG ALS VIS DATA1 define SI1143 REG ALS IR DATAO define SI1143 REG ALS IR DATA1 define SI1143 REG PS1 DATAO define SI1143 REG PS1 DATA1 define SI1143 REG PS2 DATAO define 511143 REG 52 DATA1 define 511143 REG bai DATAO define 511143 REG 53 DATA1 define SI1143 REG AUX DATAO define SI1143 REG AUX DATA1 define SI1143 REG PARAM RD define 511143 REG CHIP STAT define 511143 REG ANA IN KEY define 511143 REG ANA IN KEY2 define 511143 REG ANA IN define 511143 REG ANA IN KENYA define 511143 I2C ADDRESS 0x5A void 511143 WriteParameters char target char parameters 40 void SI1143 initPulseSensor void void SI1143 readPulseSensor void void SI1143 Select void int SI1143 begin void uint8 SI1143 ReadParameters char target void SI1143 WriteParameters char target char parameters void SI1143 initPulseSensor void float smooth float data float filterVal float smoothedVal uint8 SI1143 ReadRESPONSE void uint16 511143 ReadVisible void uint16 511143 ReadIR void uint16 511143 ReadPS1 void uint16 511143 ReadPS2 void uint16 511143 ReadPS3 void uint16 511143 ReadAUX void void fetchData void void fetchLedData void bool constrain int x int a int b void SI1143 readPulseSensor void 11143 C include SI1143 h
37. 64 graphview GraphView import com jjoe64 graphview GraphView GraphViewData import com jjoe64 graphview GraphViewSeries import com jjoe64 graphview LineGraphView import android app Activity import android os Bundle import android os Environment import android util Log import android widget LinearLayout public class ADXL_GRAPHER extends Activity private final static String TAG ADXL_GRAPHER class getSimpleName String file String H getintent getSerializableExtra EXTRAS FILE String file sdcard abc csv public static String file protected void onCreate Bundle savedinstanceState super onCreate savedinstanceState setContentView R layout test Bundle extras ADKL GRAPHER this getlntent getExtras ArrayList lt GraphViewData gt data new ArrayList lt GraphViewData gt file extras getString EXTRAS_FILE_NAME file Environment getExternalStorageDirectory file II file sdcard file BufferedReader reader null try reader new BufferedReader new FileReader file catch FileNotFoundException e1 TODO Auto generated catch block e1 printStackTrace 67 try String line while line reader readLine null String RowData line split String type RowData 0 replace trim String date RowData 1 replace trim String magnitude RowData 2 replace trim String utc
38. 7 static void HalAccSelect void Set up I2C that is used to communicate with 5 21 HalI2CInit ADXL345 ADDRESS i2cClock 267KHZ float calcAccel int8 rawX uint8 range 1 float v switch range case HAL ACC RANGE 2G calculate acceleration range 2 2 v rawX 1 0 256 4 break case HAL ACC RANGE 4G calculate acceleration unit G range 4 44 rawX 1 0 256 8 break case HAL ACC RANGE 4G calculate acceleration range 8 8 rawX 1 0 256 16 break return v 77 J PS PE PR 5 sk sk ok ok ok HAL IRTEMP H ifndef HAL IRTEMP H define HAL IRTEMP H ifdef _ cplusplus extern C endif PE k k ak k ak k INCLUDES WA include comdef h oR ok 58 CONSTANTS 7 PE E TYPEDEFS typedef enum 006 OFF IR Temperature Sleeping 006 IDLE IR Temperature O
39. ARAM PS1ADCMUX 511132 PARAM ADCMUX LARGEIR prox sensor 1 uses LED 1 511132 WriteParameters SI1132 PARAM PSLED12SEL 511132 PARAM PSLED12SEL PS1LED1 fastest clocks clock div 1 SI1132 WriteParameters SI1132 PARAM PSADCGAIN 0 take 511 clocks to measure S11132 WriteParameters SI1132 PARAM PSADCOUNTER S11132 PARAM ADCCOUNTER 511CLK in prox mode high range S11132 WriteParameters SI1132 PARAM PSADCMISC SI1132 PARAM PSADCMISC RANGE SI1132 PARAM PSADCMISC PSMODE 511132 WriteParameters SI1132 PARAM ALSIRADCMUX S11132 PARAM ADCMUX SMALLIR fastest clocks clock div 1 S11132 WriteParameters SI1132 PARAM ALSIRADCGAIN 0 take 511 clocks to measure 511132 WriteParameters SI1132 PARAM ALSIRADCOUNTER 511132 PARAM ADCCOUNTER 511CLK in high range mode 511132 WriteParameters SI1132 PARAM ALSIRADCMISC S11132 PARAM ALSIRADCMISC RANGE 35 fastest clocks clock div 1 511132 WriteParameters SI1132 PARAM ALSVISADCGAIN 0 take 511 clocks to measure 511132 WriteParameters SI1132 PARAM ALSVISADCOUNTER 511132 PARAM ADCCOUNTER 511CLK in high range mode not normal signal 511132 WriteParameters SI1132 PARAM ALSVISADCMISC 511132 PARAM ALSVISADCMISC VISRANGE void 511132 AutoMeasure void measurement rate for auto uint8 value pointer value pointer OxFF HalSensorWriteReg SI1132 REG MEASRATEO amp value_pointer BYTE1 255 31 25uS 8ms auto run value poi
40. ATT CONNECTED 2 OK else if BluetoothLeService ACTION_GATT_DISCONNECTED equals action mConnected false updateConnectionState R string disconnected invalidateOptionsMenu clearUI Log i ON GATT DISCONNECTED OK else if BluetoothLeService ACTION_GATT_SERVICES_ DISCOVERED equals action 1 Show all the supported services and characteristics on the II user interface Log i ON GATT SERVICE DISCOVERED OK getGattServices mBluetoothLeService getSupportedGattServices Log i ON DISPLAYED SERVICES OK else if BluetoothLeService ACTION DATA AVAILABLE equals action Log i ON GATT DATA AVAILABLE OK displayData intent getStringExtra BluetoothLeService EXTRA_DATA E private void updateConnectionState final int resourceld runOnUiThread new Runnable Override public void run mConnectionState setText resourceld Ir private void displayData String data if data null if data length 45 H Log d TAG data length if realTime false mDataField setText data substring data length 34 data length 1 replace else mDataField setText REAL TIME MODE 97 sortData data substring data length 34 data length 1 replace else mDataField setText data private void sortData String data Log d TAG data String delimitString data split Log d TAG delimitS
41. B byte1 pBuf 4 LSB byte2 pBuf 5 HI UINT16 pBuf 6 LO UINT16 pBuf 7 HI UINT16 pBuf 8 LO UINT16 pBuf 9 HI UINT16 55 pBuf 10 LO UINT16 z printf HIGH u n HI UINT16 x printf HIGH x n HI UINT16 x printf LOW u n LO UINT16 x printf LOW x n LO_UINT16 x printf HIGH LOW u n BUILD UINT16 LO UINT16 x HI UINT16 x printf HIGH LOW x n BUILD UINT16 LO UINT16 x HI UINT16 x Turn off sensor HalSensorWriteReg ADXL345 REG POWER CTL amp value pointer 1 HalSensorWriteReg ADXL345 REG POWER CTL amp accSensorOff sizeof accSensorOff return success sk ok ok fn 1 brief Read data from the accelerometer X Y Z 3 bytes return TRUE if valid data FALSE if not SC bool HalAccRead uint8 pBuf uint8 x uint8 y uint8 z bool success Select this sensor HalAccSelect Turn on sensor HalSensorWriteReg ACC REG ADDR CTRL REG1 amp accSensorConfig sizeof accSensorConfig Wait for measurement ready appx 1 45 ms ST HAL DELAY 180 Read the three registers success HalSensorReadReg ACC REG ADDR XOUT amp x sizeof x if success t success HalSensorReadReg ACC
42. BluetoothLeService null private static IntentFilter makeGattUpdatelntentFilter final IntentFilter intentFilter new IntentFilter intentFilter addAction BluetoothLeService ACTION_GATT_CONNECTED intentFilter addAction BluetoothLeService ACTION GATT DISCONNECTED intentFilter addAction BluetoothLeService ACTION GATT SERVICES DISCOVERED intentFilter addAction BluetoothLeService ACTION DATA AVAILABLE return intentFilter private void getGattServices List lt BluetoothGattService gt gattServices if gattServices null return String null ArrayList lt HashMap lt String String gattServiceData new ArrayList lt HashMap lt String String gt gt ArrayList lt ArrayListcHashMap lt String String gt gt gt gattCharacteristicData new ArrayList lt ArrayList lt HashMap lt String String gt gt gt mGattCharacteristics new ArrayList lt BluetoothGattCharacteristic gt H Loops through available GATT Services for BluetoothGattService gattService gattServices HashMap lt String String gt currentServiceData new HashMap lt String String gt uuid gattService getUuid toString currentServiceData put LIST_NAME iBeacon currentServiceData put LIST UUID uuid gattServiceData add currentServiceData ArrayList lt HashMap lt String String gattCharacteristicGroupData new ArrayList lt HashMap lt String String gt gt List lt BluetoothGattCharacteristic gt gattCh
43. CTIME H ifndef UTCTime H define UTCTime H endif UTCTime H int32 calculateUTCTime uint8 month uint8 day uint8 year uint8 hour uint8 min UTCTIME C include hal drivers h int32 calculateUTCTime uint8 month uint8 day uint8 year uint8 hour uint8 months is months since January 0 11 year only has last 2 digits hours is in military 0 24 int32 secs day 86400 int32 secs hour 3600 int32 secs min 60 int32 secs year 31536000 int monthDays 0 switch month 46 case 0x01 monthDays 31 31 break case 0x02 monthDays 59 28 break case 0x03 monthDays 90 31 break case 0x04 monthDays 120 30 break case 0x05 monthDays 151 31 break case 0x06 monthDays 181 30 break case 0x07 monthDays 212 31 break case 0x08 monthDays 242 30 break case 0x09 monthDays 273 31 break case 0x0a monthDays 303 30 break case 0x0b monthDays 334 31 break int 1 2000 year int years since 1970 1 1970 int leapyears years since 1970 4 1 yearSeconds years since 1970 secs year leapyearSeconds leapyears secs day monthSeconds monthDays secs day daySeconds day secs day test yearSeconds leapyearSeconds monthSeconds daySeconds hourSeconds hour secs hour minSeconds min secs min 4 HOURS TO GET GMT UTC TIME FROM EST estToGMT 4 secs hou
44. Connect request result result Override protected void onPause super onPause unregisterReceiver mGattUpdateReceiver Override protected void onDestroy super onDestroy unbindService mServiceConnection mBluetoothLeService null Override public boolean onCreateOptionsMenu Menu menu getMenulnflater inflate R menu gatt services menu if mConnected menu findltem R id menu connect setVisible false menu findltem R id menu disconnect setVisible true else menu findltem R id menu connect setVisible true menu findltem R id menu disconnect setVisible false return true Override public boolean onOptionsltemSelected Menultem item switch item getltemld case R id menu_connect mBluetoothLeService connect mDeviceAddress return true case R id menu disconnect mBluetoothLeService disconnect 87 return true case android R id home onBackPressed return true return super onOptionsltemSelected item private void updateConnectionState final int resourceld runOnUiThread new Runnable Override public void run mConnectionState setText resourceld D private void displayData String data if data null mDataField setText data Demonstrates how to iterate through the supported GATT Services Characteristics this sample we populate the data structure that is bound to the ExpandableListVi
45. D 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone catch Exception e return 115 int num 150 double v 0 for int i20 i lt num i v 0 2 Si TMPO006 Obj java package com example android bluetoothlegatt import static java lang Math pow import java io Serializable import java text SimpleDateFormat import java util Calendar import java util Date import java util TimeZone import android util Log public class TMP006_Obj implements Serializable private String date private String data private byte value new byte 4 private double ambient private double target public TMP006_Obj Integer UTC String data this date getDateCurrentTimeZone UTC this data data Log d TEMPERATURE HELLO data String delimit data split byte vLSB byte int Integer parselnt delimit 2 16 amp OxFF byte vMSB byte int Integer parselnt delimit 3 16 amp OxFF byte tLSB byte int Integer parselnt delimit 4 16 amp OxFF byte tMSB byte int Integer parselnt delimit 5 16 amp OxFF byte value VMSB vLSB tMSB tLSB this ambient extractAmbientTemperature value this target extractTargetTemperature value ambient 116 private String getDateCurrentTimeZone long timestamp try Cale
46. D ADXL345 DATARATE 100 HZ x A 50Hz Bandwidth 140A IDD ADXL345 DATARATE 50 HZ 0x09 25 2 Bandwidth 90pA IDD ADXL345 DATARATE 25 HZ 0x08 12 5Hz Bandwidth 60pA IDD ADXL345 DATARATE 12 5 HZ 0x07 6 25Hz Bandwidth 5 uA IDD ADXL345 DATARATE 6 25HZ 0x06 3 13Hz Bandwidth 45 IDD ADXL345 DATARATE 3 13 HZ 0x05 1 56Hz Bandwidth 4 uA IDD ADXL345 DATARATE 1 56 HZ 0x04 0 78Hz Bandwidth 34A IDD ADXL345 DATARATE 0 78 HZ 0x03 0 39Hz Bandwidth 23 IDD ADXL345 DATARATE 0 39 HZ 0x02 0 20Hz Bandwidth 23 IDD ADXL345 DATARATE 0 20 HZ 0x01 0 10Hz Bandwidth 23 IDD ADXL345 DATARATE 0 10 HZ 0x00 0 05Hz Bandwidth 23pA IDD default value dataRate t Used with register 0x31 ADXL345 REG DATA FORMAT to set g range typedef enum ADXL345 RANGE 16 0x03 16g ADXL345 RANGE 8 G 0x02 8g ADXL345 RANGE A 0 01 4g ADXL345 RANGE 2 6 0x00 2g default value range t 52 Local Functions static uint8 accSensorConfig static uint8 accSensorOff static uint8 accRange FR KKK fn HalAccInit brief This function initializes the HAL Accelerometer abstraction layer return None void HalAccInit void sk Pk ok ok
47. D heart rate Low Debounce Button 13 10 N N Value Description 1uF 4 7uF 15uF 1uF 10uF 10uF 15pF 0 1uF 220pF 1uF 12pF 10uH SMD BLE Antenna Chip Balun 511143 511132 CC2541 256k TPS62203 FM24V10 FRAM ADXL345BCCZ 006 LM3658 UX60 MB 5s8 JST 2mm male CC debugger header FA 20H 32MHz 32 768KHz Red LED Green LED Red MCU LEDs HR IR LED HR RED LED SPDT Switch Plastic Standoffs Metal Standoffs R1 R2 R19 R21 R8 R10 R11 R9 R4 R5 R13 R16 R17 R20 R18 3 7V LiPo Battery 14 0 156 threaded 0 156 threaded 0 330 56K 750 2 7K 1K 30 Appendix D Project Costs Prototype Costs Discrete Components Resistors Caps Inductors LEDs Crystals 25 ICs Sensors Memory Microcontroller Power Management 40 Battery 5 Mechanicals Mounting Connectors 3D Enclosure Print PCB 15 Total Costs for Single Device 85 when ordering minimum quantity of parts Development Costs Our development costs consisted mostly of eval boards for system components two PCB revisions and the components required to populate those PCBs Evaluation Boards Development Tools Cost 218 e MSP430G2 LaunchPad 12 x 2 e CC2541 SensorTag Development Kit 26 e CC Debugger 50 e TMP006 Evaluation Kit 25 e 51114 Evaluation Kit 60 Rev A Boards x 6 75 Rev B PCB Boards x 3 24 All Components for PCBs 300 Hunt Library 3D Printi
48. HT DATA HOLDER intent putExtra bpm data 107 BPM DATA HOLDER intent putExtra tmpO06 data 006 DATA HOLDER startActivity intent D new Thread runnable start private void sync timer final Handler handler new Handler Runnable runnable new Runnable public void run while timerSends lt 5 try Thread sleep 500 catch InterruptedException e e printStackTrace handler post new Runnable public void run characteristic getCharac TIME_MONTH_CONFIG if characteristic null Log d TAG CHARACTERISTIC IS characteristic getUuid switch timerSends case 0 BluetoothGattDescriptor desc characteristic getDescriptor TIME DAY desc setValue new byte byte month gatt writeDescriptor desc break desc characteristic getDescriptor TIME DAY CONFIG desc setValue new byte byte day gatt writeDescriptor desc break 108 desc characteristic getDescriptor TIME DAY CONFIG desc setValue new byte byte year gatt writeDescriptor desc break desc characteristic getDescriptor TIME DAY CONFIG desc setValue new byte byte hour gatt writeDescriptor desc break desc characteristic getDescriptor TIME DAY CONFIG desc setValue new byte byte min gatt writeDescriptor desc break timerSends D
49. Labs Si1143 light sensor was chosen as the heart rate sensor The 511143 operates at 3 3V Using the widely employed heart rate measurement technique involving the sensing of light absorption by hemoglobin in blood i e pulse oximetry the Si1143 s capabilities were perfect for our desired application Using absorption measurements obtained from IR and Red visible light LEDs in conjunction with a software algorithm for processing the measurements the sensor was capable of obtaining accurate heart rate figures Additionally The 511143 was chosen for its FC interfacing and digital data output Ambient UV Light The Silicon Labs Si1132 light sensor was chosen as our ambient and UV light sensor The Si1132 operates at 3 3V The Si1132 is capable of simultaneously acquiring ambient and UV light readings making it a viable solution for our application Additionally The Si1132 was chosen for its FC interfacing low power consumption and digital data output Skin Temperature The Texas Instruments 006 thermocouple sensor was chosen for skin temperature measurement The 006 operates at 3 3V and obtains skin temperature measurements by absorbing IR energy emitted from an object it is pointed at subsequently reading the voltage change in its internal thermocouple array and outputting a temperature measurement Careful board layout considerations were taken into effect with the sensor in order to thermally isolate it from the rest of the circuit co
50. NTER define SI1143 PARAM PS ADC CLKDIV define 511143 PARAM PS ADC GAIN define SI1143 PARAM PS ADC MISC define 511143 ALS1 ADC define 511143 PARAM ALS2 ADC MUX define 511143 PARAM ALS3 ADC MUX define 511143 ALSVIS ADC COUNTER define 511143 ALSVIS ADC CLKDIV define SI1143 PARAM ALSVIS ADC GAIN define 511143 PARAM ALSVIS ADC MISC define SI1143 PARAM ALS HYST define SI1143 PARAM PS HYST define 511143 PARAM PS HISTORY 39 define SI1143 PARAM ALS HISTORY define 511143 PARAM ADC OFFSET define 511143 PARAM SLEEP CTRL define 511143 PARAM LED RECOVERY define 511143 PARAM ALSIR ADC COUNTER define SI1143 PARAM ALSIR ADC CLKDIV define 511143 ALSIR ADC GAIN define SI1143 PARAM ALSIR ADC MISC COMMANDS define SI1143 REG PART ID define 511143 REG REV ID define 511143 REG SEQ ID define SI1143 REG INT CFG amp define 511143 REG IRQ ENABLE define 511143 REG IRQ MODE1 define 511143 REG IRQ MODE2 define SI1143 REG HW KEY define SI1143 REG MEAS RATE define 511143 REG ALS RATE define SI1143 REG PS RATE define SI1143 REG ALS LOW THO define 511143 REG ALS LOW 1 define SI1143 REG ALS HI THO define 511143 REG ALS HI TH1 define SI1143 REG PS LED21 define SI1143 REG PS LED3 define SI1143 REG PS1 THO define 511143 REG 51 1 define 511143 REG bai THO define 511143 REG 52 1 define 511143 REG PS3 THO define 511143 REG PS3 1 define SI11
51. PRE define ACC REG ADDR INT SRC REG define ACC REG ADDR INT SRC REG2 define ACC REG ADDR STATUS REG tdefine ACC REG ADDR INT REL define ACC REG ADDR CTRL REGI R W define ACC REG ADDR CTRL REG2 R W define ACC REG ADDR CTRL REG3 R W define REG ADDR INT CTRL REG R W define ACC REG ADDR INT CTRL REG2 R W define ACC REG ADDR INT CTRL REG3 R W define ACC REG ADDR DATA CTRL REG R W define ACC REG ADDR TILT TIMER R W define ACC REG ADDR WUF TIMER R W define ACC REG ADDR TDT TIMER R W define ACC REG ADDR TDT H THRESH R W define ACC REG ADDR TDT L THRESH R W define ACC REG ADDR TDT TAP TIMER R W define ACC REG ADDR TDT TOTAL TIMER R W define ACC REG ADDR TDT LATENCY TIMER R W define ACC REG ADDR TDT WINDOW TIMER R W define ACC REG ADDR BUF CTRL1 R W define ACC REG ADDR BUF CTRL2 R W define ACC REG ADDR BUF STATUS REG R define ACC REG ADDR BUF STATUS REG2 R W define ACC REG ADDR BUF CLEAR W define ACC REG ADDR SELF TEST R W define ACC REG ADDR WUF THRESH R W define ACC REG ADDR TILT ANGLE R W define ACC REG ADDR HYST SET R W define ACC REG ADDR BUF READ R W Select register valies define REG VAL WHO AM I data sheet says 0x04 CTRL1 BIT MASKS define ACC REG CTRL PC Power control 1 On oi define ACC REG CTRL RES Resolution 1 High e define ACC REG CTRL DRDYE Data Ready 1 On EN define ACC REG CTRL GSEL HI Range 00 2g 501 define ACC REG CTRL GSEL LO 10 8g 11
52. R id CSV_FILES_LIST csv_list setAdapter new ArrayAdapter lt String gt this android R layout simple list item 1 FilesInFolder csv list setOnltemClickListener new AdapterView OnltemClickListener public void onltemClick AdapterView lt gt parent View v int position long id filename csv list getltemAtPosition position toString Log d TAG TESTING filename Intent graphintent new Intent getBaseContext csv data selector class graphintent putExtra EXTRAS FILE filename startActivity graphintent DeviceControlActivity java package com example android bluetoothlegatt import android app Activity import android bluetooth BluetoothGattCharacteristic import android bluetooth BluetoothGattService import android content BroadcastReceiver import android content ComponentName import android content Context import android content Intent import android content IntentFilter import android content ServiceConnection import android os Bundle import android os IBinder import android util Log import android view Menu import android view Menultem import android view View import android widget ExpandableListView import android widget SimpleExpandableListAdapter import android widget TextView import java util ArrayList import java util HashMap import java util List For a given BLE device this Activity provides the user interface to connect display dat
53. STATE DISCONNECTED Log i TAG Disconnected from GATT server broadcastUpdate intentAction 72 Log i STATE DISCONNECTED BROADCAST SENT if mConnectionState 123334 Override public void onServicesDiscovered BluetoothGatt gatt int status if status BluetoothGatt GATT_SUCCESS broadcastUpdate ACTION GATT SERVICES DISCOVERED Log i GATT SUCCESS SERVICES DISCOVERED OK else Log w TAG onServicesDiscovered received status Override public void onCharacteristicRead BluetoothGatt gatt BluetoothGattCharacteristic characteristic int status if status BluetoothGatt GATT_SUCCESS broadcastUpdate ACTION DATA AVAILABLE characteristic Override public void onCharacteristicChanged BluetoothGatt gatt BluetoothGattCharacteristic characteristic broadcastUpdate ACTION DATA AVAILABLE characteristic private void broadcastUpdate final String action final Intent intent new Intent action sendBroadcast intent Log i INTENT SENT OK private void broadcastUpdate final String action final BluetoothGattCharacteristic characteristic final Intent intent new Intent action II For all other profiles writes the data formatted in HEX final byte data 7 characteristic getValue if data null amp amp data length gt 0 final StringBuilder stringBuilder new StringBuilder data length for byte byteChar data stringBuild
54. TING 1 private static final int STATE_CONNECTED 2 public final static String ACTION_GATT_CONNECTED com example bluetooth le ACTION GATT CONNECTED public final static String ACTION DISCONNECTED com example bluetooth le ACTION GATT DISCONNECTED public final static String ACTION GATT SERVICES DISCOVERED com example bluetooth le ACTION GATT SERVICES DISCOVERED public final static String ACTION DATA AVAILABLE com example bluetooth le ACTION DATA AVAILABLE public final static String EXTRA DATA com example bluetooth le EXTRA DATA Implements callback methods for GATT events that the app cares about For example connection change and services discovered private final BluetoothGattCallback mGattCallback new BluetoothGattCallback Override public void onConnectionStateChange BluetoothGatt gatt int status int newState String intentAction if newState BluetoothProfile STATE CONNECTED Log i STATE CONNECTED OK intentAction ACTION_GATT_CONNECTED mConnectionState STATE CONNECTED broadcastUpdate intentAction Log i STATE CONNECTED BROADCAST SENT DISCOVERING SERVICES Attempts to discover services after successful connection mBluetoothGatt discoverServices Log i AFTER DISCOVER SERVICES OK else if newState BluetoothProfile STATE DISCONNECTED Log i STATE DISCONNECTED OK intentAction ACTION GATT DISCONNECTED mConnectionState
55. _REG_ADDR_YOUT_H amp y sizeof y if success t success HalSensorReadReg ACC REG ADDR ZOUT H amp z sizeof z 56 if success t Valid dat pBuf 0 X pBuf 1 y pBuf 2 7 Turn off sensor HalSensorWriteReg ACC REG ADDR CTRL REG1 amp accSensorOff sizeof accSensorOff return success J SRK OR GR ORE er fn HalAccTest brief Run a sensor self test return TRUE if passed FALSE if failed 7 bool HalAccTest void uint8 val Select this sensor on the I2C bus HalAccSelect Check the DCST RESP pattern 0x55 ST ASSERT HalSensorReadReg ACC REG ADDR DCST RESP amp val 1 ST ASSERT val 0x55 Check the DCST RESP pattern xAA val 0x10 Sets the DCST bit ST ASSERT HalSensorWriteReg ACC REG ADDR CTRL REG3 amp val 1 ST ASSERT HalSensorReadReg ACC REG ADDR DCST RESP amp val 1 ST ASSERT val 0xAA Check the WHO AM I register ST ASSERT HalSensorReadReg ACC REG ADDR WHO AM I amp val 1 ST ASSERT val REG VAL WHO AM I return TRUE kk kok k k fn HalAccSelect 57 brief Select the accelerometer on the I2C bus return
56. a and display GATT services and characteristics supported by the device The Activity communicates with code BluetoothLeService which in turn interacts with the Bluetooth LE API 84 public class DeviceControlActivity extends Activity private final static String TAG DeviceControlActivity class getSimpleName public static final String EXTRAS DEVICE NAME DEVICE NAME public static final String EXTRAS DEVICE ADDRESS DEVICE ADDRESS private TextView mConnectionState private TextView mDataField private String mDeviceName private String mDeviceAddress private ExpandableListView mGattServicesList private BluetoothLeService mBluetoothLeService private ArrayList lt ArrayList lt BluetoothGattCharacteristic gt gt mGattCharacteristics new ArrayList lt ArrayList lt BluetoothGattCharacteristic gt gt private boolean mConnected false private BluetoothGattCharacteristic mNotifyCharacteristic private final String LIST NAME NAME private final String LIST UUID UUID Code to manage Service lifecycle private final ServiceConnection mServiceConnection new ServiceConnection Override public void onServiceConnected ComponentName componentName IBinder service mBluetoothLeService BluetoothLeService LocalBinder service getService mBluetoothLeService initialize if ImBluetoothLeService initialize Log e TAG Unable to initialize Bluetooth finish 1 Aut
57. acc c amp hal acc h The ADXL345 is used to measure acceleration and movement for a user wearing the device The following functions are used for the ADXL345 to be operational Functions Void HalAccSelect This function lets the MCU initialize an i2c connection with the ADXL345 void setRange range t range This sets and calibrates the range and sensitivity the ADXL345 will read measurements our design uses a 16G calibration bool readAcc uint8 pBuf int32 UTCTime reads X Y Z acceleration measurements and puts it into the FRAM data array holder Operation The ADXL345 is polled every minute Once the polling of the ADXL345 is enabled by the main MCU software Sensortag c the function readAccData Time is called This function takes in the time passed by the caller and processes it like the other functions Inside the readAccData function readAcc is called which sets up the ADXL345 sensor by initializing the i2c connection and calibrating its sensor Once calibration is done the registers containing the X Y and Z measurements 2 byte values are read into the FRAM data array holder The array data holder format in big endian is shown below Header UTCmsb1 UTCmsb2 UTCIsb1 UTCIsb2 xMSB xLSB yMSB yLSB zMSB zLSB Note The Header value for any ADXL345 is always 1 This value is used for our Bluetooth communication between MCU and Phone as the phone will be able to decode which data it is by the header FM24V10 FRAM
58. activity detection define ADXL345 REG THRESH FF 0x28 Free fall threshold define ADXL345 REG TIME FF 0x29 Free fall time define ADXL345 REG AXES 0x2A Axis control for single double tap define ADXL345 REG STATUS 0x2B Source for single double tap define ADXL345 REG BW RATE 0x2C Data rate and power mode control define ADXL345 REG POWER CTL 0x2D Power saving features control define ADXL345 REG INT ENABLE 0 2 Interrupt enable control define ADXL345 REG INT MAP Ox2F Interrupt mapping control define ADXL345 REG INT SOURCE 0x30 Source of interrupts define ADXL345 REG DATA FORMAT 0x31 Data format control define ADXL345 REG DATAXO 0x32 X axis data 0 define ADXL345 REG 1 0x33 X axis data define ADXL345 REG DATAYO 0x34 Y axis data define ADXL345 REG 1 0x35 Y axis data define ADXL345 REG DATAZO 0x36 Z axis data define ADXL345 REG 21 0x37 Z axis data 51 define ADXL345 REG FIFO CTL 0x38 FIFO control define ADXL345 REG FIFO STATUS 0x39 FIFO status Used with register 0x2C ADXL345 REG BW RATE to set bandwidth typedef enum ADXL345 DATARATE 3200 HZ x F 1600Hz Bandwidth 140 IDD ADXL345 DATARATE 1600 HZ x E 8 Hz Bandwidth 90pA IDD ADXL345 DATARATE 800 HZ OxOD 4 Hz Bandwidth 140pA IDD ADXL345 DATARATE 400 HZ 0x0C 2 Hz Bandwidth 140pA IDD ADXL345 DATARATE 200 HZ 0x0B 1 Hz Bandwidth 140pA ID
59. alue pointer 0 HalSensorWriteReg SI1132 REG MEASRATEO amp value pointer BYTE1 HalSensorWriteReg SI1132 REG MEASRATE1 amp value pointer BYTE1 HalSensorWriteReg SI1132 REG IRQEN amp value pointer BYTE1 HalSensorWriteReg SI1132 REG IRQMODE1 amp value pointer BYTE1 HalSensorWriteReg SI1132 REG IRQMODE2 amp value pointer BYTE1 HalSensorWriteReg SI1132 REG INTCFG amp value pointer BYTE1 33 BYTE1 value pointer OxFF HalSensorWriteReg SI1132 REG IRQSTAT amp value pointer BYTE1 value pointer SI1132 RESET HalSensorWriteReg SI1132 REG COMMAND amp value pointer BYTE1 delay cycles 10000 delay program execution for 1000 cycles value pointer 0x17 HalSensorWriteReg SI1132 REG HWKEY amp value pointer BYTE1 delay cycles 10000 delay program execution for 1000 cycles void SI1132 SetCoefficients uint8 value pointer value pointer 0x29 HalSensorWriteReg SI1132 REG amp value pointer BYTE1 value pointer 0x89 HalSensorWriteReg SI1132 REG UCOEFF1 amp value pointer BYTE1 value pointer 0x02 HalSensorWriteReg SI1132 REG UCOEFF2 amp value pointer BYTE1 value pointer 0x00 HalSensorWriteReg SI1132 REG UCOEFF3 amp value pointer BYTE1 void SI1132 EnableUV void 511132 WriteParameters SI1132 PARAM CHLIST SI1132 PARAM CHLIST ENUV SI1132 PARAM CHLIST ENALSIR SI1132 PARAM CHLIST ENALSVIS SI1132 PARAM CHLIST ENPS1 v
60. aracteristic getUuid toString currentCharaData put LIST NAME iBeacon Char currentCharaData put LIST_UUID uuid gattCharacteristicGroupData add currentCharaData 88 mGattCharacteristics add charas gattCharacteristicData add gattCharacteristicGroupData SimpleExpandableListAdapter gattServiceAdapter new SimpleExpandableListAdapter this gattServiceData android R layout simple expandable list item 2 new String LIST NAME LIST UUID new int android R id text1 android R id text2 gattCharacteristicData android R layout simple expandable list item 2 new String LIST NAME LIST UUID new int android R id text1 android R id text2 mGattServicesList setAdapter gattServiceAdapter private static IntentFilter makeGattUpdatelntentFilter final IntentFilter intentFilter new IntentFilter intentFilter addAction BluetoothLeService ACTION GATT CONNECTED intentFilter addAction BluetoothLeService ACTION GATT DISCONNECTED intentFilter addAction BluetoothLeService ACTION GATT SERVICES DISCOVERED intentFilter addAction BluetoothLeService ACTION DATA AVAILABLE return intentFilter DeviceScanActivity java package com example android bluetoothlegatt import android app Activity import android app ListActivity import android bluetooth BluetoothAdapter import android bluetooth BluetoothDevice import android bluetooth BluetoothManager import android content Context
61. aracteristics gattService getCharacteristics ArrayList lt BluetoothGattCharacteristic gt charas new ArrayList lt BluetoothGattCharacteristic gt H Loops through available Characteristics for BluetoothGattCharacteristic gattCharacteristic gattCharacteristics characteristicsByUUID put gattCharacteristic getUuid toString gattCharacteristic Log d TAG gattCharacteristic getUuid gattCharacteristic getPermissions charas add gattCharacteristic HashMap lt String String gt currentCharaData new HashMap lt String String gt uuid gattCharacteristic getUuid toString H Log d TAG currentCharaData put LIST_NAME iBeacon Char currentCharaData put LIST_UUID uuid gattCharacteristicGroupData add currentCharaData H mGattCharacteristics add charas 104 gattCharacteristicData add gattCharacteristicGroupData private BluetoothGattCharacteristic getCharac UUID id for BluetoothGattService gattService mBluetoothL eService getSupportedGattServices List lt BluetoothGattCharacteristic gt gattCharacteristics gattService getCharacteristics for BluetoothGattCharacteristic b gattCharacteristics if b getUuid equals id Log d TAG b getUuid characteristic b return characteristic return characteristic private void readCharacteristicValue UUID id for BluetoothGattService gattService mBluetoothLeService g
62. at selected file name and passes that into a new intent This section of code is associated with csv select xml DeviceScanActivity java This section of code is where the BLE connection is handled Major code sections discussed as an overview below onCreate It begins by creating a handler that will handle of of the available BLE devices within range of the Android device The code also performs the necessary checks to make sure the Android device is capable of BLE as well as standard Bluetooth onListltemClick Creates a new intent which passes along the selected device name and address so that the new intent can pair to the selected device without having to rescan onOptionsltemSelected Is written so that the user may select to restart or stop a scan LeDeviceListAdapter This holds the BLE devices that were found during scanning and then add them to an ArrayList of available BLE device This ArrayList is used to display the BLE devices This section of code is associated with itemlist device xml 25 GraphViewData java This section of code is very simple The object is used to hold data as an x y coordinate pair so that it may be later plotted using GraphView InitOptionSelect java This section of code handles the connection to specific UUID addresses being used on the device It also handles the syncing of time to the device syncing data from the device and streaming data from the device in real time The intent receives
63. ate TextView realTimeVlISdata private TextView realTimelRdata private TextView realTimeUVdata private TextView realTimeTempdata private String mDeviceName private String mDeviceAddress private ExpandableListView mGattServicesList private BluetoothLeService mBluetoothLeService private ArrayList lt BluetoothGattCharacteristic gt mGattCharacteristics new ArrayList lt BluetoothGattCharacteristic gt 95 private BluetoothGattCharacteristic characteristic private Hashtable lt String BluetoothGattCharacteristic gt characteristicsByUUID new Hashtable lt String BluetoothGattCharacteristic gt private boolean mConnected false private BluetoothGattCharacteristic mNotifyCharacteristic private final String LIST NAME NAME private final String LIST UUID UUID private Handler mHandler private int sync byte 0 private int timerSends 0 private int month private int day private int year private int hour private int min private String data string private static View thisView private ArrayList lt ADXL_Obj gt ADKL DATA HOLDER new ArrayList lt ADXL_Obj gt private ArrayList lt LIGHT_Obj gt LIGHT DATA HOLDER new ArrayList lt LIGHT_Obj gt private ArrayList lt TMP006_Obj gt TMPO06 DATA HOLDER new ArrayList lt TMP006_Obj gt private ArrayList lt BPM_Obj gt BPM DATA HOLDER new ArrayList lt BPM_Obj gt private Intent intent private boolean realTime false publi
64. by examining their skin temperature activity level heart rate and light exposure In addition to measuring these parameters our project goal simultaneously addresses existing accuracy and cost issues related to fitness sleep tracking devices The device implements readily available components and sensors in a wearable form factor allowing the user to monitor their sleep habits and physiological metrics with ease and comfort Additionally the device employs a simple and clean user interface with a non intrusive form factor resemblant of a wrist watch 2 System Architecture Measurement Variables Light Exposure Activity Motion Skin Temperature Heart Rate Sensors acquire data Wearable Device Android Application Data Pre Processing PI i Sensor Data Displayed EP d a Function of Time Figure 1 System Architecture The function of our system is based on the acquisition and interpretation of data pertinent to a user s circadian rhythm Using appropriate sensors the system will acquire process and display measurements of a variety of physiological and environmental variables for a user of the device i e heart rate skin temperature motion and ambient UV light exposure The sensor data is stored in the internal memory of the device and can be subsequently transmitted via Bluetooth Low Energy to a PC or a smartphone running the Android OS Once the device and data have been
65. c static final int FORMAT UINTS 17 public static final int FORMAT SINT8 33 private final ServiceConnection mServiceConnection new ServiceConnection Override public void onServiceConnected ComponentName componentName IBinder service mBluetoothLeService BluetoothLeService LocalBinder service getService mBluetoothLeService initialize if ImBluetoothLeService initialize Log e TAG Unable to initialize Bluetooth finish 1 Automatically connects to the device upon successful start up H initialization mBluetoothLeService connect mDeviceAddress Override public void onServiceDisconnected ComponentName componentName mBluetoothLeService null E H Handles various events fired by the Service 96 ACTION GATT CONNECTED connected to a GATT server ACTION GATT DISCONNECTED disconnected from a GATT server ACTION GATT SERVICES DISCOVERED discovered GATT services ACTION DATA AVAILABLE received data from the device This be a II result of read II or notification operations private final BroadcastReceiver mGattUpdateReceiver new BroadcastReceiver Override public void onReceive Context context Intent intent final String action intent getAction if BluetoothLeService ACTION_GATT_CONNECTED equals action Log i ON GATT CONNECTED 1 mConnected true updateConnectionState R string connected invalidateOptionsMenu Log i ON G
66. ccess HalSensorReadReg TMP006 REG ADDR VOLTAGE uint8 amp v IRTEMP REG LEN if success t success HalSensorReadReg TMP006_REG_ADDR_TEMPERATURE uint8 amp t IRTEMP_REG_LEN 62 if success Store values uint8 LSB_byte2 UTCTime amp exeeeeeefft uint8 LSB_byte1 UTCTime amp 0 0000 00 gt gt 8 uint8 MSB byte2 UTCTime amp 0 00 0000 gt gt 16 uint8 MSB byte1 UTCTime amp Oxff000000 gt gt 24 pBuf 0 4 pBuf 1 MSB byte1 pBuf 2 MSB byte2 pBuf 3 LSB byte1 pBuf 4 LSB byte2 pBuf 5 0 pBuf 6 0 pBuf 7 LO UINT16 v pBuf 8 HI UINT16 v pBuf 9 LO UINT16 t pBuf 10 HI UINT16 t Turn off sensor if HalSensorWriteReg TMP006 REG ADDR CONFIG configSensorOff IRTEMP REG LEN t irtSensorState TMP006_OFF HalDcDcControl ST IRTEMP false return success ok ok fn HalIRTempStatus brief Read the state of the sensor return none EEEE EEEE E EE E E E E E E E E E E E E E K E K K K kK k K K k k kk k K K k KK k k kK kk IRTemperature States t HallIRTempStatus void if irtSensorState TMP006 OFF t bool success uint16 v 6
67. ce for approximately 5 seconds until the BLE indicator light turns solid then release the button Turning off BLE on your device will provide you with better battery life Viewing Logged Data 1 2 3 4 5 Open the Circadian Rhythm Analyzer application on your Android device Select Read CSV File The available CSV files are displayed on the same screen in order of newest to oldest CSV s are titled according to the date on the phone when you synced your Circadian Rhythm Monitor Select the CSV file you want to view data for On the next screen select the type of data you are interested in viewing The next screen will display a graph of all of the collected data for the type you selected in the previous screen You can zoom pinch and slide the graph to change scaling of the graph Sliding the graph left or right scrolls the data and the corresponding time the data was captured is shown on the X axis 17 6 Turn off Bluetooth Low Energy on your Circadian Rhythm Monitor by holding down the button on the device for approximately 5 seconds until the BLE indicator light turns solid then release the button Turning off BLE on your device will provide you with better battery life Charging Your Circadian Rhythm Monitor is always running Over time your Circadian Rhythm Monitor s battery will diminish Charging the device on a regular basis will eliminate the need to resync the date and time Should your device ever completely run
68. d Each device shows it s address below it allowing user to differentiate between devices with the same or similar names Selecting a Circadian Rhythm option takes the user to the next screen BIG F 684 12 12 e Circadian Rhythm Analyzer Device address 6C EC EB 57 5C 8F State Connected Data No data Sync Time Sync Data Real Time X Data Y Data Z Data Visible Light IR Light UV Light Temperature Syncing Data Byte 0 of 131072 12 12 PM e Circadian Rhythm Analyzer Device address 6C EC EB 57 5C 8F State Connected Data REAL TIME MODE Real Time X Data 0 4707192 m s 2 Y Data 1 0983448 m s 2 Z Data 0 8629851999999999 m s 2 Visible Light 262 0 lux IR Light 268 0 lux UV Light 0 03 Temperature 76 66752011086064 F Syncing Data Byte 0 of 131072 Figure 4 Syncing Screen and Real Time Screen The next screen allows the user to select between Sync Time Sync Data and Real Time To activate enable data collection on the device a user must select Sync Time this must be performed every time power is cycled or the battery dies on the circadian rhythm device Sync Data will provide syncing progress at the bottom of the screen A user may not select to view real time data and synchronize data simultaneously To select an option the user must return to the previous screen and select the appropriate device from the list of available devices again e Sync Tim
69. data value as time changes 5 Mechanical Design USB Port Button Port T A LED Ports Housing Light Sensor Port Clasps PCB Mounting Holes Skin Temp Sensor Port Heart Rate Band Braces N Sensor Base Figure 6 Enclosure Diagram Housing is a shell casing that flushly envelopes the PCB board and battery and secures it to the user s wrist for wearability It consists of a base cover and band 5 1 Assembly The PCB board is mounted to the base by way of 2 56 size screws that come up through the base at the mounting holes through 0 156 standoffs attached to the board through its own mounting holes Once secured the cover is then clasped down over the base and PCB board after threading the button and LEDs through their respective ports The USB port should also be aligned with the USB opening With these in place the band is then fed through it s braces and then wrapped around the user s wrist in such a way as to expose the user s skin to the opening in the base when worn 5 2 Device User Interface The device employs a simple user interface allowing for easy and intuitive operation A SPDT switch was used to toggle the enable pin of the Buck converter allowing the user to power on the device by tieing the enable pin high or powering off the device by tieing the enable pin to ground A push button switch connected to one of the GPIO pins of the microcontroller allows the user to initialize Bluetooth broadcasting with a
70. ds Activity private final static String TAG BPM GRAPHER class getSimpleName String file String H getintent getSerializableExtra EXTRAS FILE String file sdcard abc csv public static String file protected void onCreate Bundle savedinstanceState super onCreate savedInstanceState setContentView R layout test Bundle extras BPM GRAPHER this getIntent getExtras ArrayList lt GraphViewData gt data new ArrayList lt GraphViewData gt file extras getString EXTRAS_FILE_NAME file Environment getExternalStorageDirectory file file sdcard file BufferedReader reader null try reader new BufferedReader new FileReader file catch FileNotFoundException e1 1 TODO Auto generated catch block e1 printStackTrace try String line while line reader readLine null String RowData line split String type RowData 0 replace trim String date RowData 1 replace trim String bpm RowData 2 replace trim String utc RowData 3 replace trim if type equals BPM Log d TAG IN HERE type Log d TAG IN HERE UTC double Long parseLong utc Log d TAG IN HERE BPM Integer parselnt bpm data add new GraphViewData double Long parseLong utc Double parseDouble bpm 77 catch IOException ex H handle exception finally
71. e will synchronize the device s date and time settings to match the Android device and also enable data collection on the circadian rhythm device e Sync Data will synchronize the data from device to the Android device e Real Time will enable real time data viewing Upon selecting Real Time the raw data collected from the circadian rhythm device is updated and showed on the bottom of the screen This can be seen in the screenshot above GF 481 1210 BG FO 4 12 10 PM e Circadian Rhythm Analyzer e Circadian Rhythm Analyzer 10 092 Motion magnitude m s 2 10 0612 10 029 View Motion Data 9 9978 9 9661 View Visible Light 9 9344 Data 9 9027 9 8711 View UV Light Data aum 9 8077 2014 12 05 18 43 04 2014 12 05 18 43 46 View IR Light Data View Skin Temperature Data View BPM Data Figure 5 Data Selection Screen and Data Graph Screen Back at the initial screen where the user is presented with the option of Sync Phone and Read CSV File upon selecting the latter a user is brought to the next screen allowing them to specify the type of data they want to have graphed Upon selecting one of the View Data where is the type of data a user is brought to the next screen where the data is graphed in a date time vs data value x vs y format The user can turn their android device horizontally to change screen orientation pinch to zoom in and out and scroll left and right to see the
72. eDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone catch Exception e return int num 150 double v 0 for int i20 i lt num i v 0 2 j ADXL Obj java package com example android bluetoothlegatt import java io Serializable import java text SimpleDateFormat import java util Calendar import java util Date import java util TimeZone public class ADXL_Obj implements Serializable private double ADXL345_MG2G_MULTIPLIER 0 004 private double SENSORS_GRAVITY_STANDARD 9 80665 private String date private String data private double x private double y private double z private Integer UTC public ADXL_Obj Integer UTC String data this UTC UTC 69 this date getDateCurrentTimeZone UTC this data data public double getX String delimit data split String xString delimit 1 Integer decVal Integer parselnt xString 16 if delimit 0 equalslgnoreCase FF decVal 1 return decVal ADXL345 MG2G MULTIPLIER SENSORS GRAVITY STANDARD public double getY String delimit data split String xString delimit 3 Integer decVal Integer parselnt xString 16 if delimit 2 equalslgnoreCase FF decVal 1 return decVal ADXL345 MG2G MULTIPLIER SENSORS GRAVITY STANDARD public double g
73. ead etc SI1143 WriteParameters SI1143 PARAM PSLED12 SELECT 0x21 SI1143 WriteParameters SI1143 PARAM PSLED3 SELECT 0x04 writeParam PulsePlug PARAM PSLED12 SELECT 0x21 21 LED 2 amp LED 1 red resp writeParam PulsePlug PARAM PSLED3 SELECT 0x04 4 LED 3 only Sensors for reading the three LEDs 0x03 Large IR Photodiode 0x02 Visible Photodiode cannot be read with LEDs on just for ambient measurement 0x00 Small IR Photodiode SI1143 WriteParameters SI1143 PARAM PS1 ADCMUX 0x03 511143 WriteParameters SI1143 PARAM 52 ADCMUX 0x03 511143 WriteParameters SI1143 PARAM PS3 ADCMUX 0x03 writeParam PulsePlug PARAM PS1 ADCMUX 0x03 PS1 photodiode select writeParam PulsePlug PARAM PS2 ADCMUX 0x03 PS2 photodiode select writeParam PulsePlug PARAM PS3 ADCMUX 0x03 PS3 photodiode select SI1143 WriteParameters SI1143 PARAM PS ADC COUNTER 0x70 writeParam PulsePlug PARAM PS ADC COUNTER B01110000 B01110000 is default value pointer PSALS AUTO Cmd HalSensorWriteReg SI1143 REG COMMAND amp value_pointer BYTE1 setReg PulsePlug COMMAND PulsePlug PSALS AUTO Cmd starts an autonomous read loop 44 Serial println getReg PulsePlug CHIP STAT HEX Serial print end init float smooth float data float filterVal float smoothedVal if filterVal gt 1 check to make sure param s are within range filterVal 99 else if
74. ed asynchronously through the code BluetoothGattCallback onConnectionStateChange android bluetooth BluetoothGatt int int callback public void disconnect if mBluetoothAdapter null mBluetoothGatt null Log w TAG BluetoothAdapter not initialized return mBluetoothGatt disconnect ET After using a given BLE device the app must call this method to ensure resources are released properly public void close if mBluetoothGatt null return mBluetoothGatt close mBluetoothGatt null ES Request a read a given code BluetoothGattCharacteristic The read result is reported asynchronously through the code BluetoothGattCallback onCharacteristicRead android bluetooth BluetoothGatt android bluetooth BluetoothGattCharacteristic int callback param characteristic The characteristic to read from public void readCharacteristic BluetoothGattCharacteristic characteristic if mBluetoothAdapter null mBluetoothGatt null 75 Log w TAG BluetoothAdapter not initialized return mBluetoothGatt readCharacteristic characteristic Enables or disables notification on a give characteristic param characteristic Characteristic to act on param enabled If true enable notification False otherwise public void setCharacteristicNotification BluetoothGattCharacteristic characteristic boolean enabled if mBlueto
75. eed to in writing software distributed under the License is distributed on an AS IS BASIS WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND either express or implied See the License for the specific language governing permissions and limitations under the License package com example android bluetoothlegatt import android app Service import android bluetooth BluetoothAdapter import android bluetooth BluetoothDevice import android bluetooth BluetoothGatt import android bluetooth BluetoothGattCallback import android bluetooth BluetoothGattCharacteristic import android bluetooth BluetoothGattService import android bluetooth BluetoothManager 71 import android bluetooth BluetoothProfile import android content Context import android content Intent import android os Binder import android os IBinder import android util Log import java util List Ju Service for managing connection and data communication with a GATT server hosted on a given Bluetooth LE device public class BluetoothLeService extends Service private final static String TAG BluetoothLeService class getSimpleName private BluetoothManager mBluetoothManager private BluetoothAdapter mBluetoothAdapter private String mBluetoothDeviceAddress private BluetoothGatt mBluetoothGatt private int mConnectionState STATE_DISCONNECTED private static final int STATE_DISCONNECTED 0 private static final int STATE_CONNEC
76. egister off ST ASSERT HalSensorReadReg TMPO06 REG ADDR CONFIG uint8 amp val IRTEMP REG LEN val LO UINT16 val lt lt 8 HI UINT16 val ST ASSERT val 006 VAL CONFIG OFF Turn sensor on ST ASSERT HalSensorWriteReg TMP006 REG ADDR CONFIG configSensorOn IRTEMP REG LEN Check config register on ST ASSERT HalSensorReadReg TMPO06 REG ADDR CONFIG uint8 amp val IRTEMP REG LEN val LO UINT16 val lt lt 8 HI UINT16 val 64 ST ASSERT val TMP006_VAL_CONFIG_ON Turn sensor off ST ASSERT HalSensorWriteReg TMP006 REG ADDR CONFIG configSensorOff IRTEMP REG LEN return TRUE E R E E fn HalIRTempSelect brief Select the 006 slave and set the I2C bus speed return none ee reer re static void HalIRTempSelect void Select slave and set clock rate HallI2CInit TMP006 I2C ADDRESS i2cClock 533KHZ double calcTmpLocal uint16 rawT calculate die temperature C m tmpAmb double qint16 rawT 128 0 return m tmpAmb Conversion algorithm for target temperature double calcTmpTarget uinti16 rawT calculate target temperatu
77. er 0x43 printf 1 return 1 look for SI1145 DEVICE FOUND Reset SI1146 Registers printf 0 return 0 42 uint8 SI1143 ReadParameters char target uint8 registerPointer uint8 value pointer value pointer target SI1143 PARAM QUERY HalSensorWriteReg SI1143 REG COMMAND amp value pointer BYTE1 HalSensorReadReg SI1143 REG PARAM RD uint8 amp registerPointer BYTE1 return registerPointer void SI1143 WriteParameters char target char parameters uint8 registerPointer uint8 value pointer value pointer parameters HalSensorWriteReg SI1143 REG PARAM WR amp value pointer BYTE1 Pass parameter x to the mailbox register host to sequencer value pointer target SI1143 PARAM SET HalSensorWriteReg SI1143 REG COMMAND amp value pointer BYTE1 Sets parameter pointed by target with value just placed into mailbox register HalSensorReadReg SI1143 REG PARAM RD uint8 amp registerPointer BYTE1 Read from the mailbox register sequencer to host required to clear void 511143 initPulseSensor uint8 value pointer value pointer 0x17 HalSensorWriteReg SI1143 REG HW KEY amp value pointer BYTE1 value pointer 0x03 HalSensorWriteReg SI1143 REG INT CFG amp value pointer BYTE1 value pointer 0x10 HalSensorWriteReg SI1143 REG IRQ ENABLE amp value_pointer BYTE1 value pointer 0x01 HalSensorWriteReg SI1143 REG IRQ MODE2 amp value pointer BYTE
78. er android com guide topics connectivity bluetooth le html GraphView jar is required for our project as it is our primary way of graphing collected data from a CSV file as an output http www android graphview org opencsv jar is also required for our project as it is being used for CSV file creation http opencsv sourceforge net 20 Appendix 2541 Firmware File Descriptions The following sections details the implementation and integration of our sensor firmware and software 511132 511132 amp 511132 511132 is used for IR UV and Visible light measurements The following functions are used to make the 511132 sensor operational Functions void SI1132 Select This function is used for MCU to initialize an i2c communication with the 511132 sensor void 611132 RESETFUNCTION This function clears necessary 511132 registers to OxFF void SI1132 SetCoefficients This function initializes parameters necessary for setting up the SI1132 such as ADC Overflow Response and Auto Measurement mode void 611132 EnableUV This function writes to the 511132 internal memory and sets up the enabling of the UV Sensor by writing necessary configuration parameters void 611132 EnablelnterrupOnEverySample This function initializes the parameters of the 511132 register to enable interrupts for data sampling void 511132 ProximitySensorSetup This function initialize and calibrates the 511132 sensors in hi
79. er append String format 02X byteChar intent putExtra EXTRA DATA new String data n stringBuilder toString sendBroadcast intent public class LocalBinder extends Binder BluetoothLeService getService return BluetoothLeService this 73 Override public IBinder onBind Intent intent return mBinder Override public boolean onUnbind Intent intent 1 After using a given device you should make sure that BluetoothGatt close is called such that resources are cleaned up properly In this particular example close is H invoked when the UI is disconnected from the Service close return super onUnbind intent private final IBinder mBinder new LocalBinder pr Initializes a reference to the local Bluetooth adapter return Return true if the initialization is successful public boolean initialize For API level 18 and above get a reference to BluetoothAdapter through H BluetoothManager if mBluetoothManager null mBluetoothManager BluetoothManager getSystemService Context BLUETOOTH_SERVICE if mBluetoothManager null Log e TAG Unable to initialize BluetoothManager return false mBluetoothAdapter mBluetoothManager getAdapter if mBluetoothAdapter null Log e TAG Unable to obtain a BluetoothAdapter return false return true Connects to the GATT server hosted on the Bluetooth LE device
80. etSupportedGattServices List lt BluetoothGattCharacteristic gt gattCharacteristics gattService getCharacteristics for BluetoothGattCharacteristic b gattCharacteristics if b getUuid equals id Log d TAG b getUuid characteristic b if characteristic null Log d TAG NOT NULL mBluetoothLeService readCharacteristic characteristic int charaProp characteristic getProperties if charaProp BluetoothGattCharacteristic PROPERTY READ gt 0 If there is an active notification on a characteristic clear II it first so it doesn t update the data field on the user II interface if mNotifyCharacteristic null mBluetoothLeService setCharacteristicNotification mNotifyCharacteristic false mNotifyCharacteristic null mBluetoothLeService readCharacteristic characteristic 105 if BluetoothGattCharacteristic PROPERTY NOTIFY gt 0 mNotifyCharacteristic characteristic mBluetoothLeService setCharacteristicNotification characteristic true mDataField setText characteristic getUuid private void real_time final Handler handler new Handler Runnable runnable new Runnable public void run while realTime true try Thread sleep 1000 catch InterruptedException e e printStackTrace handler post new Runnable public void run readCharacteristicValue ADXL_DATA
81. etZ String delimit data split String xString delimit 5 Integer decVal Integer parselnt xString 16 if delimit 4 equalslgnoreCase FF decVal 1 return decVal ADXL345 MG2G MULTIPLIER SENSORS GRAVITY STANDARD public double getMagnitude double x getX double y 7 getY double z 7 getZ return Math sqrt Math pow x 2 Math pow y 2 Math pow z 2 public Integer getUTC return UTC public String getDate return date 70 public void setDate String date public String getData public void setData String data this date date return data this data data private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getInstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timestamp 1000 calendar add Calendar MILLISECOND 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone catch Exception e return BluetoothLeService java Copyright 2013 The Android Open Source Project Licensed under the Apache License Version 2 0 the License you may not use this file except in compliance with the License You may obtain a copy of the License at http www apache org licenses LICENSE 2 0 Unless required by applicable law or agr
82. evice address viewHolder deviceName TextView view findViewById R id device view setTag viewHolder else viewHolder ViewHolder view getTag BluetoothDevice device mLeDevices get i final String deviceName device getName if deviceName null amp amp deviceName length gt 0 viewHolder deviceName setText deviceName else viewHolder deviceName setText R string unknown device viewHolder deviceAddress setText device getAddress return view Device scan callback private BluetoothAdapter L eScanCallback mLeScanCallback new BluetoothAdapter LeScanCallback Override public void onLeScan final BluetoothDevice device int rssi byte scanRecord runOnUiThread new Runnable Override public void run mLeDeviceListAdapter addDevice device mLeDeviceListAdapter notifyDataSetChanged static class ViewHolder TextView deviceName TextView deviceAddress GraphViewData java package com example android bluetoothlegatt import com jjoe64 graphview GraphViewDatalnterface public class GraphViewData implements GraphViewDatalnterface private double x y public GraphViewData double x double y this x x this y y 93 Override public double getX return this x Override public double getY return this y public int compareTo GraphViewData other if this getX lt other getX return 1
83. ew on the UI private void displayGattServices List lt BluetoothGattService gt gattServices if gattServices null return String uuid null ArrayList lt HashMap lt String String gt gt gattServiceData new ArrayList lt HashMap lt String String gt gt ArrayList lt ArrayList lt HashMap lt String String gt gt gt gattCharacteristicData new ArrayList lt ArrayList lt HashMap lt String String gt gt gt mGattCharacteristics new ArrayList lt ArrayList lt BluetoothGattCharacteristic gt gt H Loops through available GATT Services for BluetoothGattService gattService gattServices HashMap lt String String gt currentServiceData new HashMap lt String String gt uuid gattService getUuid toString currentServiceData put LIST NAME iBeacon currentServiceData put LIST gattServiceData add currentServiceData ArrayList lt HashMap lt String String gattCharacteristicGroupData new ArrayList lt HashMap lt String String gt gt List lt BluetoothGattCharacteristic gt gattCharacteristics gattService getCharacteristics ArrayList lt BluetoothGattCharacteristic gt charas new ArrayList lt BluetoothGattCharacteristic gt H Loops through available Characteristics for BluetoothGattCharacteristic gattCharacteristic gattCharacteristics charas add gattCharacteristic HashMap lt String String gt currentCharaData new HashMap lt String String gt uuid gattCh
84. ew GraphViewData import com jjoe64 graphview GraphViewSeries import com jjoe64 graphview LineGraphView import android app Activity import android os Bundle import android os Environment 113 import android util Log import android widget LinearLayout public class TEMPERATURE GRAPHER extends Activity private final static String TAG TEMPERATURE GRAPHER class getSimpleName String file String H getintent getSerializableExtra EXTRAS FILE String file sdcard abc csv public static String file protected void onCreate Bundle savedinstanceState super onCreate savedInstanceState setContentView R layout test Bundle extras TEMPERATURE GRAPHER this getlIntent getExtras ArrayList lt GraphViewData gt data new ArrayList lt GraphViewData gt file extras getString EXTRAS FILE file Environment getExternalStorageDirectory file file sdcard file BufferedReader reader null try reader new BufferedReader new FileReaderf file catch FileNotFoundException e1 1 TODO Auto generated catch block e1 printStackTrace try String line while line reader readLine null String RowData line split if IRowData 2 contains NaN String type RowData 0 replace trim String date RowData 1 replace trim String skin temp RowData 2 replace trim String utc RowData 3
85. ewSeries input set view port start 2 size 40 graphView setViewPort 2 40 graphView setScrollable true H optional activate scaling zooming graphView setScalable true LinearLayout layout LinearLayout findViewByld R id graph1 layout addView graphView private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getInstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timestamp 1000 calendar add Calendar MILLISECOND 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone catch Exception e return 111 int num 150 double v 0 for int i20 i lt num i v 0 2 Si LIGHT Obj java package com example android bluetoothlegatt import java io Serializable import java text SimpleDateFormat import java util Calendar import java util Date import java util TimeZone public class LIGHT_Obj implements Serializable private String date private String data private float UV private float IR private float VIS public LIGHT_Obj Integer UTC String data this date getDateCurrentTimeZone UTC this data data private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getlnstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timesta
86. get Calendar MINUTE Log d TAG SYNC TIME PRESSED mDataField TextView findViewByld R id data_value mDataField setText byte month byte day byte year byte hour byte sync timer D button syncData setOnClickListener new View OnClickListener public void onClick View v button syncTime setEnabled false button syncData setEnabled false button RealTime setEnabled false Date date new Date String csv name new SimpleDateFormat yyyy MM dd HH mm format date try writer new CSVWriter new FileWriter sdcard csv name circadianrhythm csv catch IOException e Il error data_sync_text TextView InitOptionSelect this findViewByld R id data_sync_text Log d TAG SYNC Data PRESSED mDataField TextView findViewByld R id data_value readCharacteristicValue FRAM_BUFFER data_sync_text setVisibility v VISIBLE InitOptionSelect this findViewByld R id data sync progressbar setVisibility v VISIBLE thisView v realTime false sync counter button RealTime setOnClickListener new View OnClickListener 102 public void onClick View v button syncTime setEnabled false button syncData setEnabled false realTime true Log d TAG FRAM PRESSED mDataField TextView findViewByld R id data value _realTimeXdata setVisibility v VISIBLE realTimeYdata setVisibil
87. get ListView import android widget TextView public class csv select extends Activity public static String filename null public static String EXTRAS FILE NAME private final static String TAG csv select class getSimpleName private ListView csv_list public ArrayList lt String gt GetFiles String DirectoryPath ArrayList lt String gt MyFiles new ArrayList lt String gt File f new File DirectoryPath f mkdirs File files f listFiles if files length 0 return null else for int 0 i lt files length i if files i toString contains csv MyFiles add files i getName Collections sort MyFiles Collections reverse MyFiles return MyFiles protected void onCreate Bundle savedinstanceState super onCreate savedinstanceState setContentView R layout csv_select Icsv_list ListView findViewByld R id CSV_FILES_LIST ImGattServicesList setOnChildClickListener servicesListClickListner public void onClick View if v getld R id SyncPhone Intent syncPhonelntent new Intent this DeviceScanActivity class startActivity syncPhonelntent selse if v getld R id readCSV TextView fileselect TextView findViewByld R id selectafiletext fileselect setVisibility 0 To set visible 83 ArrayList lt String gt FilesInFolder GetFiles Environment getExternalStorageDirectory toString csv list ListView findViewByld
88. getSupportedGattServices Log i ON DISPLAYED SERVICES else if BluetoothLeService ACTION DATA AVAILABLE equals action Log i ON GATT DATA AVAILABLE OK displayData intent getStringExtra BluetoothLeService EXTRA DATA a given GATT characteristic is selected check for supported features This sample demonstrates Read and Notify features See http d android com reference android bluetooth BluetoothGatt html for the complete list of supported characteristic features private final ExpandableListView OnChildClickListener servicesListClickListner new ExpandableListView OnChildClickListener Override public boolean onChildClick ExpandableListView parent View v int groupPosition int childPosition long id if mGattCharacteristics null final BluetoothGattCharacteristic characteristic mGattCharacteristics get groupPosition get childPosition final int charaProp characteristic getProperties if charaProp BluetoothGattCharacteristic PROPERTY READ gt 0 If there is an active notification on a characteristic clear it first so it doesn t update the data field on the user interface if mNotifyCharacteristic null mBluetoothLeService setCharacteristicNotification mNotifyCharacteristic false mNotifyCharacteristic null mBluetoothLeService readCharacteristic characteristic if charaProp BluetoothGattCharacteristic PROPERTY NOTIFY gt 0 mNo
89. gh range mode High sensitivity ADC range void SI1132 AutoMeasure This function initializes and calibrates the rate at which the 511132 is measuring data when it is on It is set at a rate of 8 ms Operation The 511132 is polled every 15 minutes Once the polling of the 511132 has been enabled in the main MCU software code SensorTag c the 511132 readSl1132 UTCTime function is called The caller sends this function the current time determined by the UTC which is a 32 bit integer value The readSl1132 function calls all the functions described above to initialize the 511132 sensor to begin taking light measurements Within this function call 3 registers are read from the UVINDEX the ALSVISDATA and the ALSIRDATA registers Each register is 2 bytes long Upon reading each of these registers if the data is ready and i2c read access to all of them are successful than the values are stored to a 11 byte array which is in the big endian format of Header UTCmsb1 UTCmsb2 UTCIsb1 UTCIsb2 VisibleMSB VisibleLSB IRMSB IRLSB UVMSB UVLSB This array of values is then copied into FRAM at the next available location in FRAM to store Note The Header value for any 511132 value UV IR VISIBLE is always 2 This value is used for our Bluetooth communication between MCU and Phone as the phone will be able to decode which data it is by the header 511143 511143 amp SI1143 h The 511143 is used for the heart rate and BPM measurement coun
90. imestamp 1000 calendar add Calendar MILLISECOND 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone 122 catch Exception e return D J int num 150 double v 0 for int i 0 i lt num i v 0 2 123
91. include the following lines of code to enable Bluetooth and BLE permissions for the Android application lt uses feature android name android hardware bluetooth_le android required true gt lt uses permission android name android permission BLUETOOTH gt lt uses permission android name android permission BLUETOOTH_ADMIN gt lt uses permission android name android permission WRITE_EXTERNAL_STORAGE gt 26 Appendix J 2541 Firmware Source Code FRAM H uint8 READFRAM int32 address void WRITE FRAM int32 address uint8 data void WRITE SENSORDATA FRAM int32 address uint8 data array void READ CURRENT DATA int32 address uint8 FRAM DATA FRAM C include hal i2c h include stdio h define BYTE1 1 define BYTE2 2 uint8 READFRAM int32 address uint8 i2c pg addr 0x00 uint8 address MSB address amp Oxff00 gt gt 8 uint8 address LSB address 8 0x00ff uint8 registerPointer 0x00 if address lt 65536 pgselect 0 i2c pg addr 0x50 0 112 0 50 i2cClock 533KHZ Jelse i2c pg addr 0x51 pg0 HallI2CInit 0x51 i2cClock 533KHZ READ FRAN FROM ADDRESS BYTE1 amp i2c pg uint8 amp address MSB uint8 amp address LSB uint8 amp registerPointer return registerPointer void WRITE FRAM int32 address uint8 data uint8 i2c pg addr 0x00 uint8 address MSB address amp Oxff00 gt gt 8 uint8 address LSB address am
92. intent For example in ADXL_GRAPHER java the parser is only looking for data that is from the Accelerometer For each piece of data collected as a GraphViewData type is created and stored an ArrayList for convenience The ArrayList is later used to plot a graph This section of code is associated with grapher_layout xml data type Obj java These sections of code use the raw data extracted from the FRAM Sensors as an input and parse through the data to create real meaningful data as an output that can be analyze and or graphed later This output changes for each data type This section of code also converts UTC into a meaningful Date Time format for the user csv data selector java This section of code is rather simple as it pulls the selected CSV filename from the previous intent and then lets a user specify which type of data in the previously selected CSV that they would like to have graphed This section of code is associated with csv dataviews xml csv select java This is the starting point for the entire application The method has two outcomes depending on the interaction with the user If Sync Phone is clicked then a new intent is made to sync the device with the Android Device If Read CSV File is clicked An ArrayList is created in GetFiles containing all csv files on the Android device That list is then displayed on the screen When a user selects a CSV file from the list onltemClick saves th
93. ity v V ISIBLE _realTimeZdata setVisibility v VISIBLE _realTimeVI Sdata setVisibility v VISIBLE _realTimelRdata setVisibility v VISIBLE _realTimeUVdata setVisibility v VISIBLE characteristic getCharac FRAM CONFIG H characteristic setValue new byte 0x01 H gatt writeCharacteristic characteristic real time Il Log d TAG CHARACTERISTIC IS characteristic getUuid D mGattServicesList ExpandableListView findViewByld R id gatt services list ImGattServicesList setOnChildClickListener servicesListClickListner mDataField 7 TextView findViewByld R id data value getActionBar setTitle mDeviceName getActionBar setDisplayHomeAsUpEnabled true Intent gattServicelntent new Intent this BluetoothLeService class bindService gattServicelntent mServiceConnection BIND AUTO CREATE private BluetoothGattCallback mGattCallback new BluetoothGattCallback D Override protected void onResume super onResume registerReceiver mGattUpdateReceiver makeGattUpdatelntentFilter if mBluetoothLeService null final boolean result mBluetoothLeService connect mDeviceAddress Log d TAG Connect request result result Override protected void onPause super onPause unregisterReceiver mGattUpdateReceiver 103 Override protected void onDestroy super onDestroy unbindService mServiceConnection m
94. lntent new Intent BluetoothAdapter ACTION REQUEST ENABLE startActivityForResult enableBtIntent REQUEST ENABLE BT H Initializes list view adapter mLeDeviceListAdapter new LeDeviceListAdapter setListAdapter mLeDeviceListAdapter scanLeDevice true Override protected void onActivityResult int requestCode int resultCode Intent data H User chose not to enable Bluetooth if requestCode REQUEST ENABLE amp amp resultCode Activity RESULT CANCELED finish return super onActivityResult requestCode resultCode data Override protected void onPause super onPause scanLeDevice false mLeDeviceListAdapter clear Override protected void onListltemClick ListView View v int position long id final BluetoothDevice device mLeDeviceListAdapter getDevice position if device null return final Intent intent new Intent this DeviceControlActivity class final Intent intent new Intent this InitOptionSelect class intent putExtra DeviceControlActivity EXTRAS DEVICE NAME device getName intent putExtra DeviceControlActivity EXTRAS DEVICE ADDRESS device getAddress if mScanning mBluetoothAdapter stopLeScan mLeScanCallback mScanning false startActivity intent private void scanLeDevice final boolean enable if enable Stops scanning after a pre defined scan period 91 mHandler postDelayed new Runnable
95. mp 1000 calendar add Calendar MILLISECOND 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone Exception e return public String getDate return date public String getData return data public float getUV 112 String delimit data split String IRString delimit 4 delimit 5 Integer decVal Integer parselnt IRString 16 return float decVal float 100 public float getlR 4 String delimit data split String IRString delimit 2 delimit 3 Integer decVal Integer parselnt IRString 16 return float decVal public float getVIS String delimit data split String VisString delimit 0 delimit 1 Integer decVal Integer parselnt VisString 16 return float decVal TEMPERATURE GRAPHER java package com example android bluetoothlegatt import java io BufferedReader import java io FileNotFoundException import java io FileReader import java io OException import java io InputStream import java io InputStreamReader import java text SimpleDateFormat import java util ArrayList import java util Calendar import java util Date import java util TimeZone import com jjoe64 graphview CustomLabelFormatter import com jjoe64 graphview GraphView import com jjoe64 graphview GraphVi
96. mponents ensuring accurate data The 006 interfaces via I C and outputs digital data 3 2 Power Management Subsystem Mini USB Charging Circuitry and LiPo Battery The Texas Instruments LM3658 LiPo battery charging IC was chosen to allow a user of the device to charge their device battery via a Mini USB connection while also allowing for the possible future addition of AC charging The LM3658 when connected to a 3 7V LiPo battery charges the battery at 4 2V at a rate of 100 or 500mA charge rate pin selectable and switches to maintenance mode upon sensing a full battery charge The support circuitry also featured charging status LEDs indicating battery level Buck Converter Switching Regulator The Texas Instruments TPS62203 DC DC Step Down Buck Converter was chosen to convert the 3 7V LiPo battery output or the LM3658 output if no battery was connected to the 3 3V required by system components for operation The device also provided up to 300mA to the system which is necessary when all components are active at the same time The TPS62203 was chosen instead of a Low Drop Out Regulator in an attempt to reduce heat dissipation inside the enclosure while also improving performance 3 3 Microcontroller Memory and Bluetooth Transmission Subsystem The Texas Instruments CC2541 Microcontroller was chosen for our application because the MCU features a Bluetooth Low Energy transmitter receiver SoC system on chip Using the CC2541 was advantageous
97. n and Configured 006 DATA READY IR Temperature On Configured and Data is Ready IRTemperature States t J EESESEOROK EORR R EOROKOR OR EROR GEOP GEGEN DK ER o RR OK FSK FUNCTIONS void HALIRTempInit void void HalIRTempTurnOn void void HalIRTempTurnOff void bool HalIRTempRead uint8 irTempData int32 UTCTime bool HalIRTempTest void IRTemperature States t HalIRTempStatus void ifdef _ cplusplus endif endif HAL_IRTEMP_H HAL IRTEMP C include hal_irtemp h include hal_i2c h include hal_sensor h include stdio h Slave address 59 define 006 I2C ADDRESS 006 register addresses define 006 REG ADDR VOLTAGE define 006 REG ADDR TEMPERATURE define 006 REG ADDR CONFIG define TMPO06 REG ID define 006 REG PROD ID 006 register values define 006 VAL CONFIG RESET 0x7400 Sensor reset state define 006 VAL CONFIG ON 0x7000 Sensor on state define TMP006 VAL CONFIG OFF 0 0000 Sensor off state define 006 VAL MANF ID 0 5449 Manufacturer ID define 006 VAL PROD ID 0x0067 Product ID Bit values define DATA RDY BIT 0 8000 Data ready Register length define IRTEMP REG LEN define 006 BO 0 0000294 define 006 B1 0 00000057 define 006 B2 0 00000000463 define TMP006 C2 13
98. nal memory of the device and can be subsequently transmitted via Bluetooth Low Energy to a PC or a smartphone running the Android OS Once the device and data have been synchronized with and transmitted to an appropriate peripheral device post processing is performed and the data is displayed in either data vs time formatting or as raw measurements in a csv file The system enables an individual to conveniently view data on their smartphone and continually log data in hopes of drawing conclusions about how they can improve the quality and regularity of their sleep and circadian rhythm Link to addition team photos http imgur com a Mf9WY 0 Please submit your class report with this one page document Your class report should include the following Max of 10 pages excluding appendix Table of contents List of figures and tables A detailed written description of the project design Hardware Design Any Software Architecture used include any software code as part of Appendix Testing and Results Conclusions Future Work Recommendations Acknowledgements and or References Appendix schematics CAD drawings Critical IC Bill of Materials User Manual etc SSQW057 Wearable Circadian Rhythm Monitor Final Design Document Project Team David Brown Jonathan Howell David Le Project Sponsor ASSIST Center Project Advisors Dr John Muth Dr Rachana Gupta Table of Contents 1 Project Description 2
99. ndar calendar Calendar getlnstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timestamp 1000 calendar add Calendar MILLISECOND 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone Exception e return public double getTemp return target 9 5 32 private static double extractAmbientTemperature byte v int offset 2 return shortUnsignedAtOffset v offset 128 0 private static double extractTargetTemperature byte v double ambient Integer twoByteValue shortSignedAtOffset v 0 double Vobj2 twoByteValue doubleValue Vobj2 0 00000015625 double Tdie ambient 273 15 double S0 5 593E 14 Calibration factor double a1 1 75E 3 double a2 1 678E 5 double b0 2 94E 5 double b1 5 7E 7 double b2 4 63E 9 double c2 13 4 double Tref 298 15 double S S0 1 1 Tdie Tref a2 pow Tdie Tref 2 double Vos b0 b1 Tdie Tref b2 pow Tdie Tref 2 double fObj Vobj2 Vos c2 pow Vobj2 Vos 2 double data Tdie Tdie Tdie Tdie fObj S 117 double tObj pow data 25 return tObj 273 15 private static Integer shortSignedAtOffset byte c int offset Integer lowerByte int c offset amp OxFF Integer upperByte int c offset 1
100. ne define define define 511132 REG PARTID 0x00 511132 REG 0 01 511132 REG SEQID 0 02 511132 REG INTCFG 0x03 511132 REG INTCFG 0x01 511132 REG INTCFG INTMODE 0x02 511132 REG IRQEN 0 04 SI1132 REG IRQEN ALSEVERYSAMPLE 0x01 511132 REG IRQEN PSIEVERYSAMPLE 0x04 511132 REG IRQEN PS2bEVERYSAMPLE 0x08 SI1132 REG IRQEN PS3EVERYSAMPLE 0x10 511132 REG IRQMODE1 0x05 SI1132 REG IRQMODE2 0x06 SI1132 REG HWKEY 0x07 511132 REG MEASRATEO 0x08 511132 REG MEASRATE1 0x09 511132 REG PSRATE O0x0A 511132 REG PSLED21 OxOF 511132 REG PSLED3 0x10 511132 REG UCOEFFO 0x13 511132 REG UCOEFF1 0 14 511132 REG UCOEFF2 0 15 511132 REG UCOEFF3 0x16 511132 REG PARAMWR 0x17 511132 REG COMMAND 0x18 511132 REG RESPONSE 0x20 511132 REG IRQSTAT 0 21 511132 REG IRQSTAT ALS 9 01 SI1132 REG ALSVISDATAO 0x22 SI1132 REG ALSVISDATA1 0x23 511132 REG ALSIRDATAO 0x24 SI1132 REG ALSIRDATA1 0x25 511132 REG PS1DATAO 0x26 511132 REG 51 1 0x27 SI1132 REG PS2DATAO 0x28 SI1132 REG PS2DATA1 0x29 511132 REG PS3DATAO 0 2 511132 REG PS3DATA1 0 2 31 define 511132 REG UVINDEXO 0x2C define 511132 REG UVINDEX1 0x2D define SI1132 REG PARAMRD 2 define 511132 REG CHIPSTAT 0x30 define 511132 I2C ADDRESS 0x60 11132 C include SI1132 h include hal drivers h include bcomdef h include OSAL h include OSAL PwrMgr h include OnBoard h include hal adc h include hal led h include hal
101. new Thread runnable start private void createCSV IRLIGHT_GRAPHER java package com example android bluetoothlegatt import java io BufferedReader import java io FileNotFoundException import java io FileReader import java io IOException import java io InputStream import java io InputStreamReader import java text SimpleDateF ormat import java util ArrayList import java util Calendar import java util Date import java util TimeZone 109 import com jjoe64 graphview CustomLabelFormatter import com jjoe64 graphview GraphView import com jjoe64 graphview GraphView GraphViewData import com jjoe64 graphview GraphViewSeries import com jjoe64 graphview LineGraphView import android app Activity import android os Bundle import android os Environment import android util Log import android widget LinearLayout public class IRLIGHT_GRAPHER extends Activity private final static String TAG IRLIGHT_GRAPHER class getSimpleName String file String H getintent getSerializableExtra EXTRAS FILE String file sdcard abc csv public static String file protected void onCreate Bundle savedinstanceState super onCreate savedinstanceState setContentView R layout test Bundle extras IRLIGHT_GRAPHER this getIntent getExtras ArrayList lt GraphViewData gt data new ArrayList lt GraphViewData gt file extras getString EXTRAS_FILE_NAME
102. ng Services 40 Total Development Costs 624 15 Appendix E User Manual Introduction Congratulations on being the proud owner of the Wearable Circadian Rhythm Measurement System The Circadian Rhythm Monitor is a wristband worn device designed to track the parameters used to determine an individual s circadian rhythm By wearing this device and examining the data it collects you will be able to determine your own personal circadian rhythm cycles and determine what your rhythms are most affected by This device was developed with medical applications in mind and is just as likely to have been referred to you by your treating physician If this is the case please remember to share your collected data with your physician What Are Circadian Rhythms Everybody is familiar with the times of day when they are most wakeful or sleepy Circadian Rhythms are the cycles by which bodily systems synchronize with a day to day cycle They are not the same as but are driven by a your biological clock How Do They Affect Me Circadian Rhythms influence an individual s sleep wake cycles hormone release body temperature and other bodily functions For example a disturbance in your general daily rhythms have been linked to various sleep disorders such as insomnia and jet lag In some extreme cases abnormal circadian rhythms have been associated with obesity diabetes depression bipolar disorder and seasonal affective disorder How Will My Monit
103. nt8 amp address LSB uint8 amp registerPointer FRAM DATA 9 registerPointer address 15 READ ERAN FROM ADDRESS BYTE1 amp i2c pg addr amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAM DATA 10 registerPointer 511132 29 ifndef define SI1132_H_ SI1132_H_ endif SI1132_H_ COMMANDS define define define define define define define define define define define define define define define SI1132_PARAM_QUERY 0x80 511132 PARAM SET 511132 0x0 511132 RESET 0x01 SI1132 BUSADDR 0x02 SI1132 PS FORCE 0x05 SI1132 ALS FORCE 0x06 SI1132 PSALS FORCE 0x07 SI1132 PS PAUSE 0x09 SI1132 ALS PAUSE 0x0A SI1132 PSALS PAUSE OxB SI1132 PS AUTO x D 511132 ALS AUTO 511132 PSALS AUTO OxOF SI1132 GET CAL 0x12 Parameters define define define define define define define define define define define define define define define define define define define define define define define define define define define define define define define define define SI1132 PARAM I2CADDR 0x00 SI1132 PARAM CHLIST 9501 SI1132 PARAM CHLIST ENUV 0x80 SI1132 PARAM CHLIST ENAUX 0x40 SI1132 PARAM CHLIST ENALSIR 0x20 SI1132 PARAM CHLIST ENALSVIS 0x10 511132 PARAM CHLIST ENPS1 0x01 SI1132 PARAM CHLIST ENPS2 0x02 SI1132 PARAM CHLIST ENPS3 0x04 511132 PARAM PSLED12SEL 0x02 SI1132 PARAM PSLED
104. nter SI1132 PSALS AUTO HalSensorWriteReg SI1132 REG COMMAND amp value_pointer BYTE1 uint16 SI1132 ReadUV void uinti16 registerPointer HalSensorReadReg SI1132 REG UVINDEXO uint8 amp registerPointer BYTE2 return registerPointer uint16 511132 ReadVisible void uint16 registerPointer HalSensorReadReg SI1132 REG ALSVISDATAO uint8 amp registerPointer BYTE2 return registerPointer 16 511132 ReadIR void 5 uint16 registerPointer HalSensorReadReg SI1132 REG ALSIRDATAO uint8 amp registerPointer BYTE2 return registerPointer uint16 511132 ReadProx void uint16 registerPointer HalSensorReadReg SI1132 REG PS1DATAO uint8 amp registerPointer BYTE2 return registerPointer 36 bool readSI1132 uint8 pBuf int32 UTCTime uint16 visible uint16 IR uint16 UV bool success SI1132 Select 511132 RESETFUNCTION 511132 SetCoefficients 511132 EnableUV SI1132 EnableInterrupOnEverySample SI1132 ProximitySensorSetup 511132 AutoMeasure ST HAL DELAY 180 Read the three registers success HalSensorReadReg SI1132 REG UVINDEXO uint8 amp UV BYTE2 success HalSensorReadReg ACC REG ADDR XOUT H amp x sizeof x if success t success HalSensorReadReg SI1132 REG ALSVISDATAO uint8 amp visible BYTE2 if success success HalSensorReadReg SI1132 REG ALSIRDATAO uint8 amp IR BYTE2 if
105. oid 511132 WriteParameters char target char parameters uint8 registerPointer uint8 value pointer value pointer parameters HalSensorWriteReg SI1132 REG PARAMWR amp value pointer BYTE1 Pass parameter x to the mailbox register host to sequencer value pointer target SI1132 PARAM SET HalSensorWriteReg SI1132 REG COMMAND amp value pointer 1 Sets parameter pointed by target with value just placed into mailbox register 34 HalSensorReadReg SI1132 REG PARAMRD uint8 amp registerPointer 1 Read from the mailbox register sequencer to host required to clear uint8 511132 ReadParameters char target uint8 registerPointer uint8 value pointer value pointer target SI1132 PARAM QUERY HalSensorWriteReg SI1132 REG COMMAND amp value pointer BYTE1 HalSensorReadReg SI1132 REG PARAMRD uint8 amp registerPointer BYTE1 return registerPointer void 511132 EnableInterrupOnEverySample void 5 uint8 value pointer value pointer SI1132 REG INTCFG INTOE HalSensorWriteReg SI1132 REG INTCFG amp value pointer BYTE1 value pointer SI1132 REG IRQEN ALSEVERYSAMPLE HalSensorWriteReg SI1132 REG IRQEN amp value pointer BYTE1 void SI1132 ProximitySensorSetup void uint8 value pointer value pointer 0x03 program LED current HalSensorWriteReg SI1132 REG PSLED21 amp value pointer BYTE1 20mA for LED 1 only S11132 WriteParameters SI1132 P
106. ointed at subsequently reading the voltage change in its internal thermocouple array and outputting a temperature measurement This was beneficial because it allowed for a non invasive way to determine a user s skin temperature and also had a small footprint on the PCB 1 LM3658 The Texas Instruments LM3658 LiPo battery charging IC was http www ti com pr chosen to allow a user of the device to charge their device battery Y via a Mini USB connection while also allowing for the possible oduct LM3658 descri future addition of AC charging The LM3658 when connected to a ption 3 7V LiPo battery charges the battery at 4 2V at a rate of 100 or 500mA charge rate pin selectable and switches to maintenance mode upon sensing a full battery charge The support circuitry also featured charging status LEDs indicating battery level 1 TPS62203 The Texas Instruments TPS62203 DC DC Step Down Buck http www ti com pr Converter was chosen to convert the 3 7V LiPo battery output or gem the LM3658 output if no battery was connected to the 3 3V oduct t 562203 required by system components for operation The device also provided up to 300mA to the system which is necessary when all components are active at the same time The TPS62203 was chosen instead of a Low Drop Out Regulator in an attempt to reduce heat dissipation inside the enclosure while also improving performance Submit your TI Innovation Challenge project to http
107. omatically connects to the device upon successful start up initialization mBluetoothLeService connect mDeviceAddress Override public void onServiceDisconnected ComponentName componentName mBluetoothLeService null E Handles various events fired by the Service ACTION GATT CONNECTED connected to a GATT server ACTION DISCONNECTED disconnected from a GATT server ACTION GATT SERVICES DISCOVERED discovered GATT services ACTION DATA AVAILABLE received data from the device This be a result of read II or notification operations private final BroadcastReceiver mGattUpdateReceiver new BroadcastReceiver Override public void onReceive Context context Intent intent final String action intent getAction if BluetoothLeService ACTION_GATT_CONNECTED equals action Log i ON GATT CONNECTED 1 mConnected true updateConnectionState R string connected invalidateOptionsMenu Log i ON GATT CONNECTED 2 else if BluetoothLeService ACTION_GATT_DISCONNECTED equals action mConnected false updateConnectionState R string disconnected 85 invalidateOptionsMenu clearUl Log i ON GATT DISCONNECTED else if BluetoothLeService ACTION GATT SERVICES DISCOVERED equals action JI Show all the supported services and characteristics on the user interface Log i ON GATT SERVICE DISCOVERED OK displayGattServices mBluetoothLeService
108. on turns off the TMP006 sensor IRTemperature States t HallRTempStatus This function returns the state that the TMP006 sensor is in If the Sensor is on this function will check if data is ready to be read from the TMP006 registers Operation The TMP006 is polled every 15 minutes Once the polling of the TMP006 has been enabled in the main MCU software code SensorTag c the TMP006 is first checked for the status of the sensor If the sensor is off the TMP006 is turned on If the sensor is on than the TMPOO6 is checked for the status of the data in its internal register If the data is ready than the readlRTempData UTCTime function is called The calling block of code sends the current UTCTime to this function and it is processed the exact same way as in the previous sensors described above Inside the readIRTempData function the Object Voltage VObj value and Ambient Temperature Temp values are read from the 06 registers These data values 2 byte unsigned values Once these values are read the data is passed into the 11 byte data holding array which is used for FRAM The big endian format of this array is shown below Header UTCmsb1 UTCmsb2 UTCIsb1 UTCIsb2 0 0 VObjESB VObjMSB TempLSB TempMSB 22 Note The Header value for any 006 data is always 4 This value is used for our Bluetooth communication between MCU and Phone as the phone will be able to decode which data it is by the header ADXL345 hal
109. or Help Me Circadian Rhythms are affected by a number of signals from one s environment the most significant being light exposure In order to track your own circadian rhythms this device has been outfitted with light sensors capable of tracking UV IR and visible light intake The device also has the capabilites of monitoring motion skin temperature and heart rate in order to capture a vivid picture of the factors affecting your circadian rhythms Included in your kit e Circadian Rhythm Monitor e Mini USB Cable e Circadian Rhythm Analyzer Android Application Setup 1 Plugin the mini USB to the device Plug the other end into a USB receptacle An internal red light should come on indicating its charging status When the internal light turns off your device is ready for use Strap the device to your right hand so that the status LED s are oriented in the bottom right corner This ensures proper alignment of the heart rate sensor 4 Install the Circadian Rhythm Analyzer application on your android device This can be found the Android App store or downloaded online Syncing Date and Time 1 Open the Circadian Rhythm Analyzer application on your Android device 2 Select Sync Phone 3 On your Circadian Rhythm Monitor push the button in the upper left corner to turn on Bluetooth Low Energy connectivity The BLE indicator light should begin flickering 4 Your Circadian Rhythm Monitor should now show up on you
110. othAdapter null mBluetoothGatt null Log w TAG BluetoothAdapter not initialized return mBluetoothGatt setCharacteristicNotification characteristic enabled Er Retrieves a list of supported GATT services on the connected device This should be invoked only after code BluetoothGatt discoverServices completes successfully return A code List of supported services public List lt BluetoothGattService gt getSupportedGattServices if mBluetoothGatt null return null return mBluetoothGatt getServices public BluetoothGatt getGatt return mBluetoothGatt BPM GRAPHER java package com example android bluetoothlegatt import java io BufferedReader import java io FileNotFoundException import java io FileReader import java io OException import java io InputStream import java io InputStreamReader import java text SimpleDateFormat import java util ArrayList import java util Calendar import java util Date import java util TimeZone import com jjoe64 graphview CustomLabelFormatter import com jjoe64 graphview GraphView 76 import com jjoe64 graphview GraphView GraphViewData import com jjoe64 graphview GraphViewSeries import com jjoe64 graphview LineGraphView import android app Activity import android os Bundle import android os Environment import android util Log import android widget LinearLayout public class GRAPHER exten
111. p 0Ox00ff if address lt 65536 pgselect 0 i2c pg addr 0x50 0 HallI2CInit 0x50 i2cClock 533KHZ Jelse i2c pg addr 0x51 0 HalI2CInit 0x51 i2cClock 533KHZ 27 WRITE TO FRAM TEST uint8 amp address MSB uint8 amp address LSB uint8 amp data void WRITE SENSORDATA FRAM int32 address uint8 data_array uint8 i2c pg addr 0x00 uint8 address MSB address amp Oxff00 gt gt 8 uint8 address LSB address amp 0Ox00ff if address lt 65536 pgselect 0 i2c pg addr 0x50 0 HallI2CInit 0x50 i2cClock 533KHZ Jelse i2c pg addr 0x51 0 112 0 51 i2cClock 533KHZ void uint8 MSB uint8 LSB uint8 data array WRITE SENSOR DATA TO FRAM uint8 amp address MSB uint8 amp address LSB data array void READ CURRENT DATA int32 address uint8 FRAM DATA uint8 i2c pg addr 0x00 uint8 address MSB address amp Oxff00 gt gt 8 uint8 address LSB address amp 0x00ff uint8 registerPointer 0x00 if address lt 65536 pgselect 0 i2c pg addr 0x50 0 HallI2CInit 0x50 i2cClock 533KHZ Jelse i2c pg addr 0x51 0 HallI2CInit 0x51 i2cClock 533KHZ READ ERAN FROM ADDRESS BYTE1 amp i2c pg uint8 amp address MSB uint8 amp address LSB uint8 amp registerPointer FRAN DATA 0 registerPointer address_LSB READ_FRAM_FROM_ADDRESS BYTE1 amp i2c pg
112. r 47 int32 gmtUTC yearSeconds leapyearSeconds monthSeconds daySeconds hourSeconds minSeconds estToGMT 90062 return gmtUTC HAL ACC H ifndef HAL ACC H define HAL ACC H ifdef _ cplusplus extern endif include comdef h define HAL ACC RANGE 8G define HAL ACC RANGE 46 define HAL ACC RANGE 2G 48 void HalAccInit void bool HalAccRead uint8 pBuf bool HalAccTest void void HalAccSetRange uint8 range ifdef _ cplusplus J endif endif E HAL ACC C include hal acc h include hal sensor h include hal i2c h include hal board cfg h Sensor I2C address define HAL KXTI9 I2C ADDRESS KXTI9 register addresses define ACC REG ADDR XOUT HPF L define ACC REG ADDR XOUT HPF H define ACC REG ADDR YOUT HPF L define ACC REG ADDR YOUT HPF H define ACC REG ADDR ZOUT HPF L define ACC REG ADDR ZOUT HPF H define ACC REG ADDR XOUT L define ACC REG ADDR XOUT H define ACC REG ADDR YOUT L define ACC REG ADDR YOUT H 0 0 0 0 0 0 0 D define ACC REG ADDR ZOUT L define ACC REG ADDR ZOUT H define ACC REG ADDR DCST RESP define ACC REG ADDR WHO AM I define ACC REG ADDR TILT POS CUR define ACC REG ADDR TILT POS
113. r phone as an available device to connect to If it does not select Sync in the upper right corner of the application Select the device 5 Onthe next screen select Sync Time 16 6 When this is selected the sensors on the device are enabled and begin reading visible light IR light UV light your heart rate your skin temperature and your motion This data is collected and stored on board your Circadian Rhythm Monitor Turn off Bluetooth Low Energy on your Circadian Rhythm Monitor by holding down the button on the device for approximately 5 seconds until the BLE indicator light turns solid then release the button Turning off BLE on your device will provide you with better battery life Sync Data Collected Data omo e Open the Circadian Rhythm Analyzer application on your Android device Select Sync Phone On your Circadian Rhythm Monitor push the button in the upper left corner to turn on Bluetooth Low Energy connectivity The BLE indicator light should begin flickering Your Circadian Rhythm Monitor should now show up on your phone as an available device to connect to If it does not select Sync in the upper right corner of the application Select the device On the next screen select Sync Data Data will begin transmission from the Circadian Rhythm Monitor to your Android device Progress is shown on the bottom of the screen please do not disconnect your device during this process As data is collected a CSV
114. ra bpm data Iprivate ArrayList lt TMPO06_Obj gt TMP DATA ArrayList TMP006 Obj getIntent getSerializableExtra tmpO06 data private final static String TAG CopyOfGrapher class getSimpleName protected void onCreate Bundle savedinstanceState super onCreate savedInstanceState setContentView R layout test ADKL DATA ArrayList lt ADXL_Obj gt getlntent getSerializableExtra adxl data if ADXL_DATA size gt 0 GraphViewData data new GraphViewData ADXL_DATA size int i 0 for ADXL_Obj adxl ADXL_DATA Log d TAG DATA adxl getData Log d TAG DATAX adxl getX Log d TAG DATAY adxl getY Log d TAG DATAZ adxl getZ Log d TAG DATAMAG adxl getMagnitude data i new GraphViewData adxl getUTC adxl getMagnitude itt GraphView graphView new LineGraphView this GraphViewDemo y add data graphView addSeries new GraphViewSeries data set view port start 2 size 40 graphView setViewPort 2 40 graphView setScrollable true H optional activate scaling zooming graphView setScalable true LinearLayout layout LinearLayout findViewByld R id graph1 layout addView graphView int num 150 double v 0 80 for int i 0 i lt num i v 0 2 csv data selector java package com example android bluetoothlegatt import java io File import java util ArrayList import com jjoe6
115. re C double Vobj2 double qinti6 rawT Vobj2 0 00000015625 double Tdie2 m tmpAmb 273 15 const double 50 6 4E 14 Calibration factor const double a1 1 75E 3 const double a2 1 678E 5 65 const double b 2 94E 5 const double b1 5 7E 7 const double b2 4 63E 9 const double c2 13 45 const double Tref 298 15 double S Se 1 ai1 Tdie2 Tref a2 pow Tdie2 Tref 2 double Vos be b1 Tdie2 Tref b2 pow Tdie2 Tref 2 double fObj Vobj2 Vos c2 pow Vobj2 Vos 2 double tObj pow pow Tdie2 4 fObj S 25 tObj tObj 273 15 return tObj sk sk sk sk ok ok ok ok sk oR ok 66 Appendix Android Application Source Code ADXL GRAPHER java package com example android bluetoothlegatt import java io BufferedReader import java io FileNotFoundException import java io FileReader import java io IOException import java io InputStream import java io InputStreamReader import java text SimpleDateFormat import java util ArrayList import java util Calendar import java util Date import java util TimeZone import com jjoe64 graphview CustomLabelFormatter import com jjoe
116. reate savedinstanceState setContentView R layout test Bundle extras UVLIGHT_GRAPHER this getIntent getExtras ArrayList lt GraphViewData gt data new ArrayList lt GraphViewData gt file extras getString EXTRAS_FILE_NAME file Environment getExternalStorageDirectory file II file sdcard file BufferedReader reader null try reader new BufferedReader new FileReaderf file catch FileNotFoundException e1 TODO Auto generated catch block e1 printStackTrace try String line while line reader readLine null String RowData line split String type RowData 0 replace trim String date RowData 1 replace trim String light RowData 2 replace trim String utc RowData 3 replace trim if type equals UV Log d TAG IN HERE type Log d TAG IN HERE UTC double Long parseLong utc Log d TAG IN HERE UVLIGHT Float parseFloat light data add new GraphViewData double Long parseLong utc Double parseDouble light catch IOException ex H handle exception finally try reader close catch IOException e handle exception GraphView graphView new LineGraphView this UV Light UV Index graphView setCustomLabelFormatter new CustomLabelFormatter Override public String formatLabel double value boolean isValueX if isValueX
117. red if GSR was incorporated into the system Knowing an individual s GSR could help reduce errors during sensor readings That data may also be useful when put alongside data from the other sensors This could be done via a Wheatstone bridge op amp circuit connected to the microcontroller s ADC e Data Analysis This project focused primarily on gathering and presenting the collected data in a way that would be meaningful for a professional to examine and determine trends It would be ideal if more data analysis could be done that would aid the professionals and save them time in processing the data For example if certain events were to happen then a flag could be raised alerting the professional to a disturbance in an individual s circadian rhythm 10 558 Breca oru 050 8 PECIAL DRILL 0 1560 5 o GND ISET 8 USE_SESTAT 5 EN B starz Hi Brecht DRILL 0 1560 z T i z NET reves use 2 z 2222222228 Appendix A Schematic 11 Appendix B Board Layout Bottom 12 Appendix Bill of Materials Designator Quantity Per Board C7 C10 C2 SI1143 C6 C39 C9 C23 C25 C26 C28 C31 C32 C33 C34 C37 C38 C41 C42 C27 C29 C30 C35 C36 L1 Antenna F1 IC1 2 IC4 U2 U1 U3 U4 Mini USB J1 JP1 X1 2 D2 power supply indicators LED4 LED5 2 IR LEDS Heart Rate Other Red LE
118. return getDateCurrentTimeZone long value 119 return null D GraphViewData input new GraphViewData data size for int i 0 i lt input length i input i data get i H add data graphView addSeries new GraphViewSeries input set view port start 2 size 40 graphView setViewPort 2 40 graphView setScrollable true II optional activate scaling zooming graphView setScalable true LinearLayout layout LinearLayout findViewByld R id graph1 layout addView graphView private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getInstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timestamp 1000 calendar add Calendar MILLISECOND 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone catch Exception e return int num 150 double v 0 for int i20 i lt num i v 0 2 j Si VISLIGHT_GRAPHER java package com example android bluetoothlegatt import java io BufferedReader import java io FileNotFoundException import java io FileReader import java io IOException import java io InputStream import java io InputStreamReader import java text SimpleDateF ormat 120 import java util ArrayList import java util Calendar import java util Date import java
119. ry in order for the device to more accurately gather heart rate and skin temperature measurements This was due to interference between the two sensors between the sensors and the skin and between the sensors and the enclosure 7 Future Work amp Recommendations Future work that can be made to our system that would improve the overall performance is listed below e Heart Rate BPM Counter Due to lack of knowledge on the subject of pulse oximetry the algorithm created for the BPM counter was made off an interpretation of a research paper on the subject Further exploration and research on acquiring a BPM count is needed e Improved Synergy The PCB could be redesigned along with the mechanical enclosure to provide a better relationship between the two This would allow for the PCB to be moved closer to the skin and would likely improve skin temperature and heart rate measurements This would also allow for changes to be made to the enclosure that would decrease interference between sensors that rely on similar resources such as infrared light Additionally there is some room for system improvements beyond our original scope of work These potential improvements and features are listed below e Improved Device User Interface Rather than using an LED based interface the device could incorporate a low power screen alternative such as an OLED or E Ink display e Galvanic Skin Response Another potentially important metric that could be measu
120. s2 II CSV CSV CSV String first3 2 UV String second3 getDateCurrentTimeZone corrected UTC String third3 Float toString uv String fourth3 String valueOf UTC String entries3 first3 second3 third3 fourth3 split writer writeNext entries3 99 break case 3 BPM Log d TAG getDateCurrentTimeZone long UTC BPM DATA data string String BPM String data string replace Integer BPM Integer Integer parselnt BPM String 16 BPM Obj bpm data new BPM_Obj UTC data string DATA HOLDER add bpm data CSV CSV CSV String first BPM String second getDateCurrentTimeZone corrected UTC String third String valueOf BPM Integer String fourth String valueOf UTC String entries first second third fourth split writer writeNext entries break case 4 006 Log d TAG getDateCurrentTimeZone long UTC TMP006 DATA data string TMPO006 Obj tmp data new 06 ODj UTC data string Log d TAG TMP006 DATA ACTUAL TEMP tmp data getTemp if realTime true if Double isNaN tmp data getTemp tmp data getTemp 0 break _realTimeTempdata setText Temperature tmp data getTemp F else 006 DATA HOLDER add tmp data double temp tmp data getTemp if Double isNaN temp temp 0 break CSV CSV CSV S
121. single press of the button Two status LEDs provided power state and Bluetooth transmission indication One LED remains on when the device is powered on and the other blinks rapidly when the button is pressed and Bluetooth begins searching for connectivity BLE Status Indicator Power Status LED BLE Broadcasting Button Figure 7 3D Printed Enclosure 6 Testing Results amp Conclusions Upon testing our device we were able to gather the all of the parameters related to a user s circadian rhythm that we planned for in our initial project goals The degree of accuracy of the sensors varied the light sensor and accelerometer providing very accurate measurements and the heart rate and skin temperature sensors lacking in accuracy This lack of accuracy was likely due to the inadequate interfacing of the sensors to the parameter they were analyzing i e the surface of the user s skin The accuracy was also impaired by the data outliers that occurred during sensor readings This data was verified using existing products that are available on the market as well as tools such as an infrared heat gun and pulse oximeter Despite the outliers we concluded that the device could 9 realistically be used to gather usable data pertaining to a user s motion and light exposure while also gathering reasonable data pertaining to an individual s heart rate and skin temperature We also determined that modifications to the enclosure design would be necessa
122. success Valid data uint8 LSB byte2 UTCTime amp 0x000000ff uint8 LSB_byte1 UTCTime 8 0x0000ff00 gt gt 8 uint8 MSB byte2 UTCTime amp 0 00 0000 gt gt 16 uint8 MSB_byte1 UTCTime amp Oxff000000 gt gt 24 pBuf 0 25 pBuf 1 MSB byte1 pBuf 2 MSB byte2 pBuf 3 LSB byte1 pBuf 4 LSB byte2 pBuf 5 HI UINT16 visible pBuf 6 LO UINT16 visible pBuf 7 HI UINT16 IR pBuf 8 LO UINT16 IR pBuf 9 HI UINT16 UV pBuf 10 LO UINT16 UV 37 Turn off sensors S11132 WriteParameters SI1132 PARAM CHLIST 0x00 return success 511143 ifndef 511143 H define 511143 H amp endif 511143 include bcomdef h include OSAL h include OSAL PwrMgr h include OnBoard h include hal adc h include hal led h include hal keys h include hal i2c h include gatt h amp include hci h include gapgattserver h include gattservapp h iif defined PLUS BROADCASTER include peripheralBroadcaster h 1 lt include peripheral h endif include gapbondmgr h if defined FEATURE_OAD include oad h include oad target h endif Services include st_util h include devinfoservice st h include irtempservice h include accelerometerservice h include SI1132service h include humidityservice h include magnetometerservice h include testwritetimeservice h incl
123. ter The following functions are used for the 511143 Functions void SI1143 Select This function is used for the MCU to initialize a new i2c connection between the CC2541 and the SI1143 void 511143 initPulseSensor This function is the main firmware code that drives the 511143 sensor It is in charge of initializing and calibrating the sensors in the same matter as the 511132 above In addition to IR ADC 21 sampling rate etc sensor calibrations this function is in charge of turning on the red LED and calibrating the current consumption and brightness of the LED Uint8 511143 ReadParameters char target This function is a helper function which returns the 1 byte value from the passed in register void SI1143 WriteParameters char target char parameters This function writes a value to the 511143 internal registers Operation The Heart Rate BPM calculations are all done within the MCU software code SensorTag c The 511143 is polled every 15 minutes Once an Event is triggered in the software to poll 511143 it is turned on To produce the beats per minute calculation once this sensor is polled the current internal timer of the MCU in milliseconds is checked to see if it has run for 20 seconds This can be changed to another amount of time During these 20 seconds the red LED shoots light up into the wrist where this device is worn The IR sensors calculate the reflectance of this light that is being reflected from the
124. tifyCharacteristic characteristic mBluetoothLeService setCharacteristicNotification characteristic true return true return false private void clearUI 1 mGattServicesList setAdapter SimpleExpandableListAdapter null mDataField setText R string no data Override public void onCreate Bundle savedInstanceState super onCreate savedinstanceState setContentView R layout gatt_services_characteristics final Intent intent getIntent 86 mDeviceName intent getStringExtra EXTRAS DEVICE NAME mDeviceAddress intent getStringExtra QEXTRAS DEVICE ADDRESS Sets up UI references TextView finaViewByld R id device address setText mDeviceAddress mGattServicesList ExpandableListView find ViewById R id gatt services list mGattServicesList setOnChildClickListener servicesListClickListner mConnectionState TextView findViewByld R id connection_state mDataField TextView findViewByld R id data_value getActionBar setTitle mDeviceName getActionBar setDisplayHomeAsUpEnabled true Intent gattServicelntent new Intent this BluetoothLeService class bindService gattServicelntent mServiceConnection BIND AUTO CREATE Override protected void onResume super onResume registerReceiver mGattUpdateReceiver makeGattUpdatelntentFilter if mBluetoothLeService null final boolean result mBluetoothLeService connect mDeviceAddress Log d TAG
125. tiic na hartehanks com Your team is encouraged to post your project as early as possible Your submission will be kept offline until the contest has officially closed Instructions Submit your project and include the following documents o Your full class report which much include this TI project report o Upload a video of demonstrating your project to www ti com vidoes must log into and provide the link to that video in this project report We d love to see your team engaging with TI products o Link to supplemental photos Project abstract a short high level written description of the design and motivation behind project 1 000 words max Among the growing popularity and excitement surrounding the wearable fitness sleep tracker market a need for a cheaper and more accurate device has emerged The purpose of this project was to produce a functional prototype which will effectively monitor an individual s circadian rhythm while also addressing existing accuracy and cost issues related to fitness sleep tracking devices The function of our system is based on the acquisition and interpretation of data pertinent to a user s circadian rhythm Using appropriate sensors the system will acquire process and display measurements of a variety of physiological and environmental variables for a user of the device i e heart rate skin temperature motion and ambient UV light exposure The sensor data is stored in the inter
126. time and date given a time from the phone during synchronization The UTC was implemented in response to not having a RTC A user 23 syncs up their phone and sends the current date and time to the MCU From there the UTC function will then take in the parameters such as month day year hour and minute and convert them into the UTC format of milliseconds since 1970 This time is then saved on the MCU where it is used to determine the exact time and date polling of data occurred 24 Appendix I Android Application File Descriptions Understanding the fundamentals of Bluetooth Low Energy is paramount in creating a successful BLE enabled Android application The intention of this section of the report is to explain the details of the major components of each java file It is assumed that the reader has basic understanding of the BLE stack and a background in java and android development Also note that data type is representative of all of the different types of data we are collecting from our wrist device visible light IR light UV light motion BPM temperature etc data type GRAPHER java These sections of code bring in the filename selected from the previous intent It uses that filename to access the file of the same name saved on an external storage The file which will always be a CSV is opened and is parsed line by line The parser is looking for only data that is of interest to the user which is determined in the previous
127. to us because it reduced the number of components needed for BLE connectivity rather than adding an additional IC just for BLE communication The BLE pins of the CC2541 only needed to be routed to a surface mount BLE antenna in order for data transmission to be possible Additionally extra memory was required on top of the 256k memory of the CC2541 to store sensor data so the FM24V10 FRAM memory IC was chosen This provided ample storage capacity for our application and allowed data to be stored temporarily without the need for continuous Bluetooth communication 4 Software Design 4 1 MCU Firmware Design Our device s firmware uses Texas Instrument s open source SensorTag code as the basis for its design The reason why we chose to use this open source provided by TI is because it helped simplify of all our event processing sending and communication BLE events for our system Therefore during development of our device we saved time by not having to worry about underlying event processing and message sending firmware design This allowed us to focus on developing firmware to enable the communication and use of our device sensors 511132 511143 ADXL345 006 with the CC2541 Furthermore this allowed us to also focus on developing firmware for the CC2541 to use external FRAM FM24V10 as well as developing software that controls sensor execution for data polling as well as a Unix Time Clock implementation to keep track of real time as our
128. tring 0 Integer header Integer parselnt delimitString 0 charAt 2 String UTCtime delimitString 1 delimitString 2 delimitString 3 delimitString 4 Integer UTC Integer parselnt UTCtime 16 Integer corrected_UTC UTC 86400 H long ts long UTC 1 Date localTime new Date ts String format yyyy MM dd HH mm ss SimpleDateFormat sdf new SimpleDateFormat format Log d TAG UTC String dateAsText new SimpleDateFormat yyyy MM dd HH mm ss format new Date Integer parselnt UTCtime 16 1000L Log d TAG getDateCurrentTimeZone long UTC data string delimitString 5 delimitString 6 delimitString 7 delimitString 8 delimitString 9 delimitString 10 if UTC 0 switch header case 0 empty Log d TAG getDateCurrentTimeZone long UTC EMPTY DATA data string break case 1 ADXL Log d TAG ADXL DATA data string ADXL Obj adxl data new ADXL_Obj UTC data string if realTime true _realTimeXdata setText X Data adxl data getX m s 2 _realTimeYdata setText Y Data adxl data getY m s 2 _realTimeZdata setText Z Data data getZ m s 2 98 1 ADXL DATA HOLDER add adxl data double mag adxl data getMagnitude if mag 0 break II CSV CSV CSV String first Accelerometer String
129. tring first Temperature String second1 getDateCurrentTimeZone corrected UTC String third1 String valueOf temp String fourth1 String valueOf UTC String entries1 first1 second1 third1 fourth1 split writer writeNext entries 1 private String getDateCurrentTimeZone long timestamp try Calendar calendar Calendar getlnstance TimeZone tz TimeZone getDefault calendar setTimelnMillis timestamp 1000 100 calendar add Calendar MILLISECOND 0 SimpleDateFormat sdf new SimpleDateFormat yyyy MM dd HH mm ss Date currenTimeZone Date calendar getTime return sdf format currenTimeZone catch Exception e return private void mGattServicesList setAdapter SimpleExpandableListAdapter null mDataField setText R string no_data public void onCreate Bundle savedinstanceState super onCreate savedinstanceState setContentView R layout init_option_select intent getIntent mDeviceName intent getStringExtra EXTRAS_DEVICE_NAME mDeviceAddress intent getStringExtra EXTRAS_DEVICE_ADDRESS mConnectionState TextView findViewByld R id connection_state Sets up UI references TextView findViewByld R id device_address setText mDeviceAddress Intent gattServicelntent new Intent this BluetoothLeService class bindService gattServicelntent mServiceConnection BIND AUTO CREATE final
130. try Thread sleep 100 catch InterruptedException e TODO Auto generated catch block e printStackTrace readCharacteristicValue LIGHT_DATA try Thread sleep 100 catch InterruptedException e TODO Auto generated catch block e printStackTrace readCharacteristicValue TEMP DATA new Thread runnable start private void sync_counter final Handler handler new Handler Runnable runnable new Runnable public void run while true try Thread sleep 500 catch InterruptedException e e printStackTrace handler post new Runnable 106 public void run data sync text setText Synching Data Block sync byte of 5957 if sync byte lt 50 characteristic getCharac FRAM CONFIG if characteristic null characteristic setValue new byte 0x01 gatt writeCharacteristic characteristic try Thread sleep 100 catch InterruptedException e e printStackTrace readCharacteristicValue FRAM_BUFFER sync_byte if sync_byte 50 try writer close catch IOException e Auto generated catch block 1 TODO e printStackTrace data sync text setVisibility thisView INVISIBLE InitOptionSelect this findViewByld R id data sync progressbar setVisibility thisView INVISIBLE intent putExtra adxl data ADXL DATA HOLDER intent putExtra light data LIG
131. ty private static CSVWriter writer null private static final UUID FRAM BUFFER UUID fromString fo00aa41 0451 4000 b000 000000000000 private static final UUID ADXL_DATA UUID fromString f000aa11 0451 4000 b000 000000000000 private static final UUID LIGHT DATA UUID fromString f000aa21 0451 4000 b000 000000000000 private static final UUID TEMP DATA UUID fromString f000aa01 0451 4000 b000 000000000000 private static final UUID FRAM CONFIG UUID fromString f000aa42 0451 4000 b000 000000000000 private static final UUID TIME_SERVICE UUID fromString fo00dd10 0451 4000 b000 000000000000 private static final UUID TIME MONTH CONFIG UUID fromString fo00dd13 0451 4000 b000 000000000000 private static final UUID TIME DAY CONFIG UUID fromString fo00dd14 0451 4000 b000 000000000000 private static final UUID TIME YEAR CONFIG UUID fromString fo00dd15 0451 4000 b000 000000000000 private final static String TAG DeviceControlActivity class getSimpleName public static final String EXTRAS_DEVICE_NAME DEVICE_NAME public static final String EXTRAS DEVICE ADDRESS DEVICE ADDRESS private BluetoothAdapter mBtAdapter private BluetoothGatt gatt private BluetoothDevice device private TextView mConnectionState private TextView data sync text private TextView mDataField private TextView realTimeXdata private TextView realTimeY data private TextView realTimeZdata priv
132. ude barometerservice h include gyroservice h 38 include testservice h include simplekeys h include ccservice h Sensor drivers include sensorTag h include hal sensor h include hal irtemp h include hal acc h include hal humi h include hal mag h include hal bar hi include hal gyro h include SI1132 h include UTCTime h COMMAND REGISTERS define cmd Forces a zero into the RESPONSE register define RESET cmd Performs a software reset of the firmware define BUSADDR cmd Modifies I2C address define PS FORCE cmd Forces a single PS measurement define PSALS FORCE cmd Forces a single PS and ALS measurement define PS PAUSE cmd Pauses autonomous PS define ALS PAUSE cmd Pauses autonomous ALS define PSALS PAUSE cmd Pauses PS and ALS define PS AUTO cmd Starts Restarts an autonomous PS Loop define ALS AUTO cmd Starts Restarts an autonomous ALS Loop define PSALS AUTO Starts Restarts autonomous ALS and PS loop PARAMS define 511143 PARAM SET xAQ define SI1143 PARAM QUERY 0x80 define SI1143 PARAM I2C ADDR define SI1143 PARAM CH LIST define 511143 PARAM PSLED12 SELECT define SI1143 PARAM PSLED3 SELECT define SI1143 PARAM FILTER EN define 511143 PARAM PS ENCODING define SI1143 PARAM ALS ENCODING define SI1143 PARAM PS1 ADCMUX define SI1143 PARAM PS2 ADCMUX define 511143 PARAM PS3 ADCMUX define 511143 PARAM PS ADC COU
133. ugh BluetoothManager final BluetoothManager bluetoothManager BluetoothManager getSystemService Context BLUETOOTH_SERVICE mBluetoothAdapter bluetoothManager getAdapter Checks if Bluetooth is supported on the device if mBluetoothAdapter null Toast makeText this R string error bluetooth not supported Toast LENGTH_SHORT show finish return Override public boolean onCreateOptionsMenu Menu menu getMenulnflater inflate R menu main menu if ImScanning menu findltem R id menu stop setVisible false menu findltem R id menu scan setVisible true menu findltem R id menu refresh setActionView null else menu findltem R id menu stop setVisible true menu findltem R id menu scan setVisible false menu findltem R id menu refresh setActionView R layout actionbar indeterminate progress return true Override public boolean onOptionsltemSelected Menultem item switch item getltemld case R id menu_scan mLeDeviceListAdapter clear scanLeDevice true break case R id menu stop 90 scanLeDevice false break return true Override protected void onResume super onResume Ensures Bluetooth is enabled on the device If Bluetooth is not currently enabled II fire an intent to display a dialog asking the user to grant permission to enable it if ImBluetoothAdapter isEnabled if ImBluetoothAdapter isEnabled Intent enableBt
134. ur and minutes sent from the phone in hexadecimal values Upon receiving all of these values from the phone when synchronized the MCU begins to poll and process events related to the sensors The FRAM service is important to the overall operation of our device because when the phone and MCU are synchronized the FRAM service is used to offload the data that the current FRAM pointer is at 19 Appendix Datasheets and References 2541 Microcontroller Datasheet http www ti com lit ds symlink cc2541 pdf User Guide http www ti com lit ug swru191f swru191f pdf 811132 Light Sensor Datasheet http www silabs com Support 20Documents TechnicalDocs Si1132 pdf 11143 Light Sensor Datasheet http www silabs com Support 20Documents TechnicalDocs Si114x pdf ADXL345 Accelerometer Datasheet http www analog com static imported files data_sheets ADXL345 pdf TMP006 IR Temperature Sensor Datasheet http www ti com lit ds symlink tmp006 pdf User Guide http www ti com lit ug sbou107 sbou107 pdf Layout and Assembly Guide http www ti com lit ug sbou108 sbou108 pdf FM24V10 FRAM Datasheet http www cypress com docID 48138 TPS62203 DC DC Step Down Buck Converter Datasheet http www ti com lit ds symlink tps62203 pdf LM3658 Dual Source USB AC Li Chemistry Charger IC for Portable Applications Datasheet http www ti com lit ds symlink Im3658 pdf Android Development Sources Bluetooth Low Energy https develop
135. util TimeZone import com jjoe64 graphview CustomLabelFormatter import com jjoe64 graphview GraphView import com jjoe64 graphview GraphView GraphViewData import com jjoe64 graphview GraphViewSeries import com jjoe64 graphview LineGraphView import android app Activity import android os Bundle import android os Environment import android util Log import android widget LinearLayout public class VISLIGHT GRAPHER extends Activity private final static String TAG VISLIGHT_GRAPHER class getSimpleName String file String H getintent getSerializableExtra EXTRAS FILE String file sdcard abc csv public static String file protected void onCreate Bundle savedinstanceState super onCreate savedinstanceState setContentView R layout test Bundle extras VISLIGHT GRAPHER this getlntent getExtras ArrayList lt GraphViewData gt data new ArrayList lt GraphViewData gt file extras getString EXTRAS_FILE_NAME file Environment getExternalStorageDirectory file file sdcard file BufferedReader reader null try reader new BufferedReader new FileReader file catch FileNotFoundException e1 TODO Auto generated catch block e1 printStackTrace try String line while line reader readLine null String RowData line split String type RowData 0 replace trim String date RowData 1 replace
136. v getld R id viewUVLIGHT Intent LIGHTintent new Intent this UVLIGHT_GRAPHER class LIGHTintent putExtra EXTRAS FILE filename startActivity LIGHTintent else if v getld R id viewIRLIGHT Intent LIGHTintent new Intent this IRLIGHT GRAPHER class LIGHTintent putExtra EXTRAS FILE filename startActivity LIGHTintent else if v getld R id viewTEMP Intent LIGHTintent new Intent this TEMPERATURE GRAPHER class LIGHTintent putExtra EXTRAS FILE filename startActivity LIGHTintent else if v getld R id viewBPM Intent BPMintent new Intent this BPM_GRAPHER class BPMintent putExtra EXTRAS FILE filename startActivity BPMintent csv select java package com example android bluetoothlegatt import java io File import java util ArrayList import java util Collections import com jjoe64 graphview GraphView import com jjoe64 graphview GraphView GraphViewData import com jjoe64 graphview GraphViewSeries import com jjoe64 graphview LineGraphView import android app Activity import android content Intent import android os Bundle import android os Environment import android util Log import android view View import android widget AdapterView import android widget ArrayAdapter 82 import android widget Button import android widget ExpandableListView import android widget LinearLayout import android wid
137. void readbacks adxl range range bool readAcc uint8 pBuf int32 UTCTime HalAccSelect setRange ADXL345 RANGE 16 G uint8 registerPointer bool success HalSensorReadReg ADXL345 REG DEVID uint8 amp registerPointer 1 printf nREGISTERPOINTER x n registerPointer if success if registerPointer 5 Turn on sensor uint8 value pointer 0x08 HalSensorWriteReg ADXL345 REG POWER CTL amp value pointer 1 54 printf INSIDE READACCNn uint16 x uint16 y uint16 2 Select this sensor Wait for measurement ready appx 1 45 ms ST HAL DELAY 180 Read the three registers success HalSensorReadReg ADXL345 REG DATAXO uint8 amp x 2 success HalSensorReadReg ACC REG ADDR XOUT H amp x sizeof x if success success HalSensorReadReg ADXL345 REG DATAYO uint8 amp y 2 if success t success HalSensorReadReg ADXL345 REG DATAZO uint8 amp z 2 if success t printf printf X x n x printf XACCL f n float int x ADXL345 MG2G MULTIPLIER SENSORS_GRAVITY_STANDARD Valid data uint8 LSB byte2 UTCTime amp 0x000000ff uint8 LSB_byte1 UTCTime amp 0x0000ff00 gt gt 8 uint8 MSB byte2 UTCTime amp 0 00 0000 gt gt 16 uint8 MSB_byte1 UTCTime amp Oxff000000 gt gt 24 pBuf 0 1 pBuf 1 MSB byte1 pBuf 2 MSB byte2 pBuf 3 LS
Download Pdf Manuals
Related Search
Related Contents
KitchenAid KCMS135H User's Manual Bedienungsanleitung Computer NOVAPLUS-10 Calendrier des collectes de déchets 2011 環境活動レポート - エコアクション21 BACK - PROFI - Alle-Bedienungsanleitungen.de CNC Laser Lab Manual - Jonathan Hils, Associate Professor TROUBLESHOOTING GUIDANCE FOR USERS OF EMPLOYEE Copyright © All rights reserved.
Failed to retrieve file