Hello guys,
I use a reed sensor to get speed on bicycle, this speed is sending from Arduino Mega via HC 05 to Arduino Uno via next HC 05 as master slave. Pairing is done well because Arduinos can change the information but Arduino slave reads wrong these information.
I want slave Arduino will control the pwm pin according to the speed that receives. Faster speed = 100% pwm, low or no speed = 0% pwm.
Current function: Arduino gets random values, sometime pwm is 100%, sometime 0%. I don't know why. Can you help me please? Thank you very much. Scheme is attached.
I would also need to reset the pwm if the value of speed is for example 3 seconds the same... But it also does not work...
Master
float start, finished;
float elapsed, time;
float circMetric=2.093; // wheel circumference (in meters)
float circImperial; // using 1 kilometer = 0.621371192 miles
int speedk, speedm;
float AuraPWM;
void setup() {
Serial.begin(9600);
circImperial=circMetric*.62137;
attachInterrupt(digitalPinToInterrupt(2), speedCalc, RISING);
start=millis();
}
void speedCalc()
{
//Function called by the interrupt
if((millis()-start)>100) // 100 millisec debounce
{
//calculate elapsed
elapsed=millis()-start;
//reset start
start=millis();
//calculate speed in km/h
speedk=(3600*circMetric)/elapsed;
//calculate speed in mph
speedm=(3600*circImperial)/elapsed;
}
}
void loop() {
Serial.println(speedk);
Serial.write(speedk);
delay(100);
AuraPWM = speedk;
}
Slave
#define Aura 3
int state = 0; // Vyctena hodnota z bluetooth
int OldState = 0;
int8_t AuraPWM = 0;
long unsigned OldMillis = 0;
long unsigned OldMillis2 = 0;
void setup() {
pinMode(Aura, OUTPUT);
Serial.begin(9600);
}
void loop() {
if (millis() - OldMillis > 500) {
OldMillis = millis();
if (state - OldState == 0) {
state = 0;
}
OldState = state;
}
if (Serial.available() > 0)
{
state = Serial.read();
AuraPWM = state * 10;
if (state != OldState) {
OldMillis = millis();
OldState = state;
}
}
if (millis() - OldMillis2 > 1000) {
OldMillis2 = millis();
Serial.println(state);
analogWrite(Aura, state);
}
}