Control a DC Motor with Push Button as a switch

Hi I'm trying to turn a DC Motor on and off using a push button. I built my circuit on Arduino Uno board. I checked my circuits for both motor and switch and they work. Can someone please take a look at my code please and tell me what I'm doing wrong? Thank you.

import processing.serial.*;
import cc.arduino.*;
Arduino arduino;

//DC motor - with this setup it has to be an analog pin!
int motorPin = 3; 
int buttonPin = 2;
int count = 0;
int state = 0;      // the current state of the output pin
int reading;           // the current reading from the input pin
int previous = 1;    // the previous reading from the input pin
long time = 0;         // the last time the output pin was toggled
long debounce = 200;   // the debounce time, increase if the output flickers


void setup() {

  size (500, 500);
  arduino = new Arduino(this, Arduino.list()[0], 57600);
  arduino.pinMode(motorPin, Arduino.OUTPUT);
  arduino.pinMode(buttonPin, Arduino.INPUT);
}
void draw() {

 reading = arduino.analogRead(buttonPin);
 println("Reading value = ");
 println(reading);

if (reading == 0 && previous == 1 && millis() - time > debounce) {
    if (state == 0)
      state = 1;
    else
      state = 0;

    time = millis();    
  }
if (state == 1){
  arduino.analogWrite(motorPin, 1000);
}
else 
{
 // arduino.analogWrite(motorPin, 0);
}
  previous = reading;
}


void mousePressed()
{
  //turn on the motor when the mouse is pressed
  arduino.analogWrite(motorPin, 1000);
}

void mouseReleased()
{
  //turn off the motor when the mouse is released
  arduino.analogWrite(motorPin, 0);
}

Answers

  • have you loaded the Firmata into your Arduino?

    Run Arduino, open the Examples > Firmata > StandardFirmata sketch, and upload it to the Arduino board.

    what you try to do is best achieved with arduino alone, no need to involve processing.

Sign In or Register to comment.