经过调测,发现上面的代码有一个小问题,就是如果拿着橙子不松手,则会出现琴键的“连击”现象,说起来也不算问题,但还是做了优化,修改一下,代码如下,另外,顺便说一句,通过手感来感觉,苹果比橙子电阻更大,触摸时不如橙子灵敏。- /* Date : Feb 2nd, 2014
- Author : Zhou Keke
- Description:
- 1.Simulate the keyboard to play the piano software by sending a, s,d,f,g,h key to the computer
- 2.Solve the problem of sending the one key to computer continuously.
- */
- int InData1 = 0, InData2 = 0, InData3 = 0, InData4 = 0, InData5 = 0, InData0 = 0; //触摸输入值暂存
- int aKeyPressed = 0, sKeyPressed = 0, dKeyPressed = 0, fKeyPressed = 0, gKeyPressed = 0, hKeyPressed = 0;
- int TouchSensitivity = 50; //触摸灵敏度。0~1023,越大越不灵敏
- int cycle = 0;
- void setup()
- {
- Serial.begin(9600);
-
- for(int i = 6; i <= 12; i++)
- {
- pinMode(i, OUTPUT);
- }
-
- Keyboard.begin();
- }
-
- void loop()
- {
- //UsbKeyboard.update();
- //读取所有引脚电压值,并且由于上拉电阻原因,
- //默认所有引脚为最高电平1023,通过触摸拉低引脚电平。
- //所以数值由1024-analogRead(A0);
-
- InData0 = 1024 - analogRead(A0);
- InData1 = 1024 - analogRead(A1);
- InData2 = 1024 - analogRead(A2);
- InData3 = 1024 - analogRead(A3);
- InData4 = 1024 - analogRead(A4);
- InData5 = 1024 - analogRead(A5);
-
- //按照各种可能触发键盘事件
- if(InData0 >= TouchSensitivity){
- Serial.print("InData0=");
- Serial.println(InData0);
- digitalWrite(6, HIGH);
- if(aKeyPressed == 0){
- Keyboard.write('a');
- }
- aKeyPressed = 1;
- }
- else{
- aKeyPressed = 0;
- digitalWrite(6, LOW);
- }
-
- if(InData1 >= TouchSensitivity){
- Serial.print("InData1=");
- Serial.println(InData1);
- digitalWrite(7, HIGH);
- if(sKeyPressed == 0){
- Keyboard.write('s');
- }
- sKeyPressed = 1;
- }
- else {
- sKeyPressed = 0;
- digitalWrite(7, LOW);
- }
-
- if(InData2 >= TouchSensitivity){
- Serial.print("InData2=");
- Serial.println(InData2);
- digitalWrite(8, HIGH);
- if(dKeyPressed == 0){
- Keyboard.write('d');
- }
- dKeyPressed = 1;
- }
- else {
- dKeyPressed = 0;
- digitalWrite(8, LOW);
- }
-
- if(InData3 >= TouchSensitivity){
- Serial.print("InData3=");
- Serial.println(InData3);
- digitalWrite(9, HIGH);
- if(fKeyPressed == 0){
- Keyboard.write('f');
- }
- fKeyPressed = 1;
- }
- else{
- fKeyPressed = 0;
- digitalWrite(9, LOW);
- }
-
- if(InData4 >= TouchSensitivity){
- Serial.print("InData4=");
- Serial.println(InData4);
- digitalWrite(10, HIGH);
- if(gKeyPressed == 0){
- Keyboard.write('g');
- }
- gKeyPressed = 1;
- }
- else{
- gKeyPressed = 0;
- digitalWrite(10, LOW);
- }
-
- if(InData5 >= TouchSensitivity){
- Serial.print("InData5=");
- Serial.println(InData5);
- digitalWrite(11, HIGH);
- if(hKeyPressed == 0){
- Keyboard.write('h');
- }
- hKeyPressed = 1;
- }
- else{
- hKeyPressed = 0;
- digitalWrite(11, LOW);
- }
-
- Serial.println("cycle");
- Serial.println(cycle++);
- delay(100);
- //
-
- }
复制代码 |