-2

I need some help with a translation of a python code into java. I'm new in Python, and i don't know all the functions/methods/etc. I use this Python code to read some datas from 2 sensors on Raspberry Pi and i need to get this datas in Java.

Here is the Python code:

#!/usr/bin/python

import spidev
import time
import os

# Open SPI bus
spi = spidev.SpiDev()
spi.open(0,0)

# Function to read SPI data from MCP3008 chip
# Channel must be an integer 0-7
def ReadChannel(channel):
  adc = spi.xfer2([1,(8+channel)<<4,0])
  data = ((adc[1]&3) << 8) + adc[2]
  return data

# Function to convert data to voltage level,
# rounded to specified number of decimal places.
def ConvertVolts(data,places):
  volts = (data * 3.3) / float(1023)
  volts = round(volts,places)
  return volts

# Function to calculate temperature from
# TMP36 data, rounded to specified
# number of decimal places.
def ConvertTemp(data,places):

  # ADC Value
  # (approx)  Temp  Volts
  #    0      -50    0.00
  #   78      -25    0.25
  #  155        0    0.50
  #  233       25    0.75
  #  310       50    1.00
  #  465      100    1.50
  #  775      200    2.50
  # 1023      280    3.30

  temp = ((data * 330)/float(1023))-50
  temp = round(temp,places)
  return temp

# Define sensor channels
light_channel = 0
temp_channel  = 1

# Define delay between readings
delay = 5

while True:

  # Read the light sensor data
  light_level = ReadChannel(light_channel)
  light_volts = ConvertVolts(light_level,2)

  # Read the temperature sensor data
  temp_level = ReadChannel(temp_channel)
  temp_volts = ConvertVolts(temp_level,2)
  temp       = ConvertTemp(temp_level,2)

  # Print out results
  print "--------------------------------------------"
  print("Light: {} ({}V)".format(light_level,light_volts))
  print("Temp : {} ({}V) {} deg C".format(temp_level,temp_volts,temp))

  # Wait before repeating loop
  time.sleep(delay)

and this is the Java code that i've tried(i'm using Pi4j library):

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.RaspiPin;


public class MCP3008_TMP36 {

    private static Pin spiClk = RaspiPin.GPIO_01; // Pin #18, clock
    private static Pin spiMiso = RaspiPin.GPIO_04; // Pin #23, data in. MISO: Master In Slave Out
    private static Pin spiMosi = RaspiPin.GPIO_05; // Pin #24, data out. MOSI: Master Out Slave In
    private static Pin spiCs = RaspiPin.GPIO_06; // Pin #25, Chip Select

    private enum MCP3008_channels {
        CH0(0), CH1(1), CH2(2), CH3(3), CH4(4), CH5(5), CH6(6), CH7(7);

        private int ch;

        MCP3008_channels(int chNum) {
            this.ch = chNum;
        }

        public int ch() {
            return this.ch;
        }
    }

    private static GpioPinDigitalInput misoInput = null;
    private static GpioPinDigitalOutput mosiOutput = null;
    private static GpioPinDigitalOutput clockOutput = null;
    private static GpioPinDigitalOutput chipSelectOutput = null;

    private static boolean run = true;

    public static void main(String[] args){

        GpioController gpio = GpioFactory.getInstance();

        //TODO
        while(run){

            float lightLevel = channelReading(MCP3008_channels.CH0);
            float lightVolts = convertVolts(lightLevel);

            float tempLevel = channelReading(MCP3008_channels.CH1);
            float tempVolts = convertVolts(tempLevel);
            float temp = convertTemp(tempVolts);

            System.out.println("Light: " + lightLevel+"/"+lightVolts+"V");
            System.out.println("Temp:"+temp+"/"+tempVolts+"V");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Bye...");
        gpio.shutdown();

    }

    public static float convertVolts(float data){
        //TODO
        float rez = (float) ((data * 3.3)/1023);
        float rez1 = Math.round(rez);
        return rez1;
    }

    public static float convertTemp(float data){
        //TODO
        float rez = (float) ((data * 330)/1023)-50;
        float rez1 = Math.round(rez);
        return rez1;
    }

    private static int channelReading(MCP3008_channels channel) {
        chipSelectOutput.high();

        clockOutput.low();
        chipSelectOutput.low();

        int adccommand = channel.ch();
        adccommand |= 0x18; // 0x18: 00011000
        adccommand <<= 3;
        // Send 5 bits: 8 - 3. 8 input channels on the MCP3008.
        for (int i = 0; i < 5; i++) //
        {
            if ((adccommand & 0x80) != 0x0) // 0x80 = 0&10000000
                mosiOutput.high();
            else
                mosiOutput.low();
            adccommand <<= 1;
            clockOutput.high();
            clockOutput.low();
        }

        int adcOut = 0;
        for (int i = 0; i < 12; i++) // Read in one empty bit, one null bit and
                                        // 10 ADC bits
        {
            clockOutput.high();
            clockOutput.low();
            adcOut <<= 1;

            if (misoInput.isHigh()) {
                // System.out.println("    " + misoInput.getName() +
                // " is high (i:" + i + ")");
                // Shift one bit on the adcOut
                adcOut |= 0x1;
            }
        }
        chipSelectOutput.high();

        adcOut >>= 1; // Drop first bit
        return adcOut;
      }
}

I want to know if this java code is ok or it needs modifications.

This is the result that i get on running:

Exception in thread "main" java.lang.NullPointerException
    at MCP3008_TMP36.channelReading(MCP3008_TMP36.java:80)
    at MCP3008_TMP36.main(MCP3008_TMP36.java:44)

I'm not sure that the "channelReading" function is ok. Please help me with it.

Thanks a lot!

1
  • 1
    Run it. If it does the same thing as the Python, you're good to go. If it doesn't, it needs more work. Commented Jun 7, 2015 at 22:30

1 Answer 1

1

This is a problem with your java code and has nothing to do with Python (yet).

Looking at the error you get,

Exception in thread "main" java.lang.NullPointerException at MCP3008_TMP36.channelReading(MCP3008_TMP36.java:80) at MCP3008_TMP36.main(MCP3008_TMP36.java:44)

You should look at the line 80 in your code, which is

chipSelectOutput.high();

within the method

private static int channelReading(MCP3008_channels channel) {

as called from line 44 of your main method

float lightLevel = channelReading(MCP3008_channels.CH0);

So you are calling the method chipSelectOutput.high(), but looking at the rest of your code, we have

private static GpioPinDigitalOutput chipSelectOutput = null;

and you never created/assigned an object to this variable, so chipSelectOutput still has the value null when you call a method from it. That's why you get a NullPointerException.

You need to create a chipSelectOutput object somewhere in your code before doing anything else, so that there is an object to call the function on.

Here's an example of how you can/should initialize a static member:

static variable initialization java

private static final B a = new B(); // consider making it final too

If this works, you will then get the same type of error for the same reason, for your other objects clockOutput, mosiOutput and misoInput, which you also have not initialized (given a value) anywhere.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.