使用串口控制LED [英] Controlling LED using serial port

查看:30
本文介绍了使用串口控制LED的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个简单的自动化项目的一部分,我试图通过串行端口控制一些 LED.我无法使以下代码工作

As part of a simple Automation project, I was trying to control some LEDs through serial port. I cannot make the following code working

int pin =0;
int state = 0;

void setup() {
    Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {
    // send data only when you receive data:
    if (Serial.available() > 0) {
        // read the incoming byte:
        if(Serial.read() == 'S' && Serial.read() == 'S') {
            // Command to set the pin
            pin  = Serial.read() - 65;
            state = Serial.read() - '0';
            Serial.print("Set State Command received");
            // Set the Pin
            pinMode(pin, OUTPUT);          
            digitalWrite(pin, state == 0? LOW:HIGH);
        }
    }
}

我正在将SSN1"从我的 python 程序发送到 Arduino 串行端口进行测试,但没有任何反应(我在引脚 13 上连接了一个 LED)

I am sending "SSN1" from my python program to the Arduino serial port for testing, and nothing happens (I have an LED connected on pin 13)

SS -  Set State Command
N  - (pin no) + 'A'  - Pin number 13
1  - State ( 0 = LOW, 1= HIGH)

推荐答案

我改进了我的代码,看起来像这样

I improved my code as it look like this

int pin =0;
int state = 0;

void setup() {
        Serial.begin(9600);     // opens serial port, sets data rate to 9600 bps
}

void loop() {

        // send data only when you receive data:
        if (Serial.available() > 3) { // I am using chunk of 4 characters/bytes as a command 
                // read the incoming byte:
                if(Serial.read() == 'S' && Serial.read() == 'S') {
                  // Command to set the pin
                  pin  = Serial.read() - 65;
                  state = Serial.read() - '0';
                  Serial.print("Set State Command received");
                  // Set the Pin
                  pinMode(pin, OUTPUT);          
                  digitalWrite(pin, state == 0? LOW:HIGH);
                }
                delay(50); 
        }
}

它非常适合我.由于循环频率高,Arduino 无法获取连续读取的字节.所以我们正在等待 4 个字节在缓冲区中累积以读取那些(Arduino 的串行缓冲区是 64 个字节).

It works perfectly for me. Due to the high frequency of looping, Arduino was not able pickup the bytes for consecutive read. So we are waiting for 4 bytes to accumulate in the buffer to read those (Arduino's serial buffer is 64 bytes).

这篇关于使用串口控制LED的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆