Example on controlling MCP4261 and Arduino Uno via Python



  • Just a small part of a project I'm working on but figured I'd share here. I needed to change some 10k manual pots to digital so I could automate it. I wrote the following Arduino sketch and the subsequent python wrapper to do just that. Hope this helps some!

    Arduino Side basically just expects two spaced integers corresponding to the Potentiometer number [0-3] and the position you'd like [0-254] followed by a return (e.g. newline character \n):

    #include "mcp4261.h"
    
    // Example demonstrating how to use the MCP4261 library with
    // the MCP4261 Arduino Uno V0.1 shield to change wiper 
    // position based on serial input
    
    int pot;
    int wiper_pos;
    const int POT_0_CS = 5;
    const int POT_1_CS = 6;
    const int LOOP_DELAY = 200;
    MCP4261 pot0 = MCP4261(POT_0_CS);
    MCP4261 pot1 = MCP4261(POT_1_CS);
    
    
    void setup() {
    
        // Setup SPI communications
        SPI.setDataMode(SPI_MODE0);
        SPI.setBitOrder(MSBFIRST);
        SPI.setClockDivider(SPI_CLOCK_DIV8);
        SPI.begin();
    
        // Initialize potentiometers
        pot0.initialize();
        pot1.initialize();
        pot0.setWiper0(0);
        pot0.setWiper1(0);
        pot1.setWiper0(0);
        pot1.setWiper1(0);
    
        // Initialize Serial
        Serial.begin(9600);
        // Serial.println("Serial Ready...");
    }
    
    
    void loop()
    {
     while (Serial.available() > 0) {
       pot = Serial.parseInt();
       wiper_pos = Serial.parseInt();
       if (Serial.read() == '\n') {
        switch (pot) {
          case 0:
           pot0.setWiper0(wiper_pos);
           Serial.print("Pot 0 set to "); 
           Serial.println(wiper_pos);
           break;
          case 1:
           pot0.setWiper1(wiper_pos);
           Serial.print("Pot 1 set to "); 
           Serial.println(wiper_pos);
           break;
          case 2:
           pot1.setWiper0(wiper_pos);
           Serial.print("Pot 2 set to "); 
           Serial.println(wiper_pos);
           break;
         case 3:
           pot1.setWiper1(wiper_pos);
           Serial.print("Pot 3 set to "); 
           Serial.println(wiper_pos);
           break;
         }
         wiper_pos = 0;
         Serial.flush();
       }
     }
    }
    

    The python class just gives you an easy way to connect to the the first found Arduino over serial and change the pot and value (requires pyserial, currently using 2.7) Will need to be modified for different Arduino boards and if there are multiple connected to the host:

    #!/usr/bin/env python
    
    ###############################################################################
    #
    # Class to control IO Rodeo MCP4261 Potentiometer Shield
    # http://iorodeo.com/collections/arduino-shields-and-breakout-boards/products/digital-potentiometer-shield
    #
    ###############################################################################
    
    import serial
    
    from serial.tools import list_ports
    
    
    class Controller(object):
        def __init__(self):
            '''Finds then sets up communication to connected Arduino'''
            self.port = self.find()
            self.baudrate = 9600
            self.timeout = 2
            self.pot_shield = self.connect(self.port)
    
        def find(self):
            '''Find a connected ECUsim and return its port'''
            for device in list_ports.comports():
                if device[1] == "Arduino Uno":
                    port = device[0]
                    return port
            else:
                print "Could not find a connected Arduino"
                return False
    
        def connect(self, port):
            '''Connect to a specified Arduino on [port]'''
            try:
                pot_shield = serial.Serial(port=port, baudrate=self.baudrate, timeout=self.timeout)
                return pot_shield
            except:
                print "Unable to connect to the Arduino at: {}".format(self.port)
    
        def turn_pot(self, pot, position):
            '''Send a command to the connected Arduino to turn a specific potentiometer [0-3] to a specific value [0-254]'''
            self.pot_shield.write("{} {}\n".format(pot, position))
            response = self.pot_shield.readline()
            return response.strip()
    
        def close(self):
            '''Close the communication to the ECUsim if the port is open'''
            if self.pot_shield.isOpen():
                self.pot_shield.close()
            return
    

Log in to reply