Descarga la aplicación para disfrutar aún más
Vista previa del material en texto
Cristal Aricel Sáenz Hernández 18131059 Practica 9 Hacer los programas indicados en C# A lunes 15 mayo 2023 Ejercicio 1: Encender y apagar un led con dos botones Código visual 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 LEDON_OFF { public partial class Form1 : Form { System.IO.Ports.SerialPort Arduino; public Form1() { InitializeComponent(); Arduino = new System.IO.Ports.SerialPort(); Arduino.PortName = "COM5"; Arduino.BaudRate = 9600; Arduino.Open(); } private void encender_Click(object sender, EventArgs e) { Arduino.Write("E"); } private void apagar_Click(object sender, EventArgs e) { Arduino.Write("F"); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if(Arduino.IsOpen) { Arduino.Close(); } } private void button1_Click(object sender, EventArgs e) { Close(); } } } Código Arduino const int PIN_LED=13; void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(PIN_LED, OUTPUT); } void loop() { // put your main code here, to run repeatedly: if(Serial.available()>0) { int LeerCaracter=Serial.read(); if(LeerCaracter=='E'){ digitalWrite(PIN_LED,HIGH); }else if(LeerCaracter=='F'){ digitalWrite(PIN_LED,LOW); }else{ } } } Evidencias Ejercicio 2: Instalar tu propio medidor de temperatura con LM35 Código visual using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace LM35 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { SerialPort miSerial = new SerialPort("COM5"); miSerial.BaudRate = 9600; miSerial.Parity = Parity.None; miSerial.DataBits = 8; miSerial.Handshake = Handshake.None; miSerial.RtsEnable = true; miSerial.DtrEnable = true; miSerial.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); miSerial.Open(); } private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadLine(); if(a.InvokeRequired) { a.Invoke(new MethodInvoker(delegate { a.Text = indata; })); } } } } Código Arduino float tempC; int pinLM35=A0; float t; void setup() { // put your setup code here, to run once: Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: tempC=analogRead(pinLM35); int value=analogRead(pinLM35); float millivolts=(value/1023.0)*5000; float celsius=millivolts/10; Serial.print(celsius); Serial.println(" C°"); delay (1000); } Evidencia Ejercicio 3: Leer Arduino en Visual Código Arduino int num; void setup() { Serial.begin(9600); num=0; } void loop() { num=num+1; Serial.print(String ("Contador: ")); Serial.println(num); delay(1000); } Código visual using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace leerarduinop9 { public partial class Form1 : Form { System.IO.Ports.SerialPort Port; bool IsClosed = false; public Form1() { InitializeComponent(); Port = new System.IO.Ports.SerialPort(); Port.PortName = "COM5"; Port.BaudRate = 9600; Port.ReadTimeout = 500; try { Port.Open(); } catch { } } private void Form1_Load(object sender, EventArgs e) { Thread Hilo = new Thread(EscucharSerial); Hilo.Start(); } private void EscucharSerial() { while(!IsClosed) { try { string cadena = Port.ReadLine(); a.Invoke(new MethodInvoker(delegate { a.Text = cadena; })); } catch { } } } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { IsClosed = true; if (Port.IsOpen) Port.Close(); } private void button1_Click(object sender, EventArgs e) { Close(); } } } Evidencia Nota: En este programa no se tuvieron que hacer modificaciones Ejercicio 4: Control de un motor de cd desde visual comunicando con Arduino IDE. Control de velocidad y dirección de giro usando botones y tracBar Código Arduino int velocidad; int ma= 6; int mb= 5; boolean derecha = false; boolean izquierda = false; void setup() { pinMode(ma,OUTPUT); pinMode(mb,OUTPUT); Serial.begin(9600); } void loop() { } void serialEvent() { velocidad = Serial.parseInt(); if(velocidad !=0 ) { if(velocidad == 1) // velocidad leida derecha { derecha = true; izquierda = false; } if(velocidad == 2) // frenado de motor { digitalWrite(ma, LOW); digitalWrite(mb, LOW); velocidad=0; izquierda = false; derecha = false; } if(velocidad== 3) // velocidad leída izquierda { izquierda = true; derecha= false; } if (derecha && !izquierda) { digitalWrite(ma, LOW); //apaga la salida izquierda analogWrite(mb, velocidad);// salida de velocidad pwm derecha; } if (!derecha && izquierda) { digitalWrite(mb, LOW); //apaga salida derecha analogWrite(ma, velocidad);// salida de velocidad pwm izquierda; } } } Código Visual 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 static System.Windows.Forms.VisualStyles.VisualStyleElement; namespace WindowsFormsApp7 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void trackBar1_Scroll(object sender, EventArgs e) { { trackBar1.Text = trackBar1.Value.ToString(); try { serialPort1.Open(); serialPort1.WriteLine(trackBar1.Value.ToString()); serialPort1.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } private void pictureBox2_Click(object sender, EventArgs e) { } private void Form1_FormClosed(objectsender, FormClosedEventArgs e) { try { serialPort1.Open(); serialPort1.WriteLine("2"); serialPort1.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void button3_Click_1(object sender, EventArgs e) { try { serialPort1.Open(); serialPort1.WriteLine("1"); serialPort1.WriteLine(trackBar1.Value.ToString()); serialPort1.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void button8_Click(object sender, EventArgs e) { try { serialPort1.Open(); serialPort1.WriteLine("3"); serialPort1.WriteLine(trackBar1.Value.ToString()); serialPort1.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void Form1_Load(object sender, EventArgs e) { try { comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames()); comboBox1.SelectedIndex = 0; serialPort1.BaudRate = (9600); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void comboBox1_SelectedIndexChanged_1(object sender, EventArgs e) { try { serialPort1.PortName = comboBox1.Text; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void button2_Click_1(object sender, EventArgs e) { try { serialPort1.Open(); serialPort1.WriteLine("2"); serialPort1.Close(); } catch (Exception ex) { MessageBox.Show(ex.Message); } } } } Evidencias Notas: Para realizar esta practica se tuvieron que hacer algunas modificaciones: 1. En el código Arduino se tienen que declarar las variables y usarlas de manera correcta, usando los “;” cada vez que una variable se usa o se escribe una línea de código. 2. En el código de visual se tienen que agregar los tres botones: paro, giro izquierdo y giro derecho, se tiene que agregar también una trackBar para el cambio de velocidad, un puerto serial para leer el puerto al cual está conectado el Arduino y agregar un combo para mostrar el puerto serial. 3. Se tienen que nombrar estas variables de una manera sencilla para no tener complicaciones en el código al momento de usarlas. 4. Se deben agregar etiquetas para identificar cada dato que sea necesario. 5. Cada vez que se intente editar un código antes deberá hacer doble clic en cada botón o barra para poder hacer la programación en cada uno de ellos según le corresponda. 6. Si el código lo tomas de cualquier otra fuente deberás asegurar que las líneas de código no se dividan en dos partes si pertenecen a la misma línea de código. 7. También hay que especificar al inicio el sistema de entradas y salidas para hacer la comunicación.
Compartir