1 of 26

Python- Analog control

CDSID: lvishwan

1

LEVEL -6

2 of 26

viswa

2

7/12/2019

Contents

​

System components

  • power
  • volume
  • screen
  • Com ports
  • Threading
  • Bluetooth connection
  • Wifi connection
  • Py serial
  • Micro controller
  • Micro processor
  • Bluetooth connection
  • Wifi connection
  • Arduino connection

​

3 of 26

VOLUME

​

from ctypes import cast, POINTER

from comtypes import CLSCTX_ALL

from pycaw.pycaw import AudioUtilities, IAudioEndpointVolume

​

devices = AudioUtilities.GetSpeakers()

interface = devices.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None)

volume = cast(interface, POINTER(IAudioEndpointVolume))

​

# Control volume

volume.SetMasterVolumeLevel(-0.0, None) #max

#volume.SetMasterVolumeLevel(-5.0, None) #72%

#volume.SetMasterVolumeLevel(-10.0, None) #51%

​

​

4 of 26

POWER

​

#Shutdown

import os

os.system("shutdown /s /t 1")

​

#Restart

os.system("shutdown /r /t 1")

​

#Lock

os.system("shutdown -l")

(or)

import ctypes

ctypes.windll.user32.LockWorkStation()

​

​

​

​

5 of 26

Screen Brightness

​

import screen_brightness_control as sbc

​

current_brightness = sbc.get_brightness()

print(current_brightness)

​

#set brightness to 50%

sbc.set_brightness(100)

6 of 26

SERIAL PORT

module: pyserial

import serial

import serial.tools.list_ports

import time

from PyQt5 import QtGui,QtCore

from PyQt5.QtWidgets import *

from PyQt5.QtGui import *

from PyQt5.QtCore import *

​

ports = serial.tools.list_ports.comports()

comport=''

for port in ports:

print(str(port))

if 'Arduino Uno' in str(port):

comport=port.name

app = QApplication([])

sit=QWidget()

sit.showMaximized()

​

with serial.Serial(port=comport, baudrate=9600) as serialPort:

while 1:

data = serialPort.readline()

if data:

data=''.join([data.decode('utf-8').rstrip()])

#time.sleep(1)

if data=='8132': sit.hide()

else: sit.show()

app.exec()

7 of 26

import serial

import serial.tools.list_ports

import time

​

from PyQt5 import QtGui,QtCore

from PyQt5.QtWidgets import *

from PyQt5.QtGui import *

from PyQt5.QtCore import *

​

from threading import *

def work1():

ports = serial.tools.list_ports.comports()

comport=''

for port in ports:

print(str(port))

if 'Arduino Uno' in str(port):

comport=port.name

with serial.Serial(port=comport, baudrate=9600) as serialPort:

while 1:

data = serialPort.readline()

if data:

data=''.join([data.decode('utf-8').rstrip()])

#time.sleep(1)

if data=='8132': sit.hide()

else: sit.show()

​

app = QApplication([])

​

sit=QWidget()

sit.showMaximized()

t1=Thread(target=work1)

t1.start()

app.exec()

Threading:

8 of 26

BLUETOOTH

​

import bluetooth

import ctypes

​

target_name = "E0:13:B5:B9:9C:40"

status=False

​

nearby_devices = bluetooth.discover_devices(lookup_names=True)

print(len(nearby_devices))

for bdaddr,name in nearby_devices:

print(bdaddr)

if bdaddr=="E0:13:B5:B9:9C:40":

status=True

break

​

if status is not False:

ctypes.windll.user32.LockWorkStation()

9 of 26

​

import os

import glob

import time

from bluetooth import *

​

server_sock = BluetoothSocket( RFCOMM )

server_sock.bind(("",PORT_ANY))

server_sock.listen(1)

​

port = server_sock.getsockname()[1]

uuid = "94f39d29-7d6d-437d-973b-fba39e49d4ee"

advertise_service( server_sock, "TestServer",service_id = uuid,service_classes = [ uuid, SERIAL_PORT_CLASS ],profiles = [ SERIAL_PORT_PROFILE ])

print ("Waiting for connection on RFCOMM channel %d" % port)

client_sock, client_info = server_sock.accept()

print ("Accepted connection from ", client_info)

​

while True:

try:

req = client_sock.recv(1024)

if len(req) == 0:break

print ("received [%s]" % req)

client_sock.send(‘xyz’’)

except IOError:pass

except KeyboardInterrupt:

print ("disconnected")

client_sock.close()

server_sock.close()

break

10 of 26

import serial

import serial.tools.list_ports

import time

​

ports = serial.tools.list_ports.comports()

comport=''

for port in ports:

print(str(port))

if 'Bluetooth' in str(port):

comport=port.name

print(comport)

​

serialPort = serial.Serial(port=comport, baudrate=9600, timeout=0, parity=serial.PARITY_EVEN, stopbits=1)

while 1:

​

data = serialPort.readline()

if data:

x=str(data).replace("b'",'').replace('\\r\\n\'','')

print(x)

## if x=='disconnect':break

## serialPort.write(b'Z')

11 of 26

Setting Serial port for bluetooth

​

​

  1. Open Bluetooth Devices .� From the Windows desktop, navigate: Start (Settings) Control Panel (Network and Internet) Bluetooth Devices� If using Windows 8/10, navigate: Right-click Start Control Panel > In the search box, enter "Bluetooth" then select Change Bluetooth settings .
  2. From the COM Ports tab, click Add .
  3. Ensure that "Incoming (device initiates the connection)" is selected then click OK .
  4. Click OK .

​

12 of 26

WIFI

​

# importing the subprocess module

import subprocess

​

# using the check_output() for having the network term retrieval

devices = subprocess.check_output(['netsh','wlan','show','network'])

​

# decode it to strings

devices = devices.decode('ascii')

device s= devices.replace("\r","")

​

# displaying the information

print(devices)

​

13 of 26

Saved network

​

import winwifi

winwifi.WinWiFi.connect('Devil')

​

​

​

import os

wifi_name='Wi-Fi'

def enable():

os.system('netsh interface set interface "'+wifi_name+'" enabled')

​

def disable():

os.system('netsh interface set interface "'+wifi_name+'" disabled')

​

14 of 26

#server.py

import os

from socket import *

​

addr = ("192.168.0.168", 13000)

UDPSock = socket(AF_INET, SOCK_DGRAM)

UDPSock.bind(addr)

print ("Waiting to receive messages...")

while True:

(data, addr) = UDPSock.recvfrom(1024)

print ("Received message: " , data)

if data == "exit":

break

UDPSock.close()

os._exit(0)

​

15 of 26

​

Client connection

import os

from socket import *

​

UDPSock = socket(AF_INET, SOCK_DGRAM)

while True:

data = input("Enter message to send or type 'exit': ")

print(data)

UDPSock.sendto(bytes(data,'utf-8'), ("192.168.0.168", 13000))

if data == "exit":

break

UDPSock.close()

os._exit(0)

16 of 26

pyautogui.size()

pyautogui.position()

pyautogui.moveTo(100, 200)

pyautogui.move(0, 50)

​

pyautogui.click()

pyautogui.click(x=100, y=200)

pyautogui.click(button='right')

pyautogui.click(button='right', clicks=3, interval=0.25)

​

pyautogui.scroll(10)

pyautogui.scroll(10, x=100, y=100)

pyautogui.hscroll(10)

​

wins=pyautogui.getWindowsWithTitle('')

win=wins[0]

win.title

win.activate()

win.maximize()

win.minimize()

win.close()

pyautogui.hotkey('ctrl', 'g')

pyautogui.write('a2')

pyautogui.press('enter')

pyautogui.write('Hello world!')

pyautogui.hotkey('ctrl', 'f')

pyautogui.write('Hello world!')

17 of 26

Location

​

import geocoder

g = geocoder.ip('me')

print(g)

print(g.latlng)

18 of 26

19 of 26

Micro controller

-Arduino

-C++

20 of 26

Arduino:

​

  • micro controller
  • converts analog to digital
  • types: uno/nano/micro,......
  • C++ used
  • Auto start
  • External programing

Raspberry pi:

​

  • microprocessor
  • converts analog to digital
  • types: A,B,C,...
  • python used
  • boot required
  • Internal programing

21 of 26

Arduino:

​

IR program

c++:

#include<IRremote.h>

IRrecv irrecv(11);

decode_results results;

void setup()

{Serial.begin(9600);

irrecv.enableIRIn();

digitalWrite(13, HIGH);}

void loop(){

if (irrecv.decode(&results))

{Serial.println(results.value,HEX);

irrecv.resume();}

delay(100);

}

Arduino:

​

Connection

​

22 of 26

#include <IRremote.h>

const int RECV_PIN = 2;

IRrecv irrecv(RECV_PIN);

decode_results results;

void setup()

{

Serial.begin(9600);

irrecv.enableIRIn();

irrecv.blink13(true);

}

​

void loop() {

if (irrecv.decode(&results)) {

if (results.decode_type == NEC) {

Serial.print("NEC: ");

} else if (results.decode_type == SONY) {

Serial.print("SONY: ");

} else if (results.decode_type == RC5) {

Serial.print("RC5: ");

} else if (results.decode_type == RC6) {

Serial.print("RC6: ");

} else if (results.decode_type == UNKNOWN) {

Serial.print("UNKNOWN: ");

}

Serial.println(results.value, HEX);

irrecv.resume();

}

}

23 of 26

#include <IRremote.h>

​

const byte IR_RECEIVE_PIN =2;

​

void setup()

{

Serial.begin(115200);

Serial.println("IR Receive test");

IrReceiver.begin(IR_RECEIVE_PIN, ENABLE_LED_FEEDBACK);

}

​

void loop()

{

if (IrReceiver.decode())

{

Serial.println(IrReceiver.decodedIRData.command, HEX);

IrReceiver.resume();

}

}

24 of 26

#include <IRremote.h>

IRsend irsend;

void setup() {}

void loop() {

irsend.sendRC5(0x1FC1, 32);

delay(5000);

}

25 of 26

LCD 16x2 with I2C

​

#include <Wire.h>

#include <LiquidCrystal_I2C.h>

​

LiquidCrystal_I2C lcd(0x27,16,2); // set the LCD address to 0x27 for a 16 chars and 2 line display

​

void setup()

{

lcd.init(); // initialize the lcd

lcd.backlight();

Serial.begin(9600);

}

​

void loop()

{

if (Serial.available()) {

delay(100);

lcd.clear();

while (Serial.available() > 0) {lcd.write(Serial.read());}

}

}

26 of 26

MULTI SERIAL (IR/bluetooth/lcd)

​

#include<IRremote.h>

#include <SoftwareSerial.h>

#include <Wire.h>

#include <LiquidCrystal_I2C.h>

​

//ir- out=2

//bluetooth-rx=tx;tx=rx

//i2c-a4=sda;a5=scl

​

LiquidCrystal_I2C lcd(0x27,16,2);

SoftwareSerial blueseial(0, 1);

IRrecv irrecv(2);

decode_results results;

​

void setup()

{Serial.begin(9600);

blueseial.begin(9600);

irrecv.enableIRIn();

lcd.init();

lcd.backlight();

lcd.println("welcome");

}

void loop(){

if (irrecv.decode(&results))

{Serial.println(results.value,HEX);

blueseial.println(results.value,HEX);

lcd.clear();

lcd.println(results.value,HEX);

irrecv.resume();}

delay(100);

}