【问题标题】:Translate Python code to Java code [closed]将 Python 代码转换为 Java 代码 [关闭]
【发布时间】:2015-06-07 22:29:52
【问题描述】:

我需要一些关于将 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)

我不确定“channelReading”功能是否正常。请帮帮我。

非常感谢!

【问题讨论】:

  • 运行它。如果它和 Python 做同样的事情,你就可以开始了。如果没有,则需要更多工作。

标签: java python raspberry-pi


【解决方案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) {

从你的 main 方法的第 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,您也没有在任何地方初始化(给定值)。

【讨论】:

    猜你喜欢
    • 2012-04-10
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    • 2012-11-21
    相关资源
    最近更新 更多