• If you are citizen of an European Union member nation, you may not use this service unless you are at least 16 years old.

  • Finally, you can manage your Google Docs, uploads, and email attachments (plus Dropbox and Slack files) in one convenient place. Claim a free account, and in less than 2 minutes, Dokkio (from the makers of PBworks) can automatically organize your content for you.



Page history last edited by Jerry_Qiu 7 years, 9 months ago

Jerry Qiu

EE 47

Dr. Sirkin

Aug. 17th, 2013

Final Project Documentation

Point of View

-let people be able to sit comfortably on a train or a bus;

-let people be able to listen to music while they are on a train or a bus;

-functions as an electronic lock, meaning it can let the user know when somebody tries to steal something from his/her backpack (even when the user is sleeping);


Verplank diagram

Paper prototype

State diagram


I use two arduinos in my project: one for MP3 player, while the other for remote control and the lock, so there are two pieces of code.


-MP3 Code

1. main code (named “final_project”)


// ---- includes and defines ------------------------------------------------


// first step is to include (arduino) sd, eeprom and (our own) mp3 libraries.


#include <SD.h>

#include <EEPROM.h>


#include <mp3.h>

#include <mp3conf.h>


// include the adafruit pcd8544 & gfx libraries for a nokia 5110 graphic lcd.




// setup microsd and decoder chip select pins, and the decoder-specific pins.


#define sd_cs 17 // 'chip select' line for the microsd card


#define mp3_cs A0 // 'command chip select' connect to cs pin

#define mp3_dcs A1 // 'data chip select' connect to bsync pin

#define mp3_rst -1 // 'reset' connects to decoder's reset pin

#define mp3_dreq A2 // 'data request line' connect to dreq pin


// now assign pins for the graphic lcd (carried over from the etch-a-sketch).



// 'read_buffer' is the amount of data read from microsd and sent to decoder.

// it's probably best to keep this a factor of 2, up to about 1kb (2kb is the

// max). you might change this if you experienced skips during song playback.


#define read_buffer 512 // size (bytes) of the microsd read buffer

#define mp3_vol 210 // default volume. range min=0 and max=254


// file names are 13 bytes max (8 + '.' + 3 + '\0'), and the file list should

// fit into the eeprom. for example, 13 * 40 = 520 bytes of eeprom are needed

// to store a list of 40 songs. if you use shorter file names, or if your mcu

// has more eeprom, you can change these.


#define max_name_len 13

#define max_num_songs 40


// id3v2 tags have variable-length song titles. that length is indicated in 4

// bytes within the tag. id3v1 tags also have variable-length song titles, up

// to 30 bytes maximum, but the length is not indicated within the tag. using

// 60 bytes here is a compromise between holding most titles and saving sram.


// if you increase this above 255, look for and change 'for' loop index types

// so as to not to overflow the unsigned char data type.


#define max_title_len 60


// ---- global variables ----------------------------------------------------


// instantiate a graphic lcd object using the pins that we #define'd earlier.

// comment out the graphics lines to save memory if you're not using the lcd.



// 'File' is a wrapper of the 'SdFile' data type from the sd utility library.


File sd_file; // object to represent a file on a microsd


// store the number of songs in this directory, and the current song to play.


unsigned char num_songs = 0, current_song = 0;


// an array to hold the current_song's file name in ram. every file's name is

// stored longer-term in the eeprom. this array is used in 'sd_file.open()'.


char fn[max_name_len];


// an array to hold the current_song's title in ram. it needs 1 extra char to

// hold the '\0' that indicates the end of a character string. the song title

// is found in 'get_title_from_id3tag()'.


char title[max_title_len + 1];


// the program runs as a state machine. the 'state' enum includes the states.

// 'current_state' is the default as the program starts. add new states here.


enum state { DIR_PLAY, MP3_PLAY, PAUSED , PAUSED2 };

state current_state = DIR_PLAY;


volatile int alarm_value = 0;

//---- module functions -----------------------------------------------------


// you must open a song file that you want to play using 'sd_file_open' prior

// to fetching song data from the file. you can only open one file at a time.


void sd_file_open() {

// first, find the file name (that's stored in eeprom) of the current song.


// then open the file using the name we just found (stored in 'fn' global).

sd_file = SD.open(fn, FILE_READ);

// find the current song's title tag (if present) then print it to the lcd.




// read a number of bytes from the microsd card, then forward them to the Mp3

// library's 'play' function, which streams them out to the decoder chip.


void mp3_play() {

unsigned char bytes[read_buffer]; // buffer to read and send to the decoder

unsigned int bytes_to_read; // number of bytes read from microsd card


// first fill the 'bytes' buffer with (up to) 'read_buffer' count of bytes.

// that happens through the 'sd_file.read()' call, which returns the actual

// number of bytes that were read (which can be fewer than 'read_buffer' if

// at the end of the file). then send the retrieved bytes out to be played.

// 'sd_file.read()' manages the index pointer into the file and knows where

// to start reading the next batch of bytes. 'Mp3.play()' manages the index

// pointer into the 'bytes' buffer and knows how to send it to the decoder.


bytes_to_read = sd_file.read(bytes, read_buffer);

Mp3.play(bytes, bytes_to_read);

// 'bytes_to_read' is only smaller than 'read_buffer' when the song's over.


if (bytes_to_read < read_buffer) {


// if we've been in the MP3_PLAY state, then we want to pause the player.


if (current_state == MP3_PLAY) {

current_state == PAUSED;





// continue to play the current (playing) song, until there are no more songs

// in the directory to play. 2 other sd library methods (that we haven't used

// here) can help track your progress while playing songs: 'sd_file.size()' &

// 'sd_file.position()'. you can use these to show say, the percent of a song

// that has already played.

void dir_play() {

if (sd_file) {



else {

// since 'sd_file' isn't open, the recently playing song must have ended.

// increment the index, and open the next song, unless it's the last song

// in the directory. in that case, just set the state to PAUSED.


if (current_song < (num_songs - 1)) {




else {

current_song = 0;





// ---- setup and loop ------------------------------------------------------


// setup is pretty straightforward. initialize serial communication (used for

// the following error messages), mp3 library, microsd card objects, then the

// graphic lcd. then open the first song in the root library to play.


void setup() {

// initialize the mp3 library, and set default volume. 'mp3_cs' is the chip

// select, 'dcs' is data chip select, 'rst' is reset and 'dreq' is the data

// request. the decoder sets the 'dreq' line (automatically) to signal that

// its input buffer can accommodate 32 more bytes of incoming song data.

// the decoder's default state prevents the spi bus from working with other

// spi devices, so we initialize it first.

Mp3.begin(mp3_cs, mp3_dcs, mp3_rst, mp3_dreq);


// initialize the microsd (which checks the card, volume and root objects).


// putting all of the root directory's songs into eeprom saves flash space.


// the program is setup to enter DIR_PLAY mode immediately, so this call to

// open the root directory before reaching the state machine is needed.


attachInterrupt(1,paused_play, RISING);

attachInterrupt(0,alarm, RISING);



// the state machine is setup (at least, at first) to open the microsd card's

// root directory, play all of the songs within it, close the root directory,

// and then stop playing. change these, or add new actions here.


// the DIR_PLAY state plays all of the songs in a directory and then switches

// into PAUSED when done. the MP3_PLAY state plays one specific song and then

// switches into PAUSED. this sample player doesn't enter the MP3_PLAY state,

// as its goal (for now) is just to play all the songs. you can change that.


void loop() {

switch(current_state) {


case DIR_PLAY:




case MP3_PLAY:




case PAUSED:


case PAUSED2:



alarm_value = 0;

analogWrite(A5, alarm_value);

current_state = PAUSED;




void paused_play(){

if(current_state == MP3_PLAY || current_state == DIR_PLAY){

current_state = PAUSED;


current_state = MP3_PLAY;




void alarm(){

current_state = PAUSED2;

alarm_value = 676;



2. Id3Tag


* example sketch to play audio file(s) in a directory, using the mp3 library

* for playback and the arduino sd library to read files from a microsd card.

* pins are setup to work well for teensy 2.0. double-check if using arduino.


* originally based on frank zhao's player: http://frank.circleofcurrent.com/

* utilities adapted from previous versions of the functions by matthew seal.


* (c) 2011, 2012 david sirkin sirkin@cdr.stanford.edu

* akil srinivasan akils@stanford.edu



// this utility function reads id3v1 and id3v2 tags, if any are present, from

// mp3 audio files. if no tags are found, just use the title of the file. :-|


void get_title_from_id3tag () {

unsigned char id3[3]; // pointer to the first 3 characters to read in


// visit http://www.id3.org/id3v2.3.0 to learn all(!) about the id3v2 spec.

// move the file pointer to the beginning, and read the first 3 characters.



sd_file.read(id3, 3);

// if these first 3 characters are 'ID3', then we have an id3v2 tag. if so,

// a 'TIT2' (for ver2.3) or 'TT2' (for ver2.2) frame holds the song title.


if (id3[0] == 'I' && id3[1] == 'D' && id3[2] == '3') {

unsigned char pb[4]; // pointer to the last 4 characters we read in

unsigned char c; // the next 1 character in the file to be read

// our first task is to find the length of the (whole) id3v2 tag. knowing

// this means that we can look for 'TIT2' or 'TT2' frames only within the

// tag's length, rather than the entire file (which can take a while).


// skip 3 bytes (that we don't use), then read in the last 4 bytes of the

// header, which contain the tag's length.


sd_file.read(pb, 3);

sd_file.read(pb, 4);

// to combine these 4 bytes together into the single value, we first have

// to shift each one over to get it into its correct 'digits' position. a

// quirk of the spec is that bit 7 (the msb) of each byte is set to 0.

unsigned long v2l = ((unsigned long) pb[0] << (7 * 3)) +

((unsigned long) pb[1] << (7 * 2)) +

((unsigned long) pb[2] << (7 * 1)) + pb[3];

// we just moved the file pointer 10 bytes into the file, so we reset it.



while (1) {

// read in bytes of the file, one by one, so we can check for the tags.

sd_file.read(&c, 1);


// keep shifting over previously-read bytes as we read in each new one.

// that way we keep testing if we've found a 'TIT2' or 'TT2' frame yet.

pb[0] = pb[1];

pb[1] = pb[2];

pb[2] = pb[3];

pb[3] = c;


if (pb[0] == 'T' && pb[1] == 'I' && pb[2] == 'T' && pb[3] == '2') {

// found an id3v2.3 frame! the title's length is in the next 4 bytes.

sd_file.read(pb, 4);


// only the last of these bytes is likely needed, as it can represent

// titles up to 255 characters. but to combine these 4 bytes together

// into the single value, we first have to shift each one over to get

// it into its correct 'digits' position.


unsigned long tl = ((unsigned long) pb[0] << (8 * 3)) +

((unsigned long) pb[1] << (8 * 2)) +

((unsigned long) pb[2] << (8 * 1)) + pb[3];


// skip 2 bytes (we don't use), then read in 1 byte of text encoding.


sd_file.read(pb, 2);

sd_file.read(&c, 1);

// if c=1, the title is in unicode, which uses 2 bytes per character.

// skip the next 2 bytes (the byte order mark) and decrement tl by 2.

if (c) {

sd_file.read(pb, 2);

tl -= 2;


// remember that titles are limited to only max_title_len bytes long.

if (tl > max_title_len) tl = max_title_len;

// read in tl bytes of the title itself. add an 'end-of-string' byte.


sd_file.read(title, tl);

title[tl] = '\0';




if (pb[1] == 'T' && pb[2] == 'T' && pb[3] == '2') {

// found an id3v2.2 frame! the title's length is in the next 3 bytes,

// but we read in 4 then ignore the last, which is the text encoding.

sd_file.read(pb, 4);

// shift each byte over to get it into its correct 'digits' position.

unsigned long tl = ((unsigned long) pb[0] << (8 * 2)) +

((unsigned long) pb[1] << (8 * 1)) + pb[2];


// remember that titles are limited to only max_title_len bytes long.


if (tl > max_title_len) tl = max_title_len;


// there's no text encoding, so read in tl bytes of the title itself.

sd_file.read(title, tl);

title[tl] = '\0';




if (sd_file.position() == v2l) {

// we reached the end of the id3v2 tag. use the file name as a title.


strncpy(title, fn, max_name_len);





else {

// the file doesn't have an id3v2 tag so search for an id3v1 tag instead.

// an id3v1 tag begins with the 3 characters 'TAG'. if these are present,

// then they are located exactly 128 bits from the end of the file.

sd_file.seek(sd_file.size() - 128);

sd_file.read(id3, 3);

if (id3[0] == 'T' && id3[1] == 'A' && id3[2] == 'G') {

// found it! now read in the full title, which is always 30 bytes long.

sd_file.read(title, 30);

// strip spaces and non-printable characters from the end of the title.

// you may have to expand this range to incorporate unicode characters.

for (char i = 30 - 1; i >= 0; i--) {

if (title[i] <= ' ' || title[i] > 126) {

title[i] = '\0';


else {





else {

// we reached the end of the id3v1 tag. use the file name as a title.

strncpy(title, fn, max_name_len);





3. Utility


* example sketch to play audio file(s) in a directory, using the mp3 library

* for playback and the arduino sd library to read files from a microsd card.

* pins are setup to work well for teensy 2.0. double-check if using arduino.


* originally based on frank zhao's player: http://frank.circleofcurrent.com/

* utilities adapted from previous versions of the functions by matthew seal.


* (c) 2011, 2012 david sirkin sirkin@cdr.stanford.edu

* akil srinivasan akils@stanford.edu



// first step, declare the variables used later to represent microsd objects.


File sd_root; // the sd partition's root ('/') directory


// check that the microsd card is present, can be initialized and has a valid

// root volume. 'sd_root' is a pointer to the card's root volume object.


void sd_card_setup() {

if (!SD.begin(sd_cs)) {

// lcd.clearDisplay();

// lcd.println("sd card failed\nor not present");

// lcd.display();



sd_root = SD.open("/");

if (!sd_root) {

// lcd.clearDisplay();

// lcd.println("couldn't mount\nsd root volume");

// lcd.display();





// for each song file in the current directory, store its file name in eeprom

// for later retrieval. this saves on using program memory for the same task,

// which is helpful as you add more functionality to the program.


// it also lets users change songs on the microsd card without having to hard

// code file names into the program. ask an instructor if you want to use sub

// directories also.


void sd_dir_setup() {

num_songs = 0;


while (num_songs < max_num_songs) {

// break out of while loop when we check all files (past the last entry).

File p = sd_root.openNextFile();

if (!p) break;

// only store current (not deleted) file entries, and ignore the . and ..

// directory entries. also ignore any sub-directories.

if (p.name()[0] == '~' || p.name()[0] == '.' || p.isDirectory()) {



// to find the position of the '.' that precedes the file name extension,

// we have to search through the file name (stored as an array of chars).

// fat16 prefers 8.3 type file names, and the sd library will shorten any

// names longer than that. so if we have an mp3 or wav file, the '.' will

// appear no later than position 8 ('max_name_len'-5) of the file name.

char i;

for (i = max_name_len - 5; i > 0; i--) {

if (p.name()[i] == '.') break;



// only store mp3 or wav files in eeprom (for now). if you add other file

// types, you should add their extensions here.


if ((p.name()[i] == 'M' && p.name()[i+1] == 'P' && p.name()[i+2] == '3') ||

(p.name()[i] == 'W' && p.name()[i+1] == 'A' && p.name()[i+2] == 'V')) {

// store each character of the file name (including the terminate-array

// character '\0' at position 12) into a byte in the eeprom.

for (char i = 0; i < max_name_len; i++) {

EEPROM.write(num_songs * max_name_len + i, p.name()[i]);







// given the numerical index of a particular song to play, go to its location

// in eeprom, r etrieve its file name and set the global variable 'fn' to it.


void get_current_song_as_fn() {

for (char i = 0; i < max_name_len; i++) {

fn[i] = EEPROM.read(current_song * max_name_len + i);




// print the title to the lcd. if no title is available, print the file name.


void print_title_to_lcd() {



// lcd.clearDisplay();

// lcd.println(title);

// lcd.display();




-remote control and lock code (named final_project_slave)


LiquidCrystal Library - Hello World

Demonstrates the use a 16x2 LCD display. The LiquidCrystal

library works with all LCD displays that are compatible with the

Hitachi HD44780 driver. There are many of them out there, and you

can usually tell them by the 16-pin interface.

This sketch prints "Hello World!" to the LCD

and shows the time.

The circuit:

* LCD RS pin to digital pin 12

* LCD Enable pin to digital pin 11

* LCD D4 pin to digital pin 5

* LCD D5 pin to digital pin 4

* LCD D6 pin to digital pin 3

* LCD D7 pin to digital pin 2

* LCD R/W pin to ground

* 10K resistor:

* ends to +5V and ground

* wiper to LCD VO pin (pin 3)



// include the library code:

#include <LiquidCrystal.h>

#include <EEPROM.h>


// initialize the library with the numbers of the interface pins

LiquidCrystal lcd(12, 11, 5, 4, 3, 2);


int aPin = A0;

int bPin = A1;

int cPin = A2;

int dPin = A3;

int enterPin = A4;

int infoPin = 6;


int valueA0;

int valueA1;

int valueA2;

int valueA3;

int valueA4;

int i = 0;


volatile int paused_play_info = 0;

volatile int alarm_state = LOW;

int alarm_pin = 7;

int alarm_stop = 0;


void setup() {

// set up the LCD's number of columns and rows:

lcd.begin(16, 2);


// Print a message to the LCD.

lcd.print("hello, world!");

pinMode(alarm_pin, OUTPUT);

pinMode(infoPin, OUTPUT);


attachInterrupt(3,alarm,FALLING);//interrupt connected to pin 1/TX

attachInterrupt(2,paused_play,RISING); //interrupt connected to pin 0/RX



void loop() {

valueA0 = digitalRead(aPin);

valueA1 = digitalRead(bPin);

valueA2 = digitalRead(cPin);

valueA3 = digitalRead(dPin);

valueA4 = digitalRead(enterPin);

if(valueA0 == HIGH){







}else if(valueA1 == HIGH){







}else if(valueA2 == HIGH){







}else if(valueA3 == HIGH){







}else if(valueA4 == HIGH){




i = 0;


int a = EEPROM.read(i-4);

int b = EEPROM.read(i-3);

int c = EEPROM.read(i-2);

int d = EEPROM.read(i-1);

int password = a*1000 + b*100 + c*10 + d;






if(password == 330){











i = 0;




digitalWrite(alarm_pin,alarm_state) ;

if(paused_play_info == HIGH){

digitalWrite(infoPin, paused_play_info);




paused_play_info = LOW;

digitalWrite(infoPin, paused_play_info);




void alarm(){

static unsigned long last = 0;

unsigned long time = millis();

if(time - last > 1000){

alarm_state = HIGH;



last = time;



void paused_play(){

static unsigned long last1 = 0;

unsigned long time1 = millis();

if(time1-last1 > 150){

paused_play_info = HIGH;


last1 = time1;





Comments (1)

kdade said

at 3:12 pm on Aug 20, 2013

Dear Jerry,

We love your point of view because it addresses a specific need in a specific situation. With your project anyone can fall asleep listening to music on the bus and not have to worry about the safety of their belongings! Your state diagram and Verplank diagram also bring a lot to the report, and we would love to read more about the different interactions you have designed for the device (how the buttons work, for instance).

Your prototype is great, and it is awesome to see that the prototype seems to have helped you fabricate your final product accurately. We always love to read about the various steps you have taken in designing your project, and it would be good if you could include any other ideas you had for combining the music with a relaxing pillow. Were you always planning to use that neck cushion, or did you experiment with several different pillows? These things are always interesting to people attempting to recreate your project, and it is good to include as much detail in your description of the process as possible.

The physical device is beautifully constructed, and you completed all of the functionality you set out to tackle in your original plan. We love the hand-held controller with your hand-made buttons and the LCD screen embedded so perfectly - it almost looks like a consumer product! Great work this quarter, you should be really proud of what you have accomplished!

Kevin, David, Jessica, Matt, Vivien

You don't have permission to comment on this page.