将Python代码转换为Java代码

时间:2015-06-07 22:29:52

标签: java python raspberry-pi

我需要一些帮助将python代码转换为java。我是Python的新手,我不知道所有的功能/方法/等。我使用这个Python代码从Raspberry Pi上的2个传感器读取一些数据,我需要用Java获取这些数据。

这是Python代码:

#!/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)

这是我尝试过的Java代码(我使用的是Pi4j库):

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;
      }
}

我想知道这个java代码是否正常还是需要修改。

这是我开始运行的结果:

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

我不确定&#34; channelReading&#34;功能还可以。请帮帮我。

非常感谢!

1 个答案:

答案 0 :(得分:1)

这是你的java代码的一个问题,与Python(还)无关。

看看你得到的错误,

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

您应该查看代码中的第80行,即

chipSelectOutput.high();

方法

中的

private static int channelReading(MCP3008_channels channel) {

从主方法的第44行调用

float lightLevel = channelReading(MCP3008_channels.CH0);

所以你要调用方法chipSelectOutput.high(),但是看看你的其余代码,我们有

private static GpioPinDigitalOutput chipSelectOutput = null;

并且您从未创建/为此变量分配对象,因此当您从中调用方法时,chipSelectOutput仍具有值null。这就是你得到NullPointerException的原因。

在执行任何其他操作之前,您需要在代码中的某处创建chipSelectOutput对象,以便有一个对象来调用该函数。

以下是如何/应该初始化静态成员的示例:

static variable initialization java

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

如果此方法有效,那么出于同样的原因,对于您尚未初始化的其他对象clockOutputmosiOutputmisoInput,您将收到相同类型的错误(在任何地方给出一个值。