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

Swapping Workspace in Ubuntu using Accelerometer and Python Script

By Varun Kumar

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

 

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

  • 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)

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 Research robot samsung semiconductor sensor software STMicroelectronics switch Technology vishayintertechnology wireless

RSS EDABOARD.com Discussions

  • Please help to identify the signal input port on board
  • Hotplugging UART
  • RF switch selection
  • sensitivity in filters and number of bits of system
  • MDO4104-6 Front Panel Not Working

RSS Electro-Tech-Online.com Discussions

  • software PWM
  • Combination of Wires of two DC motor giving Output current.
  • Passthrough charging-simple but impossible to achieve?
  • geared motor to revolve oval platform
  • None existant errors (MPLAB X)
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