I am trying to insert a processing sketch into my wordpress blog using processing.js.
The problem is that I am getting a frozen image instead of a moving one. Its as if the draw function is not looping.
(On my pc the sketch works fine)
what could be the cause of it ? and how can i fix it ?
<script type="text/processing" data-processing-target="MySketch">
ball[] balls;
int numBalls = 20;
void setup(){
size (300,300,P3D);
background(255);balls=new ball[numBalls];
for(int i=0; i<numBalls;i++){
float r=random(5,20);
balls[i] = new ball(random(r,width-r),random(r,height-r),0,r,random(-1,10),random(-1,10));
}
}
void draw(){
background(255);
for(int i=0; i<numBalls;i++){
ball b; b=balls[i];
b.drawBall();
b.moveBall();
b.boundaries();
}
}
class ball{
float x;
float y;
float z;
float r;
float vx;
float vy;
ball(float x1,float y1,float z1,float r1,float vx1,float vy1 ){
x=x1;
y=y1;
z=z1;
r=r1;
vx=vx1;
vy=vy1;
}
void drawBall(){
noStroke();
fill(255,0,0);
lights();
pushMatrix();
translate(x, y,z);
sphere(r);
popMatrix();
}
void moveBall(){
x=x+vx;
y=y+vy;
}
void boundaries(){
if(x>=width-r || x<0+r)
vx=vx*-1;
if(y>=height-r || y<0+r)
vy=vy*-1;
}
}
</script>
<canvas id="MySketch"></canvas>
Your first stop should be the JavaScript console. That's where any errors you're getting will show up. On most browsers you can just push the F12 key, or find it in your developer settings in the menu.
When I run your code and look at the JavaScript browser, I see this error: Uncaught can only create 8 lights.
What I gather from that error is the browser can only handle drawing 8 lights, but you're trying to create more. It works fine on your PC because you're probably using Java mode, which does not have the same restrictions.
If that's the case, the only thing you can do is decrease the number of lights you're drawing.
Related
i am trying to make a stopwatch and counter project for arduino. Code aside, is this wired correctly?
The top button is to start the stopwatch, second is the button to start the counter (every press increases by one), and the bottom button should be to reset any of them. the green light is to show the stopwatch is selected and blue is to show the counter is selected. the lcd is to display everything obviusly. Also, what is the best way to learn to code this and how long would it take? Thanks.
This is the code as per your requirement. I have defined pins as per above connections. counter mode has minutes and seconds and it does not contain milliseconds as I am encountering problem to implement it. You can suggest me if you have got any way. Counter mode selection button is the same button which is going to be used to increment the counter.
#include <LiquidCrystal.h>
LiquidCrystal mylcd(7,6,5,4,3,2);
int counter_sel=12,stopwatch_sel=11,reset1=10,stopwatch_led=9,counter_led=8;
void setup()
{
mylcd.begin(16,2);
mylcd.setCursor(0,0);
mylcd.print("Counter and ");
mylcd.print("Stopwatch");
delay(1000);
pinMode(counter_sel,INPUT);
pinMode(stopwatch_sel, INPUT);
pinMode(reset1, INPUT);
pinMode(counter_led,OUTPUT);
pinMode(stopwatch_led, OUTPUT);
}
void loop()
{ int state1=digitalRead(counter_sel);
int state2=digitalRead(stopwatch_sel);
if (state1==0) {delay(300); counter(); } // call counter function
else if (state2==0) {delay(300); stopwatch(); } // call stopwatch function
}
void counter()
{ mylcd.clear();
digitalWrite(counter_led,1);
mylcd.setCursor(0,0);
mylcd.print("Counter Mode :");
short int i=0;
while(1)
{
int rst=digitalRead(reset1);
if (rst==0) { delay(300); break;}
int state1=digitalRead(counter_sel);
if (state1==0) { i++; delay(200);}
mylcd.setCursor(0,1);
mylcd.print(i);
}
digitalWrite(counter_led,0);
}
void stopwatch()
{
mylcd.clear();
digitalWrite(stopwatch_led,1);
long int ms=millis();
byte sec=0, mins=0;
mylcd.setCursor(0,0);
mylcd.print("Stopwatch Mode : ");
while(1)
{
mylcd.setCursor(0,1);
int state1=digitalRead(reset1);
if (state1==0){delay(300); break; }
if (sec==59) {mins++; sec=0;}
if ((millis()-ms)>1000) {sec++; ms=millis(); }
mylcd.print(mins);
mylcd.setCursor(3,1);
mylcd.print(":");
mylcd.setCursor(5,1);
mylcd.print(sec);
mylcd.print(":");
//mylcd.print(millis()-ms);
}
digitalWrite(stopwatch_led,0);
}
As much as I can see, and considering what you explained above, the connections are correct. But the thing is you need to make it clear as much as you can, because due to intersecting point in LCD connection, it would be very much harder to debug and resolve the connection problem, for that you must make it neat. To learn to code this stuff there is no rocket science, just use your wisdom, and start reading books, blogs, articles on arduino ide(which is too simple too use), c programming and microcontrollers , and youtube videos are the great source to learn to code, you should have handful experience of c programming, that's all.
Qt: 5.14.1
SDL: 2.0.12
OS: Windows 10
I'm working on a video player and I'm using Qt for UI and SDL for rendering frames.
I created the SDL window by passing my rendering widget's (inside a layout) winId() handle.
This works perfectly when I start a non-threaded Play().
However, this causes some issues with playback when resizing or moving the app window. Nothing serious, but since the play code is non threaded my frame queues fill-up which then causes the video to speed up until it catches to the audio.
I solved that by putting my play code inside Win32 thread created with CreateThread function.
Now when I move window the video continues to play as intended, but when resizing the app, rendering widget will stop refreshing the widget and only the last displayed frame before resize event will be shown.
I can confirm that video is still running and correct frames are still being displayed. The displayed image can even be resized, but its never refreshed.
The similar thing happens when I was testing Qt threads with SDL. Consider this code
class TestThread: public QThread
{
public:
TestThread(QObject *parent = NULL) : QThread(parent)
{
}
void run() override
{
for (;;)
{
SDL_Delay(1000/60);
// Basic square bouncing animation
SDL_Rect spos;
spos.h = 100;
spos.w = 100;
spos.y = 100;
spos.x = position;
SDL_SetRenderDrawColor(RendererRef, 0, 0, 0, 255);
SDL_RenderFillRect(RendererRef, 0);
SDL_SetRenderDrawColor(RendererRef, 0xFF, 0x0, 0x0, 0xFF);
SDL_RenderFillRect(RendererRef, &spos);
SDL_RenderPresent(RendererRef);
if (position >= 500)
dir = 0;
else if (position <= 0)
dir = 1;
if (dir)
position += 5;
else
position -= 5;
}
}
};
// a call from Init SDL and Start Thread button
...
// create new SDL borderless resizible window.
WindowRef = SDL_CreateWindow("test",10,10,1280,800,SDL_WINDOW_RESIZABLE | SDL_WINDOW_BORDERLESS);
// create and start thread
test_thread = new TestThread();
test_thread->start();
...
This will create a separate window from the Qt app window and will start rendering a bouncy square. However if any resize event occurs in the Qt app, the rendering context will be lost and the the same thing that happens in my video player will happen here.
I also found out that If I remove SDL_RenderPresent function from the Thread object and put it in a Main Qt Window, the rendering will continue after resize event. However this has proved as completely unreliable and will sometimes completely freeze my app.
I also can't figure out why my completely separate SDL window and renderer still freezes on resize.
I presume there is a clash somewhere with SDL renderer/window and Qt's drawing stuff, but I'm at a loss here.
Also, it's only the resize stuff. Everything else works.
Thanks.
Answer:
SDL_Renderer needs to be destroyed and recreated on window resize as well as any SDL_Texture created with previous renderer.
The same thing will happen even without qt.
However, I think this is just a workaround and not a real solution.
A simple code to recreate the issue.
int position = 0;
int dir = 0;
SDL_Window *window = NULL;
SDL_Renderer *sdlRenderer_ = NULL;
DWORD WINAPI MyThreadFunction( LPVOID lpParam )
{
for (;;)
{
SDL_Delay(1000/60);
// Basic square bouncing animation
SDL_Rect spos;
spos.h = 100;
spos.w = 100;
spos.y = 100;
spos.x = position;
SDL_SetRenderDrawColor(sdlRenderer_, 0, 0, 0, 255);
SDL_RenderFillRect(sdlRenderer_, 0);
SDL_SetRenderDrawColor(sdlRenderer_, 0xFF, 0x0, 0x0, 0xFF);
SDL_RenderFillRect(sdlRenderer_, &spos);
SDL_RenderPresent(sdlRenderer_);
if (position >= 500)
dir = 0;
else if (position <= 0)
dir = 1;
if (dir)
position += 5;
else
position -= 5;
}
}
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine,_In_ int nCmdShow)
{
SDL_Init(SDL_INIT_VIDEO);
window = SDL_CreateWindow("test",SDL_WINDOWPOS_UNDEFINED,SDL_WINDOWPOS_UNDEFINED,600,600,SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE);
if (!window)
printf("Unable to create window");
sdlRenderer_ = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED |SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE);
if (!sdlRenderer_)
printf("Unable to create renderer");
HANDLE playHandle = CreateThread(0, 0, MyThreadFunction, 0, 0, 0);
if (playHandle == NULL)
{
return 0;
}
SDL_Event e;
while(1)
{
SDL_PollEvent(&e);
if (e.type == SDL_WINDOWEVENT )
{
switch( e.window.event )
{
case SDL_WINDOWEVENT_SIZE_CHANGED:
int mWidth = e.window.data1;
int mHeight = e.window.data2;
SDL_DestroyRenderer(sdlRenderer_); // stops rendering on resize if commented out
sdlRenderer_ = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED |SDL_RENDERER_PRESENTVSYNC | SDL_RENDERER_TARGETTEXTURE);
break;
}
}
}
return 0;
}
EDIT:
Real solution.
Renderer doesn't need to be recreated. Seperate the Qt code from SDL main thread by making a seperate thread. Create all SDL stuff in that thread because SDL_Renderer needs to be created in a thread that handles SDL events.
Use SDL_PushEvent to signal this thread to render to screen.
This way textures don't need to be recreated.
I'm trying to work with a simple Arduino circuit that increments a counter variable on pressing a push button in the circuit (connected as INPUT to PIN 8). My code is as simple as follows:
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);
int c = 0, btnPIN, btnVal;
void setup ()
{
btnPIN = 8;
pinMode(btnPIN, INPUT);
lcd.begin(16,2);
lcd.clear();
}
void void loop()
{
btnVal = digitalRead(btnPIN);
if (btnVal == LOW)
{
c++;
lcd.clear();
lcd.print(c);
}
}
Problem is the counter increases by more than 1 every time I push the button. A little bit of printing on the serial monitor indicates that each time the button is pressed and the voltage is LOW, the conditional code is executed multiple times and the counter increases by multiple times instead of 1.
Maybe, I need to write some logic that checks if the button was initially unpressed, then pushed and then released again and then these steps would trigger the required action.
The solution I'm currently working with is as under (which works just fine):
int btnStatus = 0;
void loop()
{
btnVal = digitalRead(btnPIN);
if (btnVal == LOW)
btnStatus = 1;
if(btnStatus == 1 && btnVal == HIGH)
{
c++;
lcd.clear();
lcd.print(c);
btnStatus = 0;
}
}
I'm not sure if there's a simpler solution available or if this approach is wrong for other reasons? Any advice would be most welcome!
Another problem you you may be having is that mechanical buttons bounce. That is, they jump between two positions several times quickly before settling to a final position. This is standard operation so it is necessary to "debounce" the button.
There are very many ways to do this, but Here is a tutorial using an Arduino.
The main issue, as you probably figured out, is that the loop function is getting called multiple times while the button is down. This is what is fixed by your code, and yours looks to be a good solution and I don't really see a simpler way. For another way, though, perhaps you could try just adding a call to delay at the end of loop to slow it down a bit. You would have to play with the delay amount a bit, but it could work. Really though, your solution looks just fine.
Your idea is correct, you need to track the previous state of the button to know if it is a new press or if it is simply being held down. Your code could be rewritten to look more like a state machine, however:
typedef enum {
BTN_STATE_RELEASED,
BTN_STATE_PRESSED
} ButtonState;
ButtonState btnStatus = BTN_STATE_RELEASED;
void increment_counter()
{
c++;
lcd.clear();
lcd.print(c);
}
void loop()
{
btnVal = digitalRead(btnPIN);
switch(btnStatus)
{
case BTN_STATE_PRESSED:
// Handle button release
if(btnVal == HIGH)
{
btnStatus = BTN_STATE_RELEASED;
}
break;
case BTN_STATE_RELEASED:
// Handle button press
if(btnVal == LOW)
{
increment_counter();
btnStatus = BTN_STATE_PRESSED;
}
break;
}
}
This was rewritten to use an enum to track the state of the system (a bit overkill for a simple button, but an important concept to know in case your system grows more complex).
The code to update the display was also moved into its own function to make it better separated between the display change and the actual update of the state.
I'm making a program that will display a few images from a directory beside each other.
When I scale the images to fit within the height of the window (ie - QGraphicsPixmapItem->scale(...)), it runs fairly well in windows, but runs unbearably slow in linux (Ubuntu 11.04).
If the images are not scaled, performance is similar on both systems.
I'm not sure if it has to do with the way each OS caches memory, since when I run the program under Linux, the memory used is always constant and around 5mb, when it's closer to 15-30mb under Windows depending on the images loaded.
Here is the related code:
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent)
{
scene = new QGraphicsScene(this);
view = new QGraphicsView(scene);
setCentralWidget(view);
setWindowTitle(tr("ImgVw"));
bestFit = true;
view->setHorizontalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
view->setVerticalScrollBarPolicy ( Qt::ScrollBarAlwaysOff );
view->setDragMode(QGraphicsView::ScrollHandDrag);
view->setStyleSheet( "QGraphicsView { border-style: none; padding: 5px; background-color: #000; }" ); // set up custom style sheet
// Get image files from folder
QDir dir("test_img_folder");
QStringList fileList = dir.entryList();
fileList = fileList.filter(QRegExp(".*(\.jpg|\.jpeg|\.png)$"));
// Create graphics item for each image
int count = 0;
foreach(QString file, fileList)
{
if (count >= 0)
{
QPixmap g(dir.absolutePath() + QString("/") + file);
scene->addPixmap(g);
}
count++;
if (count >= 5) break;
}
}
void MainWindow::resizeEvent(QResizeEvent *event)
{
int pos = 0;
foreach(QGraphicsItem *item, scene->items(Qt::AscendingOrder))
{
double ratio = 1.0;
QGraphicsPixmapItem *pixmapItem = (QGraphicsPixmapItem*) item;
// Resize to fit to window
if (bestFit) {
double h = (double) (view->height()-10)/pixmapItem->pixmap().height();
ratio = min(h, 1.0);
pixmapItem->setScale(ratio);
}
// Position 5 pixels to the right of the previous image
item->setPos(pos,0);
pos += pixmapItem->pixmap().width()*ratio + 5;
}
// Resize scene to fit items
scene->setSceneRect(scene->itemsBoundingRect());
}
You could try different graphicssystems e.g. with the command line switch -graphicssystem raster|native|opengl or by setting the environment variable QT_GRAPHICSSYSTEM to "raster" etc.
In my experience, I agree with trying the QT_GRAPHICSSYSTEM environment variable hack. It took me some time in development of a new real-time QT4 application, with high bandwidth callbacks, to discover that setting QT_GRAPHICSSYSTEM = 'raster', prevented my RedHat Linux X11 system from gobbling up CPU time. So I suspect there is a resource issue when QT_GRAPHICSSYSTEM is not set or set to 'native'.
I'm trying to read data from a photocell resistor and my Arduino Diecimila and then graph it in real-time with Processing.
It should be painfully simple; but it’s growing into a little bit of a nightmare for me.
The code I'm running on my Arduino:
int photoPin;
void setup(){
photoPin = 0;
Serial.begin(9600);
}
void loop(){
int val = int(map(analogRead(photoPin), 0, 1023, 0, 254));
Serial.println(val); // Sending data over Serial
}
The code I'm running in Processing:
import processing.serial.*;
Serial photocell;
int[] yvals;
void setup(){
size(300, 150);
photocell = new Serial(this, Serial.list()[0], 9600);
photocell.bufferUntil(10);
yvals = new int[width];
}
void draw(){
background(0);
for( int i = 1; i < width; i++ ){
yvals[i - 1] = yvals[i];
}
if(photocell.available() > 0){
yvals[width - 1] = photocell.read();
}
for(int i = 1; i < width; i++){
stroke(#ff0000);
line(i, yvals[i], i, height);
}
println(photocell.read()); // For debugging
}
I've tested both bits of code separately, and I know that they work. It's only when I try to have the input from the Arduino going to Processing that the problems start.
When I view the data in Arduino's "Serial Monitor", I get a nice constant flow of data that seems to look valid.
But when I read that same data through Processing, I get a repeating pattern of random values.
After a closer look at the resources at hand, I realized that the problem had already been solved for me by the folks over at http://arduino.cc
http://arduino.cc/en/Tutorial/Graph
Oh how much time I could have saved if I had seen that earlier.
You could transmit that data with the Plotly Arduino API, which along with the documentation and setup is available here. Basic idea: you can continuously stream data from your Arduino, or transmit a single chunk.
Then, if you want to embed it into a site, you'll want to grab the URL and use this snippet:
<iframe id="igraph"
src="https://plot.ly/~abhishek.mitra.963/1/400/250/"
width="400"
height="250"
seamless="seamless"
scrolling="no"></iframe>
You can change the width/height dimensions in that snippet. Note: you need to swap in your own URL there to get it stream through.
Here's an example of how it looks to stream Arduino data
Full disclosure: I work for Plotly.