Touchscreen Music

Made this back in May but never actually made a post on here about it. I used the “Touch Screen/Digitizer for NDSi LL” I got from DealExtreme and a speaker to generate sound based on where you press on the screen.


Here’s the code for the program used in the first video:

#include 

#define X1_PIN A0
#define X2_PIN A2
#define Y1_PIN A3
#define Y2_PIN A1 

#define WIDTH 100
#define HEIGHT 100

#define SPEAKER_PIN0 9
#define SPEAKER_PIN1 10
#define MIN_FREQ 262
#define MAX_FREQ 2000
#define NOTE_DURATION 20

Tone note[2];

// Change these values to correspond to your touchscreen;
// X and Y values from 0 to 1023 come from the analogRead()
// in the getTouch() function
int topLeftXY[] = {750,80};
int bottomRightXY[] = {40,700};

int pmouseX=0, pmouseY=0, mouseX=0, mouseY=0;

void setup() {
  note[0].begin(SPEAKER_PIN0);
  note[1].begin(SPEAKER_PIN1);
}

void loop() {
  if ( getTouch() ) {
    note[0].play((int) map(mouseX,0,WIDTH,MIN_FREQ,MAX_FREQ));
    note[1].play((int) map(mouseY,0,HEIGHT,MIN_FREQ,MAX_FREQ));
  }
  else {
    note[0].stop();
    note[1].stop();
  }
}

boolean getTouch() {  
  /* Gets the touched position on the screen and stores 
     it in mouseX and mouseY, and updates pmouseX and pmouseY
     with previous coordinates. Returns false if the screen
     is not touched. */
  pinMode(X1_PIN,OUTPUT);
  pinMode(X2_PIN,OUTPUT);
  digitalWrite(X1_PIN,LOW);
  digitalWrite(X2_PIN,HIGH);
 
  digitalWrite(Y1_PIN,LOW);
  digitalWrite(Y2_PIN,LOW);
 
  pinMode(Y1_PIN,INPUT);
  pinMode(Y2_PIN,INPUT);
  
  pmouseX = mouseX;
  mouseX = analogRead(Y1_PIN-14); // Subtract 14 to get the analog pin number
  
  pinMode(Y1_PIN,OUTPUT);
  pinMode(Y2_PIN,OUTPUT);
  digitalWrite(Y1_PIN,LOW);
  digitalWrite(Y2_PIN,HIGH);
 
  digitalWrite(X1_PIN,LOW);
  digitalWrite(X2_PIN,LOW);
 
  pinMode(X1_PIN,INPUT);
  pinMode(X2_PIN,INPUT);
 
  pmouseY = mouseY;
  mouseY = analogRead(X1_PIN - 14); // Subtract 14 to get the analog pin number
  
  //Non-zero values get converted to a point on the screen
  if (mouseX != 0 && mouseY != 0) {
    mouseX = (int) map(mouseX, topLeftXY[0], bottomRightXY[0], 0, WIDTH);
    mouseY = (int) map(mouseY, topLeftXY[1], bottomRightXY[1], 0, HEIGHT);
    return true;
  }
  else
    return false;
}

The code used in the second video is essentially the same except uses a discrete set of frequency values (well I guess technically the first video uses discrete values too, but there are way more frequencies than the second video).