Hi gyus I wrote this code in order to control the arduinos digital outputs by sending it a string with 54 1s or 0s, for example 00100000000000000000000000000000000000000000 is only turn digital output 3 HIGH, but havent found why it isnt working, really hope you can help me see what im missing!
int io[52]; //save each pin state here
int d = 0;
void setup() {
Serial.begin(9600);
for (int i = 3; i <= 52; i++)
{
pinMode(i, OUTPUT);
digitalWrite(i, 0); //initiate pins off
}
}
void loop()
{
if (Serial.available() > 0)
{
io[d] = Serial.read(); // save all 252 incoming values into this array
Serial.print(io[d]);
d++;
if (d == 52) //when all values are received, start processing
{
d = 0;
Serial.write("Applying");
for (int i = 3; i < 52; i++)
{
digitalWrite(i, io[i]);
}
}
}
}
I have a RGB led connected to pins 12 and 13 to check function, but it never turns on.
Im using an Arduino Due
Yes, Im sending enough chars (value 1 =49) so the arduino sends me the "applying"message when it should start opening the outputs, but they arent.
Ok I think I got it, it isnt working because it is considering ASCII decimal value (49 for 1, 48 for 0), not the char, how do I convert this value when arriving from the serial read?
change
int io[52]; //save each pin state here
to
byte io[54]; //save each pin state here
doesn't need to be an int
Could also compress the data - just send 7 bytes
byte io[7];
byte byte 0 representing D0-D7.
byte 1 D8-D15,
byte 2 D16-D23, etc.
If you can further map the bytes to Ports, makes it really easy!
byte 0 = PORTA,
byte 1 = PORTB, etc. then
if (Serial.availabe()>6){ // 7 bytes received
PORTA = Serial.read();
PORTB = Serial.read();
PORTC = Serial.read();
PORTD = Serial.read();
PORTE = Serial.read();
PORTF = Serial.read();
PORTG = Serial.read();
}
Won't be quite that simple, I think a couple ports are only partly used, and have to not mess up the serial port, but it's way less data to mess with.
Steinhoff:
Ok I think I got it, it isnt working because it is considering ASCII decimal value (49 for 1, 48 for 0), not the char, how do I convert this value when arriving from the serial read?
Ok I think I got it, it isnt working because it is considering ASCII decimal value (49 for 1, 48 for 0), not the char, how do I convert this value when arriving from the serial read?
Maybe something like below.
if (Serial.available()>0){
Serial.print (Serial.read() - 48);
}
Ok thank you all, I did what you said and also had to add one piece of code to tell the arduino when to start receiving the io[] array strings, because when you open the serial port it sends some data, which contaminated the io[] array. Now it works perfectly.