Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
const leftReverseOffset = 60;
const rightReverseOffset = 30;
window.onload = function(){
if (window.DeviceMotionEvent == undefined) {
//No accelerometer is present. Use buttons.
alert("no accelerometer");
}
else {
// alert("accelerometer found");
window.addEventListener("deviceorientation", accelerometerUpdate);
}
document.getElementById("xtilt").value = "Waiting input";
document.getElementById("ytilt").value = "Waiting input";
document.getElementById("ztilt").value = "Waiting input";
}
function accelerometerUpdate(event) {
var x = event.beta; // In degree in the range [-180,180]
var y = event.gamma; // In degree in the range [-90,90]
var leftSpeed = 0;
var rightSpeed = 0;
//The following two lines are just to calculate a
// tilt. Not really needed.
//xPosition = Math.atan2(aY, aZ);
//yPosition = Math.atan2(aX, aZ);
document.getElementById("xtilt").value = x;
document.getElementById("ytilt").value = y;
leftSpeed = Math.floor(Math.abs(y)*5);
rightSpeed = Math.floor(Math.abs(y)*5);
if (x<0) {
// käännytään oikealle
leftSpeed += Math.abs(x);
rightSpeed -= Math.abs(x);
}
else if (x>0) {
// käännytään vasemmalle
rightSpeed += Math.abs(x);
leftSpeed -= Math.abs(x);
}
// var speed = Math.floor(y*5);
document.getElementById("lspeed").value = leftSpeed;
document.getElementById("rspeed").value = rightSpeed;
if(y>0){
//mennään eteenpäin, vasen moottori pyörii taaksepäin
leftSpeed=-(leftSpeed+leftReverseOffset);
}
else if (y<0) {
// mennään taaksepäin, oikeamoottori pyörii taaksepän
rightSpeed=-(rightSpeed+rightReverseOffset);
}
$.get("http:\/\/192.168.0.190:8080/oikea/"+rightSpeed);
$.get("http:\/\/192.168.0.190:8080/vasen/"+leftSpeed);
}
</script>
</head>
<body>
X-tilt: <input type="text" id="xtilt"><br>
Y-tilt: <input type="text" id="ytilt"><br>
Z-tilt: <input type="text" id="ztilt"><br>
Left speed: <input type="text" id="lspeed"> right speed: <input type="text" id="rspeed">
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment