I am new to Arduino. I want to simulate a circuit which uses an accelerometer ADXL335 and a DC motor. If any deviation observed in the accelerometer readings, I want the motor to rotate. Is there any way I can simulate its working in software without implementing it?

Your sensor supplies an analog signal, ranging from 0V for -3g to 3.3V for +3g. This means you have a signal averaging at "338" when read using Arduino's analogRead() function, with spikes in either direction when acceleration changes.

You would want some code which gives you a variable hovering around "338", with random acceleration spikes injected in either direction. This could look something like this:

int16_t num_zerog = (3.3 / 5) * 512;
int16_t num_xaxis = num_zerog;
uint8_t num_random = 0;

void setup() {

void loop() {
  // put your main code here, to run repeatedly:
  num_random = random(256);
  if (num_random == 255) {
    num_xaxis += 200;
  else if (num_random == 0) {
    num_xaxis -= 200;
  else if (num_random < 100) {
    num_xaxis += 1;
  else if (num_random > 155) {
    num_xaxis += 1;
  else {
    num_xaxis += (num_zerog - num_xaxis) / 4;
  if(num_xaxis < 0 || num_xaxis > 675) {
    num_xaxis = num_zerog;

Explanation: First, the value for 0g is determined from the voltage difference. A random value is generated, ranging from 0 to 255. If the random value is 0, a negative value is added to your "signal". If it's 255, a positive spike is added. If any other value is obtained, it goes back to it's 0g level with 1/4th of the difference between the current value and the 0g value per loop.

The serial commands only serve to let you watch the result in Arduino IDE's serial plotter. If you need the spike to occur less frequently, adjust the delay(), or let the counter run to higher numbers. If the CPU-blocking delay() command is an issue in your project, you could run the randomization code using a timer and an interrupt.

Please note that real acceleration sensors exhibit a lot more noise than this. This could be implemented by adding smaller spikes at a broader range of random values (like -1 if num_random is below 100 and +1 if it is above 155). Graph

  • 1
    An input voltage of 1.65 V (half of 3.3 V) should give you a reading of (1.65 V ÷ 5 V) × 1024 ≈ 338. – Edgar Bonet Nov 14 at 8:23
  • You're right of course, I forgot that analogRead() defaults to 10 bit. Thank you, post corrected. – Tobias Weiß Nov 14 at 8:48

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.