Hide minor edits - Show changes to markup
La función write_pot permite controlar cada potenciómeto. Se pone SLAVESELECT (pin 10) a nivel bajo para habilitar el dispositivo. A continuación se transfiere el byte de dirección seguido del byte del valor de la resistencia. Por último, se pone SLAVSELECT a nivel alto de nuevo para liberar el chip y terminar la transferencia del dato.
/*The write_pot function allows us to control the individual potentiometers. We set the SLAVESELECT line low to enable the device. Then we transfer the address byte followed by the resistance value byte. Finally, we set the SLAVSELECT line high again to release the chip and signal the end of our data transfer.*/
La función write_pot permite controlar cada potenciómeto. Ponemos SLAVESELECT (pin 10) a nivel bajo para habilitar el dispositivo. A continuación transferimos el byte de dirección seguido del byte del valor de la resistencia. Por último, ponemos SLAVSELECT a nivel alto de nuevo para liberar el chip y terminar la transferencia del dato.
LED video
Programa completo de LEDs
/*For easy copy and pasting the full program text of this tutorial is below: */
code, tutorial and photos by Heather Dewey-Hagborg
código, tutorial y fotos por Heather Dewey-Hagborg
Se termina la función setup() poniendo todos los potenciómetros con el valor máximo de resistencia, así los LEDs están apagados.
/*We conclude the setup function by setting all the potentiometers to full on resistance states thereby turning the LEDs off:*/
Terminamos la función setup() poniendo todos los potenciómetros con el valor máximo de resistencia, así los LEDs están apagados.
/*In our main loop we iterate through each resistance value (0-255) for each potentiometer address (0-5). We pause for 10 milliseconds each iteration to make the steps visible. This causes the LEDs to sequentially flash on brightly and then fade out slowly:*/
/*The spi_transfer function loads the output data into the data transmission register, thus starting the SPI transmission. It polls a bit to the SPI Status register (SPSR) to detect when the transmission is complete using a bit mask, SPIF. An explanation of bit masks can be found here. It then returns any data that has been shifted in to the data register by the EEPROM:*/
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2 pone al SPI para tomar los datos en el flanco de subida de la señal de reloj y el bit 1 y 0 ajusta la velocidad del SPI a la más rápida. Depués de configurar el registro de control se limpia el registro de estado (SPSR) y el registro de dato (SPDR) con la variable clr para eliminar posible datos almacenados anteriormente.
/*Now we set the SPI Control register (SPCR) to the binary value 01010000. In the control register each bit sets a different functionality. The eighth bit disables the SPI interrupt, the seventh bit enables the SPI, the sixth bit chooses transmission with the most significant bit going first, the fifth bit puts the Arduino in Master mode, the fourth bit sets the data clock idle when it is low, the third bit sets the SPI to sample data on the rising edge of the data clock, and the second and first bits set the speed of the SPI to system speed / 4 (the fastest). After setting our control register up we read the SPI status register (SPSR) and data register (SPDR) in to the junk clr variable to clear out any spurious data from past runs:*/
Ahora configuramos el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7(0) deshabilita la interrupción SPI, el bit 6(1) habilita el SPI, el bit 5(0) elige la transmisión del primer bit al bit más significativo MSB (Most Significant Bit), el bit 4(1) pone a Arduino en modo Maestro en la comunicación, el bit 3(0)ajusta la polaridad de la señal de reloj a nivel bajo, el bit 2(0) pone al SPI para tomar los datos en el flanco de subida de la señal de reloj y el bit 1 y 0 (00) ajusta la velocidad del SPI a la más rápida. Depués de configurar el registro de control se limpia el registro de estado (SPSR) y el registro de dato (SPDR) con la variable clr para eliminar posible datos almacenados anteriormente.
A continuación se asigna variables para almacenar el valor de las resistencias y la dirección de los potenciómetros.
/*Next we allocate variables to store resistance values and address values for the potentiometers:*/
A continuación asignamos variables para almacenar el valor de las resistencias y la dirección de los potenciómetros.
Primero se configuras el modo de los pines como entrada y salida y se pone el pin digital de salida SLAVESELECT a nivel alto para empezar. Esto hace que desactive el dispositivo SPI y evita datos falsos en la transmisión debido al ruido de la línea.
/*First we set our input and output pin modes and set the SLAVESELECT line high to start. This deselects the device and avoids any false transmission messages due to line noise:*/
Primero se configuramos el modo de los pines como entrada y salida y ponemos el pin digital de salida SLAVESELECT a nivel alto para empezar. Esto hace que desactive el dispositivo SPI y evita datos falsos en la transmisión debido a posibles ruidos en el cableado.
/*Now we will write the code to enable SPI control of the AD5206. This program will sequentially pulse each LED on and then fade it out gradually. This is accomplished in the main loop of the program by individually changing the resistance of each potentiometer from full off to full on over its full range of 255 steps.*/
A continuación el código del programa en pequeñas secciones.
/*We will walk through the code in small sections.*/
Se definen los pines que se usan para la conexión al SPI, DATAOUT, DATAIN, SPICLOCK y SLAVESELECT. Aunque no se están leyendo datos del AD5206 en este programa, el pin 12 está asignado a recepción de datos de un dispositivo SPI. Por tanto, es mejor no utilizarlo para otras tareas de programación para evitar posibles errores.
/*We define the pins we will be using for our SPI connection, DATAOUT, DATAIN, SPICLOCK and SLAVESELECT. Although we are not reading any data back out of the AD5206 in this program, pin 12 is attached to the builtin SPI so it is best not to use it for other programming functions to avoid any possible errors:*/
A continuación comentamos el código del programa en pequeñas secciones.
Definimos los pines que se usan para la conexión al SPI: DATAOUT, DATAIN, SPICLOCK y SLAVESELECT. Aunque no se están leyendo datos del AD5206 en este programa, el pin 12 está asignado a la recepción de datos de un dispositivo SPI en otros ejemplos. Por tanto, es mejor no utilizarlo para otras tareas de programación para evitar posibles errores.
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo el pin Chip Select (CS)a nivel bajo. Las instrucciones se envían en códigos de operaciones (opcodes) de 11 bits con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255. La transferencia del dato empieza con el bit más significativo (MSB, Most Significant Bit) en el flanco de subida de la señal de reloj. La señal de reloj es inactiva a nivel bajo, y la velocidad de comunicación del interfaz es mucho más rápida que la velocidad de procesamiento de Arduino, por lo que no es necesario un pre-escaler para adaptarse a la velocidad de transmisión.
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo el pin Chip Select (CS)a nivel bajo. Las instrucciones se envían en códigos de operaciones (opcodes) de 10 bits con los tres bits más significativos (10-8) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (7-0)definiendo que valor poner al potenciómetro entre 0-255. La transferencia del código de operación empieza con el bit más significativo (MSB, Most Significant Bit) en el flanco de subida de la señal de reloj. La señal de reloj es inactiva a nivel bajo, y la velocidad de comunicación del interfaz es mucho más rápida que la velocidad de procesamiento de Arduino, por lo que no es necesario un pre-escaler para adaptarse a la velocidad de transmisión.
Inserte el circuito integrado AD5206 en la placa de prueba. Conecta 5V de alimentación y masa de la placa de prueba a 5V de alimentación y masa de la placa de Arduino. Conecte los pines 3, 6, 10, 13, 16, 21 y 24 del AD5206 a +5V y los pines 1, 4, 9, 12, 15, 18, 19 y 22 a masa. Hemos conectado todos los pines A a masa y los pines B a +5V para crear 6 divisores de tensión.
Insertamos el circuito integrado AD5206 en la placa de prueba. Conecta 5V de alimentación y masa de la placa de prueba a 5V de alimentación y masa de la placa de Arduino. Conecte los pines 3, 6, 10, 13, 16, 21 y 24 del AD5206 a +5V y los pines 1, 4, 9, 12, 15, 18, 19 y 22 a masa. Hemos conectado todos los pines A a masa y los pines B a +5V para crear 6 divisores de tensión.
Conecta el pin 5 de AD5206 al pin 10 de Arduino (Slave Select - SS), el pin 7 de AD5206 al pin 11 de Arduino (Master Out Slave In - MMOSI), y el pin 8 de AD5206 al pin 13 de Arduino (Serial Clock - SCK)
Conectamos el pin 5 de AD5206 al pin 10 de Arduino (Slave Select - SS), el pin 7 de AD5206 al pin 11 de Arduino (Master Out Slave In - MMOSI), y el pin 8 de AD5206 al pin 13 de Arduino (Serial Clock - SCK)
Finalmente, conecta cada uno de los LEDs entre el pin W (en el AD5206 los pines 2, 11, 14, 17, 20 y 23) y masa, de la siguiente manera: la patilla larga del LED conectada al pin W y la patilla corta, o la cara plana del LED, conectada a masa.
Finalmente, conectamos cada uno de los LEDs entre el pin W (en el AD5206 los pines 2, 11, 14, 17, 20 y 23) y masa, de la siguiente manera: la patilla larga del LED conectada al pin W y la patilla corta, o la cara plana del LED, conectada a masa.
Conectar el pin 5 de AD5206 al pin 10 de Arduino (Slave Select - SS), el pin 7 de AD5206 al pin 11 de Arduino (Master Out Slave In - MMOSI), y el pin 8 de AD5206 al pin 13 de Arduino (Serial Clock - SCK)
/*Connect AD5206 pin 5 to Arduino pin 10 (Slave Select - SS), AD5206 pin 7 to Arduino pin 11 (Master Out Slave In - MOSI), and AD5206 pin 8 to Arduino pin 13 (Serial Clock - SCK).*/
Conecta el pin 5 de AD5206 al pin 10 de Arduino (Slave Select - SS), el pin 7 de AD5206 al pin 11 de Arduino (Master Out Slave In - MMOSI), y el pin 8 de AD5206 al pin 13 de Arduino (Serial Clock - SCK)
Finalmente, conectar cada uno de los LEDs entre el pin W (en el AD5206 los pines 2, 11, 14, 17, 20 y 23) y masa, de la siguiente manera: la patilla larga del LED conectada al pin W y la patilla corta, o la cara plana del LED, conectada a masa.
/*Finally, connect an LED between each Wiper pin (AD5206 pins 2, 11, 14, 17, 20 and 23) and ground so that the long pin of the LED connects to the wiper and the short pin, or flat side of the LED connects to ground.*/
Finalmente, conecta cada uno de los LEDs entre el pin W (en el AD5206 los pines 2, 11, 14, 17, 20 y 23) y masa, de la siguiente manera: la patilla larga del LED conectada al pin W y la patilla corta, o la cara plana del LED, conectada a masa.
Ahora se escribe el código para realizar el control del AD5206 por comunicación SPI. Este programa activa secuencialmente cada LED y luego se va apagando gradualmente. Esto se hace en la función principal loop() del programa cambiando individualmente el valor de resistencia de cada potenciómetro desde apagado hasta encendido (0-255).
Ahora escribiremos el código en la placa Arduino para realizar el control del AD5206 por comunicación SPI. Este programa activa secuencialmente cada LED y luego se va apagando gradualmente. Esto se hace en la función principal loop() del programa cambiando individualmente el valor de resistencia de cada potenciómetro desde apagado hasta encendido (0-255).
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo el pin Chip Select (CS)a nivel bajo. Las instrucciones se envían en códigos de operaciones (opcodes) de 11 bits con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255. La transferencia del dato empieza con el bit más significativo (MSB, Most Significant Bit) en el flanco de subida de la señal de reloj. La señal de reloj es inactiva a nivel bajo, y la velocidad del interfaz de comunicación es mucho más rápida que la velocidad de procesamiento de Arduino, por lo que no es necesario un pre-escaler para adaptarse a la velocidad de transmisión.
/*The AD5206 is digitally controlled using SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) with the three most significant bits (11-9) defining the address of which potentiometer to adjust and the eight least significant bits (8-1) defining what value to set that potentiometer to from 0-255. Data is shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.*/
Inserte el chip AD5206 en el Breadboard. Conexión de 5V power y masa del breadboard a 5V power y masa de la placa del microcontrolador Arduino. Conecte los pines 3, 6, 10, 13, 16, 21 y 24 del AD5206 a 5V y los pines 1, 4, 9, 12, 15, 18, 19 y 22 a masa. Se ha conectado todos los pines A a masa y los pines B a 5V para crear 6 divisores de tensión.
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo el pin Chip Select (CS)a nivel bajo. Las instrucciones se envían en códigos de operaciones (opcodes) de 11 bits con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255. La transferencia del dato empieza con el bit más significativo (MSB, Most Significant Bit) en el flanco de subida de la señal de reloj. La señal de reloj es inactiva a nivel bajo, y la velocidad de comunicación del interfaz es mucho más rápida que la velocidad de procesamiento de Arduino, por lo que no es necesario un pre-escaler para adaptarse a la velocidad de transmisión.
Inserte el circuito integrado AD5206 en la placa de prueba. Conecta 5V de alimentación y masa de la placa de prueba a 5V de alimentación y masa de la placa de Arduino. Conecte los pines 3, 6, 10, 13, 16, 21 y 24 del AD5206 a +5V y los pines 1, 4, 9, 12, 15, 18, 19 y 22 a masa. Hemos conectado todos los pines A a masa y los pines B a +5V para crear 6 divisores de tensión.
/*Insert the AD5206 chip into the breadboard. Connect 5V power and ground from the breadboard to 5V power and ground from the microcontroller. Connect AD5206 pins 3, 6, 10, 13, 16, 21 and 24 to 5v and pins 1, 4, 9, 12, 15, 18, 19, and 22 to ground. We are connecting all the A pins to ground and all of the B pins to 5v to create 6 voltage dividers.*/
El AD5206 es un portenciómetro digital de 6 canales. Esto significa que tiene seis resistores variables (potenciómetros) en un circuito integrado. Hay tres pines por cada uno de los seis resistores variables internos, y se hace el conexionado como un potenciómetro mecánico. Los pines de cada resistor variable está etiquetado com Ax. Bx y Wx. Ejemplo: A1, B1 y W1
/*The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors (potentiometers) built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer. The individual variable resistor pins are labeled Ax, Bx and Wx, ie. A1, B1 and W1.*/
Por ejemplo, en este tutorial se usará cada resistor variable como un divisor de tensión en un lado se conecta el pin de tensión alta (pin B), en el otra lado el pin de tesnión baja (pin A) y se toma el pin central (pin W) como salida de la tensión variable.
/*For example, in this tutorial we will be using each variable resistor as a voltage divider by pulling one side pin (pin B) high, pulling another side pin (pin A) low and taking the variable voltage output of the center pin (Wiper).*/
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo a nivel bajo el pin Chip Select (CS). Las instrucciones se envían en códigos de operaciones de 11 bits (opcodes) con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255. La transferencia del dato empieza con el bit más significativo (MSB, Most Significant Bit) en el flanco de subida de la señal de reloj. La señal de reloj es inactiva a nivel bajo, y la velocidad del interfaz de comunicación es mucho más rápida que la velocidad de procesamiento de Arduino, por lo que no es necesario un pre-escaler para adaptarse a la velocidad de transmisión.
El AD5206 es un portenciómetro digital de 6 canales. Esto significa que tiene seis resistores variables (potenciómetros) en un circuito integrado. Hay tres pines en el circuito integrado por cada uno de los seis resistores variables internos, y se hace el conexionado como un potenciómetro mecánico. Los pines de cada resistor variable está etiquetado com Ax. Bx y Wx. Ejemplo: A1, B1 y W1
Por ejemplo, en este tutorial usaremos cada resistor variable como un divisor de tensión en un lado se conecta el pin de tensión alta (pin B), en el otra lado el pin de tesnión baja (pin A) y se toma el pin central (pin W) como salida de la tensión variable.
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo el pin Chip Select (CS)a nivel bajo. Las instrucciones se envían en códigos de operaciones (opcodes) de 11 bits con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255. La transferencia del dato empieza con el bit más significativo (MSB, Most Significant Bit) en el flanco de subida de la señal de reloj. La señal de reloj es inactiva a nivel bajo, y la velocidad del interfaz de comunicación es mucho más rápida que la velocidad de procesamiento de Arduino, por lo que no es necesario un pre-escaler para adaptarse a la velocidad de transmisión.
En este tutorial aprenderás como controlar el potenciómetro digital AD5206 usando el bus SPI (Serial Peripheral Interface). Para una explicación del funcionamineto del SPI ver el tutorial SPI EEPROM. Los potenciómetos digitales son útiles cuando se necesita variar la resistencia electrónicamente en un circuito en lugar de manualmente. Ejemplos de aplicaciones son la regulación de LED, acondicionamiento de señal de audio y generación de tono. En este ejemplo se usará un potenciómetro de seis canales para controlar el brillo de seis LEDs. Los pasos dados aquí para implementar la comunicación SPI se puede aplicar en otros dispositivos SPI.
En este tutorial aprenderás como controlar el potenciómetro digital AD5206 usando el bus SPI (Serial Peripheral Interface). Para una explicación del funcionamineto del SPI ver el tutorial SPI EEPROM. Los potenciómetos digitales son útiles cuando se necesita variar la resistencia electrónicamente en un circuito en lugar de manualmente. Ejemplos de aplicaciones son la regulación de LED, acondicionamiento de señal de audio y generación de tono. En este ejemplo se usará un potenciómetro de seis canales para controlar el brillo de seis LEDs. Los pasos que veremos aquí para implementar una comunicación SPI pueden ser fácilmente modificados para su uso con cualquier otro dispositivo SPI.
/*The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors (potentiometers) built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer. The individual variable resistor pins are labeled Ax, Bx and Wx, ie. A1, B1 and W1.
/*The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors (potentiometers) built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer. The individual variable resistor pins are labeled Ax, Bx and Wx, ie. A1, B1 and W1.*/
SPDR = data; // Start the transmission while (!(SPSR & (1<<SPIF))) // Wait the end of the transmission
SPDR = data; // Empezar la transmisión while (!(SPSR & (1<<SPIF))) // Espera la terminación de la transmisión
return SPDR; // return the received byte
return SPDR; // Devuelve el byte recibido
digitalWrite(SLAVESELECT,HIGH); //disable device
digitalWrite(SLAVESELECT,HIGH); //deshabilita el dispositivo SPI
digitalWrite(SLAVESELECT,HIGH); //release chip, signal end transfer
digitalWrite(SLAVESELECT,HIGH); //libera el chip, finalización transferencia
For easy copy and pasting the full program text of this tutorial is below:
Para mayor facilidad copiar y pegar el código completo del programa de este tutorial:
/*For easy copy and pasting the full program text of this tutorial is below: */
The write_pot function allows us to control the individual potentiometers. We set the SLAVESELECT line low to enable the device. Then we transfer the address byte followed by the resistance value byte. Finally, we set the SLAVSELECT line high again to release the chip and signal the end of our data transfer.
La función write_pot permite controlar cada potenciómeto. Se pone SLAVESELECT (pin 10) a nivel bajo para habilitar el dispositivo. A continuación se transfiere el byte de dirección seguido del byte del valor de la resistencia. Por último, se pone SLAVSELECT a nivel alto de nuevo para liberar el chip y terminar la transferencia del dato.
/*The write_pot function allows us to control the individual potentiometers. We set the SLAVESELECT line low to enable the device. Then we transfer the address byte followed by the resistance value byte. Finally, we set the SLAVSELECT line high again to release the chip and signal the end of our data transfer.*/
digitalWrite(SLAVESELECT,HIGH); //release chip, signal end transfer
digitalWrite(SLAVESELECT,HIGH); //liberar chip, fin de transmisión
SPDR = data; // Start the transmission while (!(SPSR & (1<<SPIF))) // Wait the end of the transmission
SPDR = data; // Empieza la transmisión while (!(SPSR & (1<<SPIF))) // Espera la terminación de la transmisión
return SPDR; // return the received byte
return SPDR; // Devuelve el byte recibido
The spi_transfer function loads the output data into the data transmission register, thus starting the SPI transmission. It polls a bit to the SPI Status register (SPSR) to detect when the transmission is complete using a bit mask, SPIF. An explanation of bit masks can be found here. It then returns any data that has been shifted in to the data register by the EEPROM:
La función spi_transfer carga el dato de salida en el registro de transmisión de datos, comenzando la transmisión SPI. Se sondea el bit (SPIF), usando un bit de máscara, del registro de estado (SPSR)del SPI para detectar cuando la transmisión serie se ha completado. Una explicación de bit de máscara se puede encontrar aquí. La función termina devolviendo el dato que se ha registrado en el registro de datos de la EEPROM.
/*The spi_transfer function loads the output data into the data transmission register, thus starting the SPI transmission. It polls a bit to the SPI Status register (SPSR) to detect when the transmission is complete using a bit mask, SPIF. An explanation of bit masks can be found here. It then returns any data that has been shifted in to the data register by the EEPROM:*/
In our main loop we iterate through each resistance value (0-255) for each potentiometer address (0-5). We pause for 10 milliseconds each iteration to make the steps visible. This causes the LEDs to sequentially flash on brightly and then fade out slowly:
En la función principal loop() se repite para incrementar el valor de la resistencia (0-255) para cada potenciómetro (0-5). Hay una pausa de 10 milisegunda en cada iteración para hacer visible los pasos. Este código hace que cada LED se encienda y luego se apague poco a poco, de manera secuencial.
/*In our main loop we iterate through each resistance value (0-255) for each potentiometer address (0-5). We pause for 10 milliseconds each iteration to make the steps visible. This causes the LEDs to sequentially flash on brightly and then fade out slowly:*/
We conclude the setup function by setting all the potentiometers to full on resistance states thereby turning the LEDs off:
Se termina la función setup() poniendo todos los potenciómetros con el valor máximo de resistencia, así los LEDs están apagados.
/*We conclude the setup function by setting all the potentiometers to full on resistance states thereby turning the LEDs off:*/
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2 pone al SPI para tomar los datos en el flanco de subida de la señal de reloj y el bit 1 y 0 ajusta la velocidad del SPI a la más rápida. Depués de configurar el registro de control se limpia el registro de estado (SPSR) del SPI y el registro de dato (SPDR) con la variable clr para eliminar posible datos almacenados anteriormente.
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2 pone al SPI para tomar los datos en el flanco de subida de la señal de reloj y el bit 1 y 0 ajusta la velocidad del SPI a la más rápida. Depués de configurar el registro de control se limpia el registro de estado (SPSR) y el registro de dato (SPDR) con la variable clr para eliminar posible datos almacenados anteriormente.
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2 pone al SPI para tomar los datos en el flanco de subida de la señal de reloj
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2 pone al SPI para tomar los datos en el flanco de subida de la señal de reloj y el bit 1 y 0 ajusta la velocidad del SPI a la más rápida. Depués de configurar el registro de control se limpia el registro de estado (SPSR) del SPI y el registro de dato (SPDR) con la variable clr para eliminar posible datos almacenados anteriormente.
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2 pone al SPI para tomar los datos en el flanco de subida de la señal de reloj
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2 pone
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2 pone
Ahora se pone en el registro de control (SPCR) del SPI el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro
Ahora se configura el registro de control (SPCR) del SPI con el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro, el bit 3 pone la señal de reloj desactiva a nivel bajo, el bit 2
Ahora se pone en el registro de control (SPCR) del SPI el valor binario 01010000. En este registro de control cada bit tiene una función. El bit 7 deshabilita la interrupción SPI, el bit 6 habilita el SPI, el bit 5 elige la transmisión del primer bit como MSB (Most Significant Bit), el bit 4 pone a Arduino en modo Maestro
En este tutorial aprenderás como controlar el potenciómetro digital AD5206 usando el bus SPI (Serial Peripheral Interface). Para una explicación del funcionamineto del SPI ver el SPI EEPROM tutorial. Los potenciómetos digitales son útiles cuando se necesita variar la resistencia electrónicamente en un circuito en lugar de manualmente. Ejemplos de aplicaciones son la regulación de LED, acondicionamiento de señal de audio y generación de tono. En este ejemplo se usará un potenciómetro de seis canales para controlar el brillo de seis LEDs. Los pasos dados aquí para implementar la comunicación SPI se puede aplicar en otros dispositivos SPI.
En este tutorial aprenderás como controlar el potenciómetro digital AD5206 usando el bus SPI (Serial Peripheral Interface). Para una explicación del funcionamineto del SPI ver el tutorial SPI EEPROM. Los potenciómetos digitales son útiles cuando se necesita variar la resistencia electrónicamente en un circuito en lugar de manualmente. Ejemplos de aplicaciones son la regulación de LED, acondicionamiento de señal de audio y generación de tono. En este ejemplo se usará un potenciómetro de seis canales para controlar el brillo de seis LEDs. Los pasos dados aquí para implementar la comunicación SPI se puede aplicar en otros dispositivos SPI.
Now we set the SPI Control register (SPCR) to the binary value 01010000. In the control register each bit sets a different functionality. The eighth bit disables the SPI interrupt, the seventh bit enables the SPI, the sixth bit chooses transmission with the most significant bit going first, the fifth bit puts the Arduino in Master mode, the fourth bit sets the data clock idle when it is low, the third bit sets the SPI to sample data on the rising edge of the data clock, and the second and first bits set the speed of the SPI to system speed / 4 (the fastest). After setting our control register up we read the SPI status register (SPSR) and data register (SPDR) in to the junk clr variable to clear out any spurious data from past runs:
/*Now we set the SPI Control register (SPCR) to the binary value 01010000. In the control register each bit sets a different functionality. The eighth bit disables the SPI interrupt, the seventh bit enables the SPI, the sixth bit chooses transmission with the most significant bit going first, the fifth bit puts the Arduino in Master mode, the fourth bit sets the data clock idle when it is low, the third bit sets the SPI to sample data on the rising edge of the data clock, and the second and first bits set the speed of the SPI to system speed / 4 (the fastest). After setting our control register up we read the SPI status register (SPSR) and data register (SPDR) in to the junk clr variable to clear out any spurious data from past runs:*/
digitalWrite(SLAVESELECT,HIGH); //disable device
digitalWrite(SLAVESELECT,HIGH); //dispositivo SPI deshabilitado
First we set our input and output pin modes and set the SLAVESELECT line high to start. This deselects the device and avoids any false transmission messages due to line noise:
Primero se configuras el modo de los pines como entrada y salida y se pone el pin digital de salida SLAVESELECT a nivel alto para empezar. Esto hace que desactive el dispositivo SPI y evita datos falsos en la transmisión debido al ruido de la línea.
/*First we set our input and output pin modes and set the SLAVESELECT line high to start. This deselects the device and avoids any false transmission messages due to line noise:*/
Next we allocate variables to store resistance values and address values for the potentiometers:
A continuación se asigna variables para almacenar el valor de las resistencias y la dirección de los potenciómetros.
/*Next we allocate variables to store resistance values and address values for the potentiometers:*/
Se definen los pines que se usan para la conexión al SPI, DATAOUT, DATAIN, SPICLOCK y SLAVESELECT.
Se definen los pines que se usan para la conexión al SPI, DATAOUT, DATAIN, SPICLOCK y SLAVESELECT. Aunque no se están leyendo datos del AD5206 en este programa, el pin 12 está asignado a recepción de datos de un dispositivo SPI. Por tanto, es mejor no utilizarlo para otras tareas de programación para evitar posibles errores.
We will walk through the code in small sections.
We define the pins we will be using for our SPI connection, DATAOUT, DATAIN, SPICLOCK and SLAVESELECT. Although we are not reading any data back out of the AD5206 in this program, pin 12 is attached to the builtin SPI so it is best not to use it for other programming functions to avoid any possible errors:
A continuación el código del programa en pequeñas secciones.
/*We will walk through the code in small sections.*/
Se definen los pines que se usan para la conexión al SPI, DATAOUT, DATAIN, SPICLOCK y SLAVESELECT.
/*We define the pins we will be using for our SPI connection, DATAOUT, DATAIN, SPICLOCK and SLAVESELECT. Although we are not reading any data back out of the AD5206 in this program, pin 12 is attached to the builtin SPI so it is best not to use it for other programming functions to avoid any possible errors:*/
Ahora se escribe el código para realizar el control del AD5206 por comunicación SPI. Este programa activa secuencialmente cada LED y luego se va apagando gradualmente. Esto se hace en la función loop() del programa
Ahora se escribe el código para realizar el control del AD5206 por comunicación SPI. Este programa activa secuencialmente cada LED y luego se va apagando gradualmente. Esto se hace en la función principal loop() del programa cambiando individualmente el valor de resistencia de cada potenciómetro desde apagado hasta encendido (0-255).
Ahora se escribe el código para realizar el control del AD5206 por comunicación SPI
Ahora se escribe el código para realizar el control del AD5206 por comunicación SPI. Este programa activa secuencialmente cada LED y luego se va apagando gradualmente. Esto se hace en la función loop() del programa
Now we will write the code to enable SPI control of the AD5206. This program will sequentially pulse each LED on and then fade it out gradually. This is accomplished in the main loop of the program by individually changing the resistance of each potentiometer from full off to full on over its full range of 255 steps.
Ahora se escribe el código para realizar el control del AD5206 por comunicación SPI /*Now we will write the code to enable SPI control of the AD5206. This program will sequentially pulse each LED on and then fade it out gradually. This is accomplished in the main loop of the program by individually changing the resistance of each potentiometer from full off to full on over its full range of 255 steps.*/
Por ejemplo, en este tutorial se usará cada resistor variable como un divisor de tensión en un lado se conecta el pin de tensión alta (pin B), en el otra lado el pin de tesnión baja (pin A) y se toma el pin central (pin W) como salida de la tesnión variable.
Por ejemplo, en este tutorial se usará cada resistor variable como un divisor de tensión en un lado se conecta el pin de tensión alta (pin B), en el otra lado el pin de tesnión baja (pin A) y se toma el pin central (pin W) como salida de la tensión variable.
Finally, connect an LED between each Wiper pin (AD5206 pins 2, 11, 14, 17, 20 and 23) and ground so that the long pin of the LED connects to the wiper and the short pin, or flat side of the LED connects to ground.
Finalmente, conectar cada uno de los LEDs entre el pin W (en el AD5206 los pines 2, 11, 14, 17, 20 y 23) y masa, de la siguiente manera: la patilla larga del LED conectada al pin W y la patilla corta, o la cara plana del LED, conectada a masa.
/*Finally, connect an LED between each Wiper pin (AD5206 pins 2, 11, 14, 17, 20 and 23) and ground so that the long pin of the LED connects to the wiper and the short pin, or flat side of the LED connects to ground.*/
Connect AD5206 pin 5 to Arduino pin 10 (Slave Select - SS), AD5206 pin 7 to Arduino pin 11 (Master Out Slave In - MOSI), and AD5206 pin 8 to Arduino pin 13 (Serial Clock - SCK).
Conectar el pin 5 de AD5206 al pin 10 de Arduino (Slave Select - SS), el pin 7 de AD5206 al pin 11 de Arduino (Master Out Slave In - MMOSI), y el pin 8 de AD5206 al pin 13 de Arduino (Serial Clock - SCK)
/*Connect AD5206 pin 5 to Arduino pin 10 (Slave Select - SS), AD5206 pin 7 to Arduino pin 11 (Master Out Slave In - MOSI), and AD5206 pin 8 to Arduino pin 13 (Serial Clock - SCK).*/
Inserte el chip AD5206 en el Breadboard. Conexión de 5V power y masa del breadboard a 5V power y masa de la placa del microcontrolador Arduino.
Inserte el chip AD5206 en el Breadboard. Conexión de 5V power y masa del breadboard a 5V power y masa de la placa del microcontrolador Arduino. Conecte los pines 3, 6, 10, 13, 16, 21 y 24 del AD5206 a 5V y los pines 1, 4, 9, 12, 15, 18, 19 y 22 a masa. Se ha conectado todos los pines A a masa y los pines B a 5V para crear 6 divisores de tensión.
Insert the AD5206 chip into the breadboard. Connect 5V power and ground from the breadboard to 5V power and ground from the microcontroller. Connect AD5206 pins 3, 6, 10, 13, 16, 21 and 24 to 5v and pins 1, 4, 9, 12, 15, 18, 19, and 22 to ground. We are connecting all the A pins to ground and all of the B pins to 5v to create 6 voltage dividers.
Inserte el chip AD5206 en el Breadboard. Conexión de 5V power y masa del breadboard a 5V power y masa de la placa del microcontrolador Arduino.
/*Insert the AD5206 chip into the breadboard. Connect 5V power and ground from the breadboard to 5V power and ground from the microcontroller. Connect AD5206 pins 3, 6, 10, 13, 16, 21 and 24 to 5v and pins 1, 4, 9, 12, 15, 18, 19, and 22 to ground. We are connecting all the A pins to ground and all of the B pins to 5v to create 6 voltage dividers.*/
/*The AD5206 is digitally controlled using SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) with the three most significant bits (11-9) defining the address of which potentiometer to adjust and the eight least significant bits (8-1) defining what value to set that potentiometer to from 0-255. Data is shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.
/*The AD5206 is digitally controlled using SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) with the three most significant bits (11-9) defining the address of which potentiometer to adjust and the eight least significant bits (8-1) defining what value to set that potentiometer to from 0-255. Data is shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.*/
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo a nivel bajo el pin Chip Select (CS). Las instrucciones se envían en códigos de operaciones de 11 bits (opcodes) con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255. La transferencia del dato empieza con el bit más significativo (MSB, Most Significant Bit) en el flanco de subida de la señal de reloj. La señal de reloj es inactiva a nivel bajo, y la velocidad del interfaz de comunicación es mucho más rápida que la velocidad de procesamiento de Arduino,
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo a nivel bajo el pin Chip Select (CS). Las instrucciones se envían en códigos de operaciones de 11 bits (opcodes) con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255. La transferencia del dato empieza con el bit más significativo (MSB, Most Significant Bit) en el flanco de subida de la señal de reloj. La señal de reloj es inactiva a nivel bajo, y la velocidad del interfaz de comunicación es mucho más rápida que la velocidad de procesamiento de Arduino, por lo que no es necesario un pre-escaler para adaptarse a la velocidad de transmisión.
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo a nivel bajo el pin Chip Select (CS). Las instrucciones se envían en códigos de operaciones de 11 bits (opcodes) con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255.
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo a nivel bajo el pin Chip Select (CS). Las instrucciones se envían en códigos de operaciones de 11 bits (opcodes) con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255. La transferencia del dato empieza con el bit más significativo (MSB, Most Significant Bit) en el flanco de subida de la señal de reloj. La señal de reloj es inactiva a nivel bajo, y la velocidad del interfaz de comunicación es mucho más rápida que la velocidad de procesamiento de Arduino,
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo a nivel bajo el pin Chip Select (CS).
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo a nivel bajo el pin Chip Select (CS). Las instrucciones se envían en códigos de operaciones de 11 bits (opcodes) con los tres bits más significativos (11-9) definiendo la dirección del potenciómetro a ajustar y los ocho bits menos significativos (8-1)definiendo que valor poner al potenciómetro entre 0-255.
For example, in this tutorial we will be using each variable resistor as a voltage divider by pulling one side pin (pin B) high, pulling another side pin (pin A) low and taking the variable voltage output of the center pin (Wiper).
The AD5206 is digitally controlled using SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) with the three most significant bits (11-9) defining the address of which potentiometer to adjust and the eight least significant bits (8-1) defining what value to set that potentiometer to from 0-255. Data is shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.
/*For example, in this tutorial we will be using each variable resistor as a voltage divider by pulling one side pin (pin B) high, pulling another side pin (pin A) low and taking the variable voltage output of the center pin (Wiper).*/
El AD5206 es controlado digitalmente usando SPI. El dispositivo es habilitado poniendo a nivel bajo el pin Chip Select (CS).
/*The AD5206 is digitally controlled using SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) with the three most significant bits (11-9) defining the address of which potentiometer to adjust and the eight least significant bits (8-1) defining what value to set that potentiometer to from 0-255. Data is shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.
En este tutorial aprenderás como controlar el potenciómetro digital AD5206 usando el bus SPI (Serial Peripheral Interface). Para una explicación del funcionamineto del SPI ver el SPI EEPROM tutorial. Los potenciómetos digitales son útiles cuando se necesita variar la resistencia electrónicamente en un circuito en lugar de manualmente. Ejemplos de aplicaciones son la regulación de LED, acondicionamiento de señal de audio y generación de tono. En este ejemplo se usará un potenciómetro de seis canales para controlar el brillo de seis LEDs. los pasos para implementar la comunicación SPI se puede aplicar en otros dispositivos SPI.
En este tutorial aprenderás como controlar el potenciómetro digital AD5206 usando el bus SPI (Serial Peripheral Interface). Para una explicación del funcionamineto del SPI ver el SPI EEPROM tutorial. Los potenciómetos digitales son útiles cuando se necesita variar la resistencia electrónicamente en un circuito en lugar de manualmente. Ejemplos de aplicaciones son la regulación de LED, acondicionamiento de señal de audio y generación de tono. En este ejemplo se usará un potenciómetro de seis canales para controlar el brillo de seis LEDs. Los pasos dados aquí para implementar la comunicación SPI se puede aplicar en otros dispositivos SPI.
Por ejemplo, en este tutorial se usará cada resistor variable como un divisor de tensión en un lado se conecta el pin de tensión alta (pin B), en el otra lado el pin de tesnión baja (pin A) y se toma el pin central (pin W) como salida de la tesnión variable.
El AD5206 es un portenciómetro digital de 6 canales.
El AD5206 es un portenciómetro digital de 6 canales. Esto significa que tiene seis resistores variables (potenciómetros) en un circuito integrado. Hay tres pines por cada uno de los seis resistores variables internos, y se hace el conexionado como un potenciómetro mecánico. Los pines de cada resistor variable está etiquetado com Ax. Bx y Wx. Ejemplo: A1, B1 y W1
The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors (potentiometers) built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer. The individual variable resistor pins are labeled Ax, Bx and Wx, ie. A1, B1 and W1.
El AD5206 es un portenciómetro digital de 6 canales.
/*The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors (potentiometers) built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer. The individual variable resistor pins are labeled Ax, Bx and Wx, ie. A1, B1 and W1.
In this tutorial you will learn how to control the AD5206 digital potentiometer using Serial Peripheral Interface (SPI). For an explanation of SPI see the SPI EEPROM tutorial. Digital potentiometers are useful when you need to vary the resistance in a ciruit electronically rather than by hand. Example applications include LED dimming, audio signal conditioning and tone generation. In this example we will use a six channel digital potentiometer to control the brightness of six LEDs. The steps we will cover for implementing SPI communication can be modified for use with most other SPI devices.
Materials Needed:
En este tutorial aprenderás como controlar el potenciómetro digital AD5206 usando el bus SPI (Serial Peripheral Interface). Para una explicación del funcionamineto del SPI ver el SPI EEPROM tutorial. Los potenciómetos digitales son útiles cuando se necesita variar la resistencia electrónicamente en un circuito en lugar de manualmente. Ejemplos de aplicaciones son la regulación de LED, acondicionamiento de señal de audio y generación de tono. En este ejemplo se usará un potenciómetro de seis canales para controlar el brillo de seis LEDs. los pasos para implementar la comunicación SPI se puede aplicar en otros dispositivos SPI.
Materiales necesarios:
VIDEO ? LEDs
LED video
@]
@]
code, tutorial and photos by Heather Dewey-Hagborg
PICTURE power

PICTURE datacom

PICTURE leds

Materials Needed:
PICTURE pins
PICTURE pin functions


VIDEO ? LEDs
The write_pot function allows us to control the individual potentiometers. First we shift the potentiometer address 8 bits to the left to put it in the most significant bit position of the 11 bit data byte. This makes room to add the resistance value which occupies the least significant eight bits of the data byte. When we sum the two together we get our 11 bit opcode to transmit:
The write_pot function allows us to control the individual potentiometers. We set the SLAVESELECT line low to enable the device. Then we transfer the address byte followed by the resistance value byte. Finally, we set the SLAVSELECT line high again to release the chip and signal the end of our data transfer.
int opcode=0; address<<=8; //shift pot address 8 left, ie. 101 = 10100000000 opcode = address+value; //10111111111
@]
We set the SLAVESELECT line low to enable the device. Then we transfer the 11 bit opcode in two bytes sending the eight most significant bits first and sending the three least significant bits last. We set the SLAVSELECT line high again to release the chip and signal the end of our data transfer.
[@
spi_transfer((char)(opcode>>8)); //send MSByte address first a0a1a2d0d1d2d3d4 spi_transfer((char)(opcode)); //send LSByte address, d5d6d700000
spi_transfer(address); spi_transfer(value);
int opcode=0; address<<=8; //shift pot address 8 left, ie. 101 = 10100000000 opcode = address+value; //10111111111
spi_transfer((char)(opcode>>8)); //send MSByte address first a0a1a2d0d1d2d3d4 spi_transfer((char)(opcode)); //send LSByte address, d5d6d700000
spi_transfer(address); spi_transfer(value);
The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer. The individual variable resistor pins are labeled Ax, Bx and Wx, ie. A1, B1 and W1.
The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors (potentiometers) built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer. The individual variable resistor pins are labeled Ax, Bx and Wx, ie. A1, B1 and W1.
The spi_transfer function loads the output data into the data transmission register, thus starting the SPI transmission. It polls a bit to the SPI Status register (SPSR) to detect when the transmission is complete using a bit mask, SPIF. An explanation of bit masks can be found here?. It then returns any data that has been shifted in to the data register by the EEPROM:
In our main loop we iterate through each resistance value (0-255) for each potentiometer address (0-5). We pause for 10 milliseconds each iteration to make the steps visible. This causes the LEDs to sequentially flash on brightly and then fade out slowly:
char spi_transfer(volatile char data)
void loop()
SPDR = data; // Start the transmission
while (!(SPSR & (1<<SPIF))) // Wait the end of the transmission
{
};
return SPDR; // return the received byte
write_pot(pot,resistance);
delay(10);
resistance++;
if (resistance==255)
{
pot++;
}
if (pot==6)
{
pot=0;
}
@]
The spi_transfer function loads the output data into the data transmission register, thus starting the SPI transmission. It polls a bit to the SPI Status register (SPSR) to detect when the transmission is complete using a bit mask, SPIF. An explanation of bit masks can be found here. It then returns any data that has been shifted in to the data register by the EEPROM:
char spi_transfer(volatile char data)
{
SPDR = data; // Start the transmission
while (!(SPSR & (1<<SPIF))) // Wait the end of the transmission
{
};
return SPDR; // return the received byte
}
The write_pot function allows us to control the individual potentiometers. First we shift the potentiometer address 8 bits to the left to put it in the most significant bit position of the 11 bit data byte. This makes room to add the resistance value which occupies the least significant eight bits of the data byte. When we sum the two together we get our 11 bit opcode to transmit:
byte write_pot(int address, int value)
{
int opcode=0;
address<<=8; //shift pot address 8 left, ie. 101 = 10100000000
opcode = address+value; //10111111111
We set the SLAVESELECT line low to enable the device. Then we transfer the 11 bit opcode in two bytes sending the eight most significant bits first and sending the three least significant bits last. We set the SLAVSELECT line high again to release the chip and signal the end of our data transfer.
digitalWrite(SLAVESELECT,LOW); //2 byte opcode spi_transfer((char)(opcode>>8)); //send MSByte address first a0a1a2d0d1d2d3d4 spi_transfer((char)(opcode)); //send LSByte address, d5d6d700000 digitalWrite(SLAVESELECT,HIGH); //release chip, signal end transfer }
For easy copy and pasting the full program text of this tutorial is below:
[@
byte pot=0; byte resistance=0;
char spi_transfer(volatile char data) {
SPDR = data; // Start the transmission
while (!(SPSR & (1<<SPIF))) // Wait the end of the transmission
{
};
return SPDR; // return the received byte
}
void setup() {
byte i;
byte clr;
pinMode(DATAOUT, OUTPUT);
pinMode(DATAIN, INPUT);
pinMode(SPICLOCK,OUTPUT);
pinMode(SLAVESELECT,OUTPUT);
digitalWrite(SLAVESELECT,HIGH); //disable device
// SPCR = 01010000
//interrupt disabled,spi enabled,msb 1st,master,clk low when idle,
//sample on leading edge of clk,system clock/4 (fastest)
SPCR = (1<<SPE)|(1<<MSTR);
clr=SPSR;
clr=SPDR;
delay(10);
for (i=0;i<6;i++)
{
write_pot(i,255);
}
}
byte write_pot(int address, int value) {
int opcode=0; address<<=8; //shift pot address 8 left, ie. 101 = 10100000000 opcode = address+value; //10111111111 digitalWrite(SLAVESELECT,LOW); //2 byte opcode spi_transfer((char)(opcode>>8)); //send MSByte address first a0a1a2d0d1d2d3d4 spi_transfer((char)(opcode)); //send LSByte address, d5d6d700000 digitalWrite(SLAVESELECT,HIGH); //release chip, signal end transfer
}
void loop() {
write_pot(pot,resistance);
delay(10);
resistance++;
if (resistance==255)
{
pot++;
}
if (pot==6)
{
pot=0;
}
}
First we set our input and output pin modes and set the SLAVESELECT line high to start. This deselects the device and avoids any false transmission messages due to line noise:
void setup()
{
byte clr;
pinMode(DATAOUT, OUTPUT);
pinMode(DATAIN, INPUT);
pinMode(SPICLOCK,OUTPUT);
pinMode(SLAVESELECT,OUTPUT);
digitalWrite(SLAVESELECT,HIGH); //disable device
Now we set the SPI Control register (SPCR) to the binary value 01010000. In the control register each bit sets a different functionality. The eighth bit disables the SPI interrupt, the seventh bit enables the SPI, the sixth bit chooses transmission with the most significant bit going first, the fifth bit puts the Arduino in Master mode, the fourth bit sets the data clock idle when it is low, the third bit sets the SPI to sample data on the rising edge of the data clock, and the second and first bits set the speed of the SPI to system speed / 4 (the fastest). After setting our control register up we read the SPI status register (SPSR) and data register (SPDR) in to the junk clr variable to clear out any spurious data from past runs:
SPCR = (1<<SPE)|(1<<MSTR); clr=SPSR; clr=SPDR; delay(10);
We conclude the setup function by setting all the potentiometers to full on resistance states thereby turning the LEDs off:
for (i=0;i<6;i++)
{
write_pot(i,255);
}
}
The spi_transfer function loads the output data into the data transmission register, thus starting the SPI transmission. It polls a bit to the SPI Status register (SPSR) to detect when the transmission is complete using a bit mask, SPIF. An explanation of bit masks can be found here?. It then returns any data that has been shifted in to the data register by the EEPROM:
char spi_transfer(volatile char data)
{
SPDR = data; // Start the transmission
while (!(SPSR & (1<<SPIF))) // Wait the end of the transmission
{
};
return SPDR; // return the received byte
}
The AD5206 is digitally controlled using SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) and are shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.
The AD5206 is digitally controlled using SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) with the three most significant bits (11-9) defining the address of which potentiometer to adjust and the eight least significant bits (8-1) defining what value to set that potentiometer to from 0-255. Data is shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.
Finally, connect an LED between each Wiper pin (AD5206 pins 2, 11, 14, 17, 20 and 23) and ground so that the long pin of the LED connects to the wiper and the short pin, or flat side of the LED connects to ground.
PICTURE leds
Now we will write the code to enable SPI control of the AD5206. This program will sequentially pulse each LED on and then fade it out gradually. This is accomplished in the main loop of the program by individually changing the resistance of each potentiometer from full off to full on over its full range of 255 steps.
We will walk through the code in small sections.
We define the pins we will be using for our SPI connection, DATAOUT, DATAIN, SPICLOCK and SLAVESELECT. Although we are not reading any data back out of the AD5206 in this program, pin 12 is attached to the builtin SPI so it is best not to use it for other programming functions to avoid any possible errors:
#define DATAOUT 11//MOSI #define DATAIN 12//MISO - not used, but part of builtin SPI #define SPICLOCK 13//sck #define SLAVESELECT 10//ss
Next we allocate variables to store resistance values and address values for the potentiometers:
byte pot=0; byte resistance=0;
The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer.
The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer. The individual variable resistor pins are labeled Ax, Bx and Wx, ie. A1, B1 and W1.
The AD5206 is digitally controlled using standard SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) and are shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.
The AD5206 is digitally controlled using SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) and are shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.
Insert the AD5206 chip into the breadboard. Connect 5V power and ground from the breadboard to 5V power and ground from the microcontroller. Connect AD5206 pins 3, 6, 10, 13, 16, 21 and 24 to 5v and pins 1, 4, 9, 12, 15, 18, 19, and 22 to ground. We are connecting all the A pins to ground and all of the B pins to 5v to create 6 voltage dividers.
PICTURE power
Connect AD5206 pin 5 to Arduino pin 10 (Slave Select - SS), AD5206 pin 7 to Arduino pin 11 (Master Out Slave In - MOSI), and AD5206 pin 8 to Arduino pin 13 (Serial Clock - SCK).
PICTURE datacom
The AD5206 is digitally controlled using standard SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) and are shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs up to speeds of 100Mhz.
The AD5206 is digitally controlled using standard SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) and are shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs much faster than the Arduino, so we don't need to worry about pre-scaling to slow down the transmission.
The AD5206is controlled using standard SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 8 bit operational codes (opcodes) and are shifted in on the rising edge of the data clock.
The AD5206 is digitally controlled using standard SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 11 bit operational codes (opcodes) and are shifted in Most Significant Bit (MSB) first on the rising edge of the data clock. The data clock is idle when low, and the interface runs up to speeds of 100Mhz.
In this tutorial you will learn how to control the AD5206 digital potentiometer using Serial Peripheral Interface (SPI). For an explanation of SPI see the SPI EEPROM tutorial. Digital potentiometers are useful when you need to vary the resistance in a ciruit electronically rather than by hand. Example applications include LED dimming, audio signal conditioning and tone generation. In this example we will use a six channel digital potentiometer to control the brightness of six LEDs. The steps we will cover for implementing SPI communication can be modified for use with most other SPI devices.
PICTURE pins
PICTURE pin functions
The AD5206 is a 6 channel digital potentiometer. This means it has six variable resistors built in for individual electronic control. There are three pins on the chip for each of the six internal variable resistors, and they can be interfaced with just as you would use a mechanical potentiometer.
For example, in this tutorial we will be using each variable resistor as a voltage divider by pulling one side pin (pin B) high, pulling another side pin (pin A) low and taking the variable voltage output of the center pin (Wiper).
The AD5206is controlled using standard SPI. The device is enabled by pulling the Chip Select (CS) pin low. Instructions are sent as 8 bit operational codes (opcodes) and are shifted in on the rising edge of the data clock.