A while ago, I created a post titled ‘XBee Test Sketch’. This was the premise: you hit a key on keyboard and robot moves in the requested direction. From reading more recent posts, however, you’ll know I am working to set up the MATLAB <–> XBees <–> Robot interface(s); incorporating MATLAB is the next step after setting up the simple XBee <–> Robot interface, which is what the ‘XBee Test Sketch’ Post addressed.
(Scroll to bottom for final code).
Working Through It:
I started with these two lines:
s = serial('COM13', 'BaudRate', 9600, 'Terminator', 'CR', 'StopBit', 1, 'Parity', 'None'); fopen(s);
Note: it is very important to type ‘fclose(s)’ after you’re finished with any of the below bits of code.
And I was initially following that with code that looked like this:
while(1) fprintf(s, '//'); fscanf(s) s.BytesAvailable end
But I needed a loop that wouldn’t require quitting MATLAB everytime I wanted to change something… and didn’t really need MATLAB responding to XTCU, so I changed it to this:
for c = 1:10 fprintf(s, a) end
I wanted a simpler way to send commands to XTCU; it turns out you can just use:
fprintf(s, 'whatever you want to send');
The problem, however, was that I didn’t want to have to write ‘fprintf(s, ‘whatever’)’ every time I wanted to send a character. So I tried this:
a = 'hello' for c = 1:10 pause(10) fprintf(s, a) end
I needed to specify ‘a’ ahead of the loop so that MATLAB would recognize it. But I then gave myself 10 seconds delay within the loop, thinking I could change ‘a’s value in that time, and MATLAB would send the new one.
It did not. It took like two whole minutes to get through all those ‘hello’s lol.
I needed a better way for MATLAB to take/send the characters I wanted.
I tried the ‘MATLAB asks for user input’ method, but I still had to hit ‘Enter’ after every key stroke for the command to send to XTCU. Since the idea was for the input/robot-reaction to be continuous, like in ‘XBee Test Sketch’, this wasn’t the best option:
for c = 1:3 x = input('what would you like to send?','s') fprintf(s, x) end
I did some more Googling and found a MATLAB function called GetKey. Aptly named, it freezes MATLAB and intakes your next keystroke. Here’s the code I came up with:
(Because I programmed the letters (not ASCII values) ‘i’, ‘j’, ‘k’ and ‘l’ into the ‘XBee Test Sketch’ Arduino code, I used GetKey’s ‘non-ascii’ option).
s = serial('COM13', 'BaudRate', 9600, 'Terminator', 'CR', 'StopBit', 1, 'Parity', 'None'); fopen(s); for c = 1:3 x = getkey('non-ascii') fprintf(s, x) end
The for-loop length can (and should be) adjusted depending. I put 1:100 to test it, and it worked great!
Here’s a video! (will download) 191019KA_MATLABtoRobot