Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //If you found my video helpful, please SUBSCRIBE: https://www.youtube.com/c/CuriousScientist?sub_confirmation=1
- //The code belongs to this tutorial video: https://youtu.be/_SHazOc5wSU
- //STM32-based digital potmeter
- #include <SPI.h> //SPI comunication
- int analogValue_1;
- int analogValue_2;
- const byte analogInputPin_1 = PA0;
- const byte analogInputPin_2 = PA1;
- const byte CS1_pin = PA4; //CS pin for potmeter 1
- const byte CS2_pin = PB9; //CS pin for potmeter 2
- float rwa_1;
- float rwa_2;
- float rwb_1;
- float rwb_2;
- int counter_1 = 0; //counter for the potmeter 1
- int counter_2 = 256; //counter for the potmeter 2
- void setup()
- {
- Serial.begin(9600);
- Serial.println("MCP41100");
- pinMode(CS1_pin, OUTPUT); //Chip select is an output
- pinMode(CS2_pin, OUTPUT); //Chip select is an output
- digitalWrite(CS1_pin, HIGH);
- digitalWrite(CS2_pin, HIGH);
- SPI.begin();
- }
- void loop()
- {
- writePotmeter_1();
- writePotmeter_2();
- delay(300);
- readAnalogPin_1();
- readAnalogPin_2();
- counter_1++;
- counter_2--;
- if(counter_1 > 256) //this is for the increasing counter
- {
- counter_1 = 0;
- }
- if(counter_2 < 1) //this is for the decreasing counter
- {
- counter_2 = 256;
- }
- }
- void writePotmeter_1()
- {
- //CS goes low
- digitalWrite(CS1_pin, LOW);
- SPI.transfer(0x11); //command 00010001 [00][01][00][01]
- SPI.transfer(counter_1);
- delayMicroseconds(100);
- Serial.print("counter_1: ");
- Serial.println(counter_1);
- //CS goes high
- digitalWrite(CS1_pin, HIGH);
- }
- void writePotmeter_2()
- {
- digitalWrite(CS2_pin, LOW);
- SPI.transfer(0x11); //command 00010001 [00][01][00][11]
- SPI.transfer(counter_2);
- delayMicroseconds(100);
- Serial.print("counter_2: ");
- Serial.println(counter_2);
- //End of transaction
- //CS goes high
- digitalWrite(CS2_pin, HIGH);
- }
- void readAnalogPin_1()
- {
- analogValue_1 = analogRead(analogInputPin_1);
- Serial.print("Analog_1: ");
- Serial.println(analogValue_1);
- //Calculate resistance
- rwa_1 = (100000 * (256 - counter_1)/256) + 125;
- rwb_1 = (100000 * (counter_1)/256) + 125;
- Serial.print("rwa_1: ");
- Serial.println(rwa_1);
- Serial.print("rwb_1: ");
- Serial.println(rwb_1);
- Serial.print("sum: ");
- Serial.println(rwa_1+rwb_1);
- }
- void readAnalogPin_2()
- {
- analogValue_2 = analogRead(analogInputPin_2);
- Serial.print("Analog_2: ");
- Serial.println(analogValue_2);
- //Calculate resistance
- rwa_2 = (100000 * (256 - counter_2)/256) + 125;
- rwb_2 = (100000 * (counter_2)/256) + 125;
- Serial.print("rwa_2: ");
- Serial.println(rwa_2);
- Serial.print("rwb_2: ");
- Serial.println(rwb_2);
- Serial.print("sum: ");
- Serial.println(rwa_2+rwb_2);
- }
- /*
- * Resistance formula
- * R = 100 kOhm *(256-x)/256 + Rw
- * Rw = 125 for the 100 kOhm
- * Check datasheet, because Rw depends on the VDD
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement