Arduino C language use toCharArray() not correct - arduino-c++

I read data from sensor and show to serial monitor like this.
int humidity = dht.readHumidity();
int temperature = dht.readTemperature();
String place = "My Home";
if (online) {
if (!client.connected()) {
reconnect();
}
client.loop();
String data = "{\"data\": {\"humidity\":" + String(humidity) + ", \"temperature\":" + String(temperature) + ", \"place\": " + place + "}}";
data.toCharArray(msg, (data.length() + 1));
Serial.println(msg);
The output is
{"data": {"humidity":60, "temperature":27, "place": My Home}}
{"data": {"humidity":2147483647, "temperature":2147483647, "place": My Home}}
After I run code it have no error but the output is not correct and the program will stop after show this output.
If I comment at line data.toCharArray(msg, (data.length() + 1)); . Then, the program will show the correct output of temperature and humidity value. How to fix it?

Use the basic itoa function. It is included in stdlib.h
char buf[12]; // "-2147483648\0"
lcd.printIn(itoa(random(1024)-512, buf, 10));
Source : Arduino Playground

Related

Plc4x cannot read more than 9 registers at once

I am trying to understand the address system in the plac4x java implementation. Below an example of the reading code of the plcs:
#Test
void testReadingFromPlc() {
// Establish a connection to the plc using the url provided as first argument
try( PlcConnection plcConnection = new PlcDriverManager().getConnection( "modbus:tcp://1.1.2.1" ) ){
// Create a new read request:
// - Give the single item requested the alias name "value"
var builder = plcConnection.readRequestBuilder();
builder.addItem( "value-" + 1, "register:1[9]" );
builder.addItem( "value-" + 2, "coil:1000[8]" );
var readRequest = builder.build();
LOGGER.info( "Synchronous request ..." );
var syncResponse = readRequest.execute().get();
// Simply iterating over the field names returned in the response.
var bytes = syncResponse.getAllByteArrays( "value-1" );
bytes.forEach( item -> System.out.println( TopicsMapping.byteArray2IntegerArray( item )[0] ) );
var booleans = syncResponse.getAllBooleans( "value-2" );
booleans.forEach( System.out::println );
}catch(Exception e){
e.printStackTrace();
}
}
Our PLCs manage 16 registers, but the regex of the addresses don't allow to have a quantity bigger than 9. Is it possible to change this?
Moreover, if I try to add an other field with the same purpose then no reading happen:
var builder = plcConnection.readRequestBuilder();
builder.addItem( "value-" + 0, "register:26[8]" );
builder.addItem( "value-" + 1, "register:34[8]" );
builder.addItem( "value-" + 2, "coil:1000[8]" );
var readRequest = builder.build();
Any help much appreciated. Could you also show me where I can find more information on this framework?
I am reading and writing using the modbus driver in PLC4x with success. I have attached some writing code to your other question at: Plc4x addressing system
About reading, here is some code:
public static PlcReadResponse readModbusTestData(ProtocolClient client,
String registerName,
int offset,
int size,
String registerType)
throws ExecutionException, InterruptedException, TimeoutException {
PlcReadRequest readRequest = client.getConnection().readRequestBuilder()
.addItem(registerName, registerType + ":" + offset + "[" + size + "]").build();
return readRequest.execute().get(2, TimeUnit.SECONDS);
}
The multiple read adding more items to the PlcReadRequest has not been tested yet by me, but it should work. Writing several items is working.
In any case, in order to understand how PLC4x works for modbus or opc-ua I have needed to dive into the source code. It works, but you need to read the source code for the details at its current state.

API Gateway exposing DynamoDB (Complex mapping template or Lambda Function needed?)

I am exposing my DDB via the AWS API Gateway. I have it working, but when I pass my "PUT" it's requiring me to include every field from my DDB in the body request. Some clients may only want to POST 5 fields of the 10 in my DDB. Would this be done as a POST or a PATCH? If so, what does my mapping template look like for these?
Second: I'd like to add an auto-generated order_number to each entry in the DDB. So now each PUT or POST will have a unique order_number. So my Primary Key will be a variable, and the secondary key would be a customer sku number, or vice versa.
Thanks for the help.
Body Template: I still need it to generate the "order_number"
automatically for each new entry.
#set($inputSep = $input.path('$'))
#set($thisLoop =
'{"CustomerNm":"1","ShipDate":"2","Shipping":"3","commentId":"4"}')
#set($myPlaces = $util.parseJson($thisLoop))
#set($allKeys = '')
#set($myVals = '"')
{
"TableName": "BRPI",
"Key": {
"CustomerID": {
"S": "$input.path('$.CustomerID')"
}
},
#foreach($type in $inputSep.keySet())
#if($type == "CustomerID")
#else
#set($thisPlace = $myPlaces.get($type))
#set($params = $inputSep.get($type))
#set($thisKey = "$type" + " = :val" + "$thisPlace")
#set($thisPath = "$params")
#if($foreach.hasNext)
#set($myComma = ",")
#set($myReturn = '"')
#else
#set($myComma = "")
#set($myReturn = "")
#end
#set($allKeys = "$allKeys" + "$thisKey" + "$myComma")
#set($myVals = "$myVals" + ":val" + "$thisPlace" + '": {"S": "' +
"$thisPath" + '"}' + "$myComma" + "$myReturn")
#end
#end
"UpdateExpression": "SET $allKeys",
"ExpressionAttributeValues": {
$myVals
},
"ReturnValues":"UPDATED_NEW"
}

Lua in Redis from JSON

I have a list of JSON strings stored in Redis that looks something like this:
[
{ "ID": 25, "DomainID": 23455, "Name": "Stuff", "Value": 23 },
{ "ID": 35, "DomainID": 23455, "Name": "Stuff", "Value": 10 }
]
The key would be something like "Event:23455".
Using a Lua script and ServiceStack.Redis how would I pull out an anonymous object containing only values where the value is less than 20?
So what I want to return would look like this:
[{ "ID": 35, "Value": 10}]
Thanks.
UPDATE 03/31/2013:
After trying what has been suggested I now have a new problem. A Lua script syntax error.
I'm getting a Lua syntax error about "expecting '=' near cjson". Here is the Lua script string (in C#) I am feeding to Redis:
string luaScript = "local tDecoded = cjson.decode(redis.call('GET', KEYS[1]));"
+ "local tFinal = {};"
+ "for iIndex, tValue in ipairs(tDecoded) do"
+ " if tonumber( tValue.Value ) < 20 then"
+ " table.insert(tFinal, { ID = tValue.ID, Value = tValue.Value});"
+ " end"
+ "end"
+ "return cjson.encode(tFinal);";
Are there any Lua or Redis Lua experts out there that can see what might be the problem? i.e. Does the Lua syntax look correct?
UPDATE 04/02/2013
The parsing error was resolved by adding \n newline characters to end of each line like so.
string luaScript = "local tDecoded = redis.call('GET', KEYS[1]);\n"
+ "local tFinal = {};\n"
+ "for iIndex, tValue in ipairs(tDecoded) do\n"
+ " if tonumber( tValue.Value ) < 20 then\n"
+ " table.insert(tFinal, { ID = tValue.ID, Value = tValue.Value});\n"
+ " else\n"
+ " table.insert(tFinal, { ID = 999, Value = 0});\n"
+ " end\n"
+ "end\n"
+ "return cjson.encode(tFinal);";
Unfortunately this works without errors but for some reason only returns "{}" or an empty list in the ServiceStack RedisClient. So I'm not there yet but I am one step closer.
You can use LuaJSON available on GitHub or you can also try this JSON to Lua table parser for the task. The usage will be something like this(for the GitHub link):
local json = require( "json" ) -- or JSON.lua
local tDecoded = json.decode(sJSON) -- sJSON is the original JSON string
local tFinal = {}
for iIndex, tValue in ipairs( tDecoded ) do
if tonumber( tValue.Value ) < 20 then
table.insert( tFinal, { ID = tValue.ID, Value = tValue.Value} )
end
end
print( json.encode(tFinal) )

is there any more standard way to resume function from jQuery ajax call?

I am trying to write a big project which involves of a lot of code. That's why I want to separate functionalities from different files.
the first file, dataJS, I make an AJAX call to get data from a JSON file.
the second file, showJS I want to display the data obtained from the dataJS file.
When it comes to implementation, I realise that AJAX call takes longer time and even though I include dataJS and showJS in order, showJS will still get a null data
therefore I made a function called continueFromDataJS() in showJS file
and call continueFromDataJS() at the end of the AJAX success function.
I think it's a rather makedo solution. Is there any standard way to do it?
In addition, all intellisense in my Visual Studio is gone. Despite separate files, is there any way to make visual studio get intellisense from the dataJS?
Thank you
sorry, I don't know how to add a follow up question
this is the code
for simplicity I rename some of the files and only take some part out of it. Hope that helps
code in html
code in dataJS.js
var planets = [];
var jsonData = null;
$(function () {
$.getJSON("Scripts/planetData.js", function (data) {
//planets[0] = new planet("uranus", "career", 45, 700, 400, 0.1, 5, 3);
jsonData = data;
for (var i = 0; i < data.planets.length; i++) {
var curPlanet = data.planets[i];
planets[i] = new planet(curPlanet.graphic, i, curPlanet.field, curPlanet.planetInitialAngle, curPlanet.distanceFromStar, curPlanet.planetRadius, curPlanet.planetRevolvingSpeed, curPlanet.planetRotationSpeed, curPlanet.contents.length);
$("#result").append("<p>" + curPlanet.graphic + " " + curPlanet.field + " " + curPlanet.planetInitialAngle + " " + curPlanet.distanceFromStar + " " + curPlanet.planetRadius + " " + curPlanet.planetRevolvingSpeed + " " + curPlanet.planetRotationSpeed + " " + curPlanet.contents.length + "</p>");
}
callDisplayScript(); //**continue from showJS.js file is that the way to do this?**
});
});
// more functions below in dataJS.js
showJS.js
function callDisplayScript() { **// this is the ugly part. What's the proper way to do it?**
$("#display #close").click(function () {
$("#display").fadeOut('slow');
});
$article = $("#display article");
$article.empty();
var data = jsonData.planets[pID].contents; // **this line won't get jsonData if it's out this curly brace.**
for (var i = 0; i < data.length; i++) {
$article.append(data[i].title);
$article.append(data[i].content);
}
$("#display").fadeIn('slow');
};
don't forget to answer my intellisense question. I want in datajs.js automatically hint planets and jsonData declared in datajs.js
is it possible?

Recorded Skeleton Data

The following is code I have used to try to record skeleton frame data
using (SkeletonFrame skeletonFrame = e.OpenSkeletonFrame())
{
if (skeletonFrame == null)
return;
this.Recorder.Record(skeletonFrame);
}
if the code above is run, what information is recorded?
If I were to save this information to an external file, what would I see?
Would there be coordinate information and a specific timestamp associated with each coordinate information?
Are you looking at recording the X, Y, Z data of the skeleton into a text file? It is generally easier to record the information separately in readable format. If you are looking at doing the aforementioned then this may help:
//save the XYZ of the skeleton data, but also save the XZ of depth data
private void saveCoordinates(Skeleton skeleton, string textFile)
{
StreamWriter coordinatesStream = new StreamWriter(newPath + "\\" + textFile);
foreach (Joint joint in skeleton.Joints)
{
coordinatesStream.WriteLine(joint.JointType + ", " + joint.TrackingState + ", " + joint.Position.X + ", " + joint.Position.Y + ", " + joint.Position.Z);
}
coordinatesStream.Close();
}