Showing posts with label GPIO. Show all posts
Showing posts with label GPIO. Show all posts

Tuesday, May 19, 2020

pinout command, to query Raspberry Pi GPIO pin-out information.

In update Raspbian, the pinout command was added. It's a funny and informative utility for querying Raspberry Pi GPIO pin-out information.

$ pinout


Related:
~ How to check Raspberry Pi 4B reversion 1.2, it provide more option to check your board version.


Monday, May 29, 2017

Python to output PWM to control LED brightness, with tkinter GUI

Python to generate PWM on GPIO of Raspberry Pi to control brightness of a LED, with tkinter GUI. Tested on Raspberry Pi 2 running Raspbian Jessie with PIXEL rel. 2017-04-10, work on both Python 2 (from Tkinter import *) and 3 (from Tkinter import * ).


pyGuiPwm.py
from Tkinter import *   #for Python 2
#from tkinter import *   #for Python 3

import platform
import RPi.GPIO as GPIO

def setPwm(newvalue):
    pwmValue.set(newvalue)
    pwmled.ChangeDutyCycle(float(newvalue))

def on_closing():
    print("Clean up")
    pwmled.stop()
    GPIO.cleanup()
    print("bye")
    master.destroy()

#mode = GPIO.BCM
#led = 21
mode = GPIO.BOARD
led = 40

print("Raspberry Pi board revision: "
      + str(GPIO.RPI_INFO['P1_REVISION']))
print("Machine: "
      + platform.machine())
print("Processor: "
      + platform.processor())
print("System: "
      + platform.system())
print("Version: "
      + platform.version())
print("Uname: "
      + str(platform.uname()))
print("Python version: "
      + platform.python_version())
print("RPi.GPIO version: "
      + str(GPIO.VERSION))

GPIO.setmode(mode)
GPIO.setup(led, GPIO.OUT)
pwmled = GPIO.PWM(led, 50)
pwmled.start(0)

master = Tk()

pwmValue = StringVar()
label = Label(master, textvariable=pwmValue, relief=RAISED )
label.pack()

slider = Scale(master, from_=0, to=100, orient=HORIZONTAL, command=setPwm)
slider.pack()

master.protocol("WM_DELETE_WINDOW", on_closing)
mainloop()



Next:
- Python to control RGB LED, with tkinter colorchooser/tkColorChooser

Python to generate PWM on GPIO of Raspberry Pi


Python to generate PWM on GPIO of Raspberry Pi to control brightness of a LED. Tested on Raspberry Pi 2 running Raspbian Jessie with PIXEL rel. 2017-04-10, work on both Python 2 and 3.


pyGPIO.py
import RPi.GPIO as GPIO
import time
import platform

print("Raspberry Pi board revision: "
      + str(GPIO.RPI_INFO['P1_REVISION']))
print("Machine: "
      + platform.machine())
print("Processor: "
      + platform.processor())
print("System: "
      + platform.system())
print("Version: "
      + platform.version())
print("Uname: "
      + str(platform.uname()))
print("Python version: "
      + platform.python_version())
print("RPi.GPIO version: "
      + str(GPIO.VERSION))
print("Ctrl-C to terminate and clean up GPIO")

#mode = GPIO.BCM
#led = 21
mode = GPIO.BOARD
led = 40

GPIO.setmode(mode)
GPIO.setup(led, GPIO.OUT)
pwmled = GPIO.PWM(led, 50)
pwmled.start(0)

try:
    while True:
        for dc in range(0, 101, 5):
            pwmled.ChangeDutyCycle(dc)
            time.sleep(0.1)
        for dc in range(100, -1, -5):
            pwmled.ChangeDutyCycle(dc)
            time.sleep(0.1)
finally:
    print("Clean up")
    pwmled.stop()
    GPIO.cleanup()


Reference:
~ raspberry-gpio-python - Using PWM in RPi.GPIO

Connection (same as in the post "Python to control GPIO of Raspberry Pi"):


Next:
- Python to output PWM to control LED brightness, with tkinter GUI

Thursday, October 15, 2015

GPIO Zero - a simple interface to GPIO for Raspberry Pi

GPIO Zero is a simple interface to everyday GPIO components used with Raspberry Pi, with very little code, you can quickly get going connecting your physical components together.

This video show my first try of GPIO Zero on raspberry Pi 2/Raspbian Jessie.


Connection (LED and Button):
Run IDLE with sudo, enter the simple code to test:
Python 2.7.9 (default, Mar  8 2015, 00:52:26) 
[GCC 4.9.2] on linux2
Type "copyright", "credits" or "license()" for more information.
>>> from gpiozero import LED, Button
>>> led=LED(2)
>>> button=Button(3)
>>> button.when_pressed=led.on
>>> button.when_released=led.off
>>> 


Monday, October 12, 2015

Raspberry Pi 2 + MFRC522-python, to read RFID tag

CAUTION@2016-08-19:
Somebody comment no need set device tree, check the comments (in the comments below and in the video: https://www.youtube.com/watch?v=0aVtZvkuHTA) first, before you try.



This post show the steps I install MFRC522-python (https://github.com/rasplay/MFRC522-python) on Raspberry Pi 2/Raspbian Jessie (2015-09-24), to read RFID tags (key and card) using RFID Reader, RFID-RC522.



Connection between RFID-RC522 Reader and Raspberry Pi 2:
RFID-RC522 pin NamePin #Raspberry Pi 2 Pin name
SDA24GPIO8
SCK23GPIO11
MOSI19GPIO10
MISO21GPIO9
IRQ-no connection
GNDGNDGND
RST22GPIO25
3.3V13V3

Steps:
1 - Enable SPI using Raspberry Pi Configuration


2 - Install python-dev and SPI-Py
$ sudo apt-get install python-dev
$ git clone https://github.com/lthiery/SPI-Py.git
$ cd SPI-Py
$ sudo python setup.py install


3 - Download MFRC522-python, MFRC522 Python Library for Raspberry Pi
(https://github.com/rasplay/MFRC522-python)
$ git clone https://github.com/rasplay/MFRC522-python.git


Unfortunately it is still not work!

Then I follow dzasa steps in this thread https://www.raspberrypi.org/forums/viewtopic.php?f=37&t=106313 to solve the problem.

4 - Enable device tree
Edit /boot/config.txt to add the line:
device_tree=on


5 - Install latest version of bcm2835, C library for Broadcom BCM 2835 as used in Raspberry Pi; version 1.46 currently.
(http://www.airspayce.com/mikem/bcm2835/)
# download the latest version of the library, say bcm2835-1.xx.tar.gz, then:
$ tar zxvf bcm2835-1.xx.tar.gz
$ cd bcm2835-1.xx
$ ./configure
$ make
$ sudo make check
$ sudo make install


Then reboot.

6 - Test it:
$ cd MFRC522-python
$ sudo python read.py



Updated@2016-01-30:
when we using MFRC522 it will set GPIO port mode to GPIO.BOARD. So simply you can't access using GPIO ports when it is in this mode using GPIO pins numbers. But you can access any GPIO ports according to GPIO.BOARD representation.  ~ refer to Unknown comment below.


Next:
- Raspberry Pi 2 + MFRC522-python - Dump RFID Tag data using mxgxw/MFRC522-python

Related:
- Arduino Uno + RFID-RC522, MFRC522 library example DumpInfo
- Android NFC: readBlock() for MifareClassic, to dump data in RFID tag

Friday, September 25, 2015

Python control Raspberry Pi 2 PWR/ACT LED, using RPi.GPIO or system's shell.

Last post show how to "Control Raspberry Pi 2 B on-board ACT LED with Python/RPi.GPIO", this example show how to control both the PWR and ACT LED of Raspberrry Pi 2 B, using Python, with RPi.GPIO and via system's shell by calling os.system().


*Please note that it's for Raspberrry Pi 2 B only*

Refer to Windows IoT document Raspberry Pi 2 Pin Mappings:
Red Power LED's GPIO# is 35.
Green Activity LED's GPIO# is 47.

In my experience, it cannot be perform using sudo, you have to login as root. To login as root, refer to the post "Set password of root".

pyGPIO.py
import sys
import os
import RPi.GPIO as GPIO
import time

print("**********************************************")
print("*** Toggle PWR/ACT LED on Raspberry Pi 2 B ***")
print("***        for Raspberry Pi 2 B only       ***")
print("**********************************************")
print("- System info -")
print(sys.version)
print("GPIO.VERSION: " + GPIO.VERSION)
print("GPIO.RPI_REVISION (deprecated): " + str(GPIO.RPI_REVISION))

print("")
print("GPIO.RPI_INFO:")
print(GPIO.RPI_INFO)

print("")
for keys,values in GPIO.RPI_INFO.items():
 print(keys + " : " + str(values))

print("")
#display trigger for led0 and led1
print("- Original trigger for led 0 -")
os.system("cat /sys/class/leds/led0/trigger")
print("- Original trigger for led 1 -")
os.system("cat /sys/class/leds/led1/trigger")

print("remove the trigger for led0 and led1")
os.system("echo none >/sys/class/leds/led0/trigger")
os.system("echo none >/sys/class/leds/led1/trigger")
os.system("cat /sys/class/leds/led0/trigger")
os.system("cat /sys/class/leds/led1/trigger")
print("")
 
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(35, GPIO.OUT) #Red PWR LED on RPi2B 
GPIO.setup(47, GPIO.OUT) #Green Activity LED on RPi2B

for num in range(1, 5):
    print num
    
    #Control led0 with RPi.GPIO
    GPIO.output(47, False)  #Turn OFF ACT LED for RPi 2 B
    GPIO.output(35, True) #Turn ON PWR LED for RPi 2 B
    print "LED PWR(RED)-ON ACT(GREEN)-OFF"
    time.sleep(2)

    #Control led1 with system's shell
    os.system("echo 1 >/sys/class/leds/led0/brightness")
    os.system("echo 0 >/sys/class/leds/led1/brightness")
    print "LED PWR(RED)-OFF ACT(GREEN)-ON"
    time.sleep(3)

print("")
print("Finished")
#rsume the trigger for led0 and 
#assume it's mmc0 and input
os.system("echo mmc0 >/sys/class/leds/led0/trigger")
os.system("echo input >/sys/class/leds/led1/trigger")

print("- Resummed trigger for led 0 -")
os.system("cat /sys/class/leds/led0/trigger")
print("- Resummed trigger for led 1 -")
os.system("cat /sys/class/leds/led1/trigger")
print("")


Thursday, September 24, 2015

Python/RPi.GPIO Control Raspberry Pi 2 B on-board ACT LED

I have a old example "Control the on-board LED using Python" to toggle Raspberry Pi 1 ACT LED. It's updated to toggle the ACT LED on Raspberry Pi 2.


On Raspberry Pi 2 B, the ACT LED is assigned pin 47.

pyGPIO.py
import sys
import RPi.GPIO as GPIO
import time

print(sys.version)
print("GPIO.VERSION: " + GPIO.VERSION)
print("GPIO.RPI_REVISION (deprecated): " + str(GPIO.RPI_REVISION))

print("")
print("GPIO.RPI_INFO:")
print(GPIO.RPI_INFO)

print("")
for keys,values in GPIO.RPI_INFO.items():
 print(keys + " : " + str(values))
 
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#GPIO.setup(16, GPIO.OUT)
GPIO.setup(47, GPIO.OUT)

for num in range(1, 5):
    print num
    #GPIO.output(16, True)   ##Turn OFF LED
    GPIO.output(47, False)   ##Turn OFF LED for RPi 2 B
    print "LED OFF"
    time.sleep(2)
    #GPIO.output(16, False) ##Turn ON LED
    GPIO.output(47, True)   ##Turn ON LED for RPi 2 B
    print "LED ON"
    time.sleep(3)

#GPIO.output(16, True)   ##Turn OFF LED
GPIO.output(47, False)   ##Turn OFF LED for RPi 2 B


In my experience, it cannot be perform using sudo, you have to login as root. To login as root, refer to the post "Set password of root".

Then login as root.

by default, the ACT LED is set triggered by mmc0. It can be checked with the command:

# cat /sys/class/leds/led0/trigger
none [mmc0] timer oneshot heartbeat backlight gpio cpu0 default-on

In order to program it as GPIO, remove the trigger with the command:
# echo none >/sys/class/leds/led0/trigger

Run our Python example, pyGPIO.py
# python pyGPIO.py

After test, resume the trigger by mmc0 with command (or reboot):
# echo mmc0 >/sys/class/leds/led0/trigger


Next:
- Python control Raspberry Pi 2 PWR/ACT LED, using RPi.GPIO or system's shell.

Sunday, September 14, 2014

Python + bottle@Raspberry Pi: Web based GPIO control

This example show how to program in Python with bottle on Raspberry Pi, to implement web base GPIO control.

bottle is a Python web server library. To install bottle on Raspberry Pi, enter the command:
$ sudo apt-get install python-bottle


Create webled.py
from bottle import route, run
import RPi.GPIO as GPIO

host = '192.168.1.105'

pinButton = 17
pinLed = 18
GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(pinButton, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(pinLed, GPIO.OUT)

LedState = False

def read_button():
    if GPIO.input(pinButton):
        return 'Released'
    else:
        return 'Pressed'

def update_led():
    GPIO.output(pinLed, LedState)
    
def toggleLed():
    global LedState
    LedState = not LedState
    
@route('/')
@route('/<arg>')
def index(arg=""):
    if arg == "toggle":
        toggleLed()
        
    update_led()
    
    response = "<html>\n"
    response += "<body>\n"
    response += "<script>\n"
    response += "function changed()\n"
    response += "{window.location.href='/toggle'}\n"
    response += "</script>\n"
    
    response += "Button: " + read_button() +"\n"
    response += "<br/><br/>\n"
    response += "<input type='button' onClick='changed()' value=' LED '/>\n"
    response += "</body></html>\n"
    return response
    
run(host=host, port=80)

Run it:
$ sudo python webled.py



Related:
- Web control to display on Pi connected LCD Module, with Python and bottle

Python RPi.GPIO: Read Button using GPIO.add_event_detect() with callback

The example show how to detect events of GPIO, to detect button pressed/released. It have the same operation in the post "Python RPi.GPIO: Button and LED".



import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(18, GPIO.OUT)

def ButtonCallback(channel):
    if (GPIO.input(17)):
        GPIO.output(18, False)
    else:
        GPIO.output(18, True)
    
GPIO.add_event_detect(17, GPIO.BOTH, callback=ButtonCallback);

while(True):
    #do nothing
    time.sleep(1)

Friday, September 12, 2014

Python RPi.GPIO: Button and LED

This example read button input from pin 17 (set as input with pull-up resister) and set output to pin 18 to turn ON/OFF LED accordingly.



The code GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP) set pin 17 as input with pull-up resistor. If you omit the option pull_up_down=GPIO.PUD_UP, the pin will have no pull-up resistor, and become un-stable.

led.py
import RPi.GPIO as GPIO


GPIO.setmode(GPIO.BCM)
# pin 17 as input with pull-up resistor
GPIO.setup(17, GPIO.IN, pull_up_down=GPIO.PUD_UP)
# pin 18 as output
GPIO.setup(18, GPIO.OUT)

while(True):
 if (GPIO.input(17)):
  GPIO.output(18, False)
 else:
  GPIO.output(18, True)


Next:
- Read Button using GPIO.add_event_detect() with callback

Wednesday, September 10, 2014

Raspberry Pi Python exercise: Change GPIO LED brightness with GPIO.PWM

Example of Python on Raspberry Pi, to change GPIO LED brightness with GPIO.PWM.



led.py
import RPi.GPIO as GPIO
import time

led_pin = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(led_pin, GPIO.OUT)

#frequency 500 Hz
led_pwm = GPIO.PWM(led_pin, 500)
#duty cycle = 100
led_pwm.start(100)

while(True):
    led_pwm.ChangeDutyCycle(100)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(80)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(60)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(40)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(20)
    time.sleep(1)
    led_pwm.ChangeDutyCycle(0)
    time.sleep(1)


Connection, check lst post of "Toggle LED on GPIO".

Raspberry Pi Python exercise: Toggle LED on GPIO

Python example run on Raspberry Pi, to toggle GPIO pin for LED.

connection:

Example code, led.py:
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)

while(True):
    GPIO.output(18, True)
    time.sleep(1.5)
    GPIO.output(18, False)
    time.sleep(0.5)


Run it with sudo:
$ sudo python led.py

Next:
- Change GPIO LED brightness with GPIO.PWM

Saturday, December 14, 2013

Saturday, November 23, 2013

Control the on-board LED using C language

Last post show how to control Raspberry Pi on-board LED OK or ACT in command line. This post show the code to control the LED using C language, it have the same result of the exercise using Python.

Control the on-board LED using C language
Control the Raspberry Pi on-board LED using C language
testLED.c
#include <stdio.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

#define BCM2708_PERI_BASE 0x20000000
#define GPIO_BASE   (BCM2708_PERI_BASE + 0x200000) /* GPIO controller */
#define LED_ACT    16

#define BLOCK_SIZE (4*1024)

int mem_fd;
void *gpio_map;
volatile unsigned *gpio;

// GPIO setup macros. Always use INP_GPIO(x) before using OUT_GPIO(x) or SET_GPIO_ALT(x,y)
#define INP_GPIO(g) *(gpio+((g)/10)) &= ~(7<<(((g)%10)*3))
#define OUT_GPIO(g) *(gpio+((g)/10)) |=  (1<<(((g)%10)*3))
#define SET_GPIO_ALT(g,a) *(gpio+(((g)/10))) |= (((a)<=3?(a)+4:(a)==4?3:2)<<(((g)%10)*3))

#define GPIO_SET *(gpio+7)  // sets   bits which are 1 ignores bits which are 0
#define GPIO_CLR *(gpio+10) // clears bits which are 1 ignores bits which are 0
 
int init_io()
{
 /* open /dev/mem */
 if ((mem_fd = open("/dev/mem", O_RDWR|O_SYNC) ) < 0) {
  printf("can't open /dev/mem \n");
  return(-1);
 }else{
  printf("/dev/mem opened\n");
  
  /* mmap GPIO */
  gpio_map = mmap(
   NULL,             //Any adddress in our space will do
   BLOCK_SIZE,       //Map length
   PROT_READ|PROT_WRITE,// Enable reading & writting to mapped memory
   MAP_SHARED,       //Shared with other processes
   mem_fd,           //File to map
   GPIO_BASE         //Offset to GPIO peripheral 
  );
  
  close(mem_fd);
  printf("/dev/mem closed\n");
  
  if (gpio_map == MAP_FAILED) {
   printf("mmap error %d\n", (int)gpio_map);//errno also set!
   return(-1);
  }else{
   printf("mmap Success.\n");
  }
  
 }
 
 // Always use volatile pointer!
   gpio = (volatile unsigned *)gpio_map;

   return 0;
}


int main(){
 
 if(init_io() == -1) 
 {
  printf("Failed to map the physical GPIO registers into the virtual memory space.\n");
  return -1;
 }
 
 // must use INP_GPIO before we can use OUT_GPIO
 INP_GPIO(LED_ACT); 
    OUT_GPIO(LED_ACT);
 
 int repeat;
 for (repeat=1; repeat<5; repeat++)
 {
  GPIO_SET = 1 << LED_ACT;
  printf("LED OFF\n");
  sleep(2);

  GPIO_CLR = 1 << LED_ACT;
  printf("LED ON\n");
  sleep(1);
 }
 
 printf("- finished -\n");
 return 0;
}



remark:
- You have to login as root to read /dev/mem and control the GPIO. Read the post "Set password of root".
- Disable the LED trigger from mmc0, read the post "Control the on-board LED on Raspberry Pi".

Reference:
- elinux.org: RPi Low-level peripherals

Friday, November 22, 2013

Raspberry Pi Ultimate Starter Kit

Raspberry Pi Ultimate Starter Kit -- Includes Raspberry Pi Board + 11 Essential Accessories
  • Includes Raspberry Pi - Model B (512 MB / Revision 2)
  • Raspberry Pi Enclousure Case (Clear)
  • 4GB SD Card pre-loaded with "NOOB" (Includes Raspbian -- OpenELEC -- Arch -- RaspBMC-- RISC OS -- Pidora)
  • USB Power Supply with Micro USB Cable -- HDMI Cable -- Wireless Wifi Adapter
  • Breadboard - Jumper wires -- USB to TTL Serial Cable -- GPIO Ribbon Cable with Breakout board

Control the on-board LED using Python

Last post show how to control Raspberry Pi on-board LED OK or ACT in command line. This post show the Python code to control it.

Control the on-board LED using Python
Control the on-board LED using Python
Log-in as root, and enter the Python code. It will turn OFF and ON the on-board LED OK or ACT 4 times.

pythonGPIO.py
import RPi.GPIO as GPIO
import time

GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(16, GPIO.OUT)

for num in range(1, 5):
    print num
    GPIO.output(16, True)   ##Turn OFF LED
    print "LED OFF"
    time.sleep(2)
    GPIO.output(16, False)   ##Turn ON LED
    print "LED ON"
    time.sleep(1)




Updated:
- Python/RPi.GPIO Control Raspberry Pi 2 B on-board ACT LED
- Python control Raspberry Pi 2 PWR/ACT LED, using RPi.GPIO or system's shell


Control the on-board LED on Raspberry Pi

There are 5 on-board LEDs on Raspberry Pi. One of them (marked OK or ACT) can be programmed as GPIO. It's connected GPIO16, usually SD card access indicator.


by default, it is set triggered by mmc0. It can be checked with the command:

# cat /sys/class/leds/led0/trigger
none [mmc0] timer oneshot heartbeat backlight gpio cpu0 default-on

In order to program it as GPIO, remove the trigger with the command:
# echo none >/sys/class/leds/led0/trigger

Then, to turn on the LED, enter the command:
# echo 1 >/sys/class/leds/led0/brightness

Then, to turn off the LED, enter the command:
# echo 0 >/sys/class/leds/led0/brightness

After that, resume the trigger by mmc0 with command (or reboot):
# echo mmc0 >/sys/class/leds/led0/trigger

Control the on-board LED on Raspberry Pi
Control the on-board LED on Raspberry Pi


In my experience, it cannot be perform using sudo, you have to login as root. To login as root, refer to last post "Set password of root".

Related: