I 'm trying to send the buffer of the USB HID input (which is always numeric) to the analogwrite function. So i need to convert it to a byte or an integer. Any idea how?
#include <HIDSerial.h>
HIDSerial serial;
unsigned char buffer[32];
ledPin = 10;
void setup() {
serial.begin();
}
void loop() {
if(serial.available()) {
int size = serial.read(buffer);
if (size!=0) {
serial.write((const uint8_t*)buffer, size);
// It will fail cause it needs a conversion from unsigned char to something else..
analogWrite (ledPin,buffer)
}
}
serial.poll();
}
You can convert a char to a uint8_t like this:
//assume these variables
char thisChar = '9';
uint8_t thisByte;
thisByte |= thisChar;
Serial.println(thisByte, BIN);
The output of this is: 00111001
This works because they are both a single byte variable. You are moving the bits over using a bitwise operation.
Not sure what you are trying to do here.
serial.read()
and serial.write()
deal with a buffer of data up to 32 bytes long. You can't convert that to an integer in a meaningful way. Also note that buffer
is a pointer to the memory where the data is located. It will be the same number every time, so it doesn't make sense to send that.
analogWrite()
writes a PWM value from 0 to 255 to a pin. Is this really what you want to do?
Found the solution:
This is the full program:
#include <HIDSerial.h>
HIDSerial serial;
unsigned char buffer[2];
void setup() {
serial.begin();
}
void loop() {
if(serial.available()) {
int size = serial.read(buffer);
if (size!=0) {
int bright = atoi((char *) buffer) ;
analogWrite(0,bright);
serial.println(bright);
}
}
serial.poll();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.