当斜边进入一定范围时,我试图让我的LED闪烁。但似乎正在通过斜边范围的值超过它应该的范围。 LED在恢复正常之前闪烁约30-40次。不知道如何解决这个问题。
这是我的处理代码:
import processing.serial.*;
float r_height; // rise of the slope
float r_width; // run of the slope
float hypotnuse; // hypotenuse of the right angle
int d = 20; // diameter of the chocolate
float x ; // x of the chocolate destination
float y ; // y of the chocolate destination
int ledGlow; // how much the LED will glow
Serial myPort; // serial port object
void setup () {
size (510, 510); // size of the canvas
String portName = Serial.list()[8]; // my arduino port
myPort = new Serial(this, portName, 9600);
background (0); // color of the background
fill(204); // fill of the ellipse
ellipseMode (CORNER); //Ellipse mode
x = 0; //The placement on initial X for chocolate
y = 0; // the placement on initial Y for chocolate
ellipse (x, y, d, d); // ellipse
frameRate (30);
}
void draw () {
r_height = mouseY - y; // rise
r_width = mouseX - x; //run
hypotnuse = sqrt (( (sq(r_height)) + (sq (r_width)))); //A^2 +B^2 = C^2
ledGlow = 255 - (round (hypotnuse/2.84)); // flipping the values
myPort.write(ledGlow); // The value being sent to the Arduino
println (ledGlow);
}
这是arduino代码:
float val; // Data received from the serial port
int ledPin = 9;
void setup() {
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
if (Serial.available())
{ // If data is available to read,
val = Serial.read(); // read it and store it in val
// long steps2move = val.toInt();
}
if (val > 230) {
analogWrite (ledPin, 255) ; // I have already tried digitalWrite
delay (100);
analogWrite (ledPin, 1) ;
delay (100);
}
else if (val < 230) {
analogWrite(ledPin, val);
}
}
更新ARDUINO:
float val; // Data received from the serial port
int ledPin = 9; // Set the pin to digital I/O 13
unsigned long currentTime = 0;
unsigned long pastTime = 0;
int currentState = 0;
int wait = 0;
void setup() {
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
if (Serial.available())
{ // If data is available to read,
val = Serial.read(); // read it and store it in val
// long steps2move = val.toInt();
}
if (val > 230) {
pastTime = currentTime;
currentTime = millis();
unsigned long timePassed = currentTime - pastTime;
if(timePassed >= wait)
{
switch(currentState )
{
case 0:
digitalWrite(9, HIGH);
wait = 500;
currentState = 1;
break;
case 1:
digitalWrite(9, LOW);
wait = 500;
currentState = 0;
break;
}
}
}
else if (val < 230) {
analogWrite(ledPin, val/2);
}
}
答案 0 :(得分:2)
处理代码可能是不断写入串行的。但是,当斜边进入您设置的范围时,Arduino会进行delay()
次调用。我认为这将导致它落后,因此它会一直闪烁,同时它会清除延迟期间出现的串行数据积压。
我认为更好的方法是避免使用delay()
,因此Arduino可以尽快处理串行数据。在每个循环中,它应该首先获取最新的串行数据(如果有的话)。基于此,它应该找出并存储LED当前应该做什么(即它应该闪烁,还是它应该是什么亮度)。
之后(无论是否实际接收到任何串行数据),LED都可以从存储状态更新。切记不要使用delay()
进行闪烁。相反,您可以跟踪它上次闪烁的时间,并确定自那时起是否已经过了100毫秒(使用millis()
)。如果是这样,请将其关闭。如果再过100毫秒,请重新打开。
这种方法将闪存时序与串行数据分离,因此希望它能更好地工作。