IT수업/임베디드

IT 수업 24주차 (193) 아두이노 웹 연결

워제하 2024. 6. 3. 10:17

 

아두이노 키트에 사진처럼 연결시킨다.

 

 

그리고 아두이노 IDE 를 열어 코드를 입력시켜주고 Serial Monitor를 연 뒤 업로드와 스케치 버튼을 눌러본다.

연결은 usb 포트와 연결시켜준다.

 

 

시리얼 모니터에 0(OFF)을 눌러보고 1(ON)을 눌러보고 하면 LED에 불이 들어왔다 꺼졌다를 확인할 수 있다.

 

 

start.spring.io로 들어가 자바 버전을 맞춘 뒤 Spring Web, Thymleaf, Lombok을 받아 generate를 눌러준다.

 

 

받은 파일의 압축을 풀어준 뒤 cmd를 열어 idea . 으로 인텔리제이를 열어준다.

 

 

세팅을 모두 해주고

앱 세팅

 

프로젝트 세팅

 

프로젝트 세팅

 

 

 Maven Repository로 가서 jSerialComm을 입력해서 시리얼 통신을 위한 Gradle(short)를 받아준다.

 

 

 

그리고 인텔리제이의 build.gradle의 dependencies에 붙여넣기 해준다.

 

코끼리 아이콘 눌러서 업데이트를 해준다.

 

 

그리고 templates 안에 arduino 디렉토리를 만든 후 index.html 파일을 만들어준다.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>INDEX</h1>
<fieldset style="width:200px;">
    <legend>CONNECTION</legend>
    <input class="com_port">
    <button class="conn_btn">CONN</button>
</fieldset>
<fieldSet style="width:200px;">
    <legend>LED</legend>
    <button class="led_on">LED ON</button>
    |
    <button class="led_off">LED OFF</button>
</fieldSet>

<!-- axios cdn -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/1.5.0/axios.min.js" integrity="sha512-aoTNnqZcT8B4AmeCFmiSnDlc4Nj/KPaZyB5G7JnOnUEkdNpCZs1LCankiYi01sLTyWy+m2P+W4XM+BuQ3Q4/Dg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script>
    const led_on_btn = document.querySelector('.led_on');
    const led_off_btn = document.querySelector('.led_off');

    const conn_btn = document.querySelector('.conn_btn');
    conn_btn.addEventListener('click',function(){

         const port = document.querySelector('.com_port').value;
         axios.get(`/arduino/connection/${port}`)
        .then(response=>{})
        .catch(error=>{});

    });


    led_on_btn.addEventListener('click',function(){

        axios.get('/arduino/led/1')
        .then(response=>{})
        .catch(error=>{});

    });
    led_off_btn.addEventListener('click',function(){
        axios.get('/arduino/led/0')
        .then(response=>{})
        .catch(error=>{});
    });

</script>

</body>
</html>

 

 

그리고 src의 java에 demo 밑에 controller 패키지를 만들고 ArduinoController 클래스를 만들어 준다.

 



이번에는 restcontroller 패키지를 만든 후 ArduinoRestController 클래스를 작성해준다.

package com.example.demo.restcontroller;


import com.fazecast.jSerialComm.SerialPort;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@Slf4j
@RequestMapping("/arduino")
public class ArduinoRestController {

    private SerialPort serialPort;
    private OutputStream outputStream;
    private InputStream inputStream;

    @GetMapping("/connection/{COM}")
    public ResponseEntity<String> setConnection(@PathVariable("COM") String COM, HttpServletRequest request) {
        log.info("GET /arduino/connection " + COM  + " IP : " + request.getRemoteAddr());

        if(serialPort!=null){
            serialPort.closePort();
            serialPort=null;
        }

        //Port Setting
        serialPort = SerialPort.getCommPort(COM);

        //Connection Setting
        serialPort.setBaudRate(9600);
        serialPort.setNumDataBits(8);
        serialPort.setNumStopBits(0);
        serialPort.setParity(0);

        boolean isOpen =  serialPort.openPort();
        log.info("isOpen ? " + isOpen);

        if(isOpen){
            this.outputStream   = serialPort.getOutputStream();
            this.inputStream    = serialPort.getInputStream();

            return new ResponseEntity("CONNECTION SUCCESS..!", HttpStatus.OK);
        }
        else{
            return new ResponseEntity("CONNECTION FAIL..!", HttpStatus.BAD_GATEWAY);
        }
    }

    @GetMapping("/led/{value}")
    public void led_Control(@PathVariable("value") String value, HttpServletRequest request) throws IOException {
        log.info("GET /arduino/led/value : " + value + " IP : " + request.getRemoteAddr());
        if(serialPort.isOpen()){
            outputStream.write(value.getBytes());
            outputStream.flush();
        }
    }

}

 

 

다 했으면 localhost:8080/arduino/index로 들어가 페이지가 나오는지 확인해본다.

 

 

 

 

실행하기 전 arduino IDE로 가서 USB 포트가 아닌 포트를 설정을 해주고 업로드와 스케치를 눌러 준다.

 

 

그리고 페이지를 실행시켜 자신의 아두이노 포트와 연결시킨 후 LED ON / OFF를 눌러본다.

그러면 LED가 불이 켜지고 꺼지고를 느끼고 싶다.

 

 

 

다른 사람의 아두이노 전등도 키고 끌 수 있다. 

 

 

 

이번에는 visual studio로 들어가서 실행해본다.

 

폼을 이렇게 만들어 주고

 

폼 이벤트 처리 코드를 작성해주고 

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.Net.Http;
using System.Net;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }


        private void conn_btn_Click(object sender, EventArgs e)
        {
            
            
            String port =  this.comboBox1.Items[  this.comboBox1.SelectedIndex  ].ToString();
            Console.WriteLine("PORT : " + port);
            HttpWebRequest request=null;
            HttpWebResponse response = null;
            try
            {   
                request =  (HttpWebRequest)HttpWebRequest.Create("http://localhost:8080/arduino/connection/" + port);
                request.Method = "GET";
                request.ContentType = "application/json";
                //request.Timeout = 30 * 1000;

                response = (HttpWebResponse)request.GetResponse();
           
                if(response.StatusCode == HttpStatusCode.OK)
                {
                    Console.WriteLine("RESPONSE CODE : " + response.StatusCode);

                }
               
            }catch(Exception ex)
            {
                Console.WriteLine("Ex : " + ex);
            }


        }

        private void led_on_btn_Click(object sender, EventArgs e)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:8080/arduino/led/1");
            request.Method = "GET";
            request.ContentType = "application/json";
            //request.Timeout = 30 * 1000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        }

        private void led_off_btn_Click(object sender, EventArgs e)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost:8080/arduino/led/0");
            request.Method = "GET";
            request.ContentType = "application/json";
            //request.Timeout = 30 * 1000;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }
    }
}

 

 

Form 디자인 코드를 작성해준다. ( 폼 이벤트 처리 코드의 InitializeComponent를 ctrl+클릭하면 나온다. )

namespace WindowsFormsApp1
{
    partial class Form1
    {
        /// <summary>
        /// 필수 디자이너 변수입니다.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 사용 중인 모든 리소스를 정리합니다.
        /// </summary>
        /// <param name="disposing">관리되는 리소스를 삭제해야 하면 true이고, 그렇지 않으면 false입니다.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form 디자이너에서 생성한 코드

        /// <summary>
        /// 디자이너 지원에 필요한 메서드입니다. 
        /// 이 메서드의 내용을 코드 편집기로 수정하지 마세요.
        /// </summary>
        private void InitializeComponent()
        {
            this.groupBox1 = new System.Windows.Forms.GroupBox();
            this.conn_btn = new System.Windows.Forms.Button();
            this.comboBox1 = new System.Windows.Forms.ComboBox();
            this.groupBox2 = new System.Windows.Forms.GroupBox();
            this.led_off_btn = new System.Windows.Forms.Button();
            this.led_on_btn = new System.Windows.Forms.Button();
            this.groupBox1.SuspendLayout();
            this.groupBox2.SuspendLayout();
            this.SuspendLayout();
            // 
            // groupBox1
            // 
            this.groupBox1.Controls.Add(this.conn_btn);
            this.groupBox1.Controls.Add(this.comboBox1);
            this.groupBox1.Location = new System.Drawing.Point(23, 25);
            this.groupBox1.Name = "groupBox1";
            this.groupBox1.Size = new System.Drawing.Size(200, 60);
            this.groupBox1.TabIndex = 0;
            this.groupBox1.TabStop = false;
            this.groupBox1.Text = "groupBox1";
            // 
            // conn_btn
            // 
            this.conn_btn.Location = new System.Drawing.Point(103, 20);
            this.conn_btn.Name = "conn_btn";
            this.conn_btn.Size = new System.Drawing.Size(75, 23);
            this.conn_btn.TabIndex = 1;
            this.conn_btn.Text = "연결";
            this.conn_btn.UseVisualStyleBackColor = true;
            this.conn_btn.Click += new System.EventHandler(this.conn_btn_Click);
            // 
            // comboBox1
            // 
            this.comboBox1.FormattingEnabled = true;
            this.comboBox1.Items.AddRange(new object[] {
            "COM1",
            "COM2",
            "COM3",
            "COM4",
            "COM5",
            "COM6",
            "COM7",
            "COM8",
            "COM9",
            "COM11"});
            this.comboBox1.Location = new System.Drawing.Point(7, 21);
            this.comboBox1.Name = "comboBox1";
            this.comboBox1.Size = new System.Drawing.Size(81, 20);
            this.comboBox1.TabIndex = 0;
            this.comboBox1.SelectedIndexChanged += new System.EventHandler(this.comboBox1_SelectedIndexChanged);
            // 
            // groupBox2
            // 
            this.groupBox2.Controls.Add(this.led_off_btn);
            this.groupBox2.Controls.Add(this.led_on_btn);
            this.groupBox2.Location = new System.Drawing.Point(23, 100);
            this.groupBox2.Name = "groupBox2";
            this.groupBox2.Size = new System.Drawing.Size(200, 83);
            this.groupBox2.TabIndex = 1;
            this.groupBox2.TabStop = false;
            this.groupBox2.Text = "groupBox2";
            // 
            // led_off_btn
            // 
            this.led_off_btn.Location = new System.Drawing.Point(103, 21);
            this.led_off_btn.Name = "led_off_btn";
            this.led_off_btn.Size = new System.Drawing.Size(75, 48);
            this.led_off_btn.TabIndex = 1;
            this.led_off_btn.Text = "OFF";
            this.led_off_btn.UseVisualStyleBackColor = true;
            this.led_off_btn.Click += new System.EventHandler(this.led_off_btn_Click);
            // 
            // led_on_btn
            // 
            this.led_on_btn.Location = new System.Drawing.Point(7, 21);
            this.led_on_btn.Name = "led_on_btn";
            this.led_on_btn.Size = new System.Drawing.Size(75, 48);
            this.led_on_btn.TabIndex = 0;
            this.led_on_btn.Text = "ON";
            this.led_on_btn.UseVisualStyleBackColor = true;
            this.led_on_btn.Click += new System.EventHandler(this.led_on_btn_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 12F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(273, 199);
            this.Controls.Add(this.groupBox2);
            this.Controls.Add(this.groupBox1);
            this.Name = "Form1";
            this.Text = "Form1";
            this.groupBox1.ResumeLayout(false);
            this.groupBox2.ResumeLayout(false);
            this.ResumeLayout(false);

        }

        #endregion

        private System.Windows.Forms.GroupBox groupBox1;
        private System.Windows.Forms.Button conn_btn;
        private System.Windows.Forms.ComboBox comboBox1;
        private System.Windows.Forms.GroupBox groupBox2;
        private System.Windows.Forms.Button led_off_btn;
        private System.Windows.Forms.Button led_on_btn;
    }
}

 

 

 

- 폼 실행

group Box1에 해당 포트를 선택하고 on/off를 눌러본다.

그러면 led에 불이 들어오는 것을 확인 할 수 있다.