Hello, I am new to the software community and relatively new to using microcontrollers. For short, I am not a software guy but am studying biomedical engineering and need to learn the basics. I am in a class for it and have been assigned a lab with simple orders. I need to write programs in Arduino and MATLAB so a user can input a number 0-15 and it be represented uniquely in 4 LEDS. I have the circuit part down and am using a simple technique to compare the binary version of the input and convert it the LED signals, however, sending the input from MATLAB to Arduino, I have trouble converting the ASCII notation to binary. I have it working for numbers 10-15 but not 0-9. For numbers 0-9 I get the signal that should be "7". It seems my code is having trouble converting a single digit char in MATLAB to the correct binary version. I am not sure if I have explained this in a way that is easy to understand, but if anyone sees a simple error in logic I would greatly appreciate the heads up.
Here is my code loaded on the board:
String incomingNumber=String("00"||'0'); //initialize incomingNumber variable, need to allow string or char to be single or double digit
int n; //initialize n
void setup() {
Serial.begin(9600); //set baud rate
int inMin = 8; //set lowest pin
int inMax = 11; //set highest pin
for(int i = inMin; i<=inMax; i++) //set pins 8-11 as output
{
pinMode(i, OUTPUT); //could just set led names to each pin and assign each to output
} //I'll try this and use pin 11=led1, 10=led2, etc.
}
void loop() {
if(Serial.available()>0){ //if number sent over MATLAB, read in
incomingNumber = Serial.readString(); //incomingNumber is an ASCII string
delay(200);
//Serial.print(incomingNumber.charAt(1));
int x=0;
while(incomingNumber([x]!='\0')){ //formula for converting ASCII to dec
x++;
}
if(x==1){
n=incomingNumber(0)-48;
}
else{
n=incomingNumber(1)+10-48;
}
const unsigned char One =0b00000001;
const unsigned char Two =0b00000010;
const unsigned char Four =0b00000100;
const unsigned char Eight =0b00001000;
digitalWrite(11,One&n); //if n=1,3,5,7,9,11,13,15 led1 will be HIGH
digitalWrite(10,Two&n); //if n=2,3,6,7,10,11,14,15 led2 will be HIGH
digitalWrite(9,Four&n); //if n=4,5,6,7,12,13,14,15 led3 will be HIGH
digitalWrite(8,Eight&n); //if n=8,9,10,11,12,13,14,15 led4 HIGH
delay(2000); //this should allow at least 2 seconds of signal from the leds, after this
//the loop re runs and if nothing entered, leds off bc of clear(s) in MATLAB
//if there IS something entered, the new signal will be generated
}
}
Here is the code in MATLAB:
sp=serialportlist;
pause(1); %Gives arduino time to boot up
s = serialport(sp(3),9600); %connects to arduino
pause(1); %gives time to connect
configureTerminator(s,"CR/LF"); %sets terminator
pause(1);
prompt='enter a value zero to fifteen';
str=input(prompt,'s')
writeline(s,str);
pause(0.2);
%data = readline(s);
clear s;