Matlab arduino serial communication - matlab

I am trying to send some data from Matlab to arduino. It is a matrix of [1 by 2]. My plan is to convert this two numbers in to a string and send to the arduino. However in the serial monitor, I can not read any value coming from matlab.
This is my matlab code,
val_a = matt(n,:);
A = [val_a];
asd = A(1:1);
asb = A(:,2);
strA = num2str(asd);
strB = num2str(asb);
comma = ',';
endVal = '#';
theString = strcat(strA,comma,endVal);
obj1 = instrfind('Type', 'serial', 'Port', 'COM19', 'Tag', '');
if isempty(obj1)
obj1 = serial('COM19');
else
fclose(obj1);
obj1 = obj1(1);
end
fopen(obj1);
fprintf(obj1,theString)
fclose(obj1);
delete(obj1);
A = [];
And this is the serial event of arduino
bool gotalfa = false;
bool event = false;
void serialEvent() {
while (Serial.available())
{
char inChar = (char)Serial.read();
event = true;
if (inChar == , && !gotalfa)
{
alfa = inputString;
inputString = "";
gotalfa = true;
event = false;
}
if (inChar == '#' && gotalfa)
{
theta = inputString;
gotalfa = false;
inputString = "";
Serial.print("alfa ");
Serial.print(alfa);
Serial.print("theta ");
Serial.println(theta);
//some program....
event = false;
}
if(event)
{
inputString += inChar;
}}}
Do I have to change anything in my matlab/arduino code. Any helpful tip is greatly appreciated.
Thank you in advance

Just a tip, hopefully it points you to the answer.
I would use a terminal program like putty or teraterm to isolate the root cause of your error.
i.e. Run putty/teraterm to send certain string to your serial port of your arduino and see if it does returns the expected strings.
http://www.putty.org/
https://ttssh2.osdn.jp/index.html.en
Also, consider using the ReadStringUntil in Arduino.
https://www.arduino.cc/en/Serial/ReadStringUntil
Hope it helps.

Related

Unable to Get Bitwise XOR to work in GameMaker 2

I'm trying to implement Zobrist hashing for a chess game and thought I was doing things correctly. However, when I try to apply XOR to a Hash value, it simply changes between 0 (the starting value for the hash) and -2147483648, in spite of conducting a bitwise XOR against a random number between 0 and 18446744073709551616.
Here's some code. I thought it was relatively simple with a struct for each entry in the Grid, a constructor function to make an entry, a function to create the Hash Table, and finally one for the Hash itself.
//Hash Table struct. This can be expanded for each new piece type
HashTableEntry = {
QueenHash:-1,
BishopHash:-1,
KnightHash:-1,
RookHash:-1,
PawnHash:-1,
KingHash:-1
};
//A function for creating a Hash Table Entry
function toHashTableEntryStruct() constructor {
var HashUpperBound = 18446744073709551616;
QueenHash = random(HashUpperBound);
BishopHash = random(HashUpperBound);
KnightHash = random(HashUpperBound);
RookHash = random(HashUpperBound);
PawnHash = random(HashUpperBound);
KingHash = random(HashUpperBound);
}
//A function to create a ds_grid Hash Table of the size passed to it, which it then returns
function CreateHashTable(_width, _height){
//Copy the local variables
var width = _width;
var height = _height;
//Create the grid for the Hash Table
var NewHashTable = ds_grid_create(width, height);
//Copy the original seed and set the game's seed to create the same table each time
var OriginalSeed = random_get_seed;
random_set_seed(280804);
//Loop through the Grid and fill each value with a HashTableEntry struct
for(var i = 0; i < width; i++;){
for(var j = 0; j < height; j++;){
var NewHash = new toHashTableEntryStruct();
ds_grid_set(NewHashTable, i, j, NewHash);
}
}
//Reset the seed
random_set_seed(OriginalSeed);
//Return the shiny new Hash Table
return NewHashTable;
}
//A function for creating the original Hash of a board. This should only be called on
initialising a Board as it sets the Original Hash
function CreateBoardHash(_board){
var Board = _board;
var width = ds_grid_width(Board);
var height = ds_grid_height(Board);
HashTable = CreateHashTable(width, height);
var FinalHash = 0;
for(var i = 0; i < width; i++;){
for(var j = 0; j < height; j++;){
var PieceToCheck = ds_grid_get(Board, i, j);
if(PieceToCheck == Pieces.BLANK){ continue; }
var HashEntry = ds_grid_get(HashTable, i, j);
var XorValue = MatchPieceToHashTableEntry(PieceToCheck, HashEntry);
FinalHash ^= XorValue;
}
}
if(FinalHash == 0){
//Error here
return;
}
//Set the instance variable for this original Hash
OriginalHash = FinalHash;
//Add it to the Current Hash stack
CurrentHash = FinalHash;
//Return said hash for the calling function
return FinalHash;
}
The problem comes in the FinalHash ^= XorValue; line, where XorValue each time is a random number, but FinalHash only ever comes out as 0 or -2147483648.
Can someone help with why this is the case and what I may be doing wrong with my XOR function?
Thanks to Reddit, I have fixed this. GameMaker must be doing something weird with the ^= operator, as the solution was as follows:
FinalHash = FinalHash ^ XorValue;

nanopb encode always size 0 (but no encode failure)

I have a very simple proto:
syntax = "proto2";
message TestMessage {
optional int32 val = 1;
optional string msg = 2; // I set max size to 40 in options, so TestMessage_size is defined.
}
...and I have the following code in my main loop for an arduino program:
TestMessage test_msg = TestMessage_init_zero;
test_msg.val = 123;
// Print message length.
size_t msg_length;
bool get_msg_length = pb_get_encoded_size(&msg_length, TestMessage_fields, &test_msg);
Serial.println(msg_length);
// Encode and print message.
uint8_t testbuffer[TestMessage_size];
pb_ostream_t teststream = pb_ostream_from_buffer(testbuffer, sizeof(testbuffer));
bool teststatus = pb_encode(&teststream, TestMessage_fields, &test_msg);
if (!teststatus) {
Serial.println("Failed to encode test message.");
return;
}
Serial.print("Message: ");
Serial.println(teststream.bytes_written);
for(size_t i = 0; i < teststream.bytes_written; i++){
Serial.print(testbuffer[i], OCT);
}
Serial.println("testbuffer flushed");
For some reason I can print test_msg.val and it will show 123 but when I try to encode it (following examples like this one) it always is empty / has size 0.
Is this a configuration issue with nanopb? I wonder if the encode method requires something that I am not using?
For optional fields, you also have to set the has_field:
TestMessage test_msg = TestMessage_init_zero;
test_msg.has_val = true;
test_msg.val = 123;
That's because otherwise there is no way to know if the optional field has been set or not. C++ handles this via setter methods, but C doesn't have those.

Swift, dictionary parse error

I'm using an API to get weather condition and the retrieved dict is
dict = {
base = stations;
clouds = {
all = 92;
};
cod = 200;
coord = {
lat = "31.23";
lon = "121.47";
};
dt = 1476853699;
id = 1796231;
main = {
"grnd_level" = "1028.63";
humidity = 93;
pressure = "1028.63";
"sea_level" = "1029.5";
temp = "73.38";
"temp_max" = "73.38";
"temp_min" = "73.38";
};
name = "Shanghai Shi";
rain = {
3h = "0.665";
};
sys = {
country = CN;
message = "0.0125";
sunrise = 1476827992;
sunset = 1476868662;
};
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
}
);
wind = {
deg = "84.50239999999999";
speed = "5.97";
};
}
If I want the value of humidity, I just use
let humidityValue = dict["main"]["humidity"] and it works.
But the problem is I also want to get the value of description in weather
when I used let dscptValue = dict["weather"]["description"]
it retrieved nil.
How's that? and I notice there are two brackets around weather .I'm not sure whether it is the same with the statement without brackets.
weather = (
{
description = "light rain";
icon = 10d;
id = 500;
main = Rain;
}
);
How to get the value of description?
weather keys contains Array of Dictionary not directly Dictionary, so you need to access the first object of it.
if let weather = dict["weather"] as? [[String: AnyObject]], let weatherDict = weather.first {
let dscptValue = weatherDict["description"]
}
Note: I have used optional wrapping with if let for preventing crash with forced wrapping.
Weather is an array of dictionaries.
dict["weather"][0]["description"]
may give you the expected result.

How to convert a string to a variant in jscript under wsh?

I need to append a string of text to the end of a binary file.
This is what I'm trying:
inStream = WScript.CreateObject("ADODB.Stream") ;
inStream.type = 1 ;
inStream.open() ;
inStream.LoadFromFile('test.bin') ;
outStream = WScript.CreateObject("ADODB.Stream") ;
outStream.type = 1 ;
outStream.open() ;
outStream.write( inStream.read() ) ;
outStream.write( "\nCONTENT AT THE END" ) ; // this gives an error
outStream.SaveToFile('test2.bin',2) ;
The reported error is "wrong argument".
The documentation of that method says the argument must be of type variant.
How can I convert a string to a variant?
The solution is to use auxiliary ADODB.Stream instance .copyTo() method.
var inStream = WScript.CreateObject('ADODB.Stream'); // source stream
inStream.Type = 1; // adTypeBinary
inStream.Open();
inStream.LoadFromFile('C:\\Test\\src.bin');
var outStream = WScript.CreateObject('ADODB.Stream'); // target stream
outStream.Type = 1; // adTypeBinary
outStream.Open();
outStream.Write(inStream.read());
inStream.Close();
var bufStream = WScript.CreateObject('ADODB.Stream'); // auxiliary stream
bufStream.Type = 2; // adTypeText
bufStream.Open();
bufStream.WriteText('\nCONTENT AT THE END'); // strings held as Unicode in memory
bufStream.Position = 2; // skip BOM bytes FF FE
bufStream.CopyTo(outStream); // append to the end of target stream
bufStream.Close();
outStream.SaveToFile('C:\\Test\\dst.bin', 2);
outStream.Close();

Javascript create a function that returns a boolean value based on certain parameters

Thanks for taking the time to look at my problem. What I'm trying to do is create a javascript function that tests whether a sting is a particular length and also whether each element of that string can be found in another string. The function then needs to return a boolean value of either true or false depending on whether the string is valid.
Here's what I have:
N_ALPHA = 6;
N_CHOICES = 4;
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var alphabet = ALPHABET.substring(0, N_ALPHA);
function isValidGuess(inStr)
{ var valid;
var Str = inStr;
for (i=0; i<Str.length; i++)
{ if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES.length)
{ valid = true;
}
else
{ valid = false;
}
}
return valid;
}
This code is not working at all. It only returns false every time. Any help you could provide would be greatly appreciated. Thank you.
N_CHOICES.length return undefined, because variable N_CHOICES is number.
you have to change your condition to
if (Str.charAt(i) === alphabet.charAt(i) && Str.length == N_CHOICES)