JavaScript Switch Case没有按预期工作

时间:2015-04-13 00:20:02

标签: javascript switch-statement case

我是JavaScript的初学者,所以这可能是一个业余的错误。出于某种原因,当我在js.node中运行此代码时,我总是得到默认情况。传入的数据显示到控制台就好了,所以我假设变量latestData实际上存储了传入的数据。每种情况下的console.log都是为了让我知道它正在使用哪种情况。

感谢任何帮助!

编辑:代码修改如下所示,但我仍然有同样的问题 如果有帮助的话,我今天回家后会分享arduino程序和串口显示器的截图。

var arDrone = require('ar-drone'); //Include the ar-drone library
var serialport = require('node-serialport'); //Include the serialport Library
var latestData = 0;

SerialPort = serialport.SerialPort, //Create local Instance

//Define the port and function to call
myPort = new SerialPort("/dev/ttyO3", {
    parser: serialport.parsers.readline("\r\n"), //Look for return and newline at the end of each packet. Serial.println() adds this
    baud: 9600
});

//Define what functions are called on each event
myPort.on('data', saveLatestData);
myPort.on('close', showPortClose);
myPort.on('error', showError);
myPort.on('open', showPortOpen);

//Callback functions for serial data events
function showPortOpen() {
   console.log('PORT OPEN');
}

function saveLatestData(data) {
   console.log(data);
   latestData = data;
}

function showPortClose() {
   console.log('PORT CLOSED');
}

function showError(error) {
   console.log('SERIAL PORT ERROR ' + error);
}


var client = arDrone.createClient();

//client.takeoff();  //Drone take off command, functional but removed for bench test

// Logic to read in sensor data from arduino and send flight commands to drone
switch(String.fromCharCode(latestData))
{
case 'X':
console.log('X IR');
client
    .after(1000, function() {
    this.clockwise(0.1);
  })
        .after(1000, function() {
        this.front(0.05);
  });
break;


case 'Y':
console.log('Y IR');
client
    .after(1000, function() {
    this.counterClockwise(0.1);
  })

       .after(1000, function() {
       this.front(0.05)
       });
break;

case 'Z':
console.log('Z IR');
client
    .after(1000, function() {
    this.back(0.05);
  })
        .after(1000, function() {
        this.clockwise(0.1)
    });
break;

case 'A':
console.log('A IR');
client
    .after(1000, function() {
    this.back(0.05);
  })
        .after(1000, function() {
        this.clockwise(0.1)
    });
break;

case 'N':
console.log('N IR');
client
    .after(1000, function() {
    this.front(0.05);
  }); 
break;

case 'L':
console.log('L IR');
client
    .after(1000, function() {
    this.clockwise(0.1);
  })
        .after(1000, function() {
        this.front(0.05);
  });
break;

case 'R':
console.log('R IR');
client
    .after(1000, function() {
    this.counterClockwise(0.1);
  })

       .after(1000, function() {
       this.front(0.05)
       });
break;

default:
console.log('DEFAULT CASE');
client
    .after(1000, function() {
    this.front(0.05)
  });
break;
}

这是将串行数据发送到js.node正在读取的端口的arduino代码。非常简单

/*
description:
The sample code is used to measure distance by GP2Y0A02YK IR ranger sensor.
The information is then sent serially to Ar.Drone serial port tty03
VCC -- VCC
GND -- GND
Signal -- Analog 1
*/

/*int IRpinX = 1; // analog pin for reading the X IR sensor
int IRpinY = 3;  // analog pin for reading the Y IR sensor
int IRpinZ = 5;  // analog pin for reading the Z IR sensor
*/

bool X;  // set high when X IR sensor detects obstacle
bool Y;  // set high when Y IR sensor detects obstacle
bool Z;  // set high when Z IR sensor detects obstacle


void setup()
{
Serial.begin(9600); // start the serial port

//SET ANALOG PINS TO BE USED FOR IR SENSOR INPUT
pinMode(A1, INPUT); // X SENSOR
pinMode(A3, INPUT); // Y SENSOR
pinMode(A5, INPUT); // Z SENSOR


}
void loop()
{
float voltsX = analogRead(A1)*0.0048828125; // value from sensor (5/1024) - if running 3.3.volts then change 5 to 3.3
float voltsY = analogRead(A3)*0.0048828125;
float voltsZ = analogRead(A5)*0.0048828125;
float distanceX = 65*pow(voltsX, -1.10); // worked out from graph 65 = theretical distance / (1/volts);
float distanceY = 65*pow(voltsY, -1.10);
float distanceZ = 65*pow(voltsZ, -1.10);

/*print the distances for each sensor to verify in the serial monitor
Used for initial testing
Serial.print("X = ");
Serial.println(voltsX);
Serial.print("Y = ");
Serial.println(voltsY);
Serial.print("Z = ");
Serial.println(voltsZ);*/

/*statements compare distance calculation to a static range and 
set a bit high for each sensor that detects an obstacle
May change to compare voltage as it seemed more stable*/ 

if (distanceX <=100) // check for obstacle in X direction
{
  X = HIGH;
}
else X = LOW;

if (distanceY <=100) // check for obstacle in Y direction
{
  Y = HIGH;
}
else Y = LOW;

if (distanceZ <=100) // check for obstacle in Z direction
{
  Z = HIGH;
}
else Z = LOW;

// Obstacle detected at X sensor only
if (X == HIGH && Y == LOW && Z == LOW)
{
Serial.println('X'); // Transmit character X in hex over serial port
}

// Obstacle detected at Y sensor only
if (X == LOW && Y == HIGH && Z == LOW)
{
Serial.println('Y'); // Transmit character Y in hex over serial port
}

// Obstacle detected at Z sensor only
if (X == LOW && Y == LOW && Z == HIGH)
{
Serial.println('Z'); // Transmit character Z in hex over serial port
}

// Obstacle detected at X and Y sensors only
if (X == HIGH && Y == HIGH && Z == LOW)
{
Serial.println('Z'); // Transmit character Z in hex over serial port
}                    // Not sure what to do in this condition. Turn instead?

// Obstacle detected at X and Z sensors only
if (X == HIGH && Y == LOW && Z == HIGH)
{
Serial.println('R'); // Transmit character R in hex over serial port
}                    // Rotate drone clockwise

// Obstacle detected at Y and Z sensors only
if (X == LOW && Y == HIGH && Z == HIGH)
{
Serial.println('L'); // Transmit character L in hex over serial port
}                    // Rotate drone counterclockwise

// Obstacle detected at X, Y and Z sensors
if (X == HIGH && Y == HIGH && Z == HIGH)
{
Serial.println('A'); // Transmit character L in hex over serial port
}                    // Rotate drone counterclockwise

// No Obstacle Detected
if (X == LOW && Y == LOW && Z == LOW)
{
Serial.println('N'); // Transmit character N over serial port
}                    // Hover in place


delay(100); // wait time in mS used to slow data send interval for testing

} 

2 个答案:

答案 0 :(得分:2)

您始终获得default,因为您没有任何break语句。如果你不包含break,代码将执行它下面的所有其他情况。

case 'X':
    console.log('X IR');
    client
        .after(1000, function() {
            this.clockwise(0.1);
        })
        .after(1000, function() {
            this.front(0.05);
        });
    break; //You are missing this on every case

其他问题是代码是内联JavaScript,它只是在加载JavaScript时才会运行,并且将会读取var latestData = 0;的默认值并且将达到默认情况。您需要在某种功能中设置它并触发它。

答案 1 :(得分:0)

我怀疑latestData包含整数代码。但JavaScript中的'A'是一个字符串文字。这就是为什么你的案例不起作用,JS中的65 != 'A'。您应该使用String.fromCharCode(int)将字符代码转换为字符串:

switch(String.fromCharCode(latestData)) {
  case 'A': ...; break;
  case 'B': ...; break;
}