1
我試圖通過Ardiuno Uno與pc java控制小型直流電機。這個Java應用程序是服務器應用程序,並使用套接字連接到android應用程它只是處理來自java的單個命令。但不能連續按下。當我連續按下按鈕並停止按下時,我想旋轉電機。請幫幫我。對不起,我英語不好。在ar中使用觸發事件控制直流電機
這裏是Android代碼。 /連續按/
class RepetitiveUpdater implements Runnable {
@Override
public void run() {
if (autoIncrement) {
increment();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
} else if (autoDecrement) {
decrement();
repeatUpdateHandler.postDelayed(new RepetitiveUpdater(), REPEAT_DELAY);
}
}
}
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
increment();
}
});
btn.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
autoIncrement = true;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
btn1.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
autoDecrement = true;
repeatUpdateHandler.post(new RepetitiveUpdater());
return false;
}
});
這裏是java服務器。
private void sendMsgToPort(int k) {
try {
String s = String.valueOf(k);
char buf2[] = s.toCharArray();
serialPort.writeByte((byte) buf2[0]);
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
// ........
while (true) {
try {
clientSocket = serverSocket.accept(); // accept the client connection
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader); // get the client message
message = bufferedReader.read();
sendMsgToPort(message);
System.out.println("m=:" + message);
// System.out.println("Serial : "+serialPort.readString());
//inputStreamReader.close();
// clientSocket.close();
//System.out.println(serialPort.readBytes());
//Thread.sleep(100);
} catch (IOException ex) {
// status.setText("Error: " + ex);
System.out.println("Problem in message reading");
}
}
這裏是ardiuno示例代碼:
int val = 0;
int led = 8;
void setup()
{
Serial.begin(9600);
pinMode(led, OUTPUT);
}
void loop()
{
delay(100);
}
void serialEvent() // To check if there is any data on the Serial line
{
if (Serial.available())
{
val = Serial.parseInt();
if(val == 1) //Switch on the LED, if the received value is 1.
{
digitalWrite(led, HIGH);
}
}
}
`
謝謝您的建議。我會嘗試JimmyB –