首页 > 解决方案 > 如何通过串行向arduino发送数字?

问题描述

我正在尝试通过串行向 Arduino 发送一个数值来控制可单独寻址的 LEDstrip。使用 Arduino IDE“串行监视器”,我可以毫无问题地向灯条发送一个数字。但是,当我尝试通过在处理过程中从文本文件中读取来从外部执行它时,它不会通过。

经过一些调试后,我可以看到 Processing 具有正确的数字并将其存储在变量中。然而,灯头只会在 LED 上亮起,而不是给定的数字。

处理代码:

import processing.serial.*;
import java.io.*;


Serial myPort;  // Create object from Serial class

void setup() 
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  myPort = new Serial(this, portName, 9600);
}
void draw() 
{
  while(true) {
  // Read data from the file
  {
    String[] lines = loadStrings("Lifenumber.txt");
    int number = Integer.parseInt(lines[0]);
    println(number);
    myPort.write(number);
    delay(5000);
  }
  }
}

Arduino代码:

if ( Serial.available()) // Check to see if at least one character is available
  {
    char ch = Serial.read();
      if(index <  3 && ch >= '0' && ch <= '9'){
      strValue[index++] = ch; 
      }
      else
      {
        Lnum = atoi(strValue);
        Serial.println(Lnum);
        for(i = 0; i < 144; i++)
        {
          leds[i] = CRGB::Black; 
          FastLED.show(); 
          delay(1);

        }
        re = 1;
        index = 0;
        strValue[index] = 0; 
        strValue[index+1] = 0; 
        strValue[index+2] = 0; 
    }
  }

我想让程序做的是从文本文件中读取一个数字,然后点亮 144led 灯条上的那个数量的 LED。

标签: arduinoserial-portprocessing

解决方案


以下是对您的代码的一些评论,它们应该有助于将来进行改进。尽早养成良好的编码习惯很重要:它会让你的生活变得更加轻松(我说的是一个从 flash 开始的自学成才的程序员,所以我知道什么是混乱和 hacky ;))

import processing.serial.*;
//import java.io.*; // don't include unused imports


Serial myPort;  // Create object from Serial class

void setup() 
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  // handle error initialising Serial
  try{
    myPort = new Serial(this, portName, 9600);
  }catch(Exception e){
    println("Error initializing Serial port " + portName);
    e.printStackTrace();
  }
}
void draw() 
{
  // don't use blocking while, draw() already gets called continuously
  //while(true) {
  // Read data from the file
  //{
    // don't load the file over and over again
    String[] lines = loadStrings("Lifenumber.txt");
    int number = Integer.parseInt(lines[0]);// int(lines[0]) works in Processing, but the Java approach is ok too
    println("parsed number: " + number);
    if(myPort != null){
      myPort.write(number);
    }
    // don't use blocking delays, ideally not even in Arduino
    //delay(5000);
  //}
  //}
}

这是加载文本文件的处理代码版本,解析整数然后仅将其发送到串行一次(如果一切正常,否则基本错误检查应该显示调试友好信息):

import processing.serial.*;
Serial myPort;  // Create object from Serial class

void setup() 
{
  size(200,200); //make our canvas 200 x 200 pixels big
  String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
  // handle error initialising Serial
  try{
    myPort = new Serial(this, portName, 9600);
  }catch(Exception e){
    println("Error initializing Serial port " + portName);
    e.printStackTrace();
  }
  // Read data from the file
  try{
    String[] lines = loadStrings("Lifenumber.txt");
    int number = Integer.parseInt(lines[0]);
    println("parsed number: " + number);
    // validate the data, just in case something went wrong
    if(number < 0 && number > 255){
      println("invalid number: " + number + ", expecting 0-255 byte sized values only");
      return;
    }
    if(myPort != null){
      myPort.write(number);
    }
  }catch(Exception e){
    println("Error loading text file");
    e.printStackTrace();
  }
}
void draw() 
{
  // display the latest value if you want
}

// add a keyboard shortcut to reload if you need to

您的灯条有 144 个 LED(少于 255 个),非常适合单个字节,这就是处理草图发送的内容

在 Arduino 方面,没有什么太疯狂的事情发生,所以只要您验证输入的数据应该没问题:

#include "FastLED.h"

#define NUM_LEDS 64 
#define DATA_PIN 7
#define CLOCK_PIN 13

// Define the array of leds
CRGB leds[NUM_LEDS];

int numLEDsLit = 0;

void setup() {
  Serial.begin(9600);
  Serial.println("resetting");
  LEDS.addLeds<WS2812,DATA_PIN,RGB>(leds,NUM_LEDS);
  LEDS.setBrightness(84);
}

void loop() {
  updateSerial();
  updateLEDs();
}

void updateSerial(){
  // if there's at least one byte to read
  if( Serial.available() > 0 )
  {
    // read it and assign it to the number of LEDs to light up
    numLEDsLit = Serial.read();
    // constrain to a valid range (just in case something goes funny and we get a -1, etc.)
    numLEDsLit = constrain(numLEDsLit,0,NUM_LEDS);
  }  
}

// uses blacking delay
void updateLEDs(){
  // for each LED
  for(int i = 0; i < 144; i++)
  {
    // light up only the number of LEDs received via Serial, turn the LEDs off otherwise
    if(i < numLEDsLit){
      leds[i] = CRGB::White;
    }else{
      leds[i] = CRGB::Black;
    }
    FastLED.show(); 
    delay(1);  
  }
}

调整引脚/LED芯片组/等。根据您的实际物理设置。


推荐阅读