Voting resources, early voting, and poll worker information - VOTE. ... Adafruit is open and shipping.

Using a switch to control spin direction
Moderators: adafruit_support_bill, adafruit

Please be positive and constructive with your questions and comments.

Using a switch to control spin direction

by TurboTronix on Wed Apr 02, 2008 1:18 pm

What are the output pins of the Arduino pins that connect to the motor shield? Like which pin goes where (M1 goes to what output pin #s, etc...)?

Also, is there a sample code on how to control a motor using lets say a photocell?

I tried using the following code to control the motor insead of the LEDs used in that project without sucess. I wanted 4 motors to spin on one direction and then the other based on the input (so when the LED is ON motor spins one way and the other way when LED is OFF, thats based on adding a motor instead of the LED from that project).

Flash Code:
Code: Select all | TOGGLE FULL SIZE
// Crea un objeto para recibir los eventos
arduinoListener = new Object();
//Avisa cuando se conecta
arduinoListener.onConnect = function() {
        debug_txt.text += "CONNECTED : Hoorray! You're connected!\n";
//Avisa cuando no se puede conectar
arduinoListener.onConnectError = function() {
        debug_txt.text += "ERROR : Connection Failed, please check the server configuration\n";
//Avisa cuando se desconecta
arduinoListener.onDisconnect = function() {
        debug_txt.text += "WARNING : Flash has disconnected\n";
//Avisa al recibir datos
arduinoListener.onReceiveData = function(dataObj:Object) {
        var arduinoData:String =;
        //Escribimos lo que recibimos en el textarea
        debug_txt.text += arduinoData+"\n";
        //actualizamos el scroll del textarea
        debug_txt.vPosition = debug_txt.maxVPosition+2;
//Iniciamos la conexion con el servidor através de la clase Arduino
var arduino:Arduino = new Arduino(5335);
arduino.addEventListener("onConnect", arduinoListener);
arduino.addEventListener("onConnectError", arduinoListener);
arduino.addEventListener("onDisconnect", arduinoListener);
arduino.addEventListener("onReceiveData", arduinoListener);
// Iniciamos los botones ON|OFF desde el 2 al 13 (el numero de los pines)
for (var i:Number = 2; i<=13; i++) {
        // botones "ON"
        _root["btn_on"+i].id = i;
        _root["btn_on"+i].onRelease = function() {
                debug_txt.text += "Sending Data to Arduino : LED #"" has to be ON\n";
        // botones "OFF" (parecidos a los ON)
        _root["btn_off"+i].id = i;
        _root["btn_off"+i].onRelease = function() {
                debug_txt.text += "Sending Data to Arduino : LED #"" has to be OFF\n";

Flash AS file code:
Code: Select all | TOGGLE FULL SIZE
*   ARDUINO CLASS - version 1.0 - 30-12-2005
*     this Actionscript class makes it easier to connect Flash to the Arduino Board (
*   # copyleft beltran berrocal, 2005 - -
*   # updates and examples:
*    # credits must also be given to:
*   Yaniv Steiner and the instant soup crew ( for generating the original flash client
*     # you will also need the serialProxy developed by Stefano Busti(1999) and David A. Mellis(2005)
*   that can be found either on the Arduino Site ( or redistributed with this example (see update url)
*   @@ creates the Arduino Object inside Flash
*            usage:
*                  var portNumber   = 5333;      //read the serialProxy documentation to understand this
*                  var hostIpAdress = ""; //optional it deafaults to this
*                  var ArduinoInstance:Arduino = new Arduino(portNumber, hostIpAdress);
*   @@ CONNECT
*   @@ connects to the XMLSocket server, you must have provided a port and a host adress via the constructor
*            usage:
*                  ArduinoInstance.connect()
*   @@ disconnects from the XMLSocket server
*            usage:
*                  ArduinoInstance.disconnect()
*   @@ SEND
*   @@ sends data to Arduino via the XMLSocket server(the serialProxy)
*            usage:
*                  ArduinoInstance.send("some data here");
*   ## EVENT: onDataReceived
*   ## handler of a listener object that listens to data sent from Arduino through the XMLSocket server(the serial Proxy)
*            usage:
*                  Arduino_Listener = new Object(); //create a listener object
*                  Arduino_Listener.onDataReceived = function() {
*                        //handle the received data in here
*                  }
*                  ArduinoInstance.addEventListener("onReceiveData",Arduino_Listener); //register to listen to the events
*   ## OTHER EVENTS: onConnect,  onConnectError,  onDisconnect
*            usage: use in the same way as the onDataReceived event
*   Copyright (C) 2005 beltran berrocal |  |
*   This library is free software; you can redistribute it and/or modify it
*   under the terms of the GNU Lesser General Public License
*   as published by the Free Software Foundation; either version 2.1 of the License
*   You should have received a copy of the GNU Lesser General Public License along with this library;
*   Alternatively you can find it here
*   Brief Explanation of the Licence:
*   - you can you use, redistribute, modify this software for free,
*   - you can put it into commercial projects
*   - but if you modify/enhance this Library you should release it under the same licence or alternatively under the GPL licence
*   - in all cases you should also credit the original author and all contributors


   class Arduino extends XMLSocket {
      private var _connected      :Boolean = false;      // is connected?
      private var _host         :String  = ""; // Host name or IP address
      private var _port         :Number  = 5331         //read the config file of the socket server for this one
      function addEventListener(){}
      function removeEventListener(){}   
      function dispatchEvent(){}
      function dispatchQueue(){}
   //constructor - provide a port number and a host ip adress
   //read the documentation of the SerialProxy to better understandwhat this means
      function Arduino(port, host) {
         //trace("** Arduino ** initilizing constructor");
         //check if the selected port is correct or set default
         if(port == undefined) {
            trace("** Arduino ** default port:"+_port+" initialized! to change it use new Arduino(onPortNumber)")
         } else if ((_port < 1024) || (_port > 65535)) {
            trace("** Arduino ** Port must be from 1024 to 65535 ! read the Flash Documentation and the serProxy config file to better understand")      
         } else {
            _port = port;
         //check for host or set default
         if(host != undefined) {
            _host = host;
         //register and override responder functions
         this.onConnect  = onConnectToSocket;
         this.onClose    = onDisconnectSocket;
         this.onData      = onDataReceived;
      //   CONNECT and DISCONNECT + responders
      //connect to the XMLsocket
      public function connect () {
         trace("** Arduino ** Connecting to "+_host+":"+_port+" . . .");
      //disconnects from the xmlsocket (not Arduino itself)
      public function disconnect () {
         if (_connected)   {
            trace("** Arduino ** disconnecting");
            _connected = false;
      //XMLsocket responders
      private function onConnectToSocket (success) {
         //trace("** Arduino ** onConnectToSocket");
         if (success) {
            _connected = true;
            //launch event
            trace ("** Arduino ** Connection established.")
         } else {
            trace ("** Arduino ** Connection failed! you must launch the serialProxy first");
      //XMLsocket responders
      private function onDisconnectSocket (success) {
         _connected = false;
         //trace ("** Arduino ** onDisconnectSocket ** Connection closed by remote host.");
         //launch event
      //   SEND and receive data from server
      //sends data to arduino
      public function send(dataStr:String) {
         //trace("** Arduino ** send:" + dataStr)
         if (_connected) {
            if (dataStr.length) {
               //trace("** Arduino ** Sending \""+dataStr+"\"");   
      //overrides XMLSocket.onData in order to have pure string and not the full XML object
      private function onDataReceived (str:String) {
         //trace("** Arduino ** onDataReceived str:"+str);
         //launch event
      //   EVENTS
      private function e_connectToSocket(){
         var evt = {target:this, type:"onConnect"};
      private function e_connectToSocketError(){
         var evt = {target:this, type:"onConnectError"};
      private function e_disconnectSocket(){
         var evt = {target:this, type:"onDisconnect"};
      private function e_onReceiveData (str:String){
         var evt = {target:this, type:"onReceiveData"}; = str;

Arduino Code from that website:
Code: Select all | TOGGLE FULL SIZE
// Declaration of variables int pingNumber = 0;
// Var to hold what pin has to change int lastRead = 0;
// Var to hold the last char read int preLastRead = 0; //Var to hold the char before the last char read U_U
boolean yetRead = true; //Var to hold if we have read the serial data
// Function to convert received bytes to decimal numbers
void readSerialData () {
        pingNumber = 0;
        if(Serial.available()) {
                yetRead = false;
                while (Serial.available()){
                        preLastRead = lastRead;
                        lastRead =;
                        pingNumber = pingNumber*10+lastRead;
                //At this moment, lastRead was a 0 (to make the end of the data)
                pingNumber = (pingNumber-lastRead)/10;
                //This is the ping number without the lastChar (1-0 ON-OFF)
                pingNumber = (pingNumber-preLastRead)/10;
                //If want debug, uncomment next line
//the setup, declared all pins as output
void setup() {
        Serial.begin(19200); //setup serial conversation at 9600 bauds
void loop () {
        //Read if something has come
        //If there's something out there
        if( yetRead == false) {
                Serial.print("Ping Number : ");
                yetRead = true;
                //Have i to explain this?
                if(preLastRead==1) {
                        Serial.println(" Has to be ON");
                        digitalWrite(pingNumber, HIGH);
                } else {
                        Serial.println(" Has to be OFF");
                        digitalWrite(pingNumber, LOW);
        //the delay between each loop
Posts: 4
Joined: Sun Mar 30, 2008 12:04 pm

by TurboTronix on Wed Apr 02, 2008 1:58 pm

I want to assign several motors (4 DC motors)

How can I make the dynamic? Can I write in the code something like motor+"i".run??

Also how can I write this line of code since I get an error:


I want to make the motor1 part dynamic since it will be based on the pingNumber and the motor connected to it, how can I do so?
Posts: 4
Joined: Sun Mar 30, 2008 12:04 pm

by adafruit on Wed Apr 02, 2008 2:29 pm

you cannot use digitalwrite to 'write' to the dc motor
you have to use the library commands, such as you can make the direction dynamic but you cant make the motor chosen dynamic
you would have to have test cases
such as
if (pingnumber == 1) {}
if (pingnumber ==2) {}

Posts: 12151
Joined: Thu Apr 06, 2006 4:21 pm
Location: nyc

by TurboTronix on Wed Apr 02, 2008 4:11 pm

Yes thats what I did and it worked.

Posts: 4
Joined: Sun Mar 30, 2008 12:04 pm

by darus67 on Wed Apr 02, 2008 6:01 pm

Does C++ let you declare and array of AF_DCMotor objects?
I know standard C, but I don't know C++ even well enough to be dangerous.

Instead of saying:

Code: Select all | TOGGLE FULL SIZE
AF_DCMotor motor1(1, MOTOR12_64KHZ);
AF_DCMotor motor2(2, MOTOR12_64KHZ);
AF_DCMotor motor3(3, MOTOR12_64KHZ);
AF_DCMotor motor4(4, MOTOR12_64KHZ);

can you do something like this:

Code: Select all | TOGGLE FULL SIZE
AF_DCMotor motor[1](1, MOTOR12_64KHZ);
AF_DCMotor motor[2](2, MOTOR12_64KHZ);
AF_DCMotor motor[3](3, MOTOR12_64KHZ);
AF_DCMotor motor[4](4, MOTOR12_64KHZ);

and then address them like this:

Code: Select all | TOGGLE FULL SIZE
int i;

for (i=1; i<=4; i++){

"He's just this guy. You know?"
Posts: 246
Joined: Wed Sep 26, 2007 10:25 pm
Location: Minnesota, USA

by TurboTronix on Wed Apr 02, 2008 11:22 pm

ya I wanted to keep it clean and less lines of code. An array would be a nice touch.

I haven't tested that. Right now I am trying to get some motion tracking in Flash to move the motors. It does it but not very clean. After that I'll get back to the Arduino side of things :)

On another note, how do I add analog inputs (ie button)? I can't access the pins with the motor shield on my arduino....
Posts: 4
Joined: Sun Mar 30, 2008 12:04 pm

Please be positive and constructive with your questions and comments.