Go Down

Topic: Help with a project, having trouble with Serial and Keyboard (Read 54 times) previous topic - next topic

Mayonice

Currently im working in a project were i can select with a knob a number and when i press it the keyboard will type it. The problem is that i dont know if this is even possible, for example If my potentiometer is between 0 and 100 (max is 1023) and i press the button the arduino should type 3. Here is my code, thanks in advance!
   
Code: [Select]

#include "Keyboard.h"
const int buttonPin = 4;          // input pin for pushbutton
int previousButtonState = HIGH;

void setup() {
  Serial.begin(9600);
  pinMode(buttonPin, INPUT);
  Keyboard.begin();
 
}

// the loop routine runs over and over again forever:
void loop() {

  int buttonState = digitalRead(buttonPin);
  int val = analogRead(A0);
  Serial.println(val);
  delay(1);     
  if ((buttonState != previousButtonState)
      && (buttonState == HIGH)
      && (val == 0)) {
    Keyboard.println("3");
  }
  if ((buttonState != previousButtonState)
      && (buttonState == HIGH)) {
    Keyboard.println("3");
  } 
}



DKWatson

There's nothing wrong with your code or logic, except you should avoid testing analog inputs against being exactly a specific value as they tend to fluctuate. In each case you are testing the button state so how about something like this.
Code: [Select]
if ((buttonState != previousButtonState) && (buttonState == HIGH))
{
    switch (val)
    {
        case 0 ... 100:

        case 101 ... 200:
          .
          .
        case 901 ... 1000:

        default:
    }
}
Live as if you were to die tomorrow. Learn as if you were to live forever. - Mahatma Gandhi

Go Up