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

Swapping Workspace in Ubuntu using Accelerometer and Python Script

By Varun Kumar August 23, 2021

Requirements:

1.     Arduino with Atmega328p

2.     Accelerometer ADXL335

3.    Ubuntu 14.04 and Python 2.7 on your machine

4.    Python libraries Pyserial, subprocess and sys

5.    Wmctrl installed on your ubuntu, use ”sudo apt-get install wmctrl”

Typical Image of Arduino UNO

Fig. 1: Typical Image of Arduino UNO

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.

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

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. Moreover, it can be used to measure tilt by determining static acceleration of gravity or  measure impact from shock and vibration by identifying dynamic acceleration.

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

Explanation of Source Code

This program is an application of ADC and serial communication. Before proceeding with this article you can read about ADC here.

I have made a few changes 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 last four bits in ADMUX for next conversion. After that a workspace() function is called.

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

After that a workspace() function is called.

It takes no argument but uses two globally defined variables viz. xRaw and yRaw.

As I’m using four workspaces, so the values of xRaw and yRaw will decide whether to swap to workspace1, workspace2, workspace3 or workspace4

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

For detailed information please check the Source Code it’s very well documented.

Explanation of Python Script

I’m using three libraries namely Pyserial, subprocess and sys whereby Pyserial is the one that is not preinstalled with python2.7.  However, it’s freely available and very easy to install.

First I create an object “ser” of “Serial” class and give two arguments in it

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

b.    Baud rate: I my case it’s 9600

Then I create a try and except block to check whether wmctrl is installed on  the machine or not. If not it will display the warning and exit the program.

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 that is being sent over serial port then break it and convert it to integer and store it in a list. Then save the command in a variable(bashCommand)  accordingly followed by its execution.

Then command which is stored in that variable(bashCommand) is executed.

Then I print these values on terminal for debugging purposes.

For detailed information please check the well documented Python Script.

Explanation of Circuit

As can be seen in images, my accelerometer module doesn’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 place accelerometer on Analog pins of Arduino which maps to PORTC on atmega328p.

For Vcc and GND I declare PORTC1 and PORTC5 as output and pull down PORTC1 for GND, pull 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 the same directory, and upload the code to atmega328p.

Now, run the python script and BAAMMM!! You are ready to go. Just move accelerometer and your workspace will swap accordingly.

Project Source Code

###

//Main.c

#define F_CPU       16000000UL
#include "uartLibrary.h"
#include
#include
#include
#include
 
 
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<
}
 
// Used in choosing workspace according to the accelerometer value
int workspace()
{
if (xRaw>290 && yRaw>280){return 1;}
if (xRaw>290 && yRaw<280){return 2;}
if (xRaw<290 && yRaw>320){return 3;}
if (xRaw<290 && yRaw<320){return 4;}
else{return 0;}
}
/*********** 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 workspaceping 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
}
/*************************************/
 
 
/************ 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
}
/*************************************/
 
 
 
// 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;
}
*/
 
 
 
ADCSRA |= 1<
printf("%d %d %dn", xRaw,yRaw, workspace()); // Send these to my Laptop
}
 
/*********************************************************** END *******************************************************************/
 
 
// python_serial.py
 
import serial # http://pyserial.sourceforge.net/ , Version: 2.7
import subprocess
import sys
 
 
ser = serial.Serial('/dev/ttyUSB0',9600) # This is for Linux for Windows select the respective COM port
 
 
try:
bashCommand = "wmctrl -d"
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
print output
except:
print '''The program 'wmctrl' is currently not installed. You can install it by typing:
sudo apt-get install wmctrl'''
 
sys.exit()
 
 
while(1):
try:
 
readingFromArduino = map(int,ser.readline().split())
 
if readingFromArduino[2]==1:
bashCommand= 'wmctrl -o 0,0'
if readingFromArduino[2]==2:
bashCommand= 'wmctrl -o 1366,0'
if readingFromArduino[2]==3:
bashCommand= 'wmctrl -o 0,768'
if readingFromArduino[2]==4:
bashCommand= 'wmctrl -o 1366,768'
else:
None
 
print readingFromArduino
process = subprocess.Popen(bashCommand.split(), stdout=subprocess.PIPE)
output = process.communicate()[0]
 
 
except:
#print 'Check Some error is there ......'
None
 
############################################################# END ###########################################################
 
//uartLibrary.h
 
#define F_CPU 16000000UL
#define BAUD 9600
#define BRC ((F_CPU/16/BAUD)-1)
 
 
#include
#include
#include
 
void uart_init() 
{
UBRR0H = (BRC>>8); //Putting Upper 4 bits of BRC in lower 4 bits of UBRR0H
UBRR0L = BRC; //Putting Lowwer 8 bits of BRC in UBRR0L
 
    UCSR0B = 1 << TXEN0 | 1 << TXCIE0 | 1 << RXEN0 | 1 << RXCIE0;     //Enables TX, TX complete Interupt Enable, Enable RX, RX complete Interupt Enable
UCSR0C = _BV(UCSZ01) | _BV(UCSZ00);                               //8-bit data size
}
 
void uart_putchar(char c, FILE *stream) 
{
if (c == 'n')
{
        uart_putchar('r', stream);
    }
    loop_until_bit_is_set(UCSR0A, UDRE0);  // Wait until data register empty.
    UDR0 = c;
 
}
 
char uart_getchar(FILE *stream)
{
    loop_until_bit_is_set(UCSR0A, RXC0);
    return UDR0;
}
 
FILE uart_output = FDEV_SETUP_STREAM(uart_putchar, NULL, _FDEV_SETUP_WRITE);
 
FILE uart_input = FDEV_SETUP_STREAM(NULL, uart_getchar, _FDEV_SETUP_READ);
 
// end //

###

 


Circuit Diagrams

Circuit-Diagram-Arduino-Uno-Accelerometer-Ubuntu-Workspace-Swapping-Prototype

Project Video


Filed Under: Featured Contributions

 

Next Article

← Previous Article
Next Article →

Questions related to this article?
👉Ask and discuss on Electro-Tech-Online.com and EDAboard.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.

  • Op-Amp oscillating
  • rechargeable battery and simple alkaline battery in one single product
  • Phase shift full bridge with extra added dead time?
  • Looking for FEMM expert. Need help to assess my model.
  • PCB layout impact on RF path impedance

RSS Electro-Tech-Online.com Discussions

  • WTB: "The Theory Of Servicing AM, FM, And FM Receivers" by Clarence R. Green and Robert M. Bourque
  • Anyone In The US Ordered From AliExpress Recently?
  • Calculation of A Class amplifier
  • strange laptop problem
  • restarting this Christmas 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

  • Stackpole introduces compact jumpers for high-current circuit routing
  • Ironwood Electronics launches near-device-footprint SMT elastomer socket for BGA264
  • Amphenol RF releases P67 FAKRA plugs for 6 GHz RF transmission
  • Microchip releases platform to deliver real-time specifications for AI assistants
  • GigaDevices introduces 32-bit MCUs with integrated DSP and FPU support

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