So here's my problem, First image
the highlighted portion was the time when i put the serial port close(i call it pause). Here's my code on that button:
private void disconnectbutton_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen == false) return;
serialPort.Close();
}
Now, my problem here is, when I reconnect my Program to Arduino, here's my code:
public void connectbutton_Click(object sender, EventArgs e)
{
try
{
serialPort.PortName = portscombobox.Text;
serialPort.BaudRate = Convert.ToInt32(baudratecombobox.Text);
if (serialPort.IsOpen) return;
serialPort.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show("Invalid COM Port number... Please choose the correct COM Port number. \n Looking at Device manager will help :)");
Application.Restart();
}
The graph didn't follow the last points position, specifically the time it stopped. The curve pick the last y-value and draw it until the time I reconnect but there's no problem on the curve when disconnected/pause. You can look at the 2nd pic to show there's no feed while disconnected.
Second image
When i reconnect, the graph will look like the first picture above..
I believe my problem here was the improper use of Environment.tickcount and I tried searching for the solution but unfortunately I cant solve this on my own based on my knowledge.
I want my graph will only move to its x axis(time) when I try to connect it to arduino and read the data, and my elapsed time should only run when Im only connected not disconnected.
Here's my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using ZedGraph;
namespace WindowsFormsApplication4
{
public partial class Form1 : Form
{
string datafromcom;
delegate void SetTextCallback(string text);
// Starting time in milliseconds
int tickStart = 0;
//double time = 0;
//int t;
public Form1()
{
InitializeComponent();
checkbox1.Enabled = false;
checkbox2.Enabled = false;
checkbox3.Enabled = false;
checkbox4.Enabled = false;
}
public void connectbutton_Click(object sender, EventArgs e)
{
try
{
serialPort.PortName = portscombobox.Text;
serialPort.BaudRate = Convert.ToInt32(baudratecombobox.Text);
if (serialPort.IsOpen) return;
serialPort.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
MessageBox.Show("Invalid COM Port number... Please choose the correct COM Port number. \n Looking at Device manager will help :)");
Application.Restart();
}
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
getbutton.Enabled = false;
checkbox1.Enabled = true;
checkbox2.Enabled = true;
checkbox3.Enabled = true;
checkbox4.Enabled = true;
exitbutton.Enabled = false;
connectbutton.Enabled = false;
disconnectbutton.Enabled = true;
portscombobox.Enabled = false;
baudratecombobox.Enabled = false;
}
private void disconnectbutton_Click(object sender, EventArgs e)
{
if (serialPort.IsOpen == false) return;
serialPort.Close();
//tickStart += new tickStart();
exitbutton.Enabled = true;
connectbutton.Enabled = true;
disconnectbutton.Enabled = false;
portscombobox.Enabled = true;
baudratecombobox.Enabled = true;
checkbox1.Enabled = false;
checkbox2.Enabled = false;
checkbox3.Enabled = false;
checkbox4.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
//this.Size = Screen.PrimaryScreen.WorkingArea.Size;
GraphPane myPane = z1.GraphPane;
z1.IsShowHScrollBar = true;
z1.IsShowVScrollBar = true;
z1.IsEnableHZoom = true;
z1.IsEnableVZoom = true;
// Disable the AutoScrollRange option (because we have set the scroll range manually)
z1.IsAutoScrollRange = true;
// Synchronize the Axes
z1.IsSynchronizeYAxes = true;
z1.IsSynchronizeXAxes = true;
z1.GraphPane.IsBoundedRanges = true;
// Horizontal pan allowed
z1.IsEnableHPan = true;
z1.IsEnableVPan = true;
z1.IsShowPointValues = true;
//z1.PointValueFormat = "0.00";
z1.PointDateFormat = "d";
// Change the color of the title
myPane.Title.FontSpec.FontColor = Color.Black;
myPane.Title.Text = " ";
myPane.XAxis.Title.Text = "Time (Seconds)";
myPane.YAxis.Title.Text = "Sample Potential, Volts";
// Save 20000 points. At 50 ms sample rate, this is one minute
// The RollingPointPairList is an efficient storage class that always
// keeps a rolling set of point data without needing to shift any data values
RollingPointPairList list = new RollingPointPairList(20000);
// Initially, a curve is added with no data points (list is empty)
// Color is blue, and there will be no symbols
LineItem curve = myPane.AddCurve(null, list, Color.Black, SymbolType.None);
//Sample at 50ms intervals
//timer1.Interval = 100;
//timer1.Enabled = true;
//timer1.Start();
// Just manually control the X axis range so it scrolls continuously
// instead of discrete step-sized jumps
myPane.XAxis.Scale.Min = 0;
myPane.XAxis.Scale.Max = 10;
myPane.XAxis.Scale.MinorStep = .5;
myPane.XAxis.Scale.MajorStep = 1;
myPane.YAxis.Scale.Min = -10;
myPane.YAxis.Scale.Max = 10;
myPane.YAxis.Scale.MinorStep = .1;
myPane.YAxis.Scale.MajorStep = 1;
// Add gridlines to the plot, and make them gray
myPane.XAxis.MajorGrid.IsVisible = true;
myPane.YAxis.MajorGrid.IsVisible = true;
myPane.XAxis.MajorGrid.Color = Color.LightGray;
myPane.YAxis.MajorGrid.Color = Color.LightGray;
myPane.Fill.Color = System.Drawing.Color.DarkGray;
// Make both curves thicker
curve.Line.Width = 2F;
// Increase the symbol sizes, and fill them with solid white
curve.Symbol.Size = 8.0F;
curve.Symbol.Fill = new Fill(Color.White);
// Add a background gradient fill to the axis frame
myPane.Chart.Fill = new Fill(Color.White,
Color.FromArgb(255, 255, 255), -45F);
// Scale the axes
z1.AxisChange();
//z1.AxisChange();
z1.GraphPane.AxisChange();
// Save the beginning time for reference
tickStart = Environment.TickCount;
}
private void exitbutton_Click(object sender, EventArgs e)
{
Application.Exit();
}
public void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
try
{
while (serialPort.BytesToRead > 0)
{
datafromcom = serialPort.ReadLine();
if (datafromcom.Trim() != "")
{
float dtfm = float.Parse(datafromcom);
//richtextbox.Text = "dynamic";
if (z1.GraphPane.CurveList.Count <= 0)
return;
// Get the first CurveItem in the graph
LineItem curve = z1.GraphPane.CurveList[0] as LineItem;
if (curve == null)
return;
// Get the PointPairList
IPointListEdit list = curve.Points as IPointListEdit;
// If this is null, it means the reference at curve.Points does not
// support IPointListEdit, so we won't be able to modify it
if (list == null)
return;
double time = (Environment.TickCount - tickStart) / 1000.0;
//curve.AddPoint(time, iDAT);
list.Add(time, dtfm);
Scale xScale = z1.GraphPane.XAxis.Scale;
if (time > xScale.Max - xScale.MajorStep)
{
xScale.Max = time + xScale.MajorStep ;
xScale.Min = xScale.Max - 10.0;
}
z1.AxisChange();
z1.Invalidate();
this.BeginInvoke(new SetTextCallback(SetText), new object[] { datafromcom });
}
}
}
catch (Exception )
{
}
}
private void SetText(string text)
{
this.richtextbox.Text = text;
//richtextbox.AppendText(text);
richtextbox.ScrollToCaret();
}
public void timer1_Tick(object sender, EventArgs e)
{
}
private void resetbutton_Click(object sender, EventArgs e)
{
Application.Restart();
}
}
}
Related
My objective is to obtain a flag that is sent from the Arduino by a button. This flag is going to be sent through serial communication to a C# windows form program where i will be able to obtain the flag.
The data sent to the serial port by the Arduino is "ON" and "OFF", "ON" when the button is clicked and "OFF" when the button is not clicked. This flag will be used to turn on and off the red chart that will be displayed in the windows form.
My problem is how do i get this "ON" and "OFF" from the serial communication keeping in mind that data from the sensors are also being sent to the windows form application.
//C# Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO.Ports;
using rtChart;
namespace Distance_Sensor_using_Flight_of_time
{
public partial class Form1 : Form
{
string recvData = "temporary";
bool breakloop = false;
kayChart chartData;
bool buttonPress = false;
string bufferString = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
//chart1.Series.Add("Series1");
//Connection COM & Baud Rate
string[] ports = SerialPort.GetPortNames();
string[] rates = new string[10] { "300", "600", "1200", "2400", "9600", "14400", "19200", "38400", "57600", "115200" };
cboBaudRate.SelectedText = "9600";
cboCOM.Items.AddRange(ports);
cboBaudRate.Items.AddRange(rates);
if (ports.Length >= 1)
cboCOM.SelectedIndex = 0;
//kayChart real time
chartData = new kayChart(chart1, 60);
btnStart.Enabled = false;
btnSave.Enabled = false;
chart1.Series["Series1"].Enabled = false;
}
private void BtnConnect_Click(object sender, EventArgs e)
{
try
{
if (btnConnect.Text == "Disconnect")
{
if (btnStart.Text == "Stop")
MessageBox.Show("Please click \"Stop\" button first!");
else
{
serialPort1.Close();
btnStart.Enabled = false;
btnConnect.Text = "Connect";
}
}
else
{
serialPort1.PortName = cboCOM.Text;
serialPort1.BaudRate = Convert.ToInt32(cboBaudRate.Text);
serialPort1.Parity = Parity.None;
serialPort1.StopBits = StopBits.One;
serialPort1.DataBits = 8;
serialPort1.Open();
btnStart.Enabled = true;
btnConnect.Text = "Disconnect";
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void serialDataReceive(object sender, SerialDataReceivedEventArgs e)
{
if (!breakloop)
{
SerialPort sData = sender as SerialPort;
recvData = sData.ReadLine();
bufferString = recvData;
//rtbData.Invoke((MethodInvoker)delegate {rtbData.AppendText(recvData); });
//update chart
if (recvData == "ON\r" || recvData == "OFF\r")
{
if (recvData == "ON")
buttonPress = true;
else
buttonPress = false;
}
else
{
double data;
bool result = Double.TryParse(recvData, out data);
if (result)
{
chartData.TriggeredUpdate(data);
if (buttonPress == false)
{
chart1.Invoke((MethodInvoker)delegate { chart1.Series["Series1"].Enabled = false; });
chartData.serieName = "Length";
}
else
{
chart1.Invoke((MethodInvoker)delegate { chart1.Series["Series1"].Enabled = true; });
chartData.serieName = "Series1";
}
}
}
rtbData.Invoke((MethodInvoker)delegate { rtbData.AppendText(recvData); });
}
}
private void BtnStart_Click(object sender, EventArgs e)
{
try
{
if (btnStart.Text == "Start")
{
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialDataReceive);
btnStart.Text = "Stop";
breakloop = false;
}
else
{
btnStart.Text = "Start";
breakloop = true;
//serialPort1.DataReceived += null;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
btnStart.Text = "Start";
}
}
private void RtbData_TextChanged(object sender, EventArgs e)
{
rtbData.SelectionStart = rtbData.Text.Length;
rtbData.ScrollToCaret();
}
}
}
//Arduino Code
/* This example shows how to get single-shot range
measurements from the VL53L0X. The sensor can optionally be
configured with different ranging profiles, as described in
the VL53L0X API user manual, to get better performance for
a certain application. This code is based on the four
"SingleRanging" examples in the VL53L0X API.
The range readings are in units of mm. */
#include <Wire.h>
#include <VL53L0X.h>
VL53L0X sensor;
// Uncomment this line to use long range mode. This
// increases the sensitivity of the sensor and extends its
// potential range, but increases the likelihood of getting
// an inaccurate reading because of reflections from objects
// other than the intended target. It works best in dark
// conditions.
//#define LONG_RANGE
// Uncomment ONE of these two lines to get
// - higher speed at the cost of lower accuracy OR
// - higher accuracy at the cost of lower speed
//#define HIGH_SPEED
#define HIGH_ACCURACY
const int buttonPin = 2;
const int ledPin = 8;
int buttonState = 0;
bool inLoop = false;
void setup()
{
Serial.begin(9600);
Wire.begin();
// initialize the LED pin as an output:
pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
sensor.init();
sensor.setTimeout(500);
#if defined LONG_RANGE
// lower the return signal rate limit (default is 0.25 MCPS)
sensor.setSignalRateLimit(0.1);
// increase laser pulse periods (defaults are 14 and 10 PCLKs)
sensor.setVcselPulsePeriod(VL53L0X::VcselPeriodPreRange, 18);
sensor.setVcselPulsePeriod(VL53L0X::VcselPeriodFinalRange, 14);
#endif
#if defined HIGH_SPEED
// reduce timing budget to 20 ms (default is about 33 ms)
sensor.setMeasurementTimingBudget(20000);
#elif defined HIGH_ACCURACY
// increase timing budget to 200 ms
sensor.setMeasurementTimingBudget(200000);
//sensor.setMeasurementTimingBudget(900000);
#endif
}
void loop()
{
buttonState = digitalRead(buttonPin);
Serial.print(sensor.readRangeSingleMillimeters());
if (sensor.timeoutOccurred()) { Serial.print(" TIMEOUT"); }
Serial.println();
if (buttonState == HIGH && inLoop == false)
{
Serial.write("ON");
Serial.println();
digitalWrite(ledPin, HIGH);
inLoop = true;
}
else if (buttonState == LOW && inLoop == true)
{
Serial.write("OFF");
Serial.println();
digitalWrite(ledPin, LOW);
inLoop = false;
}
}
I expect that the chart will turn red once the button is clicked and blue when the button is not clicked. Thank you in advance.
Although what you are doing may work (ie just trying to figure out what the message is on the receive side), it is far more scale-able if you use some form of message header and a delimiter. So your messages would look like this:
"btnState,true"
"btnState,false"
"data,124"
On the receive side, you will need to do a recvData.Split(',') and then check the first member of the array to find out what they message type is and then parse the second part accordingly.
Also, relating to your code specifically, I am unsure why you chose to use Serial.write for you "ON" and "OFF" instead of sticking to Serial.println. I am not positive without testing, but pretty sure you are trying to use the println as a message delimiter, and I think it may be sending the write and the empty println as two separate messages (which would explain why your on off equality may fail).
I have panel and Datagridview on Form, panel is for sliding up and down to show and hide its contents.
When I click on show button it executes this code:
private void button1_Click(object sender, EventArgs e)
{
if (hidded)
{
button1.Visible = false;
button2.Visible = true;
}
else
{
button1.Visible = true;
button2.Visible = false;
}
timer1.Start();
}
private void timer1_Tick(object sender, EventArgs e)
{
if (hidded)
{
Spanel.Height = Spanel.Height + 20;
Datagridview1.Location = new Point(23 , Datagridview1.Location.Y + 20);
if (Spanel.Height >= 140)
{
timer1.Stop();
hidded = false;
this.Refresh();
}
}
else
{
Spanel.Height = Spanel.Height - 20;
Datagridview1.Location = new Point( 23, Datagridview1.Location.Y - 20);
if (Spanel.Height <= 0)
{
timer1.Stop();
hidded = true;
this.Refresh();
}
}
}
when i try to hide/close panel the Datagridview moves up and become like this:
I just need to fix anchor size or datagridview location from down.
If you want to do it your way (with timer) just change your timer tick event handler to the code bellow. It will also change the size of the DataGridView alongside with its position.
private void timer1_Tick(object sender, EventArgs e)
{
if (hidded)
{
Spanel.Height = Spanel.Height + 20;
Datagridview1.Location = new Point(23, Datagridview1.Location.Y + 20);
Datagridview1.Size = new Size(Datagridview1.Width, Datagridview1.Height - 20);
if (Spanel.Height >= 140)
{
timer1.Stop();
hidded = false;
this.Refresh();
}
}
else
{
Spanel.Height = Spanel.Height - 20;
Datagridview1.Location = new Point(23, Datagridview1.Location.Y - 20);
Datagridview1.Size = new Size(Datagridview1.Width, Datagridview1.Height + 20);
if (Spanel.Height <= 0)
{
timer1.Stop();
hidded = true;
this.Refresh();
}
}
}
My approach to this problem would be a bit different and if u don't mind i will let it here. Instead of anchoring i would do it like this(see the pic bellow) using docking. It should work the same using the code you posted (Your SPanel is Panel2 on the picture).
Edit #1: For fluently moving or resizing controls in your WinForm app i recommend you to use this library: https://github.com/UweKeim/dot-net-transitions. Using the mentioned library your button click event hanlder would look something like this:
private bool resizing = false;
private void button1_Click(object sender, EventArgs e)
{
if (resizing)
return;
resizing = true;
Transition t = new Transition(new TransitionType_Acceleration(600));
t.TransitionCompletedEvent += (snd, ea) => { resizing = false; };
t.add(panel2, "Height", panel2.Height == 0 ? 250 : 0);
t.run();
}
This one is driving me a bit crazy. Any help gratefully received. It's a simple program to receive temperature data from an Arduino based temp sensor, and display it in a graph control on a form. The program works fine, and parses the temp data frame a treat. However..... the graph object doesn't refresh, and the whole point is to show the data over time. I thought that the chart1.DataBind command that I put in forced a refresh. I am using Visual Studio 2013 Express. Any thoughts as to what I am doing wrong very much appreciated.
// Start of program.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace serial_port_with_events_attempt_4
{
public partial class Form1 : Form
{
string RxString;
int RxRead;
int i;
int RxDec1;
int RxDec2;
int RxDec3;
float RxFloat;
float RxFloat2;
string locnString;
public Form1()
{
InitializeComponent();
}
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM8";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxRead = serialPort1.ReadByte();
this.Invoke(new EventHandler(DisplayText));
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
}
private void DisplayText(object sender, EventArgs e)
{
if (RxRead == 126)
{
textBox1.AppendText(Environment.NewLine);
i = 0;
}
if (i< 23)
{
if (i == 7)
{
if (RxRead == 51) // 51 in this position means that the temp sensor is the one in the wooden box
{
textBox1.AppendText("Temperature in Nick's office = ");
locnString = ("Nick's office");
}
}
if (i == 17)
{
RxDec1 = RxRead - 48; // Read the tens unit
}
if (i == 18)
{
RxDec2 = RxRead - 48; // Read the units
}
if (i == 20)
{
RxDec3 = RxRead - 49; // read the decimal
}
if (i == 22)
{
RxFloat = ((RxDec1 * 10) + RxDec2);
RxFloat2 = RxDec3;
RxFloat2 = RxFloat2 / 10;
RxFloat = RxFloat + RxFloat2;
RxString = RxFloat.ToString();
if (RxFloat < 30 && RxFloat >20)
{
// Put the value in the main text box if it is not corrupt, (checking if the range is reasonable
textBox1.AppendText(RxString); // Frig about to get the reads in the right format and added together
// Add a new line into the temperature database
temperature1DataSetTableAdapters.Temp1TableAdapter temp1tableadapter = new temperature1DataSetTableAdapters.Temp1TableAdapter();
temp1tableadapter.Insert(DateTime.Now, RxFloat, locnString);
}
// Delete any old data.
temperature1DataSetTableAdapters.TempTableAdapter temp2tableadapter = new temperature1DataSetTableAdapters.TempTableAdapter();
temp2tableadapter.DeleteTempQuery();
// The above two lines work, but I need to amend to select on date TODO
chart1.DataBind();
}
}
i=i+1;
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'temperature1DataSet.Temp' table. You can move, or remove it, as needed.
this.tempTableAdapter.Fill(this.temperature1DataSet.Temp);
}
}
}
Cheers,
Nick James
The issue is I can't figure out why my character moves slow when I draw an image. All the timers are set to 1 interval and never changed. Any help would be greatly appreciated. Here is the entire project:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Rice_Boy_Tester_2
{
public partial class Form1 : Form
{
bool iggy = false;
bool left2 = false;
bool right2 = false;
bool Up2 = false;
bool Down2 = false;
bool Check2 = false;
bool left = false;
bool right = false;
bool Up = false;
bool Down = false;
bool Check = false;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
// Empty block
}
private void Refresh_Tick(object sender, EventArgs e) {
this.Refresh();
}
private void PriceBoyWalk_Tick(object sender, EventArgs e) {
if (left) // Goes Left
Player.Left -= 1;
if (Player.Left < 170 & Check == false) {
// Checks how far away player is from form
left = false;
Up = true;
}
if (Up & Player.Left < 170) { // Goes Up
Player.Top -= 1;
Check = true;
}
if (Player.Top < 100 & Check) {
Up = false;
Down = true;
}
if (right) // Goes Right
Player.Left += 1;
if (Down) // Goes Down
Player.Top += 1;
if (Player.Top + 150 > this.ClientSize.Height) {
Check = false;
Down = false;
right = true;
}
if (Player.Left + 150 > this.ClientSize.Width)
right = false;
}
private void B1_Click(object sender, EventArgs e) {
this.Paint += new PaintEventHandler(form1_Pad1_Rice);
RiceBoyWalkGif.Enabled = true;
left = true;
left2 = true;
RiceBoyWalk.Enabled = true;
}
private void timer1_Tick(object sender, EventArgs e) {
if (left2) {
Player.Image = Image.FromFile("Rice-Boy-Walking-Left-Bouncing.gif"); // Animates RiceBoyWalkingLeft
left2 = false;
}
if (Player.Left < 170 & Check2 == false) {
// Checks how far away the player is from form
left2 = false;
Up2 = true;
}
if (Up2 & Player.Left < 170) { // Goes Up
this.Player.Size = new System.Drawing.Size(36, 76); // Changes size of the picture box to maintain quality
Player.Image = Image.FromFile("Rice-Boy-Walking-Up-Bouncing.gif"); // Animates RiceBoyWalkingUp
Check2 = true;
Up2 = false;
}
if (Player.Top < 101 & Check2) {
// Player.Top < 101 must be +1 greater than the RiceBoyWalkTimer
Up2 = false;
Down2 = true;
}
if (right2) {
this.Player.Size = new System.Drawing.Size(53, 77); // Changes size of the picture box to maintain quality
Player.Image = Image.FromFile("Rice-Boy-Walking-Right-Bouncing.gif"); // Animates RiceBoyWalkingRight
right2 = false;
}
if (Down2) { // Goes Down
Player.Image = Image.FromFile("Rice-Boy-Walking-Down.gif");
Down2 = false;
}
if (Player.Top + 150 > this.ClientSize.Height) {
iggy = true; // Shows that riceboy is approaching the starting point
Check2 = false;
Down2 = false;
right2 = true;
}
if (Player.Left + 150 > this.ClientSize.Width & iggy) {
right2 = false;
Player.Image = Properties.Resources.Rice_Boy_Standing_Left;
}
}
private void form1_Pad1_Rice(object sender, System.Windows.Forms.PaintEventArgs e) {
e.Graphics.DrawImage(Properties.Resources.Corn_Cobs, 120, 58, 50, 50);
// Draws Corn cobs Character goes slower when corn is drawing
// (x(-left), y(-Up), W, H)
}
Start with this:
Player.Image = Image.FromFile("Rice-Boy-Walking-Down.gif");
(and the other load routines).
On every tick? Seriously?
Load them once during initialization, store them in variables, reuse the images. Ever played a computer game? They are not trashing your disc trying to load all graphics asset every frame.
Disc access is slow. Image decoding is slow. And I doubt you change the images while the program runs.
I have application that received real time data and show this data on my chart control graph with timer:
MyObject obj = null;
Series seriesTraffic = null:
private void LoadGraph()
{
seriesTraffic = new Series();
seriesTraffic.Color = Color.Blue;
seriesTraffic.ChartType = SeriesChartType.Spline;
seriesTraffic.BorderWidth = 2;
chart1.Series.Add(seriesTraffic);
chart1.ChartAreas[0].AxisX.MajorGrid.LineColor = Color.White;
chart1.ChartAreas[0].AxisY.MajorGrid.LineColor = Color.White;
chart1.ChartAreas[0].AxisX.LabelStyle.Enabled = false;
chart1.ChartAreas[0].AxisY.LabelStyle.Enabled = false;
chart1.ChartAreas[0].AxisX.IsStartedFromZero = true;
chart1.ChartAreas[0].AxisX.IntervalOffsetType = DateTimeIntervalType.Number;
}
private void chartTimer_Tick(object sender, EventArgs e)
{
var timer = (System.Windows.Forms.Timer)sender;
MyObject wf2 = (MyObject)timer.Tag;
lblChartMbitSec.Text = string.Format("{0} Mbit/sec", (wf2.BitsPerSecond * 0.000001).ToString("0.##"));
if (seriesTraffic.Points.Count() > 150)
seriesTraffic.Points.RemoveAt(0);
seriesTraffic.Points.Add(wf.BitsPerSecond * 0.000001);
chart1.ResetAutoValues();
}
My object contain 2 properties that i want my graph to show seperate:
obj.BitsPerSecond
obj.PacketsPerSecond
Tnis is my Combobox SelectedIndexChanged event:
private void cbStatistics_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbStatistics.SelectedIndex == 0)
timerChart.Tag = wf;
else if (cbStatistics.SelectedIndex == 1)
timerChart.Tag = wf;
}
When this selected index changed fired up i want to show my other graph, how can i do that ?
I would create two series objects, and update both of them at each timer tick - one for the bits per second, one for the packets per second:
private void LoadGraph()
{
seriesBps = new Series("bps");
seriesBps.Color = Color.Blue;
seriesBps.ChartType = SeriesChartType.Spline;
seriesBps.BorderWidth = 2;
chart1.Series.Add(seriesBps);
seriesPps = new Series("pps");
seriesPps.Color = Color.Blue;
seriesPps.ChartType = SeriesChartType.Spline;
seriesPps.BorderWidth = 2;
chart1.Series.Add(seriesPps);
// set up axes as you already do
}
and then in your timer tick handler:
private void chartTimer_Tick(object sender, EventArgs e)
{
if (seriesBps.Points.Count() > 150)
seriesBps.Points.RemoveAt(0);
seriesBps.Points.Add(wf.BitsPerSecond * 0.000001);
if (seriesPps.Points.Count() > 150) seriesPps.Points.RemoveAt(0);
seriesPps.Points.Add(wf.PacketsPerSecond);
chart1.ResetAutoValues();
}
And, in your combo box event handler, enable the series you need:
private void cbStatistics_SelectedIndexChanged(object sender, EventArgs e)
{
if (cbStatistics.SelectedIndex == 0)
{
seriesBps.Enabled = true;
seriesPps.Enabled = false;
lblChartMbitSec.Text = string.Format("{0} Mbit/sec", (wf2.BitsPerSecond * 0.000001).ToString("0.##")); // and similarly for the other case below
}
else if (cbStatistics.SelectedIndex == 1)
{
seriesBps.Enabled = false;
seriesPps.Enabled = true;
}
chart1.ResetAutoValues();
}
Set the enabled flag on the two series in the LoadGraph() method to correspond to the initial state of the combo box.