Saturday, April 9, 2016

Motor Labs

Control servo via Processing

(no questions)

Control DC motor via potentiometer

Here's the code used:
const int pot_pin = A0;
const int motor_pin = 9;

void setup()
{
  // put your setup code here, to run once:
  pinMode(pot_pin, INPUT);
  pinMode(motor_pin, OUTPUT);
  Serial.begin(9600);
}

void loop()
{
  // put your main code here, to run repeatedly:
  int motor_speed = map(pot_read(), 0, 1023, 0, 255);
  int time = 500;
  analogWrite(motor_pin, motor_speed);
  delay(time);
}

int pot_read()
{
  int pot_val = analogRead(pot_pin);
  Serial.println("Potentiometer read: " + (String)pot_val);
  return pot_val;
}

Control DC motor via Processing

Here's the code used:
const int motor_pin = 9;

void setup()
{
  // put your setup code here, to run once:
  pinMode(motor_pin, OUTPUT);
  Serial.begin(9600);
}

void loop(){
  // put your main code here, to run repeatedly:
  if (Serial.available() > 0)
  {
    int read_in = Serial.read();
    int motor_speed = map(read_in, 0, 255, 0, 255);
    int time = 100;
    analogWrite(motor_pin, motor_speed);
  }
  delay(10);
}

and

import processing.serial.*;

Serial arduinoPort;

void setup(){
  size(320, 240);
  background(0,255,255);
  println(Serial.list());
  
  String portName = Serial.list()[0];
  arduinoPort = new Serial(this, portName, 9600);
}

void draw() {
  int servoVal = (int) 255 * mouseX / width;
  arduinoPort.write(servoVal);
  println(servoVal);
  
  background(255,255,0);
  fill(255,0,0);
  ellipse(mouseX, mouseY, 50, 50);
}

No comments:

Post a Comment