Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Sensor Series
      • 3D Printing
      • AI
      • ARDUINO Compatible Coding
      • Audio Electronics
      • Battery Management
      • Beginners Electronics Series
      • Brainwave
      • Digital electronics (DE)
      • Electric Vehicles
      • EMI/EMC/RFI
      • EVs
      • Hardware Filters
      • IoT tutorials
      • LoRa/LoRaWAN
      • Power Tutorials
      • Protocol
      • Python
      • RPI Python Programming
      • Sensors
      • USB
      • Thermal management
      • Verilog
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey 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
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
  • Guest Post Guidelines
  • Advertise
  • Subscribe

Controlling mouse pointer using Python script and accelerometer

By Varun Kumar July 17, 2015

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 Projects, Electronic Projects
Tagged With: Arduino, Atmega328p, python
 

Next Article

← Previous Article
Next Article →

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.

Submit a Guest Post

submit a guest post

EE TECH TOOLBOX

“ee
Tech Toolbox: Power Efficiency
Discover proven strategies for power conversion, wide bandgap devices, and motor control — balancing performance, cost, and sustainability across industrial, automotive, and IoT systems.

EE Learning Center

EE Learning Center
“engineers
EXPAND YOUR KNOWLEDGE AND STAY CONNECTED
Get the latest info on technologies, tools and strategies for EE professionals.

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!


RSS EDABOARD.com Discussions.

  • Can anyone please help me with this single board computer?
  • Anyone successfully communicated to the BlueNRG-M0 module on the B-L4S5I-IOT01A board
  • How to Build an Audio Tone Control?
  • Current version of LTspice not working on Windows 11?
  • Addressable Latch in My Logic Project

RSS Electro-Tech-Online.com Discussions

  • Measuring controller current output with a meter
  • KiCad custom symbol definition correct approach
  • restarting this Christmas project
  • Anyone In The US Ordered From AliExpress Recently?
  • My Advanced Realistic Humanoid Robots Project

Featured Tutorials

Real Time Hardware Filter Design

  • Practical implementation of bandpass and band reject filters
    Practical implementation of bandpass and band reject filters
  • Practical application of hardware filters with real-life examples
    Practical application of hardware filters with real-life examples
  • A filter design example
    A filter design example
  • Types of filter responses
    Types of filter responses
  • What are the two types of hardware filters?
    What are the two types of hardware filters?
  • What are hardware filters and their types?
    What are hardware filters and their types?
More Tutorials >

Recent Articles

  • Posifa sensors improve low-flow accuracy in compact systems
  • Acopian releases low-profile power supplies rated to 900 W
  • Octavo Systems OSDZU-3 REF Development Platform
  • Same Sky adds enclosure design to its audio engineering capabilities
  • Waterproof SMA-to-MHF I LK assemblies introduced by Amphenol RF

EE ENGINEERING TRAINING DAYS

engineering
Engineers Garage
  • Analog IC TIps
  • Connector Tips
  • Battery Power Tips
  • EDABoard Forums
  • EE World Online
  • Electro-Tech-Online Forums
  • EV Engineering
  • Microcontroller Tips
  • Power Electronic Tips
  • Sensor Tips
  • Test and Measurement Tips
  • 5G Technology World
  • Subscribe to our newsletter
  • About Us
  • Contact Us
  • Advertise

Copyright © 2025 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

Search Engineers Garage

  • Electronic Projects & Tutorials
    • Electronic Projects
      • Arduino Projects
      • AVR
      • Raspberry pi
      • ESP8266
      • BeagleBone
      • 8051 Microcontroller
      • ARM
      • PIC Microcontroller
      • STM32
    • Tutorials
      • Sensor Series
      • 3D Printing
      • AI
      • ARDUINO Compatible Coding
      • Audio Electronics
      • Battery Management
      • Beginners Electronics Series
      • Brainwave
      • Digital electronics (DE)
      • Electric Vehicles
      • EMI/EMC/RFI
      • EVs
      • Hardware Filters
      • IoT tutorials
      • LoRa/LoRaWAN
      • Power Tutorials
      • Protocol
      • Python
      • RPI Python Programming
      • Sensors
      • USB
      • Thermal management
      • Verilog
      • VHDL
    • Circuit Design
    • Project Videos
    • Components
  • Articles
    • Tech Articles
    • Insight
    • Invention Stories
    • How to
    • What Is
  • News
    • Electronic Product News
    • Business News
    • Company/Start-up News
    • DIY Reviews
    • Guest Post
  • Forums
    • EDABoard.com
    • Electro-Tech-Online
    • EG Forum Archive
  • DigiKey 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
  • Learn
    • eBooks/Tech Tips
    • Design Guides
    • Learning Center
    • Tech Toolboxes
    • Webinars & Digital Events
  • Resources
    • Digital Issues
    • EE Training Days
    • LEAP Awards
    • Podcasts
    • Webinars / Digital Events
    • White Papers
    • Engineering Diversity & Inclusion
  • Guest Post Guidelines
  • Advertise
  • Subscribe