BMP-280 with Raspberry Pi and Python Wiring/Code

Adafruit Source

Python Computer Wiring

Since there’s dozens of Linux computers/boards you can use we will show wiring for Raspberry Pi. For other platforms, please visit the guide for CircuitPython on Linux to see whether your platform is supported.

Here’s the Raspberry Pi wired with I2C:

  • adafruit_products_raspi_bmp280_i2c_bb.png
  • Pi 3V3 to sensor VIN
  • Pi GND to sensor GND
  • Pi SCL to sensor SCK
  • Pi SDA to sensor SDI

And an example on the Raspberry Pi 3 Model B wired with SPI:

  • adafruit_products_raspi_bme280_spi_bb.png
  • Pi 3V3 to sensor VIN
  • Pi GND to sensor GND
  • Pi MOSI to sensor SDI
  • Pi MISO to sensor SDO
  • Pi SCLK to sensor SCK
  • Pi #5 to sensor CS (or use any other free GPIO pin)

CircuitPython Installation of BMP280 Library

You’ll need to install the Adafruit CircuitPython BMP280 library on your CircuitPython board.

First make sure you are running the latest version of Adafruit CircuitPython for your board.

Next you’ll need to install the necessary libraries to use the hardware–carefully follow the steps to find and install these libraries from Adafruit’s CircuitPython library bundle.  Our CircuitPython starter guide has a great page on how to install the library bundle.

For non-express boards like the Trinket M0 or Gemma M0, you’ll need to manually install the necessary libraries from the bundle:

  • adafruit_bmp280.mpy
  • adafruit_bus_device

Before continuing make sure your board’s lib folder or root filesystem has the adafruit_bmp280.mpy, and adafruit_bus_device files and folders copied over.

Next connect to the board’s serial REPL so you are at the CircuitPython >>> prompt.

Python Installation of BMP280 Library

You’ll need to install the Adafruit_Blinka library that provides the CircuitPython support in Python. This may also require enabling I2C on your platform and verifying you are running Python 3. Since each platform is a little different, and Linux changes often, please visit the CircuitPython on Linux guide to get your computer ready!

Once that’s done, from your command line run the following command:

  • sudo pip3 install adafruit-circuitpython-bmp280

If your default Python is version 3 you may need to run ‘pip’ instead. Just make sure you aren’t trying to use CircuitPython on Python 2.x, it isn’t supported!

CircuitPython & Python Usage

To demonstrate the usage of the sensor we’ll initialize it and read the temperature, humidity, and more from the board’s Python REPL.

If you’re using an I2C connection run the following code to import the necessary modules and initialize the I2C connection with the sensor:

 Download: file

  1. import board
  2. import busio
  3. import adafruit_bmp280
  4. i2c = busio.I2C(board.SCL, board.SDA)
  5. sensor = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)

Or if you’re using a SPI connection run this code instead to setup the SPI connection and sensor:

 Download: file

  1. import board
  2. import busio
  3. import digitalio
  4. import adafruit_bmp280
  5. spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
  6. cs = digitalio.DigitalInOut(board.D5)
  7. sensor = adafruit_bmp280.Adafruit_BMP280_SPI(spi, cs)

Now you’re ready to read values from the sensor using any of these properties:

  • temperature – The sensor temperature in degrees Celsius.
  • pressure – The pressure in hPa.
  • altitude – The altitude in meters.

For example to print temperature and pressure:

 Download: file

  1. print(‘Temperature: {} degrees C’.format(sensor.temperature))
  2. print(‘Pressure: {}hPa’.format(sensor.pressure))
adafruit_products_Screen_Shot_2017-11-10_at_3.33.47_PM.png

For altitude you’ll want to set the pressure at sea level for your location to get the most accurate measure (remember these sensors can only infer altitude based on pressure and need a set calibration point).  Look at your local weather report for a pressure at sea level reading and set the seaLevelhPA property:

 Download: file

  1. sensor.sea_level_pressure = 1013.25

Then read the altitude property for a more accurate altitude reading (but remember this altitude will fluctuate based on atmospheric pressure changes!):

 Download: file

  1. print(‘Altitude: {} meters’.format(sensor.altitude))
adafruit_products_alti.png

That’s all there is to using the BMP280 sensor with CircuitPython!

Here’s a starting example that will print out the temperature, pressure and altitude every 2 seconds:

  1. import time
  2.  
  3. import board
  4. # import digitalio # For use with SPI
  5. import busio
  6.  
  7. import adafruit_bmp280
  8.  
  9. # Create library object using our Bus I2C port
  10. i2c = busio.I2C(board.SCL, board.SDA)
  11. bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c)
  12.  
  13. # OR create library object using our Bus SPI port
  14. #spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
  15. #bmp_cs = digitalio.DigitalInOut(board.D10)
  16. #bmp280 = adafruit_bmp280.Adafruit_BMP280_SPI(spi, bmp_cs)
  17.  
  18. # change this to match the location’s pressure (hPa) at sea level
  19. bmp280.sea_level_pressure = 1013.25
  20.  
  21. while True:
  22. print(“\nTemperature: %0.1f C” % bmp280.temperature)
  23. print(“Pressure: %0.1f hPa” % bmp280.pressure)
  24. print(“Altitude = %0.2f meters” % bmp280.altitude)
  25. time.sleep(2)

Chatroom Source

import socket

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('0.0.0.0',25565))
s.listen(10)

while True:
    print('waiting for new connection')
    conn,addr = s.accept()
    print('New connection: ' + str(addr))

    motd = "Welcome to PolyChat!"
    conn.sendto(bytes(motd,'utf-8'), addr)

    char = ''
    message = ''
    while char != None and char != 'q':
        char,temp = conn.recvfrom(1024)
        char = char.decode('utf-8')
        message += char
        print(message)
        
    conn.close()



Telnet Demo

Enabling Telnet in Windows 10

telnet YOU WILL GET THE SERVER IN CLASS
EHLO totally.legit.server.com
MAIL FROM:<NAME@AURLIWILLGIVEYOU.com>
RCPT TO: <ONEOFOUREMAILS@gmail.com>
DATA
From: Da Boss <NAME@AURLIWILLGIVEYOU.com>
To: The Dude <ONEOFOUREMAILS@gmail.com>
Subject: Totally legit offer for The Dude
Hello Mr The Dude,
I would like to give you lots of free money. Please click this not
at all suspicious link to claim it:
Best,
Da Boss
Totally Legitimate Company, Inc.
.
QUIT

Platformer Python Code


import turtle, random,time
map = input('Select a map from 1-8 or press 9 for random map')
max = 8
map = int(map)
if map == max:
  map = random.randint(1,max-1)
if map == 1:
  mapName = "v"
if map == 2:
  mapName = "d"
if map == 3:
  mapName = "m"
if map == 4:
  mapName = "a"
if map == 5:
  mapName = "j"
if map == 6:
  mapName = "e (1)"
if map == 7:
  mapName = "t"
if map == 8:
  mapName = "l"

charlist = ['rainbowbob','Kataniguana','yurp','REEE','Zhane','america','lightning','Goku','Symmetra','Dva','Junkrat2','Mercy','soldier']
print(charlist)
char1 = int(input('Player 1 Choose a character from the list.'))
char2 = int(input('Player 2 Choose a character from the list.'))
char1 = charlist[char1-1]
char2 = charlist[char2-1]

you = turtle.Turtle()
you.penup()
them = turtle.Turtle()
them.penup()
ball = turtle.Turtle()
screen = turtle.Screen()
screen.setup(400, 400)
direction = "up"
screen.bgpic(mapName+".png")
screen.addshape(char1+".png")
you.shape(char1+".png")
screen.addshape(char2+".png")
them.shape(char2+".png")
move_speed = 10


##MOVEMENT CODE FOR SPRITE 1 (YOU)
def up():
  xold = you.xcor()
  yold = you.ycor()
  you.sety(you.ycor()+move_speed)
  if you.ycor()> 200:
    you.sety(-200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def down():
  xold = you.xcor()
  yold = you.ycor()
  you.sety(you.ycor()-move_speed)
  if you.ycor()< -200:
    you.sety(200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def left():
  xold = you.xcor()
  yold = you.ycor()
  you.setx(you.xcor()-move_speed)
  if you.xcor()< -200:
    you.setx(200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def right():
  xold = you.xcor()
  yold = you.ycor()
  you.setx(you.xcor()+move_speed)
  if you.xcor()> 200:
    you.setx(-200)
  print(str(you.xcor())+','+str(you.ycor()))
  findbox(xold,yold)
def jump():
  up()
  up()
  up()
  time.sleep(0.1)
  down()
  down()
  down()
  

##MOVEMENT CODE FOR SPRITE 2 (THEM)
def up2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.sety(them.ycor()+move_speed)
  if them.ycor()> 200:
    them.sety(-200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def down2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.sety(them.ycor()-move_speed)
  if them.ycor()< -200:
    them.sety(200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def left2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.setx(them.xcor()-move_speed)
  if them.xcor()< -200:
    them.setx(200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def right2():
  xold2 = them.xcor()
  yold2 = them.ycor()
  them.setx(them.xcor()+move_speed)
  if them.xcor()> 200:
    them.setx(-200)
  print(str(them.xcor())+','+str(them.ycor()))
  findbox(xold2,yold2)
def jump2():
  up2()
  up2()
  up2()
  time.sleep(0.1)
  down2()
  down2()
  down2()
  
  
  
def findbox(xold, yold):
  if map == 1:
    coords = [
    [30,90,90,180],
    [10,120,30,70],
    [160,200,-10,70],
    [-160,-20,20,70],
    [-200,-180,20,80],
    [-80,-10,100,180],
    [-170,-120,100,200],
    [-190,-100,-80,-30],
    [-40,10,-90,-40]]
  if map == 7:
     coords = [
    [10,180,-110,-70],
    [10,180,-160,-120],
    [10,180,-180,-160],
    [-80,0,-180,-60],
    [-190,-90,-170,-60],
    [120,200,70,200],
    [20,70,80,190],
    [-160,-20,120,190],
    [-170,-120,70,100],
    [-120,-80,70,100],
    [-70,-30,70,100]]


  sprites = [you, them]
  for i in sprites:
    for j in coords:
      if i.xcor() > j[0] and i.xcor() < j[1]: 
        if i.ycor() > j[2] and i.ycor() < j[3]:
          print('you are in the box')
          i.setx(xold)
          i.sety(yold)
   
def fly(ball):
  global direction
  ball.hideturtle()
  ball.setx(you.xcor())
  ball.sety(you.ycor())
  ball.pendown()
  if direction == "up":
    ball.sety(200)
  if direction == "down":
    ball.sety(-200)
  if direction == "left":
    ball.setx(-200)
  if direction == "right":
    ball.setx(200)
  ball.penup()
  ball.showturtle()

you.penup()
you.speed(0)
you.home()
you.left(90)

them.penup()
them.speed(0)
them.home()
them.left(90)

screen.onkey(up, "Up")
screen.onkey(down, "Down")
screen.onkey(left, "Left")
screen.onkey(right, "Right")
screen.onkey(jump,"Space")

screen.onkey(up2, "w")
screen.onkey(down2, "s")
screen.onkey(left2, "a")
screen.onkey(right2, "d")
screen.onkey(jump2,"x")
screen.listen()

GPS Code for USB Receiver

import serial
gpsPort = "/dev/ttyACM0"
gpsSerial = serial.Serial(gpsPort, baudrate = 9600, timeout = 0.5)

def parseGPS(data):
    gps = data

    try:        
        if gps[2:8] == "$GNGGA":
            gps = gps.split(",")

            timeHour = (int(gps[1][0:2]) - 4) % 24
            timeMin = int(gps[1][2:4])
            timeSec = int(gps[1][4:6])
            print("Time: " + str(timeHour) + ":" + str(timeMin) + ":" + str(timeSec))

            latDeg = int(gps[2][0:2])
            latMin = int(gps[2][2:4])
            latSec = float(gps[2][5:9]) * (3/500)
            latNS = gps[3]
            print("Latitude:  " + str(latDeg) + "°" + str(latMin) + "'" + str(latSec) + '" ' + latNS)

            longDeg = int(gps[4][0:3])
            longMin = int(gps[4][3:5])
            longSec = float(gps[4][6:10]) * (3/500)
            longEW = gps[5]
            print("Longitude:  " + str(longDeg) + "°" + str(longMin) + "'" + str(longSec) + '" ' + longEW)

            alt = float(gps[9])
            print("Altitude: " + str(alt) + " m")

            sat = int(gps[7])
            print("Satellites: " + str(sat))
        if gps[2:8] == "$GNRMC":
            gps = gps.split(",")

            speed = float(gps[7]) * 1.852
            print("Speed: " + str(speed) + " km/h")
            
            head = float(gps[8])
            print("Heading: " + str(head))
        else:
            gps = ""
    except Exception as error:
        print(error)

    return gps
while True:
    print(parseGPS(gpsSerial.readline()))

Current Combined Code


import os
import picamera
import sense_hat
import time
import yagmail

camera = picamera.PiCamera()
camera.resolution = (1280, 720)
framerate = 5
camera.framerate = framerate
camera.annotate_text_size = 18

senseHat = sense_hat.SenseHat()

gps = "GPS Data"

def annotate():
    timeNow = "Time: " + str(time.strftime("%a %d %b %Y %H:%M:%S", time.localtime()))
    temperatureNow = "Temperature: " + str(round(senseHat.get_temperature())) + " C"
    humidityNow = "Humidity: " + str(round(senseHat.get_humidity())) + "%"
    locationNow = "Location: " +gps
    
    annotation = timeNow + "\n" + temperatureNow + "\n" + humidityNow + "\n" + locationNow
    return annotation

def getPicture(annotation):
    filename = "/home/pi/Pictures/" + str(time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime())) + ".jpg"

    try:
        camera.start_preview()
        time.sleep(5)
        camera.annotate_text = annotation
        camera.capture(filename)
        camera.stop_preview()
    except Exception as error:
        print(error)

    return filename

def getVideo(length):
    filename = "/home/pi/Videos/" + str(time.strftime("%Y-%m-%d@%H:%M:%S", time.localtime())) + ".mp4"
    
    try:
        camera.start_recording("/home/pi/testVideo.h264")

        for index in range(length):
            camera.annotate_text = (annotate())
            time.sleep(1)
        
        camera.stop_recording()
    except Exception as error:
        print(error)

    os.system("ffmpeg -r " + str(framerate) + " -i /home/pi/testVideo.h264 -vcodec copy " + filename)

    return filename

def sendMail(filename):
    receiver = ["yoimgeorge25@gmail.com", "otheremail@gmail.com"]
    body = "Sent at " + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())) + "."

    try:
        gmail = yagmail.SMTP("email@gmail.com", "password")

        gmail.send(
            to = receiver,
            subject = "Paul's Balloon",
            contents = body, 
            attachments = filename
        )
    except Exception as error:
        print(error)

    print("Message sent.")

sendMail(getPicture(annotate()))

Sending Emails in Python

Sending an email in Python with no attachments.

import smtplib, ssl

smtp_server = "smtp.gmail.com"
port = 587  # For starttls
sender_email = "my@gmail.com"
password = input("Type your password and press enter: ")

# Create a secure SSL context
context = ssl.create_default_context()

# Try to log in to server and send email
try:
    server = smtplib.SMTP(smtp_server,port)
    server.ehlo() # Can be omitted
    server.starttls(context=context) # Secure the connection
    server.ehlo() # Can be omitted
    server.login(sender_email, password)
    # TODO: Send email here
except Exception as e:
    # Print any error messages to stdout
    print(e)
finally:
    server.quit() 

Snapping a still image in Python

from picamera import PiCamera
camera = PiCamera()
camera.capture('/home/pi/Desktop/snapshot.jpg')

Raspberry Pi Camera Source

SENDING AN EMAIL WITH AN ATTACHMENT

import email, smtplib, ssl

from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

subject = "An email with attachment from Python"
body = "This is an email with attachment sent from Python"
sender_email = "my@gmail.com"
receiver_email = "your@gmail.com"
password = input("Type your password and press enter:")

# Create a multipart message and set headers
message = MIMEMultipart()
message["From"] = sender_email
message["To"] = receiver_email
message["Subject"] = subject
message["Bcc"] = receiver_email  # Recommended for mass emails

# Add body to email
message.attach(MIMEText(body, "plain"))

filename = "document.pdf"  # In same directory as script

# Open PDF file in binary mode
with open(filename, "rb") as attachment:
    # Add file as application/octet-stream
    # Email client can usually download this automatically as attachment
    part = MIMEBase("application", "octet-stream")
    part.set_payload(attachment.read())

# Encode file in ASCII characters to send by email    
encoders.encode_base64(part)

# Add header as key/value pair to attachment part
part.add_header(
    "Content-Disposition",
    f"attachment; filename= {filename}",
)

# Add attachment to message and convert message to string
message.attach(part)
text = message.as_string()

# Log in to server using secure context and send email
context = ssl.create_default_context()
with smtplib.SMTP_SSL("smtp.gmail.com", 465, context=context) as server:
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, text)

USING YAGMAIL

import yagmail

receiver = "your@gmail.com"
body = "Hello there from Yagmail"
filename = "document.pdf"

yag = yagmail.SMTP('mygmailusername', 'mygmailpassword')
yag.send(
    to=receiver,
    subject="Yagmail test with attachment",
    contents=body, 
    attachments=filename,
)

pip3 install yagmail 🙂
Source