Raspberry Pi Programming

GPIO digital output

Following example sets PIN18 to High(3.3V).

  • Python's import statement includes external library
  • GPIO.setmode function defines which numbering method (pysical, GPIO number) is to be used.
  • GPIO.setup function defines the usage of GPIO pins (Input or Output)
  • GPIO.output function sets the GPIO pin value to be 1(3.3V) or 0(0V)

In [ ]:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)  # use GPIO numbering, see output of gpio command
#GPIO.setmode(GPIO.BOARD) # use Physical pin numbering
GPIO.setup(18, GPIO.OUT) # PIN18 (Physical:Pin12) : Output
GPIO.output(18, GPIO.HIGH) # Ping18 -> High (3.3V)

GPIO Digital input - 1

Following example read the value of PIN18

  • GPIO.input function returns the value of GPIO pin. 3.3V or 0V

In [ ]:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)  # use GPIO numbering, see output of gpio command
GPIO.setup(18, GPIO.IN) # PIN18: Input
if GPIO.input(18) == GPIO.HIGH:
    print('PIN18: HIGH')
else:
    print('PIN18: LOW')

GPIO Digital input - 2 (Pull Down)

Raspberry Pi has internal Pull Up/Down register, which can be enabled with setup() function.

  • Pull down register is enabled with GPIO.setup() function

In [ ]:
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)  # use GPIO numbering, see output of gpio command
GPIO.setup(18, GPIO.IN, pull_up_down=GPIO_PUP_DOWN) # PIN18: Input (Pull Down enabled)
if GPIO.input(18) == GPIO.HIGH:
    print('PIN18: HIGH')
else:
    print('PIN18: LOW')

Analog data input

Raspberry Pi does not have ADC(A/D converter) internally (Arduino has ADC). In order to handle analog data, external ADC is required.

PWM (Pulse Width Modulation)

PWM is a common method used to apply a proportional control signal to an external device using a digital output pin. For example, servo motors use the pulse width of an incoming PWM signal to determine their rotation angle. LCD displays adjust their brightness based on a PWM signal's average value.

Raspberry Pi has 2 hardware PWM, Arduino UNO has 6 hardware PWM.

SPI and I2C

Raspberry Pi support SPI(Serial Peripheral Interface) and I2C(Inter Integrated Circuit), these interface can be used to external peripheral such as ADC, or Arduino.

Serial (UART) communication over USB

In order to connect 1 Raspberry Pi and 1 Arduino, UART over USB is a easiest method.