Arduino - Sensor de Força

Neste tutorial, vamos aprender:

Sobre o Sensor de Força

Pinagem do sensor de força

O sensor de força também é conhecido como resistor sensor de força, resistor sensível à força, ou simplesmente FSR. O sensor de força é basicamente um resistor que muda seu valor de resistência dependendo de quanto ele foi pressionado. O sensor de força é:

  • Barato e fácil de usar.
  • Bom para detectar pressão física e aperto.
  • Não é bom para descobrir quantos quilos de peso há sobre ele.

O sensor de força é usado em baterias eletrônicas, celulares, consoles de jogos portáteis e muitos outros eletrônicos portáteis.

Pinagem

Um sensor de força tem dois pinos. Como ele é um tipo de resistor, NÃO precisamos distinguir esses pinos. Eles são simétricos.

Como Funciona

O sensor de força é basicamente um resistor que muda sua resistência dependendo de quanto ele foi pressionado. Quanto mais forte você pressionar o sensor, menor será a resistência entre os dois terminais.

Diagrama de Ligação

Diagrama de Ligação do Sensor de Força com Arduino

This image is created using Fritzing. Click to enlarge image

Como Programar o Sensor de Força

Os pinos A0 a A5 do Arduino Uno podem funcionar como entrada analógica. O pino de entrada analógica converte a tensão (entre 0v e VCC) em valores inteiros (entre 0 e 1023), chamados de valor ADC ou valor analógico.

Ao conectar um pino do sensor de força a um pino de entrada analógica, podemos ler o valor analógico do pino usando a função analogRead() e, então, podemos saber o quanto ele foi pressionado.

Código Arduino

/* * Este código de Arduino foi desenvolvido por pt.newbiely.com * Este código de Arduino é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino/arduino-force-sensor */ #define FORCE_SENSOR_PIN A0 // the FSR and 10K pulldown are connected to A0 void setup() { Serial.begin(9600); } void loop() { int analogReading = analogRead(FORCE_SENSOR_PIN); Serial.print("Force sensor reading = "); Serial.print(analogReading); // print the raw analog reading if (analogReading < 10) // from 0 to 9 Serial.println(" -> no pressure"); else if (analogReading < 200) // from 10 to 199 Serial.println(" -> light touch"); else if (analogReading < 500) // from 200 to 499 Serial.println(" -> light squeeze"); else if (analogReading < 800) // from 500 to 799 Serial.println(" -> medium squeeze"); else // from 800 to 1023 Serial.println(" -> big squeeze"); delay(1000); }

Passos Rápidos

  • Copie o código acima e abra-o com o Arduino IDE
  • Clique no botão Upload no Arduino IDE para carregar o código no Arduino
  • Pressione o sensor de força
  • Veja o resultado no Serial Monitor.
∞
Newbiely | Arduino IDE 2.3.8
──
☐
✕
File
Edit
Sketch
Tools
Help
Arduino Uno
Newbiely.ino
···
8 Serial.println("Hello World!");
Output
Serial Monitor
Message (Enter to send message to 'Arduino Uno' on 'COM15')
New Line
9600 baud
Force sensor reading = 0 -> no pressure Force sensor reading = 0 -> no pressure Force sensor reading = 132 -> light touch Force sensor reading = 147 -> light touch Force sensor reading = 394 -> light squeeze Force sensor reading = 421 -> light squeeze Force sensor reading = 607 -> medium squeeze Force sensor reading = 791 -> medium squeeze Force sensor reading = 921 -> big squeeze Force sensor reading = 987 -> big squeeze Force sensor reading = 0 -> no pressure Force sensor reading = 0 -> no pressure
Ln 11, Col 1
Arduino Uno on COM15
2

Vídeo

O vídeo de demonstração abaixo usa o código abaixo. Observe que o vídeo mostra o Arduino Uno R4, mas funciona de forma idêntica para o Arduino Uno R3:

/* * Este código de Arduino foi desenvolvido por pt.newbiely.com * Este código de Arduino é disponibilizado ao público sem nenhuma restrição. * Para tutoriais completos e diagramas de ligação, visite: * https://pt.newbiely.com/tutorials/arduino/arduino-force-sensor */ #include <Wire.h> #include <Adafruit_GFX.h> #include <Adafruit_SSD1306.h> // OLED display configuration #define SCREEN_WIDTH 128 #define SCREEN_HEIGHT 64 #define OLED_RESET -1 Adafruit_SSD1306 display( SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET ); // Force-sensitive resistor input #define FORCE_SENSOR_PIN A0 // LED pins used to indicate force level const int ledPins[8] = { 2, 3, 4, 5, 6, 7, 8, 9 }; // Calibrated force sensor range const int FORCE_MIN = 0; const int FORCE_MAX = 1000; // Exponential moving average filter float smoothValue = 0; const float alpha = 0.3; // Initialize hardware and display void setup() { Serial.begin(115200); // Configure LED outputs and turn all LEDs off. for (int i = 0; i < 8; i++) { pinMode(ledPins[i], OUTPUT); digitalWrite(ledPins[i], LOW); } // Initialize the OLED using I2C communication. if (!display.begin( SSD1306_SWITCHCAPVCC, 0x3C )) { Serial.println("OLED failed!"); // Stop execution if the OLED cannot be initialized. while (1); } display.clearDisplay(); display.setTextColor(SSD1306_WHITE); // Display startup screen. display.setTextSize(2); display.setCursor(20, 25); display.println("DIYables"); display.display(); delay(1500); // Initialize the filter with the first sensor reading // to prevent an incorrect initial value. smoothValue = analogRead(FORCE_SENSOR_PIN); } void loop() { // Read the current FSR value. int rawValue = analogRead(FORCE_SENSOR_PIN); // Apply exponential moving average filtering // to reduce sensor noise and fluctuations. smoothValue = alpha * rawValue + (1.0 - alpha) * smoothValue; int forceValue = (int)smoothValue; // Convert the sensor value into 8 force levels. int level = map( forceValue, FORCE_MIN, FORCE_MAX, 0, 8 ); level = constrain(level, 0, 8); // Turn on LEDs progressively according to the force level. for (int i = 0; i < 8; i++) { if (i < level) { digitalWrite(ledPins[i], HIGH); } else { digitalWrite(ledPins[i], LOW); } } // Output sensor data for monitoring and calibration. Serial.print("FSR = "); Serial.print(forceValue); Serial.print(" | Level = "); Serial.println(level); // Refresh OLED display. display.clearDisplay(); // Display title. display.setTextSize(2); display.setCursor(50, 0); display.println("FSR"); // Configure the force indicator as a battery-style bar. int barX = 10; int barY = 25; int barWidth = 108; int barHeight = 18; // Draw the outer bar. display.drawRect( barX, barY, barWidth, barHeight, SSD1306_WHITE ); // Draw the battery terminal. display.fillRect( barX + barWidth, barY + 5, 4, 8, SSD1306_WHITE ); // Calculate the filled portion based on the force level. int fillWidth = map( level, 0, 8, 0, barWidth - 4 ); if (fillWidth > 0) { display.fillRect( barX + 2, barY + 2, fillWidth, barHeight - 4, SSD1306_WHITE ); } // Display current force level. display.setTextSize(1); display.setCursor(5, 50); display.print("LEVEL: "); display.print(level); display.print("/8"); // Display project branding. display.setCursor(78, 50); display.print("DIYables"); display.display(); // Short delay for stable display updates. delay(30); }

※ NOSSAS MENSAGENS

  • Fique à vontade para compartilhar o link deste tutorial. Porém, por favor, não use nosso conteúdo em outros sites. Investimos muito esforço e tempo para criar este conteúdo, por favor respeite nosso trabalho!