c++ - 使用 Arduino 信号作为 PC 的输入?

标签 c++ c windows arduino

我最近拿到了一个 Arduino (Uno),我想知道一些事情。

我的扬声器没有外部音量转换器,所以我想,也许可以将电位器连接到 Arduino,然后用它来控制音量(在 Windows 中)。但这可能吗?

要使用 Visual C、C++(或更多“多平台”语言)读取 Arduino 引脚的值?然后使用它来设置 Windows 中的音量级别(如果可能的话,也可以在 Linux 中)。

我认为这是可能的,因为如果你使用:

Serial.println(analogRead([pin with potentiometer]));

您可以将电位器的值传输到电脑(通过 USB)。那么有什么方法可以在 C 或 C++ 中读取这些值吗?

我知道如何通过 C 或 C++ 在 Windows 中设置音量,我只需要知道是否有办法在(可视)C 或 C++ 脚本中读取电位计的值。

最佳答案

当然。并使用完全相同的方法:串行通信。由于我不是出色的 Windows 专家,我无法为您写一个完整的 Windows 示例,但这里有一些片段可以帮助您在 Unix(Linux、OS X 等)上入门:

Arduino 上的代码:

#define POT_PIN 1

void setup()
{
    Serial.begin(9600); // 9600 baud is more than enough
}

void loop()
{
    int pot = analogRead(POT_PIN);
    unsigned char byte = (pot + 2) >> 2; // round and divide by 4
    Serial.write(pot);
    delay(100); // or do something useful
}

计算机上的代码:

#include <termios.h>

struct termios tio;
memset(&tio, 0, sizeof(tio));

// Open serial port in mode `8N1', non-blocking
tio.c_cflag = CS8 | CREAD | CLOCAL;
tio.c_cc[VMIN] = 1;
tio.c_cc[VTIME] = 5;

int fd = open(device, O_RDONLY);

cfsetospeed(&tio, B9600);
cfsetispeed(&tio, B9600);
tcsetattr(fd, TCSANOW, &tio);

while (1) {
    unsigned char byte;
    read(fd, &byte, 1);
    use_some_library_to_set_volume(byte);
}

关于c++ - 使用 Arduino 信号作为 PC 的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15806552/

相关文章:

c++ - 使用atoi将字符数组转换为int给出了不同的值

c++ - 函数内的 STL 容器何时将其数据保存在 C++ 中?

c - 使用 Unix 系统调用插入文本

c++ - 如何从一个函数返回多个类型?

java - Linux 中的 SMTP/POP3 客户端

c - 从内存中读取 6 个字节的更优雅的方法

c - 如何在 C 中将 int 打印为二进制?

android - 如何在 Windows 上运行 React Native 官方示例的 packager?

c# - C# 中的扩展方法 - 这是否正确?

java - 如何创建 .exe 包装器来安装 Java 应用程序