Music Controller

Design Challenge: Make a device to control playback of pre-recorded music.


  • Make a device that sends asynchronous serial messages to another device which will play the music.
  • All serial messages should be terminated by a linefeed.
  • The playback device will echo your message back to you as an acknowledgement message when it executes your command.

The device supports the following features:

  • It is operable by a user who cannot see the device.
  • The user gets an acknowledgement when they activate any control.
  • Start or stop the playback of a track (start plays track from the beginning).
  • Pause or resume playback of a track (resume plays track from last position stopped)
  • Skip ahead one track in the playlist.
  • Skip back one track in the playlist.
  • Fast-forward the current track (double speed of the track).
  • Skip to a random track in the playlist.

Tools used:

  • Arduino IDE
  • Arduino MKR1000
  • Python server
  • P5.js
  • P5 Serial Control App
  • Buttons (momentary and )
  • Vibration Sensor
  • Frosted plastic container
Arduino and Physical Components

I started this assignment by wiring my components to the breadboard and Arduino. As shown below, I wired the 2 toggle buttons, 4 momentary buttons and the vibration sensor. 

Arduino Code:

This proved to be quite tricky for me initially. My goal was to create the code from scratch and not rely on references. I encountered errors with the switch state where the serial monitor was just writing the value continually. Adding a delay did not help. I eventually discovered that my syntax was wrong (odd that the IDE did not pick up on this when I verified the code.) The culprit was a semi colon.

 My code:

const int startStop = 11;
const int pausePlay = 10;
const int next = 9;
const int back = 8;
const int randomSong = 7;
const int fast = 6;

int vibeSensor = 5;

int lastStartStopState = LOW;
int lastPausePlayState = HIGH;
int lastNextState = LOW;
int lastBackState = LOW;
int lastRandomState = LOW;
int lastFastState = LOW;

void setup() {

pinMode(startStop, INPUT_PULLUP);
pinMode(pausePlay, INPUT_PULLUP);
pinMode(next, INPUT_PULLUP);
pinMode(back, INPUT_PULLUP);
pinMode(randomSong, INPUT_PULLUP);
pinMode(fast, INPUT_PULLUP);
pinMode(vibeSensor, OUTPUT);

void loop() {
int buttonState1 = digitalRead(startStop);
int buttonState2 = digitalRead(pausePlay);
int buttonState3 = digitalRead(next);
int buttonState4 = digitalRead(back);
int buttonState5 = digitalRead(randomSong);
int buttonState6 = digitalRead(fast);

// 1. Start Stop Button
// If the button is on, send a message to serial to start playing the song
if (buttonState1 != lastStartStopState) {
if (buttonState1 == HIGH) {

analogWrite(vibeSensor, 255); // give feedback
analogWrite(vibeSensor, 0);

// If the button is off, send a message to serial to stop playing the song
} else {
analogWrite(vibeSensor, 255); // give feedback
analogWrite(vibeSensor, 0);
lastStartStopState = buttonState1;

// 2. Pause Play Button
//If the button is on, send a message to serial to pause the song
if (buttonState2 != lastPausePlayState) {
if (buttonState2 == LOW) {


analogWrite(vibeSensor, 255); // give feedback
analogWrite(vibeSensor, 0);

// If the button is off, send a message to serial to play the song
} else {

analogWrite(vibeSensor, 255); // give feedback
analogWrite(vibeSensor, 0);
lastPausePlayState = buttonState2;

//3. Next Button (skip to the next song)
// If the button is pressed, send a message to serial to skip forward to the next song

if (buttonState3 != lastNextState) {
if (buttonState3 == LOW) {

// delay(500);

analogWrite(vibeSensor, 255); // give feedback
analogWrite(vibeSensor, 0);
lastNextState = buttonState3;

// 4. Back Button (go back and play the previous song)
// If the button is on, send a message to serial to skip to the previous song

if (buttonState4 != lastBackState) {
if (buttonState4 == LOW) {

// delay(500);

analogWrite(vibeSensor, 255); // give feedback
analogWrite(vibeSensor, 0);
lastBackState = buttonState4;

// 5. Random Button (play a random song)
// If the button is on, send a message to serial to skip to a random song

if (buttonState5 != lastRandomState) {
if (buttonState5 == LOW) {

// delay(500);

analogWrite(vibeSensor, 255); // give feedback
analogWrite(vibeSensor, 0);
lastRandomState = buttonState5;

// 6. Fast Button (fast forward through the current song)
// If the button is on, send a message to serial to fast forward through the current song

if (buttonState6 != lastFastState) {
if (buttonState6 == LOW) {

// delay(500);

analogWrite(vibeSensor, 255); // give feedback
analogWrite(vibeSensor, 0);
lastFastState = buttonState6;




P5.js and Serial Communication

I haven’t touched p5 since ICM. However, setting up the serial communication and updating the sample p5 code was the most straightforward part of this assignment. 

Using this serial input to P5 tutorial, I installed the P5.serialcontrol app and the p5.serialserver. With the arduino connected to the port, I used the serial control app to ensure the port was available. Then using the command line, opened a python server the tested my controller. 

P5 code: 

var serial;
var portName = ‘/dev/cu.usbmodem1411’;
var inData;

var song; // the sound file to be played

// the list of songs:
var songs = [‘FastWine.mp3’, ‘FullExtreme.mp3’, ‘Incredible.mp3’, ‘LeaveMeAlone.mp3’, ‘TurnUp.mp3’];

var songCount = songs.length; // number of songs in the music dir
var currentSong = 0; // current song number

function preload() { // load the first song on preload
song = loadSound(‘music/’ + songs[currentSong]);

function setup() {
createCanvas(400, 300);

serial = new p5.SerialPort(); // make a new instance of the serialport library
serial.on(‘connected’, serverConnected); // callback for connecting to the server
serial.on(‘open’, portOpen); // callback for the port opening
serial.on(‘data’, serialEvent); // callback for when new data arrives
serial.on(‘error’, serialError); // callback for errors
serial.on(‘close’, portClose); // callback for the port closing

serial.list(); // list the serial ports; // open a serial port

function serverConnected() {
println(“We are connected!”);

function portOpen() {
println(“Serial Port is open!”);

function serialEvent() {
inData = Number(;

function serialError(err) {
println(‘Something went wrong with the serial port ‘ + err);

function portClose() {
println(‘The serial port is closed’);

function draw() {
background(30, 20, 180);
text(“sensor value: ” + inData, 30, 30);
// draw the song’s name and current time in seconds:
text(songs[currentSong], 20, 50);
text(song.currentTime().toFixed(3), 20, 100);

function controlSound(input) {
switch (input) {
case 49: // start/stop, press 1
if (song.isPlaying()) {
} else {;
case 50: // play/pause, press 2
if (song.isPlaying()) {
} else {;
case 51: // skip ahead, press 3
// make sure the song number is valid, and increment:
if (currentSong < songs.length - 1) {
} else {
currentSong = 0;
// get new song:
case 52: // skip back, press 4
// in the first second, just rewind the current track:
if (song.currentTime() > 1.0) {
// if more than a second has elapsed, then
// make sure the song number is valid, and decrement:
} else {
if (currentSong > 0) {
} else {
currentSong = songs.length – 1;
// get new song:
case 53: // fast forward, press 5
song.rate(2.0); // double the play speed
if (!song.isPlaying()) {;
case 54: // random song, press 6
currentSong = Math.round(random(songCount)); // get a new song number
getSong(currentSong); // play it

function getSong(songNumber) {
if (songNumber < songs.length) { // if the song number is in range
if (song.isPlaying()) {
// load a new song:
song = loadSound(‘music/’ + songs[currentSong], resumePlay);
return true;
} else { // if the song number was out of range, return false
return false;

function resumePlay() {
// if the song isn’t playing, play it
if (song.isPlaying()) {
} else {;

function keyReleased() {
controlSound(keyCode); // send the ASCII number of the key



I wanted the feel of a walkman so I purchased a small plastic container that could be held with one hand. I drilled holes for my 6 buttons and for the power cable. Then carefully installed my buttons and MKR1000. 

Experience new music

So, that was soca. In case you were wondering what I was playing. Take a listen to the tracks on my playlist, below.

262 thoughts on “Music Controller”

  1. You can certainly see your expertise in the work you write. The world hopes for more passionate writers like you who are not afraid to say how they believe. Always go after your heart.

  2. I precisely desired to say thanks again. I’m not certain the things I could possibly have achieved in the absence of the concepts contributed by you about my area of interest. Entirely was a daunting circumstance for me, but coming across a expert avenue you dealt with it forced me to cry for contentment. Extremely grateful for the advice and expect you are aware of a powerful job that you are accomplishing educating many people all through a site. I’m certain you’ve never come across all of us.

  3. I’m also commenting to let you be aware of of the brilliant discovery my child encountered checking the blog. She came to understand a lot of details, including how it is like to have a marvelous coaching character to get certain people completely comprehend a variety of complex issues. You actually did more than her desires. I appreciate you for coming up with such essential, dependable, edifying and cool guidance on that topic to Ethel.

  4. At this moment I am going away to do my breakfast, when having
    my breakfast coming over again to read additional news.
    0mniartist asmr

  5. A fascinating discussion is definitely worth comment.
    I believe that you should write more on this subject, it may
    not be a taboo matter but usually folks don’t speak about such issues.
    To the next! All the best!! 0mniartist asmr

  6. Way cool! Some extremely valid points! I appreciate you penning this write-up plus the rest of the site
    is also really good. 0mniartist asmr

  7. Hi, of course this piece of writing is really nice and I have learned lot of things from it concerning blogging.

    thanks. asmr 0mniartist

  8. I’m gone to convey my little brother, that he should also pay a visit
    this web site on regular basis to take updated from newest reports.

    my website; united

  9. Have you ever heard of second life (sl for short). It is basically a game where you can do anything you want. sl is literally my second life (pun intended lol). If you want to see more you can see these second life authors and blogs

  10. Have you ever heard of second life (sl for short). It is basically a online game where you can do anything you want. sl is literally my second life (pun intended lol). If you would like to see more you can see these Second Life articles and blogs

  11. Thanks for sharing your thoughts. I truly appreciate
    your efforts and I am waiting for your further post thanks once again.

  12. Hello, I think your site might be having browser compatibility issues.

    When I look at your blog site in Safari, it looks fine but when opening in Internet Explorer,
    it has some overlapping. I just wanted to give you a quick heads up!
    Other then that, very good blog!

  13. Link exchange is nothing else however it is simply placing the
    other person’s web site link on your page at suitable place and other person will also
    do similar in favor of you.

  14. legitimate online pharmacy uk – ed drugs medical pharmacy south or cheapest pharmacy for prescriptions without insurance

  15. Thanks for the marvelous posting! I certainly enjoyed reading it,
    you will be a great author.I will ensure that I bookmark your
    blog and will often come back in the future. I want to encourage continue your great writing, have a nice holiday weekend!

  16. I do consider all the concepts you’ve presented for your post.
    They’re very convincing and will definitely work.
    Nonetheless, the posts are too brief for novices. May you please lengthen them a bit
    from subsequent time? Thank you for the post.

  17. Please let me know if you’re looking for a writer for your site.
    You have some really good articles and I believe I would be a good asset.
    If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange for
    a link back to mine. Please send me an email if interested.

  18. Fastidious answer back in return of this difficulty with genuine arguments and describing everything about that.

  19. I am in fact delighted to glance at this website posts which contains lots of helpful information, thanks for providing these kinds of data.

  20. Hi, Neat post. There’s a problem with your site in internet explorer, would check this… IE still is the market leader and a huge portion of people will miss your wonderful writing because of this problem.

  21. F*ckin’ remarkable issues here. I am very glad to peer your article. Thank you a lot and i’m looking ahead to contact you. Will you please drop me a e-mail?

  22. scoliosis
    I am really inspired together with your writing talents and also with the structure on your blog.
    Is this a paid subject matter or did you modify it your self?
    Either way stay up the nice high quality writing, it’s
    uncommon to see a great blog like this one these days..

  23. free dating sites
    My spouse and I absolutely love your blog and find many of your post’s to be exactly what I’m looking for.
    Would you offer guest writers to write content for you personally?
    I wouldn’t mind publishing a post or elaborating on a number of
    the subjects you write about here. Again, awesome site! dating sites

  24. free dating sites
    Its like you read my thoughts! You seem to understand a lot approximately this, such as you wrote the
    guide in it or something. I feel that you just can do with some % to force the message
    home a little bit, but instead of that, that is fantastic blog.

    An excellent read. I will definitely be back.
    dating sites

  25. Excellent goods from you, man. I’ve understand
    your stuff previous to and you’re just extremely great.
    I really like what you have acquired here, certainly like what you are saying and the way in which you say it.
    You make it enjoyable and you still take care of to keep
    it wise. I can not wait to read far more from you. This is actually a great site.

  26. The subsequent time I read a blog, I hope that it doesnt disappoint me as a lot as this one. I imply, I know it was my choice to read, but I actually thought youd have something interesting to say. All I hear is a bunch of whining about something that you may repair when you werent too busy looking for attention.

  27. I blog frequently and I truly appreciate your information. Your article
    has truly peaked my interest. I am going to take a note of your blog and
    keep checking for new details about once per week.
    I opted in for your Feed as well.

  28. I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here
    frequently. I am quite sure I’ll learn plenty of new stuff right here!
    Best of luck for the next!

  29. Hi outstanding website! Does running a blog similar
    to this require a large amount of work? I’ve very
    little expertise in coding but I was hoping to start my own blog in the near future.
    Anyways, should you have any suggestions or techniques for new blog owners please share.

    I understand this is off subject however I
    just had to ask. Thanks a lot!

  30. Greetings! This is my first comment here so I just wanted to give a quick shout out and say I
    genuinely enjoy reading your articles. Can you recommend any other blogs/websites/forums that cover the same topics?
    Thanks a ton!

  31. It’s a pity you don’t have a donate button! I’d definitely
    donate to this fantastic blog! I guess for now i’ll settle for book-marking and adding your RSS feed to my Google
    account. I look forward to brand new updates and will talk about
    this blog with my Facebook group. Chat soon!

  32. This is really interesting, You’re a very skilled blogger.
    I have joined your rss feed and look forward to seeking more of your great
    post. Also, I have shared your web site in my social networks!

  33. While GTA: Online, one of their most popular Online products, has micro-transactions, they do not severely break the game in terms of balancing. Most PvP match modes in the game are not affected by the player’s personal purchases. The PC version of Grand Theft Auto V and Grand Theft Auto Online features First Person Mode, giving players the chance to explore the incredibly detailed world of Los Santos and Blaine County in an entirely new way. Rockstar Games is bringing GTA Online to PlayStation 5 as a separate, standalone game, available as a free exclusive for the first three months after its launch in the second half of 2021. Technology plays an important role in our lives, whether for work or fun. Everyone now owns a smartphone, while most have a computer or a laptop. These devices come in handy for several things, but most notably for video gaming. And to play, you need to buy the game you like. But if you want to download one for free, check out IGG Games. Among Us Free Download Igggames. Try the latest version of among us 2020 for android Among us pc game overview All games of website is free for peoples – if you can’t buy one of the games that you like or feel good, crack is a way to experience it first. Here offers you all the latest games, hottest and up-to-date. Let’s Enjoy it !

  34. Wow, superb blog layout! How long have you been blogging for?
    you made blogging look easy. The overall look of your website is wonderful, as well as the content!

  35. Hello, i think that i saw you visited my blog so i came to “return the favor”.I’m trying to find things
    to improve my site!I suppose its ok to use some of your ideas!!

  36. По всем вопросам пишите нам: Значительная часть так называемых феромонов содержит множество химических веществ, поэтому не удовлетворяют критерию простоты. “Если у пары есть проблемы в сексуальных отношениях, то нельзя говорить, что, употребляя афродизиаки, они эти проблемы решат. Сексуальное желание идет из головы, от внутреннего отношения, от здоровья”, — отметил сексолог. Оглавление Мидии – мощнейший афродизиак. В них очень много белка, приправленного цинком и селеном, которые стимулируют выработку гормонов тестостерона, эстрогена и прогестерона. А ещё мидии – низкокалорийны (77 ккал в 100 г): не отставляют тяжести в желудке, что способствует интересному продолжению вечера без помех. Хрен благодаря высокому содержанию витаминов и микроэлементов считается хорошим возбуждающим средством. Именно поэтому англичане называют этот афродизиак лошадиным редисом. На основе этого ароматного тропического фрукта можно приготовить невероятно вкусные и аппетитные напитки-афродизиаки для усиления возбуждения перед половым актом. Также является отличным усилителем желания. Эта ягода (да, ягода!) — отличный природный афродизиак, который богат калием и натуральными сахарами. Индийская традиционная медицина классифицирует бананы как «возбуждающую» пищу. Рекомендуетcя курсовой прием Алитабса, который рассчитан на 1,5 месяца использования. Можно ли употреблять Алитабс с алкогольными напитками? Да, его можно употреблять как с умеренными дозами алкогольных напитков, так и с лекарственными средствами. Купить Maral Gel гель для увеличения члена и спермы в Александрии ANT KING – единственное работающее средство на рынке для увеличения члена. Этот комплекс, который не вызывает никаких побочных эффектов, не вызывает аллергических реакций. Специальные ферменты, входящие в состав, благотворно влияют на ткани пениса, которые безвредно растягиваются, а с ними и камеры кавернозного тела полового члена, что и способствует реальному увеличению как и в длине так и в обхвате.

  37. Instagram Follower Kaufen
    Instagram-Follower kaufen: mehr Trust und Reichweite für Ihre Brand
    Das Ziel, die Reichweite auf Instagram zu erhöhen,
    ist für viele Unternehmen und Influencer häufig nur
    schwer zu erreichen. Follower zu kaufen ist eine bewährte Methode, um die Instagram-Präsenz aufzubessern und mehr Menschen und potenzielle Kunden im beliebten sozialen Netzwerk zu erreichen.
    Instagram Follower Kaufen

  38. Ortam Ölçümü
    İş Güvenliği Kanunu kapsamında çıkan “İş
    Hijyeni Ölçüm Test ve Analizi Yapan Laboratuvarlar Hakkında Yönetmelik” gereği işverenler, iş sağlığı ve güvenirliği
    tarafından çalışma alanına ve çalışanların bu
    bölgede maruz kaldığı tehlikelerin saptanmasına yönelik lüzumlu
    denetim, bölge ölçümü, araştırma ve tetkiklerin yapılmasını
    sağlamakla yükümlüdür. Bakanlık kontrollerinde ya da ana firmanın kontrollerinde işyeri çalışma alanı ile
    ilgili Çalışma Sosyal Emniyet Bakanlığı (İSGÜM) den Yetki sahibi İş hijyeni laboratuvarı doğrulusunda verdiği rapor eder istenilmektedir.

    ortam ölçümü

Leave a Reply

Your email address will not be published.