Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <SPI.h>
- #define csPin 8
- #define Z_THRESHOLD 3500
- int xy[2];
- void setup() {
- Serial.begin(38400);
- SPI.setDefaultFrequency(100000);
- SPI.begin(); //Initiallize the SPI1 port.
- pinMode(csPin, OUTPUT);
- digitalWrite(csPin, HIGH);
- }
- //-----------------------------------------------------
- //
- //-----------------------------------------------------
- void loop() {
- if(read_XY(xy)){ //Read the X,Y coordinates (12 bits, values 0-4095)
- Serial.print("X: ");
- Serial.println(xy[0]); //Print X value
- Serial.print("Y: ");
- Serial.println(xy[1]); //Print Y value
- Serial.println();
- delay(1000);
- }
- }
- //-----------------------------------------------------
- //
- //-----------------------------------------------------
- boolean read_XY(int *xy){
- int z1, z2, tmpH, tmpL;
- digitalWrite(csPin, LOW);
- //Check if touch screen is pressed.
- SPI.transfer(B10110001, SPI_CONTINUE); // Z1
- tmpH = (SPI.transfer(0, SPI_CONTINUE) << 5);
- tmpL = (SPI.transfer(0, SPI_CONTINUE) >> 3);
- z1 = tmpH | tmpL;
- SPI.transfer(B11000001, SPI_CONTINUE); // Z2
- tmpH = (SPI.transfer(0, SPI_CONTINUE) << 5);
- tmpL = (SPI.transfer(0, SPI_CONTINUE) >> 3);
- z2 = tmpH | tmpL;
- if((z2 - z1) < Z_THRESHOLD){ //If the touch screen is pressed, read the X,Y coordinates from XPT2046.
- SPI.transfer(B11010001, SPI_CONTINUE); // X
- tmpH = (SPI.transfer(0, SPI_CONTINUE) << 5);
- tmpL = (SPI.transfer(0, SPI_CONTINUE) >> 3);
- xy[0] = tmpH | tmpL;
- SPI.transfer(B10010001); // Y
- tmpH = (SPI.transfer(0, SPI_CONTINUE) << 5);
- tmpL = (SPI.transfer(0, SPI_LAST) >> 3);
- xy[1] = tmpH | tmpL;
- digitalWrite(csPin, HIGH);
- return true;
- }
- digitalWrite(csPin, HIGH);
- return false;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement