I connected everything properly. On the first try I did receive data as I was supposed to. I then wrote some logic, re-uploaded and started receiving crazy spam.
My serial monitor is getting spammed with:
- question marks if the variable is
char
, or; 25252525252
if the variable isint
, or;-1
if variable isString
.
I'm monitoring at 38400 baud which is the same as my Serial.begin()
.
Any ideas ?
Code:
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();
#define MIN_PULSE_WIDTH 650
#define MAX_PULSE_WIDTH 2350
#define DEFAULT_PULSE_WIDTH 1500
#define FREQUENCY 50
char data = 'a';
void setup()
{
analogReference(DEFAULT);
Serial.begin(38400);
pwm.begin();
pwm.setPWMFreq(FREQUENCY);
Serial.println("hello world");
}
void loop()
{
data = Serial.read();
Serial.println(data);
Serial.flush();
if (data == 'a'){
pwm.setPWM(0, 0, pulseWidth(90));
}
if (data == 's'){
pwm.setPWM(0, 0, pulseWidth(30));
}
delay(1000);
//printing time in seconds
}
int pulseWidth(int angle)
{
int pulse_wide, analog_value;
pulse_wide = map(angle, 0, 180, MIN_PULSE_WIDTH, MAX_PULSE_WIDTH);
analog_value = int(float(pulse_wide) / 1000000 * FREQUENCY * 4096);
return analog_value;
}
-
Thanks, that seems to work for the spam. I changed my variable to integer and tried sending a number. No matter what I send, I receive either 120, 128 or 248, multiple times. What's the deal ?Stoil– Stoil11/07/2018 15:37:32Commented Nov 7, 2018 at 15:37
-
you should first connect the Arduino to Serial Monitor and learn the basics of Serial communication on examplesJuraj– Juraj ♦11/07/2018 15:42:48Commented Nov 7, 2018 at 15:42
-
It does, but why is it the same no matter what character I send ?Stoil– Stoil11/07/2018 15:43:05Commented Nov 7, 2018 at 15:43
-
I cannot use answer since I am not logged in, which I cannot do since I have my password on remember on another machine. I changed print to write, however I still am getting weird results. 1 corresponds to "x?" (with a reverse question mark) and 2 corresponds to "???". I'm so lost.Stoil– Stoil11/07/2018 15:49:04Commented Nov 7, 2018 at 15:49
-
2has the BT module a baud rate 38400 baud?Juraj– Juraj ♦11/07/2018 15:57:25Commented Nov 7, 2018 at 15:57
1 Answer 1
Serial.read()
returns -1 if no data is available. It doesn't wait for the byte. Test for -1 or use Serial.available()
as any example does.
Replace Serial.print(data)
with Serial.write(data)
to get the data echoed back unchanged.