sexta-feira, março 20, 2020

Raspberry Oled Screen with DHT22 Temperature Sensor





The code bellow needs improvements






Need enable i2c and install some libraries... (Python 3.x)

pip3 install --upgrade luma.oled
pip3 install Adafruit_DHT

Optional luma.examples

aptitude install python-dev python-pip libfreetype6-dev libjpeg-dev build-essential
aptitude install i2c-tools libopenjp2-7 libtiff5 python3-dev git
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014-18 Richard Hull and contributors
# See LICENSE.rst for details.
# PYTHON_ARGCOMPLETE_OK

"""
Showcase viewport and hotspot functionality.

"""



import datetime
import os
import time
from demo_opts import get_device
from luma.core.virtual import viewport, snapshot
from PIL import ImageFont
import RPi.GPIO as GPIO
import board
from datetime import date
from datetime import datetime
import Adafruit_DHT

tiny_font = ImageFont.truetype(os.path.abspath(os.path.join(
    os.path.dirname(__file__), "fonts", "FreePixel.ttf")), 10)


def right_text(draw, y, width, margin, text):
    x = width - margin - draw.textsize(text, font=tiny_font)[0]
    draw.text((x, y), text=text, font=tiny_font, fill="white")


def title_text(draw, y, width, text):
    x = (width - draw.textsize(text)[0]) / 2
    draw.text((x, y), text=text, fill="yellow")

def position(max):
    forwards = range(0, max)
    backwards = range(max, 0, -1)
    while True:
        for x in forwards:
            yield x
        for x in backwards:
            yield x

def pause_every(interval, generator):
    try:
        while True:
            x = next(generator)
            if x % interval == 0:
                for _ in range(20):
                    yield x
            else:
                yield x
    except StopIteration:
        pass

def render_clock(draw, width, height):
    margin = 3

    now = datetime.now()
    today_date = now.strftime("%d %b %y")
    current_time = now.strftime("%H:%m:%S")

    title_text(draw, margin, width, today_date)
    draw.text((margin + 10, 20), text=current_time, fill="white", font=tiny_font)


def render_temp(draw, width, height):
    humidity, temperature_c = Adafruit_DHT.read_retry(22, 4)
    margin = 3
    
    now = datetime.now()
    today_date = now.strftime("%d %b %y")
    current_time = now.strftime("%H:%m:%S")


    title_text(draw, margin, width, text="Temp DHT22")
    draw.text((margin, 20), text="temperature:", font=tiny_font, fill="white")
    draw.text((margin, 35), text="humidity:", font=tiny_font, fill="white")
    draw.text((margin, 45), text=today_date, font=tiny_font, fill="white")

    right_text(draw, 20, width, margin, text="{0:0.1f}%".format(temperature_c))
    right_text(draw, 35, width, margin, text="{0:0.1f}%".format(humidity))
    right_text(draw, 45, width, margin, text=current_time)
 
def render_temp2(draw, width, height):
    humidity, temperature_c = Adafruit_DHT.read_retry(11, 17)
    margin = 3

    now = datetime.now()
    today_date = now.strftime("%d %b %y")
    current_time = now.strftime("%H:%m:%S")


    title_text(draw, margin, width, text="Temp DHT11")
    draw.text((margin, 20), text="temperature:", font=tiny_font, fill="white")
    draw.text((margin, 35), text="humidity:", font=tiny_font, fill="white")
    draw.text((margin, 45), text=today_date, font=tiny_font, fill="white")

    right_text(draw, 20, width, margin, text="{0:0.1f}%".format(temperature_c))
    right_text(draw, 35, width, margin, text="{0:0.1f}%".format(humidity))
    right_text(draw, 45, width, margin, text=current_time)

def main():
#    widget_width = device.width // 2
    widget_width = device.width
    widget_height = device.height


    temp = snapshot(widget_width, widget_height, render_temp, interval=1.1)
    temp2 = snapshot(widget_width, widget_height, render_temp2, interval=1.0)
    clk = snapshot(widget_width, widget_height, render_clock, interval=1.0)
    clk2 = snapshot(widget_width, widget_height, render_clock, interval=1.0)

    widgets = [temp, temp2, clk, temp2]

    virtual = viewport(device, width=widget_width * len(widgets), height=widget_height)
    for i, widget in enumerate(widgets):
        virtual.add_hotspot(widget, (i * widget_width, 0))

#    for x in pause_every(widget_width, position(widget_width * (len(widgets) - 1))):
#        print("x=",x)
#        virtual.set_position((x, 0))
    x = 0
    while True:
        virtual.set_position((0, 0))
        time.sleep(1)
        #virtual.set_position((128, 0))
        #time.sleep(2)
        #virtual.set_position((256, 0))
        #time.sleep(6)

if __name__ == "__main__":
    try:
        device = get_device()
        main()
    except KeyboardInterrupt:
        pass



systetmd
vi /etc/systemd/system/temperature-widget.service
[Unit]
Description=Temperature sensor to OLED
After=syslog.target

[Service]
Type=simple
WorkingDirectory=/etc/script.d/
RemainAfterExit=yes
ExecStart=/etc/script.d/widget_temp.py
StandardOutput=syslog
StandardError=syslog

[Install]
WantedBy=multi-user.target






quinta-feira, março 19, 2020

How to setup OLED display with Raspberry Pi

Source of this post -> HERE




aptitude install libopenjp2-7
aptitude install libtiff5

OLED display with Raspberry PI

Schematics:

The OLED should be connected as shown the in the below picture.


I2C Driver:


raspi-config Tool via Terminal

If you are using a terminal, you will need to:
  1. Run sudo raspi-config.
  2. Use the down arrow to select 5 Interfacing Options
  3. Arrow down to P4 SPI.
  4. Select yes when it asks you to enable SPI,
  5. Also select yes if it asks about automatically loading the kernel module.
  6. Use the right arrow to select the  button.
  7. Select yes when it asks to reboot.


The system will reboot. When it comes back up, log in and enter the following command
>ls /dev/*spi*
The Pi should respond with
/dev/spidev0.0  /dev/spidev0.1
These represent SPI devices on chip enable pins 0 and 1, respectively. These pins are hardwired within the Pi. Ordinarily, this means the interface supports at most two peripherals, but there are cases where multiple devices can be daisy-chained, sharing a single chip enable signal.



Install i2c tools

root@raspberrypi:~# apt-get install i2c-tools
We have connected the OLED display to the /dev/i2c-1 of the Raspberry Pi.
In order to know what is the I2C Address of the device (Though I know it already, it might help some where). We need to scan the I2C bus and there is a command for that, its called i2cdetect. It can be used as follows.

Now we know that the I2C address of the device is 0x3C. But wait, we found that Address printed in the display as 0x78 and here it shows 0x3C, how is that possible? The answer is that the actual address of the device is 0X3C and you use address 0x78 or 0x79, for write or read. As an additional information the I2C bus allows devices to be plugged and unplugged without rebooting Pi. It’ll mess up some accesses, but I2C will recover.




OLED python Library 

With the emergence of Pi board and the Linux distros along with it there are always more than one library available for each interface. Likewise for OLED display there are many libraries and many variants of libraries . For the OLED with SSD1306 I choose this library https://github.com/rm-hull/luma.oled .
This is library is already available as part of python repository or as they called cheese cake factory ;).  Type the below command to install all the required dependencies for using the OLED display.

aptitude install libopenjp2-7
aptitude install libtiff5
aptitude install -y python-dev python-pip libfreetype6-dev libjpeg-dev build-essential
aptitude install python-dev python-pip libfreetype6-dev libjpeg-dev build-essential libopenjp2-7 libtiff5


pip install --upgrade luma.oled
pip3 install --upgrade luma.oled


Example code:

git clone https://github.com/codelectron/codelectron_projects
cd codelectron_projects/Rpi/OLED
python first.py
Now I will run the first python example first.py

Follow instructions on the original post ...




segunda-feira, março 16, 2020

Raspberry Pi LCD Display: 16×2 Characters Display (HD44780)

https://tutorials-raspberrypi.com/raspberry-pi-lcd-display-16x2-characters-display-hd44780/

The most common controller of multi-line character displays is the HD44780. There are several Raspberry Pi LCD display sizes (8×2, 16×2, 20×4, etc.) that run with it. In this tutorial, I will show how to use a 16×2 character display and also run a test script.
A few words said in advance: In this tutorial, all pins are addressed directly, which occupies quite a few GPIOs. Another method is the connection via I2C.

Required Hardware Parts

The following parts are required:

Setup

In this case, I refer to the pin numbering (GPIO.BOARD), not to the GPIO numbers:

LCD Pinto RPi GPIODescription
 1. VSS Pin 6 (GND)Supply Voltage (ground)
 2. VDD Pin 2 (5V)Supply Voltage 5V
 3. V0 Pin 6 (GND)Contrast Voltage
 4. RS Pin 7 (GPIO4)Register Selection (0: Command Register, 1: Data Register)
 5. RW Pin 6 (GND) Read/Write (0: Write Modus, 1: Read Modus)
 6. E Pin 11 (GPIO17)Clock Edge
 7. D0 –Data Line 0
 8. D1 –Data Line 1
 9. D2 –Data Line 2
 10. D3 –Data Line 3
 11. D4 Pin 12 (GPIO18)Data Line 4
 12. D5 Pin 15 (GPIO22)Data Line 5
 13. D6 Pin 16 (GPIO23)Data Line 6
 14. D7 Pin 18 (GPIO24)Data Line 7
 15. A Pin 2 (5V) (mit Poti)Backlight Anode
 16. K Pin 6 (GND)Backlight Cathode

The backlight can be adjusted by turning the potentiometer. Some displays cannot stand 5V for the backlight, so you should either look at the datasheet or at least always connect a 470Ω – 510Ω resistor.

Testing the Raspberry Pi LCD Display

You can either view the script I used here or just download it and try.
wget http://www.tutorials-raspberrypi.de/wp-content/uploads/scripts/hd44780_test.py
chmod +x hd44780_test.py
python hd44780_test.py
If you have chosen a different display or pin assignment, do not forget to adapt the script.
Through the simple control, you can create different scripts, which, for example, show the status of the Pi.

quinta-feira, março 12, 2020

Arm debian based distro

Easy and simple, tested on BananaPi M1.

https://www.armbian.com/bananapi/
https://www.armbian.com/

worth trying


DHT11 & DHT22 Sensor Temperature and Humidity Phyton Examples

Old and deprecated code, BUT easy to use.

https://github.com/adafruit/Adafruit_Python_DHT




Installing

Dependencies

For all platforms (Raspberry Pi and Beaglebone Black) make sure your system is able to compile and download Python extensions with pip:
On Raspbian or Beaglebone Black's Debian/Ubuntu image you can ensure your system is ready by running one or two of the following sets of commands:
Python 2:
sudo apt-get update
sudo apt-get install python-pip
sudo python -m pip install --upgrade pip setuptools wheel
Python 3:
sudo apt-get update
sudo apt-get install python3-pip
sudo python3 -m pip install --upgrade pip setuptools wheel

Install with pip

Use pip to install from PyPI.
Python 2:
sudo pip install Adafruit_DHT
Python 3:
sudo pip3 install Adafruit_DHT

Compile and install from the repository

First download the library source code from the GitHub releases page, unzipping the archive, and execute:
Python 2:
cd Adafruit_Python_DHT
sudo python setup.py install
Python 3:
cd Adafruit_Python_DHT
sudo python3 setup.py install
You may also git clone the repository if you want to test an unreleased version:
git clone https://github.com/adafruit/Adafruit_Python_DHT.git



Examples


#!/usr/bin/python
import sys
import Adafruit_DHT
import time
from datetime import date
from datetime import datetime

while True:

  humidity, temperature = Adafruit_DHT.read_retry(22, 27)
#  print 'time ', datetime.today().strftime("%d/%m/%Y %H:%M:%S")
  print  ' ', datetime.today().strftime("%d/%m/%Y %H:%M:%S") + ' Temp: {0:0.1f} C  Humidity: {1:0.1f} %'.format(temperature, humidity) 
  time.sleep(5)




#!/usr/bin/python
# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import sys

import Adafruit_DHT


# Parse command line parameters.
sensor_args = { '11': Adafruit_DHT.DHT11,
                '22': Adafruit_DHT.DHT22,
                '2302': Adafruit_DHT.AM2302 }
if len(sys.argv) == 3 and sys.argv[1] in sensor_args:
    sensor = sensor_args[sys.argv[1]]
    pin = sys.argv[2]
else:
    print('Usage: sudo ./Adafruit_DHT.py [11|22|2302] ')
    print('Example: sudo ./Adafruit_DHT.py 2302 4 - Read from an AM2302 connected to GPIO pin #4')
    sys.exit(1)

# Try to grab a sensor reading.  Use the read_retry method which will retry up
# to 15 times to get a sensor reading (waiting 2 seconds between each retry).
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

# Un-comment the line below to convert the temperature to Fahrenheit.
# temperature = temperature * 9/5.0 + 32

# Note that sometimes you won't get a reading and
# the results will be null (because Linux can't
# guarantee the timing of calls to read the sensor).
# If this happens try again!
if humidity is not None and temperature is not None:
    print('Temp={0:0.1f}*  Humidity={1:0.1f}%'.format(temperature, humidity))
else:
    print('Failed to get reading. Try again!')
    sys.exit(1)

Raspberry Pi 3 Broken microSD card slot USB BOOT

Removing sdcard slot
Original post -> https://www.raspberrypi.org/forums/viewtopic.php?t=191197
https://www.raspberrypi.org/documentation/hardware/raspberrypi/bootmodes/gpio.md
https://github.com/raspberrypi/usbboot
https://www.raspberrypi.org/documentation/hardware/raspberrypi/bootmodes/host.md

This can explain how to change setting program_usb_boot_mode=1 using gpio pins
  • The individual OTP bits/fuses, when set disable a certain booting source, regardless of any associated boot source GPIO## wiring? Argh, only now I'm understanding that terse note "note this cannot enable boot modes that have not already been enabled in the OTP" in the documentation; this may be misleading as the OTP rather disables, or am I mistaken here?
  • When a certain OTP isn't set, then a corresponding GPIO## level does enable or disable a certain booting source? Do I need to pull up or down, and which resistance to Vcc or GND will be needed?
  • How is the GPIO## mapping exactly?
    • GPIO22: boot from primary SD
    • GPIO23: boot from secondary SD
    • GPIO24: boot from NAND
    • GPIO25: boot from SPI
    • GPIO26: boot from USB mass storage device

https://www.raspberrypi.org/forums/viewtopic.php?t=175761