Skip to main content

Grove - Switch(P)

Este Grove – Switch es un mini interruptor deslizante SPDT, excelente para situaciones de "ENCENDIDO/APAGADO". Es un interruptor confiable de gran calidad de construcción que adoptamos en muchas de nuestras placas. Deberías tener algunos en stock para tu sistema de prototipado Grove.

¿Qué significa "P"? "P" significa "montaje en panel" en este producto.

Versión

Versión del ProductoCambiosFecha de Lanzamiento
Grove-Switch(P) V1.0InicialJul 2012

Características

  • Interfaz Grove
  • Fácil de usar
  • Elemento básico de Grove
tip

Para más detalles sobre los módulos Grove, consulte Sistema Grove

Especificaciones

ParámetroValor/Rango
Voltaje de operación3.3/5V
Vida eléctrica10,000 ciclos
Fuerza de operación200 ± 50gf
Temperatura de operación-20℃ a +80℃
Tamaño20mmX20mm

Plataformas Compatibles

ArduinoRaspberry Pi
caution

Las plataformas mencionadas anteriormente como compatibles son una indicación de la compatibilidad de software o teórica del módulo. Solo proporcionamos biblioteca de software o ejemplos de código para la plataforma Arduino en la mayoría de los casos. No es posible proporcionar biblioteca de software / código de demostración para todas las plataformas MCU posibles. Por lo tanto, los usuarios tienen que escribir su propia biblioteca de software.

Primeros Pasos

note

Si esta es la primera vez que trabajas con Arduino, te recomendamos firmemente que veas Primeros Pasos con Arduino antes de comenzar.

Jugar Con Arduino

Hardware

  • Paso 1. Prepara los siguientes elementos:
Seeeduino V4.2Base ShieldGrove-Switch(P)Grove - Purple LED (3mm)
enter image description hereenter image description hereenter image description here
Obtener Uno AhoraObtener Uno AhoraObtener Uno AhoraObtener Uno Ahora
  • Paso 2. Conecta Grove-Switch(P) al puerto D2 del Grove-Base Shield.
  • Paso 3. Conecta Grove-LED al puerto D6 del Grove-Base Shield.
  • Paso 4. Conecta Grove - Base Shield al Seeeduino.
  • Paso 5. Conecta Seeeduino a la PC mediante un cable USB.

note

Si no tenemos Grove Base Shield, también podemos conectar directamente Grove-Switch(P) y Grove - Purple LED (3mm) al Seeeduino como se muestra a continuación.

SeeeduinoGrove-Switch(P)SeeeduinoGrove - Purple LED (3mm)
5VRojo5VRojo
GNDNegroGNDNegro
NCBlancoNCBlanco
D2AmarilloD6Amarillo

Software

  • Paso 1. Por favor copia el código de abajo al IDE de Arduino y súbelo al arduino. Si no sabes cómo subir el código, por favor revisa cómo subir código.
const int switchPin = 2;     // the number of the pushbutton pin
const int ledPin = 6; // the number of the LED pin

int switchState = 0; // variable for reading the pushbutton status

void setup() {
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the switch pin as an input:
pinMode(switchPin, INPUT);
Serial.begin(9600);
}

void loop(){
// read the state of the switch value:
switchState = digitalRead(switchPin);

if (switchState == HIGH) {
//turn LED on:
digitalWrite(ledPin, HIGH);
Serial.println("switch high!");
}
else {
//turn LED off:
digitalWrite(ledPin, LOW);
Serial.println("switch low");
}
}

  • Step 2. When we switch to high and the LED will be on. We also can see the Serial output as below.
switch high!
switch high!
switch high!

Jugar con Raspberry Pi (Con Grove Base Hat para Raspberry Pi)

Hardware

  • Paso 1. Elementos utilizados en este proyecto:
Raspberry piGrove Base Hat para RasPiGrove - Switch P
enter image description hereenter image description hereenter image description here
Consigue UNO AhoraConsigue UNO AhoraConsigue UNO Ahora
  • Paso 2. Conecta el Grove Base Hat al Raspberry.
  • Paso 3. Conecta el Switch al puerto 12 del Base Hat.
  • Paso 4. Conecta el Raspberry Pi a la PC a través del cable USB.

note

Para el paso 3 puedes conectar el switch a cualquier Puerto GPIO pero asegúrate de cambiar el comando con el número de puerto correspondiente.

Software

caution

Si estás usando Raspberry Pi con Raspberrypi OS >= Bullseye, tienes que usar esta línea de comandos solo con Python3.

  • Paso 1. Sigue Setting Software para configurar el entorno de desarrollo.
  • Paso 2. Descarga el archivo fuente clonando la librería grove.py.
cd ~
git clone https://github.com/Seeed-Studio/grove.py

  • Paso 3. Ejecuta los siguientes comandos para ejecutar el código.
cd grove.py/grove
python3 grove_switch.py 12

A continuación se muestra el código de grove_switch.py.



import time
from grove.gpio import GPIO


class GroveTiltSwitch(GPIO):
def __init__(self, pin):
super(GroveTiltSwitch, self).__init__(pin, GPIO.IN)

@property
def state(self):
return super(GroveTiltSwitch, self).read()


Grove = GroveTiltSwitch


def main():
import sys

if len(sys.argv) < 2:
print('Usage: {} pin'.format(sys.argv[0]))
sys.exit(1)

swicth = GroveTiltSwitch(int(sys.argv[1]))


while True:
if swicth.state is 1:
print("on")
else:
print("off")
time.sleep(1)


if __name__ == '__main__':
main()


tip

If everything goes well, you will be able to see the following result


pi@raspberrypi:~/grove.py/grove $ python3 grove_switch.py 12
off
off
on
off
on
on
off
^CTraceback (most recent call last):
File "grove_switch.py", line 70, in <module>
main()
File "grove_switch.py", line 66, in main
time.sleep(1)
KeyboardInterrupt


Puedes salir de este programa simplemente presionando ++ctrl+c++.

Jugar con Raspberry Pi (con GrovePi_Plus)

Hardware

  • Paso 1. Prepara los siguientes elementos:
Raspberry piGrovePi_PlusGrove-Switch(P)
enter image description hereenter image description hereenter image description here
Obtener Uno AhoraObtener Uno AhoraObtener Uno Ahora
  • Paso 2. Conecta el GrovePi_Plus al Raspberry.
  • Paso 3. Conecta Grove-Switch(P) al puerto D3 del GrovePi_Plus.
  • Paso 4. Conecta el Raspberry a la PC a través del cable USB.

Software

caution

Si estás usando Raspberry Pi con Raspberrypi OS >= Bullseye, tienes que usar esta línea de comandos solo con Python3.

  • Paso 1. Sigue Setting Software para configurar el entorno de desarrollo.
  • Paso 2. Clona el repositorio de Github con Git.
cd ~
git clone https://github.com/DexterInd/GrovePi.git

  • Paso 3. Ejecuta los siguientes comandos para monitorear el estado del interruptor.
cd ~/GrovePi/Software/Python
python3 grove_switch.py

Aquí está el código de grove_switch.py.

import time
import grovepi

# Connect the Grove Switch to digital port D3
# SIG,NC,VCC,GND
switch = 3

grovepi.pinMode(switch,"INPUT")

while True:
try:
print(grovepi.digitalRead(switch))
time.sleep(.5)

except IOError:
print ("Error")
  • Paso 4. Veremos el estado del interruptor como se muestra a continuación.
pi@raspberrypi:~/GrovePi/Software/Python $ python3 grove_switch.py 
1
1
0
0
0

Visor Esquemático en Línea

Recursos

Proyectos

Usando un Interruptor para Abrir y Cerrar un Relé: Aprenderás el valor de un interruptor, con su función Alta y Baja. Además aprenderás cómo usar un relé como actuador.

Soporte Técnico y Discusión de Productos

¡Gracias por elegir nuestros productos! Estamos aquí para brindarle diferentes tipos de soporte para asegurar que su experiencia con nuestros productos sea lo más fluida posible. Ofrecemos varios canales de comunicación para satisfacer diferentes preferencias y necesidades.

Loading Comments...