i am trying to make an LED light flash on the raspberry pi using some code i found online ( i know - not the best but it was a tutorial site)
When i run the following python code the led light flashes;
import RPi.GPIO as GPIO
import time
pinNum = 4
GPIO.setmode(GPIO.BCM) #numbering scheme that corresponds to breakout board and pin layout
GPIO.setup(pinNum,GPIO.OUT) #replace pinNum with whatever pin you used, this sets up that pin as an output
#set LED to flash forever
while True:
GPIO.output(pinNum,GPIO.HIGH)
time.sleep(0.5)
GPIO.output(pinNum,GPIO.LOW)
time.sleep(0.5)
When i run the following Java code which is supposed to do the same - all i get to the console are the print statements which i have added - no flashing light
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 ControlGpioExample {
public static void main(String[] args) throws InterruptedException {
final GpioController gpio = GpioFactory.getInstance();
final GpioPinDigitalOutput ledPin = gpio.provisionDigitalOutputPin(RaspiPin
.GPIO_04, "MyLED", PinState.LOW);
System.out.println("Started");
try
{
while(true)
{
System.out.println(ledPin==null);
System.out.println("Looping pin now");
ledPin.high();
System.out.println("Set high called");
Thread.sleep(2000);
ledPin.low();
System.out.println("Set low called");
Thread.sleep(2000);
}
}
catch(Exception ex)
{
gpio.shutdown();
ex.printStackTrace();
}
}
}
Does anyone know why this might be? I think logically the should be doing the same thing - both are using the same GPIO pin number from the pi too
Thanks for your help
Java has proven to be a perfect match for the Raspberry Pi, especially with the recent evolutions in the JDK and OpenJFX. The latest Raspberry Pi boards, including the $15 Raspberry Pi Zero 2 W, are great Linux machines to run Java applications on.
Blink the LED We then press CTRL-X, then Y, then press Enter to save the program and return to the terminal. Your LED should be blinking. If it doesn't blink, try connecting the red positive lead to another GPIO pin on the Raspberry Pi. To stop the program, you press CTRL-C.
A 5mm LED is used as an output device. The anode of the LED (long lead) is connected to Physical Pin 18 (GPIO24) of Raspberry Pi. The cathode of the LED (short lead) is connected to one terminal of a 100Ω Resistor. The other terminal of the Resistor is connected to GND.
The GPIO_4 in the Python GPIO code corresponds to this diagram
The pi4j corresponds to the diagram below
So GPIO_04 is in a completely different location! You should change the java code to use GPIO_07
Here's an explanation of why wiringpi has different names for the pins. It's very confusing that they are both using GPIO_XX
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With