I'm struggling to understand what is happening in part of an Arduino program I wrote, I copied the switch in processInput from another post about reading data from serial ports but have changed it a bit since then.
To me it seems like the output to the LCD screen should always be 0 since recievedNumber is set to 0 at the beginning of the function, it does output the data from the serial port correctly though. I'm also not sure what is happening on the line "receivedNumber += b - '0';" inside the last case.
Any advice or a breakdown of the logic would be appreciated, I intended to replace the last case with an if statement to learn how to do it without using the GNU extension but I just don't understand what is happening.
An example of data in the serial port:
<45,56><55,54>
Sorry if this is the wrong place but it felt too related to programming to post on the Arduino StackExchage.
const char startOfNumberDelimiter = '<';
const char middleOfNumbersDelimiter = ',';
const char endOfNumberDelimiter = '>';
void processNumberC (const long c)
{
lcd.setCursor(10,0);
lcd.print(c);
lcd.print("C");
}
void processNumberG (const long g)
{
lcd.setCursor(10,1);
lcd.print(g);
lcd.print("C");
}
void processInput ()
{
static long receivedNumber = 0;
byte b = Serial.read ();
switch (b)
{
case middleOfNumbersDelimiter:
processNumberC (receivedNumber);
receivedNumber = 0;
break;
case endOfNumberDelimiter:
processNumberG (receivedNumber);
break;
case startOfNumberDelimiter:
receivedNumber = 0;
break;
case '0' ... '9':
receivedNumber *= 10;
receivedNumber += b - '0';
break;
} // end of switch
} // end of processInput
void loop()
{
while (Serial.available ())
processInput ();
}
Related
I am communicating through Serial2 (arduino mega) by sending and receiving text.
95% of the time the communication goes well, but some of the text I am reading contains also parts of the text I am sending.
Code:
void setup (){
Serial.begin (19200);
while (!Serial) {
}
Serial1.begin(19200);
Serial2.begin (19200);
}
void loop (){
currentMillis = millis();
if(currentMillis > savedMillis + 1000){
Serial2.write("##geenbatterij##\r\n"); //check batterij
Serial2.write("##geensignaal##\r\n");
savedMillis = millis();
}
SerialEvent2zelf();
}
void serialEvent2zelf(){
if(Serial2.available()>0){
while (Serial2.available()){
processIncomingByte(Serial2.read ());
}
}
}
void processIncomingByte (const byte inByte){
static char input_line [MAX_INPUT];
static unsigned int input_pos = 0;
switch (inByte){
case '#': // end of text
input_line [input_pos] = 0; // terminating null byte
process_data (input_line);
input_pos = 0;
startSignReceived = false;
break;
// case '\r': // discard carriage return
// break;
case '#': // begin of text
startSignReceived = true;
break;
default:
if (input_pos < (MAX_INPUT - 1) && startSignReceived == true)
input_line [input_pos++] = inByte;
break;
}
}
Output (console reading):
odr/3.8
rnt/102h6m
as1/28.9
as2/28.8
ls1/0.1
ls2/0.1
bsn/82
kwt/74
wd1/4.7
wd2/0.7
rnt/102h6m
rpm/972
odr/3.7
rnt/102herijrnt/signaalrnt/102h6m //<-- see here
as1/28.9
as2/28.8
ls1/0.1
ls2/0.1
bsn/82
kwt/74
wd1/4.7
wd2/0.7
rnt/102h6m
rpm/981
odr/3.8
rnt/102h6m
as1/28.9
as2/28.8
ls1/0.1
ls2/0.1
What am I doing wrong and how to solve it? Thanks.
The fact that you have multiple instances of the Serial class is more than a little suspect because I am pretty sure you're only using a single serial port.
I'd suggest using only the first instance and completely removing serial1 and serial2.
Other notes :
code is missing. It could very well contain Undefined Behaviour
Maar weinig mensen lezen hier Nederlands. Het is niet de conventie om Nederlands te mengen met code
I am looking for a code which can generate V4 UUID using UTC Timestamp as input.
I want use this code in my Load Runner script to pass UUID in my Load Runner request.
Appreciate if the code is provided in C++
I recall using something like
int GenerateGuid()
{
typedef struct _GUID
{
unsigned long Group1;
unsigned short Group2;
unsigned short Group3;
unsigned char Group4[8];
} GUID;
GUID m_guid;
char msgId[msgIdSize];
lr_load_dll("ole32.dll");
CoCreateGuid(&m_guid);
sprintf(msgId, "%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x",
m_guid.Group1, m_guid.Group2, m_guid.Group3,
m_guid.Group4[0], m_guid.Group4[1], m_guid.Group4[2], m_guid.Group4[3],
m_guid.Group4[4], m_guid.Group4[5], m_guid.Group4[6], m_guid.Group4[7]);
lr_save_string(msgId, "msgId");
return 0;
}
This is basically call of CoCreateuid function (will apply to Windows load generators only) and storing the result into msgid LoadRunner Parameter.
Actually it was the last time I used LoadRunner as as far as I remember it failed to produce required amount of large POST requests on the hardware (and I also had to work around several artificial limitations on request size) while Apache JMeter worked as a charm. Just to compare, you need just call a single function like: ${__UUID} and that's it. Check out Writing Your First JMeter Script article if interested.
LoadRunner is a C virtual User, not C++
I refer you to the built-in functions web_save_timestamp_param() or lr_save_timestamp() as options for your use
I am using the below code to generate UUID in loadrunner independent of the OS of the Loadgenerators. Please check this link as well - How to generate Universally Unique IDentifier, UUID from LoadRunner independent of the OS
int lr_guid_gen()
{
char GUID[40];
int t = 0;
char *szTemp = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx";
char *szHex = "0123456789abcdef-";
int nLen = strlen (szTemp);
for (t=0; t<nLen+1; t++)
{
int r = rand () % 16;
char c = ' ';
switch (szTemp[t])
{
case 'x' : { c = szHex [r]; } break;
case 'y' : { c = szHex [r & 0x03 | 0x08]; } break;
case '-' : { c = '-'; } break;
case '4' : { c = '4'; } break;
}
GUID[t] = ( t < nLen ) ? c : 0x00;
}
lr_save_string(GUID,"PAR_GUID");
return 0;
}
I learning how to simulate digital logic circuits .
I am presenting the source code of my first attempt here.
It is small program for simulating circuits consisting
of AND,OR and NOT gates.
This code works well for circuits without loops.
When circuit loops are introduced it causes a stack overflow because of endless recursion.
Please help me to remove this bug.
Please note that this is a hobby project and any help will be appreciated.
Source code :
#include <cstdlib>
#include <iostream>
using namespace std;
class LogicGate
{
int type;//gate type: 0 for NOT, 1 for OR, 2 for AND
//pins
bool ina;//input a
bool inb;//input b::this pin is not used for NOT gate
bool outc;//output
//fan-in
LogicGate* ga;//gate connected to input a
LogicGate* gb;//gate connected to input b
//fan-out
LogicGate* gc;//gate connected to output
int gctarget;//target input to which the gate "gc" is connected, 0 for input a, 1 for input c
public:
char* name;
LogicGate()
{
ina = inb = outc = false;
ga = gb = gc = (LogicGate*)0;
type = 0;
}
LogicGate(bool a, bool b)
{
ina = a; inb = b; outc = false;
ga = gb = gc = (LogicGate*)0;
type = 0;
}
//set logic
void settype(int t){if(t>=0&&t<3)type=t;else type=0;}
//set input
void seta(bool a){ ina = a; }
void setb(bool b){ inb = b; }
void setab(bool a, bool b){ina = a; inb = b; }
//connect gate
void cona(LogicGate* cga){ ga = cga; }
void conb(LogicGate* cgb){ gb = cgb; }
void conab(LogicGate* cga, LogicGate* cgb){ ga = cga; gb = cgb; }
//connect the output of this gate to another gate's input
void chainc(LogicGate* cgc, int target)
{
gc = cgc;
gctarget = target;
if(target==0) cgc->cona(this); else cgc->conb(this);
}
//calculate output
bool calcout()
{
//if the input is not available make it available by forcing the connected gates to calculate
if(ga){ ina = ga->calcout(); } //BUG:this may cause Stack overflow for circuits with loops
if(gb){ inb = gb->calcout(); }//BUG:this may cause Stack overflow for circuits with loops
//do the logic when inputs are available
switch(type)
{
case 0:
outc = !ina; break;
case 1:
outc = ina || inb; break;
case 2:
outc = ina && inb; break;
}
//if a gate is connected to output pin transfer the output value to the target input pin of the gate
if(gc){
if(gctarget==0){
gc->seta(outc);
}else{
gc->setb(outc);
}
}
//for debugging only
cout<<name<<" outputs "<<outc<<endl;
return outc;
}
};
int main(int argc, char *argv[])
{
LogicGate x,z;
//AND gate
z.settype(2);
z.seta(false);
z.setb(true);
z.name = "ZZZ";
//OR gate
x.settype(1);
x.cona(&z); // take one input from AND gate's output
x.setb(true);
x.name = "XXX";
//z.cona(&x);// take one input from OR gate's output to make a loop:: results in stack overflow
x.chainc(&z,0);//connect the output to AND gate's input "a" to form loop:: results in stack overflow
cout<<"final output"<<x.calcout()<<endl;
return 0;
}
The Problem here is that you are Looping infinitely. A program behaves somehow different than real logic gates. I see two possibilities here:
1) Implement cycles
You can implement it like a cpu works. a call to calcout only calculates to Output of one gate and iterates to the next one. You could create a Container class for your gates:
class GateContainer
{
//Contains all gates of your "circuit"
std::vector<LogicalGate> allGates;
//Contains all current gates to be processed
std::queue<LogicalGate*> currentGates;
void nextStep();
}
The nextStep function could look like this:
void GateContainer::nextStep()
{
//Get first gate from queue
LogicalGate *current = currentGates.front();
currentGates.pop();
//Do all the calculations with th current gate
//Push the gate connected to the Output to the list
currentGates.push(current->gc);
}
Please not that this code is untested and may also Need some error checks
2) Try to catch Loops
You can also try to catch Loops in calcout. You could achieve this by creating a flag in LogicalGate and reset it every time before calling calcout:
class LogicalGate
{
...
bool calculated;
...
}
Now before calling calcout() You Need to set calculated to false for every gate. Then, calcout could look something like this:
bool calcout()
{
calculated = true;
if(ga && !ga->calculated){ ina = ga->calcout(); }
if(gb && !ga->calculated){ inb = gb->calcout(); }
...
}
I've come across a situation where I have a bunch of "systems" that need to be initialized in sequence, with the next system only being initialized if all of the proceeding systems initialized successfully.
This has led me to a whole slew of nested if - else statements. Here's some pseudo-code for visualization.
bool mainInit () {
if (!system1Init ()) {
reportError (); // some error reporting function
}
else {
if (!system2Init ()) {
reportError ();
}
else {
if (!system3Init ()) {
// ... and so on
I find that this starts to look like a mess when you get even a handful of levels to it.
Now I thought of using a switch statement instead, starting at the first case and falling through to the other cases on success, only breaking if there's an error.
bool mainInit () {
switch (1) {
case 1:
if (!system1Init ()) {
reportError ();
break;
}
case 2:
if (!system2Init ())
reportError ();
break;
}
// ....
}
Now, I like this a lot better. I find it much easier to read, especially with some decent comments, but I'm fairly new to programming.
So, my question is: Seeing how this is not how switch statements are traditionally used(at least from what I've seen), is something like this acceptable, or would this be considered bad form?
Being new to programming, I'm trying not to develop too many bad habits that might frustrate and make things more difficult for other programmers down the road.
I did a search, but most of what I found had to do with replacing chains of if - else if statements, not replacing nested ones.
Reference all of the systems in an array, for example an std::vector<mySystem*>, and loop over them sequentially, breaking off on the first fail. This way your entire code is reduced to less than 5 lines of code, even for 500+ systems.
The suggested switch hack is an evil example of XY problem solving: your real problem is that you don't have the array of systems, and are using named variables, thus eliminating all options to more flexibly use all systems, like in a loop.
Assuming that all your system#Init() calls are known at compile time, you can very easily put them in a table and then iterate over that table.
typedef (*system_init)(void);
system_init initialization_functions[] =
{
system1Init,
system2Init,
system3Init,
...
systemNInit
};
bool mainInit()
{
for(size_t idx(0); idx < sizeof(initialization_functions) / sizeof(initialization_functions[0]); ++idx)
{
if(!initialization_functions[idx]())
{
ReportError();
return false;
}
}
return true;
}
However, your existing code looks incorrect since the first mainInit() only calls system1Init() and then exits. Probably not what you wanted in the first place.
if(!system1Init())
{
ReportError();
return false;
}
// if you add an else, the system2Init() does not get called
// even if system1Init() succeeds
if(!system2Init())
{
ReportError();
return false;
}
[...]
return true;
Would the switch answer your problem? Not as it was written. That is, if you wanted to call the mainInit() function with a counter, it could be useful. Drupal uses that mechanism:
bool mainInit(int idx)
{
bool r(true);
switch(idx)
{
case 1:
r = system1Init();
break;
case 2:
r = system2Init();
break;
[...]
}
if(!r)
{
ReportError();
}
return r
}
Note that the table mechanism works the same way as the switch. As long as all the code is found in the systemNInit() functions (and it should be), the switch does not add anything, so you could do something like this too:
bool mainInit(int idx)
{
if(idx < 0 || idx >= sizeof(initialization_functions) / sizeof(initialization_functions[0]))
{
throw std::range_error("index out of bounds");
}
if(!initialization_functions[idx]())
{
ReportError();
return false;
}
return true;
}
Calling the mainInit() with an index can be helpful in case you want to "de-initialize" properly:
int main()
{
for(size_t idx(0); idx < ...; ++idx)
{
if(!mainInit(idx))
{
while(idx > 0)
{
--idx;
mainDeinit(idx);
}
exit(1);
}
}
...app do something here...
}
Use custom exceptions with clear error messages and add a try-catch-report-die around the code in main(). Exceptions are there to specifically make your case look good by making "bad path" implicit.
void initX() { ...; throw std::invalid_argument_exception("..."); }
int main() {
try {
init1(); init2(); ... run();
return 0;
} catch (std::exception const& e) {
log(e.what()); exit 42;
}
}
I'd do it this way:
bool mainInit () {
if (!system1Init ()) {
return(false);
}
if (!system2Init ()) {
return(false);
}
if (!system3Init ()) {
return(false);
}
//...
return(true);
}
//...
if(!mainInit()) {
reportError();
}
Consider packet coming from somewhere. It has field VERSION, there are N possible VERSIONS of incoming packet.
Every packet with VERSION X has to be processed by proper methods/set of instructions for every packet VERSION from X to 1. My only idea to accomplish this task is very ugly like:
PACKET p = GetPacketFromSomewhere();
// p.VERSION is 3
if (p.VERSION > 0) {
// things for p.VERSION == 1
}
if (p.VERSION > 1) {
// things for p.VERSION == 2
}
if (p.VERSION > 2) {
// things for p.VERSION == 3
}
// set of if statements up to version N
The real situation is that, I have packet VERSIONS above number 10 and things still are likely to change. New packet VERSIONS will be added while I need to keep backward compatibility. This code is bad, at least I don't like it. Do you guys have any better idea how to handle this case?
If the order of processing is not important, you can use switch without break:
PACKET p = GetPacketFromSomewhere();
// p.VERSION is 3
switch (p.VERSION) {
case 3: {
// things for p.VERSION == 3
}
case 2: {
// things for p.VERSION == 2
}
case 1: {
// things for p.VERSION == 1
}
}
EDIT:
You could also use recursive function template specialization like this:
template<int N>
void proc(PACKET& p){
proc<N-1>(p);
}
template<>
void proc<1>(PACKET& p){
//things for p.VERSION == 1
}
template<>
void proc<2>(PACKET& p){
proc<1>(p)
//things for p.VERSION == 2
}
template<>
void proc<3>(PACKET& p){
proc<2>(p)
//things for p.VERSION == 3
}
and then call the processing function like this:
switch (p.VERSION ) {
case 1: proc<1>(p) break;
case 3: proc<2>(p) break;
case 3: proc<3>(p) break;
default: {
std::cout << "Protocol version not impplemented - using highest known version" << std::endl;
proc<3>(p);
}
This should also be pretty efficient performance wise (in case this is a concern of yours) and you don't have to worry about gaps in the protocol version.
Use a map of type map<unsigned int, function> where function is a pointer to a function of the desired type:
typedef void (*function)();
std::map<int,function> handlers;
handlers[1] = &ver1handler;
...
handlers[N] = &verNhandler;
if(handlers.count(p.VERSION))
(*handlers.find(p.VERSION))();
where ver[N+1]handler would be defined as:
void ver[N+1]handler(){
ver[N]handler();
// additional handle commands
}
Or use the switch command, with the handlers defined in the same way.