Seeed_QTouch.cpp 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. QTouch Library
  3. 2014 Copyright (c) Seeed Technology Inc. All right reserved.
  4. Author: ZhangKun & Loovee
  5. 2013-3-20
  6. This library is free software; you can redistribute it and/or
  7. modify it under the terms of the GNU Lesser General Public
  8. License as published by the Free Software Foundation; either
  9. version 2.1 of the License, or (at your option) any later version.
  10. This library is distributed in the hope that it will be useful,
  11. but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  13. Lesser General Public License for more details.
  14. You should have received a copy of the GNU Lesser General Public
  15. License along with this library; if not, write to the Free Software
  16. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include <Wire.h>
  19. #include <Arduino.h>
  20. #include "Seeed_QTouch.h"
  21. SeeedQTouch::SeeedQTouch()
  22. {
  23. Wire.begin();
  24. }
  25. // if certain key touched, return 1 - touched, 0 untouched
  26. unsigned char SeeedQTouch::isTouch(int key)
  27. {
  28. if(key>7)return 0; // err input
  29. unsigned char st = getState();
  30. return ((0x01<<key)&st); // if touched return 1, else return 0
  31. }
  32. // return all key state, bit0 for key0, bit1 for key1....
  33. unsigned char SeeedQTouch::getState()
  34. {
  35. return readReg(0x03);
  36. }
  37. int SeeedQTouch::touchNum()
  38. {
  39. unsigned char state = getState();
  40. if(0 == state)return -1;
  41. for(int i=0; i<7; i++)
  42. {
  43. if((state>>i) & 0x01)
  44. {
  45. return i;
  46. }
  47. }
  48. return -1;
  49. }
  50. // read register
  51. unsigned char SeeedQTouch::readReg(unsigned char addr_reg)
  52. {
  53. Wire.beginTransmission(ADDR_QTOUCH);
  54. Wire.write(addr_reg); // register to read
  55. Wire.endTransmission();
  56. Wire.requestFrom(ADDR_QTOUCH, 1); // read a byte
  57. while(Wire.available())
  58. {
  59. return Wire.read();
  60. }
  61. }
  62. // write data to register
  63. unsigned char SeeedQTouch::writeReg(unsigned char addr_reg, unsigned char dta) // write register
  64. {
  65. Wire.beginTransmission(ADDR_QTOUCH);
  66. Wire.write(addr_reg); // register to read
  67. Wire.write(dta);
  68. Wire.endTransmission();
  69. }
  70. SeeedQTouch QTouch;