code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruitspi.sensor.main.SampleBMP183Main
12nosanshiro-pi4j-sample
AdafruitI2C/bmp183
Shell
mit
120
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.samples.Servo001
12nosanshiro-pi4j-sample
AdafruitI2C/servo.001
Shell
mit
109
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:../RasPISamples/classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.main.SampleTCS34725PWMMain $*
12nosanshiro-pi4j-sample
AdafruitI2C/tcs34725.pwm
Shell
mit
226
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.main.SampleL3GD20ReadRealData
12nosanshiro-pi4j-sample
AdafruitI2C/l3gd20.2
Shell
mit
128
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.main.VCNL4000ProximityWithSound
12nosanshiro-pi4j-sample
AdafruitI2C/vcnl4000.sound
Shell
mit
130
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.samples.Servo002
12nosanshiro-pi4j-sample
AdafruitI2C/servo.002
Shell
mit
109
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.gui.acc.AccelerometerUI
12nosanshiro-pi4j-sample
AdafruitI2C/lsm303.gui
Shell
mit
115
#!/bin/bash JAVAC_OPTIONS="-sourcepath ./src" JAVAC_OPTIONS="$JAVAC_OPTIONS -d ./classes" echo $JAVAC_OPTIONS CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:../GPSandSun/lib/nmeaparser.jar CP=$CP:./libs/orasocket-client-12.1.3.jar CP=$CP:./libs/json.jar # JAVAC_OPTIONS="-verbose $JAVAC_OPTIONS" JAVAC_OPTIONS="$JAVAC_OPTIONS -cp $CP" COMMAND="javac $JAVAC_OPTIONS `find ./src -name '*.java' -print`" echo Compiling: $COMMAND $COMMAND echo Done
12nosanshiro-pi4j-sample
AdafruitI2C/compile
Shell
mit
455
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:../../olivsoft/all-libs/nmeaparser.jar sudo java -cp $CP adafruiti2c.sensor.main.SampleBMP180Main
12nosanshiro-pi4j-sample
AdafruitI2C/new.nmea.reader
Shell
mit
166
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.main.SampleL3GD20ReadRawlData
12nosanshiro-pi4j-sample
AdafruitI2C/l3gd20
Shell
mit
128
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./libs/json.jar CP=$CP:./libs/orasocket-client-12.1.3.jar sudo java -cp $CP adafruiti2c.samples.ws.WebSocketListener
12nosanshiro-pi4j-sample
AdafruitI2C/ws.servo
Shell
mit
185
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.samples.Servo003
12nosanshiro-pi4j-sample
AdafruitI2C/servo.003
Shell
mit
109
"use strict"; var connection; (function () { // if user is running mozilla then use it's built-in WebSocket // window.WebSocket = window.WebSocket || window.MozWebSocket; // TODO otherwise, fall back var ws = window.WebSocket || window.MozWebSocket; // TODO otherwise, fall back // if browser doesn't support WebSocket, just show some notification and exit // if (!window.WebSocket) if (!ws) { displayMessage('Sorry, but your browser does not support WebSockets.'); // TODO Fallback return; } // open connection var rootUri = "ws://" + (document.location.hostname === "" ? "localhost" : document.location.hostname) + ":" + (document.location.port === "" ? "8080" : document.location.port); console.log(rootUri); connection = new WebSocket(rootUri); // 'ws://localhost:9876'); connection.onopen = function () { displayMessage('Connected.') }; connection.onerror = function (error) { // just in there were some problems with connection... displayMessage('Sorry, but there is some problem with your connection or the server is down.'); }; connection.onmessage = function (message) { console.log('onmessage:' + JSON.stringify(message.data)); var data = JSON.parse(message.data); var value = data.data.text.replace(/&quot;/g, '"'); var val = JSON.parse(value); displayValue.setValue(val.value); }; /** * This method is optional. If the server wasn't able to respond to the * in 3 seconds then show some error message to notify the user that * something is wrong. */ setInterval(function() { if (connection.readyState !== 1) { displayMessage('Unable to communicate with the WebSocket server. Try again.'); } }, 3000); // Ping })(); var sendMessage = function(msg) { console.log("Sending:" + msg); if (!msg) { return; } // send the message as an ordinary text connection.send(msg); }; var displayMessage = function(mess) { try { var messList = statusFld.innerHTML; messList = (((messList !== undefined && messList.length) > 0 ? messList + '<br>' : '') + mess); statusFld.innerHTML = messList; } catch (err) { console.log(mess); } }; var resetStatus = function() { statusFld.innerHTML = ""; };
12nosanshiro-pi4j-sample
AdafruitI2C/node/client.js
JavaScript
mit
2,304
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>PWM / WebSockets</title> <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" /> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script type="text/javascript" src="widgets/AnalogDisplay.js"></script> <style> * { font-family:tahoma; font-size:12px; padding:0px; margin:0px; } p { line-height:18px; } </style> <script type="text/javascript"> /** * Warning: there is a first HTTP HandShake going on, that must follow the orasocket.js protocol. * See the request header: * "tyrus-ws-attempt" = "Hand-Shake" * * Response headers will contain: * "tyrus-fallback-transports" * "tyrus-connection-id" * * FYI, tyrus is the name of the RI for JSR356. */ var response = {}; var displayValue; var statusFld; window.onload = function() { statusFld = document.getElementById("status"); displayValue = new AnalogDisplay('valueCanvas', 100, 90, 10, 1, false, 0, -90); displayValue.setValue(0); var setSliderTicks = function(el) { var $slider = $(el); var max = $slider.slider("option", "max"); var min = $slider.slider("option", "min"); var spacing = 100 / (max - min); $slider.find('.ui-slider-tick-mark').remove(); for (var i=0; i<=(max-min); i++) { $('<span class="ui-slider-tick-mark"></span>').css('left', (spacing * i) + '%').appendTo($slider); } }; var tooltip = $('<div id="tooltip" style="background:rgba(238, 234, 118, 0.5); font-size:small;" />').css( { position: 'absolute', top: -25, left: -10 }).hide(); $(function() { $( "#a-value-slider" ).slider({ min: -90, max: 90, value: 0, step: 1, animate: "slow", create: function(event, ui) { setSliderTicks(event.target); }, slide: function(event, ui) { tooltip.text(ui.value); displayValue.animate(ui.value); // Feed the server here with the new value var payload = { value: ui.value }; sendMessage(JSON.stringify(payload)); }, }).find(".ui-slider-handle").append(tooltip).hover(function() { tooltip.show(); }, function() { tooltip.hide(); }); }); console.log("Sending first (POST) request..."); var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { response = JSON.parse(xhr.responseText); console.log(response); var headers = xhr.getAllResponseHeaders(); console.log("All headers:\n" + headers); var supportedTransports = xhr.getResponseHeader("tyrus-fallback-transports"); console.log("Transports:" + supportedTransports); var transports = supportedTransports.split(","); var preferredProtocol = ""; for (var i=0; i<transports.length; i++) { console.log("Transport : " + transports[i] + " " + (transports[i] in window ? "": "NOT ") + "supported."); if (transports[i] in window) { preferredProtocol = transports[i]; break; } } if (preferredProtocol.length === 0) console.log("No protocol can be used..."); else console.log("Preferred Protocol is " + preferredProtocol); var clientID = xhr.getResponseHeader("tyrus-connection-id"); console.log("Client ID:" + clientID); } }; xhr.open("POST", "/", true); xhr.setRequestHeader("tyrus-ws-attempt", "Hand-Shake"); // Means return the transport list, and my unique ID xhr.send(); }; </script> <style type="text/css"> .ui-slider-tick-mark { display: inline-block; width: 1px; background:lightgray; height: 16px; position: absolute; top: -4px; } </style> </head> <body> <table width="100%"> <tr> <td valign="top"><h2>PWM on WebSocket</h2></td> </tr> <tr> <td align="left"> <div id="status" style="padding:5px; background:#ddd; border-radius:5px; overflow-y: scroll; border:1px solid #CCC; margin-top:10px; height: 80px;"> <!--i>Status will go here when needed...</i--> </div> </td> </tr> <tr> <td valign="top" align="right"><a href="" onclick="javascript:resetStatus(); return false;" title="Clear status board"><small>Reset Status</small></a></td> </tr> <tr> <td align="center" valign="top"> <canvas id="valueCanvas" width="240" height="140" title="Servo angle"></canvas> <br> <!-- The slider --> <div id="a-value-slider" style="width:500px;"></div> </td> </tr> </table> <br><br> <hr> <address>Oliv did it</address> <script src="./client.js"></script> </body> </html>
12nosanshiro-pi4j-sample
AdafruitI2C/node/display.html
HTML
mit
7,069
/* * @author Olivier Le Diouris */ // TODO This config in CSS // We wait for the var- custom properties to be implemented in CSS... // @see http://www.w3.org/TR/css-variables-1/ /* * For now: * Themes are applied based on a css class: * .display-scheme * { * color: black; * } * * if color is black, analogDisplayColorConfigBlack is applied * if color is white, analogDisplayColorConfigWhite is applied, etc */ var analogDisplayColorConfigWhite = { bgColor: 'white', digitColor: 'black', withGradient: true, displayBackgroundGradient: { from: 'LightGrey', to: 'white' }, withDisplayShadow: true, shadowColor: 'rgba(0, 0, 0, 0.75)', outlineColor: 'DarkGrey', majorTickColor: 'black', minorTickColor: 'black', valueColor: 'grey', valueOutlineColor: 'black', valueNbDecimal: 0, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'black', withHandShadow: true, knobColor: 'DarkGrey', knobOutlineColor: 'black', font: 'Arial' /* 'Source Code Pro' */ }; var analogDisplayColorConfigBlack = { bgColor: 'black', digitColor: 'LightBlue', withGradient: true, displayBackgroundGradient: { from: 'black', to: 'LightGrey' }, shadowColor: 'black', outlineColor: 'DarkGrey', majorTickColor: 'LightGreen', minorTickColor: 'LightGreen', valueColor: 'LightGreen', valueOutlineColor: 'black', valueNbDecimal: 1, handColor: 'rgba(0, 0, 100, 0.25)', handOutlineColor: 'blue', withHandShadow: true, knobColor: '#8ED6FF', // Kind of blue knobOutlineColor: 'blue', font: 'Arial' }; var analogDisplayColorConfig = analogDisplayColorConfigWhite; // White is the default function AnalogDisplay(cName, // Canvas Name dSize, // Display radius maxValue, // default 10 majorTicks, // default 1 minorTicks, // default 0 withDigits, // default true, boolean overlapOver180InDegree, // default 0, beyond horizontal, in degrees, before 0, after 180 startValue) // default 0, In case it is not 0 { if (maxValue === undefined) maxValue = 10; if (majorTicks === undefined) majorTicks = 1; if (minorTicks === undefined) minorTicks = 0; if (withDigits === undefined) withDigits = true; if (overlapOver180InDegree === undefined) overlapOver180InDegree = 0; if (startValue === undefined) startValue = 0; var scale = dSize / 100; var canvasName = cName; var displaySize = dSize; var running = false; var previousValue = startValue; var intervalID; var valueToDisplay = 0; var incr = 1; var instance = this; //try { console.log('in the AnalogDisplay constructor for ' + cName + " (" + dSize + ")"); } catch (e) {} (function(){ drawDisplay(canvasName, displaySize, previousValue); })(); // Invoked automatically this.repaint = function() { drawDisplay(canvasName, displaySize, previousValue); }; this.setDisplaySize = function(ds) { scale = ds / 100; displaySize = ds; drawDisplay(canvasName, displaySize, previousValue); }; this.startStop = function (buttonName) { // console.log('StartStop requested on ' + buttonName); var button = document.getElementById(buttonName); running = !running; button.value = (running ? "Stop" : "Start"); if (running) this.animate(); else { window.clearInterval(intervalID); previousValue = valueToDisplay; } }; this.animate = function() { var value; if (arguments.length === 1) value = arguments[0]; else { // console.log("Generating random value"); value = maxValue * Math.random(); } value = Math.max(value, startValue); value = Math.min(value, maxValue); //console.log("Reaching Value :" + value + " from " + previousValue); diff = value - previousValue; valueToDisplay = previousValue; // console.log(canvasName + " going from " + previousValue + " to " + value); // if (diff > 0) // incr = 0.01 * maxValue; // else // incr = -0.01 * maxValue; incr = diff / 10; if (intervalID) window.clearInterval(intervalID); intervalID = window.setInterval(function () { displayAndIncrement(value); }, 10); }; var displayAndIncrement = function(finalValue) { //console.log('Tic ' + inc + ', ' + finalValue); drawDisplay(canvasName, displaySize, valueToDisplay); valueToDisplay += incr; if ((incr > 0 && valueToDisplay > finalValue) || (incr < 0 && valueToDisplay < finalValue)) { // console.log('Stop, ' + finalValue + ' reached, steps were ' + incr); window.clearInterval(intervalID); previousValue = finalValue; if (running) instance.animate(); else drawDisplay(canvasName, displaySize, finalValue); // Final display } }; function drawDisplay(displayCanvasName, displayRadius, displayValue) { var schemeColor; try { schemeColor = getCSSClass(".display-scheme"); } catch (err) { /* not there */ } if (schemeColor !== undefined && schemeColor !== null) { var styleElements = schemeColor.split(";"); for (var i=0; i<styleElements.length; i++) { var nv = styleElements[i].split(":"); if ("color" === nv[0]) { // console.log("Scheme Color:[" + nv[1].trim() + "]"); if (nv[1].trim() === 'black') analogDisplayColorConfig = analogDisplayColorConfigBlack; else if (nv[1].trim() === 'white') analogDisplayColorConfig = analogDisplayColorConfigWhite; } } } var digitColor = analogDisplayColorConfig.digitColor; var canvas = document.getElementById(displayCanvasName); var context = canvas.getContext('2d'); var radius = displayRadius; // Cleanup //context.fillStyle = "#ffffff"; context.fillStyle = analogDisplayColorConfig.bgColor; //context.fillStyle = "transparent"; context.fillRect(0, 0, canvas.width, canvas.height); //context.fillStyle = 'rgba(255, 255, 255, 0.0)'; //context.fillRect(0, 0, canvas.width, canvas.height); context.beginPath(); //context.arc(x, y, radius, startAngle, startAngle + Math.PI, antiClockwise); // context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree), (2 * Math.PI) + toRadians(overlapOver180InDegree), false); context.arc(canvas.width / 2, radius + 10, radius, Math.PI - toRadians(overlapOver180InDegree > 0?90:0), (2 * Math.PI) + toRadians(overlapOver180InDegree > 0?90:0), false); context.lineWidth = 5; if (analogDisplayColorConfig.withGradient) { var grd = context.createLinearGradient(0, 5, 0, radius); grd.addColorStop(0, analogDisplayColorConfig.displayBackgroundGradient.from);// 0 Beginning grd.addColorStop(1, analogDisplayColorConfig.displayBackgroundGradient.to); // 1 End context.fillStyle = grd; } else context.fillStyle = analogDisplayColorConfig.displayBackgroundGradient.to; if (analogDisplayColorConfig.withDisplayShadow) { context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; context.shadowColor = analogDisplayColorConfig.shadowColor; } context.lineJoin = "round"; context.fill(); context.strokeStyle = analogDisplayColorConfig.outlineColor; context.stroke(); context.closePath(); var totalAngle = (Math.PI + (2 * (toRadians(overlapOver180InDegree)))); // Major Ticks context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { var currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.85) * Math.cos(currentAngle)); yTo = (radius + 10) - ((radius * 0.85) * Math.sin(currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 3; context.strokeStyle = analogDisplayColorConfig.majorTickColor; context.stroke(); context.closePath(); // Minor Ticks if (minorTicks > 0) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=minorTicks) { var _currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); xFrom = (canvas.width / 2) - ((radius * 0.95) * Math.cos(_currentAngle)); yFrom = (radius + 10) - ((radius * 0.95) * Math.sin(_currentAngle)); xTo = (canvas.width / 2) - ((radius * 0.90) * Math.cos(_currentAngle)); yTo = (radius + 10) - ((radius * 0.90) * Math.sin(_currentAngle)); context.moveTo(xFrom, yFrom); context.lineTo(xTo, yTo); } context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.minorTickColor; context.stroke(); context.closePath(); } // Numbers if (withDigits) { context.beginPath(); for (i = 0;i <= (maxValue - startValue) ;i+=majorTicks) { context.save(); context.translate(canvas.width/2, (radius + 10)); // canvas.height); var __currentAngle = (totalAngle * (i / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // context.rotate((Math.PI * (i / maxValue)) - (Math.PI / 2)); context.rotate(__currentAngle - (Math.PI / 2)); context.font = "bold " + Math.round(scale * 15) + "px " + analogDisplayColorConfig.font; // Like "bold 15px Arial" context.fillStyle = digitColor; str = (i + startValue).toString(); len = context.measureText(str).width; context.fillText(str, - len / 2, (-(radius * .8) + 10)); context.restore(); } context.closePath(); } // Value text = displayValue.toFixed(analogDisplayColorConfig.valueNbDecimal); len = 0; context.font = "bold " + Math.round(scale * 40) + "px " + analogDisplayColorConfig.font; // "bold 40px Arial" var metrics = context.measureText(text); len = metrics.width; context.beginPath(); context.fillStyle = analogDisplayColorConfig.valueColor; context.fillText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.valueOutlineColor; context.strokeText(text, (canvas.width / 2) - (len / 2), ((radius * .75) + 10)); // Outlined context.closePath(); // Hand context.beginPath(); if (analogDisplayColorConfig.withHandShadow) { context.shadowColor = analogDisplayColorConfig.shadowColor; context.shadowOffsetX = 3; context.shadowOffsetY = 3; context.shadowBlur = 3; } // Center context.moveTo(canvas.width / 2, radius + 10); var ___currentAngle = (totalAngle * ((displayValue - startValue) / (maxValue - startValue))) - toRadians(overlapOver180InDegree); // Left x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle - (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle - (Math.PI / 2)))); context.lineTo(x, y); // Tip x = (canvas.width / 2) - ((radius * 0.90) * Math.cos(___currentAngle)); y = (radius + 10) - ((radius * 0.90) * Math.sin(___currentAngle)); context.lineTo(x, y); // Right x = (canvas.width / 2) - ((radius * 0.05) * Math.cos((___currentAngle + (Math.PI / 2)))); y = (radius + 10) - ((radius * 0.05) * Math.sin((___currentAngle + (Math.PI / 2)))); context.lineTo(x, y); context.closePath(); context.fillStyle = analogDisplayColorConfig.handColor; context.fill(); context.lineWidth = 1; context.strokeStyle = analogDisplayColorConfig.handOutlineColor; context.stroke(); // Knob context.beginPath(); context.arc((canvas.width / 2), (radius + 10), 7, 0, 2 * Math.PI, false); context.closePath(); context.fillStyle = analogDisplayColorConfig.knobColor; context.fill(); context.strokeStyle = analogDisplayColorConfig.knobOutlineColor; context.stroke(); }; this.setValue = function(val) { drawDisplay(canvasName, displaySize, val); }; function toDegrees(rad) { return rad * (180 / Math.PI); } function toRadians(deg) { return deg * (Math.PI / 180); } }
12nosanshiro-pi4j-sample
AdafruitI2C/node/widgets/AnalogDisplay.js
JavaScript
mit
12,851
// http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/ "use strict"; /** * Warning: there is a first HTTP HandShake going on, that must follow the orasocket.js protocol. * See the request header: * "tyrus-ws-attempt" = "Hand-Shake" * * Response headers will contain: * "tyrus-fallback-transports" * "tyrus-connection-id" * * FYI, tyrus is the name of the RI for JSR356. * * Static requests must be prefixed with /data/, like in http://machine:9876/data/chat.html */ // Optional. You will see this name in eg. 'ps' or 'top' command process.title = 'node-pwm'; // Port where we'll run the websocket server var port = 9876; // websocket and http servers var webSocketServer = require('websocket').server; var http = require('http'); var fs = require('fs'); var verbose = false; if (typeof String.prototype.startsWith != 'function') { String.prototype.startsWith = function (str) { return this.indexOf(str) == 0; }; } if (typeof String.prototype.endsWith != 'function') { String.prototype.endsWith = function(suffix) { return this.indexOf(suffix, this.length - suffix.length) !== -1; }; } function handler (req, res) { var respContent = ""; if (verbose) { console.log("Speaking HTTP from " + __dirname); console.log("Server received an HTTP Request:\n" + req.method + "\n" + req.url + "\n-------------"); console.log("ReqHeaders:" + JSON.stringify(req.headers, null, '\t')); console.log('Request:' + req.url); var prms = require('url').parse(req.url, true); console.log(prms); console.log("Search: [" + prms.search + "]"); console.log("-------------------------------"); } if (req.url.startsWith("/data/")) // Static resource { var resource = req.url.substring("/data/".length); console.log('Loading static ' + req.url + " (" + resource + ")"); fs.readFile(__dirname + '/' + resource, function (err, data) { if (err) { res.writeHead(500); return res.end('Error loading ' + resource); } if (verbose) console.log("Read resource content:\n---------------\n" + data + "\n--------------"); var contentType = "text/html"; if (resource.endsWith(".css")) contentType = "text/css"; else if (resource.endsWith(".html")) contentType = "text/html"; else if (resource.endsWith(".xml")) contentType = "text/xml"; else if (resource.endsWith(".js")) contentType = "text/javascript"; else if (resource.endsWith(".jpg")) contentType = "image/jpg"; else if (resource.endsWith(".gif")) contentType = "image/gif"; else if (resource.endsWith(".png")) contentType = "image/png"; res.writeHead(200, {'Content-Type': contentType}); // console.log('Data is ' + typeof(data)); if (resource.endsWith(".jpg") || resource.endsWith(".gif") || resource.endsWith(".png")) { // res.writeHead(200, {'Content-Type': 'image/gif' }); res.end(data, 'binary'); } else res.end(data.toString().replace('$PORT$', port.toString())); // Replace $PORT$ with the actual port value. }); } else if (req.url == "/") { if (req.method === "POST") { var data = ""; console.log("---- Headers ----"); for(var item in req.headers) console.log(item + ": " + req.headers[item]); console.log("-----------------"); req.on("data", function(chunk) { data += chunk; }); req.on("end", function() { console.log("POST request: [" + data + "]"); if (req.headers["tyrus-ws-attempt"] !== "undefined" && req.headers["tyrus-ws-attempt"] === "Hand-Shake") // List of the supoprted protocols { console.log(" ... writing headers..."); res.writeHead(200, {'Content-Type': 'application/json', 'tyrus-fallback-transports': 'WebSocket,MozWebSocket,XMLHttpRequest,FedEx,UPS', 'tyrus-connection-id': guid() }); } else res.writeHead(200, {'Content-Type': 'application/json'}); var status = {'status':'OK'}; res.end(JSON.stringify(status)); }); } } else { console.log("Unmanaged request: [" + req.url + "]"); respContent = "Response from " + req.url; res.writeHead(404, {'Content-Type': 'text/plain'}); res.end(); // respContent); } } // HTTP Handler /** * Global variables */ // list of currently connected clients (users) var clients = [ ]; /** * Helper function for escaping input strings */ function htmlEntities(str) { return String(str).replace(/&/g, '&amp;').replace(/</g, '&lt;') .replace(/>/g, '&gt;').replace(/"/g, '&quot;'); } /** * HTTP server */ var server = http.createServer(handler); server.listen(port, function() { console.log((new Date()) + " Server is listening on port " + port); console.log("Connect to [http://localhost:9876/data/display.html]"); }); /** * WebSocket server */ var wsServer = new webSocketServer({ // WebSocket server is tied to a HTTP server. WebSocket request is just // an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6 httpServer: server }); // This callback function is called every time someone // tries to connect to the WebSocket server wsServer.on('request', function(request) { console.log((new Date()) + ' Connection from origin ' + request.origin + '.'); // accept connection - you should check 'request.origin' to make sure that // client is connecting from your website // (http://en.wikipedia.org/wiki/Same_origin_policy) var connection = request.accept(null, request.origin); clients.push(connection); console.log((new Date()) + ' Connection accepted.'); // user sent some message connection.on('message', function(message) { if (message.type === 'utf8') { // accept only text console.log((new Date()) + ' Received Message: ' + message.utf8Data); var obj = { time: (new Date()).getTime(), text: htmlEntities(message.utf8Data) }; // broadcast message to all connected clients. That's what this app is doing. var json = JSON.stringify({ type:'message', data: obj }); console.log("Rebroadcasting: " + json); for (var i=0; i < clients.length; i++) { clients[i].sendUTF(json); } } }); // user disconnected connection.on('close', function(connection) { // Close }); }); function s4() { return (Math.floor((1 + Math.random()) * 0x10000) & 0xffff) .toString(16); // .substring(1); }; function guid() { return s4() + "." + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + "." + s4() + "." + s4(); }
12nosanshiro-pi4j-sample
AdafruitI2C/node/server.js
JavaScript
mit
7,383
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.AdafruitHTU21DF
12nosanshiro-pi4j-sample
AdafruitI2C/htu21df
Shell
mit
114
#!/bin/bash # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.main.SampleTCS34725Main $*
12nosanshiro-pi4j-sample
AdafruitI2C/tcs34725.main
Shell
mit
192
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.samples.InteractiveServo
12nosanshiro-pi4j-sample
AdafruitI2C/inter.servo
Shell
mit
117
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.AdafruitMCP9808
12nosanshiro-pi4j-sample
AdafruitI2C/mcp9808
Shell
mit
114
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.AdafruitTCS34725
12nosanshiro-pi4j-sample
AdafruitI2C/tcs34725
Shell
mit
115
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.samples.DemoStandard
12nosanshiro-pi4j-sample
AdafruitI2C/standard
Shell
mit
113
package adafruiti2c.sensor; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import com.pi4j.system.SystemInfo; import java.io.IOException; /* * Proximity sensor */ public class AdafruitVCNL4000 { public final static int LITTLE_ENDIAN = 0; public final static int BIG_ENDIAN = 1; private final static int VCNL4000_ENDIANNESS = BIG_ENDIAN; /* Prompt> sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- 13 -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- -- */ // This next addresses is returned by "sudo i2cdetect -y 1", see above. public final static int VCNL4000_ADDRESS = 0x13; // Commands public final static int VCNL4000_COMMAND = 0x80; public final static int VCNL4000_PRODUCTID = 0x81; public final static int VCNL4000_IRLED = 0x83; public final static int VCNL4000_AMBIENTPARAMETER = 0x84; public final static int VCNL4000_AMBIENTDATA = 0x85; public final static int VCNL4000_PROXIMITYDATA = 0x87; public final static int VCNL4000_SIGNALFREQ = 0x89; public final static int VCNL4000_PROXINITYADJUST = 0x8A; public final static int VCNL4000_3M125 = 0x00; public final static int VCNL4000_1M5625 = 0x01; public final static int VCNL4000_781K25 = 0x02; public final static int VCNL4000_390K625 = 0x03; public final static int VCNL4000_MEASUREAMBIENT = 0x10; public final static int VCNL4000_MEASUREPROXIMITY = 0x08; public final static int VCNL4000_AMBIENTREADY = 0x40; public final static int VCNL4000_PROXIMITYREADY = 0x20; private static boolean verbose = false; private I2CBus bus; private I2CDevice vcnl4000; public AdafruitVCNL4000() { this(VCNL4000_ADDRESS); } public AdafruitVCNL4000(int address) { try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself vcnl4000 = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); vcnl4000.write(VCNL4000_IRLED, (byte)20); // 20 * 10mA = 200mA. Range [10-200], by step of 10. try { int irLed = readU8(VCNL4000_IRLED); System.out.println("IR LED Current = " + (irLed * 10) + " mA"); } catch (Exception ex) { ex.printStackTrace(); } try { // vcnl4000.write(VCNL4000_SIGNALFREQ, (byte)VCNL4000_390K625); int freq = readU8(VCNL4000_SIGNALFREQ); switch (freq) { case VCNL4000_3M125: System.out.println("Proximity measurement frequency = 3.125 MHz"); break; case VCNL4000_1M5625: System.out.println("Proximity measurement frequency = 1.5625 MHz"); break; case VCNL4000_781K25: System.out.println("Proximity measurement frequency = 781.25 KHz"); break; case VCNL4000_390K625: System.out.println("Proximity measurement frequency = 390.625 KHz"); break; } } catch (Exception ex) { ex.printStackTrace(); } vcnl4000.write(VCNL4000_PROXINITYADJUST, (byte)0x81); try { int reg = readU8(VCNL4000_PROXINITYADJUST); System.out.println("Proximity adjustment register = " + toHex(reg)); } catch (Exception ex) { ex.printStackTrace(); } } catch (IOException e) { System.err.println(e.getMessage()); } } private int readU8(int reg) throws Exception { int result = 0; try { result = this.vcnl4000.read(reg); try { Thread.sleep(0, 170000); } catch (Exception ex) { ex.printStackTrace(); } // 170 microseconds if (verbose) System.out.println("(U8) I2C: Device " + toHex(VCNL4000_ADDRESS) + " returned " + toHex(result) + " from reg " + toHex(reg)); } catch (Exception ex) { ex.printStackTrace(); } return result; } private int readU16(int register) throws Exception { int hi = this.readU8(register); int lo = this.readU8(register + 1); int result = (VCNL4000_ENDIANNESS == BIG_ENDIAN)? (hi << 8) + lo : (lo << 8) + hi; // Little endian for VCNL4000 if (verbose) System.out.println("(U16) I2C: Device " + toHex(VCNL4000_ADDRESS) + " returned " + toHex(result) + " from reg " + toHex(register)); return result; } public int readProximity() throws Exception { int prox = 0; vcnl4000.write(VCNL4000_COMMAND, (byte)VCNL4000_MEASUREPROXIMITY); boolean keepTrying = true; while (keepTrying) { int cmd = this.readU8(VCNL4000_COMMAND); if (verbose) System.out.println("DBG: Proximity: " + (cmd & 0xFFFF) + ", " + cmd + " (" + VCNL4000_PROXIMITYREADY + ")"); if (((cmd & 0xff) & VCNL4000_PROXIMITYREADY) != 0) { keepTrying = false; prox = this.readU16(VCNL4000_PROXIMITYDATA); } else waitfor(10); // Wait 10 ms } return prox; } public int readAmbient() throws Exception { int ambient = 0; vcnl4000.write(VCNL4000_COMMAND, (byte)VCNL4000_MEASUREAMBIENT); boolean keepTrying = true; while (keepTrying) { int cmd = this.readU8(VCNL4000_COMMAND); if (verbose) System.out.println("DBG: Ambient: " + (cmd & 0xFFFF) + ", " + cmd + " (" + VCNL4000_AMBIENTREADY + ")"); if (((cmd & 0xff) & VCNL4000_AMBIENTREADY) != 0) { keepTrying = false; ambient = this.readU16(VCNL4000_AMBIENTDATA); } else waitfor(10); // Wait 10 ms } return ambient; } public final static int AMBIENT_INDEX = 0; public final static int PROXIMITY_INDEX = 1; public int[] readAmbientProximity() throws Exception { int prox = 0; int ambient = 0; vcnl4000.write(VCNL4000_COMMAND, (byte)(VCNL4000_MEASUREPROXIMITY | VCNL4000_MEASUREAMBIENT)); boolean keepTrying = true; while (keepTrying) { int cmd = this.readU8(VCNL4000_COMMAND); if (verbose) System.out.println("DBG: Proximity: " + (cmd & 0xFFFF) + ", " + cmd + " (" + VCNL4000_PROXIMITYREADY + ")"); if (((cmd & 0xff) & VCNL4000_PROXIMITYREADY) != 0 && ((cmd & 0xff) & VCNL4000_AMBIENTREADY) != 0) { keepTrying = false; ambient = this.readU16(VCNL4000_AMBIENTDATA); prox = this.readU16(VCNL4000_PROXIMITYDATA); } else waitfor(10); // Wait 10 ms } return new int[] { ambient, prox }; } private static String toHex(int i) { String s = Integer.toString(i, 16).toUpperCase(); while (s.length() % 2 != 0) s = "0" + s; return "0x" + s; } private static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } private static boolean go = true; private static int minProx = Integer.MAX_VALUE; private static int minAmbient = Integer.MAX_VALUE; private static int maxProx = Integer.MIN_VALUE; private static int maxAmbient = Integer.MIN_VALUE; public static void main(String[] args) { AdafruitVCNL4000 sensor = new AdafruitVCNL4000(); int prox = 0; int ambient = 0; // Bonus : CPU Temperature try { System.out.println("CPU Temperature : " + SystemInfo.getCpuTemperature()); System.out.println("CPU Core Voltage : " + SystemInfo.getCpuVoltage()); } catch (InterruptedException ie) { ie.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { go = false; System.out.println("\nBye"); System.out.println("Proximity between " + minProx + " and " + maxProx); System.out.println("Ambient between " + minAmbient + " and " + maxAmbient); } }); System.out.println("-- Ready --"); int i = 0; while (go) // && i++ < 5) { try { if (false) prox = sensor.readProximity(); else if (false) ambient = sensor.readAmbient(); else if (true) { int[] data = sensor.readAmbientProximity(); prox = data[PROXIMITY_INDEX]; ambient = data[AMBIENT_INDEX]; } maxProx = Math.max(prox, maxProx); maxAmbient = Math.max(ambient, maxAmbient); minProx = Math.min(prox, minProx); minAmbient = Math.min(ambient, minAmbient); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } System.out.println("Ambient:" + ambient + ", Proximity: " + prox); try { Thread.sleep(100L); } catch (InterruptedException ex) { System.err.println(ex.toString()); } } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/AdafruitVCNL4000.java
Java
mit
9,756
package adafruiti2c.sensor; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import com.pi4j.system.SystemInfo; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; /* * Altitude, Pressure, Temperature */ public class AdafruitBMP180 { public final static int LITTLE_ENDIAN = 0; public final static int BIG_ENDIAN = 1; private final static int BMP180_ENDIANNESS = BIG_ENDIAN; /* Prompt> sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- 77 */ // This next addresses is returned by "sudo i2cdetect -y 1", see above. public final static int BMP180_ADDRESS = 0x77; // Operating Modes public final static int BMP180_ULTRALOWPOWER = 0; public final static int BMP180_STANDARD = 1; public final static int BMP180_HIGHRES = 2; public final static int BMP180_ULTRAHIGHRES = 3; // BMP180 Registers public final static int BMP180_CAL_AC1 = 0xAA; // R Calibration data (16 bits) public final static int BMP180_CAL_AC2 = 0xAC; // R Calibration data (16 bits) public final static int BMP180_CAL_AC3 = 0xAE; // R Calibration data (16 bits) public final static int BMP180_CAL_AC4 = 0xB0; // R Calibration data (16 bits) public final static int BMP180_CAL_AC5 = 0xB2; // R Calibration data (16 bits) public final static int BMP180_CAL_AC6 = 0xB4; // R Calibration data (16 bits) public final static int BMP180_CAL_B1 = 0xB6; // R Calibration data (16 bits) public final static int BMP180_CAL_B2 = 0xB8; // R Calibration data (16 bits) public final static int BMP180_CAL_MB = 0xBA; // R Calibration data (16 bits) public final static int BMP180_CAL_MC = 0xBC; // R Calibration data (16 bits) public final static int BMP180_CAL_MD = 0xBE; // R Calibration data (16 bits) public final static int BMP180_CONTROL = 0xF4; public final static int BMP180_TEMPDATA = 0xF6; public final static int BMP180_PRESSUREDATA = 0xF6; public final static int BMP180_READTEMPCMD = 0x2E; public final static int BMP180_READPRESSURECMD = 0x34; private int cal_AC1 = 0; private int cal_AC2 = 0; private int cal_AC3 = 0; private int cal_AC4 = 0; private int cal_AC5 = 0; private int cal_AC6 = 0; private int cal_B1 = 0; private int cal_B2 = 0; private int cal_MB = 0; private int cal_MC = 0; private int cal_MD = 0; private static boolean verbose = false; private I2CBus bus; private I2CDevice bmp180; private int mode = BMP180_STANDARD; public AdafruitBMP180() { this(BMP180_ADDRESS); } public AdafruitBMP180(int address) { try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself bmp180 = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); try { this.readCalibrationData(); } catch (Exception ex) { ex.printStackTrace(); } } catch (IOException e) { System.err.println(e.getMessage()); } } private int readU8(int reg) throws Exception { // "Read an unsigned byte from the I2C device" int result = 0; try { result = this.bmp180.read(reg); if (verbose) System.out.println("I2C: Device " + BMP180_ADDRESS + " returned " + result + " from reg " + reg); } catch (Exception ex) { ex.printStackTrace(); } return result; } private int readS8(int reg) throws Exception { // "Reads a signed byte from the I2C device" int result = 0; try { result = this.bmp180.read(reg); if (result > 127) result -= 256; if (verbose) System.out.println("I2C: Device " + BMP180_ADDRESS + " returned " + result + " from reg " + reg); } catch (Exception ex) { ex.printStackTrace(); } return result; } private int readU16(int register) throws Exception { int hi = this.readU8(register); int lo = this.readU8(register + 1); return (BMP180_ENDIANNESS == BIG_ENDIAN) ? (hi << 8) + lo : (lo << 8) + hi; // Big Endian } private int readS16(int register) throws Exception { int hi = 0, lo = 0; if (BMP180_ENDIANNESS == BIG_ENDIAN) { hi = this.readS8(register); lo = this.readU8(register + 1); } else { lo = this.readS8(register); hi = this.readU8(register + 1); } return (hi << 8) + lo; } public void readCalibrationData() throws Exception { // Reads the calibration data from the IC cal_AC1 = readS16(BMP180_CAL_AC1); // INT16 cal_AC2 = readS16(BMP180_CAL_AC2); // INT16 cal_AC3 = readS16(BMP180_CAL_AC3); // INT16 cal_AC4 = readU16(BMP180_CAL_AC4); // UINT16 cal_AC5 = readU16(BMP180_CAL_AC5); // UINT16 cal_AC6 = readU16(BMP180_CAL_AC6); // UINT16 cal_B1 = readS16(BMP180_CAL_B1); // INT16 cal_B2 = readS16(BMP180_CAL_B2); // INT16 cal_MB = readS16(BMP180_CAL_MB); // INT16 cal_MC = readS16(BMP180_CAL_MC); // INT16 cal_MD = readS16(BMP180_CAL_MD); // INT16 if (verbose) showCalibrationData(); } private void showCalibrationData() { // Displays the calibration values for debugging purposes System.out.println("DBG: AC1 = " + cal_AC1); System.out.println("DBG: AC2 = " + cal_AC2); System.out.println("DBG: AC3 = " + cal_AC3); System.out.println("DBG: AC4 = " + cal_AC4); System.out.println("DBG: AC5 = " + cal_AC5); System.out.println("DBG: AC6 = " + cal_AC6); System.out.println("DBG: B1 = " + cal_B1); System.out.println("DBG: B2 = " + cal_B2); System.out.println("DBG: MB = " + cal_MB); System.out.println("DBG: MC = " + cal_MC); System.out.println("DBG: MD = " + cal_MD); } public int readRawTemp() throws Exception { // Reads the raw (uncompensated) temperature from the sensor bmp180.write(BMP180_CONTROL, (byte)BMP180_READTEMPCMD); waitfor(5); // Wait 5ms int raw = readU16(BMP180_TEMPDATA); if (verbose) System.out.println("DBG: Raw Temp: " + (raw & 0xFFFF) + ", " + raw); return raw; } public int readRawPressure() throws Exception { // Reads the raw (uncompensated) pressure level from the sensor bmp180.write(BMP180_CONTROL, (byte)(BMP180_READPRESSURECMD + (this.mode << 6))); if (this.mode == BMP180_ULTRALOWPOWER) waitfor(5); else if (this.mode == BMP180_HIGHRES) waitfor(14); else if (this.mode == BMP180_ULTRAHIGHRES) waitfor(26); else waitfor(8); int msb = bmp180.read(BMP180_PRESSUREDATA); int lsb = bmp180.read(BMP180_PRESSUREDATA + 1); int xlsb = bmp180.read(BMP180_PRESSUREDATA + 2); int raw = ((msb << 16) + (lsb << 8) + xlsb) >> (8 - this.mode); if (verbose) System.out.println("DBG: Raw Pressure: " + (raw & 0xFFFF) + ", " + raw); return raw; } public float readTemperature() throws Exception { // Gets the compensated temperature in degrees celcius int UT = 0; int X1 = 0; int X2 = 0; int B5 = 0; float temp = 0.0f; // Read raw temp before aligning it with the calibration values UT = this.readRawTemp(); X1 = ((UT - this.cal_AC6) * this.cal_AC5) >> 15; X2 = (this.cal_MC << 11) / (X1 + this.cal_MD); B5 = X1 + X2; temp = ((B5 + 8) >> 4) / 10.0f; if (verbose) System.out.println("DBG: Calibrated temperature = " + temp + " C"); return temp; } public float readPressure() throws Exception { // Gets the compensated pressure in pascal int UT = 0; int UP = 0; int B3 = 0; int B5 = 0; int B6 = 0; int X1 = 0; int X2 = 0; int X3 = 0; int p = 0; int B4 = 0; int B7 = 0; UT = this.readRawTemp(); UP = this.readRawPressure(); // You can use the datasheet values to test the conversion results // boolean dsValues = true; boolean dsValues = false; if (dsValues) { UT = 27898; UP = 23843; this.cal_AC6 = 23153; this.cal_AC5 = 32757; this.cal_MB = -32768; this.cal_MC = -8711; this.cal_MD = 2868; this.cal_B1 = 6190; this.cal_B2 = 4; this.cal_AC3 = -14383; this.cal_AC2 = -72; this.cal_AC1 = 408; this.cal_AC4 = 32741; this.mode = BMP180_ULTRALOWPOWER; if (verbose) this.showCalibrationData(); } // True Temperature Calculations X1 = (int)((UT - this.cal_AC6) * this.cal_AC5) >> 15; X2 = (this.cal_MC << 11) / (X1 + this.cal_MD); B5 = X1 + X2; if (verbose) { System.out.println("DBG: X1 = " + X1); System.out.println("DBG: X2 = " + X2); System.out.println("DBG: B5 = " + B5); System.out.println("DBG: True Temperature = " + (((B5 + 8) >> 4) / 10.0) + " C"); } // Pressure Calculations B6 = B5 - 4000; X1 = (this.cal_B2 * (B6 * B6) >> 12) >> 11; X2 = (this.cal_AC2 * B6) >> 11; X3 = X1 + X2; B3 = (((this.cal_AC1 * 4 + X3) << this.mode) + 2) / 4; if (verbose) { System.out.println("DBG: B6 = " + B6); System.out.println("DBG: X1 = " + X1); System.out.println("DBG: X2 = " + X2); System.out.println("DBG: X3 = " + X3); System.out.println("DBG: B3 = " + B3); } X1 = (this.cal_AC3 * B6) >> 13; X2 = (this.cal_B1 * ((B6 * B6) >> 12)) >> 16; X3 = ((X1 + X2) + 2) >> 2; B4 = (this.cal_AC4 * (X3 + 32768)) >> 15; B7 = (UP - B3) * (50000 >> this.mode); if (verbose) { System.out.println("DBG: X1 = " + X1); System.out.println("DBG: X2 = " + X2); System.out.println("DBG: X3 = " + X3); System.out.println("DBG: B4 = " + B4); System.out.println("DBG: B7 = " + B7); } if (B7 < 0x80000000) p = (B7 * 2) / B4; else p = (B7 / B4) * 2; if (verbose) System.out.println("DBG: X1 = " + X1); X1 = (p >> 8) * (p >> 8); X1 = (X1 * 3038) >> 16; X2 = (-7357 * p) >> 16; if (verbose) { System.out.println("DBG: p = " + p); System.out.println("DBG: X1 = " + X1); System.out.println("DBG: X2 = " + X2); } p = p + ((X1 + X2 + 3791) >> 4); if (verbose) System.out.println("DBG: Pressure = " + p + " Pa"); return p; } private int standardSeaLevelPressure = 101325; public void setStandardSeaLevelPressure(int standardSeaLevelPressure) { this.standardSeaLevelPressure = standardSeaLevelPressure; } public double readAltitude() throws Exception { // "Calculates the altitude in meters" double altitude = 0.0; float pressure = readPressure(); altitude = 44330.0 * (1.0 - Math.pow(pressure / standardSeaLevelPressure, 0.1903)); if (verbose) System.out.println("DBG: Altitude = " + altitude); return altitude; } protected static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } public static void main(String[] args) { final NumberFormat NF = new DecimalFormat("##00.00"); AdafruitBMP180 sensor = new AdafruitBMP180(); float press = 0; float temp = 0; double alt = 0; try { press = sensor.readPressure(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } sensor.setStandardSeaLevelPressure((int)press); // As we ARE at the sea level (in San Francisco). try { alt = sensor.readAltitude(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { temp = sensor.readTemperature(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } System.out.println("Temperature: " + NF.format(temp) + " C"); System.out.println("Pressure : " + NF.format(press / 100) + " hPa"); System.out.println("Altitude : " + NF.format(alt) + " m"); // Bonus : CPU Temperature try { System.out.println("CPU Temperature : " + SystemInfo.getCpuTemperature()); System.out.println("CPU Core Voltage : " + SystemInfo.getCpuVoltage()); } catch (InterruptedException ie) { ie.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/AdafruitBMP180.java
Java
mit
13,097
package adafruiti2c.sensor; import adafruiti2c.sensor.listener.AdafruitLSM303Listener; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import com.pi4j.system.SystemInfo; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; /* * Accelerometer + Magnetometer */ public class AdafruitLSM303 { // Minimal constants carried over from Arduino library /* Prompt> sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- 19 -- -- -- -- 1e -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- -- */ // Those 2 next addresses are returned by "sudo i2cdetect -y 1", see above. public final static int LSM303_ADDRESS_ACCEL = (0x32 >> 1); // 0011001x, 0x19 public final static int LSM303_ADDRESS_MAG = (0x3C >> 1); // 0011110x, 0x1E // Default Type public final static int LSM303_REGISTER_ACCEL_CTRL_REG1_A = 0x20; // 00000111 rw public final static int LSM303_REGISTER_ACCEL_CTRL_REG4_A = 0x23; // 00000000 rw public final static int LSM303_REGISTER_ACCEL_OUT_X_L_A = 0x28; public final static int LSM303_REGISTER_MAG_CRB_REG_M = 0x01; public final static int LSM303_REGISTER_MAG_MR_REG_M = 0x02; public final static int LSM303_REGISTER_MAG_OUT_X_H_M = 0x03; // Gain settings for setMagGain() public final static int LSM303_MAGGAIN_1_3 = 0x20; // +/- 1.3 public final static int LSM303_MAGGAIN_1_9 = 0x40; // +/- 1.9 public final static int LSM303_MAGGAIN_2_5 = 0x60; // +/- 2.5 public final static int LSM303_MAGGAIN_4_0 = 0x80; // +/- 4.0 public final static int LSM303_MAGGAIN_4_7 = 0xA0; // +/- 4.7 public final static int LSM303_MAGGAIN_5_6 = 0xC0; // +/- 5.6 public final static int LSM303_MAGGAIN_8_1 = 0xE0; // +/- 8.1 private I2CBus bus; private I2CDevice accelerometer, magnetometer; private byte[] accelData, magData; private final static NumberFormat Z_FMT = new DecimalFormat("000"); private static boolean verbose = false; private long wait = 1000L; private AdafruitLSM303Listener dataListener = null; public AdafruitLSM303() { if (verbose) System.out.println("Starting sensors reading:"); try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself accelerometer = bus.getDevice(LSM303_ADDRESS_ACCEL); magnetometer = bus.getDevice(LSM303_ADDRESS_MAG); if (verbose) System.out.println("Connected to devices. OK."); /* * Start sensing */ // Enable accelerometer accelerometer.write(LSM303_REGISTER_ACCEL_CTRL_REG1_A, (byte)0x27); // 00100111 accelerometer.write(LSM303_REGISTER_ACCEL_CTRL_REG4_A, (byte)0x00); if (verbose) System.out.println("Accelerometer OK."); // Enable magnetometer magnetometer.write(LSM303_REGISTER_MAG_MR_REG_M, (byte)0x00); int gain = LSM303_MAGGAIN_1_3; magnetometer.write(LSM303_REGISTER_MAG_CRB_REG_M, (byte)gain); if (verbose) System.out.println("Magnetometer OK."); startReading(); } catch (IOException e) { System.err.println(e.getMessage()); } } public void setDataListener(AdafruitLSM303Listener dataListener) { this.dataListener = dataListener; } // Create a separate thread to read the sensors public void startReading() { Runnable task = new Runnable() { @Override public void run() { try { readingSensors(); } catch (IOException ioe) { System.err.println("Reading thread:"); ioe.printStackTrace(); } } }; new Thread(task).start(); } public void setWait(long wait) { this.wait = wait; } private boolean keepReading = true; public void setKeepReading(boolean keepReading) { this.keepReading = keepReading; } private void readingSensors() throws IOException { while (keepReading) { accelData = new byte[6]; magData = new byte[6]; int r = accelerometer.read(LSM303_REGISTER_ACCEL_OUT_X_L_A | 0x80, accelData, 0, 6); if (r != 6) { System.out.println("Error reading accel data, < 6 bytes"); } int accelX = accel12(accelData, 0); int accelY = accel12(accelData, 2); int accelZ = accel12(accelData, 4); // Reading magnetometer measurements. r = magnetometer.read(LSM303_REGISTER_MAG_OUT_X_H_M, magData, 0, 6); if (r != 6) { System.out.println("Error reading mag data, < 6 bytes"); } int magX = mag16(magData, 0); int magY = mag16(magData, 2); int magZ = mag16(magData, 4); float heading = (float)Math.toDegrees(Math.atan2(magY, magX)); while (heading < 0) heading += 360f; // Bonus : CPU Temperature float cpuTemp = Float.MIN_VALUE; float cpuVoltage = Float.MIN_VALUE; try { cpuTemp = SystemInfo.getCpuTemperature(); cpuVoltage = SystemInfo.getCpuVoltage(); } catch (InterruptedException ie) { ie.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if (dataListener != null) dataListener.dataDetected(accelX, accelY, accelZ, magX, magY, magZ, heading); else { System.out.println("accel (X: " + accelX + ", Y: " + accelY + ", Z: " + accelZ + ") mag (X: " + magX + ", Y: " + magY + ", Z: " + magZ + ", heading: " + Z_FMT.format(heading) + ")" + (cpuTemp != Float.MIN_VALUE?" Cpu Temp:" + cpuTemp:"") + (cpuVoltage != Float.MIN_VALUE?" Cpu Volt:" + cpuVoltage:"")); } //Use the values as you want // ... try { Thread.sleep(this.wait); } catch (InterruptedException ie) { System.err.println(ie.getMessage()); } } } private static int accel12(byte[] list, int idx) { int n = list[idx] | (list[idx+1] << 8); // Low, high bytes if (n > 32767) n -= 65536; // 2's complement signed return n >> 4; // 12-bit resolution } private static int mag16(byte[] list, int idx) { int n = (list[idx] << 8) | list[idx+1]; // High, low bytes return (n < 32768 ? n : n - 65536); // 2's complement signed } public static void main(String[] args) { AdafruitLSM303 sensor = new AdafruitLSM303(); sensor.startReading(); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/AdafruitLSM303.java
Java
mit
7,288
package adafruiti2c.sensor; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import com.pi4j.system.SystemInfo; import java.io.IOException; import java.util.HashMap; import java.util.Map; /* * Light sensor */ public class AdafruitTCS34725 { public final static int LITTLE_ENDIAN = 0; public final static int BIG_ENDIAN = 1; private final static int TCS34725_ENDIANNESS = BIG_ENDIAN; /* Prompt> sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- 29 -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- -- */ // This next addresses is returned by "sudo i2cdetect -y 1", see above. public final static int TCS34725_ADDRESS = 0x29; //public final static int TCS34725_ID = 0x12; // 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 public final static int TCS34725_COMMAND_BIT = 0x80; public final static int TCS34725_ENABLE = 0x00; public final static int TCS34725_ENABLE_AIEN = 0x10; // RGBC Interrupt Enable public final static int TCS34725_ENABLE_WEN = 0x08; // Wait enable - Writing 1 activates the wait timer public final static int TCS34725_ENABLE_AEN = 0x02; // RGBC Enable - Writing 1 actives the ADC, 0 disables it public final static int TCS34725_ENABLE_PON = 0x01; // Power on - Writing 1 activates the internal oscillator, 0 disables it public final static int TCS34725_ATIME = 0x01; // Integration time public final static int TCS34725_WTIME = 0x03; // Wait time (if TCS34725_ENABLE_WEN is asserted) public final static int TCS34725_WTIME_2_4MS = 0xFF; // WLONG0 = 2.4ms WLONG1 = 0.029s public final static int TCS34725_WTIME_204MS = 0xAB; // WLONG0 = 204ms WLONG1 = 2.45s public final static int TCS34725_WTIME_614MS = 0x00; // WLONG0 = 614ms WLONG1 = 7.4s public final static int TCS34725_AILTL = 0x04; // Clear channel lower interrupt threshold public final static int TCS34725_AILTH = 0x05; public final static int TCS34725_AIHTL = 0x06; // Clear channel upper interrupt threshold public final static int TCS34725_AIHTH = 0x07; public final static int TCS34725_PERS = 0x0C; // Persistence register - basic SW filtering mechanism for interrupts public final static int TCS34725_PERS_NONE = 0b0000; // Every RGBC cycle generates an interrupt public final static int TCS34725_PERS_1_CYCLE = 0b0001; // 1 clean channel value outside threshold range generates an interrupt public final static int TCS34725_PERS_2_CYCLE = 0b0010; // 2 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_3_CYCLE = 0b0011; // 3 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_5_CYCLE = 0b0100; // 5 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_10_CYCLE = 0b0101; // 10 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_15_CYCLE = 0b0110; // 15 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_20_CYCLE = 0b0111; // 20 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_25_CYCLE = 0b1000; // 25 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_30_CYCLE = 0b1001; // 30 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_35_CYCLE = 0b1010; // 35 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_40_CYCLE = 0b1011; // 40 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_45_CYCLE = 0b1100; // 45 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_50_CYCLE = 0b1101; // 50 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_55_CYCLE = 0b1110; // 55 clean channel values outside threshold range generates an interrupt public final static int TCS34725_PERS_60_CYCLE = 0b1111; // 60 clean channel values outside threshold range generates an interrupt public final static int TCS34725_CONFIG = 0x0D; public final static int TCS34725_CONFIG_WLONG = 0x02; // Choose between short and long (12x) wait times via TCS34725_WTIME public final static int TCS34725_CONTROL = 0x0F; // Set the gain level for the sensor public final static int TCS34725_ID = 0x12; // 0x44 = TCS34721/TCS34725, 0x4D = TCS34723/TCS34727 public final static int TCS34725_STATUS = 0x13; public final static int TCS34725_STATUS_AINT = 0x10; // RGBC Clean channel interrupt public final static int TCS34725_STATUS_AVALID = 0x01; // Indicates that the RGBC channels have completed an integration cycle public final static int TCS34725_CDATAL = 0x14; // Clear channel data public final static int TCS34725_CDATAH = 0x15; public final static int TCS34725_RDATAL = 0x16; // Red channel data public final static int TCS34725_RDATAH = 0x17; public final static int TCS34725_GDATAL = 0x18; // Green channel data public final static int TCS34725_GDATAH = 0x19; public final static int TCS34725_BDATAL = 0x1A; // Blue channel data public final static int TCS34725_BDATAH = 0x1B; public final static int TCS34725_INTEGRATIONTIME_2_4MS = 0xFF; // 2.4ms - 1 cycle - Max Count: 1024 public final static int TCS34725_INTEGRATIONTIME_24MS = 0xF6; // 24ms - 10 cycles - Max Count: 10240 public final static int TCS34725_INTEGRATIONTIME_50MS = 0xEB; // 50ms - 20 cycles - Max Count: 20480 public final static int TCS34725_INTEGRATIONTIME_101MS = 0xD5; // 101ms - 42 cycles - Max Count: 43008 public final static int TCS34725_INTEGRATIONTIME_154MS = 0xC0; // 154ms - 64 cycles - Max Count: 65535 public final static int TCS34725_INTEGRATIONTIME_700MS = 0x00; // 700ms - 256 cycles - Max Count: 65535 public final static int TCS34725_GAIN_1X = 0x00; // No gain public final static int TCS34725_GAIN_4X = 0x01; // 4x gain public final static int TCS34725_GAIN_16X = 0x02; // 16x gain public final static int TCS34725_GAIN_60X = 0x03; // 60x gain public final static Map<Integer, Long> INTEGRATION_TIME_DELAY = new HashMap<Integer, Long>(); static { // Microseconds INTEGRATION_TIME_DELAY.put(TCS34725_INTEGRATIONTIME_2_4MS, 2400L); // 2.4ms - 1 cycle - Max Count: 1024 INTEGRATION_TIME_DELAY.put(TCS34725_INTEGRATIONTIME_24MS, 24000L); // 24ms - 10 cycles - Max Count: 10240 INTEGRATION_TIME_DELAY.put(TCS34725_INTEGRATIONTIME_50MS, 50000L); // 50ms - 20 cycles - Max Count: 20480 INTEGRATION_TIME_DELAY.put(TCS34725_INTEGRATIONTIME_101MS, 101000L); // 101ms - 42 cycles - Max Count: 43008 INTEGRATION_TIME_DELAY.put(TCS34725_INTEGRATIONTIME_154MS, 154000L); // 154ms - 64 cycles - Max Count: 65535 INTEGRATION_TIME_DELAY.put(TCS34725_INTEGRATIONTIME_700MS, 700000L); // 700ms - 256 cycles - Max Count: 65535 } private static boolean verbose = false; private I2CBus bus; private I2CDevice tcs34725; private int integrationTime = 0xFF; private int gain = 0x01; public static void setVerbose(boolean b) { verbose = b; } public AdafruitTCS34725() { this(TCS34725_ADDRESS); } public AdafruitTCS34725(int address) { this(address, false, 0xff, 0x01); } public AdafruitTCS34725(boolean b, int integrationTime, int gain) { this(TCS34725_ADDRESS, b, integrationTime, gain); } public AdafruitTCS34725(int integrationTime, int gain) { this(TCS34725_ADDRESS, false, integrationTime, gain); } public AdafruitTCS34725(int address, boolean v, int integrationTime, int gain) { this.integrationTime = integrationTime; this.gain = gain; verbose = v; try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself tcs34725 = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); initialize(); } catch (IOException e) { System.err.println(e.getMessage()); } catch (Exception e) { System.err.println(e.getMessage()); } } private int initialize() throws Exception { int result = this.readU8(TCS34725_ID); if (result != 0x44) return -1; enable(); return 0; } public void enable() throws IOException { this.write8(TCS34725_ENABLE, (byte)TCS34725_ENABLE_PON); waitfor(10L); this.write8(TCS34725_ENABLE, (byte)(TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN)); } public void disable() throws Exception { int reg = 0; reg = this.readU8(TCS34725_ENABLE); this.write8(TCS34725_ENABLE, (byte)(reg & ~(TCS34725_ENABLE_PON | TCS34725_ENABLE_AEN))); } public void setIntegrationTime(int integrationTime) throws IOException { this.integrationTime = integrationTime; this.write8(TCS34725_ATIME, (byte)integrationTime); } public int getIntegrationTime() throws Exception { return this.readU8(TCS34725_ATIME); } public void setGain(int gain) throws IOException { this.write8(TCS34725_CONTROL, (byte)gain); } public int getGain() throws Exception { return this.readU8(TCS34725_CONTROL); } public TCSColor getRawData() throws Exception { int r = this.readU16(TCS34725_RDATAL); int b = this.readU16(TCS34725_BDATAL); int g = this.readU16(TCS34725_GDATAL); int c = this.readU16(TCS34725_CDATAL); waitfor((long)(INTEGRATION_TIME_DELAY.get(this.integrationTime) / 1000L)); return new TCSColor(r, b, g, c); } public void setInterrupt(boolean intrpt) throws Exception { int r = this.readU8(TCS34725_ENABLE); if (intrpt) r |= TCS34725_ENABLE_AIEN; else r &= ~TCS34725_ENABLE_AIEN; this.write8(TCS34725_ENABLE, (byte)r); } public void clearInterrupt() throws IOException { tcs34725.write((byte)(0x66 & 0xff)); } public void setIntLimits(int low, int high) throws IOException { this.write8(0x04, (byte)(low & 0xFF)); this.write8(0x05, (byte)(low >> 8)); this.write8(0x06, (byte)(high & 0xFF)); this.write8(0x07, (byte)(high >> 8)); } /* * Converts the raw R/G/B values to color temperature in degrees Kelvin * see http://en.wikipedia.org/wiki/Color_temperature */ public static int calculateColorTemperature(TCSColor rgb) { // 1. Map RGB values to their XYZ counterparts. // Based on 6500K fluorescent, 3000K fluorescent // and 60W incandescent values for a wide range. // Note: Y = Illuminance or lux double X = (-0.14282 * rgb.getR()) + (1.54924 * rgb.getG()) + (-0.95641 * rgb.getB()); double Y = (-0.32466 * rgb.getR()) + (1.57837 * rgb.getG()) + (-0.73191 * rgb.getB()); double Z = (-0.68202 * rgb.getR()) + (0.77073 * rgb.getG()) + ( 0.56332 * rgb.getB()); // 2. Calculate the chromaticity co-ordinates double xc = (X) / (X + Y + Z); double yc = (Y) / (X + Y + Z); // 3. Use McCamy's formula to determine the CCT double n = (xc - 0.3320) / (0.1858 - yc); // Calculate the final CCT double cct = (449.0 * Math.pow(n, 3.0)) + (3525.0 * Math.pow(n, 2.0)) + (6823.3 * n) + 5520.33; return (int)cct; } /* * Values in Lux (or Lumens) per square meter. */ public static int calculateLux(TCSColor rgb) { double illuminance = (-0.32466 * rgb.getR()) + (1.57837 * rgb.getG()) + (-0.73191 * rgb.getB()); return (int)illuminance; } private void write8(int register, int value) throws IOException { this.tcs34725.write(TCS34725_COMMAND_BIT | register, (byte)(value & 0xff)); } private int readU16(int register) throws Exception { int lo = this.readU8(register); int hi = this.readU8(register + 1); int result = (TCS34725_ENDIANNESS == BIG_ENDIAN) ? (hi << 8) + lo : (lo << 8) + hi; // Big Endian if (verbose) System.out.println("(U16) I2C: Device " + toHex(TCS34725_ADDRESS) + " returned " + toHex(result) + " from reg " + toHex(TCS34725_COMMAND_BIT | register)); return result; } private int readU8(int reg) throws Exception { // "Read an unsigned byte from the I2C device" int result = 0; try { result = this.tcs34725.read(TCS34725_COMMAND_BIT | reg); if (verbose) System.out.println("(U8) I2C: Device " + toHex(TCS34725_ADDRESS) + " returned " + toHex(result) + " from reg " + toHex(TCS34725_COMMAND_BIT | reg)); } catch (Exception ex) { ex.printStackTrace(); } return result; } private static String toHex(int i) { String s = Integer.toString(i, 16).toUpperCase(); while (s.length() % 2 != 0) s = "0" + s; return "0x" + s; } private static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } public static class TCSColor { private int r, b, g, c; public TCSColor(int r, int b, int g, int c) { this.r = r; this.b = b; this.g = g; this.c = c; } public int getR() { return this.r; } public int getB() { return this.b; } public int getG() { return this.g; } public int getC() { return this.c; } public String toString() { return "[ r:" + Integer.toString(r) + ", b:" + Integer.toString(b) + ", g:" + Integer.toString(g) + ", c:" + Integer.toString(c) + "]"; } } public static void main(String[] args) { AdafruitTCS34725 sensor = new AdafruitTCS34725(TCS34725_INTEGRATIONTIME_50MS, TCS34725_GAIN_1X); try { System.out.println(".. Setting interrupt"); sensor.setInterrupt(false); waitfor(1000L); System.out.println(".. Getting raw data"); AdafruitTCS34725.TCSColor rgb = sensor.getRawData(); System.out.println(".. Calculating"); int colorTemp = AdafruitTCS34725.calculateColorTemperature(rgb); int lux = AdafruitTCS34725.calculateLux(rgb); System.out.println(rgb.toString()); System.out.printf("Color Temperature: %d K%n", colorTemp); System.out.printf("Luminosity: %d lux%n", lux); sensor.setInterrupt(true); waitfor(1000L); sensor.disable(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } // Bonus : CPU Temperature try { System.out.println("CPU Temperature : " + SystemInfo.getCpuTemperature()); System.out.println("CPU Core Voltage : " + SystemInfo.getCpuVoltage()); } catch (InterruptedException ie) { ie.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/AdafruitTCS34725.java
Java
mit
16,087
package adafruiti2c.sensor; import adafruiti2c.sensor.utils.BitOps; import adafruiti2c.sensor.utils.L3GD20Dictionaries; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import java.io.IOException; import java.util.Map; public class AdafruitL3GD20 { public final static int L3GD20ADDRESS = 0x6b; public final static int L3GD20_REG_R_WHO_AM_I = 0x0f; // Device identification register public final static int L3GD20_REG_RW_CTRL_REG1 = 0x20; // Control register 1 public final static int L3GD20_REG_RW_CTRL_REG2 = 0x21; // Control register 2 public final static int L3GD20_REG_RW_CTRL_REG3 = 0x22; // Control register 3 public final static int L3GD20_REG_RW_CTRL_REG4 = 0x23; // Control register 4 public final static int L3GD20_REG_RW_CTRL_REG5 = 0x24; // Control register 5 public final static int L3GD20_REG_RW_REFERENCE = 0x25; // Reference value for interrupt generation public final static int L3GD20_REG_R_OUT_TEMP = 0x26; // Output temperature public final static int L3GD20_REG_R_STATUS_REG = 0x27; // Status register public final static int L3GD20_REG_R_OUT_X_L = 0x28; // X-axis angular data rate LSB public final static int L3GD20_REG_R_OUT_X_H = 0x29; // X-axis angular data rate MSB public final static int L3GD20_REG_R_OUT_Y_L = 0x2a; // Y-axis angular data rate LSB public final static int L3GD20_REG_R_OUT_Y_H = 0x2b; // Y-axis angular data rate MSB public final static int L3GD20_REG_R_OUT_Z_L = 0x2c; // Z-axis angular data rate LSB public final static int L3GD20_REG_R_OUT_Z_H = 0x2d; // Z-axis angular data rate MSB public final static int L3GD20_REG_RW_FIFO_CTRL_REG = 0x2e; // Fifo control register public final static int L3GD20_REG_R_FIFO_SRC_REG = 0x2f; // Fifo src register public final static int L3GD20_REG_RW_INT1_CFG_REG = 0x30; // Interrupt 1 configuration register public final static int L3GD20_REG_R_INT1_SRC_REG = 0x31; // Interrupt source register public final static int L3GD20_REG_RW_INT1_THS_XH = 0x32; // Interrupt 1 threshold level X MSB register public final static int L3GD20_REG_RW_INT1_THS_XL = 0x33; // Interrupt 1 threshold level X LSB register public final static int L3GD20_REG_RW_INT1_THS_YH = 0x34; // Interrupt 1 threshold level Y MSB register public final static int L3GD20_REG_RW_INT1_THS_YL = 0x35; // Interrupt 1 threshold level Y LSB register public final static int L3GD20_REG_RW_INT1_THS_ZH = 0x36; // Interrupt 1 threshold level Z MSB register public final static int L3GD20_REG_RW_INT1_THS_ZL = 0x37; // Interrupt 1 threshold level Z LSB register public final static int L3GD20_REG_RW_INT1_DURATION = 0x38; // Interrupt 1 duration register public final static int L3GD20_MASK_CTRL_REG1_Xen = 0x01; // X enable public final static int L3GD20_MASK_CTRL_REG1_Yen = 0x02; // Y enable public final static int L3GD20_MASK_CTRL_REG1_Zen = 0x04; // Z enable public final static int L3GD20_MASK_CTRL_REG1_PD = 0x08; // Power-down public final static int L3GD20_MASK_CTRL_REG1_BW = 0x30; // Bandwidth public final static int L3GD20_MASK_CTRL_REG1_DR = 0xc0; // Output data rate public final static int L3GD20_MASK_CTRL_REG2_HPCF = 0x0f; // High pass filter cutoff frequency public final static int L3GD20_MASK_CTRL_REG2_HPM = 0x30; // High pass filter mode selection public final static int L3GD20_MASK_CTRL_REG3_I2_EMPTY = 0x01; // FIFO empty interrupt on DRDY/INT2 public final static int L3GD20_MASK_CTRL_REG3_I2_ORUN = 0x02; // FIFO overrun interrupt on DRDY/INT2 public final static int L3GD20_MASK_CTRL_REG3_I2_WTM = 0x04; // FIFO watermark interrupt on DRDY/INT2 public final static int L3GD20_MASK_CTRL_REG3_I2_DRDY = 0x08; // Date-ready on DRDY/INT2 public final static int L3GD20_MASK_CTRL_REG3_PP_OD = 0x10; // Push-pull / Open-drain public final static int L3GD20_MASK_CTRL_REG3_H_LACTIVE = 0x20; // Interrupt active configuration on INT1 public final static int L3GD20_MASK_CTRL_REG3_I1_BOOT = 0x40; // Boot status available on INT1 public final static int L3GD20_MASK_CTRL_REG3_I1_Int1 = 0x80; // Interrupt enabled on INT1 public final static int L3GD20_MASK_CTRL_REG4_SIM = 0x01; // SPI Serial interface selection public final static int L3GD20_MASK_CTRL_REG4_FS = 0x30; // Full scale selection public final static int L3GD20_MASK_CTRL_REG4_BLE = 0x40; // Big/little endian selection public final static int L3GD20_MASK_CTRL_REG4_BDU = 0x80; // Block data update public final static int L3GD20_MASK_CTRL_REG5_OUT_SEL = 0x03; // Out selection configuration public final static int L3GD20_MASK_CTRL_REG5_INT_SEL = 0xc0; // INT1 selection configuration public final static int L3GD20_MASK_CTRL_REG5_HPEN = 0x10; // High-pass filter enable public final static int L3GD20_MASK_CTRL_REG5_FIFO_EN = 0x40; // Fifo enable public final static int L3GD20_MASK_CTRL_REG5_BOOT = 0x80; // Reboot memory content public final static int L3GD20_MASK_STATUS_REG_ZYXOR = 0x80; // Z, Y, X axis overrun public final static int L3GD20_MASK_STATUS_REG_ZOR = 0x40; // Z axis overrun public final static int L3GD20_MASK_STATUS_REG_YOR = 0x20; // Y axis overrun public final static int L3GD20_MASK_STATUS_REG_XOR = 0x10; // X axis overrun public final static int L3GD20_MASK_STATUS_REG_ZYXDA = 0x08; // Z, Y, X data available public final static int L3GD20_MASK_STATUS_REG_ZDA = 0x04; // Z data available public final static int L3GD20_MASK_STATUS_REG_YDA = 0x02; // Y data available public final static int L3GD20_MASK_STATUS_REG_XDA = 0x01; // X data available public final static int L3GD20_MASK_FIFO_CTRL_REG_FM = 0xe0; // Fifo mode selection public final static int L3GD20_MASK_FIFO_CTRL_REG_WTM = 0x1f; // Fifo treshold - watermark level public final static int L3GD20_MASK_FIFO_SRC_REG_FSS = 0x1f; // Fifo stored data level public final static int L3GD20_MASK_FIFO_SRC_REG_EMPTY = 0x20; // Fifo empty bit public final static int L3GD20_MASK_FIFO_SRC_REG_OVRN = 0x40; // Overrun status public final static int L3GD20_MASK_FIFO_SRC_REG_WTM = 0x80; // Watermark status public final static int L3GD20_MASK_INT1_CFG_ANDOR = 0x80; // And/Or configuration of interrupt events public final static int L3GD20_MASK_INT1_CFG_LIR = 0x40; // Latch interrupt request public final static int L3GD20_MASK_INT1_CFG_ZHIE = 0x20; // Enable interrupt generation on Z high public final static int L3GD20_MASK_INT1_CFG_ZLIE = 0x10; // Enable interrupt generation on Z low public final static int L3GD20_MASK_INT1_CFG_YHIE = 0x08; // Enable interrupt generation on Y high public final static int L3GD20_MASK_INT1_CFG_YLIE = 0x04; // Enable interrupt generation on Y low public final static int L3GD20_MASK_INT1_CFG_XHIE = 0x02; // Enable interrupt generation on X high public final static int L3GD20_MASK_INT1_CFG_XLIE = 0x01; // Enable interrupt generation on X low public final static int L3GD20_MASK_INT1_SRC_IA = 0x40; // Int1 active public final static int L3GD20_MASK_INT1_SRC_ZH = 0x20; // Int1 source Z high public final static int L3GD20_MASK_INT1_SRC_ZL = 0x10; // Int1 source Z low public final static int L3GD20_MASK_INT1_SRC_YH = 0x08; // Int1 source Y high public final static int L3GD20_MASK_INT1_SRC_YL = 0x04; // Int1 source Y low public final static int L3GD20_MASK_INT1_SRC_XH = 0x02; // Int1 source X high public final static int L3GD20_MASK_INT1_SRC_XL = 0x01; // Int1 source X low public final static int L3GD20_MASK_INT1_THS_H = 0x7f; // MSB public final static int L3GD20_MASK_INT1_THS_L = 0xff; // LSB public final static int L3GD20_MASK_INT1_DURATION_WAIT = 0x80; // Wait number of samples or not public final static int L3GD20_MASK_INT1_DURATION_D = 0x7f; // Duration of int1 to be recognized private static boolean verbose = false; private I2CBus bus; private I2CDevice l3dg20; private double gain = 1D; // For calibration purposes private double meanX = 0; private double maxX = 0; private double minX = 0; private double meanY = 0; private double maxY = 0; private double minY = 0; private double meanZ = 0; private double maxZ = 0; private double minZ = 0; public AdafruitL3GD20() { this(L3GD20ADDRESS); } public AdafruitL3GD20(int address) { try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself l3dg20 = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); } catch (IOException e) { System.err.println(e.getMessage()); } } public void writeToRegister(int register, int mask, int value) throws Exception { int current = readU8(register); int newValue = BitOps.setValueUnderMask(value, current, mask); this.l3dg20.write(register, (byte)newValue); } public int readFromRegister(int register, int mask) throws Exception { int current = readU8(register); return BitOps.getValueUnderMask(current, mask); } private String readFromRegisterWithDictionaryMatch(int register, int mask, Map<String, Byte> dictionary) throws Exception { int current = this.readFromRegister(register, mask); for (String key : dictionary.keySet()) { if (dictionary.get(key) == (byte)current) return key; } return null; } private void writeToRegisterWithDictionaryCheck(int register, int mask, String value, Map<String, Byte> dictionary, String dictName) throws Exception { if (!dictionary.containsKey(value)) throw new RuntimeException("Value [" + value + "] not in range of " + dictName); this.writeToRegister(register, mask, dictionary.get(value)); } /* * To be called after configuration, before measuring */ public void init() throws Exception { String fullScaleValue = getFullScaleValue(); if (fullScaleValue.equals(L3GD20Dictionaries._250_DPS)) this.gain = 0.00875; else if (fullScaleValue.equals(L3GD20Dictionaries._500_DPS)) this.gain = 0.0175; else if (fullScaleValue.equals(L3GD20Dictionaries._2000_DPS)) this.gain = 0.07; } public void calibrateX() throws Exception { System.out.println("Calibrating X, please do not move the sensor..."); double[] buff = new double[20]; for (int i=0; i<20; i++) { while (this.getAxisDataAvailableValue()[0] == 0) waitfor(1L); buff[i] = this.getRawOutXValue(); } this.meanX = getMean(buff); this.maxX = getMax(buff); this.minX = getMin(buff); } public void calibrateY() throws Exception { System.out.println("Calibrating Y, please do not move the sensor..."); double[] buff = new double[20]; for (int i=0; i<20; i++) { while (this.getAxisDataAvailableValue()[1] == 0) waitfor(1L); buff[i] = this.getRawOutYValue(); } this.meanY = getMean(buff); this.maxY = getMax(buff); this.minY = getMin(buff); } public void calibrateZ() throws Exception { System.out.println("Calibrating Z, please do not move the sensor..."); double[] buff = new double[20]; for (int i=0; i<20; i++) { while (this.getAxisDataAvailableValue()[2] == 0) waitfor(1L); buff[i] = this.getRawOutZValue(); } this.meanZ = getMean(buff); this.maxZ = getMax(buff); this.minZ = getMin(buff); } public void calibrate() throws Exception { this.calibrateX(); this.calibrateY(); this.calibrateZ(); } private static double getMax(double[] da) { double max = da[0]; for (double d : da) max = Math.max(max, d); return max; } private static double getMin(double[] da) { double min = da[0]; for (double d : da) min = Math.min(min, d); return min; } private static double getMean(double[] da) { double mean = 0; for (double d : da) mean += d; return mean / da.length; } public int[] getAxisOverrunValue() throws Exception { int zor = 0; int yor = 0; int xor = 0; if (this.readFromRegister(L3GD20_REG_R_STATUS_REG, L3GD20_MASK_STATUS_REG_ZYXOR) == 0x01) { zor = this.readFromRegister(L3GD20_REG_R_STATUS_REG, L3GD20_MASK_STATUS_REG_ZOR); yor = this.readFromRegister(L3GD20_REG_R_STATUS_REG, L3GD20_MASK_STATUS_REG_YOR); xor = this.readFromRegister(L3GD20_REG_R_STATUS_REG, L3GD20_MASK_STATUS_REG_XOR); } return new int[] { xor, yor, zor }; } public int[] getAxisDataAvailableValue() throws Exception { int zda = 0; int yda = 0; int xda = 0; if (this.readFromRegister(L3GD20_REG_R_STATUS_REG, L3GD20_MASK_STATUS_REG_ZYXDA) == 0x01) { zda = this.readFromRegister(L3GD20_REG_R_STATUS_REG, L3GD20_MASK_STATUS_REG_ZDA); yda = this.readFromRegister(L3GD20_REG_R_STATUS_REG, L3GD20_MASK_STATUS_REG_YDA); xda = this.readFromRegister(L3GD20_REG_R_STATUS_REG, L3GD20_MASK_STATUS_REG_XDA); } return new int[] { xda, yda, zda }; } private double getRawOutXValue() throws Exception { int l = this.readFromRegister(L3GD20_REG_R_OUT_X_L, 0xff); int h_u2 = this.readFromRegister(L3GD20_REG_R_OUT_X_H, 0xff); int h = BitOps.twosComplementToByte(h_u2); int value = 0; if (h < 0) value = (h * 256 - l); else if (h >= 0) value = (h * 256 + l); return value * this.gain; } private double getRawOutYValue() throws Exception { int l = this.readFromRegister(L3GD20_REG_R_OUT_Y_L, 0xff); int h_u2 = this.readFromRegister(L3GD20_REG_R_OUT_Y_H, 0xff); int h = BitOps.twosComplementToByte(h_u2); int value = 0; if (h < 0) value = (h * 256 - l); else if (h >= 0) value = (h * 256 + l); return value * this.gain; } private double getRawOutZValue() throws Exception { int l = this.readFromRegister(L3GD20_REG_R_OUT_Z_L, 0xff); int h_u2 = this.readFromRegister(L3GD20_REG_R_OUT_Z_H, 0xff); int h = BitOps.twosComplementToByte(h_u2); int value = 0; if (h < 0) value = (h * 256 - l); else if (h >= 0) value = (h * 256 + l); return value * this.gain; } public double[] getRawOutValues() throws Exception { return new double[] { this.getRawOutXValue(), this.getRawOutYValue(), this.getRawOutZValue() }; } public double getCalOutXValue() throws Exception { double calX = 0d; double x = this.getRawOutXValue(); if (x >= this.minX && x <= this.maxX) calX = 0d; else calX = x - this.meanX; return calX; } public double getCalOutYValue() throws Exception { double calY = 0d; double y = this.getRawOutYValue(); if (y >= this.minY && y <= this.maxY) calY = 0d; else calY = y - this.meanY; return calY; } public double getCalOutZValue() throws Exception { double calZ = 0d; double z = this.getRawOutZValue(); if (z >= this.minZ && z <= this.maxZ) calZ = 0d; else calZ = z - this.meanZ; return calZ; } public double[] getCalOutValue() throws Exception { return new double[] { this.getCalOutXValue(), this.getCalOutYValue(), this.getCalOutZValue() }; } /* * All getters and setters */ public String getFullScaleValue() throws Exception { return this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_CTRL_REG4, L3GD20_MASK_CTRL_REG4_FS, L3GD20Dictionaries.FullScaleMap); } public void setFullScaleValue(String value) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_CTRL_REG4, L3GD20_MASK_CTRL_REG4_FS, value, L3GD20Dictionaries.FullScaleMap, "FullScaleMap") ; } public String returnConfiguration() { return "To be implemented..."; } public int getDeviceId() throws Exception { return this.readFromRegister(L3GD20_REG_R_WHO_AM_I, 0xff); } public void setAxisXEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_Xen, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isAxisXEnabled() throws Exception { String enabled = this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_Xen, L3GD20Dictionaries.EnabledMap); return enabled.equals(L3GD20Dictionaries.TRUE); } public void setAxisYEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_Yen, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isAxisYEnabled() throws Exception { String enabled = this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_Yen, L3GD20Dictionaries.EnabledMap); return enabled.equals(L3GD20Dictionaries.TRUE); } public void setAxisZEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_Zen, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isAxisZEnabled() throws Exception { String enabled = this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_Zen, L3GD20Dictionaries.EnabledMap); return enabled.equals(L3GD20Dictionaries.TRUE); } public void setPowerMode(String mode) throws Exception { if (!L3GD20Dictionaries.PowerModeMap.containsKey(mode)) throw new RuntimeException("Value ["+ mode + "] not accepted for PowerMode"); if (mode.equals(L3GD20Dictionaries.POWER_DOWN)) this.writeToRegister(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_PD, 0); else if (mode.equals(L3GD20Dictionaries.SLEEP)) this.writeToRegister(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_PD | L3GD20_MASK_CTRL_REG1_Zen | L3GD20_MASK_CTRL_REG1_Yen | L3GD20_MASK_CTRL_REG1_Xen, 8); else if (mode.equals(L3GD20Dictionaries.NORMAL)) this.writeToRegister(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_PD, 1); } public String getPowerMode() throws Exception { int powermode = this.readFromRegister(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_PD | L3GD20_MASK_CTRL_REG1_Xen | L3GD20_MASK_CTRL_REG1_Yen | L3GD20_MASK_CTRL_REG1_Zen); int dictval = -1; if (!BitOps.checkBit(powermode, 3)) dictval = 0; else if (powermode == 0b1000) dictval = 1; else if (BitOps.checkBit(powermode, 3)) dictval = 2; String key = "Unknown"; for (String s : L3GD20Dictionaries.PowerModeMap.keySet()) { if (L3GD20Dictionaries.PowerModeMap.get(s) == dictval) { key = s; break; } } return key; } public void setFifoModeValue(String value) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_FIFO_CTRL_REG, L3GD20_MASK_FIFO_CTRL_REG_FM, value, L3GD20Dictionaries.FifoModeMap, "FifoModeMap") ; } public String getFifoModeValue() throws Exception { return this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_FIFO_CTRL_REG, L3GD20_MASK_FIFO_CTRL_REG_FM, L3GD20Dictionaries.FifoModeMap); } public void setDataRateAndBandwidth(int datarate, float bandwidth) throws Exception { if (!L3GD20Dictionaries.DataRateBandWidthMap.keySet().contains(datarate)) throw new RuntimeException("Data rate:[" + Integer.toString(datarate) + "] not in range of data rate values."); if (!L3GD20Dictionaries.DataRateBandWidthMap.get(datarate).keySet().contains(bandwidth)) throw new RuntimeException("Bandwidth: [" + Float.toString(bandwidth) + "] cannot be assigned to data rate: [" + Integer.toString(datarate) + "]"); int bits = L3GD20Dictionaries.DataRateBandWidthMap.get(datarate).get(bandwidth); this.writeToRegister(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_DR | L3GD20_MASK_CTRL_REG1_BW, bits); } public Number[] getDataRateAndBandwidth() throws Exception { Number dr = null, bw = null; int current = this.readFromRegister(L3GD20_REG_RW_CTRL_REG1, L3GD20_MASK_CTRL_REG1_DR | L3GD20_MASK_CTRL_REG1_BW); for (Integer drKey : L3GD20Dictionaries.DataRateBandWidthMap.keySet()) { for (Float bwKey : L3GD20Dictionaries.DataRateBandWidthMap.get(drKey).keySet()) { if (L3GD20Dictionaries.DataRateBandWidthMap.get(drKey).get(bwKey) == current) { dr = drKey; bw = bwKey; return new Number[] { dr, bw }; } } } return new Number[] { dr, bw }; } public void setFifoThresholdValue(int value) throws Exception { this.writeToRegister(L3GD20_REG_RW_FIFO_CTRL_REG, L3GD20_MASK_FIFO_CTRL_REG_WTM, value); } public int getFifoThresholdValue() throws Exception { return this.readFromRegister(L3GD20_REG_RW_FIFO_CTRL_REG, L3GD20_MASK_FIFO_CTRL_REG_WTM); } public int getFifoStoredDataLevelValue() throws Exception { return this.readFromRegister(L3GD20_REG_R_FIFO_SRC_REG, L3GD20_MASK_FIFO_SRC_REG_FSS); } public boolean isFifoEmpty() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_FIFO_SRC_REG, L3GD20_MASK_FIFO_SRC_REG_EMPTY, L3GD20Dictionaries.EnabledMap)); } public boolean isFifoFull() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_FIFO_SRC_REG, L3GD20_MASK_FIFO_SRC_REG_OVRN, L3GD20Dictionaries.EnabledMap)); } public boolean isFifoGreaterOrEqualThanWatermark() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_FIFO_SRC_REG, L3GD20_MASK_FIFO_SRC_REG_WTM, L3GD20Dictionaries.EnabledMap)); } public void setInt1CombinationValue(String value) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_ANDOR, value, L3GD20Dictionaries.AndOrMap, "AndOrMap"); } public String getInt1CombinationValue() throws Exception { return this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_ANDOR, L3GD20Dictionaries.AndOrMap); } public void setInt1LatchRequestEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_LIR, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isInt1LatchRequestEnabled() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_LIR, L3GD20Dictionaries.EnabledMap)); } public void setInt1GenerationOnZHighEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_ZHIE, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isInt1GenerationOnZHighEnabled() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_ZHIE, L3GD20Dictionaries.EnabledMap)); } public void setInt1GenerationOnZLowEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_ZLIE, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isInt1GenerationOnZLowEnabled() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_ZLIE, L3GD20Dictionaries.EnabledMap)); } public void setInt1GenerationOnYHighEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_YHIE, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isInt1GenerationOnYHighEnabled() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_YHIE, L3GD20Dictionaries.EnabledMap)); } public void setInt1GenerationOnYLowEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_YLIE, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isInt1GenerationOnYLowEnabled() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_YLIE, L3GD20Dictionaries.EnabledMap)); } public void setInt1GenerationOnXHighEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_XHIE, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isInt1GenerationOnXHighEnabled() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_XHIE, L3GD20Dictionaries.EnabledMap)); } public void setInt1GenerationOnXLowEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_XLIE, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isInt1GenerationOnXLowEnabled() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_INT1_CFG_REG, L3GD20_MASK_INT1_CFG_XLIE, L3GD20Dictionaries.EnabledMap)); } public boolean isInt1Active() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_INT1_SRC_REG, L3GD20_MASK_INT1_SRC_IA, L3GD20Dictionaries.EnabledMap)); } public boolean hasZHighEventOccured() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_INT1_SRC_REG, L3GD20_MASK_INT1_SRC_ZH, L3GD20Dictionaries.EnabledMap)); } public boolean hasZLowEventOccured() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_INT1_SRC_REG, L3GD20_MASK_INT1_SRC_ZL, L3GD20Dictionaries.EnabledMap)); } public boolean hasYHighEventOccured() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_INT1_SRC_REG, L3GD20_MASK_INT1_SRC_YH, L3GD20Dictionaries.EnabledMap)); } public boolean hasYLowEventOccured() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_INT1_SRC_REG, L3GD20_MASK_INT1_SRC_YL, L3GD20Dictionaries.EnabledMap)); } public boolean hasXHighEventOccured() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_INT1_SRC_REG, L3GD20_MASK_INT1_SRC_XH, L3GD20Dictionaries.EnabledMap)); } public boolean hasXLowEventOccured() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_R_INT1_SRC_REG, L3GD20_MASK_INT1_SRC_XL, L3GD20Dictionaries.EnabledMap)); } public void setInt1ThresholdXValue(int value) throws Exception { this.writeToRegister(L3GD20_REG_RW_INT1_THS_XH, L3GD20_MASK_INT1_THS_H, (value & 0x7f00) >> 8); this.writeToRegister(L3GD20_REG_RW_INT1_THS_XL, L3GD20_MASK_INT1_THS_L, value & 0x00ff); } public void setInt1ThresholdYValue(int value) throws Exception { this.writeToRegister(L3GD20_REG_RW_INT1_THS_YH, L3GD20_MASK_INT1_THS_H, (value & 0x7f00) >> 8); this.writeToRegister(L3GD20_REG_RW_INT1_THS_YL, L3GD20_MASK_INT1_THS_L, value & 0x00ff); } public void setInt1ThresholdZValue(int value) throws Exception { this.writeToRegister(L3GD20_REG_RW_INT1_THS_ZH, L3GD20_MASK_INT1_THS_H, (value & 0x7f00) >> 8); this.writeToRegister(L3GD20_REG_RW_INT1_THS_ZL, L3GD20_MASK_INT1_THS_L, value & 0x00ff); } public int[] getInt1Threshold_Values() throws Exception { int xh = this.readFromRegister(L3GD20_REG_RW_INT1_THS_XH, L3GD20_MASK_INT1_THS_H); int xl = this.readFromRegister(L3GD20_REG_RW_INT1_THS_XL, L3GD20_MASK_INT1_THS_L); int yh = this.readFromRegister(L3GD20_REG_RW_INT1_THS_YH, L3GD20_MASK_INT1_THS_H); int yl = this.readFromRegister(L3GD20_REG_RW_INT1_THS_YL, L3GD20_MASK_INT1_THS_L); int zh = this.readFromRegister(L3GD20_REG_RW_INT1_THS_ZH, L3GD20_MASK_INT1_THS_H); int zl = this.readFromRegister(L3GD20_REG_RW_INT1_THS_ZL, L3GD20_MASK_INT1_THS_L); return new int[] { xh * 256 + xl, yh * 256 + yl, zh * 256 + zl }; } public void setInt1DurationWaitEnabled(boolean enabled) throws Exception { this.writeToRegisterWithDictionaryCheck(L3GD20_REG_RW_INT1_DURATION, L3GD20_MASK_INT1_DURATION_WAIT, enabled?L3GD20Dictionaries.TRUE:L3GD20Dictionaries.FALSE, L3GD20Dictionaries.EnabledMap, "EnabledMap"); } public boolean isInt1DurationWaitEnabled() throws Exception { return L3GD20Dictionaries.TRUE.equals(this.readFromRegisterWithDictionaryMatch(L3GD20_REG_RW_INT1_DURATION, L3GD20_MASK_INT1_DURATION_WAIT, L3GD20Dictionaries.EnabledMap)); } public void setInt1DurationValue(int value) throws Exception { this.writeToRegister(L3GD20_REG_RW_INT1_DURATION, L3GD20_MASK_INT1_DURATION_D, value); } public int getInt1DurationValue() throws Exception { return this.readFromRegister(L3GD20_REG_RW_INT1_DURATION, L3GD20_MASK_INT1_DURATION_D); } /* * Read an unsigned byte from the I2C device */ private int readU8(int reg) throws Exception { int result = 0; try { result = this.l3dg20.read(reg); if (verbose) System.out.println("(U8) I2C: Device " + toHex(L3GD20ADDRESS) + " returned " + toHex(result) + " from reg " + toHex(reg)); } catch (Exception ex) { ex.printStackTrace(); } return result; } private static String toHex(int i) { String s = Integer.toString(i, 16).toUpperCase(); while (s.length() % 2 != 0) s = "0" + s; return "0x" + s; } private static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/AdafruitL3GD20.java
Java
mit
37,170
package adafruiti2c.sensor; import com.pi4j.system.NetworkInfo; import com.pi4j.system.SystemInfo; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import ocss.nmea.parser.StringGenerator; /* * Altitude, Pressure, Temperature */ public class AdafruitBMP180NMEA extends AdafruitBMP180 { private static void displaySysInfo() throws InterruptedException, IOException, ParseException { System.out.println("----------------------------------------------------"); System.out.println("HARDWARE INFO"); System.out.println("----------------------------------------------------"); System.out.println("Serial Number : " + SystemInfo.getSerial()); System.out.println("CPU Revision : " + SystemInfo.getCpuRevision()); System.out.println("CPU Architecture : " + SystemInfo.getCpuArchitecture()); System.out.println("CPU Part : " + SystemInfo.getCpuPart()); System.out.println("CPU Temperature : " + SystemInfo.getCpuTemperature()); System.out.println("CPU Core Voltage : " + SystemInfo.getCpuVoltage()); System.out.println("MIPS : " + SystemInfo.getBogoMIPS()); try { System.out.println("Processor : " + SystemInfo.getProcessor()); } catch (Exception ex) { System.out.println("Processor: Oops."); } System.out.println("Hardware Revision : " + SystemInfo.getRevision()); System.out.println("Is Hard Float ABI : " + SystemInfo.isHardFloatAbi()); System.out.println("Board Type : " + SystemInfo.getBoardType().name()); System.out.println("----------------------------------------------------"); System.out.println("MEMORY INFO"); System.out.println("----------------------------------------------------"); System.out.println("Total Memory : " + SystemInfo.getMemoryTotal()); System.out.println("Used Memory : " + SystemInfo.getMemoryUsed()); System.out.println("Free Memory : " + SystemInfo.getMemoryFree()); System.out.println("Shared Memory : " + SystemInfo.getMemoryShared()); System.out.println("Memory Buffers : " + SystemInfo.getMemoryBuffers()); System.out.println("Cached Memory : " + SystemInfo.getMemoryCached()); System.out.println("SDRAM_C Voltage : " + SystemInfo.getMemoryVoltageSDRam_C()); System.out.println("SDRAM_I Voltage : " + SystemInfo.getMemoryVoltageSDRam_I()); System.out.println("SDRAM_P Voltage : " + SystemInfo.getMemoryVoltageSDRam_P()); System.out.println("----------------------------------------------------"); System.out.println("OPERATING SYSTEM INFO"); System.out.println("----------------------------------------------------"); System.out.println("OS Name : " + SystemInfo.getOsName()); System.out.println("OS Version : " + SystemInfo.getOsVersion()); System.out.println("OS Architecture : " + SystemInfo.getOsArch()); System.out.println("OS Firmware Build : " + SystemInfo.getOsFirmwareBuild()); System.out.println("OS Firmware Date : " + SystemInfo.getOsFirmwareDate()); System.out.println("----------------------------------------------------"); System.out.println("JAVA ENVIRONMENT INFO"); System.out.println("----------------------------------------------------"); System.out.println("Java Vendor : " + SystemInfo.getJavaVendor()); System.out.println("Java Vendor URL : " + SystemInfo.getJavaVendorUrl()); System.out.println("Java Version : " + SystemInfo.getJavaVersion()); System.out.println("Java VM : " + SystemInfo.getJavaVirtualMachine()); System.out.println("Java Runtime : " + SystemInfo.getJavaRuntime()); System.out.println("----------------------------------------------------"); System.out.println("NETWORK INFO"); System.out.println("----------------------------------------------------"); // display some of the network information System.out.println("Hostname : " + NetworkInfo.getHostname()); for (String ipAddress : NetworkInfo.getIPAddresses()) System.out.println("IP Addresses : " + ipAddress); for (String fqdn : NetworkInfo.getFQDNs()) System.out.println("FQDN : " + fqdn); for (String nameserver : NetworkInfo.getNameservers()) System.out.println("Nameserver : " + nameserver); System.out.println("----------------------------------------------------"); System.out.println("CODEC INFO"); System.out.println("----------------------------------------------------"); System.out.println("H264 Codec Enabled: " + SystemInfo.getCodecH264Enabled()); System.out.println("MPG2 Codec Enabled: " + SystemInfo.getCodecMPG2Enabled()); System.out.println("WVC1 Codec Enabled: " + SystemInfo.getCodecWVC1Enabled()); System.out.println("----------------------------------------------------"); System.out.println("CLOCK INFO"); System.out.println("----------------------------------------------------"); System.out.println("ARM Frequency : " + SystemInfo.getClockFrequencyArm()); System.out.println("CORE Frequency : " + SystemInfo.getClockFrequencyCore()); System.out.println("H264 Frequency : " + SystemInfo.getClockFrequencyH264()); System.out.println("ISP Frequency : " + SystemInfo.getClockFrequencyISP()); System.out.println("V3D Frequency : " + SystemInfo.getClockFrequencyV3D()); System.out.println("UART Frequency : " + SystemInfo.getClockFrequencyUART()); System.out.println("PWM Frequency : " + SystemInfo.getClockFrequencyPWM()); System.out.println("EMMC Frequency : " + SystemInfo.getClockFrequencyEMMC()); System.out.println("Pixel Frequency : " + SystemInfo.getClockFrequencyPixel()); System.out.println("VEC Frequency : " + SystemInfo.getClockFrequencyVEC()); System.out.println("HDMI Frequency : " + SystemInfo.getClockFrequencyHDMI()); System.out.println("DPI Frequency : " + SystemInfo.getClockFrequencyDPI()); } private static boolean go = true; public static void main(String[] args) { final NumberFormat NF = new DecimalFormat("##00.00"); AdafruitBMP180NMEA sensor = new AdafruitBMP180NMEA(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Exiting."); go = false; } }); try { displaySysInfo(); } catch (Exception ex) { ex.printStackTrace(); } while (go) { float press = 0; float temp = 0; double alt = 0; try { press = sensor.readPressure(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } sensor.setStandardSeaLevelPressure((int)press); // As we ARE at the sea level (in San Francisco). try { alt = sensor.readAltitude(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { temp = sensor.readTemperature(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } String nmeaMMB = StringGenerator.generateMMB("II", (press / 100)); String nmeaMTA = StringGenerator.generateMTA("II", temp); System.out.println(NF.format(press / 100) + " hPa " + nmeaMMB); System.out.println(NF.format(temp) + " C " + nmeaMTA); // System.out.println("Temperature: " + NF.format(temp) + " C"); // System.out.println("Pressure : " + NF.format(press / 100) + " hPa"); // System.out.println("Altitude : " + NF.format(alt) + " m"); waitfor(1000L); } System.out.println("Bye..."); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/AdafruitBMP180NMEA.java
Java
mit
7,927
package adafruiti2c.sensor; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import com.pi4j.system.SystemInfo; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; /* * Temperature */ public class AdafruitMCP9808 { // This next addresses is returned by "sudo i2cdetect -y 1". private final static int MCP9808_I2CADDR_DEFAULT = 0x18; // Registers private final static int MCP9808_REG_CONFIG = 0x01; private final static int MCP9808_REG_UPPER_TEMP = 0x02; private final static int MCP9808_REG_LOWER_TEMP = 0x03; private final static int MCP9808_REG_CRIT_TEMP = 0x04; private final static int MCP9808_REG_AMBIENT_TEMP = 0x05; private final static int MCP9808_REG_MANUF_ID = 0x06; private final static int MCP9808_REG_DEVICE_ID = 0x07; // Configuration register values. private final static int MCP9808_REG_CONFIG_SHUTDOWN = 0x0100; private final static int MCP9808_REG_CONFIG_CRITLOCKED = 0x0080; private final static int MCP9808_REG_CONFIG_WINLOCKED = 0x0040; private final static int MCP9808_REG_CONFIG_INTCLR = 0x0020; private final static int MCP9808_REG_CONFIG_ALERTSTAT = 0x0010; private final static int MCP9808_REG_CONFIG_ALERTCTRL = 0x0008; private final static int MCP9808_REG_CONFIG_ALERTSEL = 0x0002; private final static int MCP9808_REG_CONFIG_ALERTPOL = 0x0002; private final static int MCP9808_REG_CONFIG_ALERTMODE = 0x0001; private static boolean verbose = false; private I2CBus bus; private I2CDevice mcp9808; public AdafruitMCP9808() { this(MCP9808_I2CADDR_DEFAULT); } public AdafruitMCP9808(int address) { try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself mcp9808 = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); } catch (IOException e) { System.err.println(e.getMessage()); } } public int readU16BE(int register) throws Exception { final int TWO = 2; byte[] bb = new byte[TWO]; int nbr = this.mcp9808.read(register, bb, 0, TWO); if (nbr != TWO) throw new Exception("Cannot read 2 bytes from " + lpad(Integer.toHexString(register), "0", 2)); if (verbose) System.out.println("I2C: 0x" + lpad(Integer.toHexString(bb[0]), "0", 2) + lpad(Integer.toHexString(bb[1]), "0", 2)); return ((bb[0] & 0xFF) << 8) + (bb[1] & 0xFF); } private boolean init() throws Exception { int mid = 0, did = 0; try { mid = readU16BE(MCP9808_REG_MANUF_ID); did = readU16BE(MCP9808_REG_DEVICE_ID); } catch (Exception e) { throw e; } if (verbose) System.out.println("I2C: MID 0x" + lpad(Integer.toHexString(mid), "0", 4) + " (expected 0x0054)" + " DID 0x" + lpad(Integer.toHexString(did), "0", 4) + " (expected 0x0400)"); return (mid == 0x0054 && did == 0x0400); } public float readCelciusTemp() throws Exception { int raw = readU16BE(MCP9808_REG_AMBIENT_TEMP); float temp = raw & 0x0FFF; temp /= 16.0; if ((raw & 0x1000) != 0x0) temp -= 256; if (verbose) System.out.println("DBG: C Temp: " + lpad(Integer.toHexString(raw & 0xFFFF), "0", 4) + ", " + temp); return temp; } protected static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } private static String lpad(String s, String with, int len) { String str = s; while (str.length() < len) str = with + str; return str; } private final static NumberFormat NF = new DecimalFormat("##00.000"); public static void main(String[] args) { System.out.println("MCP9808 Demo"); AdafruitMCP9808 sensor = new AdafruitMCP9808(); try { boolean ok = sensor.init(); if (!ok) System.out.println("Warning, init failed. Expect weird results..."); } catch (Exception ex) { ex.printStackTrace(); } for (int i=0; i<10; i++) { float temp = 0; try { temp = sensor.readCelciusTemp(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); System.exit(1); } System.out.println("Temperature: " + NF.format(temp) + " C"); waitfor(1000); } // Bonus : CPU Temperature try { System.out.println("CPU Temperature : " + SystemInfo.getCpuTemperature()); System.out.println("CPU Core Voltage : " + SystemInfo.getCpuVoltage()); } catch (InterruptedException ie) { ie.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/AdafruitMCP9808.java
Java
mit
5,021
package adafruiti2c.sensor.main; import adafruiti2c.sensor.AdafruitTCS34725; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import adafruiti2c.sensor.utils.PWMPin; public class SampleTCS34725PWMMain { private static boolean go = true; public static void main(String[] args) throws Exception { int colorThreshold = 4000; if (args.length > 0) try { colorThreshold = Integer.parseInt(args[0]); } catch (NumberFormatException nfe) { System.err.println(nfe.toString()); } final AdafruitTCS34725 sensor = new AdafruitTCS34725(AdafruitTCS34725.TCS34725_INTEGRATIONTIME_50MS, AdafruitTCS34725.TCS34725_GAIN_4X); // Setup output pins here for the 3 color led final GpioController gpio = GpioFactory.getInstance(); final PWMPin greenPin = new PWMPin(RaspiPin.GPIO_00, "green", PinState.LOW); final PWMPin bluePin = new PWMPin(RaspiPin.GPIO_01, "blue", PinState.LOW); final PWMPin redPin = new PWMPin(RaspiPin.GPIO_02, "red", PinState.LOW); Thread.sleep(1000); greenPin.emitPWM(0); bluePin.emitPWM(0); redPin.emitPWM(0); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { go = false; redPin.emitPWM(0); greenPin.emitPWM(0); bluePin.emitPWM(0); gpio.shutdown(); System.out.println("\nBye"); } }); // Main loop while (go) { sensor.setInterrupt(false); // turn led on try { Thread.sleep(60); } catch (InterruptedException ie) {} // Takes 50ms to read, see above AdafruitTCS34725.TCSColor color = sensor.getRawData(); sensor.setInterrupt(true); // turn led off int r = color.getR(), g = color.getG(), b = color.getB(); int greenVol = 0, blueVol = 9, redVol = 0; // Display the color on the 3-color led accordingly System.out.println("Read color R:" + r + " G:" + g + " B:" + b); // Send to 3-color led. The output is digital!! Not analog. if (r > colorThreshold || g > colorThreshold || b > colorThreshold) { // This calculation deserves improvements redVol = Math.max(Math.min((int)((r - colorThreshold) / 100), 100), 0); greenVol = Math.max(Math.min((int)((g - colorThreshold) / 100), 100), 0); blueVol = Math.max(Math.min((int)((b - colorThreshold) / 100), 100), 0); greenPin.adjustPWMVolume(greenVol); bluePin.adjustPWMVolume(blueVol); redPin.adjustPWMVolume(redVol); System.out.println(" writing (" + redVol + ", " + greenVol + ", " + blueVol + ")"); } else { redPin.low(); greenPin.low(); bluePin.low(); } } System.out.println("Exiting. Thanks."); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/main/SampleTCS34725PWMMain.java
Java
mit
3,346
package adafruiti2c.sensor.main; import adafruiti2c.sensor.AdafruitL3GD20; import adafruiti2c.sensor.listener.SensorL3GD20Context; import adafruiti2c.sensor.utils.L3GD20Dictionaries; /* * Read real data, * and broadcast to a listener */ public class SampleL3GD20RealReader { private boolean go = true; private AdafruitL3GD20 sensor; private double refX = 0, refY = 0, refZ = 0; public SampleL3GD20RealReader() throws Exception { sensor = new AdafruitL3GD20(); sensor.setPowerMode(L3GD20Dictionaries.NORMAL); sensor.setFullScaleValue(L3GD20Dictionaries._250_DPS); sensor.setAxisXEnabled(true); sensor.setAxisYEnabled(true); sensor.setAxisZEnabled(true); sensor.init(); sensor.calibrate(); } private final static int MIN_MOVE = 10; public void start() throws Exception { long wait = 20L; double x = 0, y = 0, z = 0; while (go) { double[] data = sensor.getCalOutValue(); x = data[0]; y = data[1]; z = data[2]; // Broadcast if needed if (Math.abs(x - refX) > MIN_MOVE || Math.abs(y - refY) > MIN_MOVE || Math.abs(z - refZ) > MIN_MOVE) { // System.out.println("X:" + refX + " -> " + x); // System.out.println("Y:" + refY + " -> " + y); // System.out.println("Z:" + refZ + " -> " + z); refX = x; refY = y; refZ = z; SensorL3GD20Context.getInstance().fireMotionDetected(x, y, z); } // System.out.printf("X:%.2f, Y:%.2f, Z:%.2f%n", x, y, z); try { Thread.sleep(wait); } catch (InterruptedException ex) {} } } public void stop() { this.go = false; } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/main/SampleL3GD20RealReader.java
Java
mit
1,654
package adafruiti2c.sensor.main; import adafruiti2c.sensor.AdafruitVCNL4000; import com.pi4j.system.SystemInfo; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; public class VCNL4000ProximityWithSound { private static boolean go = true; private final static int MIN_AMBIENT = 0; private final static int MAX_AMBIENT = 5500; public final static float SAMPLE_RATE = 8000f; public static void tone(int hz, int msecs) throws LineUnavailableException { tone(hz, msecs, 1.0); } public static void tone(int hz, int msecs, double vol) throws LineUnavailableException { byte[] buf = new byte[1]; AudioFormat af = new AudioFormat(SAMPLE_RATE, // sampleRate 8, // sampleSizeInBits 1, // channels true, // signed false); // bigEndian SourceDataLine sdl = AudioSystem.getSourceDataLine(af); sdl.open(af); sdl.start(); for (int i = 0; i < msecs * 8; i++) { double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI; buf[0] = (byte) (Math.sin(angle) * 127.0 * vol); sdl.write(buf, 0, 1); } sdl.drain(); sdl.stop(); sdl.close(); } public static void main(String[] args) throws Exception { AdafruitVCNL4000 sensor = new AdafruitVCNL4000(); int prox = 0; int ambient = 0; // Bonus : CPU Temperature try { System.out.println("CPU Temperature : " + SystemInfo.getCpuTemperature()); System.out.println("CPU Core Voltage : " + SystemInfo.getCpuVoltage()); } catch (InterruptedException ie) { ie.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } final BeepThread beeper = new BeepThread(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { go = false; beeper.stopBeeping(); System.out.println("\nBye"); } }); System.out.println("-- Ready --"); beeper.start(); while (go) // && i++ < 5) { try { // prox = sensor.readProximity(); int[] data = sensor.readAmbientProximity(); prox = data[AdafruitVCNL4000.PROXIMITY_INDEX]; ambient = data[AdafruitVCNL4000.AMBIENT_INDEX]; } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } System.out.println("Ambient:" + ambient + ", Proximity: " + prox); // + " unit?"); int amb = 100 - Math.min((int)Math.round(100f * ((float)ambient / (float)(MAX_AMBIENT - MIN_AMBIENT))), 100); beeper.setAmbient(amb); try { Thread.sleep(100L); } catch (InterruptedException ex) { System.err.println(ex.toString()); } } } private static class BeepThread extends Thread { private int amb = 0; // 0 - 100 0: far, 100:Cannot be closer private boolean go = true; public void setAmbient(int amb) { this.amb = amb; } public void run() { while (go) { try { tone(1000 + (10 * amb), 100); Thread.sleep(550 - (5 * amb)); } catch (Exception ex) { ex.printStackTrace(); } } } public void stopBeeping() { this.go = false; } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/main/VCNL4000ProximityWithSound.java
Java
mit
3,878
package adafruiti2c.sensor.main; import adafruiti2c.sensor.listener.AdafruitBMP180Listener; import adafruiti2c.sensor.nmea.AdafruitBMP180Reader; import adafruiti2c.sensor.listener.SensorNMEAContext; import ocss.nmea.api.NMEAEvent; /* * Uses its own listeners, defined in this project. * @see AdafruitBMP180Listener * @see SensorNMEAContext */ public class SampleBMP180Main { private final AdafruitBMP180Reader sensorReader = new AdafruitBMP180Reader(); public SampleBMP180Main() { SensorNMEAContext.getInstance().addReaderListener(new AdafruitBMP180Listener() { public void dataDetected(NMEAEvent e) { System.out.println(e.getContent()); } }); } public void start() { System.out.println("Starting reader."); sensorReader.startReading(); } public void stop() { sensorReader.stopReading(); synchronized (Thread.currentThread()) { System.out.println("... notifying main."); Thread.currentThread().notify(); } } public static void main(String[] args) { final SampleBMP180Main reader = new SampleBMP180Main(); Thread worker = new Thread("Reader") { public void run() { reader.start(); } }; Runtime.getRuntime().addShutdownHook(new Thread("Hook") { public void run() { System.out.println(); reader.stop(); // Wait for everything to shutdown, for the example... try { Thread.sleep(2000L); } catch (InterruptedException ie) {} } }); worker.start(); synchronized (Thread.currentThread()) { try { Thread.currentThread().wait(); } catch (InterruptedException ie) { ie.printStackTrace(); } } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/main/SampleBMP180Main.java
Java
mit
1,836
package adafruiti2c.sensor.main; import adafruiti2c.sensor.AdafruitTCS34725; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; public class SampleTCS34725Main { private static boolean go = true; public static void main(String[] args) throws Exception { int colorThreshold = 4000; if (args.length > 0) try { colorThreshold = Integer.parseInt(args[0]); } catch (NumberFormatException nfe) { System.err.println(nfe.toString()); } final AdafruitTCS34725 sensor = new AdafruitTCS34725(AdafruitTCS34725.TCS34725_INTEGRATIONTIME_50MS, AdafruitTCS34725.TCS34725_GAIN_4X); // Setup output pins here for the 3 color led final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput greenPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "green", PinState.LOW); final GpioPinDigitalOutput bluePin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "blue", PinState.LOW); final GpioPinDigitalOutput redPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "red", PinState.LOW); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { go = false; System.out.println("\nBye"); } }); // Main loop while (go) { sensor.setInterrupt(false); // turn led on try { Thread.sleep(60); } catch (InterruptedException ie) {} // Takes 50ms to read, see above AdafruitTCS34725.TCSColor color = sensor.getRawData(); sensor.setInterrupt(true); // turn led off int r = color.getR(), g = color.getG(), b = color.getB(); // Display the color on the 3-color led accordingly System.out.println("Read color R:" + r + " G:" + g + " B:" + b); // Send to 3-color led. The output is digital!! Not analog. // Use a DAC: https://learn.adafruit.com/mcp4725-12-bit-dac-with-raspberry-pi/overview // For now, take the biggest one if (r > colorThreshold || g > colorThreshold || b > colorThreshold) { int max = Math.max(r, g); max = Math.max(max, b); if (max == r) { System.out.println("Red!"); redPin.high(); } else redPin.low(); if (max == g) { System.out.println("Green!"); greenPin.high(); } else greenPin.low(); if (max == b) { System.out.println("Blue!"); bluePin.high(); } else bluePin.low(); } else { redPin.low(); greenPin.low(); bluePin.low(); } } redPin.low(); greenPin.low(); bluePin.low(); gpio.shutdown(); System.out.println("Exiting. Thanks."); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/main/SampleTCS34725Main.java
Java
mit
3,233
package adafruiti2c.sensor.main; import adafruiti2c.sensor.AdafruitVCNL4000; import com.pi4j.system.SystemInfo; import java.io.IOException; import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.LineUnavailableException; import javax.sound.sampled.SourceDataLine; import sevensegdisplay.SevenSegment; public class VCNL4000ProximityWithDisplay { private static boolean go = true; private final static int MIN_AMBIENT = 0; private final static int MAX_AMBIENT = 5500; private static AdafruitVCNL4000 sensor; private static SevenSegment display; public static void main(String[] args) throws Exception { sensor = new AdafruitVCNL4000(); display = new SevenSegment(0x70, true); int prox = 0; int ambient = 0; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { go = false; try { display.clear(); } catch (IOException ioe) { ioe.printStackTrace(); } System.out.println("\nBye"); } }); while (go) // && i++ < 5) { try { // prox = sensor.readProximity(); int[] data = sensor.readAmbientProximity(); prox = data[AdafruitVCNL4000.PROXIMITY_INDEX]; ambient = data[AdafruitVCNL4000.AMBIENT_INDEX]; } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } // System.out.println("Ambient:" + ambient + ", Proximity: " + prox); // + " unit?"); int amb = /* 100 - */ Math.min((int)Math.round(100f * ((float)ambient / (float)(MAX_AMBIENT - MIN_AMBIENT))), 100); System.out.println("Ambient:" + ambient + ", Proximity: " + prox + ", " + amb); // Notice the digit index: 0, 1, 3, 4. 2 is the column ":" int one = amb / 1000; int two = (amb - (one * 1000)) / 100; int three = (amb - (one * 1000) - (two * 100)) / 10; int four = amb % 10; // System.out.println(" --> " + proxPercent + " : " + one + " " + two + "." + three + " " + four); if (one > 0) display.writeDigit(0, one); else display.writeDigitRaw(0, " "); if (two > 0 || one > 0) display.writeDigit(1, two); else display.writeDigitRaw(1, " "); if (one > 0 || two > 0 || three > 0) display.writeDigit(3, three); else display.writeDigitRaw(3, " "); display.writeDigit(4, four); try { Thread.sleep(100L); } catch (InterruptedException ex) { System.err.println(ex.toString()); } } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/main/VCNL4000ProximityWithDisplay.java
Java
mit
2,900
package adafruiti2c.sensor.main; import adafruiti2c.sensor.nmea.AdafruitBMP180Reader; import nmea.server.ctx.NMEAContext; import ocss.nmea.api.NMEAEvent; import ocss.nmea.api.NMEAListener; /* * This one uses the listeners already existing in OlivSoft * (namely the NMEA Console) * * @see AdafruitBMP180Reader * @see NMEAContext */ public class SampleBMP180NMEAMain { private final AdafruitBMP180Reader sensorReader = new AdafruitBMP180Reader(); public SampleBMP180NMEAMain() { NMEAContext.getInstance().addNMEAListener(new NMEAListener() { @Override public void dataDetected(NMEAEvent event) { System.out.println("Pure NMEA:" + event.getContent()); } }); } public void start() { sensorReader.startReading(); } public void stop() { sensorReader.stopReading(); synchronized (Thread.currentThread()) { System.out.println("... notifying main."); Thread.currentThread().notify(); } } public static void main(String[] args) { final SampleBMP180NMEAMain reader = new SampleBMP180NMEAMain(); Thread worker = new Thread("Reader") { public void run() { reader.start(); } }; Runtime.getRuntime().addShutdownHook(new Thread("Hook") { public void run() { System.out.println(); reader.stop(); // Wait for everything to shutdown, for the example... try { Thread.sleep(2000L); } catch (InterruptedException ie) { ie.printStackTrace(); } } }); worker.start(); synchronized (Thread.currentThread()) { try { Thread.currentThread().wait(); } catch (InterruptedException ie) { ie.printStackTrace(); } } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/main/SampleBMP180NMEAMain.java
Java
mit
1,830
package adafruiti2c.sensor.main; import adafruiti2c.sensor.AdafruitL3GD20; import adafruiti2c.sensor.utils.L3GD20Dictionaries; /* * Read real data */ public class SampleL3GD20ReadRealData { private boolean go = true; public SampleL3GD20ReadRealData() throws Exception { AdafruitL3GD20 sensor = new AdafruitL3GD20(); sensor.setPowerMode(L3GD20Dictionaries.NORMAL); sensor.setFullScaleValue(L3GD20Dictionaries._250_DPS); sensor.setAxisXEnabled(true); sensor.setAxisYEnabled(true); sensor.setAxisZEnabled(true); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { go = false; System.out.println("\nBye."); } }); sensor.init(); sensor.calibrate(); long wait = 20L; double x = 0, y = 0, z = 0; while (go) { double[] data = sensor.getCalOutValue(); x = data[0]; y = data[1]; z = data[2]; // x += (data[0] * wait); // y += (data[1] * wait); // z += (data[2] * wait); System.out.printf("X:%.2f, Y:%.2f, Z:%.2f%n", x, y, z); try { Thread.sleep(wait); } catch (InterruptedException ex) {} } } public static void main(String[] args) throws Exception { new SampleL3GD20ReadRealData(); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/main/SampleL3GD20ReadRealData.java
Java
mit
1,542
package adafruiti2c.sensor.main; import adafruiti2c.sensor.AdafruitL3GD20; import adafruiti2c.sensor.utils.L3GD20Dictionaries; /* * Read real data */ public class SampleL3GD20ReadRawlData { private boolean go = true; public SampleL3GD20ReadRawlData() throws Exception { AdafruitL3GD20 sensor = new AdafruitL3GD20(); sensor.setPowerMode(L3GD20Dictionaries.NORMAL); sensor.setAxisXEnabled(false); sensor.setAxisYEnabled(false); sensor.setAxisZEnabled(true); sensor.setDataRateAndBandwidth(95, 12.5f); sensor.setFifoModeValue(L3GD20Dictionaries.BYPASS); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { go = false; System.out.println("\nBye."); } }); // sensor.init(); sensor.calibrateZ(); while (go) // TODO Put a Tmax { while (sensor.getAxisDataAvailableValue()[2] == 0) try { Thread.sleep(1L); } catch (InterruptedException ex) {} double z = sensor.getCalOutZValue(); System.out.printf("Z:%.2f%n", z); } } public static void main(String[] args) throws Exception { SampleL3GD20ReadRawlData main = new SampleL3GD20ReadRawlData(); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/main/SampleL3GD20ReadRawlData.java
Java
mit
1,482
package adafruiti2c.sensor.listener; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import ocss.nmea.api.NMEAEvent; public class SensorNMEAContext implements Serializable { private static SensorNMEAContext context = null; private transient List<AdafruitBMP180Listener> sensorReaderListeners = null; private SensorNMEAContext() { sensorReaderListeners = new ArrayList<AdafruitBMP180Listener>(); } public static synchronized SensorNMEAContext getInstance() { if (context == null) context = new SensorNMEAContext(); return context; } public List<AdafruitBMP180Listener> getReaderListeners() { return sensorReaderListeners; } public synchronized void addReaderListener(AdafruitBMP180Listener l) { if (!sensorReaderListeners.contains(l)) { sensorReaderListeners.add(l); } } public synchronized void removeReaderListener(AdafruitBMP180Listener l) { sensorReaderListeners.remove(l); } public void fireDataDetected(NMEAEvent event) { for (AdafruitBMP180Listener l : sensorReaderListeners) { l.dataDetected(event); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/listener/SensorNMEAContext.java
Java
mit
1,169
package adafruiti2c.sensor.listener; import java.util.EventListener; public abstract class AdafruitLSM303Listener implements EventListener { public void dataDetected(int accX, int accY, int accZ, int magX, int magY, int magZ, float heading) {} public void close() {} }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/listener/AdafruitLSM303Listener.java
Java
mit
275
package adafruiti2c.sensor.listener; import java.util.EventListener; public abstract class AdafruitL3GD20Listener implements EventListener { public void motionDetected(double x, double y, double z) {} public void close() {} }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/listener/AdafruitL3GD20Listener.java
Java
mit
232
package adafruiti2c.sensor.listener; import java.util.EventListener; import ocss.nmea.api.NMEAEvent; public abstract class AdafruitBMP180Listener implements EventListener { public void dataDetected(NMEAEvent e) {} }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/listener/AdafruitBMP180Listener.java
Java
mit
220
package adafruiti2c.sensor.listener; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class SensorLSM303Context implements Serializable { private static SensorLSM303Context context = null; private transient List<AdafruitLSM303Listener> sensorReaderListeners = null; private SensorLSM303Context() { sensorReaderListeners = new ArrayList<AdafruitLSM303Listener>(); } public static synchronized SensorLSM303Context getInstance() { if (context == null) context = new SensorLSM303Context(); return context; } public List<AdafruitLSM303Listener> getReaderListeners() { return sensorReaderListeners; } public synchronized void addReaderListener(AdafruitLSM303Listener l) { if (!sensorReaderListeners.contains(l)) { sensorReaderListeners.add(l); } } public synchronized void removeReaderListener(AdafruitL3GD20Listener l) { sensorReaderListeners.remove(l); } public void fireDataDetected(int accX, int accY, int accZ, int magX, int magY, int magZ, float heading) { for (AdafruitLSM303Listener l : sensorReaderListeners) { l.dataDetected(accX, accY, accZ, magX, magY, magZ, heading); } } public void fireClose() { for (AdafruitLSM303Listener l : sensorReaderListeners) { l.close(); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/listener/SensorLSM303Context.java
Java
mit
1,365
package adafruiti2c.sensor.listener; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class SensorL3GD20Context implements Serializable { private static SensorL3GD20Context context = null; private transient List<AdafruitL3GD20Listener> sensorReaderListeners = null; private SensorL3GD20Context() { sensorReaderListeners = new ArrayList<AdafruitL3GD20Listener>(); } public static synchronized SensorL3GD20Context getInstance() { if (context == null) context = new SensorL3GD20Context(); return context; } public List<AdafruitL3GD20Listener> getReaderListeners() { return sensorReaderListeners; } public synchronized void addReaderListener(AdafruitL3GD20Listener l) { if (!sensorReaderListeners.contains(l)) { sensorReaderListeners.add(l); } } public synchronized void removeReaderListener(AdafruitL3GD20Listener l) { sensorReaderListeners.remove(l); } public void fireMotionDetected(double x, double y, double z) { for (AdafruitL3GD20Listener l : sensorReaderListeners) { l.motionDetected(x, y, z); } } public void fireClose() { for (AdafruitL3GD20Listener l : sensorReaderListeners) { l.close(); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/listener/SensorL3GD20Context.java
Java
mit
1,288
package adafruiti2c.sensor; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; /* * Light Sensor (I2C) */ public class AdafruitTSL2561 { public final static int LITTLE_ENDIAN = 0; public final static int BIG_ENDIAN = 1; private final static int TSL2561_ENDIANNESS = BIG_ENDIAN; public final static int TSL2561_ADDRESS = 0x39; public final static int TSL2561_ADDRESS_LOW = 0x29; public final static int TSL2561_ADDRESS_FLOAT = 0x39; public final static int TSL2561_ADDRESS_HIGH = 0x49; public final static int TSL2561_COMMAND_BIT = 0x80; public final static int TSL2561_WORD_BIT = 0x20; public final static int TSL2561_CONTROL_POWERON = 0x03; public final static int TSL2561_CONTROL_POWEROFF = 0x00; public final static int TSL2561_REGISTER_CONTROL = 0x00; public final static int TSL2561_REGISTER_TIMING = 0x01; public final static int TSL2561_REGISTER_CHAN0_LOW = 0x0C; public final static int TSL2561_REGISTER_CHAN0_HIGH = 0x0D; public final static int TSL2561_REGISTER_CHAN1_LOW = 0x0E; public final static int TSL2561_REGISTER_CHAN1_HIGH = 0x0F; public final static int TSL2561_REGISTER_ID = 0x0A; public final static int TSL2561_GAIN_1X = 0x00; public final static int TSL2561_GAIN_16X = 0x10; public final static int TSL2561_INTEGRATIONTIME_13MS = 0x00; // rather 13.7ms public final static int TSL2561_INTEGRATIONTIME_101MS = 0x01; public final static int TSL2561_INTEGRATIONTIME_402MS = 0x02; public final static double TSL2561_LUX_K1C = 0.130; // (0x0043) // 0.130 * 2^RATIO_SCALE public final static double TSL2561_LUX_B1C = 0.0315; // (0x0204) // 0.0315 * 2^LUX_SCALE public final static double TSL2561_LUX_M1C = 0.0262; // (0x01ad) // 0.0262 * 2^LUX_SCALE public final static double TSL2561_LUX_K2C = 0.260; // (0x0085) // 0.260 * 2^RATIO_SCALE public final static double TSL2561_LUX_B2C = 0.0337; // (0x0228) // 0.0337 * 2^LUX_SCALE public final static double TSL2561_LUX_M2C = 0.0430; // (0x02c1) // 0.0430 * 2^LUX_SCALE public final static double TSL2561_LUX_K3C = 0.390; // (0x00c8) // 0.390 * 2^RATIO_SCALE public final static double TSL2561_LUX_B3C = 0.0363; // (0x0253) // 0.0363 * 2^LUX_SCALE public final static double TSL2561_LUX_M3C = 0.0529; // (0x0363) // 0.0529 * 2^LUX_SCALE public final static double TSL2561_LUX_K4C = 0.520; // (0x010a) // 0.520 * 2^RATIO_SCALE public final static double TSL2561_LUX_B4C = 0.0392; // (0x0282) // 0.0392 * 2^LUX_SCALE public final static double TSL2561_LUX_M4C = 0.0605; // (0x03df) // 0.0605 * 2^LUX_SCALE public final static double TSL2561_LUX_K5C = 0.65; // (0x014d) // 0.65 * 2^RATIO_SCALE public final static double TSL2561_LUX_B5C = 0.0229; // (0x0177) // 0.0229 * 2^LUX_SCALE public final static double TSL2561_LUX_M5C = 0.0291; // (0x01dd) // 0.0291 * 2^LUX_SCALE public final static double TSL2561_LUX_K6C = 0.80; // (0x019a) // 0.80 * 2^RATIO_SCALE public final static double TSL2561_LUX_B6C = 0.0157; // (0x0101) // 0.0157 * 2^LUX_SCALE public final static double TSL2561_LUX_M6C = 0.0180; // (0x0127) // 0.0180 * 2^LUX_SCALE public final static double TSL2561_LUX_K7C = 1.3; // (0x029a) // 1.3 * 2^RATIO_SCALE public final static double TSL2561_LUX_B7C = 0.00338; // (0x0037) // 0.00338 * 2^LUX_SCALE public final static double TSL2561_LUX_M7C = 0.00260; // (0x002b) // 0.00260 * 2^LUX_SCALE public final static double TSL2561_LUX_K8C = 1.3; // (0x029a) // 1.3 * 2^RATIO_SCALE public final static double TSL2561_LUX_B8C = 0.000; // (0x0000) // 0.000 * 2^LUX_SCALE public final static double TSL2561_LUX_M8C = 0.000; // (0x0000) // 0.000 * 2^LUX_SCALE private static boolean verbose = false; private int gain = TSL2561_GAIN_1X; private int integration = TSL2561_INTEGRATIONTIME_402MS; private long pause = 800L; private I2CBus bus; private I2CDevice tsl2561; public AdafruitTSL2561() { this(TSL2561_ADDRESS); } public AdafruitTSL2561(int address) { try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends on the RasPI version if (verbose) { System.out.println("Connected to bus. OK."); } // Get device itself tsl2561 = bus.getDevice(address); if (verbose) { System.out.println("Connected to device. OK."); } turnOn(); } catch (IOException e) { System.err.println(e.getMessage()); } } public void turnOn() throws IOException { tsl2561.write(TSL2561_COMMAND_BIT, (byte)TSL2561_CONTROL_POWERON); } public void turnOff() throws IOException { tsl2561.write(TSL2561_COMMAND_BIT, (byte)TSL2561_CONTROL_POWEROFF); } public void setGain() throws IOException { setGain(TSL2561_GAIN_1X); } public void setGain(int gain) throws IOException { setGain(gain, TSL2561_INTEGRATIONTIME_402MS); } public void setGain(int gain, int integration) throws IOException { if (gain != TSL2561_GAIN_1X && gain != TSL2561_GAIN_16X) throw new IllegalArgumentException("Bad gain value [" + gain + "]"); if (gain != this.gain || integration != this.integration) { tsl2561.write(TSL2561_COMMAND_BIT | TSL2561_REGISTER_TIMING, (byte)(gain | integration)); if (verbose) System.out.println("Setting low gain"); this.gain = gain; this.integration = integration; waitfor(pause); // pause for integration (pause must be bigger than integration time) } } /* * Reads visible+IR diode from the I2C device */ public int readFull() throws Exception { int reg = TSL2561_COMMAND_BIT | TSL2561_REGISTER_CHAN0_LOW; return readU16(reg); } /* * Reads IR only diode from the I2C device */ public int readIR() throws Exception { int reg = TSL2561_COMMAND_BIT | TSL2561_REGISTER_CHAN1_LOW; return readU16(reg); } /* * Device lux range 0.1 - 40,000+ * see https://learn.adafruit.com/tsl2561/overview */ public double readLux() throws Exception { int ambient = this.readFull(); int ir = this.readIR(); if (ambient >= 0xffff || ir >= 0xffff) // value(s) exeed(s) datarange throw new RuntimeException("Gain too high. Values exceed range."); if (false && this.gain == TSL2561_GAIN_1X) { ambient *= 16; // scale 1x to 16x ir *= 16; // scale 1x to 16x } double ratio = (ir / (float)ambient); if (verbose) { System.out.println("IR Result:" + ir); System.out.println("Ambient Result:" + ambient); } /* * For the values below, see https://github.com/adafruit/Adafruit_TSL2561/blob/master/Adafruit_TSL2561_U.h */ double lux = 0d; if ((ratio >= 0) && (ratio <= TSL2561_LUX_K4C)) lux = (TSL2561_LUX_B1C * ambient) - (0.0593 * ambient * (Math.pow(ratio, 1.4))); else if (ratio <= TSL2561_LUX_K5C) lux = (TSL2561_LUX_B5C * ambient) - (TSL2561_LUX_M5C * ir); else if (ratio <= TSL2561_LUX_K6C) lux = (TSL2561_LUX_B6C * ambient) - (TSL2561_LUX_M6C * ir); else if (ratio <= TSL2561_LUX_K7C) lux = (TSL2561_LUX_B7C * ambient) - (TSL2561_LUX_M7C * ir); else if (ratio > TSL2561_LUX_K8C) lux = 0; return lux; } /* * Read an unsigned byte from the I2C device */ private int readU8(int reg) throws Exception { int result = 0; try { result = this.tsl2561.read(reg); if (verbose) System.out.println("(U8) I2C: Device " + toHex(TSL2561_ADDRESS) + " returned " + toHex(result) + " from reg " + toHex(reg)); } catch (Exception ex) { ex.printStackTrace(); } return result; } private int readU16(int register) throws Exception { int lo = this.readU8(register); int hi = this.readU8(register + 1); int result = (TSL2561_ENDIANNESS == BIG_ENDIAN) ? (hi << 8) + lo : (lo << 8) + hi; // Big Endian if (verbose) System.out.println("(U16) I2C: Device " + toHex(TSL2561_ADDRESS) + " returned " + toHex(result) + " from reg " + toHex(register)); return result; } private static String toHex(int i) { String s = Integer.toString(i, 16).toUpperCase(); while (s.length() % 2 != 0) s = "0" + s; return "0x" + s; } private static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } public static void main(String[] args) { final NumberFormat NF = new DecimalFormat("##00.00"); verbose = false; AdafruitTSL2561 sensor = new AdafruitTSL2561(); double lux = 0; try { for (int i=0; i<100; i++) { lux = sensor.readLux(); System.out.println("Lux: " + NF.format(lux) + " Lux"); waitfor(500L); } sensor.turnOff(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/AdafruitTSL2561.java
Java
mit
9,231
package adafruiti2c.sensor.utils; import java.util.HashMap; import java.util.Map; public class L3GD20Dictionaries { public final static String POWER_DOWN = "Power-down"; public final static String SLEEP = "Sleep"; public final static String NORMAL = "Normal"; public final static Map<String, Byte> PowerModeMap = new HashMap<String, Byte>(); static { PowerModeMap.put(POWER_DOWN, (byte)0); PowerModeMap.put(SLEEP, (byte)1); PowerModeMap.put(NORMAL, (byte)2); } public final static String FALSE = "false"; public final static String TRUE = "true"; public final static Map<String, Byte> EnabledMap = new HashMap<String, Byte>(); static { EnabledMap.put(FALSE, (byte)0); EnabledMap.put(TRUE, (byte)1); } public final static String HIGH = "High"; public final static String LOW = "Low"; public final static Map<String, Byte> LevelMap = new HashMap<String, Byte>(); static { LevelMap.put(HIGH, (byte)0); LevelMap.put(LOW, (byte)1); } public final static String PUSH_PULL = "Push-pull"; public final static String OPEN_DRAIN = "Open drain"; public final static Map<String, Byte> OutputMap = new HashMap<String, Byte>(); static { OutputMap.put(PUSH_PULL, (byte)0); OutputMap.put(OPEN_DRAIN, (byte)1); } public final static String _4_WIRE = "4-wire"; public final static String _3_WIRE = "3-wire"; public final static Map<String, Byte> SimModeMap = new HashMap<String, Byte>(); static { SimModeMap.put(_4_WIRE, (byte)0); SimModeMap.put(_3_WIRE, (byte)1); } public final static String BIG_ENDIAN = "Big endian"; public final static String LITTLE_ENDIAN = "Little endian"; public final static Map<String, Byte> BigLittleEndianMap = new HashMap<String, Byte>(); static { BigLittleEndianMap.put(BIG_ENDIAN, (byte)0); BigLittleEndianMap.put(LITTLE_ENDIAN, (byte)1); } public final static String _250_DPS = "250dps"; public final static String _500_DPS = "500dps"; public final static String _2000_DPS = "2000dps"; public final static Map<String, Byte> FullScaleMap = new HashMap<String, Byte>(); static { FullScaleMap.put(_250_DPS, (byte)0); FullScaleMap.put(_500_DPS, (byte)1); FullScaleMap.put(_2000_DPS, (byte)2); } public final static String CONTINUOUS_UPDATE = "Continous update"; public final static String NOT_UPDATED_UNTIL_READING = "Output registers not updated until reading"; public final static Map<String, Byte> BlockDataUpdateMap = new HashMap<String, Byte>(); static { BlockDataUpdateMap.put(CONTINUOUS_UPDATE, (byte)0); BlockDataUpdateMap.put(NOT_UPDATED_UNTIL_READING, (byte)1); } public final static String LPF1 = "LPF1"; public final static String HPF = "HPF"; public final static String LPF2 = "LPF2"; public final static Map<String, Byte> OutSelMap = new HashMap<String, Byte>(); static { OutSelMap.put(LPF1, (byte)0); OutSelMap.put(HPF, (byte)1); OutSelMap.put(LPF2, (byte)2); } public final static Map<String, Byte> IntSelMap = new HashMap<String, Byte>(); static { IntSelMap.put(LPF1, (byte)0); IntSelMap.put(HPF, (byte)1); IntSelMap.put(LPF2, (byte)2); } //public final static String NORMAL = "Normal"; public final static String REBOOT_MEMORY_CONTENT = "Reboot memory content"; public final static Map<String, Byte> BootModeMap = new HashMap<String, Byte>(); static { BootModeMap.put(NORMAL, (byte)0); BootModeMap.put(REBOOT_MEMORY_CONTENT, (byte)1); } public final static String BYPASS = "Bypass"; public final static String FIFO = "FIFO"; public final static String STREAM = "Stream"; public final static String STREAM_TO_FIFO = "Stream-to-Fifo"; public final static String BYPASS_TO_STREAM = "Bypass-to-Stream"; public final static Map<String, Byte> FifoModeMap = new HashMap<String, Byte>(); static { FifoModeMap.put(BYPASS, (byte)0); FifoModeMap.put(FIFO, (byte)1); FifoModeMap.put(STREAM, (byte)2); FifoModeMap.put(STREAM_TO_FIFO, (byte)3); FifoModeMap.put(BYPASS_TO_STREAM, (byte)4); } public final static String AND = "And"; public final static String OR = "Or"; public final static Map<String, Byte> AndOrMap = new HashMap<String, Byte>(); static { AndOrMap.put(AND, (byte)0); AndOrMap.put(OR, (byte)1); } public final static String NORMAL_WITH_RESET = "Normal with reset."; public final static String REFERENCE_SIGNAL_FOR_FILTERING = "Reference signal for filtering."; //public final static String NORMAL = "Normal"; public final static String AUTORESET_ON_INTERRUPT = "Autoreset on interrupt."; public final static Map<String, Byte> HighPassFilterMap = new HashMap<String, Byte>(); static { HighPassFilterMap.put(NORMAL_WITH_RESET, (byte)0); HighPassFilterMap.put(REFERENCE_SIGNAL_FOR_FILTERING, (byte)1); HighPassFilterMap.put(NORMAL, (byte)2); HighPassFilterMap.put(AUTORESET_ON_INTERRUPT, (byte)3); } private final static int[] DATA_RATE_VALUES = { 95, 190, 380, 760 }; private final static float[] BANDWIDTH_VALUES = { 12.5f, 20, 25, 30, 35, 50, 70, 100 }; private final static float[] HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES = { 51.4f, 27, 13.5f, 7.2f, 3.5f, 1.8f, 0.9f, 0.45f, 0.18f, 0.09f, 0.045f, 0.018f, 0.009f }; // __DRBW public final static Map<Integer, Map<Float, Byte>> DataRateBandWidthMap = new HashMap<Integer, Map<Float, Byte>>(); static { // DataRateValues[0] : { BandWidthValues[0]:0x00, BandWidthValues[2]:0x01}, Map<Float, Byte> map0 = new HashMap<Float, Byte>(); map0.put(BANDWIDTH_VALUES[0], (byte)0); map0.put(BANDWIDTH_VALUES[2], (byte)1); DataRateBandWidthMap.put(DATA_RATE_VALUES[0], map0); // DataRateValues[1] : { BandWidthValues[0]:0x04, BandWidthValues[2]:0x05, BandWidthValues[5]:0x06, BandWidthValues[6]:0x07}, Map<Float, Byte> map1 = new HashMap<Float, Byte>(); map1.put(BANDWIDTH_VALUES[0], (byte)0x4); map1.put(BANDWIDTH_VALUES[2], (byte)0x5); map1.put(BANDWIDTH_VALUES[5], (byte)0x6); map1.put(BANDWIDTH_VALUES[6], (byte)0x7); DataRateBandWidthMap.put(DATA_RATE_VALUES[1], map1); // DataRateValues[2] : { BandWidthValues[1]:0x08, BandWidthValues[2]:0x09, BandWidthValues[5]:0x0a, BandWidthValues[7]:0x0b}, Map<Float, Byte> map2 = new HashMap<Float, Byte>(); map2.put(BANDWIDTH_VALUES[1], (byte)0x8); map2.put(BANDWIDTH_VALUES[2], (byte)0x9); map2.put(BANDWIDTH_VALUES[5], (byte)0xa); map2.put(BANDWIDTH_VALUES[7], (byte)0xb); DataRateBandWidthMap.put(DATA_RATE_VALUES[2], map2); // DataRateValues[3] : { BandWidthValues[3]:0x0c, BandWidthValues[4]:0x0d, BandWidthValues[5]:0x0e, BandWidthValues[7]:0x0f} Map<Float, Byte> map3 = new HashMap<Float, Byte>(); map3.put(BANDWIDTH_VALUES[3], (byte)0xc); map3.put(BANDWIDTH_VALUES[4], (byte)0xd); map3.put(BANDWIDTH_VALUES[5], (byte)0xe); map3.put(BANDWIDTH_VALUES[7], (byte)0xf); DataRateBandWidthMap.put(DATA_RATE_VALUES[3], map3); } // __HPCF public final static Map<Float, Map<Integer, Byte>> HighPassCutOffMap = new HashMap<Float, Map<Integer, Byte>>(); static { Map<Integer, Byte> map0 = new HashMap<Integer, Byte>(); map0.put(DATA_RATE_VALUES[3], (byte)0); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[0], map0); Map<Integer, Byte> map1 = new HashMap<Integer, Byte>(); map1.put(DATA_RATE_VALUES[2], (byte)0x0); map1.put(DATA_RATE_VALUES[3], (byte)0x1); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[1], map1); Map<Integer, Byte> map2 = new HashMap<Integer, Byte>(); map2.put(DATA_RATE_VALUES[1], (byte)0x0); map2.put(DATA_RATE_VALUES[2], (byte)0x1); map2.put(DATA_RATE_VALUES[3], (byte)0x2); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[2], map2); Map<Integer, Byte> map3 = new HashMap<Integer, Byte>(); map3.put(DATA_RATE_VALUES[0], (byte)0x0); map3.put(DATA_RATE_VALUES[1], (byte)0x1); map3.put(DATA_RATE_VALUES[2], (byte)0x2); map3.put(DATA_RATE_VALUES[3], (byte)0x3); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[3], map3); Map<Integer, Byte> map4 = new HashMap<Integer, Byte>(); map4.put(DATA_RATE_VALUES[0], (byte)0x1); map4.put(DATA_RATE_VALUES[1], (byte)0x2); map4.put(DATA_RATE_VALUES[2], (byte)0x3); map4.put(DATA_RATE_VALUES[3], (byte)0x4); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[4], map4); Map<Integer, Byte> map5 = new HashMap<Integer, Byte>(); map5.put(DATA_RATE_VALUES[0], (byte)0x2); map5.put(DATA_RATE_VALUES[1], (byte)0x3); map5.put(DATA_RATE_VALUES[2], (byte)0x4); map5.put(DATA_RATE_VALUES[3], (byte)0x5); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[5], map5); Map<Integer, Byte> map6 = new HashMap<Integer, Byte>(); map6.put(DATA_RATE_VALUES[0], (byte)0x3); map6.put(DATA_RATE_VALUES[1], (byte)0x4); map6.put(DATA_RATE_VALUES[2], (byte)0x5); map6.put(DATA_RATE_VALUES[3], (byte)0x6); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[6], map6); Map<Integer, Byte> map7 = new HashMap<Integer, Byte>(); map7.put(DATA_RATE_VALUES[0], (byte)0x4); map7.put(DATA_RATE_VALUES[1], (byte)0x5); map7.put(DATA_RATE_VALUES[2], (byte)0x6); map7.put(DATA_RATE_VALUES[3], (byte)0x7); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[7], map7); Map<Integer, Byte> map8 = new HashMap<Integer, Byte>(); map8.put(DATA_RATE_VALUES[0], (byte)0x5); map8.put(DATA_RATE_VALUES[1], (byte)0x6); map8.put(DATA_RATE_VALUES[2], (byte)0x7); map8.put(DATA_RATE_VALUES[3], (byte)0x8); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[8], map8); Map<Integer, Byte> map9 = new HashMap<Integer, Byte>(); map9.put(DATA_RATE_VALUES[0], (byte)0x6); map9.put(DATA_RATE_VALUES[1], (byte)0x7); map9.put(DATA_RATE_VALUES[2], (byte)0x8); map9.put(DATA_RATE_VALUES[3], (byte)0x9); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[9], map9); Map<Integer, Byte> map10 = new HashMap<Integer, Byte>(); map10.put(DATA_RATE_VALUES[0], (byte)0x7); map10.put(DATA_RATE_VALUES[1], (byte)0x8); map10.put(DATA_RATE_VALUES[2], (byte)0x9); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[10], map10); Map<Integer, Byte> map11 = new HashMap<Integer, Byte>(); map11.put(DATA_RATE_VALUES[0], (byte)0x8); map11.put(DATA_RATE_VALUES[1], (byte)0x9); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[11], map11); Map<Integer, Byte> map12 = new HashMap<Integer, Byte>(); map12.put(DATA_RATE_VALUES[0], (byte)0x9); HighPassCutOffMap.put(HIGHPASS_FILTER_CUTOFF_FREQUENCY_VALUES[12], map12); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/utils/L3GD20Dictionaries.java
Java
mit
11,057
package adafruiti2c.sensor.utils; public class BitOps { public static boolean checkBit(int value, int position) { int mask = 1 << position; return ((value & mask) == mask); } public static int setBit(int value, int position) { return (value | (1 << position)); } public static int clearBit(int value, int position) { return (value & ~(1 << position)); } public static int flipBit(int value, int position) { return (value ^ (1 << position)); } public static boolean checkBits(int value, int mask) { return ((value & mask) == mask); } public static int setBits(int value, int mask) { return (value | mask); } public static int clearBits(int value, int mask) { return (value & (~mask)); } public static int flipBits(int value, int mask) { return value ^ mask; } public static int setValueUnderMask(int valueToSet, int currentValue, int mask) { int currentValueCleared = clearBits(currentValue, mask); int i = 0; while (mask % 2 == 0 && mask != 0x00) { mask >>= 1; i++; } return setBits(valueToSet << i, currentValueCleared); } public static int getValueUnderMask(int currentValue, int mask) { int currentValueCleared = clearBits(currentValue, ~mask); // clear bits not under mask int i = 0; while (mask % 2 == 0 && mask != 0x00) { mask >>= 1; i++; } return currentValueCleared >> i; } public static int twosComplementToByte(int value) { if (value >= 0 && value <= 0x7f) return value; else return value - 0x100; } public static int twosComplementToCustom(int value, int signBitPosition) { if (value >= 0 && value <= (1 << signBitPosition) - 1) return value; else return value - (2 << signBitPosition); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/utils/BitOps.java
Java
mit
1,856
package adafruiti2c.sensor.utils; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; public class PWMPin extends GPIOPinAdapter { // 30 seems to be the maximum value. You can really see the led blinking beyond that. private final static int CYCLE_WIDTH = 30; private final Thread mainThread; private final boolean debug = "true".equals(System.getProperty("debug", "false")); public PWMPin(Pin p, String name, PinState originalState) { super(p, name, originalState); mainThread = Thread.currentThread(); } private boolean emittingPWM = false; private int pwmVolume = 0; // [0..CYCLE_WIDTH], percent / (100 / CYCLE_WIDTH); public void emitPWM(final int percent) { if (percent < 0 || percent > 100) throw new IllegalArgumentException("Percent MUST be in [0, 100], not [" + percent + "]"); if (debug) System.out.println("Volume:" + percentToVolume(percent) + "/" + CYCLE_WIDTH); Thread pwmThread = new Thread() { public void run() { emittingPWM = true; pwmVolume = percentToVolume(percent); while (emittingPWM) { if (pwmVolume > 0) pin.pulse(pwmVolume, true); // set second argument to 'true' makes a blocking call pin.low(); waitFor(CYCLE_WIDTH - pwmVolume); // Wait for the rest of the cycle } System.out.println("Stopping PWM"); // Notify the ones waiting for this thread to end synchronized (mainThread) { mainThread.notify(); } } }; pwmThread.start(); } /** * return a number in [0..CYCLE_WIDTH] * @param percent in [0..100] * @return */ private int percentToVolume(int percent) { if (percent < 0 || percent > 100) throw new IllegalArgumentException("Percent MUST be in [0, 100], not [" + percent + "]"); return percent / (100 / CYCLE_WIDTH); } public void adjustPWMVolume(int percent) { if (percent < 0 || percent > 100) throw new IllegalArgumentException("Percent MUST be in [0, 100], not [" + percent + "]"); pwmVolume = percentToVolume(percent); } public boolean isPWMing() { return emittingPWM; } public void stopPWM() { emittingPWM = false; synchronized (mainThread) { try { mainThread.wait(); } catch (InterruptedException ie) { System.out.println(ie.toString()); } } pin.low(); } private void waitFor(long ms) { if (ms <= 0) return; try { Thread.sleep(ms); } catch (InterruptedException ie) { ie.printStackTrace(); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/utils/PWMPin.java
Java
mit
2,666
package adafruiti2c.sensor.utils; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.GpioPinShutdown; import com.pi4j.io.gpio.GpioProvider; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinMode; import com.pi4j.io.gpio.PinPullResistance; import com.pi4j.io.gpio.PinState; import java.util.Map; import java.util.concurrent.Future; public class GPIOPinAdapter implements GpioPinDigitalOutput { protected final GpioController gpio = GpioFactory.getInstance(); protected final GpioPinDigitalOutput pin; public GPIOPinAdapter(Pin p, String name, PinState originalState) { super(); pin = gpio.provisionDigitalOutputPin(p, name, originalState); } @Override public void high() { pin.high(); } @Override public void low() { pin.low(); } @Override public void toggle() { pin.toggle(); } @Override public Future<?> blink(long delay) { return pin.blink(delay); } @Override public Future<?> blink(long delay, PinState blinkState) { return pin.blink(delay, blinkState); } @Override public Future<?> blink(long delay, long duration) { return pin.blink(delay, duration); } @Override public Future<?> blink(long delay, long duration, PinState blinkState) { return pin.blink(delay, duration, blinkState); } @Override public Future<?> pulse(long duration) { return pin.pulse(duration); } @Override public Future<?> pulse(long duration, boolean blocking) { return pin.pulse(duration, blocking); } @Override public Future<?> pulse(long duration, PinState pulseState) { return pin.pulse(duration, pulseState); } @Override public Future<?> pulse(long duration, PinState pulseState, boolean blocking) { return pin.pulse(duration, pulseState, blocking); } @Override public void setState(PinState state) { pin.setState(state); } @Override public void setState(boolean state) { pin.setState(state); } @Override public boolean isHigh() { return pin.isHigh(); } @Override public boolean isLow() { return pin.isLow(); } @Override public PinState getState() { return pin.getState(); } @Override public boolean isState(PinState state) { return pin.isState(state); } @Override public GpioProvider getProvider() { return pin.getProvider(); } @Override public Pin getPin() { return pin.getPin(); } @Override public void setName(String name) { pin.setName(name); } @Override public String getName() { return pin.getName(); } @Override public void setTag(Object tag) { pin.setTag(tag); } @Override public Object getTag() { return pin.getTag(); } @Override public void setProperty(String key, String value) { pin.setProperty(key, value); } @Override public boolean hasProperty(String key) { return pin.hasProperty(key); } @Override public String getProperty(String key) { return pin.getProperty(key); } @Override public String getProperty(String key, String defaultValue) { return pin.getProperty(key, defaultValue); } @Override public Map<String, String> getProperties() { // return Collections.emptyMap(); return pin.getProperties(); } @Override public void removeProperty(String key) { pin.removeProperty(key); } @Override public void clearProperties() { pin.clearProperties(); } @Override public void export(PinMode mode) { pin.export(mode); } @Override public void unexport() { pin.unexport(); } @Override public boolean isExported() { return pin.isExported(); } @Override public void setMode(PinMode mode) { pin.setMode(mode); } @Override public PinMode getMode() { return pin.getMode(); } @Override public boolean isMode(PinMode mode) { return pin.isMode(mode); } @Override public void setPullResistance(PinPullResistance resistance) { pin.setPullResistance(resistance); } @Override public PinPullResistance getPullResistance() { return pin.getPullResistance(); } @Override public boolean isPullResistance(PinPullResistance resistance) { return pin.isPullResistance(resistance); } @Override public GpioPinShutdown getShutdownOptions() { return pin.getShutdownOptions(); } @Override public void setShutdownOptions(GpioPinShutdown options) { pin.setShutdownOptions(options); } @Override public void setShutdownOptions(Boolean unexport) { pin.setShutdownOptions(unexport); } @Override public void setShutdownOptions(Boolean unexport, PinState state) { pin.setShutdownOptions(unexport, state); } @Override public void setShutdownOptions(Boolean unexport, PinState state, PinPullResistance resistance) { pin.setShutdownOptions(unexport, state, resistance); } @Override public void setShutdownOptions(Boolean unexport, PinState state, PinPullResistance resistance, PinMode mode) { pin.setShutdownOptions(unexport, state, resistance, mode); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/utils/GPIOPinAdapter.java
Java
mit
5,224
package adafruiti2c.sensor.nmea; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import java.io.IOException; import nmea.server.ctx.NMEAContext; import ocss.nmea.api.NMEAEvent; import ocss.nmea.api.NMEAListener; import ocss.nmea.parser.StringGenerator; /* * Altitude, Pressure, Temperature */ public class AdafruitBMP180Reader { // Minimal constants carried over from Arduino library /* Prompt> sudo i2cdetect -y 1 0 1 2 3 4 5 6 7 8 9 a b c d e f 00: -- -- -- -- -- -- -- -- -- -- -- -- -- 10: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 20: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 30: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 40: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 50: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 60: -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 70: -- -- -- -- -- -- -- 77 */ // The next address is returned by "sudo i2cdetect -y 1", see above. public final static int BMP180_ADDRESS = 0x77; // Operating Modes public final static int BMP180_ULTRALOWPOWER = 0; public final static int BMP180_STANDARD = 1; public final static int BMP180_HIGHRES = 2; public final static int BMP180_ULTRAHIGHRES = 3; // BMP085 Registers public final static int BMP180_CAL_AC1 = 0xAA; // R Calibration data (16 bits) public final static int BMP180_CAL_AC2 = 0xAC; // R Calibration data (16 bits) public final static int BMP180_CAL_AC3 = 0xAE; // R Calibration data (16 bits) public final static int BMP180_CAL_AC4 = 0xB0; // R Calibration data (16 bits) public final static int BMP180_CAL_AC5 = 0xB2; // R Calibration data (16 bits) public final static int BMP180_CAL_AC6 = 0xB4; // R Calibration data (16 bits) public final static int BMP180_CAL_B1 = 0xB6; // R Calibration data (16 bits) public final static int BMP180_CAL_B2 = 0xB8; // R Calibration data (16 bits) public final static int BMP180_CAL_MB = 0xBA; // R Calibration data (16 bits) public final static int BMP180_CAL_MC = 0xBC; // R Calibration data (16 bits) public final static int BMP180_CAL_MD = 0xBE; // R Calibration data (16 bits) public final static int BMP180_CONTROL = 0xF4; public final static int BMP180_TEMPDATA = 0xF6; public final static int BMP180_PRESSUREDATA = 0xF6; public final static int BMP180_READTEMPCMD = 0x2E; public final static int BMP180_READPRESSURECMD = 0x34; private int cal_AC1 = 0; private int cal_AC2 = 0; private int cal_AC3 = 0; private int cal_AC4 = 0; private int cal_AC5 = 0; private int cal_AC6 = 0; private int cal_B1 = 0; private int cal_B2 = 0; private int cal_MB = 0; private int cal_MC = 0; private int cal_MD = 0; private static boolean verbose = false; private I2CBus bus; private I2CDevice bmp180; private int mode = BMP180_STANDARD; public AdafruitBMP180Reader() { this(BMP180_ADDRESS); } public AdafruitBMP180Reader(int address) { try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself bmp180 = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); try { this.readCalibrationData(); } catch (Exception ex) { ex.printStackTrace(); } } catch (IOException e) { System.err.println(e.getMessage()); } } private int readU8(int reg) throws Exception { // "Read an unsigned byte from the I2C device" int result = 0; try { result = this.bmp180.read(reg); if (verbose) System.out.println("I2C: Device " + BMP180_ADDRESS + " returned " + result + " from reg " + reg); } catch (Exception ex) { ex.printStackTrace(); } return result; } private int readS8(int reg) throws Exception { // "Reads a signed byte from the I2C device" int result = 0; try { result = this.bmp180.read(reg); if (result > 127) result -= 256; if (verbose) System.out.println("I2C: Device " + BMP180_ADDRESS + " returned " + result + " from reg " + reg); } catch (Exception ex) { ex.printStackTrace(); } return result; } private int readU16(int register) throws Exception { int hi = this.readU8(register); int lo = this.readU8(register + 1); return (hi << 8) + lo; } private int readS16(int register) throws Exception { int hi = this.readS8(register); int lo = this.readU8(register + 1); return (hi << 8) + lo; } public void readCalibrationData() throws Exception { // "Reads the calibration data from the IC" cal_AC1 = readS16(BMP180_CAL_AC1); // INT16 cal_AC2 = readS16(BMP180_CAL_AC2); // INT16 cal_AC3 = readS16(BMP180_CAL_AC3); // INT16 cal_AC4 = readU16(BMP180_CAL_AC4); // UINT16 cal_AC5 = readU16(BMP180_CAL_AC5); // UINT16 cal_AC6 = readU16(BMP180_CAL_AC6); // UINT16 cal_B1 = readS16(BMP180_CAL_B1); // INT16 cal_B2 = readS16(BMP180_CAL_B2); // INT16 cal_MB = readS16(BMP180_CAL_MB); // INT16 cal_MC = readS16(BMP180_CAL_MC); // INT16 cal_MD = readS16(BMP180_CAL_MD); // INT16 if (verbose) showCalibrationData(); } private void showCalibrationData() { // "Displays the calibration values for debugging purposes" System.out.println("DBG: AC1 = " + cal_AC1); System.out.println("DBG: AC2 = " + cal_AC2); System.out.println("DBG: AC3 = " + cal_AC3); System.out.println("DBG: AC4 = " + cal_AC4); System.out.println("DBG: AC5 = " + cal_AC5); System.out.println("DBG: AC6 = " + cal_AC6); System.out.println("DBG: B1 = " + cal_B1); System.out.println("DBG: B2 = " + cal_B2); System.out.println("DBG: MB = " + cal_MB); System.out.println("DBG: MC = " + cal_MC); System.out.println("DBG: MD = " + cal_MD); } public int readRawTemp() throws Exception { // "Reads the raw (uncompensated) temperature from the sensor" bmp180.write(BMP180_CONTROL, (byte)BMP180_READTEMPCMD); waitfor(5); // Wait 5ms int raw = readU16(BMP180_TEMPDATA); if (verbose) System.out.println("DBG: Raw Temp: " + (raw & 0xFFFF) + ", " + raw); return raw; } public int readRawPressure() throws Exception { // "Reads the raw (uncompensated) pressure level from the sensor" bmp180.write(BMP180_CONTROL, (byte)(BMP180_READPRESSURECMD + (this.mode << 6))); if (this.mode == BMP180_ULTRALOWPOWER) waitfor(5); else if (this.mode == BMP180_HIGHRES) waitfor(14); else if (this.mode == BMP180_ULTRAHIGHRES) waitfor(26); else waitfor(8); int msb = bmp180.read(BMP180_PRESSUREDATA); int lsb = bmp180.read(BMP180_PRESSUREDATA + 1); int xlsb = bmp180.read(BMP180_PRESSUREDATA + 2); int raw = ((msb << 16) + (lsb << 8) + xlsb) >> (8 - this.mode); if (verbose) System.out.println("DBG: Raw Pressure: " + (raw & 0xFFFF) + ", " + raw); return raw; } public float readTemperature() throws Exception { // "Gets the compensated temperature in degrees celcius" int UT = 0; int X1 = 0; int X2 = 0; int B5 = 0; float temp = 0.0f; // Read raw temp before aligning it with the calibration values UT = this.readRawTemp(); X1 = ((UT - this.cal_AC6) * this.cal_AC5) >> 15; X2 = (this.cal_MC << 11) / (X1 + this.cal_MD); B5 = X1 + X2; temp = ((B5 + 8) >> 4) / 10.0f; if (verbose) System.out.println("DBG: Calibrated temperature = " + temp + " C"); return temp; } public float readPressure() throws Exception { // "Gets the compensated pressure in pascal" int UT = 0; int UP = 0; int B3 = 0; int B5 = 0; int B6 = 0; int X1 = 0; int X2 = 0; int X3 = 0; int p = 0; int B4 = 0; int B7 = 0; UT = this.readRawTemp(); UP = this.readRawPressure(); // You can use the datasheet values to test the conversion results // boolean dsValues = true; boolean dsValues = false; if (dsValues) { UT = 27898; UP = 23843; this.cal_AC6 = 23153; this.cal_AC5 = 32757; this.cal_MB = -32768; this.cal_MC = -8711; this.cal_MD = 2868; this.cal_B1 = 6190; this.cal_B2 = 4; this.cal_AC3 = -14383; this.cal_AC2 = -72; this.cal_AC1 = 408; this.cal_AC4 = 32741; this.mode = BMP180_ULTRALOWPOWER; if (verbose) this.showCalibrationData(); } // True Temperature Calculations X1 = (int)((UT - this.cal_AC6) * this.cal_AC5) >> 15; X2 = (this.cal_MC << 11) / (X1 + this.cal_MD); B5 = X1 + X2; if (verbose) { System.out.println("DBG: X1 = " + X1); System.out.println("DBG: X2 = " + X2); System.out.println("DBG: B5 = " + B5); System.out.println("DBG: True Temperature = " + (((B5 + 8) >> 4) / 10.0) + " C"); } // Pressure Calculations B6 = B5 - 4000; X1 = (this.cal_B2 * (B6 * B6) >> 12) >> 11; X2 = (this.cal_AC2 * B6) >> 11; X3 = X1 + X2; B3 = (((this.cal_AC1 * 4 + X3) << this.mode) + 2) / 4; if (verbose) { System.out.println("DBG: B6 = " + B6); System.out.println("DBG: X1 = " + X1); System.out.println("DBG: X2 = " + X2); System.out.println("DBG: X3 = " + X3); System.out.println("DBG: B3 = " + B3); } X1 = (this.cal_AC3 * B6) >> 13; X2 = (this.cal_B1 * ((B6 * B6) >> 12)) >> 16; X3 = ((X1 + X2) + 2) >> 2; B4 = (this.cal_AC4 * (X3 + 32768)) >> 15; B7 = (UP - B3) * (50000 >> this.mode); if (verbose) { System.out.println("DBG: X1 = " + X1); System.out.println("DBG: X2 = " + X2); System.out.println("DBG: X3 = " + X3); System.out.println("DBG: B4 = " + B4); System.out.println("DBG: B7 = " + B7); } if (B7 < 0x80000000) p = (B7 * 2) / B4; else p = (B7 / B4) * 2; if (verbose) System.out.println("DBG: X1 = " + X1); X1 = (p >> 8) * (p >> 8); X1 = (X1 * 3038) >> 16; X2 = (-7357 * p) >> 16; if (verbose) { System.out.println("DBG: p = " + p); System.out.println("DBG: X1 = " + X1); System.out.println("DBG: X2 = " + X2); } p = p + ((X1 + X2 + 3791) >> 4); if (verbose) System.out.println("DBG: Pressure = " + p + " Pa"); return p; } private int standardSeaLevelPressure = 101325; public void setStandardSeaLevelPressure(int standardSeaLevelPressure) { this.standardSeaLevelPressure = standardSeaLevelPressure; } public double readAltitude() throws Exception { // "Calculates the altitude in meters" double altitude = 0.0; float pressure = readPressure(); altitude = 44330.0 * (1.0 - Math.pow(pressure / standardSeaLevelPressure, 0.1903)); if (verbose) System.out.println("DBG: Altitude = " + altitude); return altitude; } private static void waitfor(long howMuch) { try { synchronized (Thread.currentThread()) { Thread.currentThread().wait(howMuch); } } catch (InterruptedException ie) { ie.printStackTrace(); } } private boolean go = true; public void stopReading() { go = false; synchronized (Thread.currentThread()) { System.out.println("Stopping the reader"); Thread.currentThread().notify(); } } public void startReading() { go = true; while (go) { float press = 0; float temp = 0; double alt = 0; try { press = this.readPressure(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } this.setStandardSeaLevelPressure((int)press); // As we ARE at the sea level (in San Francisco). try { alt = this.readAltitude(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { temp = this.readTemperature(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } String nmeaMMB = StringGenerator.generateMMB("II", (press / 100)); String nmeaMTA = StringGenerator.generateMTA("II", temp); broadcastNMEASentence(nmeaMMB); broadcastNMEASentence(nmeaMTA); waitfor(1000L); // One sec. } System.out.println("Reader stopped."); } private void broadcastNMEASentence(String nmea) { for (NMEAListener l : NMEAContext.getInstance().getNMEAListeners()) l.dataDetected(new NMEAEvent(this, nmea)); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/nmea/AdafruitBMP180Reader.java
Java
mit
13,053
package adafruiti2c.sensor; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import java.io.IOException; import java.text.DecimalFormat; import java.text.NumberFormat; /* * Humidity, Temperature */ public class AdafruitHTU21DF { public final static int HTU21DF_ADDRESS = 0x40; // HTU21DF Registers public final static int HTU21DF_READTEMP = 0xE3; public final static int HTU21DF_READHUM = 0xE5; public final static int HTU21DF_READTEMP_NH = 0xF3; // NH = no hold public final static int HTU21DF_READHUMI_NH = 0xF5; public final static int HTU21DF_WRITEREG = 0xE6; public final static int HTU21DF_READREG = 0xE7; public final static int HTU21DF_RESET = 0xFE; private static boolean verbose = "true".equals(System.getProperty("htu21df.verbose", "false")); private I2CBus bus; private I2CDevice htu21df; public AdafruitHTU21DF() { this(HTU21DF_ADDRESS); } public AdafruitHTU21DF(int address) { try { // Get i2c bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get device itself htu21df = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); } catch (IOException e) { System.err.println(e.getMessage()); } } public boolean begin() throws Exception { reset(); htu21df.write((byte) HTU21DF_READREG); int r = htu21df.read(); if (verbose) System.out.println("DBG: Begin: 0x" + lpad(Integer.toHexString(r), "0", 2)); return (r == 0x02); } public void reset() throws Exception { // htu21df.write(HTU21DF_ADDRESS, (byte)HTU21DF_RESET); htu21df.write((byte) HTU21DF_RESET); if (verbose) System.out.println("DBG: Reset OK"); waitfor(15); // Wait 15ms } public float readTemperature() throws Exception { // Reads the raw temperature from the sensor if (verbose) System.out.println("Read Temp: Written 0x" + lpad(Integer.toHexString((HTU21DF_READTEMP & 0xff)), "0", 2)); htu21df.write((byte) (HTU21DF_READTEMP)); // & 0xff)); waitfor(50); // Wait 50ms byte[] buf = new byte[3]; /*int rc = */htu21df.read(buf, 0, 3); int msb = buf[0] & 0xFF; int lsb = buf[1] & 0xFF; int crc = buf[2] & 0xFF; int raw = ((msb << 8) + lsb) & 0xFFFC; // while (!Wire.available()) {} if (verbose) { System.out.println("Temp -> 0x" + lpad(Integer.toHexString(msb), "0", 2) + " " + "0x" + lpad(Integer.toHexString(lsb), "0", 2) + " " + "0x" + lpad(Integer.toHexString(crc), "0", 2)); System.out.println("DBG: Raw Temp: " + (raw & 0xFFFF) + ", " + raw); } float temp = raw; // t; temp *= 175.72; temp /= 65536; temp -= 46.85; if (verbose) System.out.println("DBG: Temp: " + temp); return temp; } public float readHumidity() throws Exception { // Reads the raw (uncompensated) humidity from the sensor htu21df.write((byte) HTU21DF_READHUM); waitfor(50); // Wait 50ms byte[] buf = new byte[3]; /* int rc = */htu21df.read(buf, 0, 3); int msb = buf[0] & 0xFF; int lsb = buf[1] & 0xFF; int crc = buf[2] & 0xFF; int raw = ((msb << 8) + lsb) & 0xFFFC; // while (!Wire.available()) {} if (verbose) { System.out.println("Hum -> 0x" + lpad(Integer.toHexString(msb), "0", 2) + " " + "0x" + lpad(Integer.toHexString(lsb), "0", 2) + " " + "0x" + lpad(Integer.toHexString(crc), "0", 2)); System.out.println("DBG: Raw Humidity: " + (raw & 0xFFFF) + ", " + raw); } float hum = raw; hum *= 125; hum /= 65536; hum -= 6; if (verbose) System.out.println("DBG: Humidity: " + hum); return hum; } protected static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } private static String lpad(String s, String with, int len) { String str = s; while (str.length() < len) str = with + str; return str; } public static void main(String[] args) { final NumberFormat NF = new DecimalFormat("##00.00"); AdafruitHTU21DF sensor = new AdafruitHTU21DF(); float hum = 0; float temp = 0; try { if (!sensor.begin()) { System.out.println("Sensor not found!"); System.exit(1); } } catch (Exception ex) { ex.printStackTrace(); System.exit(1); } try { hum = sensor.readHumidity(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } try { temp = sensor.readTemperature(); } catch (Exception ex) { System.err.println(ex.getMessage()); ex.printStackTrace(); } System.out.println("Temperature: " + NF.format(temp) + " C"); System.out.println("Humidity : " + NF.format(hum) + " %"); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/sensor/AdafruitHTU21DF.java
Java
mit
5,134
package adafruiti2c.gui.gyro; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class GyroDisplayFrame extends JFrame { private JMenuBar menuBar = new JMenuBar(); private JMenu menuFile = new JMenu(); private JMenuItem menuFileExit = new JMenuItem(); private GyroDisplayPanel displayPanel = null; private transient GyroscopeUI caller; public GyroDisplayFrame(GyroscopeUI parent) { this.caller = parent; displayPanel = new GyroDisplayPanel(); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setJMenuBar(menuBar); this.getContentPane().setLayout(new BorderLayout()); this.setSize(new Dimension(400, 400)); this.setTitle("Gyroscope UI"); menuFile.setText("File"); menuFileExit.setText("Exit"); menuFileExit.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { fileExit_ActionPerformed( ae ); } } ); menuFile.add( menuFileExit ); menuBar.add( menuFile ); this.getContentPane().add(displayPanel, BorderLayout.CENTER); } void fileExit_ActionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); this.caller.close(); System.exit(0); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/gui/gyro/GyroDisplayFrame.java
Java
mit
1,492
package adafruiti2c.gui.gyro; import adafruiti2c.gui.utils.Point3D; import adafruiti2c.sensor.listener.AdafruitL3GD20Listener; import adafruiti2c.sensor.listener.SensorL3GD20Context; import adafruiti2c.sensor.main.SampleL3GD20RealReader; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.Stroke; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; import javax.swing.SwingUtilities; // This class listens to the gyroscope public class GyroDisplayPanel extends JPanel { @SuppressWarnings("compatibility:5286281276243161150") public final static long serialVersionUID = 1L; protected transient Stroke thick = new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); protected transient Stroke dotted = new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] {2f}, 0f); protected transient Stroke origStroke = null; private transient Point3D[] vertices = null; private transient int[][] faces; private transient List<Point3D> rotated = null; private final static boolean DEMO = "true".equals(System.getProperty("demo", "true")); private transient SampleL3GD20RealReader sensorReader = null; private double angleX = 0d, angleY = 0d, angleZ = 0d; private final double DELTA_T = 0.05; public GyroDisplayPanel() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { System.out.println("-- Demo Mode is " + (DEMO?"ON":"OFF")); System.out.println("-- Check it in " + this.getClass().getName()); this.setLayout(null); this.setOpaque(false); this.setBackground(new Color(0, 0, 0, 0)); // Create the model here vertices = new Point3D[] { new Point3D(-2, 0.5, -1), // 0 new Point3D( 2, 0.5, -1), // 1 new Point3D( 2, -0.5, -1), // 2 new Point3D(-2, -0.5, -1), // 3 new Point3D(-2, 0.5, 1), // 4 new Point3D( 2, 0.5, 1), // 5 new Point3D( 2, -0.5, 1), // 6 new Point3D(-2, -0.5, 1) // 7 }; faces = new int[][] { new int[] { 0, 1, 2, 3 }, new int[] { 1, 5, 6, 2 }, new int[] { 5, 4, 7, 6 }, new int[] { 4, 0, 3, 7 }, new int[] { 0, 4, 5, 1 }, new int[] { 3, 2, 6, 7 } }; rotateFigure(0, 0, 0); if (DEMO) startMoving(); // This would be replaced by the listener interaction, in non-demo mode. else { Thread sensorListener = new Thread() { public void run() { try { sensorReader = new SampleL3GD20RealReader(); System.out.println("...Adding listener"); SensorL3GD20Context.getInstance().addReaderListener(new AdafruitL3GD20Listener() { public void motionDetected(double x, double y, double z) { angleX += (x * DELTA_T); angleY += (y * DELTA_T); angleZ += (z * DELTA_T); try { rotateFigure(angleX, angleY, angleZ); } catch (Exception ex) {} } public void close() { sensorReader.stop(); } }); System.out.println("Starting listening..."); sensorReader.start(); } catch (Exception ex) { ex.printStackTrace(); } } }; sensorListener.start(); } } @Override protected void paintComponent(Graphics gr) { super.paintComponent(gr); Graphics2D g2d = (Graphics2D)gr; g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // origStroke = g2d.getStroke(); if (rotated != null) { synchronized (rotated) { for (int[] f : faces) { gr.drawLine((int)rotated.get(f[0]).getX(), (int)rotated.get(f[0]).getY(), (int)rotated.get(f[1]).getX(), (int)rotated.get(f[1]).getY()); gr.drawLine((int)rotated.get(f[1]).getX(), (int)rotated.get(f[1]).getY(), (int)rotated.get(f[2]).getX(), (int)rotated.get(f[2]).getY()); gr.drawLine((int)rotated.get(f[2]).getX(), (int)rotated.get(f[2]).getY(), (int)rotated.get(f[3]).getX(), (int)rotated.get(f[3]).getY()); gr.drawLine((int)rotated.get(f[3]).getX(), (int)rotated.get(f[3]).getY(), (int)rotated.get(f[0]).getX(), (int)rotated.get(f[0]).getY()); } } } // g2d.setStroke(origStroke); } private void rotateFigure(double x, double y, double z) throws InvocationTargetException, InterruptedException { rotated = new ArrayList<Point3D>(); synchronized (rotated) { for (Point3D p : vertices) { Point3D r = p.rotateX(x).rotateY(y).rotateZ(z); Point3D proj = r.project(this.getWidth(), this.getHeight(), 256, 4); rotated.add(proj); } } // repaint(); SwingUtilities.invokeAndWait(new Runnable() { public void run() { repaint(); } }); } // For demo private void startMoving() { Thread movingThread = new Thread() { public void run() { for (int x = 0, y = 0, z = 0; x<360; x++, y++, z++) { try { rotateFigure(x, y, z); } catch (Exception ex) {} try { Thread.sleep(10L); } catch (InterruptedException ie) {} } } }; movingThread.start(); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/gui/gyro/GyroDisplayPanel.java
Java
mit
5,893
package adafruiti2c.gui.gyro; import adafruiti2c.sensor.listener.SensorL3GD20Context; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class GyroscopeUI { public GyroscopeUI() { JFrame frame = new GyroDisplayFrame(this); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } frame.setLocation( ( screenSize.width - frameSize.width ) / 2, ( screenSize.height - frameSize.height ) / 2 ); // frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { close(); System.exit(0); } }); System.out.println("Displaying frame"); frame.setVisible(true); } public static void main(String[] args) { try { if (System.getProperty("swing.defaultlaf") == null) UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } new GyroscopeUI(); } public void close() { System.out.println("Exiting."); SensorL3GD20Context.getInstance().fireClose(); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/gui/gyro/GyroscopeUI.java
Java
mit
1,568
package adafruiti2c.gui.acc; import adafruiti2c.gui.utils.Point3D; import adafruiti2c.sensor.AdafruitLSM303; import adafruiti2c.sensor.listener.AdafruitL3GD20Listener; import adafruiti2c.sensor.listener.AdafruitLSM303Listener; import adafruiti2c.sensor.listener.SensorL3GD20Context; import adafruiti2c.sensor.listener.SensorLSM303Context; import adafruiti2c.sensor.main.SampleL3GD20RealReader; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Stroke; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.List; import javax.swing.JPanel; import javax.swing.SwingUtilities; // This class listens to the LSM303 (acc + mag) public class AccelerometerDisplayPanel extends JPanel { @SuppressWarnings("compatibility:5286281276243161150") public final static long serialVersionUID = 1L; protected transient Stroke thick = new BasicStroke(2f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND); protected transient Stroke dotted = new BasicStroke(1f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND, 1f, new float[] {2f}, 0f); protected transient Stroke origStroke = null; private transient AdafruitLSM303 sensor = null; private List<Integer> accXList = new ArrayList<Integer>(); private List<Integer> accYList = new ArrayList<Integer>(); private List<Integer> accZList = new ArrayList<Integer>(); private List<Integer> magXList = new ArrayList<Integer>(); private List<Integer> magYList = new ArrayList<Integer>(); private List<Integer> magZList = new ArrayList<Integer>(); private List<Float> headingList = new ArrayList<Float>(); private int minX = Integer.MAX_VALUE, maxX = Integer.MIN_VALUE; private int minY = Integer.MAX_VALUE, maxY = Integer.MIN_VALUE; private int minZ = Integer.MAX_VALUE, maxZ = Integer.MIN_VALUE; private final double DELTA_T = 0.05; public AccelerometerDisplayPanel() { try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setLayout(null); this.setOpaque(false); this.setBackground(new Color(0, 0, 0, 0)); Thread sensorListener = new Thread() { public void run() { try { sensor = new AdafruitLSM303(); System.out.println("...Adding listener"); AdafruitLSM303Listener dataListener = new AdafruitLSM303Listener() { public void dataDetected(int accX, int accY, int accZ, int magX, int magY, int magZ, float heading) { maxX = Math.max(maxX, accX); minX = Math.min(minX, accX); maxY = Math.max(maxY, accX); minY = Math.min(minY, accX); maxZ = Math.max(maxZ, accX); minZ = Math.min(minZ, accX); synchronized (accXList) { accXList.add(accX); while (accXList.size() > 1000) { accXList.remove(0); } } synchronized (accYList) { accYList.add(accY); while (accYList.size() > 1000) { accYList.remove(0); } } synchronized (accZList) { accZList.add(accZ); while (accZList.size() > 1000) { accZList.remove(0); } } synchronized (magXList) { magXList.add(magX); while (magXList.size() > 1000) { magXList.remove(0); } } synchronized (magYList) { magYList.add(magY); while (magYList.size() > 1000) { magYList.remove(0); } } synchronized (magZList) { magZList.add(magZ); while (magZList.size() > 1000) { magZList.remove(0); } } synchronized (headingList) { headingList.add(heading); while (headingList.size() > 1000) { headingList.remove(0); } } repaint(); } public void close() { sensor.setKeepReading(false); } }; SensorLSM303Context.getInstance().addReaderListener(dataListener); sensor.setDataListener(dataListener); sensor.setWait(250L); System.out.println("Starting listening..."); sensor.startReading(); } catch (Exception ex) { ex.printStackTrace(); } } }; sensorListener.start(); } @Override protected void paintComponent(Graphics gr) { super.paintComponent(gr); Graphics2D g2d = (Graphics2D)gr; g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); // origStroke = g2d.getStroke(); // g2d.setStroke(origStroke); // System.out.println("X data:" + accXList.size() + " point(s) min:" + minX + ", max:" + maxX); gr.setColor(Color.white); gr.fillRect(0, 0, this.getWidth(), this.getHeight()); gr.setColor(Color.green); synchronized (accXList) { drawData(0, gr, accXList, minX, maxX); } gr.setColor(Color.red); synchronized (accYList) { drawData(1, gr, accYList, minY, maxY); } gr.setColor(Color.blue); synchronized (accZList) { drawData(2, gr, accZList, minZ, maxZ); } } private void drawData(int idx, Graphics gr, List<Integer> data, int min, int max) { double xRatio = (double)this.getWidth() / (double)data.size(); double yRatio = (double)(this.getHeight() / 3) / ((double)(max - min)); int _x = 0; Point previous = null; for (Integer x : data) { int xPt = (int)(_x * xRatio); int yPt = (idx * (this.getHeight() / 3)) + (int)((x.intValue() - min) * yRatio); _x++; Point pt = new Point(xPt, this.getHeight() - yPt); if (previous != null) gr.drawLine(previous.x, previous.y, pt.x, pt.y); previous = pt; } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/gui/acc/AccelerometerDisplayPanel.java
Java
mit
5,916
package adafruiti2c.gui.acc; import adafruiti2c.gui.gyro.GyroDisplayPanel; import adafruiti2c.gui.gyro.GyroscopeUI; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class AccelerometerDisplayFrame extends JFrame { private JMenuBar menuBar = new JMenuBar(); private JMenu menuFile = new JMenu(); private JMenuItem menuFileExit = new JMenuItem(); private AccelerometerDisplayPanel displayPanel = null; private transient AccelerometerUI caller; public AccelerometerDisplayFrame(AccelerometerUI parent) { this.caller = parent; displayPanel = new AccelerometerDisplayPanel(); try { jbInit(); } catch (Exception e) { e.printStackTrace(); } } private void jbInit() throws Exception { this.setJMenuBar(menuBar); this.getContentPane().setLayout(new BorderLayout()); this.setSize(new Dimension(800, 400)); this.setTitle("Accelerometer UI"); menuFile.setText("File"); menuFileExit.setText("Exit"); menuFileExit.addActionListener( new ActionListener() { public void actionPerformed( ActionEvent ae ) { fileExit_ActionPerformed( ae ); } } ); menuFile.add( menuFileExit ); menuBar.add( menuFile ); this.getContentPane().add(displayPanel, BorderLayout.CENTER); } void fileExit_ActionPerformed(ActionEvent e) { System.out.println(e.getActionCommand()); this.caller.close(); System.exit(0); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/gui/acc/AccelerometerDisplayFrame.java
Java
mit
1,628
package adafruiti2c.gui.acc; import adafruiti2c.gui.gyro.GyroDisplayFrame; import adafruiti2c.sensor.listener.SensorL3GD20Context; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.swing.JFrame; import javax.swing.SwingUtilities; import javax.swing.UIManager; public class AccelerometerUI { public AccelerometerUI() { JFrame frame = new AccelerometerDisplayFrame(this); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = frame.getSize(); if (frameSize.height > screenSize.height) { frameSize.height = screenSize.height; } if (frameSize.width > screenSize.width) { frameSize.width = screenSize.width; } frame.setLocation( ( screenSize.width - frameSize.width ) / 2, ( screenSize.height - frameSize.height ) / 2 ); // frame.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { close(); System.exit(0); } }); System.out.println("Displaying frame"); frame.setVisible(true); } public static void main(String[] args) { try { if (System.getProperty("swing.defaultlaf") == null) UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { e.printStackTrace(); } new AccelerometerUI(); } public void close() { System.out.println("Exiting."); SensorL3GD20Context.getInstance().fireClose(); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/gui/acc/AccelerometerUI.java
Java
mit
1,635
package adafruiti2c.gui.utils; public class Point3D { private double x, y, z; public double getX() { return x; } public double getY() { return y; } public double getZ() { return z; } public Point3D(double x, double y, double z) { this.x = x; this.y = y; this.z = z; } /** * Rotates the point around the X axis by the given angle in degrees. * @param angle in degrees * @return */ public Point3D rotateX(double angle) { double rad = Math.toRadians(angle); double cosa = Math.cos(rad); double sina = Math.sin(rad); double y = this.y * cosa - this.z * sina; double z = this.y * sina + this.z * cosa; return new Point3D(this.x, y, z); } /** * Rotates the point around the Y axis by the given angle in degrees. * @param angle in degrees * @return */ public Point3D rotateY(double angle) { double rad = Math.toRadians(angle); double cosa = Math.cos(rad); double sina = Math.sin(rad); double z = this.z * cosa - this.x * sina; double x = this.z * sina + this.x * cosa; return new Point3D(x, this.y, z); } /** * Rotates the point around the Z axis by the given angle in degrees. * @param angle in degrees * @return */ public Point3D rotateZ(double angle) { double rad = Math.toRadians(angle); double cosa = Math.cos(rad); double sina = Math.sin(rad); double x = this.x * cosa - this.y * sina; double y = this.x * sina + this.y * cosa; return new Point3D(x, y, this.z); } /* * Transforms this 3D point to 2D using a perspective projection. */ public Point3D project(int winWidth, int winHeight, double fieldOfView, double viewerDistance) { double factor = fieldOfView / (viewerDistance + this.z); double x = this.x * factor + winWidth / 2; double y = -this.y * factor + winHeight / 2; return new Point3D(x, y, 1); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/gui/utils/Point3D.java
Java
mit
1,937
package adafruiti2c.samples; import adafruiti2c.servo.AdafruitPCA9685; import java.io.BufferedReader; import java.io.InputStreamReader; /* * Two servos - one standard, one continous * Enter all the values from the command line, and see for yourself. */ public class InteractiveServo { private static final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); public static String userInput(String prompt) { String retString = ""; System.err.print(prompt); try { retString = stdin.readLine(); } catch(Exception e) { System.out.println(e); String s; try { s = userInput("<Oooch/>"); } catch(Exception exception) { exception.printStackTrace(); } } return retString; } public static void main(String[] args) { AdafruitPCA9685 servoBoard = new AdafruitPCA9685(); int freq = 60; String sFreq = userInput("freq (40-1000) ? > "); try { freq = Integer.parseInt(sFreq); } catch (NumberFormatException nfe) { System.err.println("Defaulting freq to 60"); nfe.printStackTrace(); } if (freq < 40 || freq > 1000) throw new IllegalArgumentException("Freq only between 40 and 1000."); servoBoard.setPWMFreq(freq); // Set frequency in Hz final int CONTINUOUS_SERVO_CHANNEL = 14; final int STANDARD_SERVO_CHANNEL = 15; int servo = STANDARD_SERVO_CHANNEL; String sServo = userInput("Servo: Continuous [C], Standard [S] > "); if ("C".equalsIgnoreCase(sServo)) servo = CONTINUOUS_SERVO_CHANNEL; else if ("S".equalsIgnoreCase(sServo)) servo = STANDARD_SERVO_CHANNEL; else System.out.println("Only C or S... Defaulting to Standard."); boolean keepGoing = true; System.out.println("Enter 'quit' to exit."); while (keepGoing) { String s1 = userInput("pulse width in ticks (0..4095) ? > "); if ("QUIT".equalsIgnoreCase(s1)) keepGoing = false; else { try { int on = Integer.parseInt(s1); if (on < 0 || on > 4095) System.out.println("Values between 0 and 4095."); else { System.out.println("setPWM(" + servo + ", 0, " + on + ");"); servoBoard.setPWM(servo, 0, on); System.out.println("-------------------"); } } catch (Exception ex) { ex.printStackTrace(); } } } System.out.println("Done."); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/samples/InteractiveServo.java
Java
mit
2,568
package adafruiti2c.samples; import adafruiti2c.servo.AdafruitPCA9685; /* * Continuous, all the way, clockwise, counterclockwise * Note: This DOES NOT work as documented. */ public class DemoContinuous { private static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } public static void main(String[] args) { AdafruitPCA9685 servoBoard = new AdafruitPCA9685(); int freq = 60; servoBoard.setPWMFreq(freq); // Set frequency in Hz final int CONTINUOUS_SERVO_CHANNEL = 14; // final int STANDARD_SERVO_CHANNEL = 15; int servo = CONTINUOUS_SERVO_CHANNEL; int servoMin = 340; int servoMax = 410; int servoStopsAt = 375; servoBoard.setPWM(servo, 0, 0); // Stop the servo waitfor(2000); System.out.println("Let's go"); for (int i=servoStopsAt; i<=servoMax; i++) { System.out.println("i=" + i); servoBoard.setPWM(servo, 0, i); waitfor(500); } System.out.println("Servo Max"); waitfor(1000); for (int i=servoMax; i>=servoMin; i--) { System.out.println("i=" + i); servoBoard.setPWM(servo, 0, i); waitfor(500); } System.out.println("Servo Min"); waitfor(1000); for (int i=servoMin; i<=servoStopsAt; i++) { System.out.println("i=" + i); servoBoard.setPWM(servo, 0, i); waitfor(500); } waitfor(2000); servoBoard.setPWM(servo, 0, 0); // Stop the servo System.out.println("Done."); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/samples/DemoContinuous.java
Java
mit
1,556
package adafruiti2c.samples.ws; import adafruiti2c.servo.AdafruitPCA9685; import java.io.FileOutputStream; import oracle.generic.ws.client.ClientFacade; import oracle.generic.ws.client.ServerListenerAdapter; import oracle.generic.ws.client.ServerListenerInterface; import org.json.JSONObject; public class WebSocketListener { private final static boolean DEBUG = false; private boolean keepWorking = true; private ClientFacade webSocketClient = null; AdafruitPCA9685 servoBoard = null; private final int freq = 60; // For the TowerPro SG-5010 private final static int servoMin = 150; // -90 deg private final static int servoMax = 600; // +90 deg private final static int STANDARD_SERVO_CHANNEL = 15; private int servo = STANDARD_SERVO_CHANNEL; public WebSocketListener() throws Exception { try { servoBoard = new AdafruitPCA9685(); servoBoard.setPWMFreq(freq); // Set frequency in Hz } catch (UnsatisfiedLinkError ule) { System.err.println("You're not on the PI, are you?"); } String wsUri = System.getProperty("ws.uri", "ws://localhost:9876/"); initWebSocketConnection(wsUri); } private void initWebSocketConnection(String serverURI) { String[] targetedTransports = new String[] {"WebSocket", "XMLHttpRequest"}; ServerListenerInterface serverListener = new ServerListenerAdapter() { @Override public void onMessage(String mess) { // System.out.println(" . Text message :[" + mess + "]"); JSONObject json = new JSONObject(mess); String valueContent = ((JSONObject)json.get("data")).get("text").toString().replace("&quot;", "\""); JSONObject valueObj = new JSONObject(valueContent); // System.out.println(" . Mess content:[" + ((JSONObject)json.get("data")).get("text") + "]"); int servoValue = valueObj.getInt("value"); System.out.println("Servo Value:" + servoValue); // TODO Drive the servo here if (servoBoard != null) { System.out.println("Setting the servo to " + servoValue); if (servoValue < -90 || servoValue > 90) System.err.println("Between -90 and 90 only"); else { int on = 0; int off = (int)(servoMin + (((double)(servoValue + 90) / 180d) * (servoMax - servoMin))); System.out.println("setPWM(" + servo + ", " + on + ", " + off + ");"); servoBoard.setPWM(servo, on, off); System.out.println("-------------------"); } } } @Override public void onMessage(byte[] bb) { System.out.println(" . Message for you (ByteBuffer) ..."); System.out.println("Length:" + bb.length); try { FileOutputStream fos = new FileOutputStream("binary.xxx"); for (int i=0; i<bb.length; i++) fos.write(bb[i]); fos.close(); System.out.println("... was written in binary.xxx"); } catch (Exception ex) { ex.printStackTrace(); } } @Override public void onConnect() { System.out.println(" .You're in!"); keepWorking = true; } @Override public void onClose() { System.out.println(" .Connection has been closed..."); keepWorking = false; } @Override public void onError(String error) { System.out.println(" .Oops! error [" + error + "]"); keepWorking = false; // Careful with that one..., in case of a fallback, use the value returned by the init method. } @Override public void setStatus(String status) { System.out.println(" .Your status is now [" + status + "]"); } @Override public void onPong(String s) { if (DEBUG) System.out.println("WS Pong"); } @Override public void onPing(String s) { if (DEBUG) System.out.println("WS Ping"); } @Override public void onHandShakeSentAsClient() { System.out.println("WS-HS sent as client"); } @Override public void onHandShakeReceivedAsServer() { if (DEBUG) System.out.println("WS-HS received as server"); } @Override public void onHandShakeReceivedAsClient() { if (DEBUG) System.out.println("WS-HS received as client"); } }; try { webSocketClient = new ClientFacade(serverURI, targetedTransports, serverListener); keepWorking = webSocketClient.init(); } catch (Exception ex) { ex.printStackTrace(); } } public static void main(String[] args) throws Exception { System.out.println("System variable ws.uri can be used if the URL is not ws://localhost:9876/"); new WebSocketListener(); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/samples/ws/WebSocketListener.java
Java
mit
5,127
package adafruiti2c.samples; import adafruiti2c.servo.AdafruitPCA9685; import java.io.BufferedReader; import java.io.InputStreamReader; /* * Standard servo * TowerPro SG-5010 * * Enter the angle interactively, and see for yourself. */ public class Servo002 { private static final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); public static String userInput(String prompt) { String retString = ""; System.err.print(prompt); try { retString = stdin.readLine(); } catch(Exception e) { System.out.println(e); String s; try { s = userInput("<Oooch/>"); } catch(Exception exception) { exception.printStackTrace(); } } return retString; } public static void main(String[] args) { AdafruitPCA9685 servoBoard = new AdafruitPCA9685(); int freq = 60; servoBoard.setPWMFreq(freq); // Set frequency in Hz // For the TowerPro SG-5010 int servoMin = 130; // -90 deg int servoMax = 615; // +90 deg final int STANDARD_SERVO_CHANNEL = 15; int servo = STANDARD_SERVO_CHANNEL; boolean keepGoing = true; System.out.println("[" + servoMin + ", " + servoMax + "]"); System.out.println("Enter 'quit' to exit."); while (keepGoing) { String s1 = userInput("Angle in degrees (0: middle, -90: full left, 90: full right) ? > "); if ("QUIT".equalsIgnoreCase(s1)) keepGoing = false; else { try { int angle = Integer.parseInt(s1); if (angle < -90 || angle > 90) System.err.println("Between -90 and 90 only"); else { int on = 0; int off = (int)(servoMin + (((double)(angle + 90) / 180d) * (servoMax - servoMin))); System.out.println("setPWM(" + servo + ", " + on + ", " + off + ");"); servoBoard.setPWM(servo, on, off); System.out.println("-------------------"); } } catch (Exception ex) { ex.printStackTrace(); } } } System.out.println("Done."); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/samples/Servo002.java
Java
mit
2,182
package adafruiti2c.samples; import adafruiti2c.servo.AdafruitPCA9685; import java.io.BufferedReader; import java.io.InputStreamReader; /* * Two servos - one standard, one continous * Enter all the values from the command line, and see for yourself. */ public class Servo001 { private static final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); public static String userInput(String prompt) { String retString = ""; System.err.print(prompt); try { retString = stdin.readLine(); } catch(Exception e) { System.out.println(e); String s; try { s = userInput("<Oooch/>"); } catch(Exception exception) { exception.printStackTrace(); } } return retString; } public static void main(String[] args) { AdafruitPCA9685 servoBoard = new AdafruitPCA9685(); int freq = 60; String sFreq = userInput("freq (40-1000) ? > "); try { freq = Integer.parseInt(sFreq); } catch (NumberFormatException nfe) { System.err.println("Defaulting freq to 60"); nfe.printStackTrace(); } if (freq < 40 || freq > 1000) throw new IllegalArgumentException("Freq only between 40 and 1000."); servoBoard.setPWMFreq(freq); // Set frequency in Hz final int CONTINUOUS_SERVO_CHANNEL = 14; final int STANDARD_SERVO_CHANNEL = 15; int servo = STANDARD_SERVO_CHANNEL; String sServo = userInput("Servo: Continuous [C], Standard [S] > "); if ("C".equalsIgnoreCase(sServo)) servo = CONTINUOUS_SERVO_CHANNEL; else if ("S".equalsIgnoreCase(sServo)) servo = STANDARD_SERVO_CHANNEL; else System.out.println("Only C or S... Defaulting to Standard."); boolean keepGoing = true; System.out.println("Enter 'quit' to exit."); while (keepGoing) { String s1 = userInput("on (0..4095) ? > "); if ("QUIT".equalsIgnoreCase(s1)) keepGoing = false; else { try { int on = Integer.parseInt(s1); String s2 = userInput("off (0..4095) ? > "); int off = Integer.parseInt(s2); if (on < 0 || on > 4095 || off < 0 || off > 4095) System.out.println("Values between 0 and 4095."); else if (off < on) System.out.println("Off is lower than On..."); else { System.out.println("setPWM(" + servo + ", " + on + ", " + off + ");"); servoBoard.setPWM(servo, on, off); System.out.println("-------------------"); } } catch (Exception ex) { ex.printStackTrace(); } } } System.out.println("Done."); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/samples/Servo001.java
Java
mit
2,764
package adafruiti2c.samples; import adafruiti2c.servo.AdafruitPCA9685; /* * Standard, all the way, clockwise, counterclockwise */ public class DemoStandard { private static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } public static void main(String[] args) { AdafruitPCA9685 servoBoard = new AdafruitPCA9685(); int freq = 60; servoBoard.setPWMFreq(freq); // Set frequency in Hz // final int CONTINUOUS_SERVO_CHANNEL = 14; final int STANDARD_SERVO_CHANNEL = 13; // 15 int servo = STANDARD_SERVO_CHANNEL; int servoMin = 122; int servoMax = 615; int diff = servoMax - servoMin; System.out.println("Min:" + servoMin + ", Max:" + servoMax + ", diff:" + diff); try { servoBoard.setPWM(servo, 0, 0); // Stop the standard one waitfor(2000); System.out.println("Let's go, 1 by 1"); for (int i=servoMin; i<=servoMax; i++) { System.out.println("i=" + i + ", " + (-90f + (((float)(i - servoMin) / (float)diff) * 180f))); servoBoard.setPWM(servo, 0, i); waitfor(10); } for (int i=servoMax; i>=servoMin; i--) { System.out.println("i=" + i + ", " + (-90f + (((float)(i - servoMin) / (float)diff) * 180f))); servoBoard.setPWM(servo, 0, i); waitfor(10); } servoBoard.setPWM(servo, 0, 0); // Stop the standard one waitfor(2000); System.out.println("Let's go, 1 deg by 1 deg"); for (int i=servoMin; i<=servoMax; i+=(diff / 180)) { System.out.println("i=" + i + ", " + Math.round(-90f + (((float)(i - servoMin) / (float)diff) * 180f))); servoBoard.setPWM(servo, 0, i); waitfor(10); } for (int i=servoMax; i>=servoMin; i-=(diff / 180)) { System.out.println("i=" + i + ", " + Math.round(-90f + (((float)(i - servoMin) / (float)diff) * 180f))); servoBoard.setPWM(servo, 0, i); waitfor(10); } servoBoard.setPWM(servo, 0, 0); // Stop the standard one waitfor(2000); float[] degValues = { -10, 0, -90, 45, -30, 90, 10, 20, 30, 40, 50, 60, 70, 80, 90, 0 }; for (float f : degValues) { int pwm = degreeToPWM(servoMin, servoMax, f); System.out.println(f + " degrees (" + pwm + ")"); servoBoard.setPWM(servo, 0, pwm); waitfor(1500); } } finally { servoBoard.setPWM(servo, 0, 0); // Stop the standard one } System.out.println("Done."); } /* * deg in [-90..90] */ private static int degreeToPWM(int min, int max, float deg) { int diff = max - min; float oneDeg = diff / 180f; return Math.round(min + ((deg + 90) * oneDeg)); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/samples/DemoStandard.java
Java
mit
2,811
package adafruiti2c.samples; import adafruiti2c.servo.AdafruitPCA9685; import java.io.BufferedReader; import java.io.InputStreamReader; /* * Continuous servo * Parallax Futaba S148 * * Enter the speed interactively, and see for yourself. */ public class Servo003 { private static final BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)); public static String userInput(String prompt) { String retString = ""; System.err.print(prompt); try { retString = stdin.readLine(); } catch(Exception e) { System.out.println(e); String s; try { s = userInput("<Oooch/>"); } catch(Exception exception) { exception.printStackTrace(); } } return retString; } public static void main(String[] args) { AdafruitPCA9685 servoBoard = new AdafruitPCA9685(); int freq = 60; servoBoard.setPWMFreq(freq); // Set frequency in Hz // For the Parallax Futaba S148 int servoMin = 130; // Full speed backward int servoMax = 615; // Full speed forward final int CONTINUOUS_SERVO_CHANNEL = 14; int servo = CONTINUOUS_SERVO_CHANNEL; boolean keepGoing = true; System.out.println("Enter 'quit' to exit."); while (keepGoing) { String s1 = userInput("Speed (0: stop, -100: full speed backward, 100: full speed forward) ? > "); if ("QUIT".equalsIgnoreCase(s1)) keepGoing = false; else { try { int speed = Integer.parseInt(s1); if (speed < -100 || speed > 100) System.err.println("Between -100 and 100 only"); else { int on = 0; int off = (int)(servoMin + (((double)(speed + 100) / 200d) * (servoMax - servoMin))); System.out.println("setPWM(" + servo + ", " + on + ", " + off + ");"); servoBoard.setPWM(servo, on, off); System.out.println("-------------------"); } } catch (Exception ex) { ex.printStackTrace(); } } } System.out.println("Done."); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/samples/Servo003.java
Java
mit
2,167
package adafruiti2c.servo; import com.pi4j.io.i2c.I2CBus; import com.pi4j.io.i2c.I2CDevice; import com.pi4j.io.i2c.I2CFactory; import java.io.IOException; /* * Servo Driver */ public class AdafruitPCA9685 { public final static int PCA9685_ADDRESS = 0x40; public final static int SUBADR1 = 0x02; public final static int SUBADR2 = 0x03; public final static int SUBADR3 = 0x04; public final static int MODE1 = 0x00; public final static int PRESCALE = 0xFE; public final static int LED0_ON_L = 0x06; public final static int LED0_ON_H = 0x07; public final static int LED0_OFF_L = 0x08; public final static int LED0_OFF_H = 0x09; public final static int ALL_LED_ON_L = 0xFA; public final static int ALL_LED_ON_H = 0xFB; public final static int ALL_LED_OFF_L = 0xFC; public final static int ALL_LED_OFF_H = 0xFD; private static boolean verbose = true; private int freq = 60; private I2CBus bus; private I2CDevice servoDriver; public AdafruitPCA9685() { this(PCA9685_ADDRESS); // 0x40 obtained through sudo i2cdetect -y 1 } public AdafruitPCA9685(int address) { try { // Get I2C bus bus = I2CFactory.getInstance(I2CBus.BUS_1); // Depends onthe RasPI version if (verbose) System.out.println("Connected to bus. OK."); // Get the device itself servoDriver = bus.getDevice(address); if (verbose) System.out.println("Connected to device. OK."); // Reseting servoDriver.write(MODE1, (byte)0x00); } catch (IOException e) { System.err.println(e.getMessage()); } } /** * * @param freq 40..1000 */ public void setPWMFreq(int freq) { this.freq = freq; float preScaleVal = 25000000.0f; // 25MHz preScaleVal /= 4096.0; // 4096: 12-bit preScaleVal /= freq; preScaleVal -= 1.0; if (verbose) { System.out.println("Setting PWM frequency to " + freq + " Hz"); System.out.println("Estimated pre-scale: " + preScaleVal); } double preScale = Math.floor(preScaleVal + 0.5); if (verbose) System.out.println("Final pre-scale: " + preScale); try { byte oldmode = (byte)servoDriver.read(MODE1); byte newmode = (byte)((oldmode & 0x7F) | 0x10); // sleep servoDriver.write(MODE1, newmode); // go to sleep servoDriver.write(PRESCALE, (byte)(Math.floor(preScale))); servoDriver.write(MODE1, oldmode); waitfor(5); servoDriver.write(MODE1, (byte)(oldmode | 0x80)); } catch (IOException ioe) { ioe.printStackTrace(); } } /** * * @param channel 0..15 * @param on 0..4095 (2^12 positions) * @param off 0..4095 (2^12 positions) */ public void setPWM(int channel, int on, int off) throws IllegalArgumentException { if (channel < 0 || channel > 15) { throw new IllegalArgumentException("Channel must be in [0, 15]"); } if (on < 0 || on > 4095) { throw new IllegalArgumentException("On must be in [0, 4095]"); } if (off < 0 || off > 4095) { throw new IllegalArgumentException("Off must be in [0, 4095]"); } if (on > off) { throw new IllegalArgumentException("Off must be greater than On"); } try { servoDriver.write(LED0_ON_L + 4 * channel, (byte)(on & 0xFF)); servoDriver.write(LED0_ON_H + 4 * channel, (byte)(on >> 8)); servoDriver.write(LED0_OFF_L + 4 * channel, (byte)(off & 0xFF)); servoDriver.write(LED0_OFF_H + 4 * channel, (byte)(off >> 8)); } catch (IOException ioe) { ioe.printStackTrace(); } } private static void waitfor(long howMuch) { try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); } } /** * * @param channel 0..15 * @param pulseMS in ms. */ public void setServoPulse(int channel, float pulseMS) { double pulseLength = 1000000; // 1s = 1,000,000 us per pulse. "us" is to be read "micro (mu) sec". pulseLength /= this.freq; // 40..1000 Hz pulseLength /= 4096; // 12 bits of resolution int pulse = (int)(pulseMS * 1000); pulse /= pulseLength; if (verbose) System.out.println(pulseLength + " us per bit, pulse:" + pulse); this.setPWM(channel, 0, pulse); } /* * Servo | Standard | Continuous * ------------+----------+------------------ * 1.5ms pulse | 0 deg | Stop * 2ms pulse | 90 deg |FullSpeed forward * 1ms pulse | -90 deg |FullSpeed backward * ------------+----------+------------------ */ public static void main(String[] args) { int freq = 60; if (args.length > 0) freq = Integer.parseInt(args[0]); AdafruitPCA9685 servoBoard = new AdafruitPCA9685(); servoBoard.setPWMFreq(freq); // Set frequency to 60 Hz int servoMin = 122; // 130; // was 150. Min pulse length out of 4096 int servoMax = 615; // was 600. Max pulse length out of 4096 final int CONTINUOUS_SERVO_CHANNEL = 14; final int STANDARD_SERVO_CHANNEL = 15; for (int i=0; false && i<5; i++) { System.out.println("i=" + i); servoBoard.setPWM(STANDARD_SERVO_CHANNEL, 0, servoMin); servoBoard.setPWM(CONTINUOUS_SERVO_CHANNEL, 0, servoMin); waitfor(1000); servoBoard.setPWM(STANDARD_SERVO_CHANNEL, 0, servoMax); servoBoard.setPWM(CONTINUOUS_SERVO_CHANNEL, 0, servoMax); waitfor(1000); } servoBoard.setPWM(CONTINUOUS_SERVO_CHANNEL, 0, 0); // Stop the continuous one servoBoard.setPWM(STANDARD_SERVO_CHANNEL, 0, 0); // Stop the standard one System.out.println("Done with the demo."); for (int i=servoMin; i<=servoMax; i++) { System.out.println("i=" + i); servoBoard.setPWM(STANDARD_SERVO_CHANNEL, 0, i); waitfor(10); } for (int i=servoMax; i>=servoMin; i--) { System.out.println("i=" + i); servoBoard.setPWM(STANDARD_SERVO_CHANNEL, 0, i); waitfor(10); } servoBoard.setPWM(CONTINUOUS_SERVO_CHANNEL, 0, 0); // Stop the continuous one servoBoard.setPWM(STANDARD_SERVO_CHANNEL, 0, 0); // Stop the standard one for (int i=servoMin; i<=servoMax; i++) { System.out.println("i=" + i); servoBoard.setPWM(CONTINUOUS_SERVO_CHANNEL, 0, i); waitfor(100); } for (int i=servoMax; i>=servoMin; i--) { System.out.println("i=" + i); servoBoard.setPWM(CONTINUOUS_SERVO_CHANNEL, 0, i); waitfor(100); } servoBoard.setPWM(CONTINUOUS_SERVO_CHANNEL, 0, 0); // Stop the continuous one servoBoard.setPWM(STANDARD_SERVO_CHANNEL, 0, 0); // Stop the standard one System.out.println("Done with the demo."); if (false) { System.out.println("Now, servoPulse"); servoBoard.setPWMFreq(250); // The same with setServoPulse for (int i=0; i<5; i++) { servoBoard.setServoPulse(STANDARD_SERVO_CHANNEL, 1f); servoBoard.setServoPulse(CONTINUOUS_SERVO_CHANNEL, 1f); waitfor(1000); servoBoard.setServoPulse(STANDARD_SERVO_CHANNEL, 2f); servoBoard.setServoPulse(CONTINUOUS_SERVO_CHANNEL, 2f); waitfor(1000); } // Stop, Middle servoBoard.setServoPulse(STANDARD_SERVO_CHANNEL, 1.5f); servoBoard.setServoPulse(CONTINUOUS_SERVO_CHANNEL, 1.5f); servoBoard.setPWM(CONTINUOUS_SERVO_CHANNEL, 0, 0); // Stop the continuous one } } public static void main__(String[] args) { double pulseLength = 1000000; // 1s = 1,000,000 us per pulse. "us" is to be read "micro (mu) sec". pulseLength /= 250; // 40..1000 Hz pulseLength /= 4096; // 12 bits of resolution int pulse = (int)(1.5 * 1000); pulse /= pulseLength; if (verbose) System.out.println(pulseLength + " us per bit, pulse:" + pulse); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruiti2c/servo/AdafruitPCA9685.java
Java
mit
7,952
package adafruitspi.sensor.main; import adafruitspi.sensor.AdafruitBMP183; import java.text.DecimalFormat; import java.text.NumberFormat; public class SampleBMP183Main { private final static NumberFormat T_FMT = new DecimalFormat("##0.0"); private final static NumberFormat P_FMT = new DecimalFormat("###0.00"); public static void main(String[] args) throws Exception { AdafruitBMP183 bmp183 = new AdafruitBMP183(); for (int i=0; i<10; i++) { double temp = bmp183.measureTemperature(); double press = bmp183.measurePressure(); System.out.println("Temperature: " + T_FMT.format(temp) + "\272C"); System.out.println("Pressure : " + P_FMT.format(press / 100.0) + " hPa"); try { Thread.sleep(1000); } catch (Exception ex) {} } AdafruitBMP183.shutdownBMP183(); System.out.println("Bye"); } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruitspi/sensor/main/SampleBMP183Main.java
Java
mit
857
package adafruitspi.sensor; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; /** * This one has an SPI interface (not I2C) */ public class AdafruitBMP183 { private final static boolean verbose = false; private static GpioController gpio; private static GpioPinDigitalInput misoInput = null; private static GpioPinDigitalOutput mosiOutput = null; private static GpioPinDigitalOutput clockOutput = null; private static GpioPinDigitalOutput chipSelectOutput = null; public final static class BMP183_REG { public final static int CAL_AC1 = 0xAA; public final static int CAL_AC2 = 0xAC; public final static int CAL_AC3 = 0xAE; public final static int CAL_AC4 = 0xB0; public final static int CAL_AC5 = 0xB2; public final static int CAL_AC6 = 0xB4; public final static int CAL_B1 = 0xB6; public final static int CAL_B2 = 0xB8; public final static int CAL_MB = 0xBA; public final static int CAL_MC = 0xBC; public final static int CAL_MD = 0xBE; // Chip ID. Value fixed to 0x55. Useful to check if communication works public final static int ID = 0xD0; public final static int ID_VALUE = 0x55; // VER Undocumented public final static int VER = 0xD1; // SOFT_RESET Write only. If set to 0xB6, will perform the same sequence as power on reset. public final static int SOFT_RESET = 0xE0; // CTRL_MEAS Controls measurements public final static int CTRL_MEAS = 0xF4; // DATA public final static int DATA = 0xF6; } // Commands public final static class BMP183_CMD { // Chip ID Value fixed to 0x55. Useful to check if communication works public final static int ID_VALUE = 0x55; // SPI bit to indicate READ or WRITE operation public final static int READWRITE = 0x80; // Read TEMPERATURE, Wait time 4.5 ms public final static int TEMP = 0x2E; public final static float TEMP_WAIT = 4.5f; // Read PRESSURE public final static int PRESS = 0x34; // 001 // PRESSURE reading modes // Example usage: (PRESS | (OVERSAMPLE_2 << 4) public final static int OVERSAMPLE_0 = 0x0; // ultra low power, no oversampling, wait time 4.5 ms public final static float OVERSAMPLE_0_WAIT = 4.5f; public final static int OVERSAMPLE_1 = 0x1; // standard, 2 internal samples, wait time 7.5 ms public final static float OVERSAMPLE_1_WAIT = 7.5f; public final static int OVERSAMPLE_2 = 0x2; // high resolution, 4 internal samples, wait time 13.5 ms public final static float OVERSAMPLE_2_WAIT = 13.5f; public final static int OVERSAMPLE_3 = 0x3; // ultra high resolution, 8 internal samples, Wait time 25.5 ms public final static float OVERSAMPLE_3_WAIT = 25.5f; } private int cal_AC1 = 0; private int cal_AC2 = 0; private int cal_AC3 = 0; private int cal_AC4 = 0; private int cal_AC5 = 0; private int cal_AC6 = 0; private int cal_B1 = 0; private int cal_B2 = 0; private int cal_MB = 0; private int cal_MC = 0; private int cal_MD = 0; private static Pin spiClk = RaspiPin.GPIO_14; // clock (pin #23) private static Pin spiMiso = RaspiPin.GPIO_13; // data in. MISO: Master In Slave Out (pin #21) private static Pin spiMosi = RaspiPin.GPIO_12; // data out. MOSI: Master Out Slave In (pin #19) private static Pin spiCs = RaspiPin.GPIO_10; // Chip Select (pin #24) private double B5 = 0d, B6 = 0d; private int UT = 0, UP = 0; // Uncompensated Temp & Press private final static float DELAY = 1f / 1000.0f; // SCK frequency 1 MHz ( 1/1000 ms) public AdafruitBMP183() throws Exception { iniBMP183(); // Check communication / read ID // int ret = this.readU8(BMP183_REG.ID); int ret = readByte(BMP183_REG.ID); if (ret != BMP183_CMD.ID_VALUE) { System.out.println("BMP183 returned 0x" + Integer.toHexString(ret) + " instead of 0x55. Communication failed, expect problems..."); shutdownBMP183(); System.exit(1); } else { if (verbose) System.out.println("Communication established."); readCalibrationData(); } } private static void iniBMP183() { gpio = GpioFactory.getInstance(); mosiOutput = gpio.provisionDigitalOutputPin(spiMosi, "MOSI", PinState.LOW); clockOutput = gpio.provisionDigitalOutputPin(spiClk, "CLK", PinState.LOW); chipSelectOutput = gpio.provisionDigitalOutputPin(spiCs, "CS", PinState.LOW); misoInput = gpio.provisionDigitalInputPin(spiMiso, "MISO"); } public static void shutdownBMP183() { gpio.shutdown(); } public void readCalibrationData() throws Exception { // Reads the calibration data from the IC cal_AC1 = mkInt16(readWord(BMP183_REG.CAL_AC1)); // INT16 cal_AC2 = mkInt16(readWord(BMP183_REG.CAL_AC2)); // INT16 cal_AC3 = mkInt16(readWord(BMP183_REG.CAL_AC3)); // INT16 cal_AC4 = mkUInt16(readWord(BMP183_REG.CAL_AC4)); // UINT16 cal_AC5 = mkUInt16(readWord(BMP183_REG.CAL_AC5)); // UINT16 cal_AC6 = mkUInt16(readWord(BMP183_REG.CAL_AC6)); // UINT16 cal_B1 = mkInt16(readWord(BMP183_REG.CAL_B1)); // INT16 cal_B2 = mkInt16(readWord(BMP183_REG.CAL_B2)); // INT16 cal_MB = mkInt16(readWord(BMP183_REG.CAL_MB)); // INT16 cal_MC = mkInt16(readWord(BMP183_REG.CAL_MC)); // INT16 cal_MD = mkInt16(readWord(BMP183_REG.CAL_MD)); // INT16 if (verbose) showCalibrationData(); } private static int mkInt16(int val) { int ret = val & 0x7FFF; if (val > 0x7FFF) ret -= 0x8000; // if (verbose) // System.out.println(val + " becomes " + ret); return ret; } private static int mkUInt16(int val) { int ret = val & 0xFFFF; return ret; } private void showCalibrationData() { // Displays the calibration values for debugging purposes System.out.println(">>> DBG: AC1 = " + cal_AC1); System.out.println(">>> DBG: AC2 = " + cal_AC2); System.out.println(">>> DBG: AC3 = " + cal_AC3); System.out.println(">>> DBG: AC4 = " + cal_AC4); System.out.println(">>> DBG: AC5 = " + cal_AC5); System.out.println(">>> DBG: AC6 = " + cal_AC6); System.out.println(">>> DBG: B1 = " + cal_B1); System.out.println(">>> DBG: B2 = " + cal_B2); System.out.println(">>> DBG: MB = " + cal_MB); System.out.println(">>> DBG: MC = " + cal_MC); System.out.println(">>> DBG: MD = " + cal_MD); } private final static int WRITE = 0; private final static int READ = 1; /** * * @param addr Register * @param value value to write * @param rw READ or WRITE * @param length length in bits * @return */ private int spiTransfer(int addr, int value, int rw, int length) { // Bit banging at address "addr", "rw" indicates READ (1) or WRITE (0) operation int retValue = 0; int spiAddr; if (rw == WRITE) spiAddr = addr & (~BMP183_CMD.READWRITE); else spiAddr = addr | BMP183_CMD.READWRITE; // System.out.println("SPI ADDR: 0x" + Integer.toHexString(spiAddr) + ", mode:" + rw); chipSelectOutput.low(); waitFor(DELAY); for (int i=0; i<8; i++) { int bit = spiAddr & (0x01 << (7 - i)); if (bit != 0) mosiOutput.high(); else mosiOutput.low(); clockOutput.low(); waitFor(DELAY); clockOutput.high(); waitFor(DELAY); } if (rw == READ) { for (int i=0; i<length; i++) { clockOutput.low(); waitFor(DELAY); int bit = misoInput.getState().getValue(); // TODO Check that clockOutput.high(); retValue = (retValue << 1) | bit; waitFor(DELAY); } } if (rw == WRITE) { for (int i=0; i<length; i++) { int bit = value & (0x01 << (length - 1 - i)); if (bit != 0) mosiOutput.high(); else mosiOutput.low(); clockOutput.low(); waitFor(DELAY); clockOutput.high(); waitFor(DELAY); } } chipSelectOutput.high(); return retValue; } private int readByte(int addr) { int retValue = spiTransfer(addr, 0, READ, 8); return retValue; } private int readWord(int addr) { return readWord(addr, 0); } // Read word from SPI interface from address "addr", option to extend read by up to 3 bits private int readWord(int addr, int extraBits) { int retValue = spiTransfer(addr, 0, READ, 16 + extraBits); return retValue; } private void writeByte(int addr, int value) { spiTransfer(addr, value, WRITE, 8); } // Start temperature measurement public double measureTemperature() { writeByte(BMP183_REG.CTRL_MEAS, BMP183_CMD.TEMP); waitFor(BMP183_CMD.TEMP_WAIT); // Read uncmpensated temperature this.UT = readWord(BMP183_REG.DATA); return calculateTemperature(); } // Calculate temperature in [degC] private double calculateTemperature() { double x1 = (this.UT - this.cal_AC6) * this.cal_AC5 / Math.pow(2, 15); double x2 = this.cal_MC * Math.pow(2, 11) / (x1 + this.cal_MD); this.B5 = x1 + x2; double t = (this.B5 + 8) / Math.pow(2, 4); return t / 10d; } public double measurePressure() { // Measure temperature is required for calculations double temp = measureTemperature(); // Read 3 samples of uncompensated pressure int[] up = new int[3]; for (int i=0; i<3; i++) { writeByte(BMP183_REG.CTRL_MEAS, BMP183_CMD.PRESS | (BMP183_CMD.OVERSAMPLE_3 << 4)); waitFor(BMP183_CMD.OVERSAMPLE_3_WAIT); up[i] = readWord(BMP183_REG.DATA, 3); } this.UP = (up[0] + up[1] + up[2]) / 3; return calculatePressure(); } private double calculatePressure() { this.B6 = this.B5 - 4000; double x1 = (this.cal_B2 * (this.B6 * this.B6 / Math.pow(2, 12))) / Math.pow(2, 11); double x2 = this.cal_AC2 * this.B6 / Math.pow(2, 11); double x3 = x1 + x2; double b3 = (double)((((this.cal_AC1 * 4 + (int)x3) << BMP183_CMD.OVERSAMPLE_3) + 2) / 4); x1 = this.cal_AC3 * this.B6 / Math.pow(2, 13); x2 = (this.cal_B1 * (this.B6 * this.B6 / Math.pow(2, 12))) / Math.pow(2, 16); x3 = ((x1 + x2) + 2) / Math.pow(2, 2); double b4 = (this.cal_AC4 * ((int)x3 + 32768) / Math.pow(2, 15)); double b7 = (this.UP - (int)b3) * (50000 >> BMP183_CMD.OVERSAMPLE_3); double p = ((b7 * 2) / b4); x1 = (p / Math.pow(2, 8)) * (p / Math.pow(2, 8)); x1 = (x1 * 3038) / Math.pow(2, 16); x2 = (-7357 * p) / Math.pow(2, 16); return p + (x1 + x2 + 3791) / Math.pow(2, 4); } private void waitFor(float ms) // in ms { long _ms = (long)ms; int ns = (int)((ms - _ms) * 1E6); // System.out.println("Wait:" + _ms + " ms, " + ns + " ns"); try { Thread.sleep(_ms, ns); } catch (Exception ex) { System.err.println("Wait for:" + ms + ", => " + _ms + " ms, " + ns + " ns"); ex.printStackTrace(); } } }
12nosanshiro-pi4j-sample
AdafruitI2C/src/adafruitspi/sensor/AdafruitBMP183.java
Java
mit
11,344
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP -Ddemo=false adafruiti2c.gui.gyro.GyroscopeUI
12nosanshiro-pi4j-sample
AdafruitI2C/l3gd20.gui
Shell
mit
125
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.AdafruitTSL2561
12nosanshiro-pi4j-sample
AdafruitI2C/tsl2561
Shell
mit
114
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.AdafruitBMP180
12nosanshiro-pi4j-sample
AdafruitI2C/bmp180
Shell
mit
113
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:../../olivsoft/all-libs/nmeaparser.jar sudo java -cp $CP adafruiti2c.sensor.AdafruitBMP180NMEA
12nosanshiro-pi4j-sample
AdafruitI2C/bmp180nmea
Shell
mit
163
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.servo.AdafruitPCA9685 $*
12nosanshiro-pi4j-sample
AdafruitI2C/servo
Shell
mit
117
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.samples.DemoContinuous
12nosanshiro-pi4j-sample
AdafruitI2C/continuous
Shell
mit
115
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.AdafruitVCNL4000
12nosanshiro-pi4j-sample
AdafruitI2C/vcnl4000
Shell
mit
115
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP adafruiti2c.sensor.AdafruitLSM303
12nosanshiro-pi4j-sample
AdafruitI2C/lsm303
Shell
mit
114
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:../../olivsoft/all-libs/nmeaparser.jar CP=$CP:../../olivsoft/all-libs/nmeareader.jar CP=$CP:../../olivsoft/all-3rd-party/xmlparserv2.jar sudo java -cp $CP adafruiti2c.sensor.main.SampleBMP180NMEAMain
12nosanshiro-pi4j-sample
AdafruitI2C/new.pure.nmea.reader
Shell
mit
269
#!/bin/bash echo Two leds!! CP=./classes:$PI4J_HOME/lib/pi4j-core.jar sudo java -Dverbose=true -cp $CP twoleds.MainController
12nosanshiro-pi4j-sample
TwoLeds/run
Shell
mit
126
package twoleds.led; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.Pin; import com.pi4j.io.gpio.PinState; public class OneLed { private GpioPinDigitalOutput led = null; private String name; public OneLed(GpioController gpio, Pin pin, String name) { this.name = name; led = gpio.provisionDigitalOutputPin(pin, "Led", PinState.LOW); } public void on() { if ("true".equals(System.getProperty("verbose", "false"))) System.out.println(this.name + " is on."); led.high(); } public void off() { if ("true".equals(System.getProperty("verbose", "false"))) System.out.println(this.name + " is off."); led.low(); } }
12nosanshiro-pi4j-sample
TwoLeds/src/twoleds/led/OneLed.java
Java
mit
739
package twoleds; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.RaspiPin; import twoleds.led.OneLed; public class MainController { public static void main(String[] args) { GpioController gpio = GpioFactory.getInstance(); OneLed yellowLed = new OneLed(gpio, RaspiPin.GPIO_01, "yellow"); OneLed greenLed = new OneLed(gpio, RaspiPin.GPIO_04, "green"); long step = 50L; for (int i=0; i<10; i++) { yellowLed.on(); try { Thread.sleep(5 * step); } catch (InterruptedException ie) {} yellowLed.off(); greenLed.on(); try { Thread.sleep(5 * step); } catch (InterruptedException ie) {} yellowLed.on(); try { Thread.sleep(10 * step); } catch (InterruptedException ie) {} yellowLed.off(); greenLed.off(); try { Thread.sleep(step); } catch (InterruptedException ie) {} } gpio.shutdown(); } }
12nosanshiro-pi4j-sample
TwoLeds/src/twoleds/MainController.java
Java
mit
948
#!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP camera.SnapShot
12nosanshiro-pi4j-sample
Camera/snap
Shell
mit
95
package camera; public class SnapShot { //private final static String SNAPSHOT_COMMAND = "raspistill -rot 180 --width 200 --height 150 --timeout 1 --output snap" + i + ".jpg --nopreview"; //private final static String SNAPSHOT_COMMAND = "fswebcam snap" + i + ".jpg"; public static void main(String[] args) throws Exception { Runtime rt = Runtime.getRuntime(); for (int i=0; i<10; i++) { long before = System.currentTimeMillis(); Process snap = rt.exec("fswebcam snap" + i + ".jpg"); snap.waitFor(); long after = System.currentTimeMillis(); System.out.println("Snapshot #" + i + " done in " + Long.toString(after - before) + " ms."); // Detect brightest spot here // TODO Analyze image here } } }
12nosanshiro-pi4j-sample
Camera/src/camera/SnapShot.java
Java
mit
764
/** Automatically generated file. DO NOT MODIFY */ package home.remote.control; public final class BuildConfig { public final static boolean DEBUG = true; }
12nosanshiro-pi4j-sample
HomeRemoteControl/gen/home/remote/control/BuildConfig.java
Java
mit
161
package home.remote.control.util; import android.app.Activity; import android.os.Build; import android.view.View; /** * A utility class that helps with showing and hiding system UI such as the * status bar and navigation/system bar. This class uses backward-compatibility * techniques described in <a href= * "http://developer.android.com/training/backward-compatible-ui/index.html"> * Creating Backward-Compatible UIs</a> to ensure that devices running any * version of ndroid OS are supported. More specifically, there are separate * implementations of this abstract class: for newer devices, * {@link #getInstance} will return a {@link SystemUiHiderHoneycomb} instance, * while on older devices {@link #getInstance} will return a * {@link SystemUiHiderBase} instance. * <p> * For more on system bars, see <a href= * "http://developer.android.com/design/get-started/ui-overview.html#system-bars" * > System Bars</a>. * * @see android.view.View#setSystemUiVisibility(int) * @see android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN */ public abstract class SystemUiHider { /** * When this flag is set, the * {@link android.view.WindowManager.LayoutParams#FLAG_LAYOUT_IN_SCREEN} * flag will be set on older devices, making the status bar "float" on top * of the activity layout. This is most useful when there are no controls at * the top of the activity layout. * <p> * This flag isn't used on newer devices because the <a * href="http://developer.android.com/design/patterns/actionbar.html">action * bar</a>, the most important structural element of an Android app, should * be visible and not obscured by the system UI. */ public static final int FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES = 0x1; /** * When this flag is set, {@link #show()} and {@link #hide()} will toggle * the visibility of the status bar. If there is a navigation bar, show and * hide will toggle low profile mode. */ public static final int FLAG_FULLSCREEN = 0x2; /** * When this flag is set, {@link #show()} and {@link #hide()} will toggle * the visibility of the navigation bar, if it's present on the device and * the device allows hiding it. In cases where the navigation bar is present * but cannot be hidden, show and hide will toggle low profile mode. */ public static final int FLAG_HIDE_NAVIGATION = FLAG_FULLSCREEN | 0x4; /** * The activity associated with this UI hider object. */ protected Activity mActivity; /** * The view on which {@link View#setSystemUiVisibility(int)} will be called. */ protected View mAnchorView; /** * The current UI hider flags. * * @see #FLAG_FULLSCREEN * @see #FLAG_HIDE_NAVIGATION * @see #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES */ protected int mFlags; /** * The current visibility callback. */ protected OnVisibilityChangeListener mOnVisibilityChangeListener = sDummyListener; /** * Creates and returns an instance of {@link SystemUiHider} that is * appropriate for this device. The object will be either a * {@link SystemUiHiderBase} or {@link SystemUiHiderHoneycomb} depending on * the device. * * @param activity * The activity whose window's system UI should be controlled by * this class. * @param anchorView * The view on which {@link View#setSystemUiVisibility(int)} will * be called. * @param flags * Either 0 or any combination of {@link #FLAG_FULLSCREEN}, * {@link #FLAG_HIDE_NAVIGATION}, and * {@link #FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES}. */ public static SystemUiHider getInstance(Activity activity, View anchorView, int flags) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { return new SystemUiHiderHoneycomb(activity, anchorView, flags); } else { return new SystemUiHiderBase(activity, anchorView, flags); } } protected SystemUiHider(Activity activity, View anchorView, int flags) { mActivity = activity; mAnchorView = anchorView; mFlags = flags; } /** * Sets up the system UI hider. Should be called from * {@link Activity#onCreate}. */ public abstract void setup(); /** * Returns whether or not the system UI is visible. */ public abstract boolean isVisible(); /** * Hide the system UI. */ public abstract void hide(); /** * Show the system UI. */ public abstract void show(); /** * Toggle the visibility of the system UI. */ public void toggle() { if (isVisible()) { hide(); } else { show(); } } /** * Registers a callback, to be triggered when the system UI visibility * changes. */ public void setOnVisibilityChangeListener( OnVisibilityChangeListener listener) { if (listener == null) { listener = sDummyListener; } mOnVisibilityChangeListener = listener; } /** * A dummy no-op callback for use when there is no other listener set. */ private static OnVisibilityChangeListener sDummyListener = new OnVisibilityChangeListener() { @Override public void onVisibilityChange(boolean visible) { } }; /** * A callback interface used to listen for system UI visibility changes. */ public interface OnVisibilityChangeListener { /** * Called when the system UI visibility has changed. * * @param visible * True if the system UI is visible. */ public void onVisibilityChange(boolean visible); } }
12nosanshiro-pi4j-sample
HomeRemoteControl/src/home/remote/control/util/SystemUiHider.java
Java
mit
5,403
package home.remote.control.util; import android.app.Activity; import android.view.View; import android.view.WindowManager; /** * A base implementation of {@link SystemUiHider}. Uses APIs available in all * API levels to show and hide the status bar. */ public class SystemUiHiderBase extends SystemUiHider { /** * Whether or not the system UI is currently visible. This is a cached value * from calls to {@link #hide()} and {@link #show()}. */ private boolean mVisible = true; /** * Constructor not intended to be called by clients. Use * {@link SystemUiHider#getInstance} to obtain an instance. */ protected SystemUiHiderBase(Activity activity, View anchorView, int flags) { super(activity, anchorView, flags); } @Override public void setup() { if ((mFlags & FLAG_LAYOUT_IN_SCREEN_OLDER_DEVICES) == 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } } @Override public boolean isVisible() { return mVisible; } @Override public void hide() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(false); mVisible = false; } @Override public void show() { if ((mFlags & FLAG_FULLSCREEN) != 0) { mActivity.getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } mOnVisibilityChangeListener.onVisibilityChange(true); mVisible = true; } }
12nosanshiro-pi4j-sample
HomeRemoteControl/src/home/remote/control/util/SystemUiHiderBase.java
Java
mit
1,708
package home.remote.control.util; import android.annotation.TargetApi; import android.app.Activity; import android.os.Build; import android.view.View; import android.view.WindowManager; /** * An API 11+ implementation of {@link SystemUiHider}. Uses APIs available in * Honeycomb and later (specifically {@link View#setSystemUiVisibility(int)}) to * show and hide the system UI. */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public class SystemUiHiderHoneycomb extends SystemUiHiderBase { /** * Flags for {@link View#setSystemUiVisibility(int)} to use when showing the * system UI. */ private int mShowFlags; /** * Flags for {@link View#setSystemUiVisibility(int)} to use when hiding the * system UI. */ private int mHideFlags; /** * Flags to test against the first parameter in * {@link android.view.View.OnSystemUiVisibilityChangeListener#onSystemUiVisibilityChange(int)} * to determine the system UI visibility state. */ private int mTestFlags; /** * Whether or not the system UI is currently visible. This is cached from * {@link android.view.View.OnSystemUiVisibilityChangeListener}. */ private boolean mVisible = true; /** * Constructor not intended to be called by clients. Use * {@link SystemUiHider#getInstance} to obtain an instance. */ protected SystemUiHiderHoneycomb(Activity activity, View anchorView, int flags) { super(activity, anchorView, flags); mShowFlags = View.SYSTEM_UI_FLAG_VISIBLE; mHideFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; mTestFlags = View.SYSTEM_UI_FLAG_LOW_PROFILE; if ((mFlags & FLAG_FULLSCREEN) != 0) { // If the client requested fullscreen, add flags relevant to hiding // the status bar. Note that some of these constants are new as of // API 16 (Jelly Bean). It is safe to use them, as they are inlined // at compile-time and do nothing on pre-Jelly Bean devices. mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN; mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN; } if ((mFlags & FLAG_HIDE_NAVIGATION) != 0) { // If the client requested hiding navigation, add relevant flags. mShowFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; mHideFlags |= View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; mTestFlags |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION; } } /** {@inheritDoc} */ @Override public void setup() { mAnchorView .setOnSystemUiVisibilityChangeListener(mSystemUiVisibilityChangeListener); } /** {@inheritDoc} */ @Override public void hide() { mAnchorView.setSystemUiVisibility(mHideFlags); } /** {@inheritDoc} */ @Override public void show() { mAnchorView.setSystemUiVisibility(mShowFlags); } /** {@inheritDoc} */ @Override public boolean isVisible() { return mVisible; } private View.OnSystemUiVisibilityChangeListener mSystemUiVisibilityChangeListener = new View.OnSystemUiVisibilityChangeListener() { @Override public void onSystemUiVisibilityChange(int vis) { // Test against mTestFlags to see if the system UI is visible. if ((vis & mTestFlags) != 0) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { // Pre-Jelly Bean, we must manually hide the action bar // and use the old window flags API. mActivity.getActionBar().hide(); mActivity.getWindow().setFlags( WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } // Trigger the registered listener and cache the visibility // state. mOnVisibilityChangeListener.onVisibilityChange(false); mVisible = false; } else { mAnchorView.setSystemUiVisibility(mShowFlags); if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) { // Pre-Jelly Bean, we must manually show the action bar // and use the old window flags API. mActivity.getActionBar().show(); mActivity.getWindow().setFlags(0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } // Trigger the registered listener and cache the visibility // state. mOnVisibilityChangeListener.onVisibilityChange(true); mVisible = true; } } }; }
12nosanshiro-pi4j-sample
HomeRemoteControl/src/home/remote/control/util/SystemUiHiderHoneycomb.java
Java
mit
4,182
package home.remote.control; import home.remote.control.util.SystemUiHider; import android.annotation.TargetApi; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class RemoteControlActivity extends Activity { private RemoteControlActivity instance = this; /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * If set, will toggle the system UI visibility upon interaction. Otherwise, * will show the system UI visibility upon interaction. */ private static final boolean TOGGLE_ON_CLICK = true; /** * The flags to pass to {@link SystemUiHider#getInstance}. */ private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; /** * The instance of the {@link SystemUiHider} for this activity. */ private SystemUiHider mSystemUiHider; private Button buttonOn = null; private Button buttonOff = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_remote_control); final View controlsView = findViewById(R.id.fullscreen_content_controls); final View contentView = findViewById(R.id.fullscreen_content); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() { // Cached values. int mControlsHeight; int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { // If the ViewPropertyAnimator API is available // (Honeycomb MR2 and later), use it to animate the // in-layout UI controls at the bottom of the // screen. if (mControlsHeight == 0) { mControlsHeight = controlsView.getHeight(); } if (mShortAnimTime == 0) { mShortAnimTime = getResources().getInteger( android.R.integer.config_shortAnimTime); } controlsView .animate() .translationY(visible ? 0 : mControlsHeight) .setDuration(mShortAnimTime); } else { // If the ViewPropertyAnimator APIs aren't // available, simply show or hide the in-layout UI // controls. controlsView.setVisibility(visible ? View.VISIBLE : View.GONE); } if (visible && AUTO_HIDE) { // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); } } }); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (TOGGLE_ON_CLICK) { mSystemUiHider.toggle(); } else { mSystemUiHider.show(); } } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.button_on).setOnTouchListener(mDelayHideTouchListener); buttonOn = (Button)findViewById(R.id.button_on); buttonOff = (Button)findViewById(R.id.button_off); buttonOn.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { sendEmailMessage("{ 'operation':'turn-relay-on' }"); } catch (Exception ex) { Toast.makeText(instance.getApplicationContext(), "Error:\n" + ex.toString(), Toast.LENGTH_LONG).show(); } } }); buttonOff.setOnClickListener(new OnClickListener() { public void onClick(View v) { try { sendEmailMessage("{ 'operation':'turn-relay-off' }"); } catch (Exception ex) { Toast.makeText(instance.getApplicationContext(), "Error:\n" + ex.toString(), Toast.LENGTH_LONG).show(); } } }); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; } }; Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() { @Override public void run() { mSystemUiHider.hide(); } }; /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } private void sendEmailMessage(String message) { Intent i = new Intent(Intent.ACTION_SEND); i.setType("message/rfc822"); i.putExtra(Intent.EXTRA_EMAIL , new String[]{"olivier.lediouris@gmail.com"}); i.putExtra(Intent.EXTRA_SUBJECT, "PI Request"); i.putExtra(Intent.EXTRA_TEXT , message); try { startActivity(Intent.createChooser(i, "Send mail...")); // Toast.makeText(RemoteControlActivity.this, "Message has been sent.", Toast.LENGTH_SHORT).show(); } catch (android.content.ActivityNotFoundException ex) { Toast.makeText(RemoteControlActivity.this, "There is no email client installed.", Toast.LENGTH_SHORT).show(); } } }
12nosanshiro-pi4j-sample
HomeRemoteControl/src/home/remote/control/RemoteControlActivity.java
Java
mit
7,007
#!/bin/bash #!/bin/bash CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar sudo java -cp $CP rangesensor.HC_SR04
12nosanshiro-pi4j-sample
RangeSensor/run
Shell
mit
111
package rangesensor; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import java.text.DecimalFormat; import java.text.Format; /** * @see https://www.modmypi.com/blog/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi * * This version is multi-threaded. * This allows the management of a signal that does not come back. */ public class HC_SR04andLeds { private final static Format DF22 = new DecimalFormat("#0.00"); private final static double SOUND_SPEED = 34300; // in cm, 343 m/s private final static double DIST_FACT = SOUND_SPEED / 2; // round trip private final static int MIN_DIST = 5; private final static long BETWEEN_LOOPS = 500L; private final static long MAX_WAIT = 500L; private final static boolean DEBUG = false; public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - Range Sensor HC-SR04."); System.out.println("Will stop is distance is smaller than " + MIN_DIST + " cm"); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput trigPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "Trig", PinState.LOW); final GpioPinDigitalInput echoPin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, "Echo"); final GpioPinDigitalOutput ledOne = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_00, "One", PinState.LOW); final GpioPinDigitalOutput ledTwo = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "Two", PinState.LOW); final GpioPinDigitalOutput ledThree = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_02, "Three", PinState.LOW); final GpioPinDigitalOutput ledFour = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_03, "Four", PinState.LOW); final GpioPinDigitalOutput ledFive = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_06, "Five", PinState.LOW); final GpioPinDigitalOutput[] ledArray = new GpioPinDigitalOutput[] { ledOne, ledTwo, ledThree, ledFour, ledFive }; Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Oops!"); for (int i=0; i<ledArray.length; i++) ledArray[i].low(); gpio.shutdown(); System.out.println("Exiting nicely."); } }); System.out.println("Waiting for the sensor to be ready (2s)..."); Thread.sleep(2000L); Thread mainThread = Thread.currentThread(); boolean go = true; System.out.println("Looping until the distance is less than " + MIN_DIST + " cm"); while (go) { boolean ok = true; double start = 0d, end = 0d; if (DEBUG) System.out.println("Triggering module."); TriggerThread trigger = new TriggerThread(mainThread, trigPin, echoPin); trigger.start(); try { synchronized (mainThread) { long before = System.currentTimeMillis(); mainThread.wait(MAX_WAIT); long after = System.currentTimeMillis(); long diff = after - before; if (DEBUG) System.out.println("MainThread done waiting (" + Long.toString(diff) + " ms)"); if (diff >= MAX_WAIT) { ok = false; if (true || DEBUG) System.out.println("...Reseting."); if (trigger.isAlive()) trigger.interrupt(); } } } catch (Exception ex) { ex.printStackTrace(); ok = false; } if (ok) { start = trigger.getStart(); end = trigger.getEnd(); if (DEBUG) System.out.println("Measuring..."); if (end > 0 && start > 0) { double pulseDuration = (end - start) / 1000000000d; // in seconds double distance = pulseDuration * DIST_FACT; if (distance < 1000) // Less than 10 meters System.out.println("Distance: " + DF22.format(distance) + " cm."); // + " (" + pulseDuration + " = " + end + " - " + start + ")"); if (distance > 0 && distance < MIN_DIST) go = false; else { if (distance < 0) System.out.println("Dist:" + distance + ", start:" + start + ", end:" + end); for (int i=0; i<ledArray.length; i++) { if (distance < ((i+1) * 10)) { ledArray[i].high(); } else ledArray[i].low(); } try { Thread.sleep(BETWEEN_LOOPS); } catch (Exception ex) {} } } else { System.out.println("Hiccup!"); // try { Thread.sleep(2000L); } catch (Exception ex) {} } } } System.out.println("Done."); for (int i=0; i<ledArray.length; i++) ledArray[i].low(); trigPin.low(); // Off gpio.shutdown(); System.exit(0); } private static class TriggerThread extends Thread { private GpioPinDigitalOutput trigPin = null; private GpioPinDigitalInput echoPin = null; private Thread caller = null; private double start = 0D, end = 0D; public TriggerThread(Thread parent, GpioPinDigitalOutput trigger, GpioPinDigitalInput echo) { this.trigPin = trigger; this.echoPin = echo; this.caller = parent; } public void run() { trigPin.high(); // 10 microsec (10000 ns) to trigger the module (8 ultrasound bursts at 40 kHz) // https://www.dropbox.com/s/615w1321sg9epjj/hc-sr04-ultrasound-timing-diagram.png try { Thread.sleep(0, 10000); } catch (Exception ex) { ex.printStackTrace(); } trigPin.low(); // Wait for the signal to return while (echoPin.isLow()) start = System.nanoTime(); // There it is while (echoPin.isHigh()) end = System.nanoTime(); synchronized (caller) { caller.notify(); } } public double getStart() { return start; } public double getEnd() { return end; } } }
12nosanshiro-pi4j-sample
RangeSensor/src/rangesensor/HC_SR04andLeds.java
Java
mit
6,255
package rangesensor; import com.pi4j.io.gpio.GpioController; import com.pi4j.io.gpio.GpioFactory; import com.pi4j.io.gpio.GpioPinDigitalInput; import com.pi4j.io.gpio.GpioPinDigitalOutput; import com.pi4j.io.gpio.PinState; import com.pi4j.io.gpio.RaspiPin; import java.text.DecimalFormat; import java.text.Format; /** * @see https://www.modmypi.com/blog/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi * */ public class HC_SR04 { private final static Format DF22 = new DecimalFormat("#0.00"); private final static double SOUND_SPEED = 34300; // in cm, 343 m/s private final static double DIST_FACT = SOUND_SPEED / 2; // round trip private final static int MIN_DIST = 5; public static void main(String[] args) throws InterruptedException { System.out.println("GPIO Control - Range Sensor HC-SR04."); System.out.println("Will stop is distance is smaller than " + MIN_DIST + " cm"); // create gpio controller final GpioController gpio = GpioFactory.getInstance(); final GpioPinDigitalOutput trigPin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_04, "Trig", PinState.LOW); final GpioPinDigitalInput echoPin = gpio.provisionDigitalInputPin(RaspiPin.GPIO_05, "Echo"); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("Oops!"); gpio.shutdown(); System.out.println("Exiting nicely."); } }); System.out.println("Waiting for the sensor to be ready (2s)..."); Thread.sleep(2000); boolean go = true; System.out.println("Looping until the distance is less than " + MIN_DIST + " cm"); while (go) { double start = 0d, end = 0d; trigPin.high(); // 10 microsec to trigger the module (8 ultrasound bursts at 40 kHz) // https://www.dropbox.com/s/615w1321sg9epjj/hc-sr04-ultrasound-timing-diagram.png try { Thread.sleep(0, 10000); } catch (Exception ex) { ex.printStackTrace(); } trigPin.low(); // Wait for the signal to return while (echoPin.isLow()) start = System.nanoTime(); // There it is while (echoPin.isHigh()) end = System.nanoTime(); if (end > 0 && start > 0) { double pulseDuration = (end - start) / 1000000000d; // in seconds double distance = pulseDuration * DIST_FACT; if (distance < 1000) // Less than 10 meters System.out.println("Distance: " + DF22.format(distance) + " cm."); // + " (" + pulseDuration + " = " + end + " - " + start + ")"); if (distance > 0 && distance < MIN_DIST) go = false; else { if (distance < 0) System.out.println("Dist:" + distance + ", start:" + start + ", end:" + end); try { Thread.sleep(1000L); } catch (Exception ex) {} } } else { System.out.println("Hiccup!"); try { Thread.sleep(2000L); } catch (Exception ex) {} } } System.out.println("Done."); System. trigPin.low(); // Off gpio.shutdown(); } }
12nosanshiro-pi4j-sample
RangeSensor/src/rangesensor/HC_SR04.java
Java
mit
3,106
#!/bin/bash JAVAC_OPTIONS="-sourcepath ./src" JAVAC_OPTIONS="$JAVAC_OPTIONS -d ./classes" echo $JAVAC_OPTIONS CP=./classes # PI4J_HOME=/home/pi/pi4j/pi4j-distribution/target/distro-contents CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/almanactools.jar CP=$CP:./lib/geomutil.jar CP=$CP:./lib/nauticalalmanac.jar CP=$CP:./lib/nmeaparser.jar # JAVAC_OPTIONS="-verbose $JAVAC_OPTIONS" JAVAC_OPTIONS="$JAVAC_OPTIONS -cp $CP" COMMAND="javac $JAVAC_OPTIONS ./src/nmea/*.java ./src/readserialport/*.java" echo Compiling: $COMMAND $COMMAND echo Done
12nosanshiro-pi4j-sample
GPSandSun/compile
Shell
mit
546
#!/bin/bash echo Read serial port, parse the RMC String echo Usage $0 [BaudRate] \(default 9600\) echo Try 2400, 4800, 9600, 19200, 38400, 57600, 115200, ... CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/almanactools.jar CP=$CP:./lib/geomutil.jar CP=$CP:./lib/nauticalalmanac.jar CP=$CP:./lib/nmeaparser.jar CP=$CP:./lib/coreutilities.jar JAVA_OPTIONS= # Default serial port is /dev/ttyAMA0 <<<<<<< HEAD JAVA_OPTIONS="$JAVA_OPTIONS -Dport.name=/dev/ttyUSB0" ======= # JAVA_OPTIONS="$JAVA_OPTIONS -Dport.name=/dev/ttyUSB0" >>>>>>> 7c09936fdac377f880d4ad8ffae6b0b7375a94db JAVA_OPTIONS="$JAVA_OPTIONS -Dverbose=true" #sudo java -cp $CP $JAVA_OPTIONS nmea.CustomRMCReader $* sudo java -cp $CP $JAVA_OPTIONS nmea.CustomGGAReader $*
12nosanshiro-pi4j-sample
GPSandSun/run
Shell
mit
744
package readserialport; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; /** * Just reads the GPS data. * No parsing, just raw data. */ public class GPSDataReader { public static void main(String args[]) throws InterruptedException, NumberFormatException { int br = Integer.parseInt(System.getProperty("baud.rate", "9600")); String port = System.getProperty("port.name", Serial.DEFAULT_COM_PORT); if (args.length > 0) { try { br = Integer.parseInt(args[0]); } catch (Exception ex) { System.err.println(ex.getMessage()); } } System.out.println("Serial Communication."); System.out.println(" ... connect using settings: " + Integer.toString(br) + ", N, 8, 1."); System.out.println(" ... data received on serial port should be displayed below."); // create an instance of the serial communications class final Serial serial = SerialFactory.createInstance(); // create and register the serial data listener serial.addListener(new SerialDataListener() { @Override public void dataReceived(SerialDataEvent event) { // print out the data received to the console String data = event.getData(); System.out.println("Got Data (" + data.length() + " byte(s))"); if (data.startsWith("$")) System.out.println(data); else { String hexString = ""; char[] ca = data.toCharArray(); for (int i=0; i<ca.length; i++) hexString += (lpad(Integer.toHexString(ca[i]), "0", 2) + " "); System.out.println(hexString); } } }); final Thread t = Thread.currentThread(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println("\nShutting down..."); try { if (serial.isOpen()) { serial.close(); System.out.println("Serial port closed"); } synchronized (t) { t.notify(); System.out.println("Thread notified"); } } catch (Exception ex) { ex.printStackTrace(); } } }); try { System.out.println("Opening port [" + port + "]"); boolean open = false; while (!open) { serial.open(port, br); open = serial.isOpen(); System.out.println("Port is " + (open ? "" : "NOT ") + "opened."); if (!open) try { Thread.sleep(500L); } catch (Exception ex) {} } synchronized (t) { t.wait(); } System.out.println("Bye..."); } catch (InterruptedException ie) { ie.printStackTrace(); } } private static String lpad(String str, String with, int len) { String s = str; while (s.length() < len) s = with + s; return s; } }
12nosanshiro-pi4j-sample
GPSandSun/src/readserialport/GPSDataReader.java
Java
mit
3,901
package nmea; import calculation.AstroComputer; import calculation.SightReductionUtil; import java.text.DecimalFormat; import java.util.Calendar; import java.util.TimeZone; import ocss.nmea.api.NMEAClient; import ocss.nmea.api.NMEAEvent; import ocss.nmea.api.NMEAListener; import ocss.nmea.parser.GeoPos; import ocss.nmea.parser.RMC; import ocss.nmea.parser.StringParsers; /** * Reads the GPS Data, parse the RMC String * Display astronomical data */ public class CustomNMEAReader extends NMEAClient { private final static DecimalFormat DFH = new DecimalFormat("#0.00'\272'"); private final static DecimalFormat DFZ = new DecimalFormat("##0.00'\272'"); private static GeoPos prevPosition = null; private static long prevDateTime = -1L; public CustomNMEAReader() { super(); } @Override public void dataDetectedEvent(NMEAEvent e) { // System.out.println("Received:" + e.getContent()); manageData(e.getContent().trim()); } private static CustomNMEAReader customClient = null; private static void manageData(String sentence) { boolean valid = StringParsers.validCheckSum(sentence); if (valid) { String id = sentence.substring(3, 6); if ("RMC".equals(id)) { System.out.println(sentence); RMC rmc = StringParsers.parseRMC(sentence); // System.out.println(rmc.toString()); if (rmc != null && rmc.getRmcDate() != null && rmc.getGp() != null) { if ((prevDateTime == -1L || prevPosition == null) || (prevDateTime != (rmc.getRmcDate().getTime() / 1000) || !rmc.getGp().equals(prevPosition))) { Calendar current = Calendar.getInstance(TimeZone.getTimeZone("etc/UTC")); current.setTime(rmc.getRmcDate()); AstroComputer.setDateTime(current.get(Calendar.YEAR), current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH), current.get(Calendar.HOUR_OF_DAY), current.get(Calendar.MINUTE), current.get(Calendar.SECOND)); AstroComputer.calculate(); SightReductionUtil sru = new SightReductionUtil(AstroComputer.getSunGHA(), AstroComputer.getSunDecl(), rmc.getGp().lat, rmc.getGp().lng); sru.calculate(); Double he = sru.getHe(); Double z = sru.getZ(); System.out.println(current.getTime().toString() + ", He:" + DFH.format(he)+ ", Z:" + DFZ.format(z) + " (" + rmc.getGp().toString() + ")"); } prevPosition = rmc.getGp(); prevDateTime = (rmc.getRmcDate().getTime() / 1000); } else { if (rmc == null) System.out.println("... no RMC data in [" + sentence + "]"); else { String errMess = ""; if (rmc.getRmcDate() == null) errMess += ("no Date "); if (rmc.getGp() == null) errMess += ("no Pos "); System.out.println(errMess + "in [" + sentence + "]"); } } } else System.out.println("Read [" + sentence + "]"); } else System.out.println("Invalid data [" + sentence + "]"); } public static void main(String[] args) { System.setProperty("deltaT", System.getProperty("deltaT", "67.2810")); // 2014-Jan-01 int br = 9600; System.out.println("CustomNMEAReader invoked with " + args.length + " Parameter(s)."); for (String s : args) { System.out.println("CustomNMEAReader prm:" + s); try { br = Integer.parseInt(s); } catch (NumberFormatException nfe) {} } customClient = new CustomNMEAReader(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println ("\nShutting down nicely."); customClient.stopDataRead(); } }); customClient.initClient(); customClient.setReader(new CustomNMEASerialReader(customClient.getListeners(), br)); customClient.startWorking(); // Feignasse! } private void stopDataRead() { if (customClient != null) { for (NMEAListener l : customClient.getListeners()) l.stopReading(new NMEAEvent(this)); } } }
12nosanshiro-pi4j-sample
GPSandSun/src/nmea/CustomRMCReader.java
Java
mit
4,583
package nmea; import com.pi4j.io.serial.Serial; import com.pi4j.io.serial.SerialDataEvent; import com.pi4j.io.serial.SerialDataListener; import com.pi4j.io.serial.SerialFactory; import java.util.List; import ocss.nmea.api.NMEAEvent; import ocss.nmea.api.NMEAListener; import ocss.nmea.api.NMEAReader; public class CustomNMEASerialReader extends NMEAReader { private int baudRate = 4800; private CustomNMEASerialReader instance = this; public CustomNMEASerialReader(List<NMEAListener> al, int br) { super(al); baudRate = br; } @Override public void read() { if (System.getProperty("verbose", "false").equals("true")) System.out.println("From " + this.getClass().getName() + " Reading Serial Port."); super.enableReading(); // Opening Serial port try { final Serial serial = SerialFactory.createInstance(); // create and register the serial data listener serial.addListener(new SerialDataListener() { @Override public void dataReceived(SerialDataEvent event) { // System.out.print(/*"Read:\n" + */ event.getData()); instance.fireDataRead(new NMEAEvent(this, event.getData())); } }); String port = System.getProperty("port.name", Serial.DEFAULT_COM_PORT); if (System.getProperty("verbose", "false").equals("true")) System.out.println("Opening port [" + port + "]"); serial.open(port, baudRate); // Reading on Serial Port if (System.getProperty("verbose", "false").equals("true")) System.out.println("Port is " + (serial.isOpen() ? "" : "NOT ") + "open."); } catch (Exception ex) { ex.printStackTrace(); } } }
12nosanshiro-pi4j-sample
GPSandSun/src/nmea/CustomNMEASerialReader.java
Java
mit
1,735
package nmea; import calculation.AstroComputer; import calculation.SightReductionUtil; import java.text.DecimalFormat; import java.util.Calendar; import java.util.List; import java.util.TimeZone; import ocss.nmea.api.NMEAClient; import ocss.nmea.api.NMEAEvent; import ocss.nmea.api.NMEAListener; import ocss.nmea.parser.GeoPos; import ocss.nmea.parser.RMC; import ocss.nmea.parser.StringParsers; import ocss.nmea.parser.UTC; /** * Reads the GPS Data, parse the GGA String */ public class CustomGGAReader extends NMEAClient { public CustomGGAReader() { super(); } @Override public void dataDetectedEvent(NMEAEvent e) { // System.out.println("Received:" + e.getContent()); manageData(e.getContent().trim()); } private static CustomGGAReader customClient = null; private static void manageData(String sentence) { boolean valid = StringParsers.validCheckSum(sentence); if (valid) { String id = sentence.substring(3, 6); if ("GGA".equals(id)) { System.out.println(sentence); List<Object> al = StringParsers.parseGGA(sentence); UTC utc = (UTC)al.get(0); GeoPos pos = (GeoPos)al.get(1); Integer nbs = (Integer)al.get(2); Double alt = (Double)al.get(3); System.out.println("\tUTC:" + utc.toString() + "\tPos:" + pos.toString()); System.out.println("\t" + nbs.intValue() + " Satellite(s) in use"); System.out.println("\tAltitude:" + alt); System.out.println("------------------"); } // else // System.out.println("Read [" + sentence + "]"); } else System.out.println("Invalid data [" + sentence + "]"); } public static void main(String[] args) { int br = 9600; System.out.println("CustomNMEAReader invoked with " + args.length + " Parameter(s)."); for (String s : args) { System.out.println("CustomGGAReader prm:" + s); try { br = Integer.parseInt(s); } catch (NumberFormatException nfe) {} } customClient = new CustomGGAReader(); Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { System.out.println ("\nShutting down nicely."); customClient.stopDataRead(); } }); customClient.initClient(); customClient.setReader(new CustomNMEASerialReader(customClient.getListeners(), br)); customClient.startWorking(); // Feignasse! } private void stopDataRead() { if (customClient != null) { for (NMEAListener l : customClient.getListeners()) l.stopReading(new NMEAEvent(this)); } } }
12nosanshiro-pi4j-sample
GPSandSun/src/nmea/CustomGGAReader.java
Java
mit
2,640
package nmea; import calculation.AstroComputer; import calculation.SightReductionUtil; import java.io.BufferedReader; import java.io.FileReader; import java.text.DecimalFormat; import java.util.Calendar; import java.util.TimeZone; import ocss.nmea.parser.GeoPos; import ocss.nmea.parser.RMC; import ocss.nmea.parser.StringParsers; /** * Parse the RMC string from a log file. * No serial port involved */ public class WithFakedData { private final static DecimalFormat DFH = new DecimalFormat("#0.00'\272'"); private final static DecimalFormat DFZ = new DecimalFormat("#0.00'\272'"); private static GeoPos prevPosition = null; private static long prevDateTime = -1L; /* * deltaT, system variable. * See http://maia.usno.navy.mil/ser7/deltat.data */ public static void main(String[] args) throws Exception { System.setProperty("deltaT", "67.2810"); // 2014-Jan-01 BufferedReader br = new BufferedReader(new FileReader("raspPiLog.nmea")); String line = ""; boolean go = true; long nbRec = 0L, nbDisplay = 0L; while (go) { line = br.readLine(); if (line == null) go = false; else { nbRec++; boolean valid = StringParsers.validCheckSum(line); if (valid) { String id = line.substring(3, 6); if ("RMC".equals(id)) { // System.out.println(line); RMC rmc = StringParsers.parseRMC(line); // System.out.println(rmc.toString()); if (rmc.getRmcDate() != null && rmc.getGp() != null) { if ((prevDateTime == -1L || prevPosition == null) || (prevDateTime != (rmc.getRmcDate().getTime() / 1000) || !rmc.getGp().equals(prevPosition))) { nbDisplay++; Calendar current = Calendar.getInstance(TimeZone.getTimeZone("etc/UTC")); current.setTime(rmc.getRmcDate()); AstroComputer.setDateTime(current.get(Calendar.YEAR), current.get(Calendar.MONTH) + 1, current.get(Calendar.DAY_OF_MONTH), current.get(Calendar.HOUR_OF_DAY), // 12 - (int)Math.round(AstroComputer.getTimeZoneOffsetInHours(TimeZone.getTimeZone(ts.getTimeZone()))), current.get(Calendar.MINUTE), current.get(Calendar.SECOND)); AstroComputer.calculate(); SightReductionUtil sru = new SightReductionUtil(AstroComputer.getSunGHA(), AstroComputer.getSunDecl(), rmc.getGp().lat, rmc.getGp().lng); sru.calculate(); Double he = sru.getHe(); Double z = sru.getZ(); System.out.println(current.getTime().toString() + ", He:" + DFH.format(he)+ ", Z:" + DFZ.format(z)); } prevPosition = rmc.getGp(); prevDateTime = (rmc.getRmcDate().getTime() / 1000); } } } } } br.close(); System.out.println(nbRec + " record(s)."); System.out.println(nbDisplay + " displayed."); } }
12nosanshiro-pi4j-sample
GPSandSun/src/nmea/WithFakedData.java
Java
mit
3,427
#!/bin/bash echo Read serial port, returns raw data echo Usage $0 [BaudRate] \(default 9600\) echo Try 2400, 4800, 9600, 19200, 38400, 57600, 115200, ... CP=./classes CP=$CP:$PI4J_HOME/lib/pi4j-core.jar CP=$CP:./lib/almanactools.jar CP=$CP:./lib/geomutil.jar CP=$CP:./lib/nauticalalmanac.jar CP=$CP:./lib/nmeaparser.jar CP=$CP:./lib/coreutilities.jar JAVA_OPTIONS= # Default serial port is /dev/ttyAMA0 # JAVA_OPTIONS="$JAVA_OPTIONS -Dport.name=/dev/ttyUSB0" JAVA_OPTIONS="$JAVA_OPTIONS -Dverbose=true" <<<<<<< HEAD DEBUG_OPTIONS= # DEBUG_OPTIONS="-client -agentlib:jdwp=transport=dt_socket,server=y,address=1044" echo ---------------------------------------------------------- sudo java $DEBUG_OPTIONS -cp $CP $JAVA_OPTIONS readserialport.GPSDataReader $* ======= sudo java -cp $CP $JAVA_OPTIONS readserialport.GPSDataReader $* >>>>>>> 7c09936fdac377f880d4ad8ffae6b0b7375a94db
12nosanshiro-pi4j-sample
GPSandSun/runUART
Shell
mit
878
@setlocal @echo off set JAVA_HOME=D:\Java\jdk1.7.0_45 set PATH=%JAVA_HOME%\bin;%PATH% set JAVAC_OTPIONS=-sourcepath .\src set JAVAC_OPTIONS=%JAVAC_OPTIONS% -d .\classes set CP=.\classes set PI4J_HOME=D:\Cloud\pi4j set CP=%CP%;%PI4J_HOME%\libs\pi4j-core.jar :: set CP=%CP%;%PI4J_HOME%\libs\pi4j-device.jar :: set CP=%CP%;%PI4J_HOME%\libs\pi4j-gpio-extension.jar :: set CP=%CP%;%PI4J_HOME%\libs\pi4j-service.jar set CP=%CP%;.\lib\almanactools.jar set CP=%CP%;.\lib\geomutil.jar set CP=%CP%;.\lib\nauticalalmanac.jar set CP=%CP%;.\lib\nmeaparser.jar set JAVAC_OPTIONS=%JAVAC_OPTIONS% -cp %CP% echo Compiling javac %JAVAC_OPTIONS% .\src\nmea\*.java .\src\readserialport\*.java echo Done @endlocal
12nosanshiro-pi4j-sample
GPSandSun/compile.cmd
Batchfile
mit
695
#!/bin/bash echo Compiling everything cd AdafruitI2C ./compile cd .. cd ADC ./compile cd .. cd DAC ./compile cd .. cd ./GPIO.01 ./compile cd .. cd GPSandSun ./compile cd .. cd GPS.sun.servo ./compile cd ..
12nosanshiro-pi4j-sample
makeall
Shell
mit
207