Hello, all
I have a small code to have a analog output from arduino uno controlled by a rotary encoder.
that go from 0 to 255 now will I to limit it that it not go from 255 to 0 or from 0 to 255.
What do I wrong?! this is my code:
//Control LED Brightness with Rotary Encoder //
#include <RotaryEncoder.h>
#include <Encoder.h> //includes the Encoder Library
Encoder myEnc(6, 5); // defines the Encoder object
//defining variables//
byte oldPosition = 0;
byte newPosition;
byte const led = 9;
void setup()
{
Serial.begin(9600); // begins the serial monitor
pinMode(led, OUTPUT); // sets the pinmode to output
}
void loop()
{
newPosition = myEnc.read() / 4; // reads position of the encoder
{
if (newPosition != oldPosition)
oldPosition = newPosition;
// Serial.println(newPosition);
// analogWrite(led, newPosition);
if (newPosition > 255) // encoder max
oldPosition = 255;
else if (newPosition < 0) // encoder min
oldPosition = 0;
}
Serial.println(newPosition);
analogWrite(led, newPosition);
}
@pvdbos it's a bit too tricky to do exactly what you want just now.
But try feeding your 0..255 values to this logic.
// first let the encoder supply the number
newPosition = myEnc.read() / 4;
// later use some maths to make it into a trangle wave:
int x = newPosition & 0xff; // just a byte, please
if (!(x & 0x80)) x <<= 1;
else x = (255 - x) << 1;
The variable x will go from 0 to 255 and then down to 0 then back up as you turn, no matter which way you turn.
If you want it to take twice as many clicks, try (untested)
// first let the encoder supply the number
newPosition = myEnc.read() / 4;
// later use some maths to make it into a trangle wave:
int x = newPosition & 0x1ff; // just 9 bits
if (x & 0x100) x = (511 - x) ;
I may have to amend that, can't test it just now. Tested. Works.
Alto777
I have tried your code but is not working for my.
void loop()
{
newPosition = myEnc.read() / 4; // reads position of the encoder
{
int x = newPosition & 0xff; // just a byte, please
if (!(x & 0x80)) x <<= 1;
else x = (255 - x) << 1;
}
Serial.println(newPosition);
analogWrite(led, newPosition);
}
I will only to limit the encode as a potentiometer min and max value 0 to 255
Alto777
It work now but is it posible that when it is 255 and I turn further on the encoder that it stay on 255
and also with when it go's to 0 that it stay on 0
Alto777
What I want is to make a adjustable power supply to control from 0 to 50 volt and 0 to 10 amp
controlled by an Arduino variable with rotary encoder and some buttons .
so pwm signal 8, 9, 10, or 16 bits to change the volt and amp.