Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

2017/08/05

Python - Date Time Comparison

This post is about how to compare system time against a pre-defined time.

1
2
3
4
5
6
7
8
9
import datetime
#print datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
str_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print str_time

if "09:00" in str_time:
   print "True"
else:
   print "False"

References:

Python - How to get current date time and format its output
http://wei48221.blogspot.tw/2017/03/python-how-to-get-current-date-time-and.html

How to determine whether a substring is in a different string
https://stackoverflow.com/questions/7361253/how-to-determine-whether-a-substring-is-in-a-different-string

2017/03/17

Python - How to get current date time and format its output

This is a quick summary of how to get the current date and time and format its output in Python.

The Code

import datetime
print datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

The Result


Reference:

2016/11/23

Python list operations examples

Here is the sample code for displaying, adding, removing contents from a list in Python.

2016/11/22

What is the difference between json.dumps and json.loads?

This post is about the difference between json.dumps and json.loads.

JSON.DUMPS - takes an json object and produces a string.

Python Script

How to convert string data into JSON object and extract data from it

This post is about how to convert string data into JSON object and extract data from it

Python Script

2016/10/31

Google Drive API - How to find file id by filename and download non Google Doc files to local storage using Python

This tutorial is based on Google Drive API v3 and Python 2.7.9.

The code below allows its user to specify the name of the file to be searched for on his/her own Google Drive. Once the file is found, the user will then be prompted on whether to download the file to the local storage or not. The download is limited to non Google Doc files. For Google Doc files, please refer to the sample code at http://wei48221.blogspot.tw/2016/10/google-drive-api-uploading-downloading.html.

2016/10/26

PyDrive Quick Overview - Authentication and File Listing - PyDrive vs Drive API Python

I came across PyDrive (https://pythonhosted.org/PyDrive/index.html) while trying to learn how to use Python to access Google Drive via Google Drive API. For someone struggling to understand how to use the Google Drive API, I think it's a godsend to have PyDrive..

OAuth2 authentication

Using PyDrive

1
2
3
4
from pydrive.auth import GoogleAuth

gauth = GoogleAuth()
gauth.LocalWebserverAuth() # Creates local webserver and auto handles authentication.

2016/10/25

2016/10/24

Google Drive API: Uploading Files And Downloading (Exporting) Google Doc Files Using Python

This is a quick note about the Google Drive API: Uploading & Downloading Files sample at https://youtu.be/-7YH6rdR-tk.

The original Python script can be downloaded from http://wescpy.blogspot.tw/2015/12/google-drive-uploading-downloading.html.

When using the v2 version API, the 'hello.txt' can be uploaded and converted into Google Doc format and stored on my Google Drive. However, the conversion to PDF and download the file to my local disk part isn't working.

Python Script - v2 version API

Notes on the common code section for accessing Google APIs using Python

This post contains my notes after watching the 2 videos below.

Google Drive API: Uploading & Downloading Files
https://youtu.be/-7YH6rdR-tk

Accessing Google APIs: Common code walkthrough
https://youtu.be/h-gBeC9Y9cE?list=PLOU2XLYxmsILOIxBRPPhgYbuSslr50KVq

The Common Code Section

Below are the first 21 lines of code for uploading and downloading files using Google Drive API. They are the common code (with minor changes to the parameters in Line 14 - SCOPE and Line 21 - DRIVE) needed for accessing Google APIs.

Notes about Google Drive API Python Quickstart example

Here are some notes about the Python Quickstart example given by Google which I think will be useful for newbie like me.

https://developers.google.com/drive/v3/web/quickstart/python.


2016/08/28

Collection of Python Programming Tips

Below is a list of Python programming tips which I consider useful for a newbie like me. More will be added to the list as I venture further into this language.

Sending / Reading E-Mail

Raspberry Pi - How to email CPU temperature using python
http://wei48221.blogspot.tw/2016/08/raspberry-pi-how-to-email-cpu.html

How to programmatically read e-mails from the Gmail server using Python and IMAP protocol
http://wei48221.blogspot.tw/2016/08/how-to-programmatically-reads-e-mail.html

String

Python: How to determine whether a substring is in a different string
http://stackoverflow.com/questions/7361253/python-how-to-determine-whether-a-substring-is-in-a-different-string

Converting integer to string in Python?
http://stackoverflow.com/questions/961632/converting-integer-to-string-in-python

Formatting

How to print without newline or space?
http://stackoverflow.com/questions/493386/how-to-print-without-newline-or-space

On-Line Learning Resources

Learn Python The Hard Way
https://learnpythonthehardway.org/book/preface.html

Learn Python Through Public Data Hacking

Delete File 

Python Delete/Remove a File If Exists On Disk
https://www.cyberciti.biz/faq/python-delete-remove-file-if-exists-on-disk/

2016/08/24

How to use the UART of Raspberry Pi for wireless communication - part 2

This is a quick summary of how to connect Raspberry Pi to a 433MHz Serial to Wireless module (HC-11 / HC-12) and how to program the Pi using Python to receive incoming data.

Before the Pi's UART can be used for this purpose, there are some preparations that need to be made. Please refer to http://wei48221.blogspot.tw/2016/08/how-to-use-uart-of-raspberry-pi-for_99.html for info. on how to prepare the Pi's UART.

Schematic:




Checking the version of the installed Python.

Issue "python --version".


Install pySerial

Issue "sudo apt-get install python-serial".

Other preparation works

Create a folder call "python" (if it hasn't been created) to keep the python programs.

1. Issue "mkdir python" to create the python folder.

2. Issue "ls" to make sure the folder is created.


Change working directory to the newly created python folder.

"cd python"

Launch nano text editor and name the file created "serial_read.py"

"nano serial_read.py"

Code

Type in the code between the 2 dash lines.
----------------------------------------------------------------------------------------------------------------------
#!/usr/bin/env python

import time
import serial

ser = serial.Serial(
         port='/dev/ttyAMA0',
         baudrate = 9600,
         parity=serial.PARITY_NONE,
         stopbits=serial.STOPBITS_ONE,
         bytesize=serial.EIGHTBITS,
         timeout=1
         )
counter=0
   
while 1:
         x=ser.readline()
         print x
---------------------------------------------------------------------------------------------------------------------
IMPORTANT!!

Watch out for the indent as python uses spacing at the start of the line to determine when code blocks start and end (http://stackoverflow.com/questions/1016814/what-to-do-with-unexpected-indent-in-python).

Save the program.
Ctrl-X to exit the editing mode, then "Y" to save the file.

Running the program 

"python serial_read.py".

Here I have an Arduino Uno with some sensors and a HC-11 module attached to it. Whenever a sensor is triggered, the Uno will send a message out via the HC-11 module. The message is picked up by the "serial_read.py " running on the Raspberry Pi and displayed in the PuTTY terminal.


When we are done with the program, use Ctrl-C to stop its execution.

References:

Using UART on Raspberry Pi – Python
https://electrosome.com/uart-raspberry-pi-python/

Arduino Lesson 17. Email Sending Movement Detector
https://learn.adafruit.com/arduino-lesson-17-email-sending-movement-detector/python-code

Read and write from serial port with Raspberry Pi
http://www.instructables.com/id/Read-and-write-from-serial-port-with-Raspberry-Pi/

---------------------------------------------------------------------------------------------------------------------

Product Offered:

Note, the 2 modules listed here have been tested to work with Arduino Uno and Raspberry Pi.

433MHz Serial RF Module -- HC-11


- Price: US$6.99/ea;
- Item Location: Taipei, Taiwan;
- Range: ~100 Meters (direct line of sight without obstruction);
- Frequency: 433MHz;
- Operating Voltage: DC 3.3V ~ 5V (when feeding DC 3.3V to the VCC of the module, the module works with Raspberry Pi without the need for level shifting / voltage division);
- Serial baud rate: 1.2Kbps to 115.2Kbps (default 9.6Kbps);
- Interface protocol: UART/TTL;
- At least 2 HC-11 modules are needed to form a complete wireless link.

IMPORTANT - THIS MODULE DOESN'T WORK WITH THE 433MHz Serial RF Module HC-12.

-------------------------------------------------------------------------------------------------------------------------

433MHz Serial RF Module -- HC-12
- Price: US$7.99/ea;
- Item Location: Taipei, Taiwan;
- Range: ~1000 Meters (@ 5000bps) direct line of sight without obstruction);
- Frequency: 433MHz;
- Operating Voltage: DC 3.3V ~ 5V (when feeding DC 3.3V to the VCC of the module, the module works with Raspberry Pi without the need for level shifting / voltage division);
- Serial baud rate: 1.2Kbps to 115.2Kbps (default 9.6Kbps);
- Interface protocol: UART/TTL;
- At least 2 HC-12 modules are needed to form a complete wireless link.

IMPORTANT - THIS MODULE DOESN'T WORK WITH THE 433MHz Serial RF Module HC-11.

How to purchase:

Leave your message in the comment section below or send me an e-mail. I will contact you for detail.

2016/08/23

How to use the UART of Raspberry Pi for wireless communication - part 1

This post is the 1st part of a 2-part series on how to use the UART of Raspberry Pi for wireless communication.

This post is mainly about how to prepare the UART of Raspberry Pi. The Pi used is Raspberry Pi 1 Model B and the OS used is Raspbian Jessie.

For info. on the python environment, python serial, and the actual code, please refer to the post at http://wei48221.blogspot.tw/2016/08/how-to-use-uart-of-raspberry-pi-for_30.html.

Raspberry Pi 1 Model B




Raspberry Pi 1 Model B Specs.

Raspberry Pi 1 Model B Pin Map (from Sparkfun)


Step 1 - Check to see if the UART pins (GPIO 14 and 15) are configured as serial console which outputs all the kernel data during boot.

Issue the command "dmesg | grep tty" and observe the output.

The line with red underline indicates that the UART is configured as serial console.


Note, if you are using Pi model 3 do not use /dev/ttyAMA0 because it's assigned to bluetooth, use /dev/ttyS0 instead.

Step 2 - Free up the UART Pins (GPIO 14, 15)

Run the configuration command and follow the instructions below

sudo raspi-config

Select "9 Advanced Options".


Select "A7 Serial".


Select "No".


The serial interface is now disabled.


Select "<Finish>'.


Select <Yes> to reboot the system.


After the system is reboot, enter the command "dmesg | grep tty" to check whether the UART is no longer configured as serial console.

**IMPORTANT - for Raspbian Jessie - missing /dev/ttyAMA0**

When you disable the serial port for boot using raspi-config, the serial port is also disabled for ANY use. To fix this you MUST set "enable_uart=1" in /boot/config.txt.

This is really a bug in raspi-config.

/dev/ttyAMA0 is missing in the below output result after running "dmesg | grep tty" after system reboot.


Note, reference to this issue can be found at https://www.raspberrypi.org/forums/viewtopic.php?f=66&t=151922.

How to set "enable_uart=1" in /boot/config.txt

First, issue "sudo nano /boot/config.txt"

Second, scroll down to find the line "enable_uart=0".


Third, change it to "enable_uart=1", followed by pressing Ctrl-X, followed by pressing Y to save the change and exit the nano editor.


Fourth, issue the "sudo reboot" command to reboot the system.

Fifth, issue the "dmesg | grep tty" command to check for the presence of /dev/ttyAMA0.

From the output result below it's clear that ttyAMA0 is now available and we could move on to the next step.


Step 3 - Verify whether the Pi could send and receive UART data by installing the tool Minicom.

First, install Minicom.

sudo apt-get update
sudo apt-get install minicom

Second, short the Rx and Tx pins on Pi (GPIO 14 and 15) so that it will receive the same data as it transmits.


Third, launch Minicom by issuing the command "minicom -b 115200 -o -D /dev/ttyAMA0". Where, 115200 is the baud rate, ttyAMA0 is the port.


Press Ctrl-A, then Z to bring up the menu. Press E to enable or disable local echo.


When local echo is enabled, you will see 2 identical characters when pressing any key on the keyboard. This mean the UART is working correctly.


References:

Raspberry Pi Serial Communication: What, Why, and a Touch of How
https://jeffskinnerbox.wordpress.com/2012/12/05/raspberry-pi-serial-communication/

Raspberry GPIO
https://learn.sparkfun.com/tutorials/raspberry-gpio

Identifying Your Model of Raspberry Pi
https://www.element14.com/community/docs/DOC-78141/l/identifying-your-model-of-raspberry-pi

Read and write from serial port with Raspberry Pi
http://www.instructables.com/id/Read-and-write-from-serial-port-with-Raspberry-Pi/

Blog of Wolfgang Klenk
https://wolfgangklenk.wordpress.com/

Using UART on Raspberry Pi – Python <-- ***Good Read!!***
https://electrosome.com/uart-raspberry-pi-python/

Using the GPIO Serial port ttyAMA0
https://www.raspberrypi.org/forums/viewtopic.php?f=44&t=17360

Using the UART
http://www.raspberry-projects.com/pi/programming-in-c/uart-serial-port/using-the-uart