Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
  • Women in Engineering

Controlling mouse pointer using Python script and accelerometer

By Varun Kumar

Requirements:

1.     Arduino with Atmega328p

2.     Accelerometer ADXL335

3.    Python 2.7 on your machine

4.    Python libraries: Pyserial and Autopy

Summary

There are many ways of controlling mouse pointer using atmega328p, out of which using a Python script and an Arduino can be considered as the most effective one because of the following reasons:

1)    Python is a common language and comes pre-installed in almost all LINUX distros.

2)    Using python script makes this project compatible to cross platforms, as no fancy software is needed.

3)    Using an Arduino avoids the trouble of making the whole circuit and then connecting it through a USB to TTL converter.

I’ll be using two non-standard libraries viz. Pyserial and Autopy both are freely available and easy to install, just like any non-standard library.  Here I have used a triple-axis accelerometer i.e. ADXL335.

Typical Image of Arduino Uno

 Fig. 1: Typical Image of Arduino Uno

Description:

How I am uploading code into arduino:

f = <source_code’s_file_name>

avr-gcc -g -mmcu=atmega328p -Wall -Os $(f).c -o $(f).elf

avr-objcopy -j .text -j .data -O ihex $(f).elf $(f).hex

sudo avrdude -F  -V -c arduino -p m328p  -P /dev/ttyUSB* -b 57600 -e -U flash:w:$(f).hex

Just type these four commands, in the same order, in your terminal and remember to put the source code’s filename in variable “f”. These commands are for Linux users only.

The first command stores the filename in variable “f”, the second command is used to convert source code to .elf file, the third command is used to convert that .elf file to .hex file which can be uploaded on Atmega328p, and the fourth command is used to upload that .hex file.

Image of Accelerometer Module used in designing mouse pointer

Fig. 2: Image of Accelerometer Module used in designing mouse pointer

Little bit about accelerometer being used

I’m using adxl335  which is a triple-axis accelerometer. It can measure acceleration with a minimum full-scale range of +-3g. It can be used to measure tilt by measuring the static acceleration of gravity or it can measure impact from shock and vibration by measuring dynamic acceleration.

For more details and knowledge you can always look up adxl335  datasheet.

Source Code

This program is an application of ADC and serial communication.

I already did explain ADC here, check it before reading this article.

There are few changes that I made in setup_adc() function and ISR() block.

In setup_adc() function I set the MUX1 bit in ADMUX register in order to start the conversion of value at PORTC2.

In ISR() block, I first store 10-bit value from ADC in a variable. Then check four bits in ADMUX, starting from LSB, depending on these four bits I decide whether 10-bit value is for x,y,z axis.

Then I set the last four bits in ADMUX for the next conversion.

After that a map_constaint() function is called. It is a combination of map() function and constraint function() available in Arduino IDE.

It takes 5 arguments, first is the value to be mapped, second is the lowest value on the original scale, third is the highest value on the original scale, fourth is the lowest value on the secondary scale, the fifth is the highest value on the secondary scale.

Then by using simple maths it linearly maps value from primary scale to secondary scale and then apply constraints on it with respect to the secondary scale.

I’m using uartLibrary.h to send readings from the accelerometer to my laptop using serial communication. I build this library referring this article . After including this library I can use printf() function from stdio.h to send strings from Atmega358p to my laptop.

I’ll put all code files in a .zip folder

For detailed information please check the Source Code.

Explanation of Python Script & Circuit

I’m using two libraries Pyserial and Autopy both of them are freely available.

First I created an object “ser” of “Serial” class and gave two arguments in it

a.    Serial Port: In my case, it is ‘/dev/ttyUSB1’

b.    Baud rate: in my case, it’s 9600

Then in an infinite loop, I put a try & except block because initially trash values are sent from atmega328p.

In try block, I read data being sent over serial port then break it and convert it to integer and store it in an array.

Next, I feed these values from the array to autopy.mouse.move(), it takes two inputs 1st is width and 2nd is the height of your screen both of them in pixels.

Then I print these values on the terminal for debugging purposes.

Image of ADXL335 Accelerometer Chip that controls the Accelerometer Module

Fig. 3: Image of ADXL335 Accelerometer Chip that controls the Accelerometer Module

Explanation of Circuit

As can be seen in images, my accelerometer module don’t have a header pin for ST, and all other i/o pins are in straight line. So instead of using a breadboard for connections I simply placed accelerometer on Analog pins of Arduino which maps to PORTC on atmega328p.

For Vcc and GND I declared PORTC1 and PORTC5 as output and pulled down PORTC1 for GND, pulled up PORTC5 for Vcc.

Now I can simply measure acceleration from x,y,z axis on PORTC2,3,4 respectively.

Getting started with this Project:

There are three files:

1.    main.c contains the source code for atmega328p side of this application.

2.    uartLibrary.h contains definition of all the functions necessary for serial communication

3.    python_serial.py it reads data from serial port and controls the mouse pointer

Place main.c and uartLibrary.h in same directory, and upload the code to atmega328p.

Now, run the python script and BAAMMM!! you are ready to go. Just move accelerometer and you pointer will start moving.

You may also like:


  • 14 IoT Boards to Quick Start Prototyping

  • Variable Frequency PWM(Pulse Width Modulation) signal generation using Timers of…

  • DIY Palm Arduino kit

  • AVR(atmega328p) Library for LCD JHD162A

  • ADC in Atmega328p

Project Source Code

###

#define F_CPU           16000000UL

#include "uartLibrary.h"

#include

#include

#include

#include

 

 

//These values are from my sensors you might have to change it according to your sensor

#define min_x 295 // approx max. value of x I'm getting from my sensor

#define max_x 395 // approx min. value of x I'm getting from my sensor

#define min_y 295 // approx max. value of y I'm getting from my sensor

#define max_y 390 // approx min. value of y I'm getting from my sensor

#define min_z 295 // approx max. value of z I'm getting from my sensor

#define max_z 422 // approx min. value of z I'm getting from my sensor

/*************************************************************************************/

 

#define height_min 0

#define height_max 767

#define width_min 0

#define width_max 1365

 

 

int xRaw=0,yRaw=0,zRaw=0;

void setup_adc();

 

 

int main(void)

{ 

    uart_init();

    stdout = &uart_output;

    stdin  = &uart_input;

   

    DDRC = 0x22;                                //Set Pin5 and Pin7 on arduino as output

    PORTC |= 1<

   

    sei();                                    //Enales global interrupt

    setup_adc();                                    //Setup ADC according to the defined function

             

    while(1)

    {

    }

}

 

 

 

void setup_adc()

{

    ADCSRA |= 1<

    ADCSRA |= 1<

    ADCSRA |=  1<

    ADMUX |= 1<

    //ADLAR=1 for left adjusted result and REFS0=1 with REFS1=0 to use Vcc as reference voltage

    //MUX1=1 because we want to start conversion from PORTC1

    DIDR0 |= 1<

}

 

 

// This function is combination of map and constraint functions

// available in Arduino IDE

int map_contraint(int val, int from_low, int from_high, int to_low, int to_high)

{

    int a = ((to_low - to_high)/(from_low - from_high)*(val - from_low)) + to_low;

    // Above is a simple fromula which LINEARLY maps one set of values on other

    //Three lines under this sets the constraint on the highest and the lowest value obtained from the above formula

    if(a < to_low){return to_low;}

    else if(a > to_high){return to_high;}

    else{return a;}

}

/*********** varun13169 **************/

 

ISR(ADC_vect)

{

    uint8_t adcl = ADCL;                                  //This is an 8-bit varible used to store the value of ADLC

    uint16_t adc_ten_bit_value = ADCH<<2 | adcl>>6;  //This is an 16-bit varible use to store the 10-bit value of left adjusted result

   

    int value_of_mux0= ADMUX & 0x0F; // Retains last four bits of ADMUX,starting fom LSB, 

                                    // used in mapping ADC converted values to xRaw,yRaw,zRaw respectively

 

    /************ For PORTC2 *************/

    if(value_of_mux0==0x02)

    {

             xRaw=adc_ten_bit_value;

             ADMUX &= 0xF0; // Clears last four bits in ADMUX

             ADMUX |= 0x03; // Put the next four bit accrding to the next conversion

             xRaw = map_contraint(xRaw,min_x,max_x,height_min,height_max);

    }

    /*************************************/

   

   

    /************ For PORTC3 *************/

    if(value_of_mux0==0x03)

    {

             yRaw=adc_ten_bit_value;

             ADMUX &= 0xF0; // Clears last four bits in ADMUX

             ADMUX |= 0x02; // Put the next four bit accrding to the next conversion

             yRaw = map_contraint(yRaw,min_y,max_y,-width_max,width_min);

             yRaw = -yRaw;

    }

    /*************************************/

   

   

   

    // This is for z-axis, as Z-out pin is connected to PORTC4,

    // I don't require Z-out but one can easily get it by

    // making some small changes

    /*

    if(value_of_mux0==0x04)

    {

             zRaw=adc_ten_bit_value;

             ADMUX &= 0xF0;

             ADMUX |= 0x02;

    }

    */

 


Circuit Diagrams

Circuit-Diagram-Arduino-Accelerometer-Based-Computer-Mouse

Project Datasheet

https://www.engineersgarage.com/wp-content/uploads/2019/10/codes.zip


Project Video


Filed Under: Arduino, Electronic Projects
Tagged With: Arduino, Atmega328p, python
 

Questions related to this article?
👉Ask and discuss on EDAboard.com and Electro-Tech-Online.com forums.



Tell Us What You Think!! Cancel reply

You must be logged in to post a comment.

HAVE A QUESTION?

Have a technical question about an article or other engineering questions? Check out our engineering forums EDABoard.com and Electro-Tech-Online.com where you can get those questions asked and answered by your peers!


Featured Tutorials

  • Designing Gate Driver Circuit and Switching Mechanism for Modified Sine Wave Inverter – (Part 9/17)
  • Completing Modified Sine Wave Inverter Design with Full Bridge Circuit and Step Up Transformer – (Part 10/17)
  • Designing an Offline UPS – Part (12 /17)
  • How to reduce Switching Time of a Relay – (Part 15/17)
  • Testing MOSFET – (Part 16/17)
  • Driving High Side MOSFET using Bootstrap Circuitry – (Part 17/17)

Stay Up To Date

Newsletter Signup

Sign up and receive our weekly newsletter for latest Tech articles, Electronics Projects, Tutorial series and other insightful tech content.

EE Training Center Classrooms

EE Classrooms

Recent Articles

  • MicroPython – I2C protocol in ESP8266 and ESP3
  • New automotive radar sensor enables reliable in-cabin monitoring system
  • TI breaks ground on 300-mm semiconductor wafer-fabrication plants in Texas
  • New wireless AR Smart Viewer reference design
  • Infineon launches scalable and wireless charging platform with configurable controllers

Most Popular

5G 555 timer circuit 8051 ai Arduino atmega16 automotive avr dc motor display Electronic Part Electronic Parts Fujitsu ic infineontechnologies integratedcircuit Intel IoT ir lcd ldr led maximintegratedproducts microchip microchiptechnology Microchip Technology microcontroller microcontrollers mosfet motor powermanagement Raspberry Pi remote renesaselectronics renesaselectronicscorporation Research samsung semiconductor sensor software STMicroelectronics switch Technology vishayintertechnology wireless

RSS EDABOARD.com Discussions

  • What's the deal with all these "MPPT" IC's with no current sense?
  • Photovoltaic MOSFET Drivers - Voltage Rating
  • Impedance requirement for SDRAM signals
  • A circuit that can adjust a resistance and probing a voltage node
  • A analogue circuit that spit out the resistance desired

RSS Electro-Tech-Online.com Discussions

  • IRS2453 the H circuit
  • Ampro 16mm Stylist projector woes.
  • How to quickly estimate lead acid battery capacity ?
  • Finally switched to Linux.
  • Multistage BJT amplifier
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • DesignFast
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • About Us
  • Contact Us
  • Advertise

Copyright © 2022 WTWH Media LLC. All Rights Reserved. The material on this site may not be reproduced, distributed, transmitted, cached or otherwise used, except with the prior written permission of WTWH Media
Privacy Policy | Advertising | About Us

Search Engineers Garage

  • Projects and Tutorials
    • Electronic Projects
      • 8051
      • Arduino
      • ARM
      • AVR
      • PIC
      • Raspberry pi
      • STM32
    • Tutorials
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Products News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • Digi-Key Store
    • Cables, Wires
    • Connectors, Interconnect
    • Discrete
    • Electromechanical
    • Embedded Computers
    • Enclosures, Hardware, Office
    • Integrated Circuits (ICs)
    • Isolators
    • LED/Optoelectronics
    • Passive
    • Power, Circuit Protection
    • Programmers
    • RF, Wireless
    • Semiconductors
    • Sensors, Transducers
    • Test Products
    • Tools
  • EE Resources
    • DesignFast
    • LEAP Awards
    • Oscilloscope Product Finder
    • White Papers
    • Webinars
  • EE Learning Center
  • Women in Engineering