Hi
I need controlled RGB LED with common cathode by Matlab. I can do it with using MATLAB Interface for Arduino, but this is too slow, I need most real-time controlling. I tried this: (it is for 2 colors, I know, but this is "prototype")
Arduino code:
const int ledPin1 = 9;
const int ledPin2 = 10;
void setup()
{
Serial.begin(9600);
pinMode(ledPin1, OUTPUT);
pinMode(ledPin2, OUTPUT);
}
void loop() {
int light;
if (Serial.available()) {
light= Serial.read();
if (light<=255){
light=byte(light-1);
analogWrite(ledPin1, light);
}
else {
light=byte((light-1)/1000);
analogWrite(ledPin2, light);
}
}
}
and Matlab code:
function light= funkce_light(x,y)
s=serial('COM16','BaudRate', 9600);
fopen(s)
pause(5)
r=x+1;
fwrite(s,r)
g=1000*(y+1);
fwrite(s,g)
delete(s)
end
I have no idea how to tell arduino: "Send this value to this pin" because for this code works only first color. When I use one red LED this code work great, exactly as I imagine. It is fast and value is still set (when I use MATLAB Interface, i must set how long the diod shine).
I do not know of MATLAB, so I do not know what happens when you use fwrite() and send a value greater than 256. It either truncates it down to 256, sends the value modulus-256 or it sends several bytes. You need to know which.
Your problem is that Serial.read() will alwys only read a single byte at a time. Just like your keyboard only sends one key at a time, and you compose words by several keys in sequence and finish with a space, so you need to send your LED commands as several bytes.
I suggest you send three bytes. The first byte is the LED1 value, the 2nd byte is the LED2 value and the 3rd byte is 255.
In your send code you never send 255 as the value. In your receive code, if the 1st or 2nd byte is 255, then you know you have "lost a byte somewhere" and your code should start waiting for byte 1 again.
That is what is called a "protocol", ie the rules how the bytes are interpreted, and how to handle some errors. There are many ways to define a protocol, my suggestion is just a simple variant that fits the approach you have in your code.