Running and stopping a processing code automatically - timer

What i wanna do is this; I want to run the processing code below, and after 2 minutes it should stop automatically and make itself run again and after 2 min stop again and again. I mean I don't want to run the code by clicking run button manually.
I'm so beginner on processing, I would be so glad if you can answer I desperately need this.
import processing.serial.*;
// The serial port:
Serial myPort;
String dataReading = "";
String [] dataOutput = {};
void setup() {
size(500,500);
// Open the port you are using at the rate you want:
myPort = new Serial(this, Serial.list()[7], 9600);
//in my case,the Serial port the Arduino is connected to is 9th on the serial list, hence the [8]
//to get access to the serial list you can use >> println(Serial.list());
myPort.bufferUntil('\n');
}
void draw() {
//...
}
void serialEvent(Serial myPort) {
dataReading = myPort.readString();
if(dataReading!=null){
dataOutput = append(dataOutput, dataReading);
saveData();
}
}
void saveData() {
println("saving to txt file...");
saveStrings("data/data.txt", dataOutput);
}

Related

How to create array of object instances in vala

as I was trying to nail down the bug why my gtk4_list_clocks only ever update one of the clocks and not all of them, I've traced down the problem to be in GLib.SList.prepend().
Changing from GLib.SList to Gee.ArrayList didn't solve the problem.
In the c code example a list of all clock widgets were created by appending them to a singly linked list. I've tried to mimic that but as it turned out the list size is always 1 and only one object ever get appended.
/* This is the list of all the ticking clocks */
static Gee.ArrayList<Clock> ticking_clocks = null;
// ...
construct {
ticking_clocks = new Gee.ArrayList<Clock> ();
}
void start_ticking () {
/* if no clock is ticking yet, start */
if (ticking_clock_id == 0) {
ticking_clock_id = GLib.Timeout.add_seconds (1, tick);
}
ticking_clocks.add (this); // Bug
// Although instance pointer is different according to the number of instantiated objects!!!
print ("Clock instance %p\n", this);
// always 1 !!!
print ("Number of ticking clocks %d\n", ticking_clocks.size);
}
Could somebody please help to point out the problem?
Thanks in advance.
This works:
void main () {
var a = new SList<Clock> ();
a.append (new Clock ());
a.append (new Clock ());
a.append (new Clock ());
a.append (new Clock ());
a.append (new Clock ());
print (#"Array length is $(a.length())\n");
}
class Clock {}
I'm not sure what the problem would be in your code, but I would remove the static from the ticking_clocks field. It can also be initialised with:
private Gee.ArrayList<Clock> ticking_clocks = new Gee.ArrayList<Clock> ();
I would also move the ticker outside the instance. If your SourceFunc returns Source.CONTINUE it will carry on ticking. Here is a stripped back example using MainContext. MainContext is the event loop within GLib's MainLoop, GApplication, etc. It is useful to understand to get a good grasp of Vala's async functions/methods:
void main () {
var maincontext = MainContext.default();
var time_to_quit = false;
var count = 5;
SourceFunc quit = () => {
print (#"$count\n");
count --;
var result = Source.CONTINUE;
if (count < 1) {
time_to_quit = true;
result = Source.REMOVE;
}
return result;
};
Timeout.add_seconds (1, (owned)quit);
while (time_to_quit == false) {
maincontext.iteration( true );
}
}
Be aware the Timeout is not precise, it is at least a second. So you may want to increase the frequency and then check the time when you update the clock.

Pinging many devices at same time cause a timeout?

Similar to other ping questions here, we need to ping many IP addresses at the same time. We thought we had it running great after following many responses and examples from here, however we are experiencing failed pings due to timeout when we attempt to ping them at the same time, or even close together.
We tested our list of IP's on another ping monitoring program and the timeout does not happen. The issue is specific to our application.
In our application, every "device" has a RouterProperties class that holds its Name, IP Address, etc. We ping from the observable collection of these devices, getting their IP addresses from their RouterProperties.
Tested separating pings by 10(ms)/20(ms) await task.delay
Tested separating pings by 10(ms)/20(ms) using a dispatcher timer
Tested pinging all at once with no delay between, causing largest amounts of timeouts.
Tested converting IP Address "strings" to IP Address before pinging, no visible change in issue.
Tested with ping timeout at 500(ms), 1000(ms), 5000(ms), etc.
Current test is for 143 devices, but needs to be able to handle more.
//OUR MAIN PING SCHEDULER
private async void PingAllDevices(object sender, EventArgs e)
{
var allPingTasks = new List<Task>();
int numOfDevices = 1;
//Assign a task to each device.
foreach (RouterProperties device in devices)
{
await Task.Delay(10);
Console.WriteLine("Pinging device #" + numOfDevices + " : " + device.RouterIP);
numOfDevices++;
allPingTasks.Add(AsyncPingDevice(device));
}
//Block here for all created tasks.
await Task.WhenAll(allPingTasks);
}
}
//OUR PING TASK
async Task AsyncPingDevice(RouterProperties device)
{
// Get device IP address to ping.
string deviceIP = device.RouterIP;
try
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
var reply = await pingSender.SendPingAsync(deviceIP, (int.Parse(Properties.Settings.Default.PingTimeout)), buffer, pingOptions);
Console.WriteLine(deviceIP + " has responded.");
if (reply.Status == IPStatus.Success)
{
device.PingCounter = 0;
}
else
{
if (device.PingCounter <= 3)
{
device.PingCounter++;
}
}
}
catch
{
if (device.PingCounter <= 3)
{
device.PingCounter++;
}
}
await Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action( () =>
{
if (device.IsDeactivated != true)
{
switch (device.PingCounter)
{
case 0:
device.Color = "#FF8AA587";
break;
case 1:
device.Color = "#FF9AB999";
break;
case 2:
device.Color = "#FFFCCEAA";
break;
case 3:
device.Color = "#FFF4837D";
break;
case 4:
device.Color = "#FFEB4960";
break;
}
}
}));
}
When we run our code, with and without the task.delay inside the ping scheduler to separate the pings, we end up with inconsistent results from the devices being pinged.
Without the delay = 75% of all devices timeout.
With the delay = inconsistently random 10% of devices timing out per
cycle.
Similar ping program to ours = 100% consistent results without any
timeouts.

Processing - How to log Strings in txt file?

Im getting more and more frustrated on why this is not doing what i want to. I need to have a text file that logs the last 10 buttons the user pressed, i tried in two ways but…
…this code only saves the last button pressed:
String [][] buttonsPressed = { {"Pressed one"}, {"Pressed two"} };
String[] sum;
void setup() {
size(700, 350);
sum = loadStrings("scores.txt");
}
void draw() {
}
void keyPressed() {
if ((key=='1')) {
saveStrings("scores.txt", buttonsPressed[0]);
}
if ((key=='2')) {
saveStrings("scores.txt", buttonsPressed[1]);
}
if ((key == ENTER)) {
printArray(sum);
}
}
…this code saves the buttons pressed but overwrites itself when i run the sketch again (probably has something to do with createWriter):
PrintWriter sum;
void setup() {
size(700, 350);
sum = createWriter("scores.txt");
}
void draw() {
}
void keyPressed() {
if ((key=='1')) {
sum.println("pressed one");
}
if ((key=='2')) {
sum.println("pressed two");
}
if ((key == ENTER)) {
sum.flush();
sum.close();
String[] lines = loadStrings("scores.txt");
for (int i = 0; i <= 9; i++) {
printArray("[" + i + "] " + lines[i]);
}
}
}
Is there a simple way to do this without using libraries ? Please get me in the right direction :)
Break your problem down into smaller steps.
Step 1: At the beginning of your program, read in the existing history file. Store them in some kind of data structure, like an array or an ArrayList.
Step 2: Make the data structure keep track of the last 10 buttons pressed. You'll need to write code that adds the newest button pressed to the end of the data structure, and if the data structure contains more than 10 items, you have to remove the oldest item. Maybe do this in a separate example sketch where you just print the data structure to the console and don't worry about outputting it to a file just yet.
Step 3: Output the data structure to a file. You don't have to worry about appending to the file because your data structure contains the entire history, so you can just overwrite the file with the entire data structure. You'll probably want to do this every time the data structure changes. Again, maybe do this in a separate example program before worrying about where the data is coming from: maybe make a program that outputs an array of random numbers every time the user clicks?
Focus on one small step at a time, and try creating small example programs for each step. Then when you get stuck, you can ask a specific question and provide an MCVE, and we'll go from there. Good luck.

Multiple Timers Arduino

Hi I had a question about timers on that Arduino.
I have 5 physical buttons (piezos) that I am getting the analog input from. I am then having them write out a keyboard key. My issue is when one is hit I want it to be unable to hit for "x" amount of time. I tried using delay, but this ended up delaying the whole program, thus 2 buttons could not be hit at the same time. Could someone explain to me how to do this with timers? I want 5 separate timers 1 for each button that controls a Boolean, I would need 5 separate timers for 5 separate if statements. (See code).
//SNARE LOOP2
if(sensorValueA0 == 0)
{
if(SnareHit == false)
{
Keyboard.write(115);
SnareHit = true;
//Use timer here to delay this part of the system
SnareHit = false;
}
}
//BASS DRUM LOOP
if(sensorValueA1 == 0)
{
if(BassHit == false)
{
Keyboard.write(98);
BassHit = true;
//Use timer here to delay this part of the system
BassHit = false;
}
}
Thanks.
You can use the millis() function, something similar to the following code:
if(ButtonPress==true){
time=millis() //time was previously declared as unsigned long
if(time>=5000){ //5000 = 5 sec
ButtonPress==false
}
}
It will not stop the arduino loop as dealy() does.
More info: http://playground.arduino.cc/Code/AvoidDelay
Perhaps you are trying to de-bounce the button. I usually do this in the main loop, and expect 5 consecutive "pressed" reads before I say the button is really pressed, something like this:
int button1PressedCount = 0;
int debounceCounter = 5; // Number of successive reads before we say the switch is pressed
boolean buttonPressed = false;
int inputPin1 = 7;
void setup() {
// Grounding the input pin causes it to actuate
pinMode(inputPin1, INPUT ); // set the input pin 1
digitalWrite(inputPin1, HIGH); // set pin 1 as a pull up resistor.
}
void loop()
{
// Some code
// Check button, we evaluate below
checkButton();
// Some more code
}
void checkButton() {
if (digitalRead(inputPin) == 0) {
// We need consecutive pressed counts to treat this is pressed
if (button1PressedCount < debounceCounter) {
button1PressedCount += 1;
// If we reach the debounce point, mark the start time
if (button1PressedCount == debounceCounter) {
// Button is detected as pressed!
buttonPressed = true;
}
}
} else {
if (button1PressedCount == debounceCounter) {
// We were pressed, but are not any more
buttonPressed = false;
}
button1PressedCount = 0;
}
}
Also it seems using an analogue input with a check if the analogue value is exactly equal to 0 might be a bit sensitive in noisy environments. This is why I use a digital input and the internal pull up resistor.

Arduino: Converting a client.read()

I'm trying to check the number of unread Mails with an Arduino+Ethernet Shield, sending two IMAP-requests.
With client.read(server_answer), I store it into a char.
When I send it to serial with Serial.print(server_answer), I get the following:
* OK IMAP server ready H migmx111 92345
0 OK LOGIN completed
* STATUS INBOX (UNSEEN 1)
0 OK STATUS completed
* STATUS INBOX (MESSAGES 1917)
0 OK STATUS completed
* BYE Server logging out
0 OK LOGOUT completed
Now my question: How can I extract the two numbers (total count of mails and unread mails, in the example 1 unread and 1917 total count)?
How can I get them in two different strings?
I want to display the numbers with some some text ("You have [number] new mails!") on a LCD.
If it helps, here's interesting part of my code:
void loop()
{
updateClient();
checkAvail();
}
void updateClient()
{
if ((millis() - updateTimer) > 10000)
{
Ethernet.begin(mac, ip);
// Serial.println("connecting...");
delay(1000);
if (client.connect())
{
//Serial.println("connected");
client.println("0 login myusername mypasswd");
client.println("0 STATUS INBOX (UNSEEN)");
client.println("0 STATUS INBOX (MESSAGES)");
client.println("0 logout");
clientConnected = true;
}
else
{
Serial.println("connection failed");
}
updateTimer = millis();
}
}
void checkAvail()
{
if (clientConnected)
{
if (client.available())
{
server_answer = client.read();
Serial.print(server_answer);
}
if (!client.connected())
{
Serial.println();
// Serial.println("disconnecting.");
client.stop();
clientConnected = false;
}
}
}
Without writing your code for you, you need to break the incoming data up into chunks using strtok_r(). Looking at your code above calling strtok_r() with '(' as a delimiter then again with a space as a delimiter and then again with ')' should get you to the begining of your first number. From there atoi() will convert it to an interger. Repeating the process should get you to the second value as well.
Take a crack at this and post your code if you have any more problems.

Resources