12189浏览
查看: 12189|回复: 7

[项目] 如何使用电容式触摸定制LED Twitch标牌

[复制链接]
本帖最后由 -YAYA- 于 2023-8-22 11:53 编辑

如何使用电容式触摸定制LED Twitch标牌

【硬件准备】

  • Arduino Mega 2560
  • Infineon PSoC 4100S Capsense先锋套件
  • LED灯带
  • 电阻器10k欧姆×3
  • 逻辑电平N沟道MOSFET×3
  • Breadboard 面包板
  • 12V电源
  • 9V电源
  • 跳线(通用)

除此之外,我还使用了一台3D打印机,如果没有这个条件的话,也有别的可行方案。

【项目理念】

这是一个可点亮的多色标牌,用户在Twitch上直播时会激活,它可以通过命令由Twitch聊天控制,也可以通过使用PSoC 4系列先锋套件(我指的是我用作PSoC 4100s的设备)通过电容触摸亲自控制。

我喜欢闪闪发亮的东西,所以我愿意花大量的时间和精力来制作这样一个又大又亮的灯光的项目。再加上有游戏、3d打印和各种电子产品的加成,我对这个项目十分感兴趣。它有趣还实用,可以提前让亲朋好友知道有一个直播正在进行,以避免尴尬的时刻。我非常喜欢想一些能与设备互动的方法,在Twitch上也会有有趣的互动功能,所以做这个项目的想法就自然而然地展开了。现在是时候开始进入项目了!

【项目步骤】

电容式触控(PSoC设置)

如何使用电容式触摸定制LED Twitch标牌图1

我从启动和运行PSoC方面开始,并使用PSoC Creator 4.4软件启动和运行。该设备配有一个非常漂亮的颜色选择器和两个按钮,非常适合这次的产品。它还附带了一个示例Color Gamut项目,这很有用。不过,我并没有仅仅利用基本功能,而是改变了按钮的工作方式,让自己有更多的控制权。

颜色托盘是很好的选择,但要获得特定的颜色可能比较难。特别是因为我是个大块头,我的手就可以占据托盘的一半。因此,我将其中一个按钮设置为通过选择颜色旋转。这是通过保持一个颜色索引来实现的,这样的话当我按下按钮时,它会增加索引,直到它把每种颜色都过了一遍,然后会返回到1。

同样,我想控制灯的亮度与LED的开关。因此,我使用另一个按钮来保持亮度指数,该指数为0-5。我们可以通过将索引值乘以51得到0-255的值,如果是0的话会关闭符号。

对于项目的其他方面,我使用了Arduino设置来直接控制LED并监听Twitch消息,因此集成PSoC设备的理想设置是通过串行消息将设备的输入转发给Arduino。我在引脚选项卡中添加了UART的TX引脚,并添加了通过UART发送串行消息的代码。这是为了发送色域中的红色、绿色和蓝色(RGB)着色值、我们设置的颜色指数和亮度指数。由于我们已经设置了串行消息,我们将确切地知道在Arduino一侧要查找什么。TX引脚用于传输信息,RX引脚接收信息,因此设置是使用跳线将PSoC 4100s的TX引脚连接到Arduino设备的RX引脚。

如何使用电容式触摸定制LED Twitch标牌图2

LED设置(点亮它!)

我引用了“makeuseof”的一篇关于设置LED灯带的文章。这是一个理想的设置,因为它可以放置不是专门为Arduino制作的LED条,这正是我碰巧可以使用的。简而言之,它使用逻辑电平MOSFET和10k电阻器组合一个简单的测试板设置,可以安全地将LED带与Arduino连接起来。这也需要一个单独的12v电源。

我等到项目已经基本上全部完成后才进行最后的润色。使用一个定制的发光标牌比使用普通的LED灯带要有趣得多,所以我决定把这两者结合起来。我使用的标牌是我设计过的3D打印标志。幸运的是,我之前已经打印出来了,这非常方便,因为我的打印机由于一个悲惨的软塞事故而完全无法使用。虽然3D打印标志很酷,但如果你在跟进的过程中发现这不是你的菜,也有很多其他选项可以使用类似泡沫板之类的材料来实现相同的基本设置。

添加LED灯带只是将其插入不直接可见的标志中。其实我的LED条有点太旧了,我无法使用它粘性的一面,必须用胶带把它粘在适当的位置。但这也有好处,因为我可以把胶带放在视线之外。

如何使用电容式触摸定制LED Twitch标牌图3

所有灯光都通过Arduino控制。基本上,你通过为Arduino提供红色、蓝色和绿色的值来点亮标志。例如,如果红色值为255,蓝色值为0,绿色值为0,那么红色会以全亮度显示。但你也可以通过这些数值控制亮度。以相同的例子,如果红色值为50,蓝色值为0,绿色值为0,那么红色会变暗。在代码中,我们保留这些值,以便可以确定正在使用的颜色,这样如果我们增加亮度,就能保持当前显示的颜色。

Arduino设置

如何使用电容式触摸定制LED Twitch标牌图4

我们已经有了灯光,现在是时候设置Arduino了。此时,我们可以使用Arduino监听来自PSoC设备的串行消息,并相应地更新标牌。我们处理传入的消息,并使用RGB值来更新颜色。我们可以使用亮度索引乘以51来创建一个0-255的值,并使用我在前一部分中描述的逻辑来更新LED的亮度。最后,我们很快将开始添加Twitch命令,但颜色索引与我已关联到Twitch聊天命令的颜色选项相匹配,这样在索引循环时,颜色会从一个变为另一个。

通常情况下,我喜欢用便宜的零件看看我能完成多少工作,但对于这个特定的项目,我打算长期使用并不断添加和调整。因此,我在组件上稍微花了一些钱。我使用了Arduino Mega,它具有额外的串行端口和更大的程序容量。虽然事实证明这并不是必要的,但正如我们将要介绍的,我认为程序会更庞大。我有时也遇到Wi-Fi不稳定的问题,所以我使用了一个以太网扩展板来确保稳定和可靠的连接。当然,我也承认我只是想找个借口尝试一下以太网扩展板。

当然,你的以太网电缆实际上必须正常工作才行。

有趣的是,你的以太网电缆必须真正为你的以太网连接工作才能合作。一旦不起作用的电缆被扔进垃圾桶,并且使用了一根好的电缆,以太网的设置就非常简单了(正如你在所附代码中看到的那样)!这意味着是时候让Twitch也能控制LED了。

以下是该项目的完整示意图:

如何使用电容式触摸定制LED Twitch标牌图5

Twitch设置

第一个关键方面是能够使用Arduino收听Twitch聊天消息。为此,你需要Twitch聊天机器人设置来提供访问权限。你可以转到以下URL,然后单击“注册你的应用程序”进行设置:https://dev.twitch.tv/console.

如何使用电容式触摸定制LED Twitch标牌图6

你还需要一个有效的oauth令牌,并且可以使用以下内容https://twitchapps.com/tokengen/设置。

一旦我们使用以太网上网,我们就从连接Twitch开始。此时,我们可以在Twitch聊天中发送一条消息,这既是一种让聊天者知道他们可以使用这些命令的方式,也是一种可视化代码工作的方式。之后,我们开始在Twitch聊天中收听消息。注意:通过设置一个连续循环来实现这一点似乎更简单,所以我在这里添加了一个监听PSoC消息的调用,因为在此期间它不会运行主循环。

如何使用电容式触摸定制LED Twitch标牌图7

设置Twitch命令的标准方法是在命令后面加一个“!”。在这种情况下,我设置了它!color<value>和!亮度<值>命令。监听Twitch消息的代码会查找这些消息,并通过调用我们之前设置的更改颜色和亮度的函数来处理命令。如果这是一个无效的命令,则不会发生任何事情。

由于提供了代码,并且我已经完成了调试过程,所以应该能正常运作了。如果你对有任何问题,你可以使用Postman,它容易上手并且能提非常清晰地报错,因为有时确实很难看出Arduino出了什么问题。

直播状态设置

这仍然需要添加根据直播状态自动打开和关闭标牌的功能。我本以为这将是项目中最容易的部分之一。毕竟,我们已经在与Twitch建立连接并以更高级的方式控制灯光了。会出什么问题呢?

但是事与愿违,尽管在Postman中确认一切都正确,在尝试建立连接时,我完全没有收到任何回应。我目前的理解是,这在很大程度上是由于Arduino(或者至少我尝试过的库)与SSL存在兼容问题,而这确实是一个https调用。

我用Python快速编写了一个程序进行了测试,并立即得到了结果。幸运的是,在此期间我有了一个全新的想法。在准备这个项目之前,我一直在参与其他有趣的与Twitch相关的项目,并且最近我还建立了一个用Python运行的主持剧本杀的聊天机器人。这意味着我有一个Python程序,我完全可以在其中加入一点额外的逻辑来设置直播开始和结束的信息。

我希望项目整体上是美观的。一旦我意识到我可以删除为此添加的所有Arduino代码,并添加一个简单的额外部分来监听聊天消息并开闭灯光(项目中已经存在这两个功能),我意识到这实际上能使整个项目变得更加简洁。我创建了一个简单的、通用的Python程序,可供使用和修改,并将其包含在项目中。它可以持续在一个单独的进程中运行。

我对剧本杀聊天机器人做出了一定的修改,在Twitch聊天中发送一条消息,说明直播模式开启时应该如何使用该机器人,并发送一条简单的消息,表示直播已结束。

如何使用电容式触摸定制LED Twitch标牌图8



你可能会想到一个问题,那就是 Twitch 用户可以使用相同的消息来欺骗 Arduino。然而,那只是打开和关闭灯光,这与我提供给他们的功能相同。这几乎就像是一个彩蛋,用来奖励聪明的聊天者。但是,如果它真的引发了某种问题,我总是可以稍微修改一下Arduino代码,来查找是谁发送了这条消息。

收尾工作

现在是时候通过一些收尾工作来让这个项目画上一个完美的句号了!

一切从焊接开始。PSoC 设备是唯一需要可访问以供使用的设备,因为这是我控制标牌的方式。为了完成这项工作,我使用了一根更长的电缆,然后可以将其隐藏起来。但在开始这个过程之前,我在外壳上刻了一个小缺口,以便电缆通过,这样我就可以重新安装外壳的后部。完成这一步之后,我将电缆焊接到了之前的 TX 引脚上。

为了适应直播,我把标牌放在一个盒子上。我在盒子上切了一个洞,将多余的 LED 条穿过去,然后从侧面穿出去。然后我重新连接了 LED 条,将 Arduino 和面包板移到桌子底下看不见的地方。电缆沿着桌子底部延伸,这样的话就只能看见标牌和 PSoC 设备。

最后一步是在标牌上附上背板,以确保它发出亮光。为此,我只是使用了一块薄的纸板,把它涂成与标牌的其余部分相匹配的颜色。添加了背板后,标牌的效果明显提升,让标牌变得更加明亮。

至此,我们已经完成了整个项目。标牌在 Twitch 直播开始时打开,监听 Twitch 命令和从 PSoC 设备接收的串行消息,以改变标牌的颜色和亮度,在直播结束时会自动关闭。

如何使用电容式触摸定制LED Twitch标牌图9


代码

Arduino代码-它控制LED条并监听PSoC消息和Twitch命令
  1. #include <SPI.h>
  2. #include <Ethernet.h>
  3. // Replace with the twitch bot's username
  4. #define TWITCH_BOT_USERNAME "<your bot username>"
  5. // Replace with the twitch bot's OAuth key
  6. #define OAUTH_KEY "oauth:<your oauth token here>"
  7. // Twitch IRC server and port
  8. #define TWITCH_IRC_SERVER "irc.chat.twitch.tv"
  9. #define TWITCH_IRC_PORT 6667
  10. byte mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED};
  11. // Ethernet client object
  12. EthernetClient client;
  13. #define RED_LED 6
  14. #define BLUE_LED 5
  15. #define GREEN_LED 9
  16. int brightness = 255;
  17. int greenValue = 0;
  18. int redValue = 0;
  19. int blueValue = 0;
  20. int fadeSpeed = 10;
  21. bool isLedOn = false;
  22. boolean turnLedOn = false;
  23. long previousCheck = 0L;
  24. String channel = "<your channel here>";
  25. String clientId = "<your client id here>";
  26. #define TWITCH_CLIENT_ID "<your client id here>"
  27. #define TWITCH_LOGIN "<your channel here>"
  28. bool isStreamLive = false;
  29. bool internetConnected = false;
  30. int brightnessIndex, colorIndex, psocRed, psocGreen, psocBlue = -1;
  31. unsigned long delayBetweenRequests = 60000; // Time between requests (1 minute)
  32. void sendMessage(String message) {
  33.   client.print("PRIVMSG #" + channel + " :" + message + "\r\n");
  34. }
  35. void turnOnOffLed(bool turnOn) {
  36.   for (int i = 0; i < 256; i++) {
  37.     analogWrite(GREEN_LED, brightness);
  38.     analogWrite(RED_LED, brightness);
  39.     analogWrite(BLUE_LED, brightness);
  40.     if (turnOn)
  41.       brightness++;
  42.     else
  43.       brightness--;
  44.     delay(fadeSpeed);
  45.   }
  46.   isLedOn = turnOn;
  47. }
  48. void setLedColor(int red, int green, int blue) {
  49.   //Update these values as well so we can use them for brightness settings
  50.   greenValue = green;
  51.   redValue = red;
  52.   blueValue = blue;
  53.   for (int i = 0; i < 256; i++) {
  54.     analogWrite(GREEN_LED, green);
  55.     analogWrite(RED_LED, red);
  56.     analogWrite(BLUE_LED, blue);
  57.     delay(fadeSpeed);
  58.   }
  59.   isLedOn = true;
  60. }
  61. void updateLEDStrip() {
  62.   if (turnLedOn) {
  63.     if (!isLedOn) {
  64.       turnOnOffLed(true);
  65.     }
  66.     for (int i = 0; i < 256; i++) {
  67.       analogWrite(GREEN_LED, greenValue);
  68.       analogWrite(RED_LED, redValue);
  69.       analogWrite(BLUE_LED, blueValue);
  70.     }
  71.   }
  72.   else if (isLedOn)
  73.     turnOnOffLed(false);
  74. }
  75. void changeBrightness(int brightness) {
  76.   if (brightness >= 0 && brightness <= 255) {
  77.     int newRedValue = redValue * brightness / 255;
  78.     int newGreenValue = greenValue * brightness / 255;
  79.     int newBlueValue = blueValue * brightness / 255;
  80.     int totalColorValue = newRedValue + newGreenValue + newBlueValue;
  81.     float redRatio = (float)newRedValue / (float)totalColorValue;
  82.     float greenRatio = (float)newGreenValue / (float)totalColorValue;
  83.     float blueRatio = (float)newBlueValue / (float)totalColorValue;
  84.     newRedValue = redRatio * brightness;
  85.     newGreenValue = greenRatio * brightness;
  86.     newBlueValue = blueRatio * brightness;
  87.     setLedColor(newRedValue, newGreenValue, newBlueValue);
  88.   }
  89.   else {
  90.     // Handle error if the brightness value is not within the range of 0-255
  91.     Serial.println("ERROR: Invalid brightness value. Brightness must be between 0 and 255.");
  92.   }
  93. }
  94. //Function to change the color of the lights
  95. void changeColor(String currentColor, int colorIndex) {
  96.   Serial.println("New color: " + currentColor);
  97.   if (currentColor == "red" || colorIndex == 1) {
  98.     //Set the lights to red
  99.     setLedColor(255, 0, 0);
  100.   } else if (currentColor == "green" || colorIndex == 2) {
  101.     //Set the lights to green
  102.     setLedColor(0, 255, 0);
  103.   } else if (currentColor == "blue" || colorIndex == 3) {
  104.     //Set the lights to blue
  105.     setLedColor(0, 0, 255);
  106.   } else if (currentColor == "yellow" || colorIndex == 4) {
  107.     //Set the lights to yellow
  108.     setLedColor(255, 255, 0);
  109.   } else if (currentColor == "purple" || colorIndex == 5) {
  110.     //Set the lights to purple
  111.     setLedColor(128, 0, 128);
  112.   } else if (currentColor == "orange" || colorIndex == 6) {
  113.     //Set the lights to orange
  114.     setLedColor(255, 165, 0);
  115.   } else if (currentColor == "white" || colorIndex == 7) {
  116.     //Set the lights to white
  117.     setLedColor(255, 255, 255);
  118.   } else if (currentColor == "off") {
  119.     //Turn the lights off
  120.     turnOnOffLed(false);
  121.   } else {
  122.     Serial.println(currentColor + " is an invalid color");
  123.   }
  124. }
  125. //Dont let twitch users do anything funky
  126. String cleanString(String input) {
  127.   input.trim(); // remove extra spaces from the beginning and end of the string
  128.   input.replace(" ", ""); // remove all spaces in the string
  129.   input.toLowerCase(); // set the string to all lowercase
  130.   // remove any illegal characters
  131.   for (int i = 0; i < input.length(); i++) {
  132.     if (!isAlphaNumeric(input[i])) {
  133.       input.remove(i, 1);
  134.       i--;
  135.     }
  136.   }
  137.   return input;
  138. }
  139. void updateLedFromTwitchChatMessage(String incomingMessage) {
  140.   //Check for the "!color" command
  141.   if (incomingMessage.startsWith("!color")) {
  142.     //Extract the color value from the incoming message
  143.     String color = cleanString(incomingMessage.substring(7));
  144.     Serial.println("Color " + color);
  145.     changeColor(color, -1);
  146.   }
  147.   //Check for the "brightness" command
  148.   if (incomingMessage.startsWith("!brightness")) {
  149.     //Extract the brightness value from the incoming message
  150.     String cleanedString = cleanString(incomingMessage.substring(11));
  151.     int newBrightness = cleanedString.toInt();
  152.     //Check if the new brightness value is valid
  153.     if ((newBrightness != 0 || cleanedString == "0") && newBrightness >= 0 && newBrightness <= 255) {
  154.       //Change the brightness of the lights
  155.       changeBrightness(newBrightness);
  156.     } else {
  157.       Serial.println(cleanedString + " is not a valid brightness");
  158.     }
  159.   }
  160. }
  161. void connectToTwitch() {
  162.   // Connect to Twitch IRC server
  163.   if (client.connect(TWITCH_IRC_SERVER, TWITCH_IRC_PORT)) {
  164.     client.print("PASS " + String(OAUTH_KEY) + "\r\n");
  165.     client.print("NICK " + String(TWITCH_BOT_USERNAME) + "\r\n");
  166.     client.print("JOIN #"+channel"+\r\n");
  167.   } else {
  168.     // Connection failed
  169.     Serial.println("ERROR: Connection to Twitch failed.");
  170.     Serial.println("Error code: " + String(client.getWriteError()));
  171.   }
  172. }
  173. void receiveTwitchMessages() {
  174.   while (client.connected()) {
  175.     if (client.available()) {
  176.       String response = client.readStringUntil('\n');
  177.       if (response == "PING :tmi.twitch.tv\r\n") {
  178.         client.print("PONG :tmi.twitch.tv\r\n");
  179.       } else {
  180.         Serial.println(response);
  181.         int startIndex = response.indexOf(":", 1);
  182.         int endIndex = response.indexOf("\r\n");
  183.         if (endIndex < 0)
  184.           endIndex = response.length();
  185.         if (startIndex != -1 && endIndex != -1) {
  186.           String message = response.substring(startIndex + 1, endIndex);
  187.           Serial.println("The message is " + message);
  188.           if (message.startsWith("!")) {
  189.             Serial.println("Sending message: " + message);
  190.             updateLedFromTwitchChatMessage(message);
  191.           } else if (message.indexOf("Press !mystery to start off a mystery anytime! (I'm a bot)") >= 0 && !isStreamLive) {
  192.             isStreamLive = true;
  193.             turnOnOffLed(isStreamLive);
  194.           } else if (message.indexOf("The stream is now offline.") >= 0 && isStreamLive) {
  195.             isStreamLive = false;
  196.             turnOnOffLed(isStreamLive);
  197.           }
  198.         }
  199.       }
  200.     }
  201.     //The loop is inaccessible, so just call for psoc messages here instead
  202.     receivePsocMessages();    //Via serial
  203.   }
  204.   client.stop();
  205. }
  206. void receivePsocMessages() {
  207.   // Check for incoming serial data from the PSOC
  208.   if (Serial1.available() > 0) {
  209.     int redHexValue, greenHexValue, blueHexValue, b, c;
  210.     String incomingData = Serial1.readStringUntil('\n');
  211.     Serial.print("incomingData ");
  212.     Serial.println(incomingData);
  213.     if (incomingData.startsWith("RGB:")) {
  214.       // Extract the red, green, and blue values from the incoming data
  215.       sscanf(incomingData.c_str(), "RGB:%02X%02X%02X", &redHexValue, &greenHexValue, &blueHexValue);
  216.       Serial.print("RGB " + String(redHexValue) + " " + String(greenHexValue) + " " + String(blueHexValue));
  217.       if (psocRed != redValue || psocGreen != greenValue || psocBlue != blueValue) {
  218.         turnLedOn = true;
  219.         psocRed, redValue = redHexValue;
  220.         psocGreen, greenValue = greenHexValue;
  221.         psocBlue, blueValue = blueHexValue;
  222.         updateLEDStrip();
  223.       }
  224.     } else if (incomingData.startsWith("Brightness Index: ")) {
  225.       // Extract the red, green, and blue values from the incoming data
  226.       sscanf(incomingData.c_str(), "Brightness Index: %d", &b);
  227.       Serial.print("Brightness Index: " + String(b));
  228.       //Change the brightness of the lights
  229.       if (b != brightnessIndex) {
  230.         changeBrightness(51 * b); //goes from 0-255
  231.         brightnessIndex = b;
  232.       }
  233.     } else if (incomingData.startsWith("Color Index: ")) {
  234.       // Extract the red, green, and blue values from the incoming data
  235.       sscanf(incomingData.c_str(), "Color Index: %d", &c);
  236.       Serial.print("Color Index: " + String(c));
  237.       if (c != colorIndex) {
  238.         changeColor("", c);
  239.         colorIndex = c;
  240.       }
  241.     }
  242.   }
  243. }
  244. void setup() {
  245.   //  pinMode(led, OUTPUT);
  246.   pinMode(GREEN_LED, OUTPUT);
  247.   pinMode(RED_LED, OUTPUT);
  248.   pinMode(BLUE_LED, OUTPUT);
  249.   turnOnOffLed(true);
  250.   delay(5000);
  251.   turnOnOffLed(false);
  252.   Serial.begin(115200);
  253.   Serial1.begin(115200);
  254.   setupConnection();
  255.   Serial.println("Setup done");
  256. }
  257. void setupConnection() {
  258.   // start Ethernet and UDP
  259.   if (Ethernet.begin(mac) == 0) {
  260.     Serial.println("Failed to configure Ethernet using DHCP");
  261.     // Check for Ethernet hardware present
  262.     if (Ethernet.hardwareStatus() == EthernetNoHardware) {
  263.       Serial.println("Ethernet shield was not found.  Sorry, can't run without hardware. :(");
  264.     } else if (Ethernet.linkStatus() == LinkOFF) {
  265.       Serial.println("Ethernet cable is not connected.");
  266.     }
  267.   } else {
  268.     Serial.println("Internet is connected");
  269.     internetConnected = true;
  270.   }
  271.   connectToTwitch();
  272.   sendMessage("Hi Twitch - You can change the light colors with !color <color> commands! (sent via a bot)");
  273. }
  274. void loop() {
  275.   if (millis() - previousCheck >= 120000L) { // check every 2 minutes
  276.     previousCheck = millis();
  277.     if (!internetConnected) {
  278.       Serial.println("Attempting to setup connection");
  279.       setupConnection();
  280.     }
  281.   }
  282.   receiveTwitchMessages();  //Via IRC on ethernet
  283.   receivePsocMessages();    //Via serial
  284. }
复制代码

Python代码-这是代码的通用版本,你可以使用它来检查流状态,并在Twitch Chat中发送消息,然后Arduino代码可以监听这些消息
  1. import requests
  2. import time
  3. from twitchio.ext import commands
  4. from twitchio.client import Client
  5. from twitchio import Message
  6. # Replace with your Twitch client ID and OAuth token
  7. TWITCH_CLIENT_ID = 'your_client_id'
  8. TWITCH_OAUTH_TOKEN = 'your_oauth_token'
  9. TWITCH_LOGIN = 'your_login_name'
  10. TWITCH_CHANNEL = 'twitch_channel_name'
  11. # Keep track of the current stream status
  12. stream_live = False
  13. CHECK_INTERVAL = 60  # seconds
  14. def is_stream_live():
  15.     url = f'https://api.twitch.tv/helix/streams?user_login={TWITCH_LOGIN}'
  16.     headers = {
  17.         'Client-ID': TWITCH_CLIENT_ID,
  18.         'Authorization': f'Bearer {TWITCH_OAUTH_TOKEN}'
  19.     }
  20.     response = requests.get(url, headers=headers)
  21.     data = response.json()
  22.     print(data)
  23.     if data.get('data') and data['data'][0].get('type') == 'live':
  24.         return True
  25.     return False
  26. def send_message(msg):
  27.     bot = commands.Bot(
  28.         irc_token='your_irc_token',
  29.         client_id='your_client_id',
  30.         nick='your_bot_name',
  31.         prefix='!',
  32.         initial_channels=[TWITCH_CHANNEL]
  33.     )
  34.     bot.run()
  35.     bot._ws.send_privmsg(TWITCH_CHANNEL, msg)
  36. def main():
  37.     stream_live = False
  38.     while True:
  39.         live = is_stream_live()
  40.         if live != stream_live:
  41.             stream_live = live
  42.             msg = 'The stream has started! Get in here for good times!' if live else 'The stream has ended. Hope you enjoyed!'
  43.             send_message(msg)
  44.             print(msg)
  45.         time.sleep(CHECK_INTERVAL)
  46. if __name__ == '__main__':
  47.     main()
复制代码
PSoC代码-这是Color Gamut示例项目的更新主.c文件,其中按钮被修改,然后数据通过UART发送到Arduino设备
  1. /******************************************************************************
  2. * File Name: main.c
  3. *
  4. * Version: 1.00
  5. *
  6. * Description:  This code example demonstrates how to use CapSense trackpad
  7. *               to input RGB color code for color mixing with PSoC 4 S-Series device.
  8. *
  9. * Related Document: CE214025 Trackpad with Color Gamut.pdf
  10. *
  11. * Hardware Dependency: See code example document CE214025 Trackpad with Color Gamut.pdf
  12. *
  13. ******************************************************************************
  14. * Copyright (2016), Cypress Semiconductor Corporation.
  15. ******************************************************************************
  16. * This software, including source code, documentation and related materials
  17. * ("Software") is owned by Cypress Semiconductor Corporation (Cypress) and is
  18. * protected by and subject to worldwide patent protection (United States and
  19. * foreign), United States copyright laws and international treaty provisions.
  20. * Cypress hereby grants to licensee a personal, non-exclusive, non-transferable
  21. * license to copy, use, modify, create derivative works of, and compile the
  22. * Cypress source code and derivative works for the sole purpose of creating
  23. * custom software in support of licensee product, such licensee product to be
  24. * used only in conjunction with Cypress's integrated circuit as specified in the
  25. * applicable agreement. Any reproduction, modification, translation, compilation,
  26. * or representation of this Software except as specified above is prohibited
  27. * without the express written permission of Cypress.
  28. *
  29. * Disclaimer: THIS SOFTWARE IS PROVIDED AS-IS, WITH NO WARRANTY OF ANY KIND,
  30. * EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, NONINFRINGEMENT, IMPLIED
  31. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  32. * Cypress reserves the right to make changes to the Software without notice.
  33. * Cypress does not assume any liability arising out of the application or use
  34. * of Software or any product or circuit described in the Software. Cypress does
  35. * not authorize its products for use as critical components in any products
  36. * where a malfunction or failure may reasonably be expected to result in
  37. * significant injury or death ("ACTIVE Risk Product"). By including Cypress's
  38. * product in a ACTIVE Risk Product, the manufacturer of such system or application
  39. * assumes all risk of such use and in doing so indemnifies Cypress against all
  40. * liability. Use of this Software may be limited by and subject to the applicable
  41. * Cypress software license agreement.
  42. *****************************************************************************/
  43. /*******************************************************************************
  44. *   Included Headers
  45. *******************************************************************************/
  46. #include <project.h>
  47. /* Include boolean function definition */
  48. #include <stdbool.h>
  49. /* Include color mixing API declarations */
  50. #include "colormixing.h"
  51. /* Include sprintf API definitions */
  52. #include <stdio.h>
  53. /*******************************************************************************
  54. *   Macros and #define Constants
  55. *******************************************************************************/
  56. /*The UART variables*/
  57. char string[100];   //Used to send the brightness data
  58. #define SEND_INTERVAL       (2000u)
  59. /* Intensity control button status */   
  60. #define BUTTON_ON                   (0x01u)
  61. #define BUTTON_OFF                  (0x00u)
  62. /* Multiplier value for color mixing to avoid floating point math */   
  63. #define POS_MULT_100                (100u)   
  64. /* Number of active sensors when palm is placed on trackpad */
  65. #define ACTIVE_SENSORS_PALM          (4u)
  66. /* Minimum and maximum intensity values. This value is divided by 10 and is multiplied
  67. *  by MAX_COMPAREVALUE     
  68. */   
  69. #define MAX_INTENSITY_LEVEL         (16u)
  70. /* Default intensity value */   
  71. #define DEFAULT_LED_INTENSITY       (MAX_COMPAREVALUE/2)
  72. /*LED wil be driven for the specified number of loops after no touch*/
  73. #define MAX_LOOPS_TO_DRIVE_LED      (75u)
  74. /*Index for brightness control array*/
  75. #define MAX_INTENSITY_INDEX         (3u)
  76. #define MIN_INTENSITY_INDEX         (0u)
  77. /*LED brightness macros*/
  78. #define LED_BRIGHTNESS_12_5         (2u)
  79. #define LED_BRIGHTNESS_25_0         (4u)
  80. #define LED_BRIGHTNESS_37_5         (6u)
  81. #define LED_BRIGHTNESS_100_0        (16u)
  82. /*Offset correction macros*/
  83. #define MIN_X_COORDINATE            (15u)
  84. #define MAX_X_COORDINATE            (75u)
  85. #define MIN_Y_COORDINATE            (8u)
  86. #define MAX_Y_COORDINATE            (77u)
  87. #define Y_COORDINATE_OFFSET         (7u)
  88. #define Y_COORDINATE_NEED_OFFSET    (29u)
  89. #define MAX_X_COORDINATE_FOR_COLOR_MIXING   (64u)
  90. /*******************************************************************************
  91. *   Module Variable and Constant Declarations with Applicable Initializations
  92. *******************************************************************************/
  93.    
  94. /* Finite state machine states for device operation */
  95. typedef enum
  96. {
  97.     SENSOR_SCAN = 0x01u,    /* Sensor is scanned in this state */
  98.     WAIT_FOR_SCAN_COMPLETE = 0x02u, /* CPU is put to sleep in this state */
  99.     PROCESS_DATA = 0x03u,   /* Sensor data is processed */
  100. } DEVICE_STATE;
  101. const uint8 brightnessLevels[] = {LED_BRIGHTNESS_12_5,LED_BRIGHTNESS_25_0
  102.                                     ,LED_BRIGHTNESS_37_5 ,LED_BRIGHTNESS_100_0};
  103. uint8 brightnessIndex = MAX_INTENSITY_INDEX;
  104. /*******************************************************************************
  105. *  Function Declarations
  106. *******************************************************************************/
  107. /* Function prototype for CapSense parameter initialization */
  108. void capSenseInit(void);
  109. /* Function prototype to scan CapSense sensors */
  110. void capSenseProcess(void);
  111. /* Function prototype to initialize TCPWM components */
  112. void prismInit(void);
  113. /* Function that checks if trackpad or button sensors are ON */
  114. bool anyWidgetActive(void);
  115. /* Function that performs color mixing */
  116. void colorMixingProcess(void);
  117. /*******************************************************************************
  118. *   Module Variable and Constant Declarations with Applicable Initializations
  119. *******************************************************************************/
  120. /* Contains current x, y coordinates of trackpad */
  121. uint16 trackpadXPos = CapSense_SLIDER_POS_NONE;
  122. uint16 trackpadYPos = CapSense_SLIDER_POS_NONE;   
  123. /* Variable to store color mixing error status */
  124. uint8 colorMixingError;
  125. /* Variable to store interrupt state */
  126. uint32 interruptState = 0u;
  127. /* Variable to store the current trackpad XY coordinates.
  128. *  The XY coordinate is multiplied with 100 to avoid floating point math
  129. */
  130. XY_COORDINATE currentXYCoordinate;
  131. /* Variable to store last valid touch coordinates */
  132. XY_COORDINATE lastValidXYCoordinate;
  133. /* Variable to store RGB led dimming values */
  134. uint16 rgbLEDDimmingValue[NUM_LEDS];
  135. uint16 timeoutCounter;
  136. /* Variable to store RGB LED coordinates on the color gamut
  137. *  The coordinates are multiplied by 10000 to avoid floating point math
  138. */
  139. LED_COORDINATE rgbLEDXYPosition[NUM_LEDS];
  140. /* Variable to store On/Off condition of trackpad */
  141. uint8 trackpadStatus = 0;
  142. /* Variable to control the maximum intensity of RGB LED
  143. *  Variable takes the following values 2, 4, 8 and 16
  144. *  The resulting PWM compare value is multiplied with this value
  145. *  and normalized to achieve duty cycle of 100%, 50%, 25% and 12.5%
  146. */
  147. uint8 intensityCtrl = MAX_INTENSITY_LEVEL;
  148. /* Variable to store the status of intensity control buttons */  
  149. uint8 button0CurrState = BUTTON_OFF;
  150. uint8 button0PrevState = BUTTON_OFF;
  151. uint8 button1CurrState = BUTTON_OFF;
  152. uint8 button1PrevState = BUTTON_OFF;
  153. /* Minimum and maximum brightness index */
  154. #define MIN_BRIGHTNESS_INDEX 0
  155. #define MAX_BRIGHTNESS_INDEX 5
  156. /* Minimum and maximum color index */
  157. #define MIN_COLOR_INDEX 1
  158. #define MAX_COLOR_INDEX 7
  159. /* Current color index */
  160. uint8 colorIndex = MIN_COLOR_INDEX;
  161. /******************************************************************************
  162. * Function Name: main
  163. *******************************************************************************
  164. *
  165. * Summary: This function implements the state machine for device operation.
  166. *
  167. * Parameters:
  168. *  None.
  169. *
  170. * Return:
  171. *  None.
  172. *
  173. * Theory:
  174. *   main() performs following functions:
  175. *  1: Initialize the CapSense, EZI2C and PWM Components
  176. *  2: Scans trackpad, buttons and performs color mixing and brightness control using
  177. *     RGB LED
  178. *
  179. * Side Effects: None
  180. *
  181. * Note:None
  182. *
  183. *******************************************************************************/
  184. int main()
  185. {   
  186.     /* Start the firmware state machine with sensor scan */
  187.     DEVICE_STATE currentState = SENSOR_SCAN;
  188.    
  189.     /* Variable to hold active sensors count */
  190.     uint16 sensorCount = 0u;
  191.    
  192.     /* Variable to check active sensor bits */
  193.     uint16 mask = 0u;
  194.    
  195.     /* Temporary variable */
  196.     uint16 tempVar = 0u;   
  197.    
  198.     /* Enable interrupts. This is required for CapSense and I2C operation */
  199.     CyGlobalIntEnable;
  200.    
  201.     /* Initialize I2C component for CapSense tuner */
  202.     EZI2C_Start();
  203.    
  204.     /* Set up communication data buffer to CapSense data structure to
  205.     * expose to I2C master at primary slave address request
  206.     */
  207.     EZI2C_EzI2CSetBuffer1(sizeof(CapSense_dsRam), sizeof(CapSense_dsRam),\
  208.                          (uint8 *)&CapSense_dsRam);
  209.    
  210.     /* Start the CapSense component and autocalibrate IDAC values */
  211.     capSenseInit();  
  212.    
  213.     /* Initialize PWM components */
  214.     prismInit();
  215.    
  216.     /* Load XY coordinates of RGB LED on color gamut into local variables */
  217.     initializeLedCoordinates(rgbLEDXYPosition);
  218.    
  219.     SW_Tx_UART_1_Start();
  220.    
  221.     for(;;)
  222.     {        
  223.         switch(currentState)
  224.         {
  225.             case SENSOR_SCAN:
  226.                         {
  227.                 /* Initiate new scan only if the CapSense hardware is idle */
  228.                 if(CapSense_NOT_BUSY == CapSense_IsBusy())
  229.                 {
  230.                     /* Update CapSense parameters set via CapSense tuner */
  231.                     CapSense_RunTuner();      
  232.                     
  233.                     /*Scan trackpad and buttons*/
  234.                     CapSense_ScanAllWidgets();
  235.                     
  236.                     /* Set the state machine to wait state until the scan is complete */
  237.                     currentState = WAIT_FOR_SCAN_COMPLETE;   
  238.                 }
  239.                     break;
  240.                         }
  241.             
  242.                         case WAIT_FOR_SCAN_COMPLETE:
  243.                         {
  244.                 /* Device is in CPU Sleep until CapSense scanning is complete or
  245.                 *  device is woken-up by either CapSense interrupt or I2C interrupt
  246.                 */
  247.                 /* Disable interrupts, so that ISR is not serviced while
  248.                 *  checking for CapSense scan status. Otherwise, interrupt might
  249.                 *  get serviced after checking for IsBusy condition and device
  250.                 *  might not wakeup since CapSense interrupt is already serviced
  251.                 */
  252.                 interruptState = CyEnterCriticalSection();
  253.                            
  254.                 /* Check if CapSense scanning is complete */
  255.                 if(CapSense_NOT_BUSY != CapSense_IsBusy())
  256.                 {
  257.                     /* If CapSense scannning is in progress, put CPU to sleep
  258.                     *  Device wakesup because of CapSense scan complete interrupt
  259.                     */
  260.                     CySysPmSleep();
  261.                 }
  262.                 /* If CapSense scanning is complete, process the CapSense data */
  263.                 else
  264.                 {
  265.                     /* If current widget is trackpad or mode is slow scan mode, process the sensor data */
  266.                     currentState = PROCESS_DATA;
  267.                 }
  268.                 /* Enable interrupts for servicing ISR */
  269.                 CyExitCriticalSection(interruptState);
  270.                     break;
  271.             }           
  272.             
  273.                         case PROCESS_DATA:
  274.             {            
  275.                        
  276.                 /* Set next state to Sensor Scan */
  277.                 currentState = SENSOR_SCAN;
  278.                 CapSense_ProcessAllWidgets();
  279.                 /* The below code resets trackpad baseline if a palm is detected on the trackpad */
  280.                 if(CapSense_IsWidgetActive(CapSense_TRACKPAD_WDGT_ID))
  281.                 {
  282.                     /* Initialize mask variable */
  283.                     mask = 1u;
  284.                     
  285.                     /* Set active sensor count to zero */
  286.                     sensorCount = 0u;
  287.                     
  288.                     /* Loop through all the row and column sensors */
  289.                     for(tempVar = CapSense_TRACKPAD_COL0_ID; tempVar <= CapSense_TRACKPAD_ROW6_ID; tempVar++)
  290.                     {
  291.                         /* Check each bit for active sensor condition */
  292.                         if(CapSense_SNS_STATUS0_VALUE & mask)
  293.                         {
  294.                             /* Increment sensor count for each active sensor */
  295.                            sensorCount++;
  296.                         }
  297.                         /* If all the column sensors are searched and active sensorCount is not greater than threshold
  298.                         *  reset the sensorCount variable to detect active row sensors
  299.                         */
  300.                         if((tempVar == CapSense_TRACKPAD_COL6_ID) && (sensorCount <= ACTIVE_SENSORS_PALM))
  301.                         {
  302.                             sensorCount = 0u;
  303.                         }
  304.                         
  305.                         /* If active sensor count in either a row or column has exceed the threshold
  306.                         *  reset all the trackpad sensor baselines
  307.                         */
  308.                         if(sensorCount > ACTIVE_SENSORS_PALM)
  309.                         {
  310.                             CapSense_InitializeWidgetBaseline(CapSense_TRACKPAD_WDGT_ID);
  311.                             break;
  312.                         }
  313.                         /* Update the mask variable until all the bits are scanned for active status */
  314.                         mask = mask << 1u;
  315.                     }                           
  316.                 }
  317.                 /* Check if Left button is active */
  318.                 if(CapSense_IsWidgetActive(CapSense_INTENSITYUP_WDGT_ID))
  319.                     button0CurrState = BUTTON_ON;
  320.                 else
  321.                     button0CurrState = BUTTON_OFF;
  322.                 /* Check if Right button is active */
  323.                 if(CapSense_IsWidgetActive(CapSense_INTENSITYDOWN_WDGT_ID))
  324.                     button1CurrState = BUTTON_ON;
  325.                 else
  326.                     button1CurrState = BUTTON_OFF;
  327.                 /* Check for rising edge of Left button status  and toggle brightness value 0-5 */
  328.                 if((button0CurrState == BUTTON_ON) && (button0PrevState == BUTTON_OFF))
  329.                 {                    
  330.                     if(brightnessIndex >= MAX_BRIGHTNESS_INDEX)
  331.                     {
  332.                         brightnessIndex = MIN_BRIGHTNESS_INDEX;
  333.                     }
  334.                     else
  335.                     {
  336.                         brightnessIndex++;
  337.                     }
  338.                 }
  339.                 /* Check for rising edge of Right button status  and toggle color settings 1-7 */
  340.                 else if((button1CurrState == BUTTON_ON) && (button1PrevState == BUTTON_OFF))
  341.                 {
  342.                     if(colorIndex >= MAX_COLOR_INDEX)
  343.                     {
  344.                         colorIndex = MIN_COLOR_INDEX;
  345.                     }
  346.                     else
  347.                     {
  348.                         colorIndex++;
  349.                     }
  350.                 }
  351.             /* Initialize previous button state to current button state */
  352.             button0PrevState = button0CurrState;
  353.             button1PrevState = button1CurrState;               
  354.            
  355.             /* If trackpad or button sensor is not active, increment the LED timeout counter */
  356.            if(!anyWidgetActive())
  357.              {
  358.                 timeoutCounter++;
  359.                 /* Check if sensor is inactive for a duration greater than MAX_LOOPS_TO_DRIVE_LED */
  360.                 if(timeoutCounter >= MAX_LOOPS_TO_DRIVE_LED)
  361.                 {                        
  362.                     /* Set LED pin drive mode to high-z to stop driving LEDs */
  363.                     Red_LED_SetDriveMode(Red_LED_DM_ALG_HIZ);
  364.                     Green_LED_SetDriveMode(Green_LED_DM_ALG_HIZ);
  365.                     Blue_LED_SetDriveMode(Blue_LED_DM_ALG_HIZ);                        
  366.                 }
  367.             }  
  368.             /* If either trackpad or button sensors are active, perform color mixing */
  369.             else
  370.             {                    
  371.                 /* Because sensor is active, reset the counter */
  372.                 timeoutCounter = 0;
  373.                 /* If widget is active, perform color mixing */
  374.                 colorMixingProcess();
  375.             }                              
  376.                 break;
  377.         }
  378.          
  379.             default:
  380.                         {
  381.             /*******************************************************************
  382.              * Unknown state. Unexpected situation.
  383.              ******************************************************************/
  384.                     CYASSERT(0);
  385.                     break;
  386.                         }
  387.         }
  388.     }
  389. }
  390. /******************************************************************************
  391. * Function Name: capSenseInit
  392. *******************************************************************************
  393. *
  394. * Summary: This API initializes CapSense block
  395. *
  396. * Parameters:
  397. *  None.
  398. *
  399. * Return:
  400. *  None.
  401. *
  402. * Theory:
  403. *   capSenseInit() performs following functions:
  404. *  1: Starts the CapSense block
  405. *  2: Scan the trackpad widget and initialize the previous touch coordinate values
  406. *
  407. * Side Effects: None
  408. *
  409. * Note: None
  410. *
  411. *******************************************************************************/
  412. void capSenseInit(void)
  413. {
  414.     /* Variable to store the XY coordinates */
  415.     uint32 tempCoordinates;
  416.    
  417.     /* Initialize CapSense block */
  418.     CapSense_Start();
  419.    
  420.     CapSense_InitializeWidgetBaseline(CapSense_INTENSITYUP_WDGT_ID);
  421.     CapSense_InitializeWidgetBaseline(CapSense_INTENSITYDOWN_WDGT_ID);
  422.    
  423.     /* Scan the trackpad widget and initialize the previous touch coordinate values*/
  424.     trackpadStatus =  CapSense_IsWidgetActive(CapSense_TRACKPAD_WDGT_ID);
  425.    
  426.     /* Get XY Coordinates */
  427.     tempCoordinates = CapSense_GetXYCoordinates(CapSense_TRACKPAD_WDGT_ID);
  428.    
  429.     /* Load XY position to variable. Note: the XY position is interchanged as the
  430.     *  columns and rows in the PCB layout is inverse of X, Y coordinate of color gamut
  431.     */
  432.     trackpadYPos = LO16(tempCoordinates);
  433.     trackpadXPos = HI16 (tempCoordinates);
  434.    
  435.     /* Initialize last valid coordinates so that RGB LED glows
  436.     *  when button is touched before trackpad after device power-up or reset.
  437.     */
  438.     lastValidXYCoordinate.currentX = RED_BASE_COLOR_X;
  439.     lastValidXYCoordinate.currentY = RED_BASE_COLOR_Y;
  440.    
  441.     /* Set default led intensity value */
  442.     currentXYCoordinate.ledIntensity = DEFAULT_LED_INTENSITY;
  443. }
  444. /******************************************************************************
  445. * Function Name: prismInit
  446. *******************************************************************************
  447. *
  448. * Summary: This API initializes PWM components
  449. *
  450. * Parameters:
  451. *  None.
  452. *
  453. * Return:
  454. *  None.
  455. *
  456. * Theory:
  457. *  prismInit() performs following functions:
  458. *  1: Starts the TCPWM block
  459. *  2: Initializes the TCPWM compare value to minimum value
  460. *
  461. * Side Effects: None
  462. *
  463. * Note: None
  464. *
  465. *******************************************************************************/
  466. void prismInit(void)
  467. {
  468.     /* Start TCPWM Blocks */
  469.     PrISM_Red_Start();
  470.     PrISM_Green_Start();
  471.     PrISM_Blue_Start();
  472.    
  473.     /* Set TCPWM compare value to zero initially */
  474.     PrISM_Red_WriteCompare(MIN_COMPAREVALUE);
  475.     PrISM_Green_WriteCompare(MIN_COMPAREVALUE);
  476.     PrISM_Blue_WriteCompare(MIN_COMPAREVALUE);
  477. }
  478. /*******************************************************************************
  479. * Function Name: anyWidgetActive
  480. ********************************************************************************
  481. *
  482. * Summary:
  483. *  This API checks if any widget is active
  484. *
  485. * Parameters:
  486. *  None.
  487. *
  488. * Theory: This API checks if any of the IntensityUp, IntensityDown or trackpad sensors
  489. *         are active and returns true if any one of them is active.
  490. *
  491. * Side Effects: None
  492. *
  493. * Note: None
  494. *
  495. *******************************************************************************/
  496. bool anyWidgetActive(void)
  497. {
  498.     /* Check if either trackpad or any of the two button sensors are active */
  499.     if(CapSense_IsWidgetActive(CapSense_TRACKPAD_WDGT_ID) || \
  500.        CapSense_IsWidgetActive(CapSense_INTENSITYUP_WDGT_ID) || \
  501.        CapSense_IsWidgetActive(CapSense_INTENSITYDOWN_WDGT_ID))
  502.     {
  503.         return TRUE;
  504.     }
  505.     else
  506.     {
  507.         return FALSE;
  508.     }
  509. }
  510. /*******************************************************************************
  511. * Function Name: colorMixingProcess
  512. ********************************************************************************
  513. *
  514. * Summary:
  515. *  This API checks if any widget is active and computes the TCPWM compare value
  516. *
  517. * Parameters:
  518. *  None.
  519. *
  520. * Theory: This API checks if any of the IntensityUp, IntensityDown or trackpad sensors
  521. *         are active. Based on the status, the color mixing algorithm is executed to
  522. *         compute the compare
  523. *
  524. * Side Effects: None
  525. *
  526. * Note: None
  527. *
  528. *******************************************************************************/
  529. void colorMixingProcess(void)
  530. {
  531.     /* Temporary variable */
  532.     uint32 tempVar;
  533.    
  534.     /* Variable to store XY coordinates of trackpad */
  535.     uint32 tempCoordinates;
  536.     /* Obtain the maximum compare value depending on the intensity level set by user */
  537.     tempVar = (uint32) (intensityCtrl * MAX_COMPAREVALUE);
  538.     tempVar /= MAX_INTENSITY_LEVEL;
  539.     currentXYCoordinate.ledIntensity = (uint16)tempVar;
  540.     lastValidXYCoordinate.ledIntensity = currentXYCoordinate.ledIntensity;   
  541.    
  542.     /* Check if trackpad is active */
  543.     trackpadStatus =  CapSense_IsWidgetActive(CapSense_TRACKPAD_WDGT_ID);
  544.    
  545.     /* Get trackpad XY coordinates */
  546.     tempCoordinates = CapSense_GetXYCoordinates(CapSense_TRACKPAD_WDGT_ID);
  547.    
  548.     /* XY position values and store in local variable
  549.     *  Note: The XY position is interchanged because the rows and columns are
  550.     *  interchanged in the kit
  551.     */
  552.     trackpadYPos = LO16(tempCoordinates);
  553.     trackpadXPos = HI16(tempCoordinates);
  554.    
  555.     /* If trackpad is active, load the XY position for computing dimming values */
  556.     if(trackpadStatus)
  557.     {
  558.         /* Normalization is done because row0 to row6 and column0 to column 6
  559.         *  are inverted in the layout      
  560.         */
  561.         trackpadXPos = CapSense_TRACKPAD_Y_RESOLUTION - trackpadXPos;
  562.         trackpadYPos = CapSense_TRACKPAD_X_RESOLUTION - trackpadYPos;
  563.         
  564.         /*Offset correction to get smooth response near color gamut edges*/
  565.         if(trackpadXPos <= MIN_X_COORDINATE)
  566.         {
  567.             trackpadXPos = MIN_X_COORDINATE;
  568.         }        
  569.         else if (trackpadXPos >= MAX_X_COORDINATE_FOR_COLOR_MIXING && trackpadXPos <= MAX_X_COORDINATE)
  570.         {
  571.             trackpadXPos = MAX_X_COORDINATE_FOR_COLOR_MIXING;
  572.         }        
  573.         
  574.         if(trackpadYPos <= MIN_Y_COORDINATE)
  575.         {
  576.             trackpadYPos = MIN_Y_COORDINATE;
  577.         }
  578.         else if (trackpadYPos <= Y_COORDINATE_NEED_OFFSET)
  579.         {
  580.             trackpadYPos = trackpadYPos + Y_COORDINATE_OFFSET;
  581.         }
  582.         else if(trackpadYPos >= MAX_Y_COORDINATE)
  583.         {
  584.             trackpadYPos = MAX_Y_COORDINATE;
  585.         }
  586.         
  587.     }
  588.     else
  589.     {
  590.         trackpadXPos = 0u;
  591.         trackpadYPos = 0u;
  592.     }
  593.    
  594.     /* Multiply the coordinate value by 100 to avoid floating point math */
  595.     currentXYCoordinate.currentX = (int16)(trackpadXPos * POS_MULT_100);
  596.     currentXYCoordinate.currentY = (int16)(trackpadYPos * POS_MULT_100);
  597.    
  598.     /* If finger is on trackpad, use current touch coordinates to compute dimming values */
  599.     if(trackpadStatus)
  600.     {
  601.         /* Compute RGB LED dimming values for a given XY coordinate */
  602.         colorMixingError = rgbColorMix(currentXYCoordinate, rgbLEDXYPosition, rgbLEDDimmingValue);
  603.         
  604.         /* If color mixing was successful, save the current coordinates */
  605.         if(colorMixingError != INVALID_COLOR)
  606.         {
  607.             lastValidXYCoordinate.currentX = currentXYCoordinate.currentX;
  608.             lastValidXYCoordinate.currentY = currentXYCoordinate.currentY;
  609.         }
  610.     }
  611.     /* If IntensityUp or IntensityDown button is pressed, compute dimming value using previous saved touch coordinates */
  612.     else
  613.     {
  614.         colorMixingError = rgbColorMix(lastValidXYCoordinate, rgbLEDXYPosition, rgbLEDDimmingValue);
  615.     }
  616.     /* Update the LED dimming value only when color mixing process is successful */
  617.     if(colorMixingError != INVALID_COLOR)
  618.     {
  619.         /* Set LED pin drive mode to strong to save power */
  620.         Red_LED_SetDriveMode(Red_LED_DM_STRONG);
  621.         Green_LED_SetDriveMode(Green_LED_DM_STRONG);
  622.         Blue_LED_SetDriveMode(Blue_LED_DM_STRONG);
  623.                         
  624.         /* Load the computed dimming value to the PrISM component */
  625.         PrISM_Red_WriteCompare(rgbLEDDimmingValue[LED_RED]);
  626.         PrISM_Green_WriteCompare(rgbLEDDimmingValue[LED_GREEN]);
  627.         PrISM_Blue_WriteCompare(rgbLEDDimmingValue[LED_BLUE]);
  628.         
  629.         
  630.         /* Transmit different data types through the UART */
  631.         SW_Tx_UART_1_PutString("RGB:");
  632.         SW_Tx_UART_1_PutHexByte(rgbLEDDimmingValue[LED_RED]);
  633.         SW_Tx_UART_1_PutHexByte(rgbLEDDimmingValue[LED_GREEN]);
  634.         SW_Tx_UART_1_PutHexByte(rgbLEDDimmingValue[LED_BLUE]);
  635.         SW_Tx_UART_1_PutCRLF();
  636.         SW_Tx_UART_1_PutString("Brightness Index: ");
  637.         SW_Tx_UART_1_PutHexInt(brightnessIndex);
  638.         SW_Tx_UART_1_PutCRLF();
  639.         SW_Tx_UART_1_PutString("Color Index: ");
  640.         SW_Tx_UART_1_PutHexInt(colorIndex);
  641.         SW_Tx_UART_1_PutCRLF();
  642.         CyDelay(SEND_INTERVAL);
  643.         SW_Tx_UART_1_PutCRLF();
  644.     }
  645. }
  646. /* [] END OF FILE */
复制代码

希望你会喜欢这个新奇的标牌!祝一切顺利。

原文作者:donutsorelse
原文链接:https://community.dfrobot.com/makelog-313144.html

转载请注明来源信息

Amos Young  中级技师

发表于 2023-8-23 17:12:30

厉害了,膜拜大神作品
回复

使用道具 举报

快看擎天猪  中级技师

发表于 2023-8-24 14:25:00

厉害了,膜拜大神作品
回复

使用道具 举报

三春牛-创客  初级技神

发表于 2023-8-26 10:36:25

厉害厉害
回复

使用道具 举报

三春牛-创客  初级技神

发表于 2023-8-26 10:37:29

太棒了,赞一个
回复

使用道具 举报

花生编程  中级技匠

发表于 2023-8-29 17:23:06

厉害厉害!
回复

使用道具 举报

花生编程  中级技匠

发表于 2023-8-29 17:24:07

不错不错!
回复

使用道具 举报

快看擎天猪  中级技师

发表于 2023-8-31 14:24:35

6666666666666666666
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail