A friend is helping me write a plugin for a bus simulator, it captures the dashboard data (speed, rpm's, idiot lights etc) and sends it via (usb) serial to my arduino mega (1280) which works the gauges and lights in the real dashboard.
we are a little worried that we may be using too many delays, as after every serial read we need a 1millisecond delay, i know that's not much, but worried they may add up and cause problems,
Can someone look at our code and advise if there are better ways to do it please,
we have another 8 gauges to add, and a good 20 or more lights,
// Last updated: March 12th, 2012 - 7:39PM GMT
char kind_of_data;
void setup(){
Serial.begin(115200);
TCCR4B = (TCCR4B & 0xF8) | 0x01 ; //set timer 4 to 31Khz to silence singing coils in gauges
pinMode(22, OUTPUT);
pinMode(23, OUTPUT);
pinMode(24, OUTPUT);
pinMode(25, OUTPUT);
pinMode(26, OUTPUT);
}
void loop()
{
while(Serial.available() > 0)
{
kind_of_data = Serial.read();
// Gauges
if (kind_of_data == 'R' ) Read_Rpm();
if (kind_of_data == 'o' ) Read_Oil();
// Lights
if (kind_of_data == 'S' ) Read_BusStopLight();
if (kind_of_data == 'B' ) Read_Blinker();
if (kind_of_data == 'H' ) Read_Highbeam();
if (kind_of_data == 'b' ) Read_Battery();
// Test routine - can be removed when necessary
if (kind_of_data == 'I' ) digitalWrite(23,HIGH); //turns led on or off to show connection
if (kind_of_data == 'O' ) digitalWrite(23,LOW);
}
}
// Lights
void Read_BusStopLight(){
delay(1);
int haltewunsch = Serial.read() - '0';
if (haltewunsch == 1)
{
digitalWrite(22,HIGH);
}
else
{
digitalWrite(22,LOW);
}
}
void Read_Blinker(){
delay(1);
int lights_blinkgeber = Serial.read() - '0';
if (lights_blinkgeber == 1)
{
digitalWrite(24,HIGH);
}
else
{
digitalWrite(24,LOW);
}
}
void Read_Highbeam(){
delay(1);
int cockpit_fernlichthebel = Serial.read() - '0';
if (cockpit_fernlichthebel == 1)
{
digitalWrite(25,HIGH);
}
else
{
digitalWrite(25,LOW);
}
}
void Read_Battery(){
delay(1);
int battery = Serial.read() - '0';
if (battery == 1)
{
digitalWrite(26,HIGH);
}
else
{
digitalWrite(26,LOW);
}
}
// Gauges
void Read_Rpm(){
delay(1);
int rpm1000 = Serial.read()- '0';
delay(1);
int rpm100 = Serial.read()- '0';
delay(1);
int rpm10 = Serial.read()- '0';
delay(1);
int rpm1 = Serial.read()- '0';
int rpm = 1000*rpm1000 + 100*rpm100 + 10*rpm10 + rpm1;
tone(9, map(rpm,0,5700,55,423)); //50% duty variable frequency to run rev counter
}
void Read_Oil(){
delay(1);
int oil1 = Serial.read()- '0';
delay(1);
int oilm1 = Serial.read()- '0';
int oil = 10*oil1 + oilm1;
analogWrite(8,map(oil,0,50,0,255)); //PWM to imitate varying resistance to earth for oil gauge
}