Example #1
0
//RAIN FUNCTION
uint8_t animation::rain(cube &c){
    uint16_t count = 0;
    uint8_t rX = 0;
    uint8_t rY = 0;
    uint8_t rZ = 0;
    
    slow++;
    if(slow < 200){
        return 0;
    }
    slow = 0;
    
    randomSeed(analogRead(0));
    
    //shift the rain down
    for(int x = 0; x < Xd; x++){
        for(int y = 0; y < Yd; y++){
            for(int z = 0; z < Zd-1; z++){
                if(z == 0 && c.getVoxel(x, y, z)){
                    c.clearVoxel(x, y, z);
                }
                
                if(c.getVoxel(x, y, z+1)){
                    c.clearVoxel(x, y, z+1);
                    c.setVoxel(x, y, z);
                }
            }
        }
    }
    
    //create some raindrops
    rX = random(0,8);
    rY = random(0,8);
    while(c.getVoxel(rX, rY, 7) != 0 && count < 100){
        rX = random(0,8);
        rY = random(0,8);
        count++;
    }
    c.setVoxel(rX, rY, 7);

    return 1;
}
Example #2
0
void setup()
{
  
	int i=0;

	randomSeed(analogRead(0));
	MINIGAME_pressRightNumber();
	
	timer = millis();
	
	for(i=0;i<8;i++)
	{
		pinMode(ledPins[i],OUTPUT);
		digitalWrite(ledPins[i],0);
	}
	
	pinMode(LED_PIN,OUTPUT);
	pinMode(BUT_PIN,INPUT);

}
Example #3
0
/*..........................................................................*/
QState Tunnel_initial(Tunnel *me, QEvt const *e) {
    uint8_t n;

    (void)e;                  /* avoid the "unreferenced parameter" warning */

    for (n = 0; n < GAME_MINES_MAX; ++n) {
        QHsm_init(me->mine1_pool[n], (QEvt *)0);/*initial tran. for Mine1 */
        QHsm_init(me->mine2_pool[n], (QEvt *)0);/*initial tran. for Mine2 */
    }

    randomSeed(1234);                   /* seed the pseudo-random generator */

    QActive_subscribe((QActive *)me, TIME_TICK_SIG);
    QActive_subscribe((QActive *)me, PLAYER_TRIGGER_SIG);
    QActive_subscribe((QActive *)me, PLAYER_QUIT_SIG);

    QS_OBJ_DICTIONARY(&l_tunnel);    /* object dictionary for Tunnel object */
    QS_OBJ_DICTIONARY(&l_tunnel.blinkTimeEvt);
    QS_OBJ_DICTIONARY(&l_tunnel.screenTimeEvt);

    QS_FUN_DICTIONARY(&Tunnel_initial); /* fun. dictionaries for Tunnel HSM */
    QS_FUN_DICTIONARY(&Tunnel_final);
    QS_FUN_DICTIONARY(&Tunnel_active);
    QS_FUN_DICTIONARY(&Tunnel_playing);
    QS_FUN_DICTIONARY(&Tunnel_demo);
    QS_FUN_DICTIONARY(&Tunnel_game_over);
    QS_FUN_DICTIONARY(&Tunnel_screen_saver);
    QS_FUN_DICTIONARY(&Tunnel_screen_saver_hide);
    QS_FUN_DICTIONARY(&Tunnel_screen_saver_show);

    QS_SIG_DICTIONARY(BLINK_TIMEOUT_SIG,  &l_tunnel);      /* local signals */
    QS_SIG_DICTIONARY(SCREEN_TIMEOUT_SIG, &l_tunnel);
    QS_SIG_DICTIONARY(SHIP_IMG_SIG,       &l_tunnel);
    QS_SIG_DICTIONARY(MISSILE_IMG_SIG,    &l_tunnel);
    QS_SIG_DICTIONARY(MINE_IMG_SIG,       &l_tunnel);
    QS_SIG_DICTIONARY(MINE_DISABLED_SIG,  &l_tunnel);
    QS_SIG_DICTIONARY(EXPLOSION_SIG,      &l_tunnel);
    QS_SIG_DICTIONARY(SCORE_SIG,          &l_tunnel);

    return Q_TRAN(&Tunnel_demo);
}
Example #4
0
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
bool 
Babuino::setup()
{
	reset();
	randomSeed(analogRead(4));
	Serial.begin(9600);
	// TODO:
	// Configure pin directions
	
	//_storage.writeByte(0x01F0,0);	// Starting address should be 0 for now.
	//_storage.writeByte(0x01F1,0);
	
	_motors.setup();
	
	_switches.setuprun();
	setupuserLed();
	setuppiezoBeeper();
	
	double_beep();
	return true;
}
Example #5
0
int main(void)
{
	init();
	
	pinMode(kLeftButton, INPUT);
	pinMode(kRightButton, INPUT);
	pinMode(kUpButton, INPUT);
	pinMode(kDownButton, INPUT);
		
	randomSeed(analogRead(5));

	mModel.Init();
	mView.Init(&mModel);
	mController.Init(&mModel, &mView);

    for (;;)
	{
		mController.Tick();
	}
    
    return 0;
}
Example #6
0
void DW1000RangingClass::startAsTag(char address[],  const byte mode[]){
    //save the address
    DW1000.convertToByte(address, _currentAddress);
    //write the address on the DW1000 chip
    DW1000.setEUI(address);
    Serial.print("device address: ");
    Serial.println(address);
    //we need to define a random short address:
    randomSeed(analogRead(0));
    _currentShortAddress[0]=random(0,256);
    _currentShortAddress[1]=random(0,256);
    
    //we configur the network for mac filtering
    //(device Address, network ID, frequency)
    DW1000Ranging.configureNetwork(_currentShortAddress[0]*256+_currentShortAddress[1], 0xDECA, mode);
    
    generalStart();
    //defined type as anchor
    _type=TAG;
    
    Serial.println("### TAG ###");
}
Example #7
0
void Tennis::Begin ()
{
  Serial.begin(9600);
  
    #if defined SERIAL_DEBUG
    Serial.print("Score, past faultMusic.getTotalDur:");
    Serial.println(scoreDisplayTime);
    #endif

  // travel LEDs
  pinMode(9, OUTPUT); // Initialize Arduino Digital Pins 9 PWM as output
  pinMode(10, OUTPUT); // Initialize Arduino Digital Pins 10 PWM as output
  pinMode(11, OUTPUT); // Initialize Arduino Digital Pins 11 PWM as output
  pinMode(6, OUTPUT); // Initialize Arduino Digital Pins 11 PWM as output
  pinMode(5, OUTPUT); // Initialize Arduino Digital Pins 11 PWM as output
  pinMode(3, OUTPUT); // Initialize Arduino Digital Pins 11 PWM as output

  // player inputs
  pinMode(player2InputPin,INPUT); // Initialize Arduino Digital Pins 2 as input for connecting Pushbutton
  pinMode(player12InputPin,INPUT); // Initialize Arduino Digital Pins 12 as input for connecting Pushbutton

  // player faults
  pinMode(player2FaultPin, OUTPUT);  // Initialize Arduino Digital Pins 4 as output
  pinMode(player12FaultPin, OUTPUT);  // Initialize Arduino Digital Pins 4 as output

  // get random eed (from analog noise) and determine starting direction {0, 1}
  randomSeed(analogRead(0));
  dir = random(2); // {0, 1}
  dir = (dir - 0.5) * 2; // {-1, 1}

  travelWait = (travelWaitMin + travelWaitMax) / 2;
  
  state = INTRO;
  returnFault = NONE;
  introMusic.Begin();
  digitalWrite(player2FaultPin, HIGH);
  digitalWrite(player12FaultPin, HIGH);
};
void MXBMESH::begin(channel_t chan,uint16_t localaddress,HardwareSerial *mySerial,bool powermode)
{
#if WITHSINKSOFT
	sinkSerial=mySerial;
#endif
	NODEINFO.localAddress=localaddress;
	NODEINFO.localChannel=chan;
	NODEINFO.islowpower=powermode;
	MxTimer2::set(TIMER2TICKS*1000, timer2function); // call every 30s for broadcast ,resolution must >=1000
	MxTimer2::start();
	if (NODEINFO.LoadCONFIG()) //maybe restart
	{
		MxRadio.begin(NODEINFO.localChannel,0xffff,NODEINFO.localAddress,true,true,true,15);
		MxRadio.setParam(phyTransmitPower,(txpwr_t)(NODEINFO.txPower-TXPOWERSHIFT));
	}
	else
	{
		NODEINFO.SaveCONFIG();
		MxRadio.begin(NODEINFO.localChannel,0xffff,NODEINFO.localAddress,true,true,true,15);
	}
	randomSeed(NODEINFO.localAddress);

	MxRadio.attachReceiveFrame(recievehandler);
	//MxRadio.attachError(errHandle);
	MxRadio.attachTxDone(onXmitDone);
	for (int nbindex=0;nbindex<MAX_NB;nbindex++)
	{
		NODEINFO.neigbour[nbindex].nodeid=BROADCASTADDR;
	}
	rxqueue.init_queue();
	txqueue.init_queue();


	if (NODEINFO.dataupload_interval==0xffff)
		NODEINFO.dataupload_interval=0;
	watchdog_init();
	watchdog_start();
}
Example #9
0
/**
 * calles to init the Websockets server
 */
void WebSocketsServer::begin(void) {
    WSclient_t * client;

    // init client storage
    for(uint8_t i = 0; i < WEBSOCKETS_SERVER_CLIENT_MAX; i++) {
        client = &_clients[i];

        client->num = i;
        client->cUrl = "";
        client->cKey = "";
        client->cProtocol = "";
        client->cVersion = 0;
        client->cIsUpgrade = false;
        client->cIsWebsocket = false;

        client->status = WSC_NOT_CONNECTED;
    }

    // todo find better seed
    randomSeed(millis());

    _server->begin();
}
Example #10
0
extern "C" int main(void)
{
	int count=0;
	randomSeed(analogRead(0));

	// while(1) {
	// 	x=sine[count];
	// 	y=sine[(count+1024)&0x0FFF];
	// 	count = (count+32)&0x0FFF;
	// 	laser.set(x, y, 255, 255, 255);
	// }
	int16_t step = 20;
	int x, y, xo = 0, yo = 0;
	while (1) {
		x=sine[count];
		y=sine[(count+1024)&0x0FFF];
		count = (count+32)&0x0FFF;
		laser_line_to(x, y, step, 255, 255, 255);
		laser_line_to(4095-x, y, step, 255, 255, 255);
		laser_line_to(4095-x, 4095-y, step, 255, 255, 255);
		laser_line_to(x, 4095-y, step, 255, 255, 255);
	}
}
Example #11
0
 Client(boost::asio::io_service& service
        , boost::asio::io_service::strand& ioStrand
        , unsigned sf
        , unsigned numClients
        , unsigned clientId
        , bool analytical
        , unsigned numOps
        , unsigned oltpWaitTime
        , double insertProb
        , double deleteProb
        , double updateProb
        , bool onlyQ1)
     : mSocket(service)
     , mIOStrand(ioStrand)
     , mClient(mSocket)
     , mSf(sf)
     , mNumTuples(numTuples(sf))
     , mStartTime(Clock::now())
     , mRnd(randomSeed())
     , mDist(0, analytical ? 2 : 3)
     , mAnalytical(analytical)
     , mNumClients(numClients)
     , mClientId(clientId)
     , mOLTPWaitTime(oltpWaitTime)
     , mOnlyQ1(onlyQ1)
 {
     mBatchOp.numOps        = numOps;
     mBatchOp.insertProb    = insertProb;
     mBatchOp.deleteProb    = deleteProb;
     mBatchOp.updateProb    = updateProb;
     mBatchOp.clientId      = mClientId;
     mBatchOp.numClients    = mNumClients;
     mBatchOp.baseInsertKey = calcBaseInsertKey(sf, numClients, clientId);
     mBatchOp.baseDeleteKey = clientId;
     assert(mAnalytical ||
             (mBatchOp.baseInsertKey > mBatchOp.baseDeleteKey && mBatchOp.baseInsertKey >= numTuples(mSf) - mNumClients));
 }
Example #12
0
void setup() {
    Serial.begin(9600);

    // int *bad_news = (int *) malloc(4000);

    mem_info("********* THIS IS THE BEGINNING *********");
    randomSeed(analogRead(0));

    int16_t Test_len = 1024;
    int16_t Test[Test_len];

    Serial.print("In: ");
    for (int16_t i=0; i < Test_len; i++) {
        Test[i] = random(0, 100);
if ( 1 ) {
        Serial.print(Test[i]);
        Serial.print(" ");
}
        }
    Serial.println();

    merge_sort(Test, Test_len);
    
if ( 1 ) {
    Serial.print("Out: ");
    for (int16_t i=0; i < Test_len; i++) {
        if ( i < Test_len-1 && Test[i] > Test[i+1] ) {
            Serial.print("Out of order!!");
            }

        Serial.print(Test[i]);
        Serial.print(" ");
        }
    Serial.println();
}
    }
Example #13
0
void GameOfLife::init(){
  if(is_initialised){
    return;
  }
  
  // Initialise all the alive,prev,etc.
  newleds = new CRGB[_num_leds];
  alive = new bool[_num_leds];
  next = new bool[_num_leds];
  prev = new bool[_num_leds];
  
  // Init colours
  randomSeed(analogRead(A3));
  generateColour();
  from_hue = to_hue; from_val = to_val; from_sat = to_sat;
  generateColour();
  
  // seed the first cells
  seedFlag = false;
  last_GoLstep = 0;
  GoLseed();
  
  is_initialised = true;
}
Example #14
0
boolean RF22Mesh::get_address() {
    uint8_t ret, len = GLOBAL_BUFFER_SIZE, source, dest, new_address = 0;
    int temp_type = -1, temp_me = -1;
    char *json_str;
    unsigned long starttime;
    boolean recv_ret;
    aJsonObject *root, *item;

    randomSeed( analogRead( 1 ) );

    me = (uint8_t) random( 256 );

    #ifdef CLIENT
    Serial.println( F( "This is the client" ) );
    #endif

    while( new_address == 0 ) {

        root = aJson.createObject();
        aJson.addNumberToObject( root, F( "t" ), (uint8_t) ADDRESS_REQUEST );
        aJson.addNumberToObject( root, F( "m" ), (uint8_t) me );
        json_str = aJson.print( root );

        ret = sendtoWait( (uint8_t *) json_str, strlen( json_str ), RF22_BROADCAST_ADDRESS );

        if( ret != RF22_ROUTER_ERROR_NONE ) {
            Serial.print( F( "Error Code: " ) );
            Serial.println( ret );
            errno = ret;
            //return 0;
        }

        aJson.deleteItem( root );
        free( json_str );

        starttime = millis();

        for( int i = 0; i < 4 && new_address == 0; i++ ) {
            if( recvfromAckTimeout( global_msg_buffer, &len, 1000,  &source, &dest ) )
            {
                root = aJson.parse( (char *) global_msg_buffer );
                item = aJson.getObjectItem( root, F( "t" ) );
                if( item ) {
                    temp_type = item->valueint;
                }
                item = aJson.getObjectItem( root, F( "m" ) );
                if( item ) {
                    temp_me = item->valueint;
                }
                if( temp_type == ADDRESS_GRANT && temp_me == me ) 
                {
                    new_address = aJson.getObjectItem( root, F( "a" ) )->valueint;
                    setThisAddress( new_address );
                    server_address = source;
                    return 1;
                }
                aJson.deleteItem( root );
            }
        }
    }

    return 1;

}
Example #15
0
void initBoard()
{
	initAERobot();
	randomSeed(1);

}
Example #16
0
Json::Value walletPropose (Json::Value const& params)
{
    boost::optional<Seed> seed;

    KeyType keyType = KeyType::secp256k1;

    if (params.isMember (jss::key_type))
    {
        if (! params[jss::key_type].isString())
        {
            return RPC::expected_field_error (
                jss::key_type, "string");
        }

        keyType = keyTypeFromString (
            params[jss::key_type].asString());

        if (keyType == KeyType::invalid)
            return rpcError(rpcINVALID_PARAMS);
    }

    if (params.isMember (jss::passphrase) ||
        params.isMember (jss::seed) ||
        params.isMember (jss::seed_hex))
    {
        Json::Value err;
        seed = RPC::getSeedFromRPC (params, err);
        if (!seed)
            return err;
    }
    else
    {
        seed = randomSeed ();
    }

    auto const publicKey = generateKeyPair (keyType, *seed).first;

    Json::Value obj (Json::objectValue);

    obj[jss::master_seed] = toBase58 (*seed);
    obj[jss::master_seed_hex] = strHex (seed->data(), seed->size());
    obj[jss::master_key] = seedAs1751 (*seed);
    obj[jss::account_id] = toBase58(calcAccountID(publicKey));
    obj[jss::public_key] = toBase58(TOKEN_ACCOUNT_PUBLIC, publicKey);
    obj[jss::key_type] = to_string (keyType);
    obj[jss::public_key_hex] = strHex (publicKey.data(), publicKey.size());

    if (params.isMember (jss::passphrase))
    {
        auto const entropy = estimate_entropy (
            params[jss::passphrase].asString());

        // 80 bits of entropy isn't bad, but it's better to
        // err on the side of caution and be conservative.
        if (entropy < 80.0)
            obj[jss::warning] =
                "This wallet was generated using a user-supplied "
                "passphrase that has low entropy and is vulnerable "
                "to brute-force attacks.";
        else
            obj[jss::warning] =
                "This wallet was generated using a user-supplied "
                "passphrase. It may be vulnerable to brute-force "
                "attacks.";
    }

    return obj;
}
Example #17
0
char screenPlay(void)
{
    unsigned long ulNow=millis();

    if(cSPredraw==1)
    {
        //reset all!!!!
        randomSeed(ulNow);
        iSPspeed=iSMspeed;
        iSPblock=-1;
        iSPblockNext=-1;
        screenPlayNewBlock();//compute next block
        ulSPnextMove=0;
        cSPredraw=0;
        cCollision=0;
        iSPpoints=0;
        iSPpointsBar=0;
        iSPbarLen=0;
        screenPlayRedraw();

        if(cSMsound!=0)
        {
            play_rtttl_start(iSMtone);
        }
    }

    if(ulSPnextMove<ulNow)
    {
        ulSPnextMove=ulNow+100*(9-iSPspeed)+200;

        if(screenPlayCheck(0,1,0)==0)
        {
            cCollision=0;//no collision this time
            displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_reset);
            iSPy++;
            displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_set);
        }
        else
        {

//i'm at the bottom. let's look for full lines
            screenPlayCleanup();


            //end of game?
            //i'm not able to move down. maybe is time to choose another block
            if(cCollision==1)
            {
                //second time!! end of game
                play_rtttl_stop();
                cSPredraw=1;
                return _screenEnd;
            }
            else
            {
                //delete next block on screen
                displayShowIconXY(_icon_tetris_1+iSPblockNext*4, 12,0,_draw_reset);
                screenPlayNewBlock();//compute next block
                displayShowIconXY(_icon_tetris_1+iSPblockNext*4, 12,0,_draw_set);
                cCollision=1;
            }

        }

    }



    switch(keyboardGetKey())
    {
    case up_key:
    case enter_key:
        if(screenPlayCheck(0,0,1)==0)
        {
//rotation is possible
            displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_reset);
            iSPblockRotation=(iSPblockRotation+1)&3 ;
            displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_set);

        }
        else
        {
//try with a little movement
            if(screenPlayCheck(iSPbias,0,1)==0)
            {

                displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_reset);
                iSPx+=iSPbias;
                iSPblockRotation=(iSPblockRotation+1)&3 ;
                displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_set);
                iSPbias=-iSPbias;
            }
            else
            {
                if(screenPlayCheck(-iSPbias,0,1)==0)
                {

                    displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_reset);
                    iSPx+=-iSPbias;
                    iSPblockRotation=(iSPblockRotation+1)&3 ;
                    displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_set);
                    iSPbias=-iSPbias;
                }
            }
        }

        break;
    case down_key:
        ulSPnextMove=0;//force go-down
        break;
    case left_key:
        if(screenPlayCheck(-1,0,0)==0)
        {
            displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_reset);
            iSPx--;
            displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_set);
        }
        break;
    case right_key:
        if(screenPlayCheck(1,0,0)==0)
        {
            displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_reset);
            iSPx++;
            displayShowIconXY(_icon_tetris_1+iSPblock*4+iSPblockRotation, iSPx,iSPy, _draw_set);
        }
        break;
    }

//every 3 lines add a pixel to the bar
    if(iSPpointsBar>=1)
    {
        iSPpointsBar=0;
        iSPbarLen++;
        if(iSPbarLen==5)
        {
//new level!!!
//change level value if possible
            iSPbarLen=0;
            if(iSPspeed<9)
            {
                displayShowIconXY(_icon_0+iSPspeed, 13,5,_draw_reset);
                iSPspeed++;
                displayShowIconXY(_icon_0+iSPspeed, 13,5,0);
            }
//delete bar
            displayLineDy(13,11,4,_draw_reset);
            displayLineDy(14,11,4,_draw_reset);
        }
        else
        {
            displayLineDx(13,15-iSPbarLen,2,_draw_set);
        }
    }




    return _screenPlay;
}
Example #18
0
/**
 * G26: Mesh Validation Pattern generation.
 *
 * Used to interactively edit the mesh by placing the
 * nozzle in a problem area and doing a G29 P4 R command.
 *
 * Parameters:
 *
 *  B  Bed Temperature
 *  C  Continue from the Closest mesh point
 *  D  Disable leveling before starting
 *  F  Filament diameter
 *  H  Hotend Temperature
 *  K  Keep heaters on when completed
 *  L  Layer Height
 *  O  Ooze extrusion length
 *  P  Prime length
 *  Q  Retraction multiplier
 *  R  Repetitions (number of grid points)
 *  S  Nozzle Size (diameter) in mm
 *  T  Tool index to change to, if included
 *  U  Random deviation (50 if no value given)
 *  X  X position
 *  Y  Y position
 */
void GcodeSuite::G26() {
  SERIAL_ECHOLNPGM("G26 starting...");

  // Don't allow Mesh Validation without homing first,
  // or if the parameter parsing did not go OK, abort
  if (axis_unhomed_error()) return;

  // Change the tool first, if specified
  if (parser.seenval('T')) tool_change(parser.value_int());

  g26_extrusion_multiplier    = EXTRUSION_MULTIPLIER;
  g26_retraction_multiplier   = RETRACTION_MULTIPLIER;
  g26_layer_height            = MESH_TEST_LAYER_HEIGHT;
  g26_prime_length            = PRIME_LENGTH;
  g26_bed_temp                = MESH_TEST_BED_TEMP;
  g26_hotend_temp             = MESH_TEST_HOTEND_TEMP;
  g26_prime_flag              = 0;

  float g26_nozzle            = MESH_TEST_NOZZLE_SIZE,
        g26_filament_diameter = DEFAULT_NOMINAL_FILAMENT_DIA,
        g26_ooze_amount       = parser.linearval('O', OOZE_AMOUNT);

  bool g26_continue_with_closest = parser.boolval('C'),
       g26_keep_heaters_on       = parser.boolval('K');

  if (parser.seenval('B')) {
    g26_bed_temp = parser.value_celsius();
    if (g26_bed_temp && !WITHIN(g26_bed_temp, 40, 140)) {
      SERIAL_ECHOLNPGM("?Specified bed temperature not plausible (40-140C).");
      return;
    }
  }

  if (parser.seenval('L')) {
    g26_layer_height = parser.value_linear_units();
    if (!WITHIN(g26_layer_height, 0.0, 2.0)) {
      SERIAL_ECHOLNPGM("?Specified layer height not plausible.");
      return;
    }
  }

  if (parser.seen('Q')) {
    if (parser.has_value()) {
      g26_retraction_multiplier = parser.value_float();
      if (!WITHIN(g26_retraction_multiplier, 0.05, 15.0)) {
        SERIAL_ECHOLNPGM("?Specified Retraction Multiplier not plausible.");
        return;
      }
    }
    else {
      SERIAL_ECHOLNPGM("?Retraction Multiplier must be specified.");
      return;
    }
  }

  if (parser.seenval('S')) {
    g26_nozzle = parser.value_float();
    if (!WITHIN(g26_nozzle, 0.1, 1.0)) {
      SERIAL_ECHOLNPGM("?Specified nozzle size not plausible.");
      return;
    }
  }

  if (parser.seen('P')) {
    if (!parser.has_value()) {
      #if HAS_LCD_MENU
        g26_prime_flag = -1;
      #else
        SERIAL_ECHOLNPGM("?Prime length must be specified when not using an LCD.");
        return;
      #endif
    }
    else {
      g26_prime_flag++;
      g26_prime_length = parser.value_linear_units();
      if (!WITHIN(g26_prime_length, 0.0, 25.0)) {
        SERIAL_ECHOLNPGM("?Specified prime length not plausible.");
        return;
      }
    }
  }

  if (parser.seenval('F')) {
    g26_filament_diameter = parser.value_linear_units();
    if (!WITHIN(g26_filament_diameter, 1.0, 4.0)) {
      SERIAL_ECHOLNPGM("?Specified filament size not plausible.");
      return;
    }
  }
  g26_extrusion_multiplier *= sq(1.75) / sq(g26_filament_diameter); // If we aren't using 1.75mm filament, we need to
                                                                    // scale up or down the length needed to get the
                                                                    // same volume of filament

  g26_extrusion_multiplier *= g26_filament_diameter * sq(g26_nozzle) / sq(0.3); // Scale up by nozzle size

  if (parser.seenval('H')) {
    g26_hotend_temp = parser.value_celsius();
    if (!WITHIN(g26_hotend_temp, 165, 280)) {
      SERIAL_ECHOLNPGM("?Specified nozzle temperature not plausible.");
      return;
    }
  }

  if (parser.seen('U')) {
    randomSeed(millis());
    // This setting will persist for the next G26
    random_deviation = parser.has_value() ? parser.value_float() : 50.0;
  }

  int16_t g26_repeats;
  #if HAS_LCD_MENU
    g26_repeats = parser.intval('R', GRID_MAX_POINTS + 1);
  #else
    if (!parser.seen('R')) {
      SERIAL_ECHOLNPGM("?(R)epeat must be specified when not using an LCD.");
      return;
    }
    else
      g26_repeats = parser.has_value() ? parser.value_int() : GRID_MAX_POINTS + 1;
  #endif
  if (g26_repeats < 1) {
    SERIAL_ECHOLNPGM("?(R)epeat value not plausible; must be at least 1.");
    return;
  }

  g26_x_pos = parser.seenval('X') ? RAW_X_POSITION(parser.value_linear_units()) : current_position[X_AXIS];
  g26_y_pos = parser.seenval('Y') ? RAW_Y_POSITION(parser.value_linear_units()) : current_position[Y_AXIS];
  if (!position_is_reachable(g26_x_pos, g26_y_pos)) {
    SERIAL_ECHOLNPGM("?Specified X,Y coordinate out of bounds.");
    return;
  }

  /**
   * Wait until all parameters are verified before altering the state!
   */
  set_bed_leveling_enabled(!parser.seen('D'));

  if (current_position[Z_AXIS] < Z_CLEARANCE_BETWEEN_PROBES) {
    do_blocking_move_to_z(Z_CLEARANCE_BETWEEN_PROBES);
    set_current_from_destination();
  }

  if (turn_on_heaters() != G26_OK) goto LEAVE;

  current_position[E_AXIS] = 0.0;
  sync_plan_position_e();

  if (g26_prime_flag && prime_nozzle() != G26_OK) goto LEAVE;

  /**
   *  Bed is preheated
   *
   *  Nozzle is at temperature
   *
   *  Filament is primed!
   *
   *  It's  "Show Time" !!!
   */

  ZERO(circle_flags);
  ZERO(horizontal_mesh_line_flags);
  ZERO(vertical_mesh_line_flags);

  // Move nozzle to the specified height for the first layer
  set_destination_from_current();
  destination[Z_AXIS] = g26_layer_height;
  move_to(destination, 0.0);
  move_to(destination, g26_ooze_amount);

  #if HAS_LCD_MENU
    ui.capture();
  #endif

  //debug_current_and_destination(PSTR("Starting G26 Mesh Validation Pattern."));

  #if DISABLED(ARC_SUPPORT)

    /**
     * Pre-generate radius offset values at 30 degree intervals to reduce CPU load.
     */
    #define A_INT 30
    #define _ANGS (360 / A_INT)
    #define A_CNT (_ANGS / 2)
    #define _IND(A) ((A + _ANGS * 8) % _ANGS)
    #define _COS(A) (trig_table[_IND(A) % A_CNT] * (_IND(A) >= A_CNT ? -1 : 1))
    #define _SIN(A) (-_COS((A + A_CNT / 2) % _ANGS))
    #if A_CNT & 1
      #error "A_CNT must be a positive value. Please change A_INT."
    #endif
    float trig_table[A_CNT];
    for (uint8_t i = 0; i < A_CNT; i++)
      trig_table[i] = INTERSECTION_CIRCLE_RADIUS * cos(RADIANS(i * A_INT));

  #endif // !ARC_SUPPORT

  mesh_index_pair location;
  do {
     location = g26_continue_with_closest
      ? find_closest_circle_to_print(current_position[X_AXIS], current_position[Y_AXIS])
      : find_closest_circle_to_print(g26_x_pos, g26_y_pos); // Find the closest Mesh Intersection to where we are now.

    if (location.x_index >= 0 && location.y_index >= 0) {
      const float circle_x = _GET_MESH_X(location.x_index),
                  circle_y = _GET_MESH_Y(location.y_index);

      // If this mesh location is outside the printable_radius, skip it.
      if (!position_is_reachable(circle_x, circle_y)) continue;

      // Determine where to start and end the circle,
      // which is always drawn counter-clockwise.
      const uint8_t xi = location.x_index, yi = location.y_index;
      const bool f = yi == 0, r = xi >= GRID_MAX_POINTS_X - 1, b = yi >= GRID_MAX_POINTS_Y - 1;

      #if ENABLED(ARC_SUPPORT)

        #define ARC_LENGTH(quarters)  (INTERSECTION_CIRCLE_RADIUS * M_PI * (quarters) / 2)
        float sx = circle_x + INTERSECTION_CIRCLE_RADIUS,   // default to full circle
              ex = circle_x + INTERSECTION_CIRCLE_RADIUS,
              sy = circle_y, ey = circle_y,
              arc_length = ARC_LENGTH(4);

        // Figure out where to start and end the arc - we always print counterclockwise
        if (xi == 0) {                             // left edge
          sx = f ? circle_x + INTERSECTION_CIRCLE_RADIUS : circle_x;
          ex = b ? circle_x + INTERSECTION_CIRCLE_RADIUS : circle_x;
          sy = f ? circle_y : circle_y - (INTERSECTION_CIRCLE_RADIUS);
          ey = b ? circle_y : circle_y + INTERSECTION_CIRCLE_RADIUS;
          arc_length = (f || b) ? ARC_LENGTH(1) : ARC_LENGTH(2);
        }
        else if (r) {                             // right edge
          sx = b ? circle_x - (INTERSECTION_CIRCLE_RADIUS) : circle_x;
          ex = f ? circle_x - (INTERSECTION_CIRCLE_RADIUS) : circle_x;
          sy = b ? circle_y : circle_y + INTERSECTION_CIRCLE_RADIUS;
          ey = f ? circle_y : circle_y - (INTERSECTION_CIRCLE_RADIUS);
          arc_length = (f || b) ? ARC_LENGTH(1) : ARC_LENGTH(2);
        }
        else if (f) {
          sx = circle_x + INTERSECTION_CIRCLE_RADIUS;
          ex = circle_x - (INTERSECTION_CIRCLE_RADIUS);
          sy = ey = circle_y;
          arc_length = ARC_LENGTH(2);
        }
        else if (b) {
          sx = circle_x - (INTERSECTION_CIRCLE_RADIUS);
          ex = circle_x + INTERSECTION_CIRCLE_RADIUS;
          sy = ey = circle_y;
          arc_length = ARC_LENGTH(2);
        }
        const float arc_offset[2] = {
          circle_x - sx,
          circle_y - sy
        };

        const float dx_s = current_position[X_AXIS] - sx,   // find our distance from the start of the actual circle
                    dy_s = current_position[Y_AXIS] - sy,
                    dist_start = HYPOT2(dx_s, dy_s);
        const float endpoint[XYZE] = {
          ex, ey,
          g26_layer_height,
          current_position[E_AXIS] + (arc_length * g26_e_axis_feedrate * g26_extrusion_multiplier)
        };

        if (dist_start > 2.0) {
          retract_filament(destination);
          //todo:  parameterize the bump height with a define
          move_to(current_position[X_AXIS], current_position[Y_AXIS], current_position[Z_AXIS] + 0.500, 0.0);  // Z bump to minimize scraping
          move_to(sx, sy, g26_layer_height + 0.500, 0.0); // Get to the starting point with no extrusion while bumped
        }

        move_to(sx, sy, g26_layer_height, 0.0); // Get to the starting point with no extrusion / un-Z bump

        recover_filament(destination);
        const float save_feedrate = feedrate_mm_s;
        feedrate_mm_s = PLANNER_XY_FEEDRATE() / 10.0;

        if (g26_debug_flag) {
          SERIAL_ECHOPAIR(" plan_arc(ex=", endpoint[X_AXIS]);
          SERIAL_ECHOPAIR(", ey=", endpoint[Y_AXIS]);
          SERIAL_ECHOPAIR(", ez=", endpoint[Z_AXIS]);
          SERIAL_ECHOPAIR(", len=", arc_length);
          SERIAL_ECHOPAIR(") -> (ex=", current_position[X_AXIS]);
          SERIAL_ECHOPAIR(", ey=", current_position[Y_AXIS]);
          SERIAL_ECHOPAIR(", ez=", current_position[Z_AXIS]);
          SERIAL_CHAR(')');
          SERIAL_EOL();
        }

        plan_arc(endpoint, arc_offset, false);  // Draw a counter-clockwise arc
        feedrate_mm_s = save_feedrate;
        set_destination_from_current();
        #if HAS_LCD_MENU
          if (user_canceled()) goto LEAVE; // Check if the user wants to stop the Mesh Validation
        #endif

      #else // !ARC_SUPPORT

        int8_t start_ind = -2, end_ind = 9; // Assume a full circle (from 5:00 to 5:00)
        if (xi == 0) {                      // Left edge? Just right half.
          start_ind = f ? 0 : -3;           //  03:00 to 12:00 for front-left
          end_ind = b ? 0 : 2;              //  06:00 to 03:00 for back-left
        }
        else if (r) {                       // Right edge? Just left half.
          start_ind = b ? 6 : 3;            //  12:00 to 09:00 for front-right
          end_ind = f ? 5 : 8;              //  09:00 to 06:00 for back-right
        }
        else if (f) {                       // Front edge? Just back half.
          start_ind = 0;                    //  03:00
          end_ind = 5;                      //  09:00
        }
        else if (b) {                       // Back edge? Just front half.
          start_ind = 6;                    //  09:00
          end_ind = 11;                     //  03:00
        }

        for (int8_t ind = start_ind; ind <= end_ind; ind++) {

          #if HAS_LCD_MENU
            if (user_canceled()) goto LEAVE;          // Check if the user wants to stop the Mesh Validation
          #endif

          float rx = circle_x + _COS(ind),            // For speed, these are now a lookup table entry
                ry = circle_y + _SIN(ind),
                xe = circle_x + _COS(ind + 1),
                ye = circle_y + _SIN(ind + 1);

          #if IS_KINEMATIC
            // Check to make sure this segment is entirely on the bed, skip if not.
            if (!position_is_reachable(rx, ry) || !position_is_reachable(xe, ye)) continue;
          #else                                               // not, we need to skip
            rx = constrain(rx, X_MIN_POS + 1, X_MAX_POS - 1); // This keeps us from bumping the endstops
            ry = constrain(ry, Y_MIN_POS + 1, Y_MAX_POS - 1);
            xe = constrain(xe, X_MIN_POS + 1, X_MAX_POS - 1);
            ye = constrain(ye, Y_MIN_POS + 1, Y_MAX_POS - 1);
          #endif

          print_line_from_here_to_there(rx, ry, g26_layer_height, xe, ye, g26_layer_height);
          SERIAL_FLUSH();  // Prevent host M105 buffer overrun.
        }

      #endif // !ARC_SUPPORT

      if (look_for_lines_to_connect()) goto LEAVE;
    }

    SERIAL_FLUSH(); // Prevent host M105 buffer overrun.

  } while (--g26_repeats && location.x_index >= 0 && location.y_index >= 0);

  LEAVE:
  ui.set_status_P(PSTR("Leaving G26"), -1);

  retract_filament(destination);
  destination[Z_AXIS] = Z_CLEARANCE_BETWEEN_PROBES;

  //debug_current_and_destination(PSTR("ready to do Z-Raise."));
  move_to(destination, 0); // Raise the nozzle
  //debug_current_and_destination(PSTR("done doing Z-Raise."));

  destination[X_AXIS] = g26_x_pos;                            // Move back to the starting position
  destination[Y_AXIS] = g26_y_pos;
  //destination[Z_AXIS] = Z_CLEARANCE_BETWEEN_PROBES;         // Keep the nozzle where it is

  move_to(destination, 0);                                    // Move back to the starting position
  //debug_current_and_destination(PSTR("done doing X/Y move."));

  #if HAS_LCD_MENU
    ui.release();                                             // Give back control of the LCD
  #endif

  if (!g26_keep_heaters_on) {
    #if HAS_HEATED_BED
      thermalManager.setTargetBed(0);
    #endif
    thermalManager.setTargetHotend(active_extruder, 0);
  }
}
Example #19
0
void AddressStorageClass::begin()
{
    randomSeed(analogRead(0));
}
Example #20
0
Scroll::Scroll(String text, int scrollspeed, int tr, int tg, int tb, int br, int bg, int bb, int displaynumber){

  int startdelay = scrollspeed*8*displaynumber;
  randomSeed(analogRead(0));

  Colorduino.init();


  Colorduino.setWhiteBalance(36, 63, 63); // Set white balance
  delay(startdelay);


  int numberofcharacters = text.length();
  for(int xv = 10; xv > -((numberofcharacters+1)*6) ; xv--){

    GFX_Color_t textcolor = Colorduino.color(tr, tg, tb);//Color of text to scroll Default: White
    GFX_Color_t textBG = Colorduino.color(br, bg, bb);//Color of text background Default: Black/Nothing

    char char1 = text.charAt(0);
    char char2 = text.charAt(1);
    char char3 = text.charAt(2);
    char char4 = text.charAt(3);
    char char5 = text.charAt(4);
    char char6 = text.charAt(5);
    char char7 = text.charAt(6);
    char char8 = text.charAt(7);
    char char9 = text.charAt(8);
    char char10 = text.charAt(9);
    char char11 = text.charAt(10);
    char char12 = text.charAt(11);
    char char13 = text.charAt(12);
    char char14 = text.charAt(13);
    char char15 = text.charAt(14);
    char char16 = text.charAt(15);
    char char17 = text.charAt(16);
    char char18 = text.charAt(17);
    char char19 = text.charAt(18);
    char char20 = text.charAt(19);
    

   
      Colorduino.drawChar(xv+6*1, 1, char1, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*2, 1, char2, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*3, 1, char3, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*4, 1, char4, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*5, 1, char5, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*6, 1, char6, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*7, 1, char7, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*8, 1, char8, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*9, 1, char9, textcolor, textBG, 1); 
      Colorduino.drawChar(xv+6*10, 1, char10, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*11, 1, char11, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*12, 1, char12, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*13, 1, char13, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*14, 1, char14, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*15, 1, char15, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*16, 1, char16, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*17, 1, char17, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*18, 1, char18, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*19, 1, char19, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*20, 1, char20, textcolor, textBG, 1);  
      Colorduino.drawChar(xv+6*20, 1, ' ', textcolor, textBG, 1); 
      
      Colorduino.swapBuffers(true);
    delay(scrollspeed); 

    }



  }
Example #21
0
// seed the random number generator with entropy from the temperature,
// voltage reading, and microseconds since boot.
// this method is still most effective when called semi-randomly such
// as after a user hits a button to start a game or other semi-random
// events
void Arduboy::initRandomSeed()
{
  power_adc_enable(); // ADC on
  randomSeed(~rawADC(ADC_TEMP) * ~rawADC(ADC_VOLTAGE) * ~micros() + micros());
  power_adc_disable(); // ADC off
}
void setup() {
  Serial.begin(9600);       // 初始化串口通信
  randomSeed(analogRead(0)); // 产生随机种子
}
Example #23
0
CX10::CX10() {
    randomSeed((analogRead(A0) & 0x1F) | (analogRead(A1) << 5));
    for (int n = 0; n < CRAFT; ++n) {
        Craft *c = &craft_[n];
        c->nextPacket = 0;
        memset(c->aid, 0xff, sizeof c->aid);
        memset(c->Servo_data, 0, sizeof c->Servo_data);
        setThrottle(n, 0);
        setAileron(n, 500);
        setElevator(n, 500);
        setRudder(n, 500);
        for(uint8_t i=0;i<4;i++) {
#ifdef RFDUINO
            c->txid[i] = random(256);
#else
            c->txid[i] = random();
#endif
        }
        c->txid[1] %= 0x30;
        c->freq[0] = (c->txid[0] & 0x0F) + 0x03;
        c->freq[1] = (c->txid[0] >> 4) + 0x16;
        c->freq[2] = (c->txid[1] & 0x0F) + 0x2D;
        c->freq[3] = (c->txid[1] >> 4) + 0x40;
    }
    pinMode(ledPin, OUTPUT);
    //RF module pins
    pinMode(MOSI_pin, OUTPUT);
    pinMode(SCK_pin, OUTPUT);
    pinMode(MISO_pin, INPUT);
    pinMode(CS_pin, OUTPUT);
    pinMode(CE_pin, OUTPUT);
    digitalWrite(ledPin, LOW);//start LED off
    CS_on;//start CS high
    CE_on;//start CE high
    MOSI_on;//start MOSI high
    SCK_on;//start sck high
    delay(70);//wait 70ms
    CS_off;//start CS low
    CE_off;//start CE low
    MOSI_off;//start MOSI low
    SCK_off;//start sck low
    delay(100);
    CS_on;//start CS high
    delay(10);
#ifdef RFDUINO
    SPI.begin();
    SPI.setFrequency(250);
#endif
    //############ INIT1 ##############
    CS_off;
    _spi_write(0x3f); // Set Baseband parameters (debug registers) - BB_CAL
    _spi_write(0x4c);
    _spi_write(0x84);
    _spi_write(0x67);
    _spi_write(0x9c);
    _spi_write(0x20);
    CS_on;
    delayMicroseconds(5);
    CS_off;
    _spi_write(0x3e); // Set RF parameters (debug registers) - RF_CAL
    _spi_write(0xc9);
    _spi_write(0x9a);
    _spi_write(0xb0);
    _spi_write(0x61);
    _spi_write(0xbb);
    _spi_write(0xab);
    _spi_write(0x9c);
    CS_on;
    delayMicroseconds(5);
    CS_off;
    _spi_write(0x39); // Set Demodulator parameters (debug registers) - DEMOD_CAL
    _spi_write(0x0b);
    _spi_write(0xdf);
    _spi_write(0xc4);
    _spi_write(0xa7);
    _spi_write(0x03);
    CS_on;
    delayMicroseconds(5);
    CS_off;
    _spi_write(0x30); // Set TX address 0xCCCCCCCC
    _spi_write(0xcc);
    _spi_write(0xcc);
    _spi_write(0xcc);
    _spi_write(0xcc);
    _spi_write(0xcc);
    CS_on;
    delayMicroseconds(5);
    CS_off;
    _spi_write(0x2a); // Set RX pipe 0 address 0xCCCCCCCC
    _spi_write(0xcc);
    _spi_write(0xcc);
    _spi_write(0xcc);
    _spi_write(0xcc);
    _spi_write(0xcc);
    CS_on;
    delayMicroseconds(5);
    _spi_write_address(0xe1, 0x00); // Clear TX buffer
    _spi_write_address(0xe2, 0x00); // Clear RX buffer
    _spi_write_address(0x27, 0x70); // Clear interrupts
    _spi_write_address(0x21, 0x00); // No auto-acknowledge
    _spi_write_address(0x22, 0x01); // Enable only data pipe 0
    _spi_write_address(0x23, 0x03); // Set 5 byte rx/tx address field width
    _spi_write_address(0x25, 0x02); // Set channel frequency
    _spi_write_address(0x24, 0x00); // No auto-retransmit
    _spi_write_address(0x31, PACKET_LENGTH); // 19-byte payload
    _spi_write_address(0x26, 0x07); // 1 Mbps air data rate, 5dbm RF power
    _spi_write_address(0x50, 0x73); // Activate extra feature register
    _spi_write_address(0x3c, 0x00); // Disable dynamic payload length
    _spi_write_address(0x3d, 0x00); // Extra features all off
    MOSI_off;
    delay(100);//100ms delay

    //############ INIT2 ##############
    healthy_ = _spi_read_address(0x10) == 0xCC;
    
    _spi_write_address(0x20, 0x0e); // Power on, TX mode, 2 byte CRC
    MOSI_off;
    delay(100);
    bindAllowed_ = true;
    nextBind_ = micros();
    nextSlot_ = 0;
}
Example #24
0
//
// Performs all the RAM checks on the region supplied to the object.
//
PERROR
CRamCheck::checkRandomAccess(
    const RAM_REGION *ramRegion
)
{
    PERROR error = errorSuccess;

    UINT8  dataBusWidth    = m_cpu->dataBusWidth(ramRegion->start);
    UINT8  dataAccessWidth = m_cpu->dataAccessWidth(ramRegion->start);

    UINT32 regionLength    = (ramRegion->end - ramRegion->start) / ramRegion->step;
    UINT32 countLength     = (regionLength * 3) / (dataBusWidth * ramRegion->step);

    //
    // This function only works with at least byte-wide memory.
    // Use a duplicate entry in the RAM_REGION for the byte-wide representation.
    //
    if ((ramRegion->mask != 0x00FF) &&
        (ramRegion->mask != 0xFF00) &&
        (ramRegion->mask != 0xFFFF))
    {
        return errorNotImplemented;
    }

    //
    // Clear the region first to all 0.
    // This will also perform any bank switch.
    //
    error = write(ramRegion, 0);

    if (FAILED(error))
    {
        return error;
    }

    //
    // Outer loop to periodically reset the region back to 0 to restart
    // with different seeds for the address & data values.
    //
    for (UINT8 cycle = 0 ; (cycle < 8) && SUCCESS(error) ; cycle++)
    {
        //
        // Pass 1 - write/read/verify, random access
        //

        randomSeed(ramRegion->start + ramRegion->step + ramRegion->mask + cycle);

        //
        // The length & step are used for the iteration count as a means to equalize the random access
        // density no matter what the size of the RAM.
        //
        for (UINT32 count = 0 ; count < countLength ; count++ )
        {
            UINT32 address = (((UINT32) random(regionLength)) * (dataBusWidth * ramRegion->step)) + ramRegion->start;
            UINT16 expData = (((address + cycle) * 3) ^ ((address + cycle) / 5));
            UINT16 recData = 0;

            // For 16-bit we just use the same value for hi & lo.
            expData = (expData & 0xFF) | (expData << 8);

            //
            // Pause to make sure the data is actually held valid.
            // This is done to help detect DRAM refresh failure.
            //
            if ((count % (countLength / 4)) == 0)
            {
                delay(cycle * 200);
            }

            //
            // Add in some blind writes to let the writes accumulate
            // a bit more agressively to fill in the memory with data.
            //
            if (count & 2)
            {
                error = m_cpu->memoryWrite(address, expData);

                if (FAILED(error))
                {
                    break;
                }

                continue;
            }

            // Read what's there.
            error = m_cpu->memoryRead(address, &recData);

            if (FAILED(error))
            {
                break;
            }

            expData &= ramRegion->mask;
            recData &= ramRegion->mask;

            // If we a read a 0 then write out a value.
            if (recData == 0)
            {
                error = m_cpu->memoryWrite(address, expData);

                if (FAILED(error))
                {
                    break;
                }

                continue;
            }

            if (dataAccessWidth == 1)
            {
                CHECK_VALUE_UINT8_BREAK(error, ramRegion->location, address, expData, recData);
            }
            else if (dataAccessWidth == 2)
            {
                CHECK_VALUE_UINT16_BREAK(error, ramRegion->location, address, expData, recData);
            }
            else
            {
                error = errorNotImplemented;
                break;
            }

            //
            // Add in an optional clear after verify.
            // This is less agressive than the blind one to that
            // on average data accumulates in the RAM
            //
            if (count & 4)
            {
                error = m_cpu->memoryWrite(address, 0);

                if (FAILED(error))
                {
                    break;
                }
            }
        }

        //
        // Add in a variable delay between cycles.
        // This is to detect a very specific failure mode encountered on TMS4060
        // DRAM used on Space Invaders where the RAM fails a few seconds after the
        // data is written.
        //
        delay(cycle * 300);

        //
        // Pass 2 - verify/clear entire contents, random access
        //

        randomSeed(ramRegion->start + ramRegion->step + ramRegion->mask + cycle);

        //
        // The length & step are used for the iteration count as a means to equalize the random access
        // density no matter what the size of the RAM.
        //
        for (UINT32 count = 0 ; count < countLength ; count++ )
        {
            UINT32 address = (((UINT32) random(regionLength)) * (dataBusWidth * ramRegion->step)) + ramRegion->start;
            UINT16 expData = (((address + cycle) * 3) ^ ((address + cycle) / 5));
            UINT16 recData = 0;

            // For 16-bit we just use the same value for hi & lo.
            expData = (expData & 0xFF) | (expData << 8);

            // Read what's there.
            error = m_cpu->memoryRead(address, &recData);

            if (FAILED(error))
            {
                break;
            }

            expData &= ramRegion->mask;
            recData &= ramRegion->mask;

            // Nothing to verify if 0
            if (recData == 0)
            {
                continue;
            }

            if (dataAccessWidth == 1)
            {
                CHECK_VALUE_UINT8_BREAK(error, ramRegion->location, address, expData, recData);
            }
            else if (dataAccessWidth == 2)
            {
                CHECK_VALUE_UINT16_BREAK(error, ramRegion->location, address, expData, recData);
            }
            else
            {
                error = errorNotImplemented;
                break;
            }

            error = m_cpu->memoryWrite(address, 0);

            if (FAILED(error))
            {
                break;
            }
        }

    }

    return error;
}
Example #25
0
/*
The loop() override function is basically deivided between these two while loops.
The first while loop happen when there is an audio file playing and the second
	while loop happen when there is no audio file playing.
*/
void NTGVS1053::NTGVS1053Loop(){

	/*
	When an audio file in playing you cannot tag the RFID card.
	I do this to keep maintaining space inside the controller.
	In this case I am using Arduino UNO which has only 32 kilo bytes.
	There is a way to implement tagging RFID tag while an audio file is playing.
	1. Audio is playing.
	2. New RFID input into software serial (check NTGRFIDReader class).
	3. Copy every input from the software serial into new array of int.
	4. Turn off the audio playing.
	5. Play new audio file based on the copied input from the software serial.
	I have tried this but the codes go beyond 32 kilo bytes.
	Possible solutions are using better controller than Arduino Uno or using good pointer management
		(of which I do not understand yet).
	*/
	while(vs1053.playingMusic){
		PhysicalButton(vs1053.playingMusic);
		DebugSerialButton(vs1053.playingMusic);
	}

	//While the audio is not playing you can tag an RFID card.
	while(!vs1053.playingMusic){

		PhysicalButton(vs1053.playingMusic);
		DebugSerialButton(vs1053.playingMusic);

		/*
		Get RFID index from NTGRFIDLoop() function.
		This NTGRFIDLoop() function returns an integer number.
		*/
		mp3Index = ntgRFIDReader.NTGRFIDReaderLoop(vs1053.playingMusic);

		/*
		So if NTGRFIDLoop() function returns a -1 then the value from the RFID card is not valid.
		Hence we are not executing these codes below anymore.
		Just try to remember this, if NTGRFIDLoop() returns -1 the RFID card is not valid, if
			NTGRFIDLoop() returns 1 then the RFID card/tag is valid and the program goes through.
		*/
		if(mp3Index != -1){

			//If mp3Index is equal to 0 then it means Exhibition Prime audio will be played.
			if(mp3Index == 0){
				mp3IndexBufferString = voicePrime;
				mp3IndexBufferString.toCharArray(mp3IndexBufferCharArray, 50);
			}
			else if(mp3Index != 0){
				mp3IndexBufferString = String(mp3Index) + ".mp3";
				mp3IndexBufferString.toCharArray(mp3IndexBufferCharArray, 50);
			}

			//Check if the visited exhibition is a proper detinated exhibition.
			if(mp3Index == targetExhibitionArray[0] || mp3Index == targetExhibitionArray[1]){ haveVisitedTargetExhibition = true; }
			else if(mp3Index != targetExhibitionArray[0] && mp3Index != targetExhibitionArray[1]){ haveVisitedTargetExhibition = false; }

			//Play an audio file to welcome player/visitor to any visited exhibition in the museum.
			Play(voiceWelcomeToExhibition);
			Play(mp3IndexBufferCharArray);

			//If the player properly visited the next exhibition.
			if(haveVisitedTargetExhibition){

				/*
				Give explanation here.
				Generate random seed from floating analog pin.
				*/
				randomSeed(analogRead(RANDOM_SEED));
				//Generate random integer from 1 to 4 (there is only 4 explanations available per exhibition).
				int explanationIndexRandom = random(1, 5);
				Play(voiceExplanationNumber);
				//Convert int to String to char array.
				mp3IndexBufferString = String(explanationIndexRandom) + ".mp3";
				mp3IndexBufferString.toCharArray(mp3IndexBufferCharArray, 50);
				Play(mp3IndexBufferCharArray);

				//Roll and assign new target here.
				Play(voicePleaseShakeTheDice);
				Play(voiceYouRolled);
				randomSeed(analogRead(RANDOM_SEED));
				int targetExhibitionIndexRandom = random(1, 21);
				mp3IndexBufferString = String(targetExhibitionIndexRandom) + ".mp3";
				mp3IndexBufferString.toCharArray(mp3IndexBufferCharArray, 50);
				Play(mp3IndexBufferCharArray);

				/*
				Assign four target exhibitions here.
				The dice must be rolled to determine which path character/visitor is taking.
				*/
				if(targetExhibitionIndexRandom <= 10){
					targetExhibitionArray[0] = targetExhibitionDatabaseArray[mp3Index][0];
					targetExhibitionArray[1] = targetExhibitionDatabaseArray[mp3Index][1];
				}
				else if(targetExhibitionIndexRandom > 10){
					targetExhibitionArray[0] = targetExhibitionDatabaseArray[mp3Index][2];
					targetExhibitionArray[1] = targetExhibitionDatabaseArray[mp3Index][3];
				}

				Play(voicePleaseVisitAndTap);

				for(int i = 0; i < 2; i ++){

					if(targetExhibitionArray[i] != 0){

						mp3IndexBufferString = String(targetExhibitionArray[i]) + ".mp3";
						mp3IndexBufferString.toCharArray(mp3IndexBufferCharArray, 50);
						Play(mp3IndexBufferCharArray);

					}
					//If exhibition prime is the one of target exhibition.
					else{ Play(voicePrime); }

					if(i == 0){ Play(voiceOr); }

				}

				//Set the boolean variable to false again so that the visitor can visit the next destinated exhibition.
				haveVisitedTargetExhibition 	= false;
				//If this if statement is executed at least the prime exhibition has been visited.
				isPrimeExhibitionVisited 		= true;

			}
			else if(!haveVisitedTargetExhibition){

				Play(voicePleaseVisitAndTap);

				if(isPrimeExhibitionVisited){

					for(int i = 0; i < 2; i ++){

						if(targetExhibitionArray[i] != 0){

							mp3IndexBufferString = String(targetExhibitionArray[i]) + ".mp3";
							mp3IndexBufferString.toCharArray(mp3IndexBufferCharArray, 50);
							Play(mp3IndexBufferCharArray);

						}
						//If exhibition prime is the one of target exhibition.
						else{ Play(voicePrime); }

						if(i == 0){ Play(voiceOr); }

					}
				}
				else if(!isPrimeExhibitionVisited){
					Play(voicePrime);
				}
				
			}

		}

	}

}
int generatePrime(mpz_t *p,mpz_t *q,mpz_t *n,int number)
{
	int i;

	gmp_randstate_t rstate_p[number],rstate_q[number];

	for(i = 0; i < number; i++)
	{
		gmp_randinit_mt(rstate_p[i]);
		gmp_randinit_mt(rstate_q[i]);
	}


	for(i = 0; i < number; i++)
	{

		//Seeds to generate random number
		gmp_randseed_ui(rstate_p[i],randomSeed());
		gmp_randseed_ui(rstate_q[i],randomSeed());

		do{
			do{
				mpz_urandomb(*(p+i),rstate_p[i],32); // generate random number p less than 2^32-1

			}while(mpz_sizeinbase(*(p+i),2)!=32); //checks whether p is 32 bit or not


		}while(!isPrimeNumber(*(p+i)) || (!mpz_congruent_ui_p(*(p+i),3,4))); //checks whether p is prime or not with 500 witnesses


		do{
			do{
				mpz_urandomb(*(q+i),rstate_q[i],32); // generate random number q less than 2^32-1

			}while(mpz_sizeinbase(*(q+i),2)!=32); //checks whether p is 32 bit or not


		}while(!isPrimeNumber(*(q+i)) || (!mpz_congruent_ui_p(*(q+i),3,4))); //checks whether q is prime or not with 500 witnesses


		mpz_mul (*(n+i),*(p+i),*(q+i));

	}

/*	for(i = 0; i < number; i++)
	{
		//Seeds to generate random number
		gmp_randseed_ui(rstate_q[i],randomSeed());

		do{
			do{
				mpz_urandomb(*(q+i),rstate_q[i],32); // generate random number q less than 2^32-1

			}while(mpz_sizeinbase(*(q+i),2)!=32); //checks whether p is 32 bit or not


		}while(!isPrimeNumber(*(q+i)) || (!mpz_congruent_ui_p(*(q+i),3,4))); //checks whether q is prime or not with 500 witnesses

	}*/


	return TRUE;
}
Example #27
0
//init method for snow
//must be called before any method in this file
void s_init(){
	snow_set = (SnowSet*)calloc(1, sizeof(SnowSet));

	snow_set->max_lit = 255;

	snow_set->in_length = 1;
	snow_set->de_length = 20;
	snow_set->ch_length = 50;

	Color col = {.R = 255, .G = 255, .B = 255};
	change_snow_color(col);
	randomSeed(analogRead(0));
}

//main loop method for snow
//call this in loop to use this setup
void snow(){
	static unsigned long in_cur = 0, de_cur = 0, ch_cur = 0;
	SnowSet *ss = snow_set;
	bool bright = false, dark = false;

	if(ch_cur + ss->ch_length < millis()){
		ch_cur = millis();
		ss->cur_b[random(LENGTH)] = true;
	}

	//is it time to brighten?
	if(in_cur + ss->in_length < millis()){
		in_cur = millis();
		bright = true;
	}
	if(de_cur + ss->de_length < millis()){
		de_cur = millis();
		dark = true;
	}

	for(int i = 0; i < LENGTH; i++){
		//find which ones to brighten
		if(bright){
			if(ss->cur_b[i]){
			//is it already bright enough?
				if(ss->cur_lit[i] >= ss->max_lit){
					ss->cur_b[i] = false;
				}else{
					ss->cur_lit[i]++;
				}
			}
		}
		if(dark){
			if(!ss->cur_b[i]){
				if(ss->cur_lit[i] > 0){
					ss->cur_lit[i]--;
				}
			}
		}
		leds.setPixelColor(i,
			scale(ss->col.R, ss->cur_lit[i]),
			scale(ss->col.G, ss->cur_lit[i]),
			scale(ss->col.B, ss->cur_lit[i])
			);
	}

	leds.show();

}

void change_snow_color(Color col){
	snow_set->col = col;
}
Example #28
0
void setup() {
	Serial.begin(SERIAL_SPEED);

	randomSeed(analogRead(1));

	#ifdef DEBUG
		Serial.println("start test...");
		Serial.print(F(" CE="));
		Serial.print(PIN_CE);
		Serial.print(F(" CSN="));
		Serial.print(PIN_CSN);
		Serial.print(F(" MISO="));
		Serial.print(MISO);
		Serial.print(F(" MOSI="));
		Serial.print(MOSI);
		Serial.print(F(" SCK="));
		Serial.println(SCK);
	#endif

	#ifdef RTC_ENABLE
		rtc.init(90);
		uint32_t tmp = rtc.read();
		setTime(tmp);
		Serial.print(millis());
		Serial.print(F(": time is: "));
		Serial.print(tmp);
		Serial.print(F(" = "));

		tmElements_t tmElems;
		breakTime(tmp, tmElems);
		Serial.print((uint16_t) 1970 + tmElems.Year);
		Serial.print(F("/"));
		Serial.print(tmElems.Month);
		Serial.print(F("/"));
		Serial.print(tmElems.Day);
		Serial.print(F(" "));
		Serial.print(tmElems.Hour);
		Serial.print(F(":"));
		Serial.print(tmElems.Minute);
		Serial.print(F(":"));
		Serial.println(tmElems.Second);
	#endif


	//enable watchdog
	wdt_enable(WDTO_8S);

	//get address config
	getAddress();

	ram.init(RAM_MGR_SS_PIN, RAM_MGR_ADDRESS_WIDTH, RAM_MGR_RAM_LEN);


	#ifdef WEBSERVER_ENABLE
		webServerWrapper.init();
	#endif

	#ifdef SDCARD_ENABLE
		sdcard.initSD();
		discoveryManager.init();
		nodeInfo.init();
	#endif

	dispatcher.init();
	hwInterface.init();

	//init network
	l3.init(address_local);
	l2.init(&l3, PIN_CE, PIN_CSN, address_local);
	l3.setLayer2(&l2);

	dht11.init(A2, 20);

	#ifdef __AVR_ATmega2560__
	rcsw.init(14, 21);
	#else
	rcsw.init(A6, 21);
	#endif

	bmp180.init(80);
	motion.init(A3, 50);
	light.init(A7, 60);
	//mytone.init(A8, 70);

	#ifdef RTC_ENABLE
		hwInterface.registerDriver((HardwareDriver*) &rtc);
	#endif

	hwInterface.registerDriver((HardwareDriver*) &dht11);
	hwInterface.registerDriver((HardwareDriver*) &rcsw);
	hwInterface.registerDriver((HardwareDriver*) &motion);
	hwInterface.registerDriver((HardwareDriver*) &light);
	hwInterface.registerDriver((HardwareDriver*) &bmp180);
	//hwInterface.registerDriver((HardwareDriver*) &mytone);

	dispatcher.init(&l3, &hwInterface);

	#ifdef SDCARD_LOGGER_ENABLE
		dispatcher.getResponseHandler()->registerListenerByPacketType(0, HARDWARE_COMMAND_RES, 0, &sdlistener);
	#endif

	#ifdef TIMER_ENABLE
	timer.init();
	#endif

	/*/test rcsw
	//HardwareCommandResult cmd;
	//memset(&cmd, 0, sizeof(cmd));
	//cmd.setHardwareType(HWType_rcswitch);
	//cmd.setAddress(rcsw.getAddress());
	//cmd.setUint8ListNum(2);
	//cmd.getUint8List()[0] = 3;
	//cmd.getUint8List()[1] = 0;
	//hwInterface.executeCommand(&cmd);
	///*/


	/*
	SDcard::SD_nodeDiscoveryInfoTableEntry_t infos[2];
	infos[0].hardwareAddress = 0xAA;
	infos[0].hardwareType = 0xBB;
	infos[0].rtcTimestamp = 0xCC;
	infos[1].hardwareAddress = 0xDD;
	infos[1].hardwareType = 0xEE;
	infos[1].rtcTimestamp = 0xFF;
	sdcard.saveDiscoveryInfos(1, infos, 2);

	SDcard::SD_nodeDiscoveryInfoTableEntry_t discovery[SD_DISCOVERY_NUM_INFOS_PER_NODE];
	sdcard.getDiscoveryInfosForNode(1, discovery, SD_DISCOVERY_NUM_INFOS_PER_NODE);
	Serial.print(discovery[0].hardwareAddress);
	Serial.print(F(" "));
	Serial.print(discovery[0].hardwareType);
	Serial.print(F(" "));
	Serial.println(discovery[0].rtcTimestamp);
	Serial.print(discovery[1].hardwareAddress);
	Serial.print(F(" "));
	Serial.print(discovery[1].hardwareType);
	Serial.print(F(" "));
	Serial.println(discovery[1].rtcTimestamp);
	Serial.flush();
	*/

/*
	#ifdef SDCARD_ENABLE
		char buf[17];
		memset(buf, 0, sizeof(buf));
		Serial.print(millis());
		Serial.print(F(": nodeinfo"));
		if(sdcard.getNodeInfo(l3.localAddress, (uint8_t*) buf, sizeof(buf))) {
			buf[16] = '\0';
			Serial.print(F("=\""));
			Serial.print(buf);
			Serial.println(F("\""));
			} else {
			Serial.println(F(" not available"));
		}

		dispatcher.getResponseHandler()->registerListenerByPacketType(0, HARDWARE_COMMAND_RES, 0, &sdlistener);

		packet_application_numbered_cmd_t appPacket;
		memset(&appPacket, 0, sizeof(appPacket));
		appPacket.packetType = HARDWARE_COMMAND_RES;
		command_t* hwcmd = (command_t*) appPacket.payload;
		hwcmd->address = 10;
		hwcmd->type = HWType_rtc;
		hwcmd->numUint8 = 4;
		uint32_t now = rtc.read();
		hwcmd->uint8list[0] = now >> 24;
		hwcmd->uint8list[1] = (now >> 16) & 0xff;
		hwcmd->uint8list[2] = (now >> 8) & 0xff;
		hwcmd->uint8list[3] = now & 0xff;
		dispatcher.handleNumbered(13, HARDWARE_COMMAND_RES, 123, &appPacket);
		//sdlistener.doCallback(&appPacket, 17, 1234);
	#endif
*/

/*
	//mySimpleTimer = SimpleTimer::instance();

	//Serial.println("### testHardwareCommand: Tone ###");
	//Serial.flush();
	//testHardwareCommandTone();
//
//
	//Serial.println("### testHardwareCommand: Light ###");
	//Serial.flush();
	//testHardwareCommand(0, HWType_light, true);
	//testHardwareCommand(0, HWType_light, true);
	//testHardwareCommand(0, HWType_light, true);
//
	//Serial.println("### testHardwareCommand: Temperature ###");
	//Serial.flush();
	//testHardwareCommand(0, HWType_temprature, true);
//
	//Serial.println("### testHardwareCommand: Motion ###");
	//Serial.flush();
	//testHardwareCommand(0, HWType_motion, true);
//
	//Serial.println("### testHardwareCommandRead ###");
	//Serial.flush();
	//testHardwareCommandRead();
//
	//Serial.println("### testDiscovery ###");
	//Serial.flush();
	//testDiscovery();
//
	//Serial.println("### testSubscriptionSet ###");
	//Serial.flush();
	//testSubscriptionSet();
//
	//Serial.println("### testSubscriptionInfo ###");
	//Serial.flush();
	//testSubscriptionInfo();
//
	//Serial.println("### testSubscriptionExecution ###");
	//Serial.flush();
	//testSubscriptionExecution();
//
	//Serial.println("### testSubscriptionPolling ###");
	//Serial.flush();
	//testSubscriptionPolling();
//
	//Serial.println("### testSubscriptionPolling Light ###");
	//Serial.flush();
	//testSubscriptionPollingLight();
//
	////turn off LED
	//pinMode(LED_BUILTIN, LOW);*/
}
Example #29
0
void QTestLogger::stopLogging()
{
    QTestElement *iterator = listOfTestcases;

    if(format == TLF_XunitXml ){
        char buf[10];

        currentLogElement = new QTestElement(QTest::LET_TestSuite);
        currentLogElement->addAttribute(QTest::AI_Name, QTestResult::currentTestObjectName());

        QTest::qt_snprintf(buf, sizeof(buf), "%i", testCounter);
        currentLogElement->addAttribute(QTest::AI_Tests, buf);

        QTest::qt_snprintf(buf, sizeof(buf), "%i", failureCounter);
        currentLogElement->addAttribute(QTest::AI_Failures, buf);

        QTest::qt_snprintf(buf, sizeof(buf), "%i", errorCounter);
        currentLogElement->addAttribute(QTest::AI_Errors, buf);

        QTestElement *property;
        QTestElement *properties = new QTestElement(QTest::LET_Properties);

        property = new QTestElement(QTest::LET_Property);
        property->addAttribute(QTest::AI_Name, "QTestVersion");
        property->addAttribute(QTest::AI_PropertyValue, QTEST_VERSION_STR);
        properties->addLogElement(property);

        property = new QTestElement(QTest::LET_Property);
        property->addAttribute(QTest::AI_Name, "QtVersion");
        property->addAttribute(QTest::AI_PropertyValue, qVersion());
        properties->addLogElement(property);

        if (hasRandomSeed()) {
            property = new QTestElement(QTest::LET_Property);
            property->addAttribute(QTest::AI_Name, "RandomSeed");
            QTest::qt_snprintf(buf, sizeof(buf), "%i", randomSeed());
            property->addAttribute(QTest::AI_PropertyValue, buf);
            properties->addLogElement(property);
        }

        currentLogElement->addLogElement(properties);

        currentLogElement->addLogElement(iterator);

        /* For correct indenting, make sure every testcase knows its parent */
        QTestElement* testcase = iterator;
        while (testcase) {
            testcase->setParent(currentLogElement);
            testcase = testcase->nextElement();
        }

        currentLogElement->addLogElement(errorLogElement);

        QTestElement *it = currentLogElement;
        logFormatter->output(it);
    }else{
        logFormatter->output(iterator);
    }

    logFormatter->stopStreaming();
}
Example #30
0
/**
 * M48: Z probe repeatability measurement function.
 *
 * Usage:
 *   M48 <P#> <X#> <Y#> <V#> <E> <L#> <S>
 *     P = Number of sampled points (4-50, default 10)
 *     X = Sample X position
 *     Y = Sample Y position
 *     V = Verbose level (0-4, default=1)
 *     E = Engage Z probe for each reading
 *     L = Number of legs of movement before probe
 *     S = Schizoid (Or Star if you prefer)
 *
 * This function requires the machine to be homed before invocation.
 */
void GcodeSuite::M48() {

  if (axis_unhomed_error()) return;

  const int8_t verbose_level = parser.byteval('V', 1);
  if (!WITHIN(verbose_level, 0, 4)) {
    SERIAL_ECHOLNPGM("?(V)erbose level is implausible (0-4).");
    return;
  }

  if (verbose_level > 0)
    SERIAL_ECHOLNPGM("M48 Z-Probe Repeatability Test");

  const int8_t n_samples = parser.byteval('P', 10);
  if (!WITHIN(n_samples, 4, 50)) {
    SERIAL_ECHOLNPGM("?Sample size not plausible (4-50).");
    return;
  }

  const ProbePtRaise raise_after = parser.boolval('E') ? PROBE_PT_STOW : PROBE_PT_RAISE;

  float X_current = current_position[X_AXIS],
        Y_current = current_position[Y_AXIS];

  const float X_probe_location = parser.linearval('X', X_current + X_PROBE_OFFSET_FROM_EXTRUDER),
              Y_probe_location = parser.linearval('Y', Y_current + Y_PROBE_OFFSET_FROM_EXTRUDER);

  if (!position_is_reachable_by_probe(X_probe_location, Y_probe_location)) {
    SERIAL_ECHOLNPGM("? (X,Y) out of bounds.");
    return;
  }

  bool seen_L = parser.seen('L');
  uint8_t n_legs = seen_L ? parser.value_byte() : 0;
  if (n_legs > 15) {
    SERIAL_ECHOLNPGM("?Number of legs in movement not plausible (0-15).");
    return;
  }
  if (n_legs == 1) n_legs = 2;

  const bool schizoid_flag = parser.boolval('S');
  if (schizoid_flag && !seen_L) n_legs = 7;

  /**
   * Now get everything to the specified probe point So we can safely do a
   * probe to get us close to the bed.  If the Z-Axis is far from the bed,
   * we don't want to use that as a starting point for each probe.
   */
  if (verbose_level > 2)
    SERIAL_ECHOLNPGM("Positioning the probe...");

  // Disable bed level correction in M48 because we want the raw data when we probe

  #if HAS_LEVELING
    const bool was_enabled = planner.leveling_active;
    set_bed_leveling_enabled(false);
  #endif

  setup_for_endstop_or_probe_move();

  float mean = 0.0, sigma = 0.0, min = 99999.9, max = -99999.9, sample_set[n_samples];

  // Move to the first point, deploy, and probe
  const float t = probe_pt(X_probe_location, Y_probe_location, raise_after, verbose_level);
  bool probing_good = !isnan(t);

  if (probing_good) {
    randomSeed(millis());

    for (uint8_t n = 0; n < n_samples; n++) {
      if (n_legs) {
        const int dir = (random(0, 10) > 5.0) ? -1 : 1;  // clockwise or counter clockwise
        float angle = random(0, 360);
        const float radius = random(
          #if ENABLED(DELTA)
            (int) (0.1250000000 * (DELTA_PRINTABLE_RADIUS)),
            (int) (0.3333333333 * (DELTA_PRINTABLE_RADIUS))
          #else
            (int) 5.0, (int) (0.125 * MIN(X_BED_SIZE, Y_BED_SIZE))
          #endif
        );

        if (verbose_level > 3) {
          SERIAL_ECHOPAIR("Starting radius: ", radius);
          SERIAL_ECHOPAIR("   angle: ", angle);
          SERIAL_ECHOPGM(" Direction: ");
          if (dir > 0) SERIAL_ECHOPGM("Counter-");
          SERIAL_ECHOLNPGM("Clockwise");
        }

        for (uint8_t l = 0; l < n_legs - 1; l++) {
          float delta_angle;

          if (schizoid_flag)
            // The points of a 5 point star are 72 degrees apart.  We need to
            // skip a point and go to the next one on the star.
            delta_angle = dir * 2.0 * 72.0;

          else
            // If we do this line, we are just trying to move further
            // around the circle.
            delta_angle = dir * (float) random(25, 45);

          angle += delta_angle;

          while (angle > 360.0)   // We probably do not need to keep the angle between 0 and 2*PI, but the
            angle -= 360.0;       // Arduino documentation says the trig functions should not be given values
          while (angle < 0.0)     // outside of this range.   It looks like they behave correctly with
            angle += 360.0;       // numbers outside of the range, but just to be safe we clamp them.

          X_current = X_probe_location - (X_PROBE_OFFSET_FROM_EXTRUDER) + cos(RADIANS(angle)) * radius;
          Y_current = Y_probe_location - (Y_PROBE_OFFSET_FROM_EXTRUDER) + sin(RADIANS(angle)) * radius;

          #if DISABLED(DELTA)
            X_current = constrain(X_current, X_MIN_POS, X_MAX_POS);
            Y_current = constrain(Y_current, Y_MIN_POS, Y_MAX_POS);
          #else
            // If we have gone out too far, we can do a simple fix and scale the numbers
            // back in closer to the origin.
            while (!position_is_reachable_by_probe(X_current, Y_current)) {
              X_current *= 0.8;
              Y_current *= 0.8;
              if (verbose_level > 3) {
                SERIAL_ECHOPAIR("Pulling point towards center:", X_current);
                SERIAL_ECHOLNPAIR(", ", Y_current);
              }
            }
          #endif
          if (verbose_level > 3) {
            SERIAL_ECHOPGM("Going to:");
            SERIAL_ECHOPAIR(" X", X_current);
            SERIAL_ECHOPAIR(" Y", Y_current);
            SERIAL_ECHOLNPAIR(" Z", current_position[Z_AXIS]);
          }
          do_blocking_move_to_xy(X_current, Y_current);
        } // n_legs loop
      } // n_legs

      // Probe a single point
      sample_set[n] = probe_pt(X_probe_location, Y_probe_location, raise_after, 0);

      // Break the loop if the probe fails
      probing_good = !isnan(sample_set[n]);
      if (!probing_good) break;

      /**
       * Get the current mean for the data points we have so far
       */
      float sum = 0.0;
      for (uint8_t j = 0; j <= n; j++) sum += sample_set[j];
      mean = sum / (n + 1);

      NOMORE(min, sample_set[n]);
      NOLESS(max, sample_set[n]);

      /**
       * Now, use that mean to calculate the standard deviation for the
       * data points we have so far
       */
      sum = 0.0;
      for (uint8_t j = 0; j <= n; j++)
        sum += sq(sample_set[j] - mean);

      sigma = SQRT(sum / (n + 1));
      if (verbose_level > 0) {
        if (verbose_level > 1) {
          SERIAL_ECHO(n + 1);
          SERIAL_ECHOPAIR(" of ", (int)n_samples);
          SERIAL_ECHOPAIR_F(": z: ", sample_set[n], 3);
          if (verbose_level > 2) {
            SERIAL_ECHOPAIR_F(" mean: ", mean, 4);
            SERIAL_ECHOPAIR_F(" sigma: ", sigma, 6);
            SERIAL_ECHOPAIR_F(" min: ", min, 3);
            SERIAL_ECHOPAIR_F(" max: ", max, 3);
            SERIAL_ECHOPAIR_F(" range: ", max-min, 3);
          }
          SERIAL_EOL();
        }
      }

    } // n_samples loop
  }

  STOW_PROBE();

  if (probing_good) {
    SERIAL_ECHOLNPGM("Finished!");

    if (verbose_level > 0) {
      SERIAL_ECHOPAIR_F("Mean: ", mean, 6);
      SERIAL_ECHOPAIR_F(" Min: ", min, 3);
      SERIAL_ECHOPAIR_F(" Max: ", max, 3);
      SERIAL_ECHOLNPAIR_F(" Range: ", max-min, 3);
    }

    SERIAL_ECHOLNPAIR_F("Standard Deviation: ", sigma, 6);
    SERIAL_EOL();
  }

  clean_up_after_endstop_or_probe_move();

  // Re-enable bed level correction if it had been on
  #if HAS_LEVELING
    set_bed_leveling_enabled(was_enabled);
  #endif

  report_current_position();
}