How do I include code snippets (not objects) in an Arduino program? - arduino

Problem Solved!!! See below for solution
I was about to post this question and decided to check the web one more time. This site https://www.freepascal.org/docs-html/prog/progsu40.html
has this statement: The {$I filename} or {$INCLUDE filename} directive tells the compiler to read further statements from the file filename. The statements read there will be inserted as if they occurred in the current file.
This is exactly what I want to do with Arduino. How do I do it?
My Skill Set:
Writing code since 1967. Yes, I survived Y2K, which was a real thing; so I'm not new to programming/debugging. Mainframes and PC's. Very solid COBOL and SAS skills. Good skills with Borland/Lazarus Object Pascal. Weak C/C++ skills.
Background:
I have two working Arduino programs that are used on a model railroad. Prog1 uses infrared sensors to light LEDs that indicate the position of a train in a tunnel. I built the IRSensor class to handle a single sensor. Prog2 uses push-buttons to set a route through several track switches. Each track switch is set via a servo. I extended the Servo class to TOServo, which encapsulate most of the commonality in each track switch.
Now I'm working on a different model railroad and need merge Prog1 and Prog2 into a single program. Building Prog3 via copy/paste from programs 1 & 2 has proved unwieldy.
Problem:
How do I tell the Arduino pre-processor/compiler to "insert filename here; do not compile, pre-compile, or otherwise process the filename unless it is wrapped around the file asking for the insertion"?
What I've tried:
I built Prog3 by separating the code for Prog2 into 3 sections -- Main program storage & code and 2 include statements (Storage definitions and executable code for TOServo). These include statements pull in code that define or access an array of TOServo. I've used several suffixes (.h/.ino and .h/.cpp and .c/.c), and they all generate 'not declared in this scope' errors.
Finally:
Thanks for your help.
SOLUTION
My .ino file had grown large & unwieldy. The 'solution' was to move a large segment of code and matching declarations to external .h/.cpp files, and to access those files via #include statements. The program would not compile (undefined variables); they were, in fact, defined but the compiler couldn't find them. After many attempts to fix or rearrange the code, finally two things dawned on me.
1)The Arduino pre-compiler changes (rearranges?) my code so that C++ and the Arduino CPU can work together. This means that the code I see is not always the code the compiler sees.
2)My .h/.cpp files define and manage an array of servo objects. I could convert those files into an object that I access from the main .ino file.
So I've solved my problem. Thanks to all those who have posted in many forums/sites, especially to Tarick Welling who stayed with me to the end.

Related

cuda global pointer allocation in different source file

I faced a situation that I need some tables to be filled in one source file (for example fill.cu) and then be used in different kernels in different source files.
I tried declaring a pointer __device__ float *myTable; as 'extern' in fill.h header file and adding that to others.cpp and defining that pointer in fill.cu and allocate and fill it there.
This way, I got linker error indicating that myTable has been already defined in fill.cpp.
After many unsuccessful try, I decided to put all kernels that need this table in same source file, this way everything works fine until I added an cudaMalloc in main function before allocating my table in fill.cpp.
This way I noticed that table values and data allocated in main are overlapped and using cuda debugging tools of MS visual studio 2015, I found that 2 allocated pointer are same!!!
Please advice how to declare a global pointer in cuda without conflict.
The traditional CUDA linkage model requires that all device symbols, textures, functions, etc. are defined and used within the scope of the same translation unit. It sounds like your code structure is violating this requirement.
You have two choices:
Continue to the same code structure, but provide wrapper functions which your main can call to perform operations on statically declared device variables, rather than directly manipulating device symbols with the CUDA API from other code.
Use separate compilation. Here, you define the device symbol you want to access in exactly one file and declare the same symbol as externeverywhere else you need to use that symbol. You must explicitly use several nvcc options to compile your device code and use a separate device code linking stage.
Both approaches are well documented.

Block for serial output in GNURadio/GRC

I am working on a project that involves GNU Radio/GRC and am not very familiar with the software. I am trying to output data to a serial port in GNU Radio using a block, but have not found a way to do so.
I was wondering if there is a pre-defined block that I can use to put this information to a serial port (USB on a Raspberry Pi 3), or if I had to create my own block. And if I had to create my own block, what that code would look like.
I have been able to write the data to a file using the File Sink to make sure I was getting data, and was wondering if the fix is something as simple as changing the File sink to an serial port sink. See picture below:
http://imgur.com/a/BdaMZ
I also did some research and found a github repo that looks like what I need -- unfortunately, the repository that it links to is no longer there. It did mention using pyserial, which is what I believe is meant for creating my own block in python. The link to this repo is below:
https://github.com/jmalsbury/gr-pyserial
… was wondering if the fix is something as simple as changing the File sink to an serial port sink.
Yes! Or No, it's even easier:
So, in fact, you could even simply use your file sink to write to e.g. /dev/ttyS0 (or /dev/ttyUSB0, or whatever is the device name of your serial port), but you'd have to set up the serial port to work like you want it to separately first. A way of doing that would be using stty, e.g.
stty -F /dev/ttyS0 115200
prior to running your flow graph.
Note that practically all in your flow graph point points to you not being sufficiently proficient with GNU Radio to successfully exchange data. I can't cover everything here, please read the official Guided Tutorials, but:
In a flow graph like yours, where the IO is the inherently rate-limiting element, you must not use "Throttle". Throttle is really just a tool to avoid a flowgraph consuming all your CPU (and to slow down simulations)
Giving your files a .grc ending is bad practice, as that is the ending reserved for GNU Radio flow graphs.
Giving it a .txt ending is plain misleading, since there's no text involved whatsoever. The "file format" (I wouldn't even call it a format) is really just plain binary numbers, as your computer handles them; not decimal ASCII representations of these floating point binary numbers
I also did some research and found a github repo that looks like what I need -- unfortunately, the repository that it links to is no longer there. It did mention using pyserial, which is what I believe is meant for creating my own block in python. The link to this repo is below:
Don't know what you're referring to, https://github.com/jmalsbury/gr-pyserial is perfectly existing!

How to obfuscate lua code?

I can't find anything on Google for some tool that encrypts/obfuscates my lua files, so I decided to ask here. Maybe some professional knows how to do it? (For free).
I have made a simple game in lua now and I don't want people to see the code, otherwise they can easily cheat. How can I make the whole text inside the .lua file to just random letters and stuff?
I used to program in C# and I had this .NET obfuscator called SmartAssembly which works pretty good. When someone would try check the code of my applications it would just be a bunch of letters and numbers together with chinese characters and stuff.
Anyone knows any program that can do this for lua aswell? Just load what file to encrypt, click Encrypt or soemthing, and bam! It works!?
For example this:
print('Hello world!')
would turn into something like
sdf9sd###&/sdfsdd9fd0f0fsf/&
Just precompile your files (chunks) and load binary chunks. luacallows you to strip debugging info. If that is not enough, define your own transformations on the compiled lua, stripping names where possible. There's not really so much demand for lua obfuscators though...
Also, you loose one of the main advantages of using an embedded scripting language: Extensibility.
The simplest obfuscation option is to compile your Lua code as others suggested, however it has two major issues: (1) the strings are still likely to be easily visible in your compiled code, and (2) the compiled code for Lua interpreter is not portable, so if you target different architectures, you need to have different compiled chunks for them.
The first issue can be addressed by using a pre-processor that (for example) converts your strings to a sequence of numbers and then concatenates them back at run-time.
The second issue is not easily addressed without changes to the interpreter, but if you have a choice of interpreters, then LuaJIT generates portable bytecode that will run across all its platforms (running the same version of LuaJIT); note that LuaJIT bytecode is different from Lua bytecode, so it can't be run by a Lua interpreter.
A more complex option would be to encrypt the code (possibly before compiling it), but you need to weight any additional mechanisms (and work on your part) against any possible inconvenience for your users and any loss you have from someone cracking the protection. I'd personally use something sufficiently simple to deter the majority of curious users as you likely stand no chance against a dedicated hacker anyway.
You could use loadstring to get a chunk then string.dump and then apply some transformations like cycling the bytes, swapping segments, etc. Transformations must be reversible. Then save to a file.
Note that anyone having access to your "encryptor" Lua module will know how to decrypt your file. If you make your encrypted module in C/C++, anyone with access to source will too, or to binary of Lua encryption module they could require the module too and unofuscate the code. With interpreted language it is quite difficult to do: you can raise the bar a bit via the above the techniques but raising it to require a significant amount of work (the onlybreal deterent) is very difficult AFAIK.
If you embed the Lua interpreter than you can do this from C, this makes it significantly harder (assuming a Release build with all symbols stripped), person would have to be comfortable with stepping through assembly but it only takes one capable person to crack the algorithm then they can make the code available to others.
Yo still interested in doing this? :)
I thought I'd add some example code, since the answers here were helpful, but didn't get us all the way there. We wanted to save some lua table information, and just not make it super easy for someone to inject their own code. serialize your table, and then use load(str) to make it into a loadable lua chunk, and save with string.dump. With the 'true' parameter, debug information is stripped, and there's really not much there. Yes you can see string keys, but it's much better than just saving the naked serialized lua table.
function tftp.SaveToMSI( tbl, msiPath )
assert(type(tbl) == "table")
assert(type(msiPath) == "string")
local localName = _GetFileNameFromPath( msiPath )
local file,err = io.open(localName, "wb")
assert(file, err)
-- convert the table into a string
local str = serializer.Serialize( tbl )
-- create a lua chunk from the string. this allows some amount of
-- obfuscation, because it looks like gobblygook in a text editor
local chunk = string.dump(load(str), true)
file:write(chunk)
file:close()
-- send from /usr to the MSI folder
local sendResult = tftp.SendFile( localName, msiPath )
-- remove from the /usr folder
os.remove(localName)
return sendResult
end
The output from one small table looks like this in Notepad++ :
LuaS У
Vx#w( # АKА└АJБ┴ JА #
& А &  name
Coulombmetervalue?С╘ ажў

Analyzing large projects with Frama-C

I want to analyze a file from a large project to create a Program Dependence Graph using Frama-C, but keep getting odd errors such as:
/usr/include/bits/fcntl-linux.h:305:[kernel] user error: Length of array is zero. This extension is unsupported
If I try to use the libc implementation provided by frama-c, compilation fails due to missing headers such as sys/file.h.
I am trying to analyze files from the Lynx project, specifically the file in src/WWW/Library/Implementation/HTTP.c, using GCC version 4.8.1
What I really need is to be able to generate a PDG for this source file (which of course has various dependencies) but I think if I could get even a somewhat incomplete graph by skipping over undefined functions, that would be a great first step.
You need to provide your own "file.h" file in a directory "sys" placed anywhere in the path GCC searches when pre-processing for Frama-C.
For reference, here is the implementation of sys/file.h on another system. You may also be interested in this other StackOverflow question about sys/file.h.
For Frama-C's value analysis, assigns clauses alongside the prototypes go a long way:
/*# assigns *f \from ui, s, *fo; */
void finit(struct file *f, u_int ui, short s, void *p, struct fileops *fo);
Note that I have no idea what function finit() does and whether the above is a correct assigns clause for it. In fact, this is the whole point: neither does Frama-C out of the box, and since this lowish-level, lessish-portable system call is used in the code you wish to analyze, someone will have to know. I am afraid it is going to have to be you. On the plus side, you only need to provide the types, macros and function prototypes that the code you wish to analyze uses.

finding duplicate source code

I'm analyzing some legacy code. It is about 80.000 lines of old plsql code. On a fist look there is quite some duplication in the source which needs to be removed. Instead off doing diff's manual and looking at each file there must be some tool/commandline confu out there to detect duplicate lines of source code.
My goal is to make an educated guess about the minimal size of a rewrite of source and about how much actual knowledge is captured in this program. I wrote some a basic static code analyzer to find the amount of control statements IF ELSE FOR etc and Functions in each file.
But duplicated code still needs to be removed from my statistics.
Have you looked at Simian - Similarity Analyser? (Just checked and it's no longer free, but it is available for a period of 15 days for evaluation purposes.)
Simian (Similarity Analyser)
identifies duplication in Java, C#, C,
C++, COBOL, Ruby, JSP, ASP, HTML, XML,
Visual Basic, Groovy source code and
even plain text files. In fact, simian
can be used on any human readable
files such as ini files, deployment
descriptors, you name it.
I have used it in practice and it does work well.
Sonar has duplication detection and claims to support PL/SQL, though I've never used it for that.
You would need to beg/borrow/steal/write a plsql parser and compare the resulting abstract syntax trees. With the size of the code base you have, that might be worthwhile. There would be other uses for the parser once you're done.
How about this:
http://sourceforge.net/projects/sddforeclipse/
It is opensource, and is said to be used by commercial software. It is a plugin to Eclipse, by the way.

Resources