Arduino Automatic Light Switch 2 - automation

I'm currently working on an automatic light switch. Here's my code:
#include <Servo.h>
boolean time = false;
const int timeLim = 10000;
const int delLen = 5000;
int pirVal = 0;
const int pirPin = 2;
const int sensePin = 5;
boolean timeRet = false;
int lightVal;
Servo myServo;
unsigned long limit;
void setup() {
Serial.begin(9600);
pinMode(pirPin, INPUT);
myServo.attach(11);
myServo.write(40);
}
void loop() {
unsigned long Timer = millis();
pirVal = digitalRead(pirPin);
int lightVal = analogRead(sensePin);
Serial.print(pirVal);
Serial.print(' ');
Serial.print(lightVal);
Serial.print(' ');
Serial.print(Timer);
Serial.print(' ');
Serial.print(time);
Serial.print(' ');
Serial.print(limit);
Serial.print(' ');
Serial.println(timeRet);
if ( lightVal < 400 ) {
time = false;
limit = 0;
timeRet = false;
} if ( lightVal < 400 && pirVal == 1 ) {
unsigned long time = false;
pirVal = 0;
myServo.write(160);
} if ( lightVal > 400 && pirVal == 0 && timeRet == false){
limit = getTimeLim( timeLim, Timer );
pirVal = 0;
timeRet = true;
} if ( lightVal > 400 && pirVal == 0 && timeRet == true ) {
time = timeStat ( limit, Timer );
} if ( lightVal > 400 && time == true ) {
myServo.write(40);
}
}
int getTimeLim( const int timeLim, unsigned long Timer ) {
unsigned long limit = Timer + timeLim;
return limit;
}
boolean timeStat( unsigned long limit, unsigned long Timer ) {
if ( Timer < limit ) {
time = false;
} else if ( Timer > limit ) {
time = true;
}
return time;
}
The problem is that when you look at the serial the first time the getTimeLim function it works, but the second time is always some outrageous number (e.g. 4294937965). I don't know why it would give me this huge number. Help would be much appreciated.

since your code works now and you want to optimize it, i would suggest this:
// ( pseudo code since i'm not familiar with arduino )
void loop( ){
if( ( analogRead( sensePin ) < 400 )
&& ( digitalRead( pirPin ) ) ){
myServo.write( 160 ); // turn on light
int time_end = millis( ) + 60,000; // initiate timer value
while( millis( ) < time_end ); // poll time until at 60s
myServo.write( 40 ); // turn off light
}
}

Related

MQL5 Invalid array access error when trying to access first element of an array

I have a condition which checks if the latest fast moving average value is above or below the slow moving average and if the bid price is above or below the fast ma.
But I am getting this compile error:
The iMA function is returning data.
Here is my code:
int fast_ma_handle;
int slow_ma_handle;
int OnInit()
{
fast_ma_handle = iMA(_Symbol,_Period,8,0,MODE_EMA,PRICE_CLOSE);
slow_ma_handle = iMA(_Symbol,_Period,21,0,MODE_EMA,PRICE_CLOSE);
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason)
{
}
void OnTick()
{
double fast_ma_array[], slow_ma_array[];
int copied1 = CopyBuffer(fast_ma_handle,0,0,1,fast_ma_array);
int copied2 = CopyBuffer(slow_ma_handle,0,0,1,slow_ma_array);
double bid_price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
int trend_direction = 0;
if(fast_ma_array[0] > slow_ma_array[0] && bid_price > fast_ma_array)
trend_direction = 1;
else if(fast_ma_array[0] < slow_ma_array[0] && bid_price < fast_ma_array)
trend_direction = -1;
}
Thanks
You have a couple of mistakes in your code. I've corrected it for you.
int fast_ma_handle;
int slow_ma_handle;
int OnInit()
{
fast_ma_handle = iMA(_Symbol,_Period,8,0,MODE_EMA,PRICE_CLOSE);
slow_ma_handle = iMA(_Symbol,_Period,21,0,MODE_EMA,PRICE_CLOSE);
return(INIT_SUCCEEDED);
}
void OnTick()
{
double fast_ma_array[], slow_ma_array[];
ArraySetAsSeries(fast_ma_array, true);
ArraySetAsSeries(slow_ma_array, true);
int copied1 = CopyBuffer(fast_ma_handle,0,0,100,fast_ma_array);
int copied2 = CopyBuffer(slow_ma_handle,0,0,100,slow_ma_array);
double bid_price = SymbolInfoDouble(_Symbol,SYMBOL_BID);
int trend_direction = 0;
if(fast_ma_array[0] > slow_ma_array[0] && bid_price > fast_ma_array[0])
trend_direction = 1;
else if(fast_ma_array[0] < slow_ma_array[0] && bid_price < fast_ma_array[0])
trend_direction = -1;
}

Why a MQL4 bot does not detect a 5-EMA & 20-EMA cross-over in a StrategyTester run?

I am a newbie in coding bot for MetaTrader Terminal 4 platform, but I have a decent experience in coding JavaScript for the web.
I just build a simple MQL4 bot, using EMA(5) and EMA(20) to place an order, but when I try to test it via a StrategyTester run, it keeps showing both condition not met, please what am I doing wrong?
Below is my code ( https://codeshare.io/5NzvYl )
input int fastEma_Period = 5;
input int fastEma_ma_Shift = 0;
input int fastEma_ma_Method = 1; // EXPONENTIAL
input int fastEma_applied_Price = 0; // CLOSED PRICE
input int fastEma_shift_CandleIndex = 0; // CURRENT FORMING CANDLESTICK
input int slowEma_Period = 20;
input int slowEma_ma_Shift = 0;
input int slowEma_ma_Method = 1; // EXPONENTIAL
input int slowEma_applied_Price = 0; // CLOSED PRICE
input int slowEma_shift_CandleIndex = 0; // CURRENT FORMING CANDLESTICK
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double fastEmaBar0 = iMA(NULL,0,fastEma_Period,fastEma_ma_Shift,fastEma_ma_Method,fastEma_applied_Price,fastEma_shift_CandleIndex);
double slowEmaBar0 = iMA(NULL,0,slowEma_Period,slowEma_ma_Shift,slowEma_ma_Method,slowEma_applied_Price,slowEma_shift_CandleIndex);
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
double fastEmaBar1 = iMA(NULL,0,fastEma_Period,fastEma_ma_Shift,fastEma_ma_Method,fastEma_applied_Price,fastEma_shift_CandleIndex + 1);
double slowEmaBar1 = iMA(NULL,0,slowEma_Period,slowEma_ma_Shift,slowEma_ma_Method,slowEma_applied_Price,slowEma_shift_CandleIndex + 1);
double lotSize = AccountBalance() / 10000;
int maBt;
int maSt;
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
enterMarket();
// ExpertRemove();
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
string maCrossOverSignal(double fastEmaBar1, double slowEmaBar1, double fastEmaBar0, double slowEmaBar0)
{
string signal;
if((fastEmaBar1 <= slowEmaBar1) && (fastEmaBar0 > slowEmaBar0))
{
signal = "Buy";
}
else
if((fastEmaBar1 >= slowEmaBar1) && (fastEmaBar0 < slowEmaBar0))
{
signal = "Sell";
}
return signal;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void enterMarket()
{
if(/*OrdersTotal() == 0 &&*/ maCrossOverSignal(fastEmaBar1,slowEmaBar1,fastEmaBar0,slowEmaBar0)== "Buy")
{
//continue inside this condition, bcos its not getting met
Print("time to Buy ");
maBt = OrderSend(NULL,OP_BUY,lotSize,Ask,100,0,0,"maBt");
if(maBt > 0)
{
if(OrderSelect(maBt,SELECT_BY_TICKET))
{
modify(maBt,OrderOpenPrice(),OrderOpenPrice() - 50 * Point,OrderOpenPrice() + 200 * Point,0);
}
}
}
else
if(/*OrdersTotal() == 0 && */maCrossOverSignal(fastEmaBar1,slowEmaBar1,fastEmaBar0,slowEmaBar0)== "Sell")
{
Print("time to Sell ");
maSt = OrderSend(NULL,OP_SELL,lotSize,Bid,100,0,0,"maSt");
if(maSt > 0)
{
if(OrderSelect(maSt,SELECT_BY_TICKET))
{
modify(maSt,OrderOpenPrice(),OrderOpenPrice() + 50 * Point,OrderOpenPrice() - 200 * Point,0);
}
}
}
else
{
Print("both condition not met");
}
}
Q : "... what am I doing wrong?"
Almost there.
You've missed a tiny, yet cardinal detail. The both assignments of iMA()-values are fine, but in a wrong place.
You need to let re-calculate & re-assign iMA()-values after each QUOTE-message arrival ( per each tick, coming from your FX-Market access mediator ( emulated in StrategyTester runs from past-data, sure ) ).
void OnTick() { /*\/\/\/\/\/\/\/\/\ QUOTE-has arrived, i.e.
new prices are known here:
//------------------------------------------- UPDATE each control-DATA now */
fastEmaBar0 = iMA( NULL, 0, fastEma_Period,
fastEma_ma_Shift,
fastEma_ma_Method,
fastEma_applied_Price,
fastEma_shift_CandleIndex
);
slowEmaBar0 = iMA( NULL, 0, slowEma_Period,
slowEma_ma_Shift,
slowEma_ma_Method,
slowEma_applied_Price,
slowEma_shift_CandleIndex
);
fastEmaBar1 = iMA( NULL, 0, fastEma_Period,
fastEma_ma_Shift,
fastEma_ma_Method,
fastEma_applied_Price,
fastEma_shift_CandleIndex + 1
);
slowEmaBar1 = iMA( NULL, 0, slowEma_Period,
slowEma_ma_Shift,
slowEma_ma_Method,
slowEma_applied_Price,
slowEma_shift_CandleIndex + 1
);
//------------------------------------------- UPDATE
//------------------------------------------- DONE, may start making decisions
enterMarket();
// ExpertRemove();
}

Uncaught TypeError: Cannot read property 'substring' of undefined - Processing.js

I keep getting this error, and I have no clue what is wrong. I checked all variables, but all of them are defined at least somewhere
int creatures = 5;
int deathChance = 5;
int repChance = 10;
int timer = 0;
int rand = 0;
int CurrentCreatures = 0;
int b = 0;
void draw(); {
if(timer < 100)
{
b = 0;
CurrentCreatures = creatures;
while(b < CurrentCreatures)
{
rand = random(0,100);
if(rand <= repChance)
{
creatures += 1;
}
rand = random(0,100);
if(rand <= deathChance)
{
creatures -= 1;
}
b += 1;
}
println(creatures);
timer += 1;
}
}
what the program should be doing is printing the value of creatures over 100 generations (yes this is my attempt at some "life" simulator.
I think the problem lies here: void Draw(); { the ; is an end of instruction character
So it is trying to execute a function called draw, the it tries to do everything inside the {'s
possibly something like:
function draw() {
if(timer < 100) {
b = 0;
CurrentCreatures = creatures;
while(b < CurrentCreatures) {
rand = random(0,100);
if(rand <= repChance) {
creatures += 1;
}
rand = random(0,100);
if(rand <= deathChance) {
creatures -= 1;
}
b += 1;
}
println(creatures);
timer +=1;
}
}

Can't stop while loop which has scanf inside

#include <stdio.h>
int main() {
int test,i = 0,a = NULL;
int max2 = 0;
int n;
int max = -1000000, min = 1000000;
while (scanf("%d", &n) == 1 && max2 < 50)
{
if(n < min) { min = n; }
if(n > max) { max = n; }
max2++;
}
printf("%d",min+max);
return 0;
}
Input should be like this "1 5 8 9 10", I don't know how many numbers would be entered so I have to use the while loop.
Try using do while to put the scanf inside the loop.
#include <stdio.h>
int main() {
int test,i = 0,a = NULL;
int max2 = 0;
int n;
int max = -1000000, min = 1000000;
do{
scanf("%d", &n);
if(n < min) { min = n; }
if(n > max) { max = n; }
max2++;
}while ( n == 1 && max2 < 50)
printf("%d",min+max);
return 0;
}

Intel Skeletal Hand Tracking Library with Kinect

I've found this -> http://software.intel.com/en-us/articles/the-intel-skeletal-hand-tracking-library-experimental-release
I think is a good one...the problem is that i don't want to buy the "Creative Interactive Gesture Camera"...instead i want to use my Kinect.
It's not so easy and i need your help. I started with the Init()
this one is the original function :
inline bool Tracker::Init()
{
if(PXCSession_Create(session.ReleaseRef()) < PXC_STATUS_NO_ERROR || !session.IsValid()) return false;
for(int i=0; ; ++i) // For valid capture contexts
{
PXCSession::ImplDesc desc, filter = { PXCSession::IMPL_GROUP_SENSOR, PXCSession::IMPL_SUBGROUP_VIDEO_CAPTURE };
if(session->QueryImpl(&filter, i, &desc) < PXC_STATUS_NO_ERROR) break;
if(session->CreateImpl(&desc, PXCCapture::CUID, (void**)capture.ReleaseRef()) < PXC_STATUS_NO_ERROR || !capture.IsValid()) continue;
for(int j=0; ; ++j) // For valid devices
{
PXCCapture::DeviceInfo dinfo;
if(capture->QueryDevice(j, &dinfo) < PXC_STATUS_NO_ERROR) break;
if(capture->CreateDevice(j, device.ReleaseRef()) < PXC_STATUS_NO_ERROR || !device.IsValid()) continue;
for(int k=0; ; ++k) // For valid video streams
{
PXCCapture::Device::StreamInfo sinfo;
if(device->QueryStream(k, &sinfo) < PXC_STATUS_NO_ERROR) break;
if(sinfo.cuid != PXCCapture::VideoStream::CUID || device->CreateStream(k, PXCCapture::VideoStream::CUID, (void**)stream.ReleaseRef()) < PXC_STATUS_NO_ERROR || !device.IsValid()) continue;
for (int m=0; ; ++m) // For depth buffer profiles of at least 60 FPS
{
PXCCapture::VideoStream::ProfileInfo pinfo;
if(stream->QueryProfile(m, &pinfo) < PXC_STATUS_NO_ERROR) break;
if(pinfo.imageInfo.format != PXCImage::IMAGE_TYPE_DEPTH || pinfo.frameRateMin.numerator / pinfo.frameRateMin.denominator < 60 || stream->SetProfile(&pinfo) < PXC_STATUS_NO_ERROR) continue;
// If we can read at least one frame
stream->ReadStreamAsync(image.ReleaseRef(), sp.ReleaseRef());
if(sp && sp->Synchronize() >= PXC_STATUS_NO_ERROR)
{
// Obtain useful properties and reserve room for local copies of depth and color images
dimx = pinfo.imageInfo.width; dimy = pinfo.imageInfo.height;
PXCPointF32 flen; device->QueryPropertyAsPoint(PXCCapture::Device::PROPERTY_DEPTH_FOCAL_LENGTH, &flen);
fovx = atan(dimx / (flen.x*2))*2; fovy = atan(dimy / (flen.y*2))*2;
color = new unsigned char[dimx*dimy*3];
depth = new unsigned short[dimx*dimy];
// Initialize tracking library
tracker = hsklCreateTracker(HSKL_COORDS_X_RIGHT_Y_DOWN_Z_FWD, HSKL_API_VERSION);
hsklSetSensorProperties(tracker, HSKL_SENSOR_CREATIVE, dimx, dimy, fovx, fovy);
return true;
}
}
stream.ReleaseRef();
}
device.ReleaseRef();
}
capture.ReleaseRef();
}
return false;
}
}
this one is mine :
inline bool Tracker::Init()
{
if(PXCSession_Create(session.ReleaseRef()) < PXC_STATUS_NO_ERROR || !session.IsValid()) return false;
for(int i=0; ; ++i) // For valid capture contexts
{
PXCSession::ImplDesc desc, filter = { PXCSession::IMPL_GROUP_SENSOR, PXCSession::IMPL_SUBGROUP_VIDEO_CAPTURE };
if(session->QueryImpl(&filter, i, &desc) < PXC_STATUS_NO_ERROR) break;
if(session->CreateImpl(&desc, PXCCapture::CUID, (void**)capture.ReleaseRef()) < PXC_STATUS_NO_ERROR || !capture.IsValid()) continue;
for(int j=0; ; ++j) // For valid devices
{
PXCCapture::DeviceInfo dinfo;
if(capture->QueryDevice(j, &dinfo) < PXC_STATUS_NO_ERROR) break;
if(capture->CreateDevice(j, device.ReleaseRef()) < PXC_STATUS_NO_ERROR || !device.IsValid()) continue;
for(int k=0; ; ++k) // For valid video streams
{
PXCCapture::Device::StreamInfo sinfo;
if(device->QueryStream(k, &sinfo) < PXC_STATUS_NO_ERROR) break;
if(sinfo.cuid != PXCCapture::VideoStream::CUID || device->CreateStream(k, PXCCapture::VideoStream::CUID, (void**)stream.ReleaseRef()) < PXC_STATUS_NO_ERROR || !device.IsValid()) continue;
for (int m=0; ; ++m) // For depth buffer profiles of at least 60 FPS
{
PXCCapture::VideoStream::ProfileInfo pinfo;
//if(stream->QueryProfile(m, &pinfo) < PXC_STATUS_NO_ERROR) break;
//if(pinfo.imageInfo.format != PXCImage::IMAGE_TYPE_DEPTH || pinfo.frameRateMin.numerator / pinfo.frameRateMin.denominator < 60 || stream->SetProfile(&pinfo) < PXC_STATUS_NO_ERROR) continue;
//Sleep(1000);
dimx=(int)K.m_colorWidth;
dimy=(int)K.m_colorHeight;
fovx=0.99;
fovy=0.75;
// If we can read at least one frame
stream->ReadStreamAsync(image.ReleaseRef(), sp.ReleaseRef());
if((sp && sp->Synchronize() >= PXC_STATUS_NO_ERROR)||true)
{
// Obtain useful properties and reserve room for local copies of depth and color images
//dimx = pinfo.imageInfo.width; dimy = pinfo.imageInfo.height;
//PXCPointF32 flen; device->QueryPropertyAsPoint(PXCCapture::Device::PROPERTY_DEPTH_FOCAL_LENGTH, &flen);
//fovx = atan(dimx / (flen.x*2))*2; fovy = atan(dimy / (flen.y*2))*2;
color = new unsigned char[dimx*dimy*3];
depth = new unsigned short[dimx*dimy];
// Initialize tracking library
tracker = hsklCreateTracker(HSKL_COORDS_X_RIGHT_Y_DOWN_Z_FWD, HSKL_API_VERSION);
hsklSetSensorProperties(tracker, HSKL_SENSOR_IDEAL, dimx, dimy, fovx, fovy);
return true;
}
}
stream.ReleaseRef();
}
device.ReleaseRef();
}
capture.ReleaseRef();
}
return false;
}
}
And this is the original update class :
inline void Tracker::Update()
{
if(sp && sp->Synchronize() >= PXC_STATUS_NO_ERROR)
{
PXCImage::ImageData depthData; image->AcquireAccess(PXCImage::ACCESS_READ, &depthData);
memcpy_s(depth, sizeof(unsigned short)*dimx*dimy, depthData.planes[0], sizeof(unsigned short)*dimx*dimy);
const unsigned short * conf = reinterpret_cast<const unsigned short *>(depthData.planes[1]);
for(int i=0; i<dimx*dimy; ++i) color[3*i+2] = color[3*i+1] = color[3*i] = conf[i]>>2; // Can we just use IR here?
hsklTrackOneFrame(tracker, depth, conf); // Pass data to tracking library
image->ReleaseAccess(&depthData);
}
stream->ReadStreamAsync(image.ReleaseRef(), sp.ReleaseRef());
}
and mine :
inline void Tracker::Update()
{
if((sp && sp->Synchronize() >= PXC_STATUS_NO_ERROR)||true)
{
Mat matd(dimy,dimx,CV_16UC1);
Mat matir(dimy,dimx,CV_16UC1);
K.getDepth(&matd);
matir = K.getIR();
double min,max;
cv::minMaxLoc(matir,&min,&max);
Mat exit(dimy,dimx,CV_8UC1);
matir.convertTo(exit,CV_8U,pow(2.0,8.0)/max);
memcpy_s(depth,sizeof(unsigned short)*dimx*dimy,(unsigned short*)(matd.ptr()),sizeof(unsigned short)*dimx*dimy);
const unsigned short * conf = reinterpret_cast<const unsigned short *>(matir.ptr());
//PXCImage::ImageData depthData; image->AcquireAccess(PXCImage::ACCESS_READ, &depthData);
//memcpy_s(depth, sizeof(unsigned short)*dimx*dimy, depthData.planes[0], sizeof(unsigned short)*dimx*dimy);
//const unsigned short * conf = reinterpret_cast<const unsigned short *>(depthData.planes[1]);
// Can we just use IR here?
for(int i=0; i<dimx*dimy; ++i) {
color[3*i+2] = color[3*i+1] = color[3*i] = (exit.at<unsigned char>(i)) ;
}
hsklTrackOneFrame(tracker, depth, conf); // Pass data to tracking library
//image->ReleaseAccess(&depthData);
}
stream->ReadStreamAsync(image.ReleaseRef(), sp.ReleaseRef());
}
If i try to run the program there are no errors...but it doesn't track my hand...So any suggestions ?? or is there somebody who is interested and want to share the project with me ?
thanks