Skip to main content

Computer Hack with Python and Arduino



For some unknown reason PC's are dumber than smartphones. This device does help to make PC's smart by adding sensor and automation.
As you might have noticed, computer's don't have any system to control brightness automatically. So I made a little device to save me from the labor.

Components:



Arduino Pro Mirco -1x
10k Ohm Resistor - 1x
LDR - 2x 
The PCB from PCBWay

Principle - How It works:

It's always good to discuss about what we are making before jumping. A little theory is good enough to jump start.

I needed some kind of sensor to detect light intensity. LDR or light dependent resistor is best suited for that. LDR will face the person (just like phones sensor face front/person) and get light intensity data. The data will be read by Arduino. That's analog data ranging from 0 to 1024.

If we map the values (0 - 1024) we can control brightness. I tried using Arduino 'keyboard' library to press function buttons using Arduino. That doesn't work and it also freezes hardware keyboard (as the pc knows keyboard is already working).

So I am sending the sensor data to a python program that runs on the PC. And python does the rest, I mean controlling brightness.

Now, let's start making

Making and Testing Circuit/concept:




To prove my concept I first made the circuit in bread board. And wrote a simple program to output the sensor data (light intensity data) over serial monitor of Arduino.

Here's the program that I wrote (download from github)-

// define sensor pin
int sensor_pin = A3;

void setup() {
  // set things here
  Serial.begin(9600);  // init serial communication at 9600 bps
}

void loop() {
  // mainloop
  int sensorValue = analogRead(sensor_pin); // read the input on analog pin A3:
  Serial.println(sensorValue);              // send data over serial
  
  delay(200);                               // a little delay to make things work better
}

And I got some output data over serial. The data ranged from 0 to 1024 (in theory). But in practical, no LDR is perfect (not even on same batch). So I got data from 0 to 950 or something. Still that works. Doesn't matter that much in my application.

So it was a successful test and now I can proceed to next.


PCB:






I used the same circuit on easyEDA and designed a PCB (Printed Circuit Board). You can see that I used two sensors, actually that's just for design purpose. With two LDR it kind of looks like a snail. LDR_L is the LDR that is not being used.

Then I fabricated the PCB from PCBWay.com. PCBWay is one of the best and my favorite PCB manufacturer. With just 5$ I can get 10 PCB's! Anyway, I used their quick order page followed by quick order pcb section, uploaded my PCB and chose color. That's it! I think quick-order section is a blessing for all of us who don't know much, and just want to get it done. Get the PCB from here.

I used just black earlier, it was so shiny I tried matte black this time. After waiting for around 3-4 days, I got the beautiful PCB's. The quality is as always amazing. The pads, solder mask, silkscreen is just as perfect as they could be. I think I fell in love with matte black.


Soldering:



Now it's time to solder thing in place. It's simple as not much components are there. Soldered everything and made sure I did not inhale the smoke of soldering iron.

I used female headers as I am a plug and play guy. You can just solder the Arduino board itself on the board.

Caution: DO NOT INHALE SOLDERING IRON SMOKE! IT MAY CAUSE CANCER!

Code (Arduino):

Now it's time to upload the program of Arduino. Arduino uses Serial communication to send data to PC.

First of all I defined the sensor pin, the pin of Arduino where the sensor inputs data.

// define sensor pin
int sensor_pin = A3;<br>

In setup function I started serial communication with a buad rate of 9600. Setup function runs only once every time we power the Arduino board.

void setup() {
  // set things here
  Serial.begin(9600);  // init serial communication at 9600 bps
}<br>

Then in mainloop it gets data and sends over serial. A little delay of 200ms is kept to make it work smoothly.

void loop() {
  // mainloop
  int sensorValue = analogRead(sensor_pin); // read the input on analog pin A3:
  Serial.println(sensorValue);              // send data over serial
  
  delay(200);                               // a little delay to make things work better
}

Here is the complete code. Copy from below or download from here.

/*  Computer Hack! 
    Brightness Controller

    (C) License: GPL3-General Public License

    author: ashraf minhaj
    mail  : ashraf_minhaj@yahoo.com
*/

// define sensor pin
int sensor_pin = A3;

void setup() {
  // set things here
  Serial.begin(9600);  // init serial communication at 9600 bps
}

void loop() {
  // mainloop
  int sensorValue = analogRead(sensor_pin); // read the input on analog pin A3:
  Serial.println(sensorValue);              // send data over serial
  
  delay(200);                               // a little delay to make things work better
}

Opened Arduino.ide and uploaded the program to my Arduino board.


Python Program (For PC):

As we discussed earlier, Arduino sends data to Arduino and python does the rest. So I wrote a simple python script.

Anyway, If you don't have python installed install latest version from here. While installing make sure you have checked the box that says 'add python to environment variable path'.

Okay then I opened terminal and installed two libraries, Pyserial and screen-brightness-control using these commands ($ signs are to denote them as terminal command, copy without them)-

$ pip install pyserial
$ pip install screen-brightness-control<br>

After installing that I wrote the whole code. But let's break it to you guys a bit.

Here I import libraries to use them. 'serial.tools.list_ports' is needed to detect Arduino board automatically.

# import necessary libraries
import serial                                     # for serial communication
import serial.tools.list_ports                    # to get Arduino port automatically
import screen_brightness_control as brightness    # to control brightness

Then I declare buad rate and port no. Port is automatically detected so I kept it as empty string. But for my board, buad rate is 9600

BUAD_RATE = 9600                                  # Pro Micro's buad rate is 9600 
PORT      = ""

This section gets usb ports automatically and tries to connect with Arduino

# get sender device port automatically
serial_ports = list(serial.tools.list_ports.comports())  # get list of ports
for s_port in serial_ports:                              # iterate through all ports
    if 'Arduino Micro' in s_port.description:            # look for Pro Micro board
        PORT = str(s_port[0])                            # select first found board and
        break                                            # proceed

# connect with sender device
sender = serial.Serial(PORT, BUAD_RATE)<br>

This is the function that converts Arduino data (from 0 to 1024) into %data - from 0 to 100. It's called mapping. Python map function does something else, so I had to write it (took some help from internet though).

def map_value(value, in_min=0, in_max=1024, out_min=0, out_max=100):
    """ To map values. Arduio sends values from 0 to 1024. My goal
    is to make them in between 0 to 100."""
    return int((value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)

The rest of the code just makes sure that brightness stays at light intensity level

# mainloop
while 1: 
    # convert byte data into string then integer
    sensor_value = int(sender.readline().decode("utf-8"))  # get data
    final_value = map_value(value=sensor_value)            # map value (brightness in percentage)
    #print(sensor_value)
    print(final_value)
    brightness.set_brightness(final_value)                 # set brightness

# close port properly so that others can use it
sender.close()<br>

Anyway, it's always best to close something you opened after use, whether it's conversation or port.

Now, I opened my favorite python editor and ran the program. Download the full program from github.

""" Computer Hack! 
    Brightness Controller

    (C) License: GPL3-General Public License

    author: ashraf minhaj
    mail  : ashraf_minhaj@yahoo.com
"""

""" libraries -
$ pip install pyserial
$ pip install screen-brightness-control
"""

# import necessary libraries
import serial                                     # for serial communication
import serial.tools.list_ports                    # to get Arduino port automatically
import screen_brightness_control as brightness    # to control brightness

# device buadrate (bit per second)
# (change buadrate according to your need)
BUAD_RATE = 9600                                  # Pro Micro's buad rate is 9600 
PORT      = ""

# get sender device port automatically
serial_ports = list(serial.tools.list_ports.comports())  # get list of ports
for s_port in serial_ports:                              # iterate through all ports
    if 'Arduino Micro' in s_port.description:            # look for Pro Micro board
        PORT = str(s_port[0])                            # select first found board and
        break                                            # proceed

# connect with sender device
sender = serial.Serial(PORT, BUAD_RATE)

def map_value(value, in_min=0, in_max=1024, out_min=0, out_max=100):
    """ To map values. Arduio sends values from 0 to 1024. My goal
    is to make them in between 0 to 100."""
    return int((value - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)

# mainloop
while 1: 
    # convert byte data into string then integer
    sensor_value = int(sender.readline().decode("utf-8"))  # get data
    final_value = map_value(value=sensor_value)            # map value (brightness in percentage)
    #print(sensor_value)
    print(final_value)
    brightness.set_brightness(final_value)                 # set brightness

# close port properly so that others can use it
sender.close()

Plug and Play:



Download the program from github. Connect the device to your PC using an USB cable, run the Python program and see the magic!!


Comments

Popular posts from this blog

Make a Smart Phone Controlled Robotic Arm ! Arduino DIY.

Making ROBOT ARMs is very popular and fun among hobbyists, but it's not that easy to control a ROBOT ARM. So today we'll be making a robot arm that can be controlled using just your Android Smartphone or tablet. Good news is, you just need to program the Arduino, the App is already available to download for free. Step 1: Parts You'll Need 2 More Images Servo motor 4x (I'm using micro servo Sg90 but any model or size is okay) you can use upto 5 servo for this robot arm, I've only 4, so I'm using them. sliced piece of Card Board - to make the body. USB OTG (on the go) [pic3 & 4- all the same] And of course a Arduino board (any board) And a few jumpers to make the connection And a 9v battery to power the servo motors. Step 2: Making the Robot Arm (THE BODY) Now in here I'm actua...

Make a Smart Humanoid Talking Robot- MOFIZA.

This Robot - Mofiza - (weird name) Can SEE , TALK and REACT to her surroundings. Before I proceed watch the video: Ever since I've seen making talking robots I saw that people actually use other development boards rather than Arduino to make talking robots. But it's completely possible to make a Humanoid robot with Arduino who can talk and add a lot of servos to make it move. So lets begin: Step 1: Parts You'll Need Arduino Pro mini (5v 16 Mhz) [any board is good but i've used this to make it small) Female header pins for connecting on pcb Male header pins Vero Board to make the circuit Sd card TF module (to make it talk) micro sd card (not more than 2GB) 3x IR proximity sensor 3x servo motor (I've used micro servo sg90) Cardboard to make the body Step 2: Connecting IR Sensor and the Body Make a...

Make AI Assistant Robot with Arduino and Python

Introduction: We all are familiar with ‘Jarvis’ AI assistant robot from “Iron Man’ movies and Marvel series. It has always been a dream of programmers to make something on their own. I will today show a simple way to make such an assistant using Python programming. Moreover, I will also make a physical avatar of that robot, so that whenever we talk to the robot, it can do some movements. That will be more amazing than just a software robot. Because if it has a body, it is cool. So today we will learn to use both Arduino and Python programming to make an AI robot which can control your computer and have a little chit chat with you. Let’s hop in guys! Why I named the robot ‘Jaundice’? Because I painted it yellow, very very yellow!   Parts: Electronics - Arduino Nano – 1x Micro Servo Sg90 – 3x Ultra Sonic Sensor HCsr04 – 1x Body – PVC sheet (preferably white, better for coloring, I used blue one) Servo wheel (for the stand) Tools -  Cutter knife Scisso...

Arduino Automated Parking Garage

An Arduino Automated Car Parking System that is too easy and too fun to make. When a car arrives it shows the number of empty slots (if available) and then opens the gate. if there is not any empty slot then the gate does not open.  Amazing thing is that the whole project can just be POWERED using a POWER BANK!! Watch the video for the full tutorial. Note: you can use display instead of my hand made led sign display. Now lets get started. Step 1: Parts Arduino  - any board Infrared proximmity sensor  (pic 2 & 3 - both are functional) 330r resistor some  LED 's Servo motor  - any model or size you wish. Step 2: Making the LED Display To make this  LED display  I have used a piece of bredboard then soldered the LED's and the 330r resistor. Then j...

Problems using PIR sensor?? Always HIGH? DELAY? Solution is here.

PIR sensor When I was working on a project "controlling home appliances using just a wave of hand" I had used a PIR sensor and found some issues: PIR doesn't work properly when starts. PIR output value is always 1. It some times doesn't read motions. Now those are three Common and Unavoidable problems of a PIR sensor. So what would we do? I assume you know what a PIR sensor is and I'll just try to give a solution to the problems so that you can use PIR in your project efficiently, also I've added a code below on how to solve that problem. As I have mentioned earlier those are Common and Unavoidable,  keep 3 issues in mind: After powering - PIR sensor needs 1 minute to function For that 1 minute the OUTPUT is always HIGH. When a motion is detected it'll take 5 to 7 seconds to detect motion again. SOLUTION: After powering - PIR sensor needs 1 minute to function:  which means when you'll power a PIR sensor it wi...

Control Anything Over Internet / WiFi. IOT Light Switch_ NodeMCU ESP8266 .

Parts: NodeMCU ESP8266  WiFi Development Board LED 330r resistor Android app Download the app from Below , To Upload code to NodeMCU using Arduino.ide Update Arduino.ide (desktop app) start Arduino app goto  Files > Preferences  Then  paste the link  then press  ok.    http://arduino.esp8266.com/stable/package_esp8266com_index.json goto  Tools>Boards> Board Manager  then wait untill it finds ESP8266 properties Scroll down and  click install Then Restart the Arduino App. Now you can upload Code in C / C++ to NodeMCU ESP8266 using Arduino.ide Getting IP Address Code T o get the IP Address (Internet Protocol Address) Upload this Code and open serial monitor. #include <ESP8266WiFi.h> const char* ssid="WIFI name"; const char* password = "WIFI PASSWORD"; int ledPin = 13; void setup() { pinMode(ledPin,OUTPUT); digitalWrite(ledPin,LOW); Serial.begin(115200); Serial.print...

How to use ServoTimer2 Library with Arduino- full tutorial.

Introduction I've been trying to make a humanoid robot  MOFIZA -Arduino Talking Humanoid Robot.  recently- which means dealing with Servo motors. Everything worked just as fine just before I tried to make the robot TALK. When I needed to use the TMRpcm library. But there's some libraries like #TMRpcm .h #VirtualWire .h are libraries that use the Timer1 of Arduino. It appears that you can't use two devices simultaneously where both use the same timer...So, if my robot talks- the servos don't work. Because The Servo.h and the TMRpcm both works on Arduino TImer1. Which is a mess. If you want to make both of them work you have to use another library for servos. Which is ServoTimer2 library? This uses the Timer2 on Arduino...Unfortunately on internet I haven't found any tutorials to understand how this ServoTimer2 library actually works, and how to use it in code. So, I've decided to make a tutorial so that people like me can understand better. We'll be u...