Advertisement
Guest User

Untitled

a guest
Apr 23rd, 2017
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. #include <SPI.h>
  2. #define csPin 8
  3. #define Z_THRESHOLD   3500
  4.  
  5. int xy[2];
  6.  
  7. void setup() {
  8.   Serial.begin(38400);
  9.   SPI.setDefaultFrequency(100000);
  10.   SPI.begin(); //Initiallize the SPI1 port.
  11.   pinMode(csPin, OUTPUT);
  12.   digitalWrite(csPin, HIGH);
  13. }
  14.  
  15. //-----------------------------------------------------
  16. //
  17. //-----------------------------------------------------
  18. void loop() {
  19.   if(read_XY(xy)){     //Read the X,Y coordinates (12 bits, values 0-4095)
  20.     Serial.print("X: ");
  21.     Serial.println(xy[0]); //Print X value
  22.     Serial.print("Y: ");
  23.     Serial.println(xy[1]); //Print Y value
  24.     Serial.println();
  25.     delay(1000);
  26.   }
  27. }
  28.  
  29. //-----------------------------------------------------
  30. //
  31. //-----------------------------------------------------
  32. boolean read_XY(int *xy){
  33.   int z1, z2, tmpH, tmpL;
  34.   digitalWrite(csPin, LOW);
  35.  
  36.   //Check if touch screen is pressed.
  37.   SPI.transfer(B10110001, SPI_CONTINUE); // Z1
  38.   tmpH = (SPI.transfer(0, SPI_CONTINUE) << 5);
  39.   tmpL = (SPI.transfer(0, SPI_CONTINUE) >> 3);
  40.   z1 = tmpH | tmpL;
  41.  
  42.   SPI.transfer(B11000001, SPI_CONTINUE); // Z2
  43.   tmpH = (SPI.transfer(0, SPI_CONTINUE) << 5);
  44.   tmpL = (SPI.transfer(0, SPI_CONTINUE) >> 3);
  45.   z2 = tmpH | tmpL;
  46.  
  47.   if((z2 - z1) < Z_THRESHOLD){ //If the touch screen is pressed, read the X,Y  coordinates from XPT2046.
  48.     SPI.transfer(B11010001, SPI_CONTINUE); // X
  49.     tmpH = (SPI.transfer(0, SPI_CONTINUE) << 5);
  50.     tmpL = (SPI.transfer(0, SPI_CONTINUE) >> 3);
  51.     xy[0] =  tmpH | tmpL;
  52.    
  53.     SPI.transfer(B10010001); // Y
  54.     tmpH = (SPI.transfer(0, SPI_CONTINUE) << 5);
  55.     tmpL = (SPI.transfer(0, SPI_LAST) >> 3);
  56.     xy[1] =  tmpH | tmpL;
  57.     digitalWrite(csPin, HIGH);
  58.     return true;
  59.   }
  60.   digitalWrite(csPin, HIGH);
  61.   return false;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement