How to pause a program for a few milliseconds? - c++

How to pause a program for a few milliseconds using C++ managed code?
I tried Sleep() but it didn't work when I included the winbase.h file, I got lots of compile errors!
for(int i=0; i<10; i++)
{
simpleOpenGlControl1->MakeCurrent();
System::Threading::Thread::Sleep(100);
theta_rotated += 2.0* 3.141592653/(double)Model->size()/10.0;
simpleOpenGlControl1->Invalidate();
}
private: System::Void simpleOpenGlControl1_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e)
{
Gl::glMatrixMode(Gl::GL_MODELVIEW);
Gl::glLoadIdentity();
Gl::glClearColor(1, 1, 1, 1);
Gl::glClear(Gl::GL_COLOR_BUFFER_BIT | Gl::GL_DEPTH_BUFFER_BIT);
camera->Tellgl();
Gl::glRotated(Angle,X,Y,Z);
RenderModels();
}
void RenderModels(void)
{
Points = gcnew System::Collections::Generic::List<Point>();
Point p(0,0) ;
int t = -5;
double r = 5;
double x, z, theta;
for(int i = 0;i < Model->size();i++)
{
theta = i*2* 3.141592653/ (double)Model->size();
x = r*sin(theta + theta_rotated);
z = r*cos(theta + theta_rotated);
Gl::glPushMatrix();
Gl::glTranslated(x,0,z);
Model->at(i).Render();
p.X=x;
p.Y=0;
Points->Add(p);
t +=1;
Gl::glPopMatrix();
}
//simpleOpenGlControl1->Invalidate();
}

You want System::Threading::Thread::Sleep().
http://msdn.microsoft.com/en-us/library/system.threading.thread.sleep.aspx

System::Threading::Thread::Sleep() as mentioned in another answer. But let me warn you, it is not precise, and for small (milliseconds) Sleep is extremely imprecise. consider that your app run together with other apps and threads and they all want processor time.

#include <unistd.h>
main() {
usleep(2000); // 2 msecs
}
Read the man pages ;-)
man 3 usleep

Related

Waiting-time of thread switches systematicly between 0 and 30000 microseconds for the same task

I'm writing a little Console-Game-Engine and for better performance I wanted 2 threads (or more but 2 for this task) using two buffers. One thread is drawing the next frame in the first buffer while the other thread is reading the current frame from the second buffer. Then the buffers get swapped.
Of cause I can only swap them if both threads finished their task and the drawing/writing thread happened to be the one waiting. But the time it is waiting systematicly switches more or less between two values, here a few of the messurements I made (in microseconds):
0, 36968, 0, 36260, 0, 35762, 0, 38069, 0, 36584, 0, 36503
It's pretty obvious that this is not a coincidence but I wasn't able to figure out what the problem was as this is the first time I'm using threads.
Here the code, ask for more if you need it, I think it's too much to post it all:
header-file (Manager currently only adds a pointer to my WinAppBase-class):
class SwapChain : Manager
{
WORD *pScreenBuffer1, *pScreenBuffer2, *pWritePtr, *pReadPtr, *pTemp;
bool isRunning, writingFinished, readingFinished, initialized;
std::mutex lockWriting, lockReading;
std::condition_variable cvWriting, cvReading;
DWORD charsWritten;
COORD startPosition;
int screenBufferWidth;
// THREADS (USES NORMAL THREAD AS SECOND THREAD)
void ReadingThread();
// THIS FUNCTION IS ONLY FOR INTERN USE
void SwapBuffers();
public:
// USE THESE TO CONTROL WHEN THE BUFFERS GET SWAPPED
void BeginDraw();
void EndDraw();
// PUT PIXEL | INLINED FOR BETTER PERFORMANCE
inline void PutPixel(short xPos, short yPos, WORD color)
{
this->pWritePtr[(xPos * 2) + yPos * screenBufferWidth] = color;
this->pWritePtr[(xPos * 2) + yPos * screenBufferWidth + 1] = color;
}
// GENERAL CONTROL OVER SWAP CHAIN
void Initialize();
void Run();
void Stop();
// CONSTRUCTORS
SwapChain(WinAppBase * pAppBase);
virtual ~SwapChain();
};
Cpp-file
SwapChain::SwapChain(WinAppBase * pAppBase)
:
Manager(pAppBase)
{
this->isRunning = false;
this->initialized = false;
this->pReadPtr = NULL;
this->pScreenBuffer1 = NULL;
this->pScreenBuffer2 = NULL;
this->pWritePtr = NULL;
this->pTemp = NULL;
this->charsWritten = 0;
this->startPosition = { 0, 0 };
this->readingFinished = 0;
this->writingFinished = 0;
this->screenBufferWidth = this->pAppBase->screenBufferInfo.dwSize.X;
}
SwapChain::~SwapChain()
{
this->Stop();
if (_CrtIsValidHeapPointer(pReadPtr))
delete[] pReadPtr;
if (_CrtIsValidHeapPointer(pScreenBuffer1))
delete[] pScreenBuffer1;
if (_CrtIsValidHeapPointer(pScreenBuffer2))
delete[] pScreenBuffer2;
if (_CrtIsValidHeapPointer(pWritePtr))
delete[] pWritePtr;
}
void SwapChain::ReadingThread()
{
while (this->isRunning)
{
this->readingFinished = 0;
WriteConsoleOutputAttribute(
this->pAppBase->consoleCursor,
this->pReadPtr,
this->pAppBase->screenBufferSize,
this->startPosition,
&this->charsWritten
);
memset(this->pReadPtr, 0, this->pAppBase->screenBufferSize);
this->readingFinished = true;
this->cvWriting.notify_all();
if (!this->writingFinished)
{
std::unique_lock<std::mutex> lock(this->lockReading);
this->cvReading.wait(lock);
}
}
}
void SwapChain::SwapBuffers()
{
this->pTemp = this->pReadPtr;
this->pReadPtr = this->pWritePtr;
this->pWritePtr = this->pTemp;
this->pTemp = NULL;
}
void SwapChain::BeginDraw()
{
this->writingFinished = false;
}
void SwapChain::EndDraw()
{
TimePoint tpx1, tpx2;
tpx1 = Clock::now();
if (!this->readingFinished)
{
std::unique_lock<std::mutex> lock2(this->lockWriting);
this->cvWriting.wait(lock2);
}
tpx2 = Clock::now();
POST_DEBUG_MESSAGE(std::chrono::duration_cast<std::chrono::microseconds>(tpx2 - tpx1).count(), "EndDraw wating time");
SwapBuffers();
this->writingFinished = true;
this->cvReading.notify_all();
}
void SwapChain::Initialize()
{
if (this->initialized)
{
POST_DEBUG_MESSAGE(Result::CUSTOM, "multiple initialization");
return;
}
this->pScreenBuffer1 = (WORD *)malloc(sizeof(WORD) * this->pAppBase->screenBufferSize);
this->pScreenBuffer2 = (WORD *)malloc(sizeof(WORD) * this->pAppBase->screenBufferSize);
for (int i = 0; i < this->pAppBase->screenBufferSize; i++)
{
this->pScreenBuffer1[i] = 0x0000;
}
for (int i = 0; i < this->pAppBase->screenBufferSize; i++)
{
this->pScreenBuffer2[i] = 0x0000;
}
this->pWritePtr = pScreenBuffer1;
this->pReadPtr = pScreenBuffer2;
this->initialized = true;
}
void SwapChain::Run()
{
this->isRunning = true;
std::thread t1(&SwapChain::ReadingThread, this);
t1.detach();
}
void SwapChain::Stop()
{
this->isRunning = false;
}
This is where I run the SwapChain-class from:
void Application::Run()
{
this->engine.graphicsmanager.swapChain.Initialize();
Sprite<16, 16> sprite(&this->engine);
sprite.LoadSprite("engine/resources/TestData.xml", "root.test.sprites.baum");
this->engine.graphicsmanager.swapChain.Run();
int a, b, c;
for (int i = 0; i < 60; i++)
{
this->engine.graphicsmanager.swapChain.BeginDraw();
for (c = 0; c < 20; c++)
{
for (a = 0; a < 19; a++)
{
for (b = 0; b < 10; b++)
{
sprite.Print(a * 16, b * 16);
}
}
}
this->engine.graphicsmanager.swapChain.EndDraw();
}
this->engine.graphicsmanager.swapChain.Stop();
_getch();
}
The for-loops above simply draw the sprite 20 times from the top-left corner to the bottom-right corner of the console - the buffers don't get swapped during that, and that again for a total of 60 times (so the buffers get swapped 60 times).
sprite.Print uses the PutPixel function of SwapChain.
Here the WinAppBase (which consits more or less of global-like variables)
class WinAppBase
{
public:
// SCREENBUFFER
CONSOLE_SCREEN_BUFFER_INFO screenBufferInfo;
long screenBufferSize;
// CONSOLE
DWORD consoleMode;
HWND consoleWindow;
HANDLE consoleCursor;
HANDLE consoleInputHandle;
HANDLE consoleHandle;
CONSOLE_CURSOR_INFO consoleCursorInfo;
RECT consoleRect;
COORD consoleSize;
// FONT
CONSOLE_FONT_INFOEX fontInfo;
// MEMORY
char * pUserAccessDataPath;
public:
void reload();
WinAppBase();
virtual ~WinAppBase();
};
There are no errors, simply this alternating waitng time.
Maybe you'd like to start by looking if I did the synchronisation of the threads correctly? I'm not exactly sure how to use a mutex or condition-variables so it might comes from that.
Apart from that it is working fine, the sprites are shown as they should.
The clock you are using may have limited resolution. Here is a random example of a clock provided by Microsoft with 15 ms (15000 microsecond) resolution: Why are .NET timers limited to 15 ms resolution?
If one thread is often waiting for the other, it is entirely possible (assuming the above clock resolution) that it sometimes waits two clockticks and sometimes none. Maybe your clock only has 30 ms resolution. We really can't tell from the code. Do you get more precise measurements elsewhere with this clock?
There are also other systems in play such as the OS scheduler or whatever controls your std::threads. That one is (hopefully) much more granular, but how all these interactions play out doesn't have to be obvious or intuitive.

glBeginQuery GL_OUT_OF_MEMORY error

I'm using glQuery for getting info about FPS count in my application:
CollectDataBegin();
/*all drawing operations with OpenGL*/
CollectDataEnd();
Where:
void RenderingInfo::CollectDataBegin()
{
//FPS begin
available = 0;
GLenum eError;
// UPDATE 1 START
if (!bQueryGenerated){
glGenQueries(1, queries);
bQueryGenerated = true;
}
// UPDATE 1 END
//GL_NO_ERROR from glGetError();
glBeginQuery(GL_TIME_ELAPSED, queries[0]);
//GL_OUT_OF_MEMORY error from glGetError();
//FPS end
}
void RenderingInfo::CollectDataEnd()
{
//FPS begin
glEndQuery(GL_TIME_ELAPSED);
iFramesCount++;
if (iFramesCount == 20)
{
iFramesCount = 0;
while (!available) {
glGetQueryObjectiv(queries[0], GL_QUERY_RESULT_AVAILABLE, &available);
}
glGetQueryObjectui64v(queries[0], GL_QUERY_RESULT, &timeElapsed);
float jeb = static_cast<float>(timeElapsed) / std::pow(10, 9);
xRenderStats.fFPS = static_cast<float>(1.0 / jeb);
sFPS = std::to_string(xRenderStats.fFPS);
// UPDATE 1 START
if (bQueryGenerated){
glDeleteQueries(1, queries);
bQueryGenerated = false;
}
// UPDATE 1 END
}
}
Private members of RenderingInfo class:
GLuint queries[] = {0};
GLint available = 0;
GLuint64 timeElapsed;
int iFramesCount = 0;
bool bQueryGenerated = false; //UPADTE 1
I wrote and tested this code using Nvidia GeForce GTX760 with newest drivers and I had no problems at all.
But after switching to my integrated Intel HD Graphics 4600 I'm recieving GL_OUT_OF_MEMORY after calling glBeginQuery(). Interesting thing is that I'm not getting this error right away but after making some calls to glBeginQuery().
I wasn't been able to find any posts related to this matter so I'm asking for Your help is solving this issue.
UPDATE 1:
I modified my code accoring to #Ike advices, but I'm still recieving an GL_OUT_OF_MEMORY error.
After removing the code associated with glQuery my app no longer produces GL_OUT_OF_MEMORY errors. Since I was using this funcionality for counting time in which single frame is rendered, I replaced it with more reliable method:
void RenderingInfo::CollectDataBegin()
{
//FPS begin
ctTimeBegin = clock();
//FPS end
}
void RenderingInfo::CollectDataEnd()
{
//FPS begin
ctTimeEnd = clock();
dElapsedTime += (static_cast<double>((ctTimeEnd - ctTimeBegin))/CLOCKS_PER_SEC);
iFramesCount++;
if (iFramesCount == 20)
{
if ((dElapsedTime / iFramesCount) < (1.0 / CLOCKS_PER_SEC)){
xRenderStats.fFPS = 60.0f;
}
else{
xRenderStats.fFPS = static_cast<float>(iFramesCount / dElapsedTime);
}
sFPS = std::to_string(xRenderStats.fFPS);
dElapsedTime = 0.0;
iFramesCount = 0;
}
//FPS end
}
Private RenderingInfo members:
int iFramesCount =0;
clock_t ctTimeBegin = 0;
clock_t ctTimeEnd = 0;
double dElapsedTime = 0.0;
This is not the answer for a question why I received GL_OUT_OF_MEMORY, but it's for showing a possible way out when someone will end up with the similar problem.

Setting a hardwarebreakpoint in multithreaded application doesn't fire

I wrote a little debugger for analysing and looging certain problems. Now I implemented a hardwarebreakpoint for detecting the access of a memory address being overwritten. When I run my debugger with a test process, then everything works fine. When I access the address, the breakpoint fires and the callstack is logged. The problem is, when I run the same against an application running multiple threads. I'm replicating the breakpoint into every thread that gets created and also the main thread. None of the functions report an error and everything looks fine, but when the address is accessed, the breakpoint never fires.
So I wonder if there is some documentation where this is described or if there are additionaly things that I have to do in case of a multithreaded application.
The function to set the breakpoint is this:
#ifndef _HARDWARE_BREAKPOINT_H
#define _HARDWARE_BREAKPOINT_H
#include "breakpoint.h"
#define MAX_HARDWARE_BREAKPOINT 4
#define REG_DR0_BIT 1
#define REG_DR1_BIT 4
#define REG_DR2_BIT 16
#define REG_DR3_BIT 64
class HardwareBreakpoint : public Breakpoint
{
public:
typedef enum
{
REG_INVALID = -1,
REG_DR0 = 0,
REG_DR1 = 1,
REG_DR2 = 2,
REG_DR3 = 3
} Register;
typedef enum
{
CODE,
READWRITE,
WRITE,
} Type;
typedef enum
{
SIZE_1,
SIZE_2,
SIZE_4,
SIZE_8,
} Size;
typedef struct
{
void *pAddress;
bool bBusy;
Type nType;
Size nSize;
Register nRegister;
} Info;
public:
HardwareBreakpoint(HANDLE hThread);
virtual ~HardwareBreakpoint(void);
/**
* Sets a hardware breakpoint. If no register is free or an error occured
* REG_INVALID is returned, otherwise the hardware register for the given breakpoint.
*/
HardwareBreakpoint::Register set(void *pAddress, Type nType, Size nSize);
void remove(void *pAddress);
void remove(Register nRegister);
inline Info const *getInfo(Register nRegister) const { return &mBreakpoint[nRegister]; }
private:
typedef Breakpoint super;
private:
Info mBreakpoint[MAX_HARDWARE_BREAKPOINT];
size_t mRegBit[MAX_HARDWARE_BREAKPOINT];
size_t mRegOffset[MAX_HARDWARE_BREAKPOINT];
};
#endif // _HARDWARE_BREAKPOINT_H
void SetBits(DWORD_PTR &dw, size_t lowBit, size_t bits, size_t newValue)
{
DWORD_PTR mask = (1 << bits) - 1;
dw = (dw & ~(mask << lowBit)) | (newValue << lowBit);
}
HardwareBreakpoint::HardwareBreakpoint(HANDLE hThread)
: super(hThread)
{
mRegBit[REG_DR0] = REG_DR0_BIT;
mRegBit[REG_DR1] = REG_DR1_BIT;
mRegBit[REG_DR2] = REG_DR2_BIT;
mRegBit[REG_DR3] = REG_DR3_BIT;
CONTEXT ct;
mRegOffset[REG_DR0] = reinterpret_cast<size_t>(&ct.Dr0) - reinterpret_cast<size_t>(&ct);
mRegOffset[REG_DR1] = reinterpret_cast<size_t>(&ct.Dr1) - reinterpret_cast<size_t>(&ct);
mRegOffset[REG_DR2] = reinterpret_cast<size_t>(&ct.Dr2) - reinterpret_cast<size_t>(&ct);
mRegOffset[REG_DR3] = reinterpret_cast<size_t>(&ct.Dr3) - reinterpret_cast<size_t>(&ct);
memset(&mBreakpoint[0], 0, sizeof(mBreakpoint));
for(int i = 0; i < MAX_HARDWARE_BREAKPOINT; i++)
mBreakpoint[i].nRegister = (Register)i;
}
HardwareBreakpoint::Register HardwareBreakpoint::set(void *pAddress, Type nType, Size nSize)
{
CONTEXT ct = {0};
super::setAddress(pAddress);
ct.ContextFlags = CONTEXT_DEBUG_REGISTERS;
if(!GetThreadContext(getThread(), &ct))
return HardwareBreakpoint::REG_INVALID;
size_t iReg = 0;
for(int i = 0; i < MAX_HARDWARE_BREAKPOINT; i++)
{
if (ct.Dr7 & mRegBit[i])
mBreakpoint[i].bBusy = true;
else
mBreakpoint[i].bBusy = false;
}
Info *reg = NULL;
// Address already used?
for(int i = 0; i < MAX_HARDWARE_BREAKPOINT; i++)
{
if(mBreakpoint[i].pAddress == pAddress)
{
iReg = i;
reg = &mBreakpoint[i];
break;
}
}
if(reg == NULL)
{
for(int i = 0; i < MAX_HARDWARE_BREAKPOINT; i++)
{
if(!mBreakpoint[i].bBusy)
{
iReg = i;
reg = &mBreakpoint[i];
break;
}
}
}
// No free register available
if(!reg)
return HardwareBreakpoint::REG_INVALID;
*(void **)(((char *)&ct)+mRegOffset[iReg]) = pAddress;
reg->bBusy = true;
ct.Dr6 = 0;
int st = 0;
if (nType == CODE)
st = 0;
if (nType == READWRITE)
st = 3;
if (nType == WRITE)
st = 1;
int le = 0;
if (nSize == SIZE_1)
le = 0;
else if (nSize == SIZE_2)
le = 1;
else if (nSize == SIZE_4)
le = 3;
else if (nSize == SIZE_8)
le = 2;
SetBits(ct.Dr7, 16 + iReg*4, 2, st);
SetBits(ct.Dr7, 18 + iReg*4, 2, le);
SetBits(ct.Dr7, iReg*2, 1, 1);
ct.ContextFlags = CONTEXT_DEBUG_REGISTERS;
if(!SetThreadContext(getThread(), &ct))
return REG_INVALID;
return reg->nRegister;
}
I'm setting the breakpoint in the main debugger loop whenever a new thread is created CREATE_THREAD_DEBUG_EVENT but looking at the sourcecode of GDB it seems not to be done there, so maybe that is to early?
So I finally found the answer to this problem.
In the debug event loop, I'm monitoring the events that windows sends me. One of those events is CREATE_THREAD_DEBUG_EVENT which I used to set the hardware breakpoint whenever a new thread was created.
The problem is, that the notification of this event comes before the thread got actually started. So Windows is setting the context for the first time AFTER this event is sent, which of course overwrites any context data that I have set before.
The solution I implemented now is, when a CREATE_THREAD_DEBUG_EVENT comes I put a software breakpoint at the start adress of the thread, so that the first instruction is my breakpoint. When I receive the breakpoint event, I restore the original code and install the hardware breakpoint, which now fires fine.
If there is a better solution, I'm all ears. :)

Can Allegro update the number of joysticks at runtime?

Is there a way to update the number of joysticks plugged in at run-time other than constantly calling remove_joystick() then install_joystick? This proves to be extremely slow (goes from 60 FPS to around 5).
Allegro 4.2 answers only please...
void Joystick::Update() {
//If joystick input was lost, attempt to reacquire.
if(GetNumJoysticks() == 0) {
throw InputNotAvailableException("Joystick");
}
//If all joysticks were deleted remove input and do nothing.
if(_numjoysticks == 0) {
remove_joystick();
return;
}
//Update state information
if(poll_joystick() < 0) {
throw InputNotAvailableException("Joystick");
}
for(int i = 0; i < _numButtons; ++i) {
_prevButtons[i].b = _curButtons[i].b;
_prevButtons[i].name = _curButtons[i].name;
_curButtons[i].b = joy[_joyNumber].button[i].b;
_curButtons[i].name = joy[_joyNumber].button[i].name;
}
for(int i = 0; i < _numSticks; ++i) {
for(int j = 0; j < joy[_joyNumber].stick[i].num_axis; ++j) {
_prevSticks[i].axis[j].name = _curSticks[i].axis[j].name;
_prevSticks[i].axis[j].pos = _curSticks[i].axis[j].pos;
_prevSticks[i].axis[j].d1 = _curSticks[i].axis[j].d1;
_prevSticks[i].axis[j].d2 = _curSticks[i].axis[j].d2;
_curSticks[i].axis[j].name = joy[_joyNumber].stick[i].axis[j].name;
_curSticks[i].axis[j].pos = joy[_joyNumber].stick[i].axis[j].pos;
_curSticks[i].axis[j].d1 = joy[_joyNumber].stick[i].axis[j].d1;
_curSticks[i].axis[j].d2 = joy[_joyNumber].stick[i].axis[j].d2;
}
_prevSticks[i].flags = _curSticks[i].flags;
_prevSticks[i].name = _curSticks[i].name;
_curSticks[i].flags = joy[_joyNumber].stick[i].flags;
_curSticks[i].name = joy[_joyNumber].stick[i].name;
}
}
int Joystick::GetNumJoysticks() {
remove_joystick();
if(install_joystick(JOY_TYPE_DIRECTX)) {
return 0;
}
return (num_joysticks);
}
The 4.x series does not. The 5.x series does.
You'll have to either listen for native OS events using custom platform specific code (assuming such things exist) and only call the Allegro deinit/init functions when a change is detected, or require the user to initiate joystick refresh manually.
Under Linux, you could inotify_add_watch() /dev/input to check for changes. Looking at the 4.4 Allegro code, looks like you'd want to call the Win32 functions joyGetNumDevs() and joyGetPos(). Something like:
int WIN_MAX_JOYSTICKS = joyGetNumDevs(); // this should never change
JOYINFO ji;
int pluggedin_count = 0;
for (int i = 0; i < WIN_MAX_JOYSTICKS; ++i)
if (joyGetPos(i, &ji) == JOYERR_NOERROR) ++pluggedin_count;
if (pluggedin_count != last_pluggedin_count) /* reinit Allegro */
You'd have to do that every N seconds.
Those joy* functions are Windows functions, so read MSDN docs to learn how to use them.

Error in Arduino programming

I am receiving the following error:
error: expected constructor, destructor, or type conversion before ‘(’ token
Here is the source code that I have written:
void setup() {
pinMode(1,OUTPUT);
[...]
pinMode(13,INPUT);
}
int i = 1;
bool pushed = digitalRead(13);
bool val = 0;
randomSeed(analogRead(0));
void loop() {
if (pushed == 1) {
for (i = 1; i < 9; i++) {
val = random(2);
digitalWrite(i,val);
}
}
}
The variables and the setup are OK; the error is located on the for line. Can anyone tell me how to fix this?
(edit : added the begining of the script, and sorry for the presentation (first question here)
(edit : looks like the error is not in the "i" definition. I'm using an Arduino UNO SMD Edition, if that helps (and the arduino alpha 0022 linux version of the IDE) )
EDIT: okay guys, solved now. It appears that my version of Arduino IDE was not completely downloaded, and that I put the randomSeed in the wrong place (it should be in the setup function.) (when i did put it in the setup function before updating, it shown an error message, saying /opt/arduino/lib/math.h was missing something (or something like that, i don't have the full message) ). Thanks for your help and i hope i'll be able to help you in arduino soon!
for (int i = 1; i < 9; i++)
is valid in C99/C11 but not valid in C89.
If you use a C89 compiler you have to define i outside the for loop clauses:
int i;
for (i = 1; i < 9; i++)
Also in C89, all declarations have to follow the left brace of a block, you cannot freely mix declarations and statements.
You appear to have a statement randomSeed(analogRead(0)); floating in between your setup() and loop() function definitions.
Move it and any other IO operations to the end of the setup() function so you read after setting up the pin directions:
int i = 1;
bool pushed;
bool val = 0;
void setup() {
pinMode(1,OUTPUT);
[...]
pinMode(13,INPUT);
pushed = digitalRead(13);
randomSeed(analogRead(0));
}
void loop() {
if (pushed == 1) {
for (i = 1; i < 9; i++) {
val = random(2);
digitalWrite(i,val);
}
}
}
That will reading the value of pin 13 into pushed only once ( e.g. you are holding a button when powering it on ); depending what you want it to do you may want to move the read to the start of loop() so writes random values whenever the button is pressed.
In C (previous to C99), it's not permissible to define a new variable in the first expression of a for loop. Try declaring your variable i at the top of the function instead.
#define pinMode1 1
#define pinMode2 13
bool pushed;
bool val = 0;
void setup() {
// Declare OUTPUT pin.
pinMode(pinMode1, OUTPUT);
// Declare INPUT pin.
pinMode(pinMode2, INPUT);
// Set digitalRead().
pushed = digitalRead(pinMode2);
// Initializes the pseudo-random number generator.
randomSeed(analogRead(0));
}
void loop() {
if (pushed == 1) {
for (int i = 1; i < 9; i++) {
val = random(2);
// Set i to HIGH or LOW.
digitalWrite(i, val);
}
}
}