"pBase not defined"? pBase is defined in the included class - c++

This program is supposed to read acceleration values from a Wii remote and light up LEDs based on those values. The only error I'm getting that prevents compilation is that pBase isn't defined in main.cpp. main.cpp includes ZedBoard.h and ZedBoard.cpp where pBase is defined so I'm failing to see the issue here. I've been trying to solve this for a while and I can't figure it out.
ZedBoard.h
#ifndef ZEDBOARD_H
#define ZEDBOARD_H
const int gpio_led1_offset = 0x12C; // Offset for LED1
const int gpio_led2_offset = 0x130; // Offset for LED2
const int gpio_led3_offset = 0x134; // Offset for LED3
const int gpio_led4_offset = 0x138; // Offset for LED4
const int gpio_led5_offset = 0x13C; // Offset for LED5
const int gpio_led6_offset = 0x140; // Offset for LED6
const int gpio_led7_offset = 0x144; // Offset for LED7
const int gpio_led8_offset = 0x148; // Offset for LED8
const int gpio_sw1_offset = 0x14C; // Offset for Switch 1
const int gpio_sw2_offset = 0x150; // Offset for Switch 2
const int gpio_sw3_offset = 0x154; // Offset for Switch 3
const int gpio_sw4_offset = 0x158; // Offset for Switch 4
const int gpio_sw5_offset = 0x15C; // Offset for Switch 5
const int gpio_sw6_offset = 0x160; // Offset for Switch 6
const int gpio_sw7_offset = 0x164; // Offset for Switch 7
const int gpio_sw8_offset = 0x168; // Offset for Switch 8
const int gpio_pbtnl_offset = 0x16C; // Offset for left push button
const int gpio_pbtnr_offset = 0x170; // Offset for right push button
const int gpio_pbtnu_offset = 0x174; // Offset for up push button
const int gpio_pbtnd_offset = 0x178; // Offset for down push button
const int gpio_pbtnc_offset = 0x17C; // Offset for center push button
// Physical base address of GPIO
const unsigned gpio_address = 0x400d0000;
// Length of memory-mapped IO window
const unsigned gpio_size = 0xff;
// Class Definition
class ZedBoard {
private:
char *pBase; // virtual address where I/O was mapped
int fd; // file descriptor for dev memory
int dummyValue; // for testing without a Zedboard
public:
ZedBoard(); // Default Constructor
~ZedBoard(); // Destructor
void RegisterWrite(char *pBase, int offset, int value);
int RegisterRead(int offset);
void Write1Led(char *pBase, int ledNum, int state);
void WriteAllLeds(int value);
int Read1Switch(int switchNum);
int ReadAllSwitches();
};
#endif
ZedBoard.cpp
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/mman.h>
#include <iostream>
#include "ZedBoard.h"
using namespace std;
/**
* Constructor Initialize general-purpose I/O
* - Opens access to physical memory /dev/mem
* - Maps memory at offset 'gpio_address' into virtual address space
*
* #param None Default constructor does not need arguments.
* #return None Default constructor does not return anything.
*/
ZedBoard::ZedBoard(){
cout << "\nStarting...." << endl;
// dummyValue = 99;
// Uncomment this block of code when connected to the Zedboard
fd = open( "/dev/mem", O_RDWR);
pBase = (char *) mmap(NULL,gpio_size,PROT_READ | PROT_WRITE,
MAP_SHARED,fd,gpio_address);
// Check error
if (pBase == MAP_FAILED)
{
cerr << "Mapping I/O memory failed - Did you run with 'sudo'? \n";
exit(1); // Returns 1 to the operating system;
}
}
/**
* Destructor to close general-purpose I/O.
* - Uses virtual address where I/O was mapped.
* - Uses file descriptor previously returned by 'open'.
*
* #param None Destructor does not need arguments.
* #return None Destructor does not return anything.
*/
ZedBoard::~ZedBoard(){
munmap(pBase, gpio_size);
}
/*
* Write a 4-byte value at the specified general-purpose I/O location.
*
* - Uses base address returned by 'mmap'.
* #parem offset Offset where device is mapped.
* #param value Value to be written.
*/
void ZedBoard::RegisterWrite(char *pBase, int offset, int value)
{
* (int *) (pBase + offset) = value;
// dummyValue = value;
}
/**
* Read a 4-byte value from the specified general-purpose I/O location.
- Uses base address returned by 'mmap'.
#param offset Offset where device is mapped.
#return Value read.
*/
int ZedBoard::RegisterRead(int offset)
{
return * (int *) (pBase + offset);
// return dummyValue;
}
/*
Changes the state of an LED (ON or OFF)
- Uses base address of I/O
#param ledNum LED number (0 to 7)
#param state State to change to (ON or OFF)
*/
/*
Show lower 8 bits of integer value on LEDs
- Calls Write1Led() to set all LEDs
#param value Value to show on LEDs
*/
void ZedBoard::WriteAllLeds(int value)
{
cout << "\nWriting to all LEDs...." << endl;
for(int i = 0; i < 8; i++) {// write to all LEDs
Write1Led(pBase, i, (value / (1<<i)) % 2);
}
}
void ZedBoard::Write1Led(char *pBase, int ledNum, int state)
{
cout << "\nWriting to LED " << ledNum << ": LED state = " << state << endl;
if (ledNum == 1)
{
RegisterWrite(pBase, gpio_led1_offset, state);
}
else
{
RegisterWrite(pBase, gpio_led1_offset + (ledNum * 4), state);
}
}
/*
Reads the value of a switch
- Uses base address of I/O
#param switchNum Switch number (0 to 7)
#return Switch value read
*/
int ZedBoard::Read1Switch(int switchNum)
{
cout << "\nReading Switch " << switchNum << endl;
//return RegisterRead(gpio_sw1_offset + (switchNum * 4));
return switchNum;
}
/*
Reads the switch values into a decimal integer
- Calls Read1Switch() to read all switches
#return Switches' value read
*/
int ZedBoard::ReadAllSwitches()
{
int switchValue = 0;
cout << "\nReading all switches...." << endl;
for(int i = 7; i >= 0; i--) {// read all switches
switchValue = (switchValue << 1) + Read1Switch(i);
}
return switchValue;
}
WiimoteAccel.h
#ifndef WIIMOTEACCEL_H
#define WIIMOTEACCEL_H
class WiimoteAccel{
public:
WiimoteAccel();
~WiimoteAccel();
void Wiimote();
void Listen();
virtual void AccelerationEvent(int code, int acceleration);
private:
int fd;
};
#endif
WiimoteAccel.cpp
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include "ZedBoard.h"
#include "WiimoteAccel.h"
WiimoteAccel::WiimoteAccel()
{
}
WiimoteAccel::~WiimoteAccel()
{
}
void WiimoteAccel::Wiimote()
{
fd = open("/dev/input/event0", O_RDONLY);
if (fd == -1)
{
std::cerr << "Error: Could not open event file - forgot sudo?\n";
exit(1);
}
}
void WiimoteAccel::Listen()
{
for (;;)
{
// Read a packet of 16 bytes from Wiimote
char buffer[16];
read(fd, buffer, 16);
// Extract code (byte 10) and value (byte 12) from packet
int code = buffer[10];
short acceleration = * (short *) (buffer + 12);
this->AccelerationEvent(code, acceleration);
}
}
void WiimoteAccel::AccelerationEvent(int code, int acceleration)
{
// Print them
std::cout << "Code = " << code << ", acceleration = " << acceleration << '\n';
}
main.cpp
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include "WiimoteAccel.h"
#include "ZedBoard.h"
#include "ZedBoard.cpp"
using namespace std;
class WiimoteToLed : public WiimoteAccel {
private:
ZedBoard* zed_board;
public:
WiimoteToLed(ZedBoard* zed_board);
~WiimoteToLed();
void AccelerationEvent(int code, int acceleration)
{
int x = 0;
for(;;)
{
if (code == 3)
{
cout << "ACCELERATION IS "<< acceleration <<"!\n";
if(acceleration == 0)
{
x = 0;
}
else if(acceleration > -100 && acceleration <= -75)
{
x = 1;
}
else if(acceleration > -75 && acceleration <= -50)
{
x = 2;
}
else if(acceleration > -50 && acceleration <= -25)
{
x = 3;
}
else if(acceleration > -25 && acceleration > 0)
{
x = 4;
}
else if(acceleration < 0 && acceleration >= 25)
{
x = 5;
}
else if(acceleration < 25 && acceleration >= 50)
{
x = 6;
}
else if(acceleration < 50 && acceleration >= 75)
{
x = 7;
}
else if(acceleration < 75 && acceleration >= 100)
{
x = 8;
}
switch(x)
{
case 0:
cout << "Wiimote isn't moving\n";
zed_board->Write1Led(pBase,1,0);
zed_board->Write1Led(pBase,2,0);
zed_board->Write1Led(pBase,3,0);
zed_board->Write1Led(pBase,4,0);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 1:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,0);
zed_board->Write1Led(pBase,3,0);
zed_board->Write1Led(pBase,4,0);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 2:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,0);
zed_board->Write1Led(pBase,4,0);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 3:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,0);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 4:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,0);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 5:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,1);
zed_board->Write1Led(pBase,6,0);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 6:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,1);
zed_board->Write1Led(pBase,6,1);
zed_board->Write1Led(pBase,7,0);
zed_board->Write1Led(pBase,8,0);
case 7:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,1);
zed_board->Write1Led(pBase,6,1);
zed_board->Write1Led(pBase,7,1);
zed_board->Write1Led(pBase,8,0);
case 8:
zed_board->Write1Led(pBase,1,1);
zed_board->Write1Led(pBase,2,1);
zed_board->Write1Led(pBase,3,1);
zed_board->Write1Led(pBase,4,1);
zed_board->Write1Led(pBase,5,1);
zed_board->Write1Led(pBase,6,1);
zed_board->Write1Led(pBase,7,1);
zed_board->Write1Led(pBase,8,1);
default:
cout << "Code = " << code <<'\n';
}
}
else
{
continue;
}
}
}
};
WiimoteToLed::WiimoteToLed(ZedBoard* zed_board)
{
Wiimote();
}
WiimoteToLed::~WiimoteToLed()
{
}
int main()
{
// Instantiate ZedBoard object statically
ZedBoard zed_board;
// Instantiate WiimoteToLed object statically, passing a pointer to the
// recently created ZedBoard object.
WiimoteToLed wiimote_to_led(&zed_board);
// Enter infinite loop listening to events. The overridden function
// WiimoteToLed::AccelerationEvent() will be invoked when the user moves
// the Wiimote.
wiimote_to_led.Listen();
// Unreachable code, previous function has an infinite loop
return 0;
}
makefile
WiimoteAccel: main.o WiimoteAccel.o
g++ main.o WiimoteAccel.o -o WiimoteAccel
main.o: main.cpp WiimoteAccel.h
g++ -g -Wall -c main.cpp
WiimoteAccel.o: WiimoteAccel.cpp WiimoteAccel.h
g++ -g -Wall -c WiimoteAccel.cpp
clean:
rm main.o WiimoteAccel.o WiimoteAccel

In WiimoteToLed::AccelerationEvent you call
zed_board->Write1Led(pBase,1,1);
but pBase is not declared in this scope. You have a pBase member of the zed_board, but that is a different one.

Related

Define_Module() throws an error | C++ | Omnet++

There is an error in Define_Module(OLT) when i try to build my code.
Am i doing something wrong?
D:\omnetpp-4.6\ptixiaki\XGPON/OLT.cc:18: undefined reference to `OLT::OLT()'
collect2.exe: error: ld returned 1 exit status
make: *** [out/gcc-debug//XGPON.exe] Error 1
Makefile:94: recipe for target 'out/gcc-debug//XGPON.exe' failed
//XGPON.NED
package xgpon;
import ned.DelayChannel;
import ned.IdealChannel;
simple OLT
{
#display("i=device/mainframe");
gates:
input splitter_to_OLT;
output OLT_to_splitter;
}
simple Splitter
{
#display("i=device/modem");
gates:
input ONU_splitter[];
input OLT_splitter;
output splitter_OLT;
output splitter_ONU[];
}
simple ONU
{
#display("i=device/laptop");
gates:
input splitter_to_ONU;
output ONU_to_splitter;
}
network XGPON
{
parameters:
#display("bgb=550,234;i=block/network2");
int n_nodes = 6;
types:
channel upstream extends ned.DatarateChannel
{
datarate = 2.48832 Gbps; //datarate of the channel
}
channel downstream extends ned.DatarateChannel
{
datarate = 9.95328 Gbps; //datarate of the channel
}
submodules:
splitter: Splitter {
#display("p=258,109");
}
olt: OLT {
#display("p=57,59");
}
onu: ONU {
#display("p=393,87");
}
connections:
olt.OLT_to_splitter --> downstream -->splitter.OLT_splitter;
splitter.splitter_OLT --> downstream --> onu.splitter_to_ONU;
splitter.splitter_ONU++ --> upstream --> olt.splitter_to_OLT;
onu.ONU_to_splitter --> upstream --> splitter.ONU_splitter++;
}
//OLT.H
#ifndef OLT_H_
#define OLT_H_
#include <omnetpp.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include "Packet_m.h"
#include "DownstreamFrame_m.h"
#include "UpstreamFrame_m.h"
#define FRAME_TIME 691.2
class OLT : public cSimpleModule
{
private:
int source;
//int destination;
simsignal_t arrivalSignal;
int no_sent;
int no_rcvd;
cMessage *DownstreamFrameSendEvent, *NewPacketArrivalEvent;
simtime_t sendTimeout, bufferTimeout;
XGPONpacket *downFragment;
cPacketQueue *OLTBuffer;
std::vector<double> distance, RTT, BandwidthUtilizationProfile, AllocationWeight;
//std::vector<long double> accumulatedRequestedBandwidth , accumulatedAllocatedBandwidth;
std:: vector<int> upstreamBandwidthDemands, DownPacketsForONU, destination;
int oltId, numberOfOnus, headerSize, PSBd, parityBytes, PLOAMdMessages, FrameQueueSize, fragmentBytes, BWMap;
//int FixedGuarandeedBandwidth, totalUpstreamBandwidth, AssuredGuarandeedBandwidth, firstPhaseNonGuarandeedBandwidth;
//long double totalBytesCreated, totalBytesReceived, SumDelay, SquareSumDelay, totalUpDelay, SumBUP;
//double ABU, ProtectionParameter, OverloadedOnusAllocationWeighSum, UpdatingImpact, SW;
double ONU_time_counter ; /* a local time counter for file results */
double variate; /* the final exponenetial variate (interarrivals) */
double sum_variate ; /* used to compute the experimental mean for variate */
double sum_rnd; /* used to compute the experimental mean for UD */
long loops ; /* counter for loops */
long pkt_per_time_unit ; /* nb of pkts per unit of time */
double time; /* our simulated time in us */
double mean,start_pktime,ref_time,end_pktime;
double rnd_nb; /* the uniform random number */
public :
OLT();
virtual ~OLT();
protected:
virtual void initialize();
virtual void handleMessage(cMessage *msg);
virtual XGPONpacket *generatePacket();
virtual void generateFrame(cPacketQueue *queue);
//virtual void generateHeader(cPacketQueue *queue);
virtual void forwardFrame(XGPONpacket *msg);
virtual void finish();
//virtual int defragmentation(cPacketQueue *queue);
};
#endif /* OLT_H_ */
//OLT.CC
#include "OLT.h"
Define_Module(OLT); //the error is here
void OLT::initialize()
{
numberOfOnus = 6;
cPacketQueue* OLTBuffer = new cPacketQueue("OLTBuffer");
for(int i = 0; i<= numberOfOnus; i++){
OLTBuffer->insert(generatePacket());
XGPONpacket *packet = (XGPONpacket *) OLTBuffer->pop();
//Distance
distance.push_back(destination.at(i) + 20);
EV << "My distance is " << distance[i] << " numbers.\n \n";
EV << "My destination is " << packet->getDestination()/2 << ".\n \n";
//RTT
RTT.push_back(distance.at(i) / 3*(10^8));
EV << "My RTT is " << RTT[i] << " numbers.\n \n";
}
EV << "My buffer size is " << OLTBuffer->getLength() << " numbers.\n \n";
//generateFrame(OLTBuffer);
}
void OLT::handleMessage(cMessage *msg)
{
XGPONpacket *ttmsg = check_and_cast<XGPONpacket *>(msg);
forwardFrame(ttmsg);
}
void OLT::generateFrame(cPacketQueue *OLTBuffer)
{
DownFrame *queue = new DownFrame();
//Fmqueue Fmqueue;
queue->~DownFrame();
//FrameQueueSize = queue -> getFrameSize();
//cPacketQueue *queue = new cPacketQueue();
//FrameQueueSize = 155520;
for(int i=0 ; i <OLTBuffer->getLength(); i++)
{
//EV << "GAMW TI MANA SOU " << OLTBuffer->getLength() << " numbers.\n \n";
XGPONpacket *packet = (XGPONpacket *) OLTBuffer->pop();
simtime_t waitingTime = simTime() - packet->getCreationTime();
double processTime = (packet->getBitLength()/(9.95328 * pow (10,9))) + (RTT.at(packet->getDestination())/2);
simtime_t receptTime = waitingTime + processTime;
packet->setReceptionTime(receptTime);
EV << "<<<<<<< OLT (id =" << oltId << ") : Packet " << packet->getName() << "reception time:" << packet->getReceptionTime() << ">>>>> \n";
OLTBuffer -> insert(packet);
}
while ((queue->getByteLength() < FrameQueueSize) && (OLTBuffer->isEmpty() == false))
{
XGPONpacket *max = (XGPONpacket *) OLTBuffer->pop();
for(int i=0; i<OLTBuffer->length(); i++)
{
XGPONpacket *data = (XGPONpacket *) OLTBuffer->pop();
if(max->getReceptionTime() >= data->getReceptionTime())
{
OLTBuffer -> insert(data);
}
else
{
OLTBuffer->insert(max);
max = data->dup();
delete data;
}
}
EV <<"<<<< OLT (id =" << oltId <<") : Packet " << max->getName() << " reception time:" << max->getReceptionTime() << "inserted to frame >>>>\n";
queue->insert(max);
}
}
XGPONpacket *OLT::generatePacket()
{
// Produce source and destination addresses.
//source = getIndex(); // our module index
//Destinationn
int time_limit = 60;
for(source = 1; source <= numberOfOnus-1; source++)
{
ONU_time_counter = 0;
pkt_per_time_unit = 0;
sum_variate = 0;
sum_rnd = 0;
loops = 0;
time=0;
destination.push_back(intuniform(2,numberOfOnus-1));
start_pktime=0.7;
end_pktime=12.7; //1gb prepei na brw transmision time
mean = start_pktime;
ref_time = time;
while( time < time_limit )
{
if(ONU_time_counter >= FRAME_TIME)
{
mean = (double) mean +(end_pktime - start_pktime)/((time_limit - ref_time)/FRAME_TIME);
ONU_time_counter = ONU_time_counter - FRAME_TIME;
/* prints the nb of pkts / unit time */
//fprintf(files1, "\n%ld", pkt_per_time_unit);
pkt_per_time_unit = 0;
}
//rnd_nb = (random()/limit); /* the random number 0<= x <=1 */
rnd_nb = uniform(0,1);
/* compute the IAT */
variate = (-mean)*log(rnd_nb); /* Poisson IAT */
//wait(variate);
XGPONpacket *msg = new XGPONpacket();
msg->setSource(source);
msg->setDestination(destination[source]);
msg->setByteLength(intuniform(64,1518));
return msg;
}
}
}
void OLT::forwardFrame(XGPONpacket *msg)
{
// Same routing as before: random gate.
int n = gateSize("out");
//int k = destination;
//EV << "Forwarding message " << msg << " on gate[" << k << "]\n";
send(msg, "out");
}
void OLT::finish()
{
//recordScalar("#sent", no_sent);
//recordScalar("received", no_rcvd);
}
In OLT.CC add at least an empty constructor and destructor:
OLT::OLT() {
}
OLT::~OLT() {
}

How do I generate a tone using SDL_audio?

I am trying to generate a simple, constant sine tone using SDL_audio. I have a small helper class that can be called to turn the tone on/off, change the frequency, and change the wave shape. I have followed some examples I could find on the web and got the following:
beeper.h
#pragma once
#include <SDL.h>
#include <SDL_audio.h>
#include <cmath>
#include "logger.h"
class Beeper {
private:
//Should there be sound right now
bool soundOn = true;
//Type of wave that should be generated
int waveType = 0;
//Tone that the wave will produce (may or may not be applicable based on wave type)
float waveTone = 440;
//Running index for sampling
float samplingIndex = 0;
//These are useful variables that cannot be changed outside of this file:
//Volume
const Sint16 amplitude = 32000;
//Sampling rate
const int samplingRate = 44100;
//Buffer size
const int bufferSize = 1024;
//Samples a sine wave at a given index
float sampleSine(float index);
//Samples a square wave at a given index
float sampleSquare(float index);
public:
//Initializes SDL audio, audio device, and audio specs
void initializeAudio();
//Function called by SDL audio_callback that fills stream with samples
void generateSamples(short* stream, int length);
//Turn sound on or off
void setSoundOn(bool soundOnOrOff);
//Set timbre of tone produced by beeper
void setWaveType(int waveTypeID);
//Set tone (in Hz) produced by beeper
void setWaveTone(int waveHz);
};
beeper.cpp
#include <beeper.h>
void fillBuffer(void* userdata, Uint8* _stream, int len) {
short * stream = reinterpret_cast<short*>(_stream);
int length = len;
Beeper* beeper = (Beeper*)userdata;
beeper->generateSamples(stream, length);
}
void Beeper::initializeAudio() {
SDL_AudioSpec desired, returned;
SDL_AudioDeviceID devID;
SDL_zero(desired);
desired.freq = samplingRate;
desired.format = AUDIO_S16SYS; //16-bit audio
desired.channels = 1;
desired.samples = bufferSize;
desired.callback = &fillBuffer;
desired.userdata = this;
devID = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(0,0), 0, &desired, &returned, SDL_AUDIO_ALLOW_FORMAT_CHANGE);
SDL_PauseAudioDevice(devID, 0);
}
void Beeper::generateSamples(short *stream, int length) {
int samplesToWrite = length / sizeof(short);
for (int i = 0; i < samplesToWrite; i++) {
if (soundOn) {
if (waveType == 0) {
stream[i] = (short)(amplitude * sampleSine(samplingIndex));
}
else if (waveType == 1) {
stream[i] = (short)(amplitude * 0.8 * sampleSquare(samplingIndex));
}
}
else {
stream[i] = 0;
}
//INFO << "Sampling index: " << samplingIndex;
samplingIndex += (waveTone * M_PI * 2) / samplingRate;
//INFO << "Stream input: " << stream[i];
if (samplingIndex >= (M_PI*2)) {
samplingIndex -= M_PI * 2;
}
}
}
void Beeper::setSoundOn(bool soundOnOrOff) {
soundOn = soundOnOrOff;
//if (soundOnOrOff) {
// samplingIndex = 0;
//}
}
void Beeper::setWaveType(int waveTypeID) {
waveType = waveTypeID;
//samplingIndex = 0;
}
void Beeper::setWaveTone(int waveHz) {
waveTone = waveHz;
//samplingIndex = 0;
}
float Beeper::sampleSine(float index) {
double result = sin((index));
//INFO << "Sine result: " << result;
return result;
}
float Beeper::sampleSquare(float index)
{
int unSquaredSin = sin((index));
if (unSquaredSin >= 0) {
return 1;
}
else {
return -1;
}
}
The callback function is being called and the generateSamples function is loading data into the stream, but I cannot hear anything but a very slight click at irregular periods. I have had a look at the data inside the stream and it follows a pattern that I would expect for a scaled sine wave with a 440 Hz frequency. Is there something obvious that I am missing? I did notice that the size of the stream is double what I put when declaring the SDL_AudioSpec and calling SDL_OpenAudioDevice. Why is that?
Answered my own question! When opening the audio device I used the flag SDL_AUDIO_ALLOW_FORMAT_CHANGE which meant that SDL was actually using a float buffer instead of the short buffer that I expected. This was causing issues in a couple of places that were hard to detect (the stream being double the amount of bytes I was expecting should have tipped me off). I changed that parameter in SDL_OpenAudioDevice() to 0 and it worked as expected!

Multiple Definitions Error of Global Arrays [duplicate]

This question already has answers here:
c++ multiple definitions of a variable
(5 answers)
multiple definition error c++
(2 answers)
What exactly is One Definition Rule in C++?
(1 answer)
Closed 2 years ago.
I am attempting to compile my c++ code, and I continue getting the error:
/tmp/ccEsZppG.o:(.bss+0x0): multiple definition of `mailboxes'
/tmp/ccEZq43v.o:(.bss+0x0): first defined here
/tmp/ccEsZppG.o:(.bss+0xc0): multiple definition of `threads'
/tmp/ccEZq43v.o:(.bss+0xc0): first defined here
/tmp/ccEsZppG.o:(.bss+0x120): multiple definition of `semaphores'
/tmp/ccEZq43v.o:(.bss+0x120): first defined here
collect2: error: ld returned 1 exit status
Here is my code:
addem.cpp
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
#include "mailbox.h"
using namespace std;
void *sumUp(void *arg);
int main(int argc, char *argv[]) {
int numThreads, minThreads, maxInt, minInt;
if (argc < 3) {
cout << "Error: Need three arguments" << endl;
return 1;
}
numThreads = atoi(argv[1]);
maxInt = atoi(argv[2]);
minThreads = 1;
minInt = 1;
if (numThreads < 1) {
cout << "Cannot work with less than one thread\n"
<< "It's okay but do better next time!\n"
<< "We'll work with 1 thread this time.\n";
numThreads = minThreads;
} else if (numThreads > MAXTHREAD) {
cout << "Sorry, the max for threads is 10.\n"
<< "We'll work with 10 threads this time.\n";
numThreads = MAXTHREAD;
}
if (maxInt < 1) {
cout << "What do you want me to do? I can't count backwards!\n"
<< "I can barely count forwards! Let's make the max number\n"
<< "be 1 to save time\n";
maxInt = minInt;
}
struct msg outgoingMail[numThreads];
int divider = maxInt / numThreads;
int count = 1;
//initialize arrays (mailboxes, semaphores)
for (int i = 0; i < numThreads; i++) {
sem_init(&semaphores[i], 0, 1);
outgoingMail[i].iSender = 0;
outgoingMail[i].type = RANGE;
outgoingMail[i].value1 = count;
count = count + divider;
if (i = numThreads - 1) {
outgoingMail[i].value2 = maxInt;
} else {
outgoingMail[i].value2 = count;
}
}
for (int message = 0; message < numThreads; message++) {
SendMsg(message+1, outgoingMail[message]);
}
int thread;
for (thread = 0; thread <= numThreads; thread++) {
pthread_create(&threads[thread], NULL, &sumUp, (void *)(intptr_t)(thread+1));
}
struct msg incomingMsg;
int total = 0;
for (thread = 0; thread < numThreads; thread++) {
RecvMsg(0, incomingMsg);
total = total + incomingMsg.value1;
}
cout << "The total for 1 to " << maxInt << " using "
<< numThreads << " threads is " << total << endl;
return 0;
}
void *sumUp(void *arg) {
int index,total;
index = (intptr_t)arg;
struct msg message;
RecvMsg(index, message);
message.iSender = index;
message.type = ALLDONE;
total = 0;
for (int i = message.value1; i <= message.value2; i++) {
total += i;
}
SendMsg(0, message);
return (void *) 0;
}
mailbox.cpp
#include <stdio.h>
#include <iostream>
#include "mailbox.h"
using namespace std;
int SendMsg(int iTo, struct msg &Msg) {
if (safeToCall(iTo)) {
cout << "Error calling SendMsg" << endl;
return 1;
}
sem_wait(&semaphores[iTo]);
mailboxes[iTo] = Msg;
sem_post(&semaphores[iTo]);
return 0;
}
int RecvMsg(int iFrom, struct msg &Msg) {
sem_wait(&semaphores[iFrom]);
if (safeToCall(iFrom)) {
cout << "Error calling RecvMsg" << endl;
return 1;
}
mailboxes[iFrom] = Msg;
sem_post(&semaphores[iFrom]);
return 0;
}
bool safeToCall(int location) {
bool safe = !(location < 0 || location > MAXTHREAD + 1);
return safe;
//return true;
}
mailbox.h
#ifndef MAILBOX_H_
#define MAILBOX_H_
#define RANGE 1
#define ALLDONE 2
#define MAXTHREAD 10
#include <semaphore.h>
#include <pthread.h>
struct msg {
int iSender; /* sender of the message (0 .. numThreads)*/
int type; /* its type */
int value1; /* first value */
int value2; /* second value */
};
struct msg mailboxes[MAXTHREAD + 1];
pthread_t threads[MAXTHREAD + 1];
sem_t semaphores[MAXTHREAD + 1];
int SendMsg(int iTo, struct msg &Msg);
int RecvMsg(int iFrom, struct msg &Msg);
bool safeToCall(int location);
#endif
I am compiling the code with the command
g++ -o addem addem.cpp mailbox.cpp -lpthread
I have tried commenting out all of the function bodies in the source code to leave them as stub functions, and the same error occurs. The only way I have been able to compile the file is if I comment out the function bodies, and remove
#include "mailbox.h"
From at least one of the files. I feel it has to do with how I am initializing the arrays? But I cannot figure out a workaround.

error in wrapping class for dll functions

I have a 3rd party .dll (and relative .h and .lib) to control a device via USB.
I want to use the dll functions into a class (AOTF_controller) to implement my desired behaviour.
What I want to do is :
Connect to the device (connect() class function);
Initialize it (init() class function);
Set some parameters (setScanningFreq() class function)
Increase sequentially the frequency of my device (increaseFreq() class function)
Reset and close the USB connection.
I can obtain this behavior when I use the dll functions directly into the _tmain() therefore the device works correctly, but when I wrap the dll functions into a class and try to use the class something goes wrong.
I repeat the above process (list item 1-5) several times: sometimes it works fine, sometimes the program stop and the debugger gives me this error:
First-chance exception at 0x77533fb7 in AOTFcontrollerDebug.exe: 0xC0150014: The activation context activation stack for the running thread of execution is corrupt.
The error seems random, sometimes I can conclude 80 times the scan without any problem, sometimes it gives me error right at the first scan.
I tried to search for that error but I was not able to find anything useful.
Anyone can help? I guess could be related on how the dll functions are called in my class?
Here is the main function code:
// AOTFcontrollerDebug.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "AOTFcontrollerDebug.h"
#include "AOTF_Controller.h"
#include <iostream>
#include <string>
#include <sstream>
#include <AotfLibrary.h>
#define DEFAULT_STARTFREQUENCY 78
#define DEFAULT_ENDFREQUENCY 95.5
#define DEFAULT_NUMOFFRAMES 256
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// The one and only application object
CWinApp theApp;
using namespace std;
int _tmain(int argc, TCHAR* argv[], TCHAR* envp[])
{
int nRetCode = 0;
HMODULE hModule = ::GetModuleHandle(NULL);
if (hModule != NULL)
{
// initialize MFC and print and error on failure
if (!AfxWinInit(hModule, NULL, ::GetCommandLine(), 0))
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: MFC initialization failed\n"));
nRetCode = 1;
}
else
{
// TODO: code your application's behavior here.
std::cout << "-----AOTF Controller Debugging-----"<<endl;
//input of scans to do
int repeatedScan;
std::cout << "Type how many repeated scan: "<<endl;
std::cin >> repeatedScan;
//instance
AOTF_Controller m_AOTF_Controller;
std::cout << "AOTF Controller instance done..."<<endl;
//loop over scans
for(int i =0;i<repeatedScan;i++)
{
m_AOTF_Controller.connect();
std::cout << "AOTF Controller connected..."<<endl;
std::cout << "Scan number : "<< (i + 1) <<endl;
m_AOTF_Controller.init();
//set the delta freq to increase at each step
m_AOTF_Controller.setScanningFreq(DEFAULT_STARTFREQUENCY, DEFAULT_ENDFREQUENCY, DEFAULT_NUMOFFRAMES);
//loop over wavelengths
int sleep_ms = 4;
for (int j =0; j <DEFAULT_NUMOFFRAMES; j++)
{
Sleep(sleep_ms) ;
m_AOTF_Controller.increaseFreq();
//std::cout << " "<< (j + 1) ;
}
// terminate scans
m_AOTF_Controller.reset();
m_AOTF_Controller.disconnect();
std::cout << endl <<"Scan number "<< (i + 1) << "terminated successfully" <<endl;
Sleep(sleep_ms*100) ;
}
}
}
else
{
// TODO: change error code to suit your needs
_tprintf(_T("Fatal Error: GetModuleHandle failed\n"));
nRetCode = 1;
}
return nRetCode;
}
and here the Aotf_Controller class code:
//Aotf_Controller.h
#pragma once
#include <AotfLibrary.h>
#include <string>
#include <sstream>
#include <iomanip>
#define CONVERSION_MHZ_TO_HZ 1000000
class AOTF_Controller
{
private:
enum Error {SUCCESSFUL , CONNECTION_ERROR, DISCONNECTION_ERROR, INIT_ERROR, RESET_ERROR , SET_ERROR }; // error enum values
HANDLE hAotfController;
int currentGain;
long currentFreq; // current frequency in Hz
long startFreq, endFreq, deltaFreq; // frequency values for the scanning in Hz
public:
AOTF_Controller(void);
~AOTF_Controller(void);
AOTF_Controller::Error connect();
AOTF_Controller::Error disconnect();
AOTF_Controller::Error init();
AOTF_Controller::Error setFreq(float freq); // for frequency value in MHZ (precision to the 3rd decimal i.e. KHz)
AOTF_Controller::Error setFreq(long freq); // for frequency value in Hz
AOTF_Controller::Error setGain(int gain);
AOTF_Controller::Error reset();
AOTF_Controller::Error setScanningFreq(float _startFreq, float _endFreq, int numOfFrames);
AOTF_Controller::Error increaseFreq();
};
//Aotf_Controller.cpp
#include "StdAfx.h"
#include "AOTF_Controller.h"
AOTF_Controller::AOTF_Controller(void)
{
currentGain = 0;
currentFreq = 0;
startFreq = 0;
endFreq = 0;
deltaFreq = 0;
hAotfController = NULL;
}
AOTF_Controller::~AOTF_Controller(void)
{
}
AOTF_Controller::Error AOTF_Controller::connect()
{
int iInstance = 0;
hAotfController = AotfOpen(iInstance);
if (!hAotfController)
{
return CONNECTION_ERROR;
}
else
{
return SUCCESSFUL;
}
}
AOTF_Controller::Error AOTF_Controller::disconnect()
{
if (!AotfClose (hAotfController))
{
return DISCONNECTION_ERROR;
}
else
{
hAotfController = NULL;
return SUCCESSFUL;
}
}
AOTF_Controller::Error AOTF_Controller::init()
{
std::string ampCom="dds a 0 16383\r"; //Command to set the amplitude parameter to the max
std::string modCom="mod dac * 16383\r";//Command to set the dac parameter to the max
int gain = 255; // set the gain to the max
if (!AotfWrite(hAotfController, ampCom.length(), (char *)ampCom.c_str()))
{
return Error::INIT_ERROR;
}
if (!AotfWrite(hAotfController, modCom.length(), (char *)modCom.c_str()))
{
return INIT_ERROR;
}
setGain(gain);
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::reset()
{
std::string resetCom = "dds reset\r";
if(!AotfWrite(hAotfController, resetCom.length() , (char *)resetCom.c_str()))
{
return RESET_ERROR;
}
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::setFreq(float freq)
{
long freqHz = (long)freq*CONVERSION_MHZ_TO_HZ;
setFreq(freqHz);
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::setFreq(long freq)
{
std::ostringstream oss; //stream to build the string
//building the string for the Frequency
oss << "dds f 0 !" << std::fixed << std::setprecision(0) << freq << "\r";
std::string freqCom = oss.str();
//send command to the AOTF
if(!AotfWrite(hAotfController, freqCom.length(), (char *) freqCom.c_str())) // set the frequency (80-120)
{
return SET_ERROR;
}
currentFreq = freq; // update monitoring variable in HZ
return Error::SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::setGain(int gain)
{
std::ostringstream oss; //stream to build the string
//building the string for the Gain
oss << "dds gain -p* * " << gain << "\r";
std::string gainCom = oss.str();
//send command to the AOTF
if(!AotfWrite(hAotfController, gainCom.length(), (char * )gainCom.c_str())) // set the gain (0-255)
{
return SET_ERROR;
}
currentGain = gain;
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::setScanningFreq(float _startFreq, float _endFreq, int numOfFrames)
{
float FreqRange = (_endFreq - _startFreq); //calculate range
//calculate DeltaFrequency (frequency increase after each captured frame)
deltaFreq = (long) ((FreqRange/(float)(numOfFrames-1))*(float)CONVERSION_MHZ_TO_HZ); //conversion from MHz to Hz
startFreq = (long) (_startFreq*CONVERSION_MHZ_TO_HZ);
endFreq = (long) (_endFreq*CONVERSION_MHZ_TO_HZ);
setFreq(_startFreq);
return SUCCESSFUL;
}
AOTF_Controller::Error AOTF_Controller::increaseFreq()
{
if (deltaFreq ==0)
{
return SET_ERROR;
}
long newFreq = currentFreq + deltaFreq;
std::ostringstream oss;
oss << "dds f 0 !" << std::fixed << std::setprecision(0) << newFreq << "\r";
std::string freqCom = oss.str();
//send command to the AOTF
if(!AotfWrite(hAotfController, freqCom.length(), (char *)freqCom.c_str())) // set the frequency (80-120)value
{
return SET_ERROR;
}
currentFreq = newFreq;
return SUCCESSFUL;
}

Unexpected Program Stoppage on Arduino

I have an issue where my Arduino program hangs for no reason. I run my program, and at some undetermined point, the Serial Monitor stops printing output. Here's what I've tested so far:
In my "com.init_drone()" method, I've commented everything out except for the last line, which signals that the method returned. When I do this, my program hangs somewhere else but still it doesn't get to the infinite while loop.
I've been outputting memory usage, and I'm getting numbers no lower than 450 -- this tells me that I'm not using an absurd amount of memory.
I've tried removing the Timer1 instantiation, interrupt attach/detach, bu that has had no effect on the program.
My .ino file(and Command) is located here for anyone that wants a fuller picture and doesn't want to scroll through all this code I'm going to post below.
Here's my log output so far. Notice the truncation!:
AT&F
AT+NMAC=00:1d:c9:10:39:6f
AT+WM=0
AT+NDHCP=1
AT+WA=ardrone_279440
AT+NCUDP=192.168.1.1,5556
S0AT*CONFIG=1,"general:navdata_demo","TRUE"
EAT*CONFIG=1,"general:navdata_demo","TRUE"
638
S0AT*CONFIG=2,"control:altitude_max","2000"
EAT*CONFIG=2,"control:altitude_max","2000"
638
S0AT*CONFIG=3,"control:euler_angle_max","0.35"
EAT*CONFIG=3,"control:euler_angle_max","0.35"
586
S0AT*CONFIG=4,"control:outdoor","FALSE"
EAT*CONFIG=4,"control:outdoor","FALSE"
635
S0AT*CONFIG=5,"control:flight_without_shell","FALSE"
EAT*CONFIG=5,"control:flight_without_shell","FALSE"
574
S0AT*CTRL=6,4,0
EAT*CTRL=6,4,0
629
S0AT*CTRL=7,0,0
EAT*CTRL=7,0,0
629
S0AT*CTRL=8,4,0
EAT*CTRL=8,4,0
629
S0AT*COMWDG=9
EAT*COMWDG=9
629
S0AT*COMWDG=10
EAT*COMWDG=10
629
S0AT*COMWDG=11
EAT*COMWDG=11
629
S0AT*COMWDG=12
EAT*COMWDG=12
629
S0AT*COMWDG=13
EAT*COMWDG=13
629
S0AT*FTRIM=14
EAT*FTRIM=14
629
Here is my .ino file:
#include "Command.h"
#include "Streaming.h"
int debug = 1;
extern ring_buffer rx_buf;
extern resultint_ resultint;
Command com;
int sequenceNumber = 1;
String atcmd = "";
#include "TimerOne.h"
#define LEDpin 13
void setup()
{
PCsrl.begin(9600);
com.start_wifi_connection();
com.drone_is_init = com.init_drone();
Timer1.initialize(COMWDG_INTERVAL_USEC);
Timer1.attachInterrupt(watchdog_timer);
}
void watchdog_timer() {
com.sendwifi(com.makeComwdg());
}
void loop()
{
if (com.drone_is_init == 0) {
if (debug) {
// never use three ! together in arduino code
PCsrl.println("Drone wasn't initlized before loop() was called. Initalizing now.\r\n");
}
} else {
com.drone_takeoff();
com.drone_takeoff();
com.sendwifi(com.makePcmd(1,0,0,0,0));
com.sendwifi(com.makePcmd(1,0,0,0,0));
delay(5000);
com.moveForward(1);
com.moveRotate(180);
com.moveForward(1);
com.moveRotate(180);
delay(500);
com.drone_landing();
com.drone_landing();
delay(500);
//end of program
Timer1.detachInterrupt();
PCsrl.println("Program finished");
while (1){};
}
}
And my Command.cpp
#ifndef GAINSPAN
#define GAINSPAN
#include "Command.h"
extern int sequenceNumber;
extern int debug;
ring_buffer rx_buf= {{0}, 0, 0};
resultint_ resultint;
Command::Command()
{
at = "";
command = "";
s2ip_running = 0;
drone_is_init = 0;
drone_is_hover = 0;
emergency = 0;
}
void Command::sendwifi(String s) {
WIFIsrl.write(27); //esc
WIFIsrl.print("S0"); //choose connection CID 0
WIFIsrl.print(s);
WIFIsrl.write(27);
WIFIsrl.print("E");
if(debug) PCsrl.println(s);
WIFIsrl.println(memoryTest());
}
int Command::start_wifi_connection()
{
WIFIsrl.begin(9600);
WIFIsrl.println("");
WIFIsrl.println("AT&F");
//WIFIsrl.println("ATE0"); //turn off echo
WIFIsrl.print("AT+NMAC=00:1d:c9:10:39:6f\r"); //set MAC address
WIFIsrl.println("AT+WM=0");
WIFIsrl.println("AT+NDHCP=1");
/* drone's network profile, change if needed*/
WIFIsrl.println("AT+WA=ardrone_279440");
WIFIsrl.println("AT+NCUDP=192.168.1.1,5556");
readARsrl();
delay(3000); //need 3 seconds for connection to establish
return 0;
}
String Command::makeComwdg()
{
at = "AT*COMWDG=";
command = at + getSequenceNumber() + "\r\n";
return command;
}
void Command::sendComwdg_t(int msec)
{
for (int i = 0; i < msec; i+=20) {
sendwifi(makeComwdg());
delay(20);
}
}
void Command::sendFtrim()
{
at = "AT*FTRIM=";
command = at + getSequenceNumber() + "\r\n";
sendwifi(command);
}
void Command::sendConfig(String option, String value)
{
at = "AT*CONFIG=";
command = at + getSequenceNumber() + ",\"" + option + "\",\"" + value + "\"\r\n";
sendwifi(command);
}
void Command::sendRef(flying_status fs)
{
at = "AT*REF=";
if(fs == TAKEOFF){
command = at + getSequenceNumber() + ",290718208\r\n"; //takeoff
}
else if(fs == LANDING){
command = at + getSequenceNumber() + ",290717696\r\n"; //landing
} else if (fs == EMERGENCY_TOGGLE){
command = at + getSequenceNumber() + ",290717952\r\n"; //landing
}
// emergency -> 290717952
sendwifi(command);
}
void Command::send_control_commands(){
at = "AT*CTRL=";
sendwifi(at+getSequenceNumber()+",4,0\r\n");
sendwifi(at+getSequenceNumber()+",0,0\r\n");
sendwifi(at+getSequenceNumber()+",4,0\r\n");
}
void Command::drone_emergency_reset()
{
at = "AT*REF=";
command = at + getSequenceNumber() + ",290717952\r\n";
sendwifi(command);
}
/** Movement functions **/
int Command::moveForward(float distanceInMeters)
{
float i = 0;
String moveForward = makePcmd(1, 0, -.855, 0, 0);
delay(1000*distanceInMeters);
sendPcmd(moveForward);
return 1;
}
int Command::moveRotate(float yawInDegrees)
{
int i = 0;
while (i < yawInDegrees) {
String stayRotate = makePcmd(1, 0, 0, 0, 0.17);
sendPcmd(stayRotate);
delay(150);
i += 8;
}
return 1;
}
String Command::makePcmd(int enable, float roll, float pitch, float gaz, float yaw)
{
at = "AT*PCMD=";
command = at + getSequenceNumber() + "," + enable + "," + fl2int(roll) + "," + fl2int(pitch) + "," + fl2int(gaz) + "," + fl2int(yaw) + "\r";
return command;
}
void Command::sendPcmd(String command)
{
previousCommand = command;
sendwifi(command);
}
void Command::sendPcmd(int enable, float roll, float pitch, float gaz, float yaw)
{
at = "AT*PCMD=";
command = at + getSequenceNumber() + "," + enable + "," + fl2int(roll) + "," + fl2int(pitch) + "," + fl2int(gaz) + "," + fl2int(yaw) + "\r";
sendwifi(command);
}
String Command::makeAnim(anim_mayday_t anim, int time)
{
at = "AT*ANIM=";
command = at + getSequenceNumber() + "," + anim + "," + time + "\r\n";
return command;
}
void Command::doLEDAnim(int animseq, int duration)
{
PCsrl << "calling LEDAnim" << endl;
at = "AT*LED=";
command = at + getSequenceNumber() + "," + animseq + ",1073741824," + duration + "\r\n";
sendwifi(command);
}
int Command::start_s2ip()
{
char temp;
//delay(20000); //wait for drone to start
readARsrl();
if (debug) {
PCsrl << "trying to start s2ip" << endl;
}
ARsrl.print("\r\n");
delay(500);
ARsrl.print("\r\n");
delay(500);
ARsrl << "cd ~" << endl;
if (debug) {
readARsrl();
}
delay(500);
ARsrl << "cd data/video/apps/" << endl;
delay(500);
ARsrl << "./s2ip.arm" << endl;
while ((int) temp != 2) {
temp = ARsrl.read();
if (temp == 2) {
PCsrl << "s2ip is running" << endl;
ARsrl << "bullshit\r\n"; //to fix a delay bug
break;
}
//PCsrl << "s2ip not running" << endl;
}
if (debug) {
while (ARsrl.available()) {
PCsrl.write(ARsrl.read());
}
}
return 1;
}
void Command::quit_s2ip()
{
ARsrl.println("EXIT");
while (ARsrl.available()) {
PCsrl.write(ARsrl.read());
}
}
int Command::init_drone()
{
sendConfig("general:navdata_demo","TRUE");
sendConfig("control:altitude_max","2000");
sendConfig("control:euler_angle_max","0.35");
sendConfig("control:outdoor","FALSE");
sendConfig("control:flight_without_shell","FALSE");
send_control_commands();
sendComwdg_t(90);
sendFtrim();
drone_emergency_reset(); //clear emergency flag
return 1;
}
int Command::drone_takeoff()
{
sendRef(TAKEOFF);
int i = 0;
return 1;
}
int Command::drone_hover(int msec)
{
int i = 0;
while (i < msec) {
sendwifi(makePcmd(1, 0, 0, 0, 0));
delay(100);
i += 100;
}
return 1;
}
int Command::drone_landing()
{
sendRef(LANDING);
return 1;
}
int Command::drone_move_up(int centimeter)
{
int i = 0;
while (i < centimeter) {
ARsrl << makePcmd(1, 0, 0, 0.6, 0);
delay(100);
i += 10;
}
return 1;
}
int Command::drone_move_down(int centimeter)
{
int i = 0;
while (i < centimeter) {
sendwifi(makePcmd(1, 0, 0, -0.5, 0));
delay(100);
i += 10;
}
return 1;
}
long Command::fl2int(float value)
{
resultint.i = 0;
if (value < -1 || value > 1) {
resultint.f = 1;
} else {
resultint.f=value;
}
return resultint.i;
}
void Command::readARsrl()
{
while (ARsrl.available()) {
if (debug) {
PCsrl.write(ARsrl.read());
}
}
}
//Memory test code from : http://www.faludi.com/2007/04/18/arduino-available-memory-test/
int Command::memoryTest() {
int byteCounter = 0; // initialize a counter
byte *byteArray; // create a pointer to a byte array
// More on pointers here: http://en.wikipedia.org/wiki/Pointer#C_pointers
// use the malloc function to repeatedly attempt
// allocating a certain number of bytes to memory
// More on malloc here: http://en.wikipedia.org/wiki/Malloc
while ( (byteArray = (byte*) malloc (byteCounter * sizeof(byte))) != NULL ) {
byteCounter++; // if allocation was successful, then up the count for the next try
free(byteArray); // free memory after allocating it
}
free(byteArray); // also free memory after the function finishes
return byteCounter; // send back the highest number of bytes successfully allocated
}
int Command::getSequenceNumber(){
return sequenceNumber++;
}
// Volatile, since it is modified in an ISR.
volatile boolean inService = false;
void SrlRead()
{
if (inService) {
PCsrl.println("timer kicked too fast");
return;
}
interrupts();
inService = true;
while(ARsrl.available()) {
unsigned char k = ARsrl.read();
store_char(k, &rx_buf);
}
inService = false;
}
void read_rx_buf()
{
while (rx_buf.tail != rx_buf.head) {
if (debug) {
PCsrl.write(rx_buf.buffer[rx_buf.tail]);
}
rx_buf.tail = (unsigned int) (rx_buf.tail+ 1) % SERIAL_BUFFER_SIZE;
}
}
inline void store_char(unsigned char c, ring_buffer *buffer)
{
int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE;
// if we should be storing the received character into the location
// just before the tail (meaning that the head would advance to the
// current location of the tail), we're about to overflow the buffer
// and so we don't write the character or advance the head.
if (i != buffer->tail) {
buffer->buffer[buffer->head] = c;
buffer->head = i;
}
else {
Serial.println("ring buffer is too small");
}
}
#endif
I know it sounds weird but, sometimes this happens when arduino is not getting enough power supply. Try connecting the arduino to a power source different from USB.
As soon as I started to put things in prog memory my program started to clear up it's hiccups. It seems it was a memory issue.
I had the same problem, but the issue was with Timer1.initialize(). Try this:
com.drone_is_init = com.init_drone();
Serial.println("One");
Serial.println("Two");
Serial.println("Three");
Timer1.initialize(COMWDG_INTERVAL_USEC);
Timer1.attachInterrupt(watchdog_timer);
Open serial monitor and see... it will show until "Two", and then Arduino will hang.
The issue was I calling some functions of the LiquidCrystal_I2C library, that need interrupt routines. Check if your timer ISR is using some interrupts. If so, you should move this code to another place in your project.