Created
September 3, 2019 20:19
-
-
Save jabrena/65f75c7adc52f5f66edb6d114a9e703a to your computer and use it in GitHub Desktop.
Modern syntax for Robots with Java 8+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package example; | |
import ev3dev.actuators.lego.motors.EV3LargeRegulatedMotor; | |
import java.util.Arrays; | |
import java.util.List; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutorService; | |
import java.util.concurrent.Executors; | |
import java.util.function.Consumer; | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
import lejos.hardware.port.MotorPort; | |
import lejos.robotics.RegulatedMotor; | |
import lejos.utility.Delay; | |
import lombok.extern.slf4j.Slf4j; | |
@Slf4j | |
public class MotorEncoderTest { | |
Consumer<RegulatedMotor> readMotor = motor -> { | |
IntStream.rangeClosed(1,50).boxed() | |
.forEach(i -> { | |
LOGGER.info("{} {}", i , motor.getTachoCount()); | |
Delay.msDelay(200); | |
}); | |
}; | |
Consumer<RegulatedMotor> writeMotor = motor -> { | |
IntStream.rangeClosed(1, 2).boxed() | |
.forEach(i -> { | |
LOGGER.info("FORWARD"); | |
motor.forward(); | |
Delay.msDelay(2000); | |
LOGGER.info("BACKWARD"); | |
motor.backward(); | |
Delay.msDelay(2000); | |
}); | |
}; | |
Consumer<RegulatedMotor> processTasks = motor -> { | |
final ExecutorService executor = Executors.newFixedThreadPool(2); | |
List<CompletableFuture<Void>> motorTasks = Arrays.asList( | |
CompletableFuture.runAsync(() -> this.readMotor.accept(motor), executor), | |
CompletableFuture.runAsync(() -> this.writeMotor.accept(motor), executor)).stream() | |
.collect(Collectors.toList()); | |
motorTasks.stream().forEach(CompletableFuture::join); | |
executor.shutdown(); | |
motor.stop(); | |
LOGGER.info("End"); | |
}; | |
public static void main(String[] args) throws Exception{ | |
LOGGER.info("MotorEncoderTest"); | |
MotorEncoderTest example = new MotorEncoderTest(); | |
example.processTasks.accept(new EV3LargeRegulatedMotor(MotorPort.A)); | |
System.exit(0); | |
} | |
} |
Author
jabrena
commented
Sep 3, 2019
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment