HOME PCB
ClientDataCommonHostlibtest.java
// START SNIPPET: serial-snippet


/*
 * #%L
 * **********************************************************************
 * ORGANIZATION  :  Pi4J
 * PROJECT       :  Pi4J :: Java Examples
 * FILENAME      :  SerialExample.java
 *
 * This file is part of the Pi4J project. More information about
 * this project can be found here:  http://www.pi4j.com/
 * **********************************************************************
 * %%
 * Copyright (C) 2012 - 2017 Pi4J
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 *
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * .
 * #L%
 */


import com.pi4j.io.serial.*;
import com.pi4j.util.CommandArgumentParser;
import com.pi4j.util.Console;

import java.io.IOException;
import java.time.LocalTime;

/**
 * This example code demonstrates how to perform serial communications using the Raspberry Pi.
 *
 * @author Robert Savage
 */
public class Test {

    /**
     * This example program supports the following optional command arguments/options:
     *   "--device (device-path)"                   [DEFAULT: /dev/ttyAMA0]
     *   "--baud (baud-rate)"                       [DEFAULT: 38400]
     *   "--data-bits (5|6|7|8)"                    [DEFAULT: 8]
     *   "--parity (none|odd|even)"                 [DEFAULT: none]
     *   "--stop-bits (1|2)"                        [DEFAULT: 1]
     *   "--flow-control (none|hardware|software)"  [DEFAULT: none]
     *
     * @param args
     * @throws InterruptedException
     * @throws IOException
     */
    public static void main(String args[]) throws InterruptedException, IOException
    {

        // !! ATTENTION !!
        // By default, the serial port is configured as a console port
        // for interacting with the Linux OS shell.  If you want to use
        // the serial port in a software program, you must disable the
        // OS from using this port.
        //
        // Please see this blog article for instructions on how to disable
        // the OS console for this port:
        // https://www.cube-controls.com/2015/11/02/disable-serial-port-terminal-output-on-raspbian/

        // create Pi4J console wrapper/helper
        // (This is a utility class to abstract some of the boilerplate code)
        //final Console console = new Console();

        // print program title/header
        //console.title("<-- The Pi4J Project -->", "Serial Communication Example");

        // allow for user to exit program using CTRL-C
        //console.promptForExit();
        System.out.println("Initialization...");
        // create an instance of the serial communications class
        final Serial serial = SerialFactory.createInstance();

        // create and register the serial data listener
        serial.addListener(new SerialDataEventListener() {

            int pos = 0;
            char var = '\0';
            byte high = 0;
            byte low = 0;
            short val;

            @Override
            public void dataReceived(SerialDataEvent event)
            {

                // NOTE! - It is extremely important to read the data received from the
                // serial port.  If it does not get read from the receive buffer, the
                // buffer will continue to grow and consume memory.

                // print out the data received to the console
                try
                {
                    byte[] bytes = event.getBytes();

                    for (byte b : bytes)
                    {
                        // System.out.print("~~" + (char)b + " ");
                        switch (this.pos)
                        {

                            case 0: {
                                if (b == '\n')
                                {
                                    // System.out.println("newline");
                                    this.pos++;
                                    continue;
                                }
                                break;
                            }
                            case 1: {
                                if (b == 'X' || b == 'Y' || b == 'Z')
                                {
                                    this.pos++;
                                    this.var = (char)b;
                                    continue;
                                }
                                break;
                            }
                            case 2: {
                                if (b == '=')
                                {
                                    this.pos++;
                                    continue;
                                }
                                break;
                            }
                            case 3: {
                                this.high = b;
                                this.pos++;
                                continue;
                                //break;
                            }
                            case 4: {
                                this.low = b;
                                //Float val = map((float) this.val, 0, 1023, -3, 3);
                                if (this.var == 'X')
                                    System.out.println(LocalTime.now());
                                System.out.println(this.var + " = " + adxl345(this.high, this.low) + " milligravities");
                                break;
                            }
                        }
                        this.pos = 0;
                    }
                    // System.out.println("\nEnd of for");
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        });

        try {
            // create serial config object
            SerialConfig config = new SerialConfig();
            System.out.println("SerialPort.getDefaultPort(): " + SerialPort.getDefaultPort());
            // set default serial settings (device, baud rate, flow control, etc)
            //
            // by default, use the DEFAULT com port on the Raspberry Pi (exposed on GPIO header)
            // NOTE: this utility method will determine the default serial port for the
            //       detected platform and board/model.  For all Raspberry Pi models
            //       except the 3B, it will return "/dev/ttyAMA0".  For Raspberry Pi
            //       model 3B may return "/dev/ttyS0" or "/dev/ttyAMA0" depending on
            //       environment configuration.
            config.device("/dev/serial0")
                    .baud(Baud._115200)
                    .dataBits(DataBits._8)
                    .parity(Parity.NONE)
                    .stopBits(StopBits._1)
                    .flowControl(FlowControl.NONE);

            // parse optional command argument options to override the default serial settings.
            if(args.length > 0)
            {
                config = CommandArgumentParser.getSerialConfig(config, args);
            }

            // display connection details

            // open the default serial device/port with the configuration settings
            serial.open(config);

            // continuous loop to keep the program running until the user terminates the program
            while(true)
            {

                // wait 1 second before continuing
                Thread.sleep(1000);
            }

        }
        catch(IOException ex)
        {
            System.out.println(" ==>> SERIAL SETUP FAILED : " + ex.getMessage());
            return;
        }
    }

    public static float map(float x, float in_min, float in_max, float out_min, float out_max)
    {
        return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
    }

    public static double adxl345(byte high, byte low)
    {
        short val = (short) ((high & 0xFF) << 8);
        val += (short)(low & 0xFF);
        double conv = (val * 3.9);
        return conv;
    }

    public static float adxl337(byte high, byte low)
    {
        return 0;
    }
}

// END SNIPPET: serial-snippet