code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
package VISTA;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.SwingUtilities;
import MODELO.ModeloIngrediente;
import MODELO.ModeloProducto;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class frmOrdenes extends javax.swing.JFrame {
private JPanel pnlOrdenes;
private JLabel jLabel2;
private JLabel jLabel1;
private JComboBox cmbCantidad;
private JLabel fecha;
private JTable tblProductoOrden;
private JScrollPane scpCatalogo;
private JPanel pnlLlenarOrden;
private JTextField txtEscribirNombres;
private JTable tblProductoOrdenes;
private JScrollPane scpProductoOrdenes;
private JButton btnCancelarOrden;
private JButton btnOkOrden;
private JLabel lblBsTotal;
private JLabel lblTotalMonto;
private JLabel lblTotal;
private JLabel lblMontoImpuesto;
private JButton btnAgregar;
private JButton btnRetirar;
private JLabel lblNombres;
private JTextField txtCedula;
private JLabel lblCedula;
private JLabel lblNro;
private JLabel lblNroOrden;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frmOrdenes inst = new frmOrdenes();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public frmOrdenes() {
super("Registro de Ordenes");
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
pnlOrdenes = new JPanel();
getContentPane().add(pnlOrdenes, BorderLayout.CENTER);
pnlOrdenes.setLayout(null);
pnlOrdenes.setBackground(new java.awt.Color(255,255,255));
pnlOrdenes.setPreferredSize(new java.awt.Dimension(1210, 516));
{
lblNroOrden = new JLabel();
pnlOrdenes.add(lblNroOrden);
lblNroOrden.setText("Nro de Orden:");
lblNroOrden.setBounds(21, 7, 118, 24);
}
{
lblNro = new JLabel();
pnlOrdenes.add(lblNro);
lblNro.setBounds(145, 12, 130, 19);
lblNro.setBackground(new java.awt.Color(229,229,229));
}
{
lblCedula = new JLabel();
pnlOrdenes.add(lblCedula);
lblCedula.setText("Cedula:");
lblCedula.setBounds(21, 72, 99, 30);
}
{
txtCedula = new JTextField();
pnlOrdenes.add(txtCedula);
txtCedula.setBounds(157, 79, 171, 23);
}
{
lblNombres = new JLabel();
pnlOrdenes.add(lblNombres);
lblNombres.setText("Nombres:");
lblNombres.setBounds(21, 117, 107, 24);
}
{
txtEscribirNombres = new JTextField();
pnlOrdenes.add(txtEscribirNombres);
txtEscribirNombres.setBounds(157, 119, 284, 22);
}
{
pnlLlenarOrden = new JPanel();
pnlLlenarOrden.setBorder(BorderFactory.createTitledBorder("Carga de Producto"));
pnlOrdenes.add(pnlLlenarOrden);
pnlLlenarOrden.setLayout(null);
pnlLlenarOrden.setBounds(21, 165, 1169, 294);
pnlLlenarOrden.setBackground(new java.awt.Color(228,196,116));
{
scpCatalogo = new JScrollPane();
pnlLlenarOrden.add(scpCatalogo);
scpCatalogo.setBounds(661, 50, 492, 151);
scpCatalogo.setBackground(new java.awt.Color(255,255,255));
{
TableModel tblProductoOrdenModel =
new DefaultTableModel(
new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } },
new String[] { "Cantidad", "Descripcion", "Monto" });
tblProductoOrden = new JTable();
scpCatalogo.setViewportView(tblProductoOrden);
tblProductoOrden.setModel(tblProductoOrdenModel);
tblProductoOrden.setBounds(17, 28, 682, 138);
tblProductoOrden.setPreferredSize(new java.awt.Dimension(472, 135));
}
}
{
btnRetirar = new JButton();
pnlLlenarOrden.add(btnRetirar);
btnRetirar.setText("Retirar");
btnRetirar.setBounds(535, 163, 102, 31);
btnRetirar.setActionCommand("Retirar");
}
{
btnAgregar = new JButton();
pnlLlenarOrden.add(btnAgregar);
btnAgregar.setText("Agregar");
btnAgregar.setBounds(535, 121, 102, 31);
btnAgregar.setActionCommand("Agregar");
}
{
lblMontoImpuesto = new JLabel();
pnlLlenarOrden.add(lblMontoImpuesto);
lblMontoImpuesto.setBounds(1077, 259, 75, 23);
}
{
lblTotal = new JLabel();
pnlLlenarOrden.add(lblTotal);
lblTotal.setText("Total:");
lblTotal.setBounds(809, 259, 97, 23);
}
{
lblTotalMonto = new JLabel();
pnlLlenarOrden.add(lblTotalMonto);
lblTotalMonto.setBounds(912, 259, 84, 23);
}
{
lblBsTotal = new JLabel();
pnlLlenarOrden.add(lblBsTotal);
lblBsTotal.setText("Bs");
lblBsTotal.setBounds(1008, 259, 70, 23);
}
{
scpProductoOrdenes = new JScrollPane();
pnlLlenarOrden.add(scpProductoOrdenes);
scpProductoOrdenes.setBounds(17, 50, 492, 151);
{
TableModel tblScrollProductoOrdenesModel =
new DefaultTableModel(
new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } },
new String[] { "Codigo", "Descripcion", "Precio Unitario" });
tblProductoOrdenes = new JTable();
scpProductoOrdenes.setViewportView(tblProductoOrdenes);
tblProductoOrdenes.setModel(tblScrollProductoOrdenesModel);
tblProductoOrdenes.setPreferredSize(new java.awt.Dimension(489, 144));
}
}
{
ComboBoxModel cmbCantidadModel =
new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
cmbCantidad = new JComboBox();
pnlLlenarOrden.add(cmbCantidad);
cmbCantidad.setBounds(535, 73, 102, 31);
int i =1;
while(i<=100){
cmbCantidad.addItem(i);
i++;
}
}
{
jLabel1 = new JLabel();
pnlLlenarOrden.add(jLabel1);
jLabel1.setText("Cantidad");
jLabel1.setBounds(558, 43, 65, 24);
}
}
{
btnOkOrden = new JButton();
pnlOrdenes.add(btnOkOrden);
btnOkOrden.setText("OK");
btnOkOrden.setBounds(946, 481, 117, 36);
btnOkOrden.setActionCommand("OK");
}
{
btnCancelarOrden = new JButton();
pnlOrdenes.add(btnCancelarOrden);
btnCancelarOrden.setText("Cancelar");
btnCancelarOrden.setBounds(1074, 481, 116, 36);
btnCancelarOrden.setActionCommand("Cancelar");
}
{
fecha = new JLabel();
pnlOrdenes.add(fecha);
fecha.setBounds(157, 37, 171, 21);
}
{
jLabel2 = new JLabel();
pnlOrdenes.add(jLabel2);
jLabel2.setText("Fecha:");
jLabel2.setBounds(22, 37, 118, 24);
}
}
pack();
this.setSize(1210, 570);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
public JLabel getLblTotalMonto() {
return lblTotalMonto;
}
public void setLblTotalMonto(JLabel lblTotalMonto) {
this.lblTotalMonto = lblTotalMonto;
}
public JTable getTblProductoOrden() {
return tblProductoOrden;
}
public void setTblProductoOrden(JTable tblProductoOrden) {
this.tblProductoOrden = tblProductoOrden;
}
public JTextField getTxtEscribirNombres() {
return txtEscribirNombres;
}
public void setTxtEscribirNombres(JTextField txtEscribirNombres) {
this.txtEscribirNombres = txtEscribirNombres;
}
public JTable getTblProductoOrdenes() {
return tblProductoOrdenes;
}
public void setTblProductoOrdenes(JTable tblProductoOrdenes) {
this.tblProductoOrdenes = tblProductoOrdenes;
}
public JTextField getTxtCedula() {
return txtCedula;
}
public void setTxtCedula(JTextField txtCedula) {
this.txtCedula = txtCedula;
}
public Vector<String []> getInfoTabla(){
Vector<String []> v = new Vector<String[]>();
for (int i = 0; i < tblProductoOrden.getRowCount(); i++){
if(!tblProductoOrden.getValueAt(i, 0).equals(""))
{String [] s = new String [] {""+tblProductoOrden.getValueAt(i, 0),""+tblProductoOrden.getValueAt(i, 1),""+tblProductoOrden.getValueAt(i, 2)};
v.add(s);}
else
break;
}
return v;
}
public void addListener(ActionListener actionListener){
this.btnAgregar.addActionListener(actionListener);
this.btnCancelarOrden.addActionListener(actionListener);
this.btnOkOrden.addActionListener(actionListener);
this.btnRetirar.addActionListener(actionListener);
}
public void limpiar(int num) {
txtCedula.setText("");
txtEscribirNombres.setText("");
lblTotalMonto.setText("");
lblNro.setText(""+num);
cmbCantidad.setSelectedIndex(0);
Date d = new Date();
fecha.setText(""+d.toLocaleString());
TableModel m = tblProductoOrden.getModel();
int i =0;
while(i< tblProductoOrden.getRowCount()) {
m.setValueAt("", i, 0);
m.setValueAt("", i, 1);
m.setValueAt("", i, 2);
i++;
}
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
public void quitar() {
int i = tblProductoOrden.getSelectedRow();
if(i!=-1){
tblProductoOrden.setValueAt("", i, 1);
tblProductoOrden.setValueAt("", i, 0);
tblProductoOrden.setValueAt("", i, 2);
calcularTotal();
}
else
mostrarMensaje("Selecione una fila");
}
public void agregar(ModeloProducto m) {
int i =0;
while(i< tblProductoOrden.getRowCount()) {
if(tblProductoOrden.getValueAt(i,0).equals("")){
tblProductoOrden.setValueAt(m.getDescripcion(), i, 1);
tblProductoOrden.setValueAt(cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex()), i, 0);
double precio = m.getPrecio() *(Integer)cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex());
tblProductoOrden.setValueAt(precio, i, 2);
break;
}
else if(tblProductoOrden.getValueAt(i,1).equals(m.getDescripcion()))
{
double precio = m.getPrecio() *(Integer)cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex());
tblProductoOrden.setValueAt(precio, i, 2);
break;
}
i++;
}
calcularTotal();
}
public void calcularTotal() {
int i =0;
double total =0;
while(i< tblProductoOrden.getRowCount()) {
if(tblProductoOrden.getValueAt(i,0).equals("")){
break;
}
else
total+=(Double)tblProductoOrden.getValueAt(i, 2);
i++;
}
lblTotalMonto.setText(""+total);
}
public boolean contar() {
int i =0;
int cont = 0;
while(i< tblProductoOrden.getRowCount()) {
if(tblProductoOrden.getValueAt(i,0).equals("")){
cont++;
}
i++;
}
return (cont==tblProductoOrden.getRowCount());
}
public JLabel getLblNro() {
return lblNro;
}
public void setLblNro(JLabel lblNro) {
this.lblNro = lblNro;
}
public Integer cantidad() {
return (Integer)cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex());
}
public void setCmbCantidad(JComboBox cmbCantidad) {
this.cmbCantidad = cmbCantidad;
}
}
| Java |
package VISTA;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.SwingUtilities;
import MODELO.ModeloIngrediente;
import bean.JTextFieldValidator;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class frmProductos extends javax.swing.JFrame {
private JPanel pnlProductos;
private JLabel lblCategoriaProducto;
private JTextField txtDescripcionProducto;
private JLabel lblDescripcionProducto;
private JTextField txtCodigoProducto;
private JLabel lblCodigoProducto;
private JLabel jLabel1;
private JComboBox cmbCantidad;
private JButton btnRetirarReceta;
private JButton btnAgregarReceta;
private JTable tblReceta;
private JScrollPane scpReceta;
private JTable tblIngredientes;
private JScrollPane scpIngredientes;
private JPanel pnlIngredientes;
private JButton btnCancelarProducto;
private JButton btnOkProducto;
private JLabel lblBsProducto;
private JTextField txtPrecioProducto;
private JLabel lblPrecioProducto;
private JComboBox cmbCategoriaProducto;
private JPanel pnlDatosProductos;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frmProductos inst = new frmProductos();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public frmProductos() {
super("Registro de Productos");
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
pnlProductos = new JPanel();
getContentPane().add(pnlProductos, BorderLayout.CENTER);
pnlProductos.setLayout(null);
pnlProductos.setBackground(new java.awt.Color(255,255,255));
pnlProductos.setPreferredSize(new java.awt.Dimension(980, 696));
{
pnlDatosProductos = new JPanel();
pnlDatosProductos.setBorder(BorderFactory.createTitledBorder("Datos"));
pnlProductos.add(pnlDatosProductos);
pnlDatosProductos.setLayout(null);
pnlDatosProductos.setBounds(18, 39, 985, 595);
pnlDatosProductos.setBackground(new java.awt.Color(228,196,116));
{
lblCodigoProducto = new JLabel();
pnlDatosProductos.add(lblCodigoProducto);
lblCodigoProducto.setText("Codigo:");
lblCodigoProducto.setBounds(17, 35, 63, 26);
}
{
txtCodigoProducto = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS);
pnlDatosProductos.add(txtCodigoProducto);
txtCodigoProducto.setBounds(118, 34, 194, 28);
}
{
lblDescripcionProducto = new JLabel();
pnlDatosProductos.add(lblDescripcionProducto);
lblDescripcionProducto.setText("Descripcion:");
lblDescripcionProducto.setBounds(360, 35, 92, 26);
}
{
txtDescripcionProducto = new JTextField();
pnlDatosProductos.add(txtDescripcionProducto);
txtDescripcionProducto.setBounds(483, 32, 193, 28);
}
{
lblCategoriaProducto = new JLabel();
pnlDatosProductos.add(lblCategoriaProducto);
lblCategoriaProducto.setText("Categoria:");
lblCategoriaProducto.setBounds(17, 80, 91, 26);
}
{
ComboBoxModel cmbCategoriaProductoModel =
new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
cmbCategoriaProducto = new JComboBox();
pnlDatosProductos.add(cmbCategoriaProducto);
cmbCategoriaProducto.setModel(cmbCategoriaProductoModel);
cmbCategoriaProducto.setBounds(120, 79, 194, 28);
}
{
lblPrecioProducto = new JLabel();
pnlDatosProductos.add(lblPrecioProducto);
lblPrecioProducto.setText("Precio Unitario:");
lblPrecioProducto.setBounds(360, 79, 117, 29);
}
{
txtPrecioProducto = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS);
pnlDatosProductos.add(txtPrecioProducto);
txtPrecioProducto.setBounds(483, 78, 126, 28);
}
{
lblBsProducto = new JLabel();
pnlDatosProductos.add(lblBsProducto);
lblBsProducto.setText("Bs");
lblBsProducto.setBounds(628, 78, 48, 28);
}
{
btnOkProducto = new JButton();
pnlDatosProductos.add(btnOkProducto);
btnOkProducto.setText("OK");
btnOkProducto.setBounds(629, 542, 113, 31);
btnOkProducto.setActionCommand("OK");
}
{
btnCancelarProducto = new JButton();
pnlDatosProductos.add(btnCancelarProducto);
btnCancelarProducto.setText("Cancelar");
btnCancelarProducto.setBounds(765, 542, 112, 31);
btnCancelarProducto.setActionCommand("Cancelar");
}
{
pnlIngredientes = new JPanel();
pnlDatosProductos.add(pnlIngredientes);
pnlIngredientes.setBackground(new java.awt.Color(237,206,149));
pnlIngredientes.setBorder(BorderFactory.createTitledBorder("Receta"));
pnlIngredientes.setLayout(null);
pnlIngredientes.setBounds(29, 126, 916, 395);
{
scpIngredientes = new JScrollPane();
pnlIngredientes.add(scpIngredientes);
scpIngredientes.setBounds(17, 32, 243, 195);
{
TableModel tblIngredientesModel =
new DefaultTableModel(
new String[][] { { "", "" }, { "", "" } ,{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" }},
new String[] { "Codigo", "Descripcion" });
tblIngredientes = new JTable();
scpIngredientes.setViewportView(tblIngredientes);
tblIngredientes.setModel(tblIngredientesModel);
tblIngredientes.setPreferredSize(new java.awt.Dimension(240,183));
}
}
{
scpReceta = new JScrollPane();
pnlIngredientes.add(scpReceta);
scpReceta.setBounds(348, 32, 551, 195);
{
TableModel tblRecetaModel =
new DefaultTableModel(
new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } },
new String[] { "Codigo", "Descripcion", "Cantidad" });
tblReceta = new JTable();
scpReceta.setViewportView(tblReceta);
tblReceta.setModel(tblRecetaModel);
tblReceta.setPreferredSize(new java.awt.Dimension(548, 170));
}
}
{
btnAgregarReceta = new JButton();
pnlIngredientes.add(btnAgregarReceta);
btnAgregarReceta.setText("Agregar a Receta");
btnAgregarReceta.setBounds(53, 259, 207, 36);
btnAgregarReceta.setActionCommand("Agregar");
}
{
btnRetirarReceta = new JButton();
pnlIngredientes.add(btnRetirarReceta);
btnRetirarReceta.setText("Retirar de Receta");
btnRetirarReceta.setBounds(53, 317, 207, 36);
btnRetirarReceta.setActionCommand("Retirar");
}
{
ComboBoxModel cmbCantidadModel =
new DefaultComboBoxModel(
new String[] { "Item One", "Item Two" });
cmbCantidad = new JComboBox();
pnlIngredientes.add(cmbCantidad);
int i =1;
while(i<=100){
cmbCantidad.addItem(i);
i++;
}
cmbCantidad.setBounds(266, 77, 76, 22);
}
{
jLabel1 = new JLabel();
pnlIngredientes.add(jLabel1);
jLabel1.setText("Cantidad");
jLabel1.setBounds(271, 41, 65, 24);
}
}
}
}
pack();
this.setSize(1037, 687);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
public Vector<String []> getInfoTabla(){
Vector<String []> v = new Vector<String[]>();
for (int i = 0; i < tblReceta.getRowCount(); i++){
if(!tblReceta.getValueAt(i, 0).equals(""))
{String [] s = new String [] {""+tblReceta.getValueAt(i, 0),""+tblReceta.getValueAt(i, 1),""+tblReceta.getValueAt(i, 2)};
v.add(s);}
else
break;
}
return v;
}
public JTable getTblIngredientes() {
return tblIngredientes;
}
public void setTblIngredientes(JTable tblIngredientes) {
this.tblIngredientes = tblIngredientes;
}
public JComboBox getCmbCategoriaProducto() {
return cmbCategoriaProducto;
}
public void setCmbCategoriaProducto(JComboBox cmbCategoriaProducto) {
this.cmbCategoriaProducto = cmbCategoriaProducto;
}
public void addListener(ActionListener actionListener){
this.btnAgregarReceta.addActionListener(actionListener);
this.btnCancelarProducto.addActionListener(actionListener);
this.btnOkProducto.addActionListener(actionListener);
this.btnRetirarReceta.addActionListener(actionListener);
}
public void limpiar() {
txtCodigoProducto.setText("");
txtDescripcionProducto.setText("");
txtPrecioProducto.setText("");
TableModel m = tblReceta.getModel();
int i =0;
while(i< tblReceta.getRowCount()) {
m.setValueAt("", i, 0);
m.setValueAt("", i, 1);
m.setValueAt("", i, 2);
i++;
}
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
public JTextField getTxtDescripcionProducto() {
return txtDescripcionProducto;
}
public void setTxtDescripcionProducto(JTextField txtDescripcionProducto) {
this.txtDescripcionProducto = txtDescripcionProducto;
}
public JTextField getTxtCodigoProducto() {
return txtCodigoProducto;
}
public void setTxtCodigoProducto(JTextField txtCodigoProducto) {
this.txtCodigoProducto = txtCodigoProducto;
}
public JTextField getTxtPrecioProducto() {
return txtPrecioProducto;
}
public void setTxtPrecioProducto(JTextField txtPrecioProducto) {
this.txtPrecioProducto = txtPrecioProducto;
}
public void quitar() {
int i = tblReceta.getSelectedRow();
if(i!=-1){
tblReceta.setValueAt("", i, 1);
tblReceta.setValueAt("", i, 2);
tblReceta.setValueAt("", i, 0);
}
else
mostrarMensaje("Selecione una fila");
}
public void agregar(ModeloIngrediente m) {
int i =0;
while(i< tblReceta.getRowCount()) {
if(tblReceta.getValueAt(i,1).equals(m.getDescripcion())){
tblReceta.setValueAt(cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex()), i, 2);
break;
}
else if(tblReceta.getValueAt(i,0).equals("")){
tblReceta.setValueAt(m.getDescripcion(), i, 1);
tblReceta.setValueAt(cmbCantidad.getItemAt(cmbCantidad.getSelectedIndex()), i, 2);
tblReceta.setValueAt(m.getCodigo(), i, 0);
break;
}
i++;
}
}
public JTable getTblReceta() {
return tblReceta;
}
public void setTblReceta(JTable tblReceta) {
this.tblReceta = tblReceta;
}
public boolean contar() {
int i =0;
int cont = 0;
while(i< tblReceta.getRowCount()) {
if(tblReceta.getValueAt(i,0).equals("")){
cont++;
}
i++;
}
return (cont==tblReceta.getRowCount());
}
}
| Java |
package VISTA;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.JViewport;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.SwingUtilities;
import bean.JTextFieldValidator;
import CONTROLADOR.ControladorCategorias;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class frmCategorias extends javax.swing.JFrame {
private JPanel pnlCategorias;
private JTextFieldValidator txtCodigo;
private JButton btnModificarCategorias;
private JButton btnCancelarCategorias;
private JTable tblCategorias;
private JScrollPane scpCategorias;
private JButton btnOkCategorias;
private JButton btnBuscar;
private JTextField txtDescripcion;
private JLabel lblDescripcion;
private JLabel lblCodigo;
private JPanel pnlDatosCategorias;
private ControladorCategorias ctrlCategorias;
public frmCategorias() {
super("Registro de Categorias");
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
pnlCategorias = new JPanel();
getContentPane().add(pnlCategorias, BorderLayout.CENTER);
pnlCategorias.setLayout(null);
pnlCategorias.setBackground(new java.awt.Color(255,255,255));
pnlCategorias.setLayout(null);
pnlCategorias.setPreferredSize(new java.awt.Dimension(436, 436));
{
pnlDatosCategorias = new JPanel();
pnlDatosCategorias.setBorder(BorderFactory.createTitledBorder("Datos"));
pnlCategorias.add(pnlDatosCategorias);
pnlDatosCategorias.setLayout(null);
pnlDatosCategorias.setBounds(62, 23, 437, 211);
pnlDatosCategorias.setBackground(new java.awt.Color(228,196,116));
pnlDatosCategorias.setEnabled(false);
{
lblCodigo = new JLabel();
pnlDatosCategorias.add(lblCodigo);
lblCodigo.setText("Codigo:");
lblCodigo.setBounds(17, 44, 70, 28);
}
{
txtCodigo = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS);
pnlDatosCategorias.add(txtCodigo);
txtCodigo.setBounds(118, 44, 138, 25);
}
{
lblDescripcion = new JLabel();
pnlDatosCategorias.add(lblDescripcion);
lblDescripcion.setText("Descripcion:");
lblDescripcion.setBounds(17, 84, 89, 21);
}
{
txtDescripcion = new JTextField();
pnlDatosCategorias.add(txtDescripcion);
txtDescripcion.setBounds(118, 81, 169, 24);
}
{
btnOkCategorias = new JButton();
pnlDatosCategorias.add(btnOkCategorias);
btnOkCategorias.setText("OK");
btnOkCategorias.setBounds(22, 141, 104, 32);
}
{
btnCancelarCategorias = new JButton();
pnlDatosCategorias.add(btnCancelarCategorias);
btnCancelarCategorias.setText("Cancelar");
btnCancelarCategorias.setBounds(312, 143, 103, 32);
btnCancelarCategorias.setActionCommand("Cancelar");
}
{
btnBuscar = new JButton();
pnlDatosCategorias.add(btnBuscar);
btnBuscar.setText("Buscar");
btnBuscar.setActionCommand("Buscar");
btnBuscar.setBounds(287, 40, 99, 32);
}
{
btnModificarCategorias = new JButton();
pnlDatosCategorias.add(btnModificarCategorias);
btnModificarCategorias.setText("Modificar");
btnModificarCategorias.setBounds(166, 142, 103, 31);
btnModificarCategorias.setActionCommand("Modificar");
}
}
{
scpCategorias = new JScrollPane();
pnlCategorias.add(scpCategorias);
scpCategorias.setBounds(62, 259, 437, 140);
{
TableModel tblCategoriasModel =
new DefaultTableModel(
new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } },
new String[] { "Codigo", "Descripcion" });
tblCategorias = new JTable();
scpCategorias.setViewportView(tblCategorias);
tblCategorias.setModel(tblCategoriasModel);
}
}
}
pack();
this.setSize(575, 465);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
public void addlistener(ActionListener actionlistener){
btnModificarCategorias.addActionListener(actionlistener);
btnOkCategorias.addActionListener(actionlistener);
btnCancelarCategorias.addActionListener(actionlistener);
btnBuscar.addActionListener(actionlistener);
}
public JTextField getTxtCodigo() {
return txtCodigo;
}
public JTextField getTxtDescripcion() {
return txtDescripcion;
}
public void setTxtDescripcion(JTextField txtDescripcion) {
this.txtDescripcion = txtDescripcion;
}
public JTable gettblCategorias(){
return tblCategorias;
}
public void bloquearNuevo(){
pnlDatosCategorias.setEnabled(false);
}
public void habilitarNuevo(){
pnlDatosCategorias.setEnabled(true);
}
public void limpiarCancelar(){
pnlDatosCategorias.setEnabled(true);
txtCodigo.setText("");
txtDescripcion.setText("");
}
public void bloquearCodigo(){
txtCodigo.setEnabled(false);
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
}
| Java |
package VISTA;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.SwingUtilities;
import bean.JTextFieldValidator;
import CONTROLADOR.ControladorIngredientes;
import MODELO.ModeloIngrediente;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class frmIngredientes extends javax.swing.JFrame {
private JPanel pnlIngredientes;
private JLabel lblCodigoIngredientes;
private JTextField txtDescripcionIngredientes;
private JLabel lblStockMinimo;
private JButton btnRegistrarNuevoIng;
private JTable tblIngredientes;
private JScrollPane scpCategorias;
private JButton btnRegistrarCompra;
private JButton btnCancelarNuevoIng;
private JButton btnAceptar;
private JButton btnCancelarEntrada;
private JButton btnProcesar;
private JLabel lblGuion;
private JTextField txtCantidad;
private JLabel lblCantidad;
private JLabel lblDescripcionEntrada;
private JLabel jLabel1;
private JPanel pnlEntradaIngrediente;
private JScrollPane scpIngredientes;
private JPanel pnlNuevoIngrediente;
private JTextFieldValidator txtStockMinimo;
private JLabel lblDescripcion;
private JTextFieldValidator txtCodigoIngrediente;
private ControladorIngredientes ctrlIngredientes;
private DefaultTableModel modelo;
public frmIngredientes() {
super("Registro de Ingredientes");
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
pnlIngredientes = new JPanel();
getContentPane().add(pnlIngredientes, BorderLayout.CENTER);
pnlIngredientes.setLayout(null);
pnlIngredientes.setBackground(new java.awt.Color(255,255,255));
pnlIngredientes.setPreferredSize(new java.awt.Dimension(1107, 601));
{
pnlNuevoIngrediente = new JPanel();
pnlNuevoIngrediente.setBorder(BorderFactory.createTitledBorder("Nuevo Ingrediente"));
pnlIngredientes.add(pnlNuevoIngrediente);
pnlNuevoIngrediente.setLayout(null);
pnlNuevoIngrediente.setBounds(19, 14, 912, 174);
pnlNuevoIngrediente.setBackground(new java.awt.Color(228,196,116));
{
txtStockMinimo = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS);
pnlNuevoIngrediente.add(txtStockMinimo);
txtStockMinimo.setBounds(140, 89, 140, 27);
txtStockMinimo.setEnabled(false);
}
{
lblStockMinimo = new JLabel();
pnlNuevoIngrediente.add(lblStockMinimo);
lblStockMinimo.setText("Stock:");
lblStockMinimo.setBounds(43, 87, 99, 29);
}
{
txtDescripcionIngredientes = new JTextField();
pnlNuevoIngrediente.add(txtDescripcionIngredientes);
txtDescripcionIngredientes.setBounds(540, 45, 194, 29);
txtDescripcionIngredientes.setEnabled(false);
}
{
lblDescripcion = new JLabel();
pnlNuevoIngrediente.add(lblDescripcion);
lblDescripcion.setText("Descripcion:");
lblDescripcion.setBounds(352, 45, 93, 26);
}
{
txtCodigoIngrediente = new JTextFieldValidator( JTextFieldValidator.SOLO_NUMEROS);
pnlNuevoIngrediente.add(txtCodigoIngrediente);
txtCodigoIngrediente.setBounds(140, 42, 140, 27);
txtCodigoIngrediente.setEnabled(false);
}
{
lblCodigoIngredientes = new JLabel();
pnlNuevoIngrediente.add(lblCodigoIngredientes);
lblCodigoIngredientes.setText("Codigo:");
lblCodigoIngredientes.setBounds(43, 41, 97, 27);
}
{
btnAceptar = new JButton();
pnlNuevoIngrediente.add(btnAceptar);
btnAceptar.setText("Aceptar");
btnAceptar.setBounds(765, 32, 112, 32);
btnAceptar.setActionCommand("Aceptar");
btnAceptar.setEnabled(false);
}
{
btnCancelarNuevoIng = new JButton();
pnlNuevoIngrediente.add(btnCancelarNuevoIng);
btnCancelarNuevoIng.setText("Cancelar");
btnCancelarNuevoIng.setBounds(765, 85, 112, 31);
btnCancelarNuevoIng.setActionCommand("Cancelar");
btnCancelarNuevoIng.setEnabled(false);
}
}
{
scpIngredientes = new JScrollPane();
pnlIngredientes.add(scpIngredientes);
scpIngredientes.setBounds(19, 220, 762, 195);
{
scpCategorias = new JScrollPane();
scpIngredientes.setViewportView(scpCategorias);
scpCategorias.setBounds(18, 260, 471, 140);
{
TableModel tblCategoriasModel =
new DefaultTableModel(
new String[][] { { "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" },{ "", "" }, { "", "" } },
new String[] { "Codigo", "Ingrediente", "Stock" });
tblIngredientes = new JTable();
scpCategorias.setViewportView(tblIngredientes);
tblIngredientes.setModel(tblCategoriasModel);
}
}
}
{
pnlEntradaIngrediente = new JPanel();
pnlEntradaIngrediente.setBorder(BorderFactory.createTitledBorder("Entrada de Ingredientes"));
pnlIngredientes.add(pnlEntradaIngrediente);
pnlEntradaIngrediente.setVisible(false);
pnlEntradaIngrediente.setLayout(null);
pnlEntradaIngrediente.setBounds(19, 449, 915, 126);
pnlEntradaIngrediente.setBackground(new java.awt.Color(228,196,116));
{
jLabel1 = new JLabel();
pnlEntradaIngrediente.add(jLabel1);
jLabel1.setText("Descripcion:");
jLabel1.setBounds(17, 39, 98, 24);
}
{
lblDescripcionEntrada = new JLabel();
pnlEntradaIngrediente.add(lblDescripcionEntrada);
lblDescripcionEntrada.setBounds(199, 44, 158, 24);
}
{
lblCantidad = new JLabel();
pnlEntradaIngrediente.add(lblCantidad);
lblCantidad.setText("Cantidad a Ingresar:");
lblCantidad.setBounds(17, 75, 182, 32);
}
{
txtCantidad = new JTextFieldValidator(JTextFieldValidator.SOLO_NUMEROS);
pnlEntradaIngrediente.add(txtCantidad);
txtCantidad.setBounds(199, 80, 139, 29);
}
{
lblGuion = new JLabel();
pnlEntradaIngrediente.add(lblGuion);
lblGuion.setBounds(304, 84, 38, 15);
lblGuion.setFont(new java.awt.Font("Bitstream Charter",1,28));
}
{
btnProcesar = new JButton();
pnlEntradaIngrediente.add(btnProcesar);
btnProcesar.setText("Procesar");
btnProcesar.setBounds(499, 42, 173, 36);
btnProcesar.setActionCommand("Procesar");
}
{
btnCancelarEntrada = new JButton();
pnlEntradaIngrediente.add(btnCancelarEntrada);
btnCancelarEntrada.setText("Cancelar Entrada");
btnCancelarEntrada.setBounds(688, 42, 170, 36);
btnCancelarEntrada.setActionCommand("CancelarE");
}
}
{
btnRegistrarCompra = new JButton();
pnlIngredientes.add(btnRegistrarCompra);
btnRegistrarCompra.setText("Realizar Compra");
btnRegistrarCompra.setBounds(814, 328, 154, 38);
btnRegistrarCompra.setActionCommand("Compra");
}
{
btnRegistrarNuevoIng = new JButton();
pnlIngredientes.add(btnRegistrarNuevoIng);
btnRegistrarNuevoIng.setText("Registrar Nuevo");
btnRegistrarNuevoIng.setBounds(814, 252, 154, 42);
}
}
pack();
this.setSize(994, 622);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
public void addListener(ActionListener actionListener){
this.btnCancelarEntrada.addActionListener(actionListener);
this.btnCancelarNuevoIng.addActionListener(actionListener);
this.btnRegistrarCompra.addActionListener(actionListener);
this.btnRegistrarNuevoIng.addActionListener(actionListener);
this.btnProcesar.addActionListener(actionListener);
this.btnAceptar.addActionListener(actionListener);
}
public JTable getTblIngredientes() {
return tblIngredientes;
}
public void setTblIngredientes(JTable tblIngredientes) {
this.tblIngredientes = tblIngredientes;
}
public void limpiarNuevo(){
this.txtDescripcionIngredientes.setText("");
this.txtStockMinimo.setText("");
this.txtCodigoIngrediente.setText("");
}
public void limpiarEntrada(){
this.txtCantidad.setText("");
this.lblDescripcionEntrada.setText("");
}
public void bloquearNuevo(){
this.txtCodigoIngrediente.setEnabled(false);
this.txtDescripcionIngredientes.setEnabled(false);
this.txtStockMinimo.setEnabled(false);
this.btnAceptar.setEnabled(false);
this.btnCancelarNuevoIng.setEnabled(false);
}
public void habilitarNuevo(){
this.txtCodigoIngrediente.setEnabled(true);
this.txtDescripcionIngredientes.setEnabled(true);
this.txtStockMinimo.setEnabled(true);
this.btnAceptar.setEnabled(true);
this.btnCancelarNuevoIng.setEnabled(true);
}
public void bloquearEntrada(){
this.txtCantidad.setEnabled(false);
this.pnlEntradaIngrediente.setVisible(false);
}
public void habilitarEntrada(){
this.txtCantidad.setEnabled(true);
this.pnlEntradaIngrediente.setVisible(true);
}
public JTextField getTxtDescripcionIngredientes() {
return txtDescripcionIngredientes;
}
public JTextField getTxtStockMinimo() {
return txtStockMinimo;
}
public JTextField getTxtCodigoIngrediente() {
return txtCodigoIngrediente;
}
public JTextField getTxtCantidad() {
return txtCantidad;
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
public JLabel getLblDescripcionEntrada() {
return lblDescripcionEntrada;
}
public void setLblDescripcionEntrada(JLabel lblDescripcionEntrada) {
this.lblDescripcionEntrada = lblDescripcionEntrada;
}
}
| Java |
package VISTA;
import java.awt.BorderLayout;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.SwingUtilities;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class frmListados extends javax.swing.JFrame {
private JPanel pnlListados;
private JPanel pnlListadoIngredientes;
private JPanel pnlOrden;
private JScrollPane scpProductoOrdenes;
private JTable tblProductoOrdenes;
private JRadioButton rbtnDescendente;
private ButtonGroup buttonGroup3;
private ButtonGroup buttonGroup2;
private ButtonGroup buttonGroup1;
private JButton btnCancelar;
private JButton btnCargarListados;
private JRadioButton rbtnMas;
private JRadioButton rbtnAscendente;
private JRadioButton rbtnProductos;
private JRadioButton rbtnIngredientes;
private JPanel pnlFiltro;
private JPanel pnlListadoVentas;
private DefaultTableModel modeloIngrediente,modeloProducto,modeloMas;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
frmListados inst = new frmListados();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public frmListados() {
super("Listados");
initGUI();
modeloIngrediente= new DefaultTableModel(null,
new String[] { "Ingrediente", "Stock en Almacen" });
modeloProducto= new DefaultTableModel(null,
new String[] { "Producto", "Total Generado","Cantidad Vendida" });
modeloMas= new DefaultTableModel(null,
new String[] { "Ingrediente", "Cantidade Usada" });
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
pnlListados = new JPanel();
getContentPane().add(pnlListados, BorderLayout.CENTER);
pnlListados.setLayout(null);
pnlListados.setBackground(new java.awt.Color(255,255,255));
pnlListados.setPreferredSize(new java.awt.Dimension(774, 467));
{
pnlListadoVentas = new JPanel();
pnlListadoVentas.setBorder(BorderFactory.createTitledBorder("Listados"));
pnlListados.add(pnlListadoVentas);
pnlListadoVentas.setLayout(null);
pnlListadoVentas.setBounds(29, 12, 728, 211);
pnlListadoVentas.setBackground(new java.awt.Color(228,196,116));
{
pnlFiltro = new JPanel();
pnlFiltro.setBorder(BorderFactory.createTitledBorder("Selecione"));
pnlListadoVentas.add(pnlFiltro);
pnlFiltro.setLayout(null);
pnlFiltro.setBounds(89, 32, 329, 152);
pnlFiltro.setBackground(new java.awt.Color(255,255,255));
{
rbtnIngredientes = new JRadioButton();
pnlFiltro.add(rbtnIngredientes);
rbtnIngredientes.setText("Listado de Ingredientes");
rbtnIngredientes.setBounds(35, 30, 272, 30);
rbtnIngredientes.setBackground(new java.awt.Color(255,255,255));
rbtnIngredientes.setActionCommand("Ingredientes");
getButtonGroup1().add(rbtnIngredientes);
}
{
rbtnProductos = new JRadioButton();
pnlFiltro.add(rbtnProductos);
rbtnProductos.setText("Listado de Productos Vendidos");
rbtnProductos.setBounds(35, 67, 278, 30);
rbtnProductos.setBackground(new java.awt.Color(255,255,255));
rbtnProductos.setActionCommand("Productos");
getButtonGroup1().add(rbtnProductos);
}
{
rbtnMas = new JRadioButton();
pnlFiltro.add(rbtnMas);
rbtnMas.setText("Listado de Ingredientes mas Usados");
rbtnMas.setBounds(35, 104, 278, 30);
rbtnMas.setBackground(new java.awt.Color(255,255,255));
rbtnMas.setActionCommand("Mas");
getButtonGroup1().add(rbtnMas);
}
}
{
pnlOrden = new JPanel();
pnlOrden.setBorder(BorderFactory.createTitledBorder("Orden"));
pnlListadoVentas.add(pnlOrden);
pnlOrden.setLayout(null);
pnlOrden.setBounds(438, 36, 285, 148);
pnlOrden.setBackground(new java.awt.Color(255,255,255));
{
rbtnAscendente = new JRadioButton();
pnlOrden.add(rbtnAscendente);
rbtnAscendente.setText("Ascendente");
rbtnAscendente.setBounds(64, 34, 171, 30);
rbtnAscendente.setBackground(new java.awt.Color(255,255,255));
rbtnAscendente.setActionCommand("Asc");
getButtonGroup2().add(rbtnAscendente);
}
{
rbtnDescendente = new JRadioButton();
pnlOrden.add(rbtnDescendente);
rbtnDescendente.setText("Descendente");
rbtnDescendente.setBounds(64, 71, 171, 30);
rbtnDescendente.setBackground(new java.awt.Color(255,255,255));
rbtnDescendente.setActionCommand("Asc");
getButtonGroup2().add(rbtnDescendente);
}
}
}
{
pnlListadoIngredientes = new JPanel();
pnlListadoIngredientes.setBorder(BorderFactory.createTitledBorder("Listado"));
pnlListados.add(pnlListadoIngredientes);
pnlListadoIngredientes.setLayout(null);
pnlListadoIngredientes.setBounds(29, 259, 728, 184);
pnlListadoIngredientes.setBackground(new java.awt.Color(228,196,116));
pnlListadoIngredientes.add(getScpProductoOrdenes());
}
{
btnCargarListados = new JButton();
pnlListados.add(btnCargarListados);
btnCargarListados.setText("Generar");
btnCargarListados.setBounds(272, 455, 107, 34);
btnCargarListados.setActionCommand("Generar");
}
{
btnCancelar = new JButton();
pnlListados.add(btnCancelar);
btnCancelar.setText("Cancelar");
btnCancelar.setBounds(410, 455, 107, 34);
btnCancelar.setActionCommand("Cancelar");
}
}
pack();
this.setSize(784, 530);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
private JScrollPane getScpProductoOrdenes() {
if(scpProductoOrdenes == null) {
scpProductoOrdenes = new JScrollPane();
scpProductoOrdenes.setBounds(17, 20, 694, 147);
scpProductoOrdenes.setViewportView(getTblProductoOrdenes());
}
return scpProductoOrdenes;
}
private JTable getTblProductoOrdenes() {
if(tblProductoOrdenes == null) {
tblProductoOrdenes = new JTable();
// tblProductoOrdenes.setModel(tblProductoOrdenesModel);
tblProductoOrdenes.setPreferredSize(new java.awt.Dimension(489,144));
}
return tblProductoOrdenes;
}
public void addListener(ActionListener actionListener){
this.btnCancelar.addActionListener(actionListener);
this.btnCargarListados.addActionListener(actionListener);
this.rbtnAscendente.addActionListener(actionListener);
this.rbtnDescendente.addActionListener(actionListener);
this.rbtnIngredientes.addActionListener(actionListener);
this.rbtnMas.addActionListener(actionListener);
this.rbtnProductos.addActionListener(actionListener);
}
public DefaultTableModel getModeloIngrediente() {
return modeloIngrediente;
}
public void setModeloIngrediente(DefaultTableModel modeloIngrediente) {
this.modeloIngrediente = modeloIngrediente;
}
public DefaultTableModel getModeloProducto() {
return modeloProducto;
}
public void setModeloProducto(DefaultTableModel modeloProducto) {
this.modeloProducto = modeloProducto;
}
public DefaultTableModel getModeloMas() {
return modeloMas;
}
public void setModeloMas(DefaultTableModel modeloMas) {
this.modeloMas = modeloMas;
}
public void setTblProductoOrdenes(JTable tblProductoOrdenes) {
this.tblProductoOrdenes = tblProductoOrdenes;
}
public JTable getProductoOrdenes() {
return tblProductoOrdenes;
}
public void mostrarMensaje(String mensaje) {
JOptionPane.showMessageDialog(this, mensaje);
}
private ButtonGroup getButtonGroup1() {
if(buttonGroup1 == null) {
buttonGroup1 = new ButtonGroup();
}
return buttonGroup1;
}
private ButtonGroup getButtonGroup2() {
if(buttonGroup2 == null) {
buttonGroup2 = new ButtonGroup();
}
return buttonGroup2;
}
}
| Java |
package VISTA;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JPanel;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.WindowConstants;
import javax.swing.SwingUtilities;
import CONTROLADOR.ControladorMenuPrincipal;
/**
* This code was edited or generated using CloudGarden's Jigloo
* SWT/Swing GUI Builder, which is free for non-commercial
* use. If Jigloo is being used commercially (ie, by a corporation,
* company or business for any purpose whatever) then you
* should purchase a license for each developer using Jigloo.
* Please visit www.cloudgarden.com for details.
* Use of Jigloo implies acceptance of these licensing terms.
* A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR
* THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED
* LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE.
*/
public class MenuPrincipal extends javax.swing.JFrame {
private JPanel pnlMenuPrincipal;
private JPanel pnlConfiguracion;
private JButton btnIngredientes;
private JButton btnProductos;
private JButton btnListados;
private JButton btnGenerarOrdenes;
private JButton btnCategorias;
/**
* Auto-generated main method to display this JFrame
*/
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
MenuPrincipal inst = new MenuPrincipal();
inst.setLocationRelativeTo(null);
inst.setVisible(true);
}
});
}
public MenuPrincipal() {
super("Menu Principal");
initGUI();
}
private void initGUI() {
try {
setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
{
pnlMenuPrincipal = new JPanel();
getContentPane().add(pnlMenuPrincipal, BorderLayout.CENTER);
pnlMenuPrincipal.setLayout(null);
pnlMenuPrincipal.setBackground(new java.awt.Color(255,255,255));
pnlMenuPrincipal.setLayout(null);
pnlMenuPrincipal.setPreferredSize(new java.awt.Dimension(763, 353));
{
pnlConfiguracion = new JPanel();
pnlMenuPrincipal.add(pnlConfiguracion);
pnlConfiguracion.setLayout(null);
pnlConfiguracion.setBounds(21, 25, 710, 137);
pnlConfiguracion.setBackground(new java.awt.Color(228,196,116));
pnlConfiguracion.setBorder(BorderFactory.createTitledBorder("Configuraciones"));
{
btnIngredientes = new JButton();
pnlConfiguracion.add(btnIngredientes);
btnIngredientes.setText("Ingredientes");
btnIngredientes.setBounds(77, 32, 205, 34);
btnIngredientes.setActionCommand("Ingredientes");
}
{
btnProductos = new JButton();
pnlConfiguracion.add(btnProductos);
btnProductos.setText("Productos");
btnProductos.setBounds(410, 32, 205, 34);
btnProductos.setActionCommand("Productos");
}
{
btnCategorias = new JButton();
pnlConfiguracion.add(btnCategorias);
btnCategorias.setText("Categorias");
btnCategorias.setBounds(245, 77, 205, 34);
btnCategorias.setActionCommand("Categorias");
}
}
{
btnGenerarOrdenes = new JButton();
pnlMenuPrincipal.add(btnGenerarOrdenes);
btnGenerarOrdenes.setText("Generar Ordenes");
btnGenerarOrdenes.setBounds(21, 193, 710, 58);
btnGenerarOrdenes.setActionCommand("Ordenes");
}
{
btnListados = new JButton();
pnlMenuPrincipal.add(btnListados);
btnListados.setText("Listados");
btnListados.setBounds(21, 273, 710, 58);
btnListados.setActionCommand("Listados");
}
}
pack();
this.setSize(765, 388);
} catch (Exception e) {
//add your error handling code here
e.printStackTrace();
}
}
public void addListener(ActionListener actionListener){
this.btnIngredientes.addActionListener(actionListener);
this.btnProductos.addActionListener(actionListener);
this.btnCategorias.addActionListener(actionListener);
this.btnGenerarOrdenes.addActionListener(actionListener);
this.btnListados.addActionListener(actionListener);
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package CONTROLADOR;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import MODELO.ModeloIngrediente;
import MODELO.ModeloProducto;
import VISTA.frmListados;
/**
*
* @author usuario
*/
public class ControladorListados implements ActionListener {
private frmListados frmListado;
private ModeloIngrediente modeloIngrediente;
private ModeloProducto modeloProducto;
private boolean ordenar,ingrediente,producto,mas;
public static void main(String[] args) {
new ControladorListados();
}
public ControladorListados() {
frmListado= new frmListados();
frmListado.setVisible(true);
modeloIngrediente= new ModeloIngrediente();
modeloProducto = new ModeloProducto();
frmListado.addListener(this);
cancelar();
}
private void cancelar() {
ordenar=false;
ingrediente=false;
producto=false;
mas=false;
frmListado.getModeloIngrediente().setRowCount(0);
frmListado.getModeloMas().setRowCount(0);
frmListado.getModeloProducto().setRowCount(0);
}
public void actionPerformed(ActionEvent ae) {
if(ae.getActionCommand().equals("Generar")){
if(ingrediente){
listaIngrediente();
//cancelar();
}
else if(producto){
listarProductos();
//cancelar();
}
else if(mas){
listarMas();
//cancelar();
}
else
frmListado.mostrarMensaje("Debe selecionar el Listado que desea ver");
}
else if(ae.getActionCommand().equals("Asc")){
ordenar = true;
}
else if(ae.getActionCommand().equals("Des")){
ordenar = false;
}
else if(ae.getActionCommand().equals("Ingredientes")){
ingrediente=true;
mas=false;
producto=false;
}
else if(ae.getActionCommand().equals("Productos")){
producto=true;
mas=false;
ingrediente=false;
}
else if(ae.getActionCommand().equals("Mas")){
mas =true;
ingrediente=false;
producto=false;
}
else if(ae.getActionCommand().equals("Cancelar")){
cancelar();
}
}
private void listarMas() {
frmListado.getModeloIngrediente().setRowCount(0);
frmListado.getModeloMas().setRowCount(0);
frmListado.getModeloProducto().setRowCount(0);
Vector<String []> v = modeloProducto.ingredientesMasUsados(ordenar);
frmListado.getProductoOrdenes().setModel(frmListado.getModeloMas());
Vector f= null;
for (String [] s : v) {
f =new Vector();
for (String string : s) {
f.add(string);
}
frmListado.getModeloMas().addRow(f);
}
}
private void listarProductos() {
frmListado.getModeloIngrediente().setRowCount(0);
frmListado.getModeloMas().setRowCount(0);
frmListado.getModeloProducto().setRowCount(0);
Vector<String []> v = modeloProducto.listarVentas(ordenar);
frmListado.getProductoOrdenes().setModel(frmListado.getModeloProducto());
Vector f = null;
for (String [] s : v) {
f =new Vector();
for (String string : s) {
f.add(string);
}
frmListado.getModeloProducto().addRow(f);
}
}
private void listaIngrediente() {
frmListado.getModeloIngrediente().setRowCount(0);
frmListado.getModeloMas().setRowCount(0);
frmListado.getModeloProducto().setRowCount(0);
Vector<ModeloIngrediente> v = modeloIngrediente.listar();
frmListado.getProductoOrdenes().setModel(frmListado.getModeloIngrediente());
Vector f;
for (ModeloIngrediente m : v) {
f =new Vector();
f.add(m.getDescripcion());
f.add(m.getStock());
frmListado.getModeloIngrediente().addRow(f);
}
}
}
| Java |
package CONTROLADOR;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Vector;
import javax.swing.table.TableModel;
import MODELO.ModeloCategoria;
import MODELO.ModeloIngrediente;
import MODELO.ModeloProducto;
import VISTA.frmProductos;
public class ControladorProductos implements ActionListener{
private facadeControladorProductos facade;
private Vector<ModeloIngrediente> ingredientes;
private List<ModeloCategoria> categorias;
public static void main(String[] args) {
new ControladorProductos();
}
//Implementacion del Patron Estructural Facade
public ControladorProductos() {
this.facade = new facadeControladorProductos();
this.facade.setVisible(true);
facade.addListener(this);
cargarTabla();
cargarCombo();
}
private void cargarTabla() {
TableModel m = facade.getTblIngredientesTblMODEL();
int i =0;
while(i< facade.getTblIngredientesTblROW()){
m.setValueAt("", i, 0);
m.setValueAt("", i, 1);
i++;
}
ingredientes = new ModeloIngrediente().listar();
i =0;
for (ModeloIngrediente modelo: ingredientes) {
m.setValueAt(modelo.getCodigo(), i, 0);
m.setValueAt(modelo.getDescripcion(), i, 1);
i++;
}
}
private void cargarCombo() {
facade.getCmbCategoriaProductoREMOVE();
categorias = new ModeloCategoria().listar();
for (ModeloCategoria modelo: categorias) {
facade.getCmbCategoriaProductoADD(modelo.getDescripcion());
}
}
@Override
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals("Cancelar")){
facade.limpiar();
}
else if(evt.getActionCommand().equals("OK")){
if(!facade.getTxtCodigoProductoEMPTY() && !facade.getTxtDescripcionProductoEMPTY() && !facade.getTxtPrecioProductoEMPTY())
if(!facade.contar())
{
facade.setCodigo(facade.getTxtCodigoProducto());
facade.setDescripcion(facade.getTxtDescripcionProducto());
facade.setStatus("A");
facade.setPrecio(Double.parseDouble(facade.getTxtPrecioProducto()));
if(facade.registrar()){
Vector<String> v = new Vector<String>();
Vector<Double> c = new Vector<Double>();
Vector<String []> vAux = facade.getInfoTabla();
for (String[] strings : vAux) {
v.add(buscarIngrediente(strings[1]).getCodigo());
c.add(Double.parseDouble(strings[2]));
}
facade.registrarIngredientes(v, c);
facade.limpiar();
facade.mostrarMensaje("Producto registrado");
}
else
facade.mostrarMensaje("Codigo registrado");
}
else
facade.mostrarMensaje("No ha registrado ingredientes");
else
facade.mostrarMensaje("Campos vacios");
}
else if(evt.getActionCommand().equals("Agregar")){
if(facade.getTblIngredientesSELECTROW()!=-1){
String des = (String)facade.getTblIngredientesGETVALUE();
facade.agregar(buscarIngrediente(des));
}
else
facade.mostrarMensaje("Selecionar un Ingrediente");
}
else if(evt.getActionCommand().equals("Quitar")){
facade.quitar();
}
}
public ModeloIngrediente buscarIngrediente(String descripicion){
for (int i = 0; i < ingredientes.size(); i++){
if(ingredientes.elementAt(i).getDescripcion().equals(descripicion))
return ingredientes.elementAt(i);
}return null;
}
}
| Java |
package CONTROLADOR;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import VISTA.*;
public class ControladorMenuPrincipal implements ActionListener {
private MenuPrincipal frmMenuPrincipal;
public ControladorMenuPrincipal() {
this.frmMenuPrincipal = new MenuPrincipal();
this.frmMenuPrincipal.addListener(this);
this.frmMenuPrincipal.setVisible(true);
}
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals("Ingredientes")){
new ControladorIngredientes();
}
else if(evt.getActionCommand().equals("Productos")){
new ControladorProductos();
}
else if(evt.getActionCommand().equals("Categorias")){
new ControladorCategorias();
}
else if(evt.getActionCommand().equals("Ordenes")){
new ControladorOrden();
}
else if(evt.getActionCommand().equals("Listados")){
new ControladorListados();
}
}//end actionPerformed
}
| Java |
package CONTROLADOR;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.TableModel;
import MODELO.ModeloCategoria;
import VISTA.frmCategorias;
public class ControladorCategorias implements ActionListener{
private ModeloCategoria modelo;
private frmCategorias frmCategorias;
public static void main(String[] args) {
new ControladorCategorias();
}
public ControladorCategorias() {
modelo = new ModeloCategoria();
this.frmCategorias = new frmCategorias();
this.frmCategorias.setVisible(true);
this.frmCategorias.addlistener(this);
cargarTabla();
}
//Implementacion del Patron de Comportamiento Iterator
private void cargarTabla() {
TableModel m = frmCategorias.gettblCategorias().getModel();
int i =0;
Vector<ModeloCategoria> v = modelo.listar();
ListIterator<ModeloCategoria> iteradorCategoria = v.listIterator();
while (iteradorCategoria.hasNext()) {
ModeloCategoria categoria = iteradorCategoria.next();
m.setValueAt(categoria.getCodigo(), i, 0);
m.setValueAt(categoria.getDescripcion(), i, 1);
i++;
}
}
@Override
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals("Nuevo")){
frmCategorias.habilitarNuevo();
}
else if(evt.getActionCommand().equals("Modificar")){
if(!frmCategorias.getTxtCodigo().getText().isEmpty() && !frmCategorias.getTxtDescripcion().getText().isEmpty())
{
modelo.setCodigo(frmCategorias.getTxtCodigo().getText());
modelo.setDescripcion(frmCategorias.getTxtDescripcion().getText());
modelo.setStatus("A");
if(modelo.actualizar()){
frmCategorias.limpiarCancelar();
cargarTabla();
frmCategorias.mostrarMensaje("Categoria actualizada");
}
else
frmCategorias.mostrarMensaje("Codigo registrado");
}
else
frmCategorias.mostrarMensaje("Campos vacios");
}
else if(evt.getActionCommand().equals("Buscar")){
if(!frmCategorias.getTxtCodigo().getText().isEmpty())
{
modelo.setCodigo(frmCategorias.getTxtCodigo().getText());
if(modelo.consultar()){
frmCategorias.bloquearCodigo();
frmCategorias.getTxtDescripcion().setText(modelo.getDescripcion());
}
else
frmCategorias.mostrarMensaje("Codigo no registrado");
}
else
frmCategorias.mostrarMensaje("Campos vacios");
}
else if(evt.getActionCommand().equals("OK")){
if(!frmCategorias.getTxtCodigo().getText().isEmpty() && !frmCategorias.getTxtDescripcion().getText().isEmpty())
{
modelo.setCodigo(frmCategorias.getTxtCodigo().getText());
modelo.setDescripcion(frmCategorias.getTxtDescripcion().getText());
modelo.setStatus("A");
if(modelo.registar()){
frmCategorias.limpiarCancelar();
cargarTabla();
frmCategorias.mostrarMensaje("Categoria registrada");
}
else
frmCategorias.mostrarMensaje("Codigo registrado");
}
else
frmCategorias.mostrarMensaje("Campos vacios");
}
else if(evt.getActionCommand().equals("Cancelar")){
frmCategorias.limpiarCancelar();
}
}
public void okCategorias(){
}
public void okModificarCategorias(boolean modificar){
if(modificar == true){
}
}
public void eliminarCategorias(){
frmCategorias.gettblCategorias().getSelectedRow();
}
}
| Java |
package CONTROLADOR;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.table.TableModel;
import MODELO.ModeloIngrediente;
import MODELO.ModeloProducto;
import VISTA.frmProductos;
public class facadeControladorProductos {
ModeloProducto modeloProducto = new ModeloProducto();
frmProductos frmProductos = new frmProductos();
public void setCodigo(String codigo){
modeloProducto.setCodigo(codigo);
}
public void setDescripcion(String descripcion){
modeloProducto.setDescripcion(descripcion);
}
public void setStatus(String status){
modeloProducto.setStatus(status);
}
public void setPrecio(double precio){
modeloProducto.setPrecio(precio);
}
public boolean registrar(){
return modeloProducto.registar();
}
public void registrarIngredientes(Vector<String> v, Vector<Double> c){
modeloProducto.registarIngredientes(v, c);
}
public void setVisible(boolean estado){
frmProductos.setVisible(estado);
}
public void addListener(ActionListener controlador){
frmProductos.addListener(controlador);
}
public TableModel getTblIngredientesTblMODEL(){
return frmProductos.getTblIngredientes().getModel();
}
public int getTblIngredientesTblROW(){
return frmProductos.getTblIngredientes().getRowCount();
}
public int getTblIngredientesSELECTROW(){
return frmProductos.getTblIngredientes().getSelectedRow();
}
public Object getTblIngredientesGETVALUE(){
return frmProductos.getTblIngredientes().getValueAt(getTblIngredientesSELECTROW(), 1);
}
public void getCmbCategoriaProductoREMOVE(){
frmProductos.getCmbCategoriaProducto().removeAllItems();
}
public void getCmbCategoriaProductoADD(String descripcion){
frmProductos.getCmbCategoriaProducto().addItem(descripcion);
}
public void limpiar(){
frmProductos.limpiar();
}
public boolean getTxtCodigoProductoEMPTY(){
return frmProductos.getTxtCodigoProducto().getText().isEmpty();
}
public boolean getTxtDescripcionProductoEMPTY(){
return frmProductos.getTxtDescripcionProducto().getText().isEmpty();
}
public boolean getTxtPrecioProductoEMPTY(){
return frmProductos.getTxtPrecioProducto().getText().isEmpty();
}
public String getTxtCodigoProducto(){
return frmProductos.getTxtCodigoProducto().getText();
}
public String getTxtDescripcionProducto(){
return frmProductos.getTxtDescripcionProducto().getText();
}
public String getTxtPrecioProducto(){
return frmProductos.getTxtPrecioProducto().getText();
}
public boolean contar(){
return frmProductos.contar();
}
public Vector<String []> getInfoTabla(){
return frmProductos.getInfoTabla();
}
public void mostrarMensaje(String mensaje){
frmProductos.mostrarMensaje(mensaje);
}
public void agregar(ModeloIngrediente ingrediente){
frmProductos.agregar(ingrediente);
}
public void quitar(){
frmProductos.quitar();
}
}
| Java |
package CONTROLADOR;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.table.TableModel;
import MODELO.ModeloCategoria;
import MODELO.ModeloIngrediente;
import MODELO.ModeloOrden;
import MODELO.ModeloProducto;
import VISTA.frmOrdenes;
public class ControladorOrden implements ActionListener{
private frmOrdenes frmOrdenes;
private ModeloOrden modeloOrden;
private Vector<ModeloProducto> productos;
public static void main(String[] args) {
new ControladorOrden();
}
public ControladorOrden() {
this.frmOrdenes = new frmOrdenes();
this.frmOrdenes.setVisible(true);
frmOrdenes.addListener(this);
this.modeloOrden = new ModeloOrden();
cargarTabla();
frmOrdenes.limpiar(modeloOrden.contarOrdenes());
}
private void cargarTabla() {
TableModel m = frmOrdenes.getTblProductoOrdenes().getModel();
int i =0;
while(i< frmOrdenes.getTblProductoOrdenes().getRowCount()) {
m.setValueAt("", i, 0);
m.setValueAt("", i, 1);
i++;
}
productos = new ModeloProducto().listar();
i =0;
for (ModeloProducto modelo: productos) {
m.setValueAt(modelo.getCodigo(), i, 0);
m.setValueAt(modelo.getDescripcion(), i, 1);
m.setValueAt(modelo.getPrecio(), i, 2);
i++;
}
}
@Override
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals("Cancelar")){
frmOrdenes.limpiar(modeloOrden.contarOrdenes());
}
else if(evt.getActionCommand().equals("OK")){
if(!frmOrdenes.getTxtCedula().getText().isEmpty() && !frmOrdenes.getTxtEscribirNombres().getText().isEmpty())
if(!frmOrdenes.contar())
{
modeloOrden.setCodigo (frmOrdenes.getLblNro().getText());
modeloOrden.setCedula(frmOrdenes.getTxtCedula().getText());
modeloOrden.setNombre(frmOrdenes.getTxtEscribirNombres().getText());
modeloOrden.setStatus("A");
modeloOrden.setTotal((Double.parseDouble(frmOrdenes.getLblNro().getText())));
if(modeloOrden.registar()){
Vector<String> v = new Vector<String>();
Vector<Double> c = new Vector<Double>();
Vector<String []> vAux = frmOrdenes.getInfoTabla();
for (String[] strings : vAux) {
ModeloProducto m = buscarProducto(strings[1]);
v.add(m.getCodigo());
c.add(Double.parseDouble(strings[0]));
int i =0;
while(i<Integer.parseInt(strings[0])){
m.actualizarStockIngredientes();
i++;
}
}
modeloOrden.registarProductos(v, c);
frmOrdenes.limpiar(modeloOrden.contarOrdenes());
frmOrdenes.mostrarMensaje("Orden registrado");
}
else
frmOrdenes.mostrarMensaje("Codigo registrado");
}
else
frmOrdenes.mostrarMensaje("No ha registrado productos");
else
frmOrdenes.mostrarMensaje("Campos vacios");
}
else if(evt.getActionCommand().equals("Agregar")){
if(frmOrdenes.getTblProductoOrdenes().getSelectedRow()!=-1){
ModeloProducto m = new ModeloProducto();
m.setCodigo((String)frmOrdenes.getTblProductoOrdenes().getValueAt(frmOrdenes.getTblProductoOrdenes().getSelectedRow(), 0));
if(m.revisarStockIngredientes((frmOrdenes.cantidad()))){
String des = (String)frmOrdenes.getTblProductoOrdenes().getValueAt(frmOrdenes.getTblProductoOrdenes().getSelectedRow(), 1);
frmOrdenes.agregar(buscarProducto(des));
}
else
frmOrdenes.mostrarMensaje("No tenemos stock pra cubrir su orden");
}
else
frmOrdenes.mostrarMensaje("Selecionar un Ingrediente");
}
else if(evt.getActionCommand().equals("Retirar")){
frmOrdenes.quitar();
}
}
public ModeloProducto buscarProducto(String descripicion){
for (int i = 0; i < productos.size(); i++)
if(productos.elementAt(i).getDescripcion().equals(descripicion))
return productos.elementAt(i);
return null;
}
}
| Java |
package CONTROLADOR;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.TableModel;
import MODELO.ModeloCategoria;
import MODELO.ModeloIngrediente;
import VISTA.frmIngredientes;
public class ControladorIngredientes implements ActionListener{
private frmIngredientes frmIngredientes;
private ModeloIngrediente modeloIngrediente;
public static void main(String[] args) {
new ControladorIngredientes();
}
public ControladorIngredientes() {
this.frmIngredientes = new frmIngredientes();
this.frmIngredientes.setVisible(true);
frmIngredientes.addListener(this);
this.modeloIngrediente = new ModeloIngrediente();
cargarTabla();
}
public void cargarTabla() {
TableModel m = frmIngredientes.getTblIngredientes().getModel();
int i =0;
while(i< frmIngredientes.getTblIngredientes().getRowCount()) {
m.setValueAt("", i, 0);
m.setValueAt("", i, 1);
m.setValueAt("", i, 2);
i++;
}
Vector<ModeloIngrediente> v = modeloIngrediente.listar();
i =0;
for (ModeloIngrediente modelo: v) {
m.setValueAt(modelo.getCodigo(), i, 0);
m.setValueAt(modelo.getDescripcion(), i, 1);
m.setValueAt(modelo.getStock(), i, 2);
i++;
}
}
public void actionPerformed(ActionEvent evt) {
if(evt.getActionCommand().equals("Cancelar")){
frmIngredientes.limpiarNuevo();
frmIngredientes.bloquearNuevo();
frmIngredientes.limpiarEntrada();
frmIngredientes.bloquearEntrada();
cargarTabla();
}
else if (evt.getActionCommand().equals("Registrar Nuevo")){
frmIngredientes.habilitarNuevo();
}
else if(evt.getActionCommand().equals("Aceptar")){
if(!frmIngredientes.getTxtCodigoIngrediente().getText().isEmpty() && !frmIngredientes.getTxtStockMinimo().getText().isEmpty() && !frmIngredientes.getTxtDescripcionIngredientes().getText().isEmpty())
{
modeloIngrediente.setCodigo(frmIngredientes.getTxtCodigoIngrediente().getText());
modeloIngrediente.setDescripcion(frmIngredientes.getTxtDescripcionIngredientes().getText());
modeloIngrediente.setStatus("A");
modeloIngrediente.setStock(Double.parseDouble(frmIngredientes.getTxtStockMinimo().getText()));
if(modeloIngrediente.registar()){
frmIngredientes.limpiarNuevo();
cargarTabla();
frmIngredientes.mostrarMensaje("Ingrediente registrado");
}
else
frmIngredientes.mostrarMensaje("Codigo registrado");
}
else
frmIngredientes.mostrarMensaje("Campos vacios");
}
else if(evt.getActionCommand().equals("Compra")){
if(!frmIngredientes.getTxtCodigoIngrediente().getText().isEmpty()){
modeloIngrediente.setCodigo(frmIngredientes.getTxtCodigoIngrediente().getText());
modeloIngrediente.setStatus("A");
if(modeloIngrediente.consultar()){
frmIngredientes.getTxtStockMinimo().setText(""+modeloIngrediente.getStock());
frmIngredientes.getLblDescripcionEntrada().setText(modeloIngrediente.getDescripcion());
frmIngredientes.habilitarEntrada();
}
else
frmIngredientes.mostrarMensaje("Codigo registrado");
}
else
frmIngredientes.mostrarMensaje("Codigo vacio");
}
else if(evt.getActionCommand().equals("CancelarE")){
frmIngredientes.limpiarEntrada();
frmIngredientes.bloquearEntrada();
}
else if(evt.getActionCommand().equals("Procesar")){
if(!frmIngredientes.getTxtCodigoIngrediente().getText().isEmpty() && !frmIngredientes.getTxtCantidad().getText().isEmpty())
{
modeloIngrediente.setCodigo(frmIngredientes.getTxtCodigoIngrediente().getText());
modeloIngrediente.setStatus("A");
modeloIngrediente.setStock(modeloIngrediente.getStock() + Double.parseDouble(frmIngredientes.getTxtCantidad().getText()));
if(modeloIngrediente.actualizar()){
frmIngredientes.limpiarEntrada();
frmIngredientes.limpiarNuevo();
frmIngredientes.bloquearEntrada();
cargarTabla();
frmIngredientes.mostrarMensaje("Compra registrada");
}
else
frmIngredientes.mostrarMensaje("Codigo registrado");
}
else
frmIngredientes.mostrarMensaje("Campos vacios");
}
}
}
| Java |
package pi4j.gpio;
import com.pi4j.io.gpio.GpioController;
import com.pi4j.io.gpio.GpioFactory;
import com.pi4j.io.gpio.GpioPinDigitalInput;
import com.pi4j.io.gpio.PinPullResistance;
import com.pi4j.io.gpio.RaspiPin;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import com.pi4j.io.gpio.event.GpioPinListenerDigital;
public class GPIOController
{
private GpioController gpio = null;
private OneLed yellowLed = null;
private OneLed greenLed = null;
private GpioPinDigitalInput button = null;
private RaspberryPIEventListener caller = null;
public GPIOController(RaspberryPIEventListener listener)
{
this.caller = listener;
this.gpio = GpioFactory.getInstance();
this.yellowLed = new OneLed(this.gpio, RaspiPin.GPIO_01, "yellow");
this.greenLed = new OneLed(this.gpio, RaspiPin.GPIO_04, "green");
this.button = this.gpio.provisionDigitalInputPin(RaspiPin.GPIO_02, PinPullResistance.PULL_DOWN);
this.button.addListener(new GpioPinListenerDigital()
{
@Override
public void handleGpioPinDigitalStateChangeEvent(GpioPinDigitalStateChangeEvent event)
{
caller.manageEvent(event);
}
});
}
public void shutdown()
{
this.gpio.shutdown();
}
public void switchYellow(boolean on)
{
if (on)
yellowLed.on();
else
yellowLed.off();
}
public void switchGreen(boolean on)
{
if (on)
greenLed.on();
else
greenLed.off();
}
}
| Java |
package pi4j.gpio;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
public interface RaspberryPIEventListener
{
public void manageEvent(GpioPinDigitalStateChangeEvent event);
}
| Java |
package pi4j.gpio;
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();
}
}
| Java |
package pi4j.email;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import javax.mail.Address;
import javax.mail.Flags;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.internet.InternetAddress;
import javax.mail.search.AndTerm;
import javax.mail.search.FlagTerm;
import javax.mail.search.FromStringTerm;
import javax.mail.search.OrTerm;
import javax.mail.search.SearchTerm;
import javax.mail.search.SubjectTerm;
public class EmailReceiver
{
private static String protocol;
private static int outgoingPort;
private static int incomingPort;
private static String username;
private static String password;
private static String outgoing;
private static String incoming;
private static String replyto;
private static boolean smtpauth;
private static String sendEmailsTo;
private static String acceptEmailsFrom;
private static String acceptSubject;
private static String ackSubject;
private static boolean verbose = "true".equals(System.getProperty("verbose", "false"));
private EmailSender emailSender = null; // For Ack
private String provider = null;
public EmailReceiver(String provider) throws RuntimeException
{
this.provider = provider;
EmailReceiver.protocol = "";
EmailReceiver.outgoingPort = 0;
EmailReceiver.incomingPort = 0;
EmailReceiver.username = "";
EmailReceiver.password = "";
EmailReceiver.outgoing = "";
EmailReceiver.incoming = "";
EmailReceiver.replyto = "";
EmailReceiver.smtpauth = false;
EmailReceiver.sendEmailsTo = "";
EmailReceiver.acceptEmailsFrom = "";
EmailReceiver.acceptSubject = "";
EmailReceiver.ackSubject = "";
Properties props = new Properties();
String propFile = "email.properties";
try
{
FileInputStream fis = new FileInputStream(propFile);
props.load(fis);
}
catch (Exception e)
{
System.out.println("email.properies file problem...");
throw new RuntimeException("File not found:email.properies");
}
EmailReceiver.sendEmailsTo = props.getProperty("pi.send.emails.to");
EmailReceiver.acceptEmailsFrom = props.getProperty("pi.accept.emails.from");
EmailReceiver.acceptSubject = props.getProperty("pi.email.subject");
EmailReceiver.ackSubject = props.getProperty("pi.ack.subject");
EmailReceiver.protocol = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.protocol");
EmailReceiver.outgoingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server.port", "0"));
EmailReceiver.incomingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server.port", "0"));
EmailReceiver.username = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.username", "");
EmailReceiver.password = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.password", "");
EmailReceiver.outgoing = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server", "");
EmailReceiver.incoming = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server", "");
EmailReceiver.replyto = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.replyto", "");
EmailReceiver.smtpauth = "true".equals(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.smtpauth", "false"));
if (verbose)
{
System.out.println("Protocol:" + EmailReceiver.protocol);
System.out.println("Usr/pswd:" + EmailReceiver.username + "/" + EmailReceiver.password);
}
}
private static SearchTerm[] buildSearchTerm(String str)
{
String[] sa = str.split(",");
List<SearchTerm> lst = new ArrayList<SearchTerm>();
for (String s : sa)
lst.add(new FromStringTerm(s.trim()));
SearchTerm[] sta = new SearchTerm[lst.size()];
sta = lst.toArray(sta);
return sta;
}
private Properties setProps()
{
Properties props = new Properties();
props.put("mail.debug", verbose?"true":"false");
// TASK smtp should be irrelevant for a receiver
props.put("mail.smtp.host", EmailReceiver.outgoing);
props.put("mail.smtp.port", Integer.toString(EmailReceiver.outgoingPort));
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true"); // See http://www.oracle.com/technetwork/java/faq-135477.html#yahoomail
// props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.ssl.enable", "true");
if ("pop3".equals(EmailReceiver.protocol))
{
props.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.pop3.socketFactory.fallback", "false");
props.setProperty("mail.pop3.port", Integer.toString(EmailReceiver.incomingPort));
props.setProperty("mail.pop3.socketFactory.port", Integer.toString(EmailReceiver.incomingPort));
}
if ("imap".equals(protocol))
{
props.setProperty("mail.imap.starttls.enable", "false");
// Use SSL
props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.setProperty("mail.imap.socketFactory.fallback", "false");
props.setProperty("mail.imap.port", Integer.toString(EmailReceiver.incomingPort));
props.setProperty("mail.imap.socketFactory.port", Integer.toString(EmailReceiver.incomingPort));
props.setProperty("mail.imaps.class", "com.sun.mail.imap.IMAPSSLStore");
}
return props;
}
public boolean isAuthRequired()
{
return EmailReceiver.smtpauth;
}
public String getUserName()
{
return EmailReceiver.username;
}
public String getPassword()
{
return EmailReceiver.password;
}
public String getReplyTo()
{
return EmailReceiver.replyto;
}
public String getIncomingServer()
{
return EmailReceiver.incoming;
}
public String getOutgoingServer()
{
return EmailReceiver.outgoing;
}
public List<String> receive()
throws Exception
{
return receive(null);
}
public List<String> receive(String dir)
throws Exception
{
if (verbose) System.out.println("Receiving...");
List<String> messList = new ArrayList<String>();
Store store = null;
Folder folder = null;
try
{
// Properties props = System.getProperties();
Properties props = setProps();
if (verbose)
{
Set<Object> keys = props.keySet();
for (Object o : keys)
System.out.println(o.toString() + ":" + props.get(o).toString());
}
if (verbose) System.out.println("Getting session...");
// Session session = Session.getInstance(props, null);
Session session = Session.getInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
session.setDebug(verbose);
if (verbose) System.out.println("Session established.");
store = session.getStore(EmailReceiver.protocol);
if (EmailReceiver.incomingPort == 0)
store.connect(EmailReceiver.incoming, EmailReceiver.username, EmailReceiver.password);
else
store.connect(EmailReceiver.incoming, EmailReceiver.incomingPort, EmailReceiver.username, EmailReceiver.password);
if (verbose) System.out.println("Connected to store");
folder = store.getDefaultFolder();
if (folder == null)
throw new RuntimeException("No default folder");
folder = store.getFolder("INBOX");
if (folder == null)
throw new RuntimeException("No INBOX");
folder.open(Folder.READ_WRITE);
if (verbose) System.out.println("Connected... filtering, please wait.");
SearchTerm st = new AndTerm(new SearchTerm[] { new OrTerm(buildSearchTerm(sendEmailsTo)),
new SubjectTerm(acceptSubject),
new FlagTerm(new Flags(Flags.Flag.SEEN), false) });
// st = new SubjectTerm("PI Request");
Message msgs[] = folder.search(st);
// Message msgs[] = folder.getMessages();
if (verbose) System.out.println("Search completed, " + msgs.length + " message(s).");
for (int msgNum=0; msgNum<msgs.length; msgNum++)
{
try
{
Message mess = msgs[msgNum];
Address from[] = mess.getFrom();
String sender = "";
try
{
sender = from[0].toString();
}
catch(Exception exception)
{
exception.printStackTrace();
}
// System.out.println("Message from [" + sender + "], subject [" + subject + "], content [" + mess.getContent().toString().trim() + "]");
if (true)
{
if (!mess.isSet(javax.mail.Flags.Flag.SEEN) &&
!mess.isSet(javax.mail.Flags.Flag.DELETED))
{
String txtMess = printMessage(mess, dir);
messList.add(txtMess);
mess.setFlag(javax.mail.Flags.Flag.SEEN, true);
mess.setFlag(javax.mail.Flags.Flag.DELETED, true);
// Send an ack - by email.
if (this.emailSender == null)
this.emailSender = new EmailSender(this.provider);
this.emailSender.send(new String[] { sender },
ackSubject,
"Your request [" + txtMess.trim() + "] is being taken care of.");
if (verbose) System.out.println("Sent an ack to " + sender);
}
else
{
if (verbose) System.out.println("Old message in your inbox..., received " + mess.getReceivedDate().toString());
}
}
}
catch(Exception ex)
{
// System.err.println(ex.getMessage());
ex.printStackTrace();
}
}
}
catch(Exception ex)
{
throw ex;
}
finally
{
try
{
if (folder != null)
folder.close(true);
if (store != null)
store.close();
}
catch(Exception ex2)
{
System.err.println("Finally ...");
ex2.printStackTrace();
}
}
return messList;
}
public static String printMessage(Message message, String dir)
{
String ret = "";
try
{
String from = ((InternetAddress)message.getFrom()[0]).getPersonal();
if(from == null)
from = ((InternetAddress)message.getFrom()[0]).getAddress();
if (verbose) System.out.println("From: " + from);
String subject = message.getSubject();
if (verbose) System.out.println("Subject: " + subject);
Part messagePart = message;
Object content = messagePart.getContent();
if (content instanceof Multipart)
{
// messagePart = ((Multipart)content).getBodyPart(0);
int nbParts = ((Multipart)content).getCount();
if (verbose) System.out.println("[ Multipart Message ], " + nbParts + " part(s).");
for (int i=0; i<nbParts; i++)
{
messagePart = ((Multipart)content).getBodyPart(i);
if (messagePart.getContentType().toUpperCase().startsWith("APPLICATION/OCTET-STREAM"))
{
if (verbose) System.out.println(messagePart.getContentType() + ":" + messagePart.getFileName());
InputStream is = messagePart.getInputStream();
String newFileName = "";
if (dir != null)
newFileName = dir + File.separator;
newFileName += messagePart.getFileName();
FileOutputStream fos = new FileOutputStream(newFileName);
ret = messagePart.getFileName();
if (verbose) System.out.println("Downloading " + messagePart.getFileName() + "...");
copy(is, fos);
if (verbose) System.out.println("...done.");
}
else // text/plain, text/html
{
if (verbose) System.out.println("-- Part #" + i + " --, " + messagePart.getContentType().replace('\n', ' ').replace('\r', ' ').replace("\b", "").trim());
InputStream is = messagePart.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = "";
while (line != null)
{
line = br.readLine();
if (line != null)
{
if (verbose) System.out.println("[" + line + "]");
if (messagePart.getContentType().toUpperCase().startsWith("TEXT/PLAIN"))
ret += line;
}
}
br.close();
if (verbose) System.out.println("-------------------");
}
}
}
else
{
// System.out.println(" .Message is a " + content.getClass().getName());
// System.out.println("Content:");
// System.out.println(content.toString());
ret = content.toString();
}
if (verbose) System.out.println("-----------------------------");
}
catch(Exception ex)
{
ex.printStackTrace();
}
return ret;
}
private static void copy(InputStream in, OutputStream out)
throws IOException
{
synchronized(in)
{
synchronized(out)
{
byte buffer[] = new byte[256];
while (true)
{
int bytesRead = in.read(buffer);
if(bytesRead == -1)
break;
out.write(buffer, 0, bytesRead);
}
}
}
}
}
| Java |
package pi4j.email;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.json.JSONObject;
public class SampleMain
{
private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
private static boolean verbose = "true".equals(System.getProperty("verbose", "false"));
/**
* Invoked like:
* java pi4j.email.SampleMain [-verbose] -send:google -receive:yahoo
*
* This will send emails using google, and receive using yahoo.
* Do check the file email.properties for the different values associated with email servers.
*
* NO GPIO INTERACTION in this one.
*
* @param args See above
*/
public static void main(String[] args)
{
// String provider = "yahoo";
String providerSend = "oracle";
// String provider = "oracle";
// provider = "yahoo";
String providerReceive = "oracle";
// provider = "oracle";
for (int i=0; i<args.length; i++)
{
if ("-verbose".equals(args[i]))
{
verbose = true;
System.setProperty("verbose", "true");
}
else if (args[i].startsWith("-send:"))
providerSend = args[i].substring("-send:".length());
else if (args[i].startsWith("-receive:"))
providerReceive =args[i].substring("-receive:".length());
else if ("-help".equals(args[i]))
{
System.out.println("Usage:");
System.out.println(" java pi4j.email.SampleMain -verbose -send:google -receive:yahoo -help");
System.exit(0);
}
}
final EmailSender sender = new EmailSender(providerSend);
Thread senderThread = new Thread()
{
public void run()
{
try
{
for (int i=0; i<10; i++)
{
System.out.println("Sending...");
sender.send(new String[] { "olivier@lediouris.net",
"webmaster@lediouris.net",
"olivier.lediouris@gmail.com",
"olivier_le_diouris@yahoo.com",
"olivier.lediouris@oracle.com" },
"PI Request",
"{ operation: 'see-attached-" + Integer.toString(i + 1) + "' }",
"P8150115.JPG");
System.out.println("Sent.");
Thread.sleep(60000L); // 1 minute
}
System.out.println("Exiting...");
sender.send(new String[] { "olivier@lediouris.net",
"webmaster@lediouris.net",
"olivier.lediouris@gmail.com",
"olivier_le_diouris@yahoo.com",
"olivier.lediouris@oracle.com" },
"PI Request",
"{ operation: 'exit' }");
System.out.println("Bye.");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
};
senderThread.start(); // Bombarding
if (args.length > 1)
providerSend = args[1];
EmailReceiver receiver = new EmailReceiver(providerReceive); // For Google, pop must be explicitely enabled at the account level
try
{
boolean keepLooping = true;
while (keepLooping)
{
List<String> received = receiver.receive();
if (verbose || received.size() > 0)
System.out.println(SDF.format(new Date()) + " - Retrieved " + received.size() + " message(s).");
for (String s : received)
{
// System.out.println(s);
String operation = "";
try
{
JSONObject json = new JSONObject(s);
operation = json.getString("operation");
}
catch (Exception ex)
{
System.err.println(ex.getMessage());
System.err.println("Message is [" + s + "]");
}
if ("exit".equals(operation))
{
keepLooping = false;
System.out.println("Will exit next batch.");
// break;
}
else
{
System.out.println("Operation: [" + operation + "], sent for processing.");
try { Thread.sleep(1000L); } catch (InterruptedException ie) { ie.printStackTrace(); }
}
}
}
System.out.println("Done.");
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
| Java |
package pi4j.email;
import com.sun.mail.smtp.SMTPTransport;
import java.io.FileInputStream;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
public class EmailSender
{
private static String protocol;
private static int outgoingPort;
private static int incomingPort;
private static String username;
private static String password;
private static String outgoing;
private static String incoming;
private static String replyto;
private static boolean smtpauth;
private static String sendEmailsTo;
private static String eventSubject;
private static boolean verbose = "true".equals(System.getProperty("verbose", "false"));
public EmailSender(String provider) throws RuntimeException
{
EmailSender.protocol = "";
EmailSender.outgoingPort = 0;
EmailSender.incomingPort = 0;
EmailSender.username = "";
EmailSender.password = "";
EmailSender.outgoing = "";
EmailSender.incoming = "";
EmailSender.replyto = "";
EmailSender.smtpauth = false;
EmailSender.sendEmailsTo = "";
EmailSender.eventSubject = "";
Properties props = new Properties();
String propFile = "email.properties";
try
{
FileInputStream fis = new FileInputStream(propFile);
props.load(fis);
}
catch (Exception e)
{
System.out.println("email.properies file problem...");
throw new RuntimeException("File not found:email.properies");
}
EmailSender.sendEmailsTo = props.getProperty("pi.send.emails.to");
EmailSender.eventSubject = props.getProperty("pi.event.subject");
EmailSender.protocol = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.protocol");
EmailSender.outgoingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server.port", "0"));
EmailSender.incomingPort = Integer.parseInt(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server.port", "0"));
EmailSender.username = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.username", "");
EmailSender.password = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.password", "");
EmailSender.outgoing = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "outgoing.server", "");
EmailSender.incoming = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "incoming.server", "");
EmailSender.replyto = props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.replyto", "");
EmailSender.smtpauth = "true".equals(props.getProperty("pi." + (provider != null ? (provider + ".") : "") + "mail.smtpauth", "false"));
if (verbose)
{
System.out.println("-------------------------------------");
System.out.println("Protocol : " + EmailSender.protocol);
System.out.println("Usr/pswd : " + EmailSender.username + "/" + EmailSender.password);
System.out.println("Incoming server: " + EmailSender.incoming + ":" + EmailSender.incomingPort);
System.out.println("Outgoing server: " + EmailSender.outgoing + ":" + EmailSender.outgoingPort);
System.out.println("replyto : " + EmailSender.replyto);
System.out.println("SMTPAuth : " + EmailSender.smtpauth);
System.out.println("-------------------------------------");
}
}
public boolean isAuthRequired()
{
return EmailSender.smtpauth;
}
public String getUserName()
{
return EmailSender.username;
}
public String getPassword()
{
return EmailSender.password;
}
public String getReplyTo()
{
return EmailSender.replyto;
}
public String getIncomingServer()
{
return EmailSender.incoming;
}
public String getOutgoingServer()
{
return EmailSender.outgoing;
}
public String getEmailDest()
{
return EmailSender.sendEmailsTo;
}
public String getEventSubject()
{
return EmailSender.eventSubject;
}
public void send(String[] dest,
String subject,
String content)
throws MessagingException, AddressException
{
send(dest, subject, content, null);
}
public void send(String[] dest,
String subject,
String content,
String attachment)
throws MessagingException, AddressException
{
Properties props = setProps();
// Session session = Session.getDefaultInstance(props, auth);
Session session = Session.getInstance(props,
new javax.mail.Authenticator()
{
protected PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(username, password);
}
});
session.setDebug(verbose);
Transport tr = session.getTransport("smtp");
if (!(tr instanceof SMTPTransport))
System.out.println("This is NOT an SMTPTransport:[" + tr.getClass().getName() + "]");
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(EmailSender.replyto));
if (dest == null || dest.length == 0)
throw new RuntimeException("Need at least one recipient.");
msg.setRecipient(javax.mail.Message.RecipientType.TO, new InternetAddress(dest[0]));
for (int i=1; i<dest.length; i++)
msg.addRecipient(javax.mail.Message.RecipientType.CC, new InternetAddress(dest[i]));
msg.setSubject(subject);
if (attachment != null)
{
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText(content);
Multipart multipart = new MimeMultipart();
// Set text message part
multipart.addBodyPart(messageBodyPart);
// Part two is attachment
messageBodyPart = new MimeBodyPart();
String filename = attachment;
DataSource source = new FileDataSource(filename);
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
// Send the complete message parts
msg.setContent(multipart);
}
else
{
msg.setText(content != null ? content : "");
msg.setContent(content, "text/plain");
}
msg.saveChanges();
if (verbose) System.out.println("sending:[" + content + "], " + Integer.toString(content.length()) + " characters");
Transport.send(msg);
}
private Properties setProps()
{
Properties props = new Properties();
props.put("mail.debug", verbose?"true":"false");
props.put("mail.smtp.host", EmailSender.outgoing);
props.put("mail.smtp.port", Integer.toString(EmailSender.outgoingPort));
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true"); // See http://www.oracle.com/technetwork/java/faq-135477.html#yahoomail
// props.put("mail.smtp.starttls.required", "true");
props.put("mail.smtp.ssl.enable", "true");
return props;
}
}
| Java |
package pi4j.email;
import com.pi4j.io.gpio.event.GpioPinDigitalStateChangeEvent;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.json.JSONObject;
import pi4j.gpio.GPIOController;
import pi4j.gpio.RaspberryPIEventListener;
public class PIControllerMain implements RaspberryPIEventListener
{
private final static SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
private static boolean verbose = "true".equals(System.getProperty("verbose", "false"));
private static String providerSend = "google";
private static String providerReceive = "google";
EmailSender sender = null;
/**
* Invoked like:
* java pi4j.email.PIControllerMain [-verbose] -send:google -receive:yahoo -help
*
* This will send emails using google, and receive using yahoo.
* Default values are:
* java pi4j.email.PIControllerMain -send:google -receive:google
*
* Do check the file email.properties for the different values associated with email servers.
*
* @param args See above
*/
public static void main(String[] args)
{
for (int i=0; i<args.length; i++)
{
if ("-verbose".equals(args[i]))
{
verbose = true;
System.setProperty("verbose", "true");
}
else if (args[i].startsWith("-send:"))
providerSend = args[i].substring("-send:".length());
else if (args[i].startsWith("-receive:"))
providerReceive =args[i].substring("-receive:".length());
else if ("-help".equals(args[i]))
{
System.out.println("Usage:");
System.out.println(" java pi4j.email.PIControllerMain -verbose -send:google -receive:yahoo -help");
System.exit(0);
}
}
PIControllerMain lmc = new PIControllerMain();
GPIOController piController = new GPIOController(lmc);
EmailReceiver receiver = new EmailReceiver(providerReceive); // For Google, pop must be explicitely enabled at the account level
try
{
System.out.println("Waiting for instructions.");
boolean keepLooping = true;
while (keepLooping)
{
List<String> received = receiver.receive();
if (verbose || received.size() > 0)
System.out.println(SDF.format(new Date()) + " - Retrieved " + received.size() + " message(s).");
for (String s : received)
{
// System.out.println(s);
String operation = "";
try
{
JSONObject json = new JSONObject(s);
operation = json.getString("operation");
}
catch (Exception ex)
{
System.err.println(ex.getMessage());
System.err.println("Message is [" + s + "]");
}
if ("exit".equals(operation))
{
keepLooping = false;
System.out.println("Will exit next batch.");
// break;
}
else
{
if ("turn-green-on".equals(operation))
{
System.out.println("Turning green on");
piController.switchGreen(true);
}
else if ("turn-green-off".equals(operation))
{
System.out.println("Turning green off");
piController.switchGreen(false);
}
else if ("turn-yellow-on".equals(operation))
{
System.out.println("Turning yellow on");
piController.switchYellow(true);
}
else if ("turn-yellow-off".equals(operation))
{
System.out.println("Turning yellow off");
piController.switchYellow(false);
}
try { Thread.sleep(1000L); } catch (InterruptedException ie) { ie.printStackTrace(); }
}
}
}
piController.shutdown();
System.out.println("Done.");
System.exit(0);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public void manageEvent(GpioPinDigitalStateChangeEvent event)
{
if (sender == null)
sender = new EmailSender(providerSend);
try
{
String mess = "{ pin: '" + event.getPin() + "', state:'" + event.getState() + "' }";
System.out.println("Sending:" + mess);
sender.send(sender.getEmailDest().split(","),
sender.getEventSubject(),
mess);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
| Java |
package sevensegdisplay;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class SevenSegment
{
private LEDBackPack display = null;
private final static int[] digits = { 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, 0x7F, 0x6F, // 0..9
0x77, 0x7C, 0x39, 0x5E, 0x79, 0x71 }; // A..F
public final static Map<String, Byte> ALL_CHARS = new HashMap<>();
// 0x00, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x02, /* ! " # $ % & ' */
// 0x80, 0x0f, 0x80, 0x80, 0x04, 0x40, 0x80, 0x80, /* ( ) * + , - . / */
// 0x3F, 0x06, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x07, /* 0 1 2 3 4 5 6 7 */
// 0x7F, 0x6F, 0x80, 0x80, 0x80, 0x48, 0x80, 0x27, /* 8 9 : ; < = > ? */
// 0x80, 0x77, 0x7c, 0x39, 0x5e, 0x79, 0x71, 0x3d, /* @ A B C D E F G */
// 0x76, 0x30, 0x1E, 0x76, 0x38, 0x15, 0x37, 0x3f, /* H I J K L M N O */
// 0x73, 0x67, 0x31, 0x6d, 0x78, 0x3e, 0x1C, 0x2A, /* P Q R S T U V W */
// 0x76, 0x6e, 0x5b, 0x39, 0x80, 0x0F, 0x80, 0x08, /* X Y Z [ \ ] ^ _ */
// 0x80, 0x5f, 0x7c, 0x58, 0x5e, 0x7b, 0x71, 0x6F, /* ` a b c d e f g */
// 0x74, 0x30, 0x0E, 0x76, 0x06, 0x15, 0x54, 0x5c, /* h i j k l m n o */
// 0x73, 0x67, 0x50, 0x6d, 0x78, 0x1c, 0x1c, 0x2A, /* p q r s t u v w */
// 0x76, 0x6e, 0x5b, 0x39, 0x80, 0x0F, 0x80, 0x08 /* x y z { | } ~ */
static
{ // FYI, 0x80 is the dot, displayed instead of "undisplayable" characters.
ALL_CHARS.put(" ", (byte)0x00);
ALL_CHARS.put("!", (byte)0x80);
ALL_CHARS.put("\"", (byte)0x80);
ALL_CHARS.put("#", (byte)0x80);
ALL_CHARS.put("$", (byte)0x80);
ALL_CHARS.put("%", (byte)0x80);
ALL_CHARS.put("&", (byte)0x80);
ALL_CHARS.put("'", (byte)0x02);
ALL_CHARS.put("(", (byte)0x39);
ALL_CHARS.put(")", (byte)0x0f);
ALL_CHARS.put("*", (byte)0x80);
ALL_CHARS.put("+", (byte)0x80);
ALL_CHARS.put(",", (byte)0x04);
ALL_CHARS.put("-", (byte)0x40);
ALL_CHARS.put(".", (byte)0x80);
ALL_CHARS.put("0", (byte)0x3f);
ALL_CHARS.put("1", (byte)0x06);
ALL_CHARS.put("2", (byte)0x5b);
ALL_CHARS.put("3", (byte)0x4f);
ALL_CHARS.put("4", (byte)0x66);
ALL_CHARS.put("5", (byte)0x6d);
ALL_CHARS.put("6", (byte)0x7d);
ALL_CHARS.put("7", (byte)0x07);
ALL_CHARS.put("8", (byte)0x7f);
ALL_CHARS.put("9", (byte)0x6f);
ALL_CHARS.put(":", (byte)0x80);
ALL_CHARS.put(";", (byte)0x80);
ALL_CHARS.put("<", (byte)0x80);
ALL_CHARS.put("=", (byte)0x48);
ALL_CHARS.put(">", (byte)0x80);
ALL_CHARS.put("?", (byte)0x27);
ALL_CHARS.put("@", (byte)0x80);
ALL_CHARS.put("A", (byte)0x77);
ALL_CHARS.put("B", (byte)0x7c);
ALL_CHARS.put("C", (byte)0x39);
ALL_CHARS.put("D", (byte)0x5e);
ALL_CHARS.put("E", (byte)0x79);
ALL_CHARS.put("F", (byte)0x71);
ALL_CHARS.put("G", (byte)0x3d);
ALL_CHARS.put("H", (byte)0x76);
ALL_CHARS.put("I", (byte)0x30);
ALL_CHARS.put("J", (byte)0x1e);
ALL_CHARS.put("K", (byte)0x76);
ALL_CHARS.put("L", (byte)0x38);
ALL_CHARS.put("M", (byte)0x15);
ALL_CHARS.put("N", (byte)0x37);
ALL_CHARS.put("O", (byte)0x3f);
ALL_CHARS.put("P", (byte)0x73);
ALL_CHARS.put("Q", (byte)0x67);
ALL_CHARS.put("R", (byte)0x31);
ALL_CHARS.put("S", (byte)0x6d);
ALL_CHARS.put("T", (byte)0x78);
ALL_CHARS.put("U", (byte)0x3e);
ALL_CHARS.put("V", (byte)0x1c);
ALL_CHARS.put("W", (byte)0x2a);
ALL_CHARS.put("X", (byte)0x76);
ALL_CHARS.put("Y", (byte)0x6e);
ALL_CHARS.put("Z", (byte)0x5b);
ALL_CHARS.put("[", (byte)0x39);
ALL_CHARS.put("\\", (byte)0x80);
ALL_CHARS.put("]", (byte)0x0f);
ALL_CHARS.put("^", (byte)0x80);
ALL_CHARS.put("_", (byte)0x08);
ALL_CHARS.put("`", (byte)0x80);
ALL_CHARS.put("a", (byte)0x5f);
ALL_CHARS.put("b", (byte)0x7c);
ALL_CHARS.put("c", (byte)0x58);
ALL_CHARS.put("d", (byte)0x5e);
ALL_CHARS.put("e", (byte)0x7b);
ALL_CHARS.put("f", (byte)0x71);
ALL_CHARS.put("g", (byte)0x6f);
ALL_CHARS.put("h", (byte)0x74);
ALL_CHARS.put("i", (byte)0x30);
ALL_CHARS.put("j", (byte)0x0e);
ALL_CHARS.put("k", (byte)0x76);
ALL_CHARS.put("l", (byte)0x06);
ALL_CHARS.put("m", (byte)0x15);
ALL_CHARS.put("n", (byte)0x54);
ALL_CHARS.put("o", (byte)0x5c);
ALL_CHARS.put("p", (byte)0x73);
ALL_CHARS.put("q", (byte)0x67);
ALL_CHARS.put("r", (byte)0x50);
ALL_CHARS.put("s", (byte)0x6d);
ALL_CHARS.put("t", (byte)0x78);
ALL_CHARS.put("u", (byte)0x1c);
ALL_CHARS.put("v", (byte)0x1c);
ALL_CHARS.put("w", (byte)0x2a);
ALL_CHARS.put("x", (byte)0x76);
ALL_CHARS.put("y", (byte)0x6e);
ALL_CHARS.put("z", (byte)0x5b);
ALL_CHARS.put("{", (byte)0x39);
ALL_CHARS.put("|", (byte)0x30);
ALL_CHARS.put("}", (byte)0x0f);
ALL_CHARS.put("~", (byte)0x80);
}
public SevenSegment()
{
display = new LEDBackPack(0x70);
}
public SevenSegment(int addr)
{
display = new LEDBackPack(addr, false);
}
public SevenSegment(int addr, boolean b)
{
display = new LEDBackPack(addr, b);
}
/*
* Sets a digit using the raw 16-bit value
*/
public void writeDigitRaw(int charNumber, int value) throws IOException
{
if (charNumber > 7)
return;
// Set the appropriate digit
this.display.setBufferRow(charNumber, value);
}
public void writeDigitRaw(int charNumber, String value) throws IOException
{
if (charNumber > 7)
return;
if (value.trim().length() > 1)
return;
// Set the appropriate digit
int byteValue = ALL_CHARS.get(value);
this.display.setBufferRow(charNumber, byteValue);
}
/*
* Sets a single decimal or hexademical value (0..9 and A..F)
*/
public void writeDigit(int charNumber, int value) throws IOException
{
writeDigit(charNumber, value, false);
}
public void writeDigit(int charNumber, int value, boolean dot) throws IOException
{
if (charNumber > 7)
return;
if (value > 0xF)
return;
// Set the appropriate digit
this.display.setBufferRow(charNumber, digits[value] | (dot?0x1 << 7:0x0));
}
/*
* Enables or disables the colon character
*/
public void setColon() throws IOException
{
setColon(true);
}
public void setColon(boolean state) throws IOException
{
// Warning: This function assumes that the colon is character '2',
// which is the case on 4 char displays, but may need to be modified
// if another display type is used
if (state)
this.display.setBufferRow(2, 0xFFFF);
else
this.display.setBufferRow(2, 0);
}
public void clear() throws IOException
{
this.display.clear();
}
}
| Java |
package sevensegdisplay.samples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import sevensegdisplay.SevenSegment;
public class AllCharInteractiveSample
{
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;
}
private static SevenSegment segment = new SevenSegment(0x70, true);
public static void main(String[] args) throws IOException
{
boolean go = true;
System.out.println("Enter 'quit' to quit...");
while (go)
{
String input = userInput("Enter a string (up to 4 char) > ");
if ("quit".equalsIgnoreCase(input))
go = false;
else
{
String[] row = { " ", " ", " ", " " };
for (int i=0; i<Math.min(input.length(), 4); i++)
{
String one = input.substring(i, i+1);
Byte b = SevenSegment.ALL_CHARS.get(one);
if (b != null)
row[i] = one;
else
{
System.out.println(one + " not in the list.");
row[i] = " ";
}
}
fullDisplay(row);
}
}
System.out.println("Bye");
segment.clear();
}
private static void fullDisplay(String[] row) throws IOException
{
segment.writeDigitRaw(0, row[0]);
segment.writeDigitRaw(1, row[1]);
segment.writeDigitRaw(3, row[2]);
segment.writeDigitRaw(4, row[3]);
}
}
| Java |
package sevensegdisplay.samples;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import sevensegdisplay.SevenSegment;
public class InteractiveSample
{
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) throws IOException
{
SevenSegment segment = new SevenSegment(0x70, true);
boolean go = true;
System.out.println("Enter 'quit' to quit...");
while (go)
{
String input = userInput("Number to display [0..F] > ");
if ("quit".equalsIgnoreCase(input))
go = false;
else
{
int digit = 0;
boolean digitOk = true;
try
{
digit = Integer.parseInt(input, 16);
if (digit < 0 ||digit > 0xF)
{
System.out.println("Invalid digit");
digitOk = false;
}
}
catch (NumberFormatException nfe)
{
System.out.println(nfe.toString());
digitOk = false;
}
if (digitOk)
{
input = userInput("Position [0..7] > ");
int pos = 0;
boolean posOk = true;
try
{
pos = Integer.parseInt(input);
if (pos < 0 || pos > 7)
{
posOk = false;
System.out.println("Invalid position");
}
}
catch (NumberFormatException nfe)
{
System.out.println(nfe.toString());
posOk = false;
}
if (digitOk && posOk)
{
segment.writeDigit(pos, digit); // Display
}
}
}
}
System.out.println("Bye");
segment.clear();
}
}
| Java |
package sevensegdisplay.samples;
import com.pi4j.system.SystemInfo;
import java.io.IOException;
import sevensegdisplay.SevenSegment;
public class CPUTempSample
{
private static boolean go = true;
private static void setGo(boolean b)
{
go = b;
}
public static void main(String[] args) throws IOException, InterruptedException
{
SevenSegment segment = new SevenSegment(0x70, true);
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
setGo(false);
}
});
while (go)
{
float cpuTemp = SystemInfo.getCpuTemperature();
// Notice the digit index: 0, 1, 3, 4. 2 is the column ":"
int one = (int)cpuTemp / 10;
int two = ((int)cpuTemp) % 10;
int three = ((int)( 10 * cpuTemp) % 10);
int four = ((int)(100 * cpuTemp) % 10);
// System.out.println(one + " " + two + "." + three + " " + four);
segment.writeDigit(0, one);
segment.writeDigit(1, two, true);
segment.writeDigit(3, three);
segment.writeDigit(4, four);
// System.out.println("Temp:" + cpuTemp);
try { Thread.sleep(1000L); } catch (InterruptedException ie){}
}
segment.clear();
}
}
| Java |
package sevensegdisplay.samples;
import java.io.IOException;
import sevensegdisplay.SevenSegment;
public class OnOffSample
{
public static void main(String[] args) throws IOException
{
SevenSegment segment = new SevenSegment(0x70, true);
for (int i=0; i<5; i++)
{
// Notice the digit index: 0, 1, 3, 4. 2 is the column ":"
segment.writeDigit(0, 8, true);
segment.writeDigit(1, 8, true);
segment.writeDigit(3, 8, true);
segment.writeDigit(4, 8, true);
segment.setColon();
try { Thread.sleep(1000L); } catch (InterruptedException ie){}
segment.clear();
try { Thread.sleep(1000L); } catch (InterruptedException ie){}
}
}
}
| Java |
package sevensegdisplay.samples;
import java.io.IOException;
import sevensegdisplay.SevenSegment;
public class CounterSample
{
public static void main(String[] args) throws IOException
{
SevenSegment segment = new SevenSegment(0x70, true);
long before = System.currentTimeMillis();
for (int i=0; i<10000; i++)
{
// Notice the digit index: 0, 1, 3, 4. 2 is the column ":"
segment.writeDigit(0, (i / 1000)); // 1000th
segment.writeDigit(1, (i / 100) % 10); // 100th
segment.writeDigit(3, (i / 10) % 10); // 10th
segment.writeDigit(4, i % 10); // Ones
// try { Thread.sleep(10L); } catch (InterruptedException ie){}
}
long after = System.currentTimeMillis();
System.out.println("Took " + Long.toString(after - before) + " ms.");
try { Thread.sleep(1000L); } catch (InterruptedException ie){}
segment.clear();
}
}
| Java |
package sevensegdisplay.samples;
import java.io.IOError;
import java.io.IOException;
import java.util.Set;
import sevensegdisplay.SevenSegment;
public class AllCharSample
{
private static SevenSegment segment = new SevenSegment(0x70, true);
public static void main(String[] args) throws IOException
{
String[] displayed = { " ", " ", " ", " " };
Set<String> allChars = SevenSegment.ALL_CHARS.keySet();
for (String c : allChars)
{
System.out.println("--> " + c);
displayed = scrollLeft(displayed, c);
fullDisplay(displayed);
try { Thread.sleep(500L); } catch (InterruptedException ie){}
}
try { Thread.sleep(3000L); } catch (InterruptedException ie){}
for (int i=0; i<4; i++)
{
fullDisplay(new String[] { "C", "A", "F", "E" });
try { Thread.sleep(1000L); } catch (InterruptedException ie){}
fullDisplay(new String[] { "B", "A", "B", "E" });
try { Thread.sleep(1000L); } catch (InterruptedException ie){}
}
segment.clear();
}
private static String[] scrollLeft(String[] row, String c)
{
String[] newSa = row.clone();
for (int i=0; i<row.length - 1; i++)
newSa[i] = row[i+1];
newSa[row.length - 1] = c;
return newSa;
}
private static void fullDisplay(String[] row) throws IOException
{
segment.writeDigitRaw(0, row[0]);
segment.writeDigitRaw(1, row[1]);
segment.writeDigitRaw(3, row[2]);
segment.writeDigitRaw(4, row[3]);
}
}
| Java |
package sevensegdisplay.samples;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import sevensegdisplay.SevenSegment;
public class ClockSample
{
public static void main(String[] args) throws IOException
{
final SevenSegment segment = new SevenSegment(0x70, true);
System.out.println("Press CTRL+C to exit");
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
try
{
segment.clear();
System.out.println("\nBye");
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
});
// Continually update the time on a 4 char, 7-segment display
while (true)
{
Calendar now = GregorianCalendar.getInstance(TimeZone.getTimeZone("America/Los_Angeles"));
int hour = now.get(Calendar.HOUR);
int minute = now.get(Calendar.MINUTE);
int second = now.get(Calendar.SECOND);
// Set hours
segment.writeDigit(0, (hour / 10)); // Tens
segment.writeDigit(1, hour % 10); // Ones
// Set minutes
segment.writeDigit(3, (minute / 10)); // Tens
segment.writeDigit(4, minute % 10); // Ones
// Toggle colon
segment.setColon(second % 2 != 0); // Toggle colon at 1Hz
// Wait one second
try { Thread.sleep(1000L); } catch (InterruptedException ie){}
}
}
}
| Java |
package sevensegdisplay;
import com.pi4j.io.i2c.I2CBus;
import com.pi4j.io.i2c.I2CDevice;
import com.pi4j.io.i2c.I2CFactory;
import java.io.IOException;
/*
* I2C Required for this one
*/
public class LEDBackPack
{
/*
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: 70 -- -- -- -- -- -- --
*/
// This next addresses is returned by "sudo i2cdetect -y 1", see above.
public final static int LEDBACKPACK_ADDRESS = 0x70;
private boolean verbose = false;
private I2CBus bus;
private I2CDevice ledBackpack;
// Registers
public final static int HT16K33_REGISTER_DISPLAY_SETUP = 0x80;
public final static int HT16K33_REGISTER_SYSTEM_SETUP = 0x20;
public final static int HT16K33_REGISTER_DIMMING = 0xE0;
// Blink rate
public final static int HT16K33_BLINKRATE_OFF = 0x00;
public final static int HT16K33_BLINKRATE_2HZ = 0x01;
public final static int HT16K33_BLINKRATE_1HZ = 0x02;
public final static int HT16K33_BLINKRATE_HALFHZ = 0x03;
// Display buffer (8x16-bits).
// 1st digit, 2nd digit, column, 3rd digit, 4th digit, ?, ?, ? Probably for the 8x8 led matrix
private int[] buffer = { 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0x0000 };
public LEDBackPack()
{
this(LEDBACKPACK_ADDRESS);
}
public LEDBackPack(int address)
{
this(address, false);
}
public LEDBackPack(int address, boolean v)
{
this.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
ledBackpack = bus.getDevice(address);
if (verbose)
System.out.println("Connected to device. OK.");
//Turn the oscillator on
ledBackpack.write(HT16K33_REGISTER_SYSTEM_SETUP | 0x01, (byte)0x00);
// Turn blink off
this.setBlinkRate(HT16K33_BLINKRATE_OFF);
// Set maximum brightness
this.setBrightness(15);
// Clear the screen
this.clear();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
/*
* Sets the brightness level from 0..15
*/
private void setBrightness(int brightness) throws IOException
{
if (brightness > 15)
brightness = 15;
ledBackpack.write(HT16K33_REGISTER_DIMMING | brightness, (byte)0x00);
}
/*
* Sets the blink rate
*/
private void setBlinkRate(int blinkRate) throws IOException
{
if (blinkRate > HT16K33_BLINKRATE_HALFHZ)
blinkRate = HT16K33_BLINKRATE_OFF;
ledBackpack.write(HT16K33_REGISTER_DISPLAY_SETUP | 0x01 | (blinkRate << 1), (byte)0x00);
}
/*
* Updates a single 16-bit entry in the 8*16-bit buffer
*/
public void setBufferRow(int row, int value) throws IOException
{
setBufferRow(row, value, true);
}
public void setBufferRow(int row, int value, boolean update) throws IOException
{
if (row > 7)
return; // Prevent buffer overflow
this.buffer[row] = value; // value # & 0xFFFF
if (update)
this.writeDisplay(); // Update the display
}
/*
* Returns a copy of the raw buffer contents
*/
public int[] getBuffer()
{
int[] bufferCopy = buffer.clone();
return bufferCopy;
}
/*
* Updates the display memory
*/
private void writeDisplay() throws IOException
{
byte[] bytes = new byte[2 * buffer.length];
for (int i=0; i<buffer.length; i++)
{
int item = buffer[i];
bytes[2 * i] = (byte)(item & 0xFF);
bytes[(2 * i) + 1] = (byte)((item >> 8) & 0xFF);
}
ledBackpack.write(0x00, bytes, 0, bytes.length);
}
/*
* Clears the display memory
*/
public void clear() throws IOException
{
clear(true);
}
public void clear(boolean update) throws IOException
{
this.buffer = new int[] { 0, 0, 0, 0, 0, 0, 0, 0 }; // Reset. Bam!
if (update)
this.writeDisplay();
}
}
| Java |
package raspisamples;
import raspisamples.adc.JoyStick;
import raspisamples.adc.JoyStickClient;
import raspisamples.servo.StandardServo;
/*
* Joystick read with ADC (MCP3008)
* 2 Servos (UP/LR)
*/
public class PanTiltJoyStick
{
private static StandardServo ssUD = null,
ssLR = null;
private static JoyStick joyStick = null;
public static void main(String[] args)
{
ssUD = new StandardServo(14); // 14 : Address on the board (1..15)
ssLR = new StandardServo(15); // 15 : Address on the board (1..15)
// Init/Reset
ssUD.stop();
ssLR.stop();
ssUD.setAngle(0f);
ssLR.setAngle(0f);
StandardServo.waitfor(2000);
JoyStickClient jsc = new JoyStickClient()
{
@Override
public void setUD(int v) // 0..100
{
float angle = (float)(v - 50) * (9f / 5f); // conversion from 1..100 to -90..+90
if ("true".equals(System.getProperty("verbose", "false")))
System.out.println("UD:" + v + ", -> " + angle + " deg.");
ssUD.setAngle(angle); // -90..+90
}
@Override
public void setLR(int v) // 0..100
{
float angle = (float)(v - 50) * (9f / 5f); // conversion from 1..100 to -90..+90
if ("true".equals(System.getProperty("verbose", "false")))
System.out.println("LR:" + v + ", -> " + angle + " deg.");
ssLR.setAngle(angle); // -90..+90
}
};
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
ssUD.setAngle(0f);
ssLR.setAngle(0f);
StandardServo.waitfor(500);
ssUD.stop();
ssLR.stop();
System.out.println("\nBye (Ctrl+C)");
}
});
try
{
joyStick = new JoyStick(jsc);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
ssUD.setAngle(0f);
ssLR.setAngle(0f);
StandardServo.waitfor(500);
ssUD.stop();
ssLR.stop();
System.out.println("Bye");
}
}
}
| Java |
package raspisamples;
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;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import raspisamples.pwm.PWMPin;
public class PWM3ColorLed
{
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)
throws InterruptedException
{
final GpioController gpio = GpioFactory.getInstance();
final PWMPin pin00 = new PWMPin(RaspiPin.GPIO_00, "Blue", PinState.HIGH);
final PWMPin pin01 = new PWMPin(RaspiPin.GPIO_01, "Green", PinState.HIGH);
final PWMPin pin02 = new PWMPin(RaspiPin.GPIO_02, "Red", PinState.HIGH);
System.out.println("Ready...");
Runtime.getRuntime().addShutdownHook(new Thread("Hook")
{
public void run()
{
try
{
System.out.println("\nQuitting");
pin00.stopPWM();
pin01.stopPWM();
pin02.stopPWM();
Thread.sleep(1000);
// Last blink
System.out.println("Bye-bye");
pin00.low();
Thread.sleep(500);
pin00.high();
Thread.sleep(500);
pin00.low();
gpio.shutdown();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
});
Thread.sleep(1000);
pin00.emitPWM(0);
pin01.emitPWM(0);
pin02.emitPWM(0);
for (int vol=0; vol<100; vol++)
{
pin00.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin00.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
for (int vol=0; vol<100; vol++)
{
pin01.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin01.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
for (int vol=0; vol<100; vol++)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
Thread one = new Thread()
{
public void run()
{
while (true)
{
final int sleep = (int)(20 * Math.random());
for (int vol=0; vol<100; vol++)
{
pin00.adjustPWMVolume(vol);
try { Thread.sleep(sleep); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin00.adjustPWMVolume(vol);
try { Thread.sleep(sleep); } catch (Exception ex) {}
}
}
}
};
Thread two = new Thread()
{
public void run()
{
while (true)
{
final int sleep = (int)(20 * Math.random());
for (int vol=0; vol<100; vol++)
{
pin01.adjustPWMVolume(vol);
try { Thread.sleep(sleep); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin01.adjustPWMVolume(vol);
try { Thread.sleep(sleep); } catch (Exception ex) {}
}
}
}
};
Thread three = new Thread()
{
public void run()
{
while (true)
{
final int sleep = (int)(20 * Math.random());
for (int vol=0; vol<100; vol++)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(sleep); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(sleep); } catch (Exception ex) {}
}
}
}
};
one.start();
two.start();
three.start();
Thread me = Thread.currentThread();
synchronized (me)
{
try { me.wait(); } catch (InterruptedException ie) {}
}
System.out.println("Tcho!");
}
}
| Java |
package raspisamples;
import adafruiti2c.sensor.AdafruitBMP180;
import com.pi4j.system.SystemInfo;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import sevensegdisplay.SevenSegment;
/*
* Two devices on the I2C bus.
* A BMP180, and a 7-segment backpack display HT16K33
* mounted serially (V3V, GND, SDA, SLC)
*/
public class SevenSegBMP180
{
private static boolean go = true;
private static long wait = 2000L;
public static void main(String[] args)
{
final NumberFormat NF = new DecimalFormat("##00.00");
AdafruitBMP180 sensor = new AdafruitBMP180();
final SevenSegment segment = new SevenSegment(0x70, true);
Runtime.getRuntime().addShutdownHook(new Thread("Hook")
{
public void run()
{
System.out.println("\nQuitting");
try { segment.clear(); } catch (Exception ex) {}
System.out.println("Bye-bye");
go = false;
}
});
while (go)
{
float temp = 0;
try { temp = sensor.readTemperature(); }
catch (Exception ex)
{
System.err.println(ex.getMessage());
ex.printStackTrace();
}
System.out.println("Temperature: " + NF.format(temp) + " C");
try
{
displayString("TEMP", segment);
try { Thread.sleep(wait); } catch (InterruptedException ie){}
displayFloat(temp, segment);
try { Thread.sleep(wait); } catch (InterruptedException ie){}
}
catch (IOException ex) { ex.printStackTrace(); }
// Bonus : CPU Temperature
try
{
float cpu = SystemInfo.getCpuTemperature();
System.out.println("CPU Temperature : " + cpu);
System.out.println("CPU Core Voltage : " + SystemInfo.getCpuVoltage());
displayString("CPU ", segment);
try { Thread.sleep(wait); } catch (InterruptedException ie){}
displayFloat(cpu, segment);
try { Thread.sleep(wait); } catch (InterruptedException ie){}
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
private static void displayFloat(float t, SevenSegment segment) throws IOException
{
int one = (int)t / 10;
int two = ((int)t) % 10;
int three = ((int)( 10 * t) % 10);
int four = ((int)(100 * t) % 10);
// System.out.println(one + " " + two + "." + three + " " + four);
segment.writeDigit(0, one);
segment.writeDigit(1, two, true);
segment.writeDigit(3, three);
segment.writeDigit(4, four);
}
private static void displayString(String row, SevenSegment segment) throws IOException
{
segment.writeDigitRaw(0, row.substring(0, 1));
segment.writeDigitRaw(1, row.substring(1, 2));
segment.writeDigitRaw(3, row.substring(2, 3));
segment.writeDigitRaw(4, row.substring(3, 4));
}
}
| Java |
package raspisamples;
import java.io.InputStream;
import raspisamples.servo.StandardServo;
/*
* Driven by keyboard entries.
* 2 Servos (UP/LR)
*/
public class PanTilt
{
private static StandardServo ssUD = null,
ssLR = null;
public static void main(String[] args) throws Exception
{
ssUD = new StandardServo(14); // 14 : Address on the board (1..15)
ssLR = new StandardServo(15); // 15 : Address on the board (1..15)
// Init/Reset
ssUD.stop();
ssLR.stop();
ssUD.setAngle(0f);
ssLR.setAngle(0f);
StandardServo.waitfor(2000);
InputStream in = System.in;
boolean go = true;
float angleUD = 0f;
float angleLR = 0f;
System.out.println("Type [U]p, [D]own, [L]eft, [R]ight, or [Q]uit. (followed by [Return])");
boolean unmanaged = false;
while (go)
{
unmanaged = false;
if (in.available() > 0)
{
int b = in.read();
if (((char)b) == 'Q' || ((char)b) == 'q')
go = false;
else if (((char)b) == 'L' || ((char)b) == 'l')
{
angleLR -= (((char)b) == 'L' ? 10 : 1);
ssLR.setAngle(angleLR); // -90..+90
}
else if (((char)b) == 'R' || ((char)b) == 'r')
{
angleLR += (((char)b) == 'R' ? 10 : 1);
ssLR.setAngle(angleLR); // -90..+90
}
else if (((char)b) == 'U' || ((char)b) == 'u') // Inverted...
{
angleUD -= (((char)b) == 'U' ? 10 : 1);
ssUD.setAngle(angleUD); // -90..+90
}
else if (((char)b) == 'D' || ((char)b) == 'd') // Inverted...
{
angleUD += (((char)b) == 'D' ? 10 : 1);
ssUD.setAngle(angleUD); // -90..+90
}
else
unmanaged = true;
if (!unmanaged && go)
{
System.out.println("LR:" + angleLR + ", UD:" + angleUD);
}
}
}
// Reset to 0,0 before shutting down.
ssUD.setAngle(0f);
ssLR.setAngle(0f);
StandardServo.waitfor(2000);
ssUD.stop();
ssLR.stop();
System.out.println("Bye");
}
}
| Java |
package raspisamples.adc;
public interface JoyStickClient
{
public void setUD(int v);
public void setLR(int v);
}
| Java |
package raspisamples.adc;
import adc.ADCContext;
import adc.ADCListener;
import adc.ADCObserver;
/* A two-channel listener */
public class JoyStick
{
private static ADCObserver.MCP3008_input_channels channel[] = null;
private final int[] channelValues = new int[] { 0, 0 }; // (0..100)
private JoyStickClient joyStickClient = null;
private int prevUDValue = 0, prevLRValue = 0;
public JoyStick(JoyStickClient jsc) throws Exception
{
System.out.println(">> Channel MCP3008 #0: Up-Down");
System.out.println(">> Channel MCP3008 #1: Left-Right");
joyStickClient = jsc;
channel = new ADCObserver.MCP3008_input_channels[]
{
ADCObserver.MCP3008_input_channels.CH0, // UD
ADCObserver.MCP3008_input_channels.CH1 // LR
};
final ADCObserver obs = new ADCObserver(channel);
ADCContext.getInstance().addListener(new ADCListener()
{
@Override
public void valueUpdated(ADCObserver.MCP3008_input_channels inputChannel, int newValue)
{
int ch = inputChannel.ch();
int volume = (int)(newValue / 10.23); // [0, 1023] ~ [0x0000, 0x03FF] ~ [0&0, 0&1111111111]
if ("true".equals(System.getProperty("verbose", "false")))
System.out.println("\tServo channel:" + ch + ", value " + newValue + ", vol. " + volume + " %.");
channelValues[ch] = volume;
if (ch == channel[0].ch() && volume != prevUDValue)
joyStickClient.setUD(volume);
if (ch == channel[1].ch() && volume != prevLRValue)
joyStickClient.setLR(volume);
}
});
obs.start();
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
if (obs != null)
obs.stop();
}
});
}
}
| Java |
package raspisamples.util;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class HTTPClient
{
public static String getContent(String url) throws Exception
{
String ret = null;
try
{
byte content[] = readURL(new URL(url));
ret = new String(content);
}
catch(Exception e)
{
throw e;
}
return ret;
}
private static byte[] readURL(URL url) throws Exception
{
byte content[] = null;
try
{
URLConnection newURLConn = url.openConnection();
InputStream is = newURLConn.getInputStream();
byte aByte[] = new byte[2];
int nBytes;
long started = System.currentTimeMillis();
int nbLoop = 1;
while((nBytes = is.read(aByte, 0, 1)) != -1)
{
content = Utilities.appendByte(content, aByte[0]);
if (content.length > (nbLoop * 1000))
{
long now = System.currentTimeMillis();
long delta = now - started;
double rate = (double)content.length / ((double)delta / 1000D);
System.out.println("Downloading at " + rate + " bytes per second.");
nbLoop++;
}
}
}
catch(IOException e)
{
System.err.println("ReadURL for " + url.toString() + "\nnewURLConn failed :\n" + e);
throw e;
}
catch(Exception e)
{
System.err.println("Exception for: " + url.toString());
}
return content;
}
}
| Java |
package raspisamples.util;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
public class Utilities
{
public static void copy(InputStream is, OutputStream os) throws IOException
{
synchronized (is)
{
synchronized (os)
{
byte[] buffer = new byte[256];
while (true)
{
int bytesRead = is.read(buffer);
if (bytesRead == -1)
break;
os.write(buffer, 0, bytesRead);
}
}
}
}
public static File findFileName(String str) throws Exception
{
File file = null;
boolean go = true;
int i = 1;
while (go)
{
String newName = str + "_" + Integer.toString(i);
File f = new File(newName);
if (f.exists())
i++;
else
{
file = f;
go = false;
}
}
return file;
}
/**
*
* @param filename
* @param extension with the preceeding ".", like ".ptrn"
* @return
*/
public static String makeSureExtensionIsOK(String filename, String extension)
{
if (!filename.toLowerCase().endsWith(extension))
filename += extension;
return filename;
}
public static String makeSureExtensionIsOK(String filename, String[] extension, String defaultExtension)
{
boolean extensionExists = false;
for (int i=0; i<extension.length; i++)
{
if (filename.toLowerCase().endsWith(extension[i].toLowerCase()))
{
extensionExists = true;
break;
}
}
if (!extensionExists)
filename += defaultExtension;
return filename;
}
public static String getMacAddress() throws IOException
{
String macAddress = null;
if (System.getProperty("os.name").indexOf("Windows") > -1)
{
String command = "ipconfig /all";
Process pid = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(pid.getInputStream()));
while (true)
{
String line = in.readLine();
if (line == null)
break;
Pattern p = Pattern.compile(".*Physical Address.*: (.*)");
Matcher m = p.matcher(line);
if (m.matches())
{
macAddress = m.group(1);
break;
}
}
in.close();
}
else
macAddress = "Unknown";
return macAddress;
}
//@SuppressWarnings("unchecked")
public static void addURLToClassPath(URL url)
{
try
{
URLClassLoader urlClassLoader = (URLClassLoader) Thread.currentThread().getContextClassLoader();
Class<?> c = /*(Class<URLClassLoader>)*/Class.forName("java.net.URLClassLoader");
Class<?>[] parameterTypes = new Class<?>[1];
parameterTypes[0] = /*(Class<?>)*/Class.forName("java.net.URL");
Method m = c.getDeclaredMethod("addURL", parameterTypes);
m.setAccessible(true);
Object[] args = new Object[1];
args[0] = url;
m.invoke(urlClassLoader, args);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public static void openInBrowser(String page) throws Exception
{
URI uri = new URI(page);
try
{
// System.out.println("Opening in browser:[" + uri.toString() + "]");
Desktop.getDesktop().browse(uri);
}
catch (Exception ex) // UnsupportedOperationException ex)
{
String mess = ex.getMessage();
mess += ("\n\nUnsupported operation on your system. URL [" + uri.toString() + "] is in the clipboard.\nOpen your browser manually, and paste it in there (Ctrl+V).");
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
String path = uri.toString();
try
{
File f = new File(page);
if (f.exists())
{
path = f.getAbsolutePath();
if (File.separatorChar != '/')
path = path.replace(File.separatorChar, '/');
if (!path.startsWith("/"))
path = "/" + path;
path = "file:" + path;
}
}
catch (Exception ex2)
{
ex2.printStackTrace();
}
StringSelection stringSelection = new StringSelection(path);
clipboard.setContents(stringSelection, null);
JOptionPane.showMessageDialog(null, mess, "Showing in Browser", JOptionPane.ERROR_MESSAGE);
}
// String os = System.getProperty("os.name");
// if (os.indexOf("Windows") > -1)
// {
// String cmd = "";
// if (page.indexOf(" ") != -1)
// cmd = "cmd /k start \"" + page + "\"";
// else
// cmd = "cmd /k start " + page + "";
// System.out.println("Command:" + cmd);
// Runtime.getRuntime().exec(cmd); // Can contain blanks...
// }
// else if (os.indexOf("Linux") > -1) // Assuming htmlview
// Runtime.getRuntime().exec("htmlview " + page);
// else
// {
// throw new RuntimeException("OS [" + os + "] not supported yet");
// }
}
public static void showFileSystem(String where) throws Exception
{
String os = System.getProperty("os.name");
if (os.indexOf("Windows") > -1)
{
String cmd = "cmd /k start /D\"" + where + "\" .";
// System.out.println("Executing [" + cmd + "]");
Runtime.getRuntime().exec(cmd); // Can contain blanks, need quotes around it...
}
else if (os.indexOf("Linux") > -1)
Runtime.getRuntime().exec("nautilus " + where);
else if (os.indexOf("Mac") > -1)
{
String[] applScriptCmd =
{
"osascript",
"-e", "tell application \"Finder\"",
"-e", "activate",
"-e", "<open cmd>", // open cmd: index 6
"-e", "end tell"
};
String pattern = File.separator;
if (pattern.equals("\\"))
pattern = "\\\\";
String[] pathElem = where.split(pattern);
String cmd = "open ";
for (int i=pathElem.length - 1; i>0; i--)
cmd += ("folder \"" + pathElem[i] + "\" of ");
cmd += "startup disk";
applScriptCmd[6] = cmd;
Runtime.getRuntime().exec(applScriptCmd);
}
else
{
throw new RuntimeException("showFileSystem method on OS [" + os + "] not implemented yet.\nFor now, you should open [" + where +"] by yourself.");
}
}
public static void main(String[] args) throws Exception
{
// System.setProperty("os.name", "Mac OS X");
// showFileSystem(System.getProperty("user.dir"));
long elapsed = 123456L; // 231234567890L;
System.out.println("Readable time (" + elapsed + ") : " + readableTime(elapsed));
}
public static int sign(double d)
{
int s = 0;
if (d > 0.0D)
s = 1;
if (d < 0.0D)
s = -1;
return s;
}
public static void makeSureTempExists() throws IOException
{
File dir = new File("temp");
if (!dir.exists())
dir.mkdirs();
}
/**
* remove leading and trailing blanks, CR, NL
* @param str
* @return
*/
public static String superTrim(String str)
{
String str2 = "";
char[] strChar = str.toCharArray();
// Leading
int i = 0;
while (strChar[i] == ' ' ||
strChar[i] == '\n' ||
strChar[i] == '\r')
{
i++;
}
str2 = str.substring(i);
while(str2.endsWith("\n") || str2.endsWith("\r"))
str2 = str2.substring(0, str2.length() - 2);
return str2.trim();
}
public static String replaceString(String orig, String oldStr, String newStr)
{
String ret = orig;
int indx = 0;
for (boolean go = true; go;)
{
indx = ret.indexOf(oldStr, indx);
if (indx < 0)
{
go = false;
}
else
{
ret = ret.substring(0, indx) + newStr + ret.substring(indx + oldStr.length());
indx += 1 + oldStr.length();
}
}
return ret;
}
public static byte[] appendByte(byte c[], byte b)
{
int newLength = c != null ? c.length + 1 : 1;
byte newContent[] = new byte[newLength];
for(int i = 0; i < newLength - 1; i++)
newContent[i] = c[i];
newContent[newLength - 1] = b;
return newContent;
}
public static byte[] appendByteArrays(byte c[], byte b[], int n)
{
int newLength = c != null ? c.length + n : n;
byte newContent[] = new byte[newLength];
if (c != null)
{
for (int i=0; i<c.length; i++)
newContent[i] = c[i];
}
int offset = (c!=null?c.length:0);
for (int i=0; i<n; i++)
newContent[offset + i] = b[i];
return newContent;
}
public static String chooseFile(int mode,
String flt,
String desc,
String title,
String buttonLabel)
{
String fileName = "";
JFileChooser chooser = new JFileChooser();
if (title != null)
chooser.setDialogTitle(title);
if (buttonLabel != null)
chooser.setApproveButtonText(buttonLabel);
if (flt != null)
{
ToolFileFilter filter = new ToolFileFilter(flt,
desc);
chooser.addChoosableFileFilter(filter);
chooser.setFileFilter(filter);
}
chooser.setFileSelectionMode(mode);
// Set current directory
File f = new File(".");
String currPath = f.getAbsolutePath();
f = new File(currPath.substring(0, currPath.lastIndexOf(File.separator)));
chooser.setCurrentDirectory(f);
int retval = chooser.showOpenDialog(null);
switch (retval)
{
case JFileChooser.APPROVE_OPTION:
fileName = chooser.getSelectedFile().toString();
break;
case JFileChooser.CANCEL_OPTION:
break;
case JFileChooser.ERROR_OPTION:
break;
}
return fileName;
}
public static int drawPanelTable(String[][] data, Graphics gr, Point topLeft, int betweenCols, int betweenRows)
{
return drawPanelTable(data, gr, topLeft, betweenCols, betweenRows, null);
}
public final static int LEFT_ALIGNED = 0;
public final static int RIGHT_ALIGNED = 1;
public final static int CENTER_ALIGNED = 2;
public static int drawPanelTable(String[][] data, Graphics gr, Point topLeft, int betweenCols, int betweenRows, int[] colAlignment)
{
return drawPanelTable(data, gr, topLeft, betweenCols, betweenRows, colAlignment, false, null, 0f);
}
public static int drawPanelTable(String[][] data, Graphics gr, Point topLeft, int betweenCols, int betweenRows, int[] colAlignment, boolean paintBackground, Color bgColor, float bgTransparency)
{
return drawPanelTable(data, gr, topLeft, betweenCols, betweenRows, colAlignment, paintBackground, bgColor, null, bgTransparency, 1f);
}
public static int drawPanelTable(String[][] data,
Graphics gr,
Point topLeft,
int betweenCols,
int betweenRows,
int[] colAlignment,
boolean paintBackground,
Color bgLightColor,
Color bgDarkColor,
float bgTransparency,
float textTransparency)
{
int w = 0, h = 0;
Font f = gr.getFont();
int[] maxLength = new int[data[0].length]; // Max length for each column
for (int i=0; i<maxLength.length; i++) // init. All to 0
maxLength[i] = 0;
// Identify the max length for each column
for (int row=0; row<data.length; row++)
{
for (int col=0; col<data[row].length; col++)
{
int strWidth = gr.getFontMetrics(f).stringWidth(data[row][col]);
maxLength[col] = Math.max(maxLength[col], strWidth);
}
}
int x = topLeft.x;
int y = topLeft.y;
w = betweenCols;
for (int i=0; i<maxLength.length; i++)
w += (maxLength[i] + betweenCols);
h = betweenRows + (data.length * (f.getSize() + betweenRows)) + betweenRows;
if (paintBackground) // Glossy
{
boolean glossy = (bgLightColor != null && bgDarkColor != null);
Color c = gr.getColor();
if (glossy)
{
drawGlossyRectangularDisplay((Graphics2D)gr,
new Point(x - betweenCols, y - f.getSize() - betweenRows),
new Point(x - betweenCols + w, y - f.getSize() - betweenRows + h),
bgLightColor,
bgDarkColor,
bgTransparency);
}
else
{
gr.setColor(bgLightColor);
gr.fillRoundRect(x - betweenCols, y - f.getSize() - betweenRows, w, h, 10, 10);
}
gr.setColor(c);
}
((Graphics2D)gr).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, textTransparency));
// Now display
for (int row=0; row<data.length; row++)
{
for (int col=0; col<data[row].length; col++)
{
int _x = x;
for (int c=1; c<=col; c++)
_x += (betweenCols + maxLength[c - 1]);
if (colAlignment != null && colAlignment[col] != LEFT_ALIGNED)
{
int strWidth = gr.getFontMetrics(f).stringWidth(data[row][col]);
switch (colAlignment[col])
{
case RIGHT_ALIGNED:
_x += (maxLength[col] - strWidth);
break;
case CENTER_ALIGNED:
_x += ((maxLength[col] - strWidth) / 2);
break;
default:
break;
}
}
gr.drawString(data[row][col], _x, y);
}
y += (f.getSize() + betweenRows);
}
return y;
}
private static void drawGlossyRectangularDisplay(Graphics2D g2d, Point topLeft, Point bottomRight, Color lightColor, Color darkColor, float transparency)
{
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, transparency));
g2d.setPaint(null);
g2d.setColor(darkColor);
int width = bottomRight.x - topLeft.x;
int height = bottomRight.y - topLeft.y;
g2d.fillRoundRect(topLeft.x , topLeft.y, width, height, 10, 10);
Point gradientOrigin = new Point(topLeft.x + (width) / 2,
topLeft.y);
GradientPaint gradient = new GradientPaint(gradientOrigin.x,
gradientOrigin.y,
lightColor,
gradientOrigin.x,
gradientOrigin.y + (height / 3),
darkColor); // vertical, light on top
g2d.setPaint(gradient);
int offset = 3;
int arcRadius = 5;
g2d.fillRoundRect(topLeft.x + offset, topLeft.y + offset, (width - (2 * offset)), (height - (2 * offset)), 2 * arcRadius, 2 * arcRadius);
}
public static boolean thisClassVerbose(Class c)
{
return (System.getProperty(c.getName() + ".verbose", "false").equals("true") || System.getProperty("all.verbose", "false").equals("true"));
}
public static String readableTime(long elapsed)
{
return readableTime(elapsed, false);
}
public static String readableTime(long elapsed, boolean small)
{
long amount = elapsed;
String str = "";
final long SECOND = 1000L;
final long MINUTE = 60 * SECOND;
final long HOUR = 60 * MINUTE;
final long DAY = 24 * HOUR;
final long WEEK = 7 * DAY;
if (amount >= WEEK)
{
int week = (int)(amount / WEEK);
str += (week + (small?" w ":" week(s) "));
amount -= (week * WEEK);
}
if (amount >= DAY || str.length() > 0)
{
int day = (int)(amount / DAY);
str += (day + (small?" d ":" day(s) "));
amount -= (day * DAY);
}
if (amount >= HOUR || str.length() > 0)
{
int hour = (int)(amount / HOUR);
str += (hour + (small?" h ":" hour(s) "));
amount -= (hour * HOUR);
}
if (amount >= MINUTE || str.length() > 0)
{
int minute = (int)(amount / MINUTE);
str += (minute + (small?" m ":" minute(s) "));
amount -= (minute * MINUTE);
}
// if (amount > SECOND || str.length() > 0)
{
int second = (int)(amount / SECOND);
str += (second + ((amount % 1000) != 0 ? "." + (amount % 1000) : "") + (small?" s ":" second(s) "));
amount -= (second * SECOND);
}
return str;
}
static class ToolFileFilter extends FileFilter
{
private Hashtable<String, FileFilter> filters = null;
private String description = null;
private String fullDescription = null;
private boolean useExtensionsInDescription = true;
public ToolFileFilter()
{
this((String) null, (String) null);
}
public ToolFileFilter(String extension)
{
this(extension, null);
}
public ToolFileFilter(String extension, String description)
{
this(new String[] {extension}, description);
}
public ToolFileFilter(String[] filters)
{
this(filters, null);
}
public ToolFileFilter(String[] filters, String description)
{
this.filters = new Hashtable<String, FileFilter>(filters.length);
for (int i = 0; i < filters.length; i++)
{
// add filters one by one
addExtension(filters[i]);
}
setDescription(description);
}
public boolean accept(File f)
{
if (f != null)
{
if(f.isDirectory())
{
return true;
}
String extension = getExtension(f);
if (extension != null && filters.get(getExtension(f)) != null)
{
return true;
}
}
return false;
}
public String getExtension(File f)
{
if(f != null)
{
String filename = f.getName();
int i = filename.lastIndexOf('.');
if (i>0 && i<filename.length()-1)
{
return filename.substring(i+1).toLowerCase();
}
}
return null;
}
public void addExtension(String extension)
{
if (filters == null)
{
filters = new Hashtable<String, FileFilter>(5);
}
filters.put(extension.toLowerCase(), this);
fullDescription = null;
}
public String getDescription()
{
if(fullDescription == null)
{
if(description == null || isExtensionListInDescription())
{
if(description != null)
{
fullDescription = description;
}
fullDescription += " (";
// build the description from the extension list
Enumeration extensions = filters.keys();
if (extensions != null)
{
fullDescription += "." + (String) extensions.nextElement();
while (extensions.hasMoreElements())
{
fullDescription += ", " + (String) extensions.nextElement();
}
}
fullDescription += ")";
}
else
{
fullDescription = description;
}
}
return fullDescription;
}
public void setDescription(String description)
{
this.description = description;
fullDescription = null;
}
public void setExtensionListInDescription(boolean b)
{
useExtensionsInDescription = b;
fullDescription = null;
}
public boolean isExtensionListInDescription()
{
return useExtensionsInDescription;
}
}
}
| Java |
package raspisamples;
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;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import raspisamples.pwm.PWMPin;
public class Real4PWMLed
{
public static void main(String[] args)
throws InterruptedException
{
final GpioController gpio = GpioFactory.getInstance();
final PWMPin pin00 = new PWMPin(RaspiPin.GPIO_00, "LED-One", PinState.HIGH);
final PWMPin pin01 = new PWMPin(RaspiPin.GPIO_01, "LED-Two", PinState.HIGH);
final PWMPin pin02 = new PWMPin(RaspiPin.GPIO_02, "LED-Three", PinState.HIGH);
final PWMPin pin03 = new PWMPin(RaspiPin.GPIO_03, "LED-Four", PinState.HIGH);
System.out.println("Ready...");
Thread.sleep(1000);
pin00.emitPWM(0);
pin01.emitPWM(0);
pin02.emitPWM(0);
pin03.emitPWM(0);
final Thread mainThread = Thread.currentThread();
final Thread monitor = new Thread()
{
public void run()
{
int nbNotification = 0;
boolean keepWaiting = true;
while (keepWaiting)
{
synchronized (this)
{
try
{
System.out.println("Monitor waiting.");
wait();
nbNotification++;
System.out.println("Received " + nbNotification + " notification(s)...");
if (nbNotification == 4)
{
synchronized (mainThread)
{
mainThread.notify();
}
keepWaiting = false;
}
}
catch (InterruptedException ie) { ie.printStackTrace(); }
}
}
System.out.println("Monitor exiting.");
}
};
monitor.start();
Thread one = new Thread()
{
public void run()
{
for (int vol=0; vol<100; vol++)
{
pin00.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin00.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
synchronized(monitor)
{
System.out.println("Thread One finishing");
monitor.notify();
}
}
};
Thread two = new Thread()
{
public void run()
{
for (int vol=100; vol>0; vol--)
{
pin01.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
for (int vol=0; vol<=100; vol++)
{
pin01.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
try { Thread.sleep(100); } catch (Exception ex) {}
synchronized(monitor)
{
System.out.println("Thread Two finishing");
monitor.notify();
}
}
};
Thread three = new Thread()
{
public void run()
{
for (int vol=0; vol<100; vol++)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=0; vol<100; vol++)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
try { Thread.sleep(200); } catch (Exception ex) {}
synchronized(monitor)
{
System.out.println("Thread Three finishing");
monitor.notify();
}
}
};
Thread four = new Thread()
{
public void run()
{
for (int vol=100; vol>0; vol--)
{
pin03.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=0; vol<=100; vol++)
{
pin03.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=100; vol>0; vol--)
{
pin03.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=0; vol<=100; vol++)
{
pin03.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
try { Thread.sleep(300); } catch (Exception ex) {}
synchronized(monitor)
{
System.out.println("Thread Four finishing");
monitor.notify();
}
}
};
one.start();
two.start();
three.start();
four.start();
synchronized (mainThread) { mainThread.wait(); }
System.out.println("Everyone's done, finishing.");
// try { Thread.sleep(5000L); } catch (Exception ex) {}
pin00.stopPWM();
pin01.stopPWM();
pin02.stopPWM();
pin03.stopPWM();
Thread.sleep(1000);
// Last blink
System.out.println("Bye-bye");
pin00.low();
Thread.sleep(500);
pin00.high();
Thread.sleep(500);
pin00.low();
gpio.shutdown();
}
}
| Java |
package raspisamples.wp;
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;
import com.pi4j.wiringpi.SoftPwm;
import com.pi4j.wiringpi.Gpio;
/*
* PWM with WiringPi
*/
public class WiringPiSoftPWM3ColorLed
{
public static void main(String[] args)
throws InterruptedException
{
// initialize wiringPi library
Gpio.wiringPiSetup();
int pinAddress_00 = RaspiPin.GPIO_00.getAddress();
int pinAddress_01 = RaspiPin.GPIO_01.getAddress();
int pinAddress_02 = RaspiPin.GPIO_02.getAddress();
// create soft-pwm pins (min=0 ; max=100)
SoftPwm.softPwmCreate(pinAddress_00, 0, 100);
SoftPwm.softPwmCreate(pinAddress_01, 0, 100);
SoftPwm.softPwmCreate(pinAddress_02, 0, 100);
// continuous loop
// while (true)
{
System.out.println("One");
// fade LED to fully ON
for (int i = 0; i <= 100; i++)
{
SoftPwm.softPwmWrite(pinAddress_00, i);
Thread.sleep(5);
}
System.out.println("Two");
// fade LED to fully OFF
for (int i = 100; i >= 0; i--)
{
SoftPwm.softPwmWrite(pinAddress_00, i);
Thread.sleep(5);
}
System.out.println("Three");
// fade LED to fully ON
for (int i = 0; i <= 100; i++)
{
SoftPwm.softPwmWrite(pinAddress_01, i);
Thread.sleep(5);
}
System.out.println("Four");
// fade LED to fully OFF
for (int i = 100; i >= 0; i--)
{
SoftPwm.softPwmWrite(pinAddress_01, i);
Thread.sleep(5);
}
System.out.println("Five");
// fade LED to fully ON
for (int i = 0; i <= 100; i++)
{
SoftPwm.softPwmWrite(pinAddress_02, i);
Thread.sleep(5);
}
System.out.println("Six");
// fade LED to fully OFF
for (int i = 100; i >= 0; i--)
{
SoftPwm.softPwmWrite(pinAddress_02, i);
Thread.sleep(5);
}
}
System.out.println("Seven");
// All spectrum
for (int a = 0; a <= 100; a++)
{
SoftPwm.softPwmWrite(pinAddress_00, a);
// Thread.sleep(5);
for (int b = 0; b <= 100; b++)
{
SoftPwm.softPwmWrite(pinAddress_01, b);
// Thread.sleep(5);
for (int c = 0; c <= 100; c++)
{
SoftPwm.softPwmWrite(pinAddress_02, c);
Thread.sleep(1);
}
for (int c = 100; c >= 0; c--)
{
SoftPwm.softPwmWrite(pinAddress_02, c);
Thread.sleep(1);
}
}
for (int b = 100; b >= 0; b--)
{
SoftPwm.softPwmWrite(pinAddress_01, b);
// Thread.sleep(5);
for (int c = 0; c <= 100; c++)
{
SoftPwm.softPwmWrite(pinAddress_02, c);
Thread.sleep(1);
}
for (int c = 100; c >= 0; c--)
{
SoftPwm.softPwmWrite(pinAddress_02, c);
Thread.sleep(1);
}
}
}
System.out.println("Eight");
for (int a = 100; a >= 0; a--)
{
SoftPwm.softPwmWrite(pinAddress_00, a);
// Thread.sleep(5);
for (int b = 0; b <= 100; b++)
{
SoftPwm.softPwmWrite(pinAddress_01, b);
// Thread.sleep(5);
for (int c = 0; c <= 100; c++)
{
SoftPwm.softPwmWrite(pinAddress_02, c);
Thread.sleep(1);
}
for (int c = 100; c >= 0; c--)
{
SoftPwm.softPwmWrite(pinAddress_02, c);
Thread.sleep(1);
}
}
for (int b = 100; b >= 0; b--)
{
SoftPwm.softPwmWrite(pinAddress_01, b);
// Thread.sleep(5);
for (int c = 0; c <= 100; c++)
{
SoftPwm.softPwmWrite(pinAddress_02, c);
Thread.sleep(1);
}
for (int c = 100; c >= 0; c--)
{
SoftPwm.softPwmWrite(pinAddress_02, c);
Thread.sleep(1);
}
}
}
System.out.println("Done");
}
}
| Java |
package raspisamples.wp;
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;
import com.pi4j.wiringpi.SoftPwm;
/*
* PWM with WiringPi
*/
public class WiringPiSoftPWMExample
{
public static void main(String[] args)
throws InterruptedException
{
// initialize wiringPi library
com.pi4j.wiringpi.Gpio.wiringPiSetup();
int pinAddress = RaspiPin.GPIO_01.getAddress();
// create soft-pwm pins (min=0 ; max=100)
// SoftPwm.softPwmCreate(1, 0, 100);
SoftPwm.softPwmCreate(pinAddress, 0, 100);
// continuous loop
boolean go = true;
for (int idx=0; idx<5; idx++)
{
// fade LED to fully ON
for (int i = 0; i <= 100; i++)
{
SoftPwm.softPwmWrite(1, i);
Thread.sleep(10);
}
// fade LED to fully OFF
for (int i = 100; i >= 0; i--)
{
SoftPwm.softPwmWrite(1, i);
Thread.sleep(10);
}
}
}
}
| Java |
package raspisamples.servo;
import adafruiti2c.servo.AdafruitPCA9685;
/*
* Standard, using I2C and the PCA9685 servo board
*/
public class StandardServo
{
public static void waitfor(long howMuch)
{
try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); }
}
private int servo = -1;
private final static int DEFAULT_SERVO_MIN = 122; // Value for Min position (-90, unit is [0..1023])
private final static int DEFAULT_SERVO_MAX = 615; // Value for Max position (+90, unit is [0..1023])
private int servoMin = DEFAULT_SERVO_MIN;
private int servoMax = DEFAULT_SERVO_MAX;
private int diff = servoMax - servoMin;
private AdafruitPCA9685 servoBoard = new AdafruitPCA9685();
public StandardServo(int channel)
{
this(channel, DEFAULT_SERVO_MIN, DEFAULT_SERVO_MAX);
}
public StandardServo(int channel, int servoMin, int servoMax)
{
this.servoMin = servoMin;
this.servoMax = servoMax;
this.diff = servoMax - servoMin;
int freq = 60;
servoBoard.setPWMFreq(freq); // Set frequency in Hz
this.servo = channel;
System.out.println("Channel " + channel + " all set. Min:" + servoMin + ", Max:" + servoMax + ", diff:" + diff);
}
public void setAngle(float f)
{
int pwm = degreeToPWM(servoMin, servoMax, f);
// System.out.println(f + " degrees (" + pwm + ")");
servoBoard.setPWM(servo, 0, pwm);
}
public void setPWM(int pwm)
{
servoBoard.setPWM(servo, 0, pwm);
}
public void stop() // Set to 0
{
servoBoard.setPWM(servo, 0, 0);
}
/*
* 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));
}
/**
* To test the servo - namely, the min & max values.
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception
{
int channel = 14;
if (args.length > 0)
{
try
{
channel = Integer.parseInt(args[0]);
}
catch (Exception e)
{
throw e;
}
}
System.out.println("Servo Channel " + channel);
StandardServo ss = new StandardServo(channel);
try
{
ss.stop();
waitfor(2000);
System.out.println("Let's go, 1 by 1 (" + ss.servoMin + " to " + ss.servoMax + ")");
for (int i=ss.servoMin; i<=ss.servoMax; i++)
{
System.out.println("i=" + i + ", " + (-90f + (((float)(i - ss.servoMin) / (float)ss.diff) * 180f)));
ss.setPWM(i);
waitfor(10);
}
for (int i=ss.servoMax; i>=ss.servoMin; i--)
{
System.out.println("i=" + i + ", " + (-90f + (((float)(i - ss.servoMin) / (float)ss.diff) * 180f)));
ss.setPWM(i);
waitfor(10);
}
ss.stop();
waitfor(2000);
System.out.println("Let's go, 1 deg by 1 deg");
for (int i=ss.servoMin; i<=ss.servoMax; i+=(ss.diff / 180))
{
System.out.println("i=" + i + ", " + Math.round(-90f + (((float)(i - ss.servoMin) / (float)ss.diff) * 180f)));
ss.setPWM(i);
waitfor(10);
}
for (int i=ss.servoMax; i>=ss.servoMin; i-=(ss.diff / 180))
{
System.out.println("i=" + i + ", " + Math.round(-90f + (((float)(i - ss.servoMin) / (float)ss.diff) * 180f)));
ss.setPWM(i);
waitfor(10);
}
ss.stop();
waitfor(2000);
float[] degValues = { -10, 0, -90, 45, -30, 90, 10, 20, 30, 40, 50, 60, 70, 80, 90, 0 };
for (float f : degValues)
{
System.out.println("In degrees:" + f);
ss.setAngle(f);
waitfor(1500);
}
}
finally
{
ss.stop();
}
System.out.println("Done.");
}
}
| Java |
package raspisamples.log.net;
import adafruiti2c.sensor.AdafruitBMP180;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONObject;
import raspisamples.util.HTTPClient;
public class BMP180Logging
{
private final static String LOGGER_URL = "http://donpedro.lediouris.net/php/raspi/insert.php"; // ?board=OlivRPi1&sensor=BMP180&type=TEMPERATURE&data=24
private final static String SENSOR_ID = "BMP180";
private final static String TEMPERATURE = "TEMPERATURE";
private final static String PRESSURE = "PRESSURE";
private static String boardID = "OlivRPi1";
private static long waitTime = 10000L;
private static String sessionID = "XX";
static
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sessionID = sdf.format(new Date());
}
private final static String BOARD_PRM = "-board";
private final static String WAIT_PRM = "-wait";
private final static String SESS_PRM = "-sess";
private final static String HELP_PRM = "-help";
protected static void waitfor(long howMuch)
{
try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); }
}
private static void processPrm(String[] args)
{
for (int i=0; i<args.length; i++)
{
if (BOARD_PRM.equals(args[i]))
boardID = args[i + 1];
else if (WAIT_PRM.equals(args[i]))
{
try
{
waitTime = 1000L * Integer.parseInt(args[i + 1]);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (SESS_PRM.equals(args[i]))
sessionID = args[i + 1];
else if (HELP_PRM.equals(args[i]))
{
System.out.println("Usage is:");
System.out.println(" java raspisamples.log.net.BMP180Logging -board <BoardID> -sess <Session ID> -wait <time-in-sec> -help ");
System.out.println(" <BoardID> is your board ID (default is OlivRPi1)");
System.out.println(" <Session ID> identifies your logging session (default current date YYYY-MM-DD)");
System.out.println(" <time-in-sec> is the amount of seconds between logs (default is 10)");
System.out.println();
System.out.println("Logging data for board [" + boardID + "]");
System.out.println("Logging data every " + Long.toString(waitTime / 1000) + " s. Session ID:" + sessionID);
System.exit(0);
}
}
}
public static void main(String[] args)
{
processPrm(args);
System.out.println("Logging data for [" + boardID + "], every " + Long.toString(waitTime / 1000) + " s.");
final NumberFormat NF = new DecimalFormat("##00.00");
AdafruitBMP180 sensor = new AdafruitBMP180();
float press = 0;
float temp = 0;
double alt = 0;
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
System.out.println("\nBye now.");
}
});
while (true)
{
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("At " + new Date().toString());
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");
// Log here
try
{
String url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + SENSOR_ID + "&type=" + TEMPERATURE + "&data=" + NF.format(temp);
String response = HTTPClient.getContent(url);
JSONObject json = new JSONObject(response);
System.out.println("Returned\n" + json.toString(2));
try { Thread.sleep(1000); } catch (Exception ex) { ex.printStackTrace(); } // To avoid duplicate PK
url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + SENSOR_ID + "&type=" + PRESSURE + "&data=" + NF.format(press / 100);
response = HTTPClient.getContent(url);
json = new JSONObject(response);
System.out.println("Returned\n" + json.toString(2));
}
catch (Exception ex)
{
ex.printStackTrace();
}
waitfor(waitTime);
}
}
}
| Java |
package raspisamples.log.net;
import adafruiti2c.sensor.AdafruitBMP180;
import adafruiti2c.sensor.AdafruitHTU21DF;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONObject;
import raspisamples.util.HTTPClient;
/**
* Log weather data in a file
*/
public class WeatherDataFileLogging
{
private static long waitTime = 10000L;
private final static String WAIT_PRM = "-wait";
private final static String FILE_PRM = "-file";
private final static String HELP_PRM = "-help";
private final static String NO_BMP180 = "-nobmp180";
private final static String NO_HTU21DF = "-nohtu21df";
private static String logFileName = "weather.data.log";
private static boolean withBMP180 = true;
private static boolean withHTU21DF = true;
protected static void waitfor(long howMuch)
{
try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); }
}
private static void processPrm(String[] args)
{
for (int i=0; i<args.length; i++)
{
if (FILE_PRM.equals(args[i]))
logFileName = args[i + 1];
else if (WAIT_PRM.equals(args[i]))
{
try
{
waitTime = 1000L * Integer.parseInt(args[i + 1]);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (NO_BMP180.equals(args[i]))
withBMP180 = false;
else if (NO_HTU21DF.equals(args[i]))
withHTU21DF = false;
else if (HELP_PRM.equals(args[i]))
{
System.out.println("Usage is:");
System.out.println(" java raspisamples.log.net.WeatherDataFileLogging -file <LogFileName> -wait <time-in-sec> [ -nobmp180 ][ -nohtu21df ] -help ");
System.out.println(" <LogFileName> is your log file name (default is weather.data.log)");
System.out.println(" <time-in-sec> is the amount of seconds between logs (default is 10)");
System.out.println();
System.out.println("Logging data in [" + logFileName + "]");
System.out.println("Logging data every " + Long.toString(waitTime / 1000) + " s");
System.exit(0);
}
}
}
public static void main(String[] args) throws Exception
{
processPrm(args);
System.out.println("Logging data in [" + logFileName + "], every " + Long.toString(waitTime / 1000) + " s.");
final BufferedWriter log = new BufferedWriter(new FileWriter(logFileName));
final NumberFormat NF = new DecimalFormat("##00.00");
AdafruitBMP180 bmpSensor = null;
if (withBMP180)
{
try { bmpSensor = new AdafruitBMP180(); }
catch (Exception ex ) { ex.printStackTrace(); }
}
float press = 0;
float temp = 0;
AdafruitHTU21DF humSensor = null;
if (withHTU21DF)
{
try { humSensor = new AdafruitHTU21DF(); }
catch (Exception ex ) { ex.printStackTrace(); }
}
float hum = 0;
if (humSensor != null)
{
try
{
if (!humSensor.begin())
{
System.out.println("Sensor not found!");
System.exit(1);
}
}
catch (Exception ex)
{
ex.printStackTrace();
System.exit(1);
}
}
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
System.out.println("\nBye now.");
// Close log file
if (log != null)
{
try
{
log.flush();
log.close();
} catch (Exception ex) { ex.printStackTrace(); }
}
}
});
while (true)
{
if (bmpSensor != null)
{
try { press = bmpSensor.readPressure(); }
catch (Exception ex)
{
System.err.println(ex.getMessage());
ex.printStackTrace();
}
try { temp = bmpSensor.readTemperature(); }
catch (Exception ex)
{
System.err.println(ex.getMessage());
ex.printStackTrace();
}
}
if (humSensor != null)
{
try { hum = humSensor.readHumidity(); }
catch (Exception ex)
{
System.err.println(ex.getMessage());
ex.printStackTrace();
}
}
long now = System.currentTimeMillis();
// System.out.println("At " + new Date().toString());
System.out.println("Temperature: " + NF.format(temp) + " C");
System.out.println("Pressure : " + NF.format(press / 100) + " hPa");
System.out.println("Humidity : " + NF.format(hum) + " %");
// Log here
try
{
JSONObject dataObject = new JSONObject(); // + NF.format(temp);
dataObject.put("epoch", now);
dataObject.put("pressure", press/100);
dataObject.put("temperature", temp);
dataObject.put("humidity", hum);
String logStr = dataObject.toString();
log.write(logStr + "\n");
log.flush();
}
catch (Exception ex)
{
ex.printStackTrace();
}
waitfor(waitTime);
}
}
}
| Java |
package raspisamples.log.net;
import adafruiti2c.sensor.AdafruitBMP180;
import adafruiti2c.sensor.AdafruitHTU21DF;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.json.JSONObject;
import raspisamples.util.HTTPClient;
/**
* Log weather data with php/MySQL over the net
*/
public class WeatherDataLogging
{
private final static String LOGGER_URL = "http://donpedro.lediouris.net/php/raspi/insert.php"; // ?board=OlivRPi1&sensor=BMP180&type=TEMPERATURE&data=24
private final static String BMP_SENSOR_ID = "BMP180";
private final static String HUM_SENSOR_ID = "HTU21D-F";
private final static String TEMPERATURE = "TEMPERATURE";
private final static String PRESSURE = "PRESSURE";
private final static String HUMIDITY = "HUMIDITY";
private static String boardID = "OlivRPi1";
private static long waitTime = 10000L;
private static String sessionID = "XX";
static
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
sessionID = sdf.format(new Date());
}
private final static String BOARD_PRM = "-board";
private final static String WAIT_PRM = "-wait";
private final static String SESS_PRM = "-sess";
private final static String HELP_PRM = "-help";
protected static void waitfor(long howMuch)
{
try { Thread.sleep(howMuch); } catch (InterruptedException ie) { ie.printStackTrace(); }
}
private static void processPrm(String[] args)
{
for (int i=0; i<args.length; i++)
{
if (BOARD_PRM.equals(args[i]))
boardID = args[i + 1];
else if (WAIT_PRM.equals(args[i]))
{
try
{
waitTime = 1000L * Integer.parseInt(args[i + 1]);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
else if (SESS_PRM.equals(args[i]))
sessionID = args[i + 1];
else if (HELP_PRM.equals(args[i]))
{
System.out.println("Usage is:");
System.out.println(" java raspisamples.log.net.WeatherDataLogging -board <BoardID> -sess <Session ID> -wait <time-in-sec> -help ");
System.out.println(" <BoardID> is your board ID (default is OlivRPi1)");
System.out.println(" <Session ID> identifies your logging session (default current date YYYY-MM-DD)");
System.out.println(" <time-in-sec> is the amount of seconds between logs (default is 10)");
System.out.println();
System.out.println("Logging data for board [" + boardID + "]");
System.out.println("Logging data every " + Long.toString(waitTime / 1000) + " s. Session ID:" + sessionID);
System.exit(0);
}
}
}
public static void main(String[] args)
{
processPrm(args);
System.out.println("Logging data for [" + boardID + "], every " + Long.toString(waitTime / 1000) + " s.");
final NumberFormat NF = new DecimalFormat("##00.00");
AdafruitBMP180 bmpSensor = new AdafruitBMP180();
float press = 0;
float temp = 0;
double alt = 0;
AdafruitHTU21DF humSensor = new AdafruitHTU21DF();
float hum = 0;
try
{
if (!humSensor.begin())
{
System.out.println("Sensor not found!");
System.exit(1);
}
}
catch (Exception ex)
{
ex.printStackTrace();
System.exit(1);
}
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
System.out.println("\nBye now.");
}
});
while (true)
{
try { press = bmpSensor.readPressure(); }
catch (Exception ex)
{
System.err.println(ex.getMessage());
ex.printStackTrace();
}
bmpSensor.setStandardSeaLevelPressure((int)press); // As we ARE at the sea level (in San Francisco).
try { alt = bmpSensor.readAltitude(); }
catch (Exception ex)
{
System.err.println(ex.getMessage());
ex.printStackTrace();
}
try { temp = bmpSensor.readTemperature(); }
catch (Exception ex)
{
System.err.println(ex.getMessage());
ex.printStackTrace();
}
try { hum = humSensor.readHumidity(); }
catch (Exception ex)
{
System.err.println(ex.getMessage());
ex.printStackTrace();
}
System.out.println("At " + new Date().toString());
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");
System.out.println("Humidity : " + NF.format(hum) + " %");
// Log here
try
{
String url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + BMP_SENSOR_ID + "&type=" + TEMPERATURE + "&data=" + NF.format(temp);
String response = HTTPClient.getContent(url);
JSONObject json = new JSONObject(response);
System.out.println("Returned\n" + json.toString(2));
try { Thread.sleep(1000); } catch (Exception ex) { ex.printStackTrace(); } // To avoid duplicate PK
url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + BMP_SENSOR_ID + "&type=" + PRESSURE + "&data=" + NF.format(press / 100);
response = HTTPClient.getContent(url);
json = new JSONObject(response);
System.out.println("Returned\n" + json.toString(2));
try { Thread.sleep(1000); } catch (Exception ex) { ex.printStackTrace(); } // To avoid duplicate PK
url = LOGGER_URL + "?board=" + boardID + "&session=" + sessionID + "&sensor=" + HUM_SENSOR_ID + "&type=" + HUMIDITY + "&data=" + NF.format(hum);
response = HTTPClient.getContent(url);
json = new JSONObject(response);
System.out.println("Returned\n" + json.toString(2));
}
catch (Exception ex)
{
ex.printStackTrace();
}
waitfor(waitTime);
}
}
}
| Java |
package raspisamples;
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;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import raspisamples.pwm.PWMPin;
public class RealPWMLed
{
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)
throws InterruptedException
{
final GpioController gpio = GpioFactory.getInstance();
PWMPin pin = new PWMPin(RaspiPin.GPIO_01, "OneLED", PinState.LOW);
pin.low(); // Useless
System.out.println("PWM, glowing up and down");
// PWM
pin.emitPWM(0);
Thread.sleep(1000);
for (int vol=0; vol<100; vol++)
{
pin.adjustPWMVolume(vol);
Thread.sleep(10);
}
for (int vol=100; vol>=0; vol--)
{
pin.adjustPWMVolume(vol);
Thread.sleep(10);
}
System.out.println("Enter \"S\" or \"quit\" to stop, or a volume [0..100]");
boolean go = true;
while (go)
{
String userInput = userInput("Volume > ");
if ("S".equalsIgnoreCase(userInput) ||
"quit".equalsIgnoreCase(userInput))
go = false;
else
{
try
{
int vol = Integer.parseInt(userInput);
pin.adjustPWMVolume(vol);
}
catch (NumberFormatException nfe)
{
System.out.println(nfe.toString());
}
}
}
pin.stopPWM();
Thread.sleep(1000);
// Last blink
System.out.println("Bye-bye");
pin.low();
Thread.sleep(500);
pin.high();
Thread.sleep(500);
pin.low();
gpio.shutdown();
}
private static void waitFor(long ms)
{
try
{
Thread.sleep(ms);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
| Java |
package raspisamples;
import raspisamples.adc.JoyStick;
import raspisamples.adc.JoyStickClient;
import raspisamples.servo.StandardServo;
/*
* Joystick read with ADC (MCP3008)
* 2 Servos (UP/LR)
*/
public class JoyStickAndServos
{
private static StandardServo ss1 = null, ss2 = null;
private static JoyStick joyStick = null;
public static void main(String[] args)
{
ss1 = new StandardServo(13); // 13 : Address on the board (1..15)
ss2 = new StandardServo(15); // 15 : Address on the board (1..15)
ss1.stop();
ss2.stop();
JoyStickClient jsc = new JoyStickClient()
{
@Override
public void setUD(int v) // 0..100
{
float angle = (float)(v - 50) * (9f / 5f);
ss1.setAngle(angle); // -90..+90
}
@Override
public void setLR(int v) // 0..100
{
float angle = (float)(v - 50) * (9f / 5f);
ss2.setAngle(angle); // -90..+90
}
};
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
ss1.stop();
ss2.stop();
System.out.println("\nBye (Ctrl+C)");
}
});
try
{
joyStick = new JoyStick(jsc);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
ss1.stop();
ss2.stop();
System.out.println("Bye");
}
}
}
| Java |
package raspisamples;
import java.io.InputStream;
import java.net.URI;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;
import org.json.JSONObject;
import raspisamples.servo.StandardServo;
/*
* Driven by WerbSocket server
* See in node/server.js
*
* 2 Servos (UP/LR)
*/
public class PanTiltWebSocket
{
private static StandardServo ssUD = null,
ssLR = null;
private static WebSocketClient webSocketClient = null;
public static void main(String[] args) throws Exception
{
ssUD = new StandardServo(14); // 14 : Address on the board (1..15)
ssLR = new StandardServo(15); // 15 : Address on the board (1..15)
// Init/Reset
ssUD.stop();
ssLR.stop();
ssUD.setAngle(0f);
ssLR.setAngle(0f);
Runtime.getRuntime().addShutdownHook(new Thread()
{
public void run()
{
close();
}
});
StandardServo.waitfor(2000);
String wsUri = System.getProperty("ws.uri", "ws://localhost:9876/");
initWebSocketConnection(wsUri);
}
private static void initWebSocketConnection(String serverURI)
{
try
{
webSocketClient = new WebSocketClient(new URI(serverURI))
{
@Override
public void onOpen(ServerHandshake serverHandshake)
{
System.out.println("WS On Open");
}
@Override
public void onMessage(String string)
{
// System.out.println("WS On Message:" + string);
JSONObject message = new JSONObject(string);
JSONObject leapmotion = new JSONObject(message.getJSONObject("data").getString("text"));
int roll = leapmotion.getInt("roll");
int pitch = leapmotion.getInt("pitch");
int yaw = leapmotion.getInt("yaw");
System.out.println("Roll:" + roll + ", pitch:" + pitch + ", yaw:" + yaw);
ssLR.setAngle(yaw);
ssUD.setAngle(-roll); // Actually pitch...
}
@Override
public void onClose(int i, String string, boolean b)
{
System.out.println("WS On Close");
}
@Override
public void onError(Exception exception)
{
System.out.println("WS On Error");
exception.printStackTrace();
}
};
webSocketClient.connect();
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
public static void close()
{
System.out.println("\nExiting...");
webSocketClient.close();
// Reset to 0,0 before shutting down.
ssUD.setAngle(0f);
ssLR.setAngle(0f);
StandardServo.waitfor(2000);
ssUD.stop();
ssLR.stop();
System.out.println("Bye");
}
}
| Java |
package raspisamples;
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;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import raspisamples.pwm.PWMPin;
public class Real4PWMLedV2
{
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)
throws InterruptedException
{
final GpioController gpio = GpioFactory.getInstance();
final PWMPin pin00 = new PWMPin(RaspiPin.GPIO_00, "LED-One", PinState.HIGH);
final PWMPin pin01 = new PWMPin(RaspiPin.GPIO_01, "LED-Two", PinState.HIGH);
final PWMPin pin02 = new PWMPin(RaspiPin.GPIO_02, "LED-Three", PinState.HIGH);
final PWMPin pin03 = new PWMPin(RaspiPin.GPIO_03, "LED-Four", PinState.HIGH);
System.out.println("Ready...");
Thread.sleep(1000);
pin00.emitPWM(0);
pin01.emitPWM(0);
pin02.emitPWM(0);
pin03.emitPWM(0);
boolean go = true;
while (go)
{
Thread one = new Thread()
{
public void run()
{
for (int vol=0; vol<100; vol++)
{
pin00.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin00.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
System.out.println("Thread One finishing");
}
};
Thread two = new Thread()
{
public void run()
{
for (int vol=100; vol>0; vol--)
{
pin01.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
for (int vol=0; vol<=100; vol++)
{
pin01.adjustPWMVolume(vol);
try { Thread.sleep(10); } catch (Exception ex) {}
}
System.out.println("Thread Two finishing");
}
};
Thread three = new Thread()
{
public void run()
{
for (int vol=0; vol<100; vol++)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=0; vol<100; vol++)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=100; vol>=0; vol--)
{
pin02.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
System.out.println("Thread Three finishing");
}
};
Thread four = new Thread()
{
public void run()
{
for (int vol=100; vol>0; vol--)
{
pin03.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=0; vol<=100; vol++)
{
pin03.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=100; vol>0; vol--)
{
pin03.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
for (int vol=0; vol<=100; vol++)
{
pin03.adjustPWMVolume(vol);
try { Thread.sleep(5); } catch (Exception ex) {}
}
System.out.println("Thread Four finishing");
}
};
one.start();
two.start();
three.start();
four.start();
String usr = userInput("Again y|n ? > ");
if (!"Y".equalsIgnoreCase(usr))
go = false;
}
pin00.stopPWM();
pin01.stopPWM();
pin02.stopPWM();
pin03.stopPWM();
Thread.sleep(1000);
// Last blink
System.out.println("Bye-bye");
pin00.low();
Thread.sleep(500);
pin00.high();
Thread.sleep(500);
pin00.low();
gpio.shutdown();
}
}
| Java |
package raspisamples.pwm;
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 PWMLedTestOne
{
public static void main(String[] args)
throws InterruptedException
{
System.out.println("GPIO Control - pin 01 ... started.");
// create gpio controller
final GpioController gpio = GpioFactory.getInstance();
// provision gpio pin #01 as an output pin and turn on
final GpioPinDigitalOutput pin = gpio.provisionDigitalOutputPin(RaspiPin.GPIO_01, "OneLED", PinState.HIGH);
System.out.println("--> GPIO state should be: ON");
Thread.sleep(1000);
// turn off gpio pin #01
pin.low();
System.out.println("--> GPIO state should be: OFF");
if (false)
{
Thread.sleep(1000);
// toggle the current state of gpio pin #01 (should turn on)
pin.toggle();
System.out.println("--> GPIO state should be: ON");
Thread.sleep(1000);
// toggle the current state of gpio pin #01 (should turn off)
pin.toggle();
System.out.println("--> GPIO state should be: OFF");
Thread.sleep(2000);
// turn on gpio pin #01 for 1 second and then off
System.out.println("--> GPIO state should be: ON for only 1 second");
pin.pulse(1000, true); // set second argument to 'true' use a blocking call
pin.low();
long before = System.currentTimeMillis();
for (int i=0; i<10000; i++)
{
pin.high();
pin.low();
}
long after = System.currentTimeMillis();
System.out.println("10000 switches took " + Long.toString(after - before) + " ms.");
}
System.out.println("PWM!!!");
// PWM
int threshold = 25;
int nbLoop = 5;
for (int pwmValueOn=1; pwmValueOn<threshold; pwmValueOn++)
{
System.out.println("PWM " + pwmValueOn);
for (int i=0; i<nbLoop; i++)
{
pin.pulse(pwmValueOn, true); // set second argument to 'true' use a blocking call
// waitFor(pwmValueOn);
pin.low();
waitFor(threshold - pwmValueOn);
}
// Thread.sleep(500);
}
for (int pwmValueOn=threshold; pwmValueOn>0; pwmValueOn--)
{
System.out.println("PWM " + pwmValueOn);
for (int i=0; i<nbLoop; i++)
{
pin.pulse(pwmValueOn, true); // set second argument to 'true' use a blocking call
// waitFor(pwmValueOn);
pin.low();
waitFor(threshold - pwmValueOn);
}
// Thread.sleep(500);
}
// stop all GPIO activity/threads by shutting down the GPIO controller
// (this method will forcefully shutdown all GPIO monitoring threads and scheduled tasks)
gpio.shutdown();
}
private static void waitFor(long ms)
{
try
{
Thread.sleep(ms);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
}
| Java |
package raspisamples.pwm;
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();
}
}
}
| Java |
package raspisamples.pwm;
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);
}
}
| Java |
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()); }
}
}
}
| Java |
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();
}
}
}
| Java |
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();
}
}
| Java |
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();
}
}
}
| Java |
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(); }
}
}
| Java |
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...");
}
}
| Java |
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();
}
}
}
| Java |
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.");
}
}
| Java |
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;
}
}
| Java |
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;
}
}
}
| Java |
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();
}
}
}
}
| Java |
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.");
}
}
| Java |
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()); }
}
}
}
| Java |
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();
}
}
}
}
| Java |
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();
}
}
| Java |
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();
}
}
| Java |
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);
}
}
}
| Java |
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() {}
}
| Java |
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() {}
}
| Java |
package adafruiti2c.sensor.listener;
import java.util.EventListener;
import ocss.nmea.api.NMEAEvent;
public abstract class AdafruitBMP180Listener implements EventListener
{
public void dataDetected(NMEAEvent e) {}
}
| Java |
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();
}
}
}
| Java |
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();
}
}
}
| Java |
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();
}
}
}
| Java |
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);
}
}
| Java |
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);
}
}
| Java |
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();
}
}
}
| Java |
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);
}
}
| Java |
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));
}
}
| Java |
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) + " %");
}
}
| Java |
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);
}
}
| Java |
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();
}
}
| Java |
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();
}
}
| Java |
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;
}
}
}
| Java |
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);
}
}
| Java |
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();
}
}
| Java |
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);
}
}
| Java |
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.");
}
}
| Java |
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.");
}
}
| Java |
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(""", "\"");
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();
}
}
| Java |
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.");
}
}
| Java |
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.");
}
}
| Java |
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));
}
}
| Java |
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.");
}
}
| Java |
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);
}
}
| Java |
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");
}
}
| Java |
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();
}
}
}
| Java |
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();
}
}
| Java |
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();
}
}
| Java |
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
}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.