import pygame

import random

import numpy as np

import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation

import serial

import os

import math

import time

from codrone_edu import *


#그래픽카드 사용 선언

os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"

os.environ["CUDA_VISIBLE_DEVICES"] = "1"



#아두이노 연결

ser = serial.Serial(port='COM7', baudrate=9600,

                    parity=serial.PARITY_NONE,

                    stopbits=serial.STOPBITS_ONE,

                    bytesize=serial.EIGHTBITS)



pygame.init()


width, height = 800, 800

radius = 360

w = 300

motion = 0

degree = 0

distance = 0

radarDist = 0

firstRun = 0

ser.x = 0

ser.y = 0

blip_countdown = 0

target = 0



fig, ax = plt.subplots(subplot_kw=dict(polar=True)) #polar 그리기

lines, = ax.plot([], [], lw=3, color='green')



def sigmoid(x):

    

    return 1 / (1 + np.exp(-x))


# Generate x values

x_values = np.linspace(-7, 7, 100)

# 타겟을 보여준다

ser_x = radius + random.uniform(-0.05, 0.05) * radius * 5

ser_y = radius + random.uniform(-0.05, 0.05) * radius * 5


def init():

    lines.set_data([], [])

    return lines,


def update(frame):

    degree = frame

    ser_x = np.radians(degree)

    ser_y = 1  # y축을 중심으로 데이터 계산

   # lines.set_data(x, y)

    lines.set_ydata(sigmoid(x_values - frame))

    return lines,


# Pygame Setup

screen = pygame.display.set_mode((width, height))

pygame.display.set_caption('Radar Simulation')

clock = pygame.time.Clock()


def calculate_distance():

    speed_of_light = 34

    round_trip_time = 2.5  

    target_position = np.array([ser_x, ser_y])

    radar_center = np.array([width/2, height/2])

    #distance = np.linalg.norm(target_position - radar_center)

    distance =  speed_of_light * round_trip_time * (target_position - radar_center) 

    return distance,




def drawRadar():

    screen.fill((0, 0, 0))  # 배경색


    


    # 레이더 원을 그린다

    for i in range(1, 4):

        circle_radius = i * 105

        circle_center = (radius, radius)


        pygame.draw.circle(screen, (0, 205, 0), circle_center, circle_radius, 2)


        font = pygame.font.SysFont("arial", 20)

        text = font.render(str(i * 45), True, (0, 255, 0))


    

        text_position = (radius + 10, radius - i * 95)

        screen.blit(text, text_position)



    # 회전하는 각도 360도 회전 후에 다시 1도로

    if degree <= 359:

        motion = 1

    if degree >= 1:

        motion = 0


    pygame.draw.aaline(screen, (0, 250, 0), (radius, radius),

                       (radius + math.cos(math.radians(degree + 360)) * w+5,

                        radius + math.sin(math.radians(degree + 360)) * w+5), 7)


    if motion == 0:

        for i in range(60): #부채꼴 회전하는 선 60도

            angle = math.radians(degree + 360 + i)

            pygame.draw.aaline(screen, (0, 250, 0),

                               (radius, radius),

                               (radius + math.cos(angle) * w,

                                radius + math.sin(angle) * w), 9)

    else:

        for i in range(-20, 0):

            angle = math.radians(degree + 360 + i)

            color_value = max(0, 20 - (10 * abs(i)))

            pygame.draw.aaline(screen, (0, color_value, 0),

                               (radius, radius),

                               (radius + math.cos(angle) * w,

                                radius + math.sin(angle) * w), 9)



    for i in range(12):

         angle = np.radians(30 * i)  

         line_start = (radius, radius)

         line_end = (radius + np.cos(angle) * radius,

                     radius + np.sin(angle) * radius)    

         pygame.draw.line(screen, (0, 255, 0), line_start, line_end, 2)    

         font = pygame.font.SysFont("arial", 20)

         text = font.render(str(i * 30), True, (0, 255, 0))   

         text_position = (line_end[0] + 5, line_end[1] - 10)

         screen.blit(text, text_position)

    

    # 부채꼴 효과

    x_blip = np.radians(degree)

    y_blip = 1  

    lines.set_data(x_blip, y_blip)


    # 글을 쓴다

    Distance = calculate_distance()

    font = pygame.font.SysFont("arial", 20)

    text_angle = font.render(f"Angle: {degree} deg", True, (0, 255, 0))

    text_distance = font.render(f"Distance: {distance} cm", True, (0, 255, 0))

    text_make = font.render(f"Radar Screen",True,(0,255,0))

    text_auther = font.render(f"Product by Woo Yong Kim",True,(0,255,0))

    screen.blit(text_angle, (100, 740))

    screen.blit(text_distance, (100, 760))

    screen.blit(text_make, (300,740))

    screen.blit(text_auther, (300,770))




# Main loop로 실행 코드

running = True

round_number = 0  # Initialize round number

while running:

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False


    # Update

    degree += 1

    if degree >= 360:

        degree = 0

        round_number += 1  # 회전각을 1씩 증가


    # 그리기 실행

    drawRadar()

    calculate_distance()

    #update(frame)

    

    


    pygame.display.flip()

    clock.tick(60)

  








댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기
 
 
 

library(plotly)

library(dplyr)

library(rearrr)

library(rgdal)

library(sp)

library(sf)

library(tidyr)

library(spreadr)

library(spatstat.sparse)

library(REdaS)


co <- read.csv('d://kaggle/dataset_5/countries_of_the_world.csv')

co  



df <- read.csv('https://raw.githubusercontent.com/plotly/datasets/master/2014_world_gdp_with_codes.csv')

df[,2] <- as.numeric(df[,2])

df[,2] <- log(df[,2])

df



co[,2] <- as.numeric(co[,2])

co[,2] <- log(co[,2])


co <- data.frame(

  "x" = runif(20),

  "y" = runif(20)

)

elev <- read.csv("d://filebox/dataset_4/csv/elevp.csv")

elev


qk <- read.csv('d://filebox/csv/earthquakes.csv')

qk

qk[,2] <- as.numeric(qk[,2])

qk[,2] <- log(qk[,2])



deg2rad <- function(deg) {

  (deg * pi) / (180)

}


deg2rad(sin(45))



fig1 <- function(x,y){

  2*x+x+1=y

}


linear_fun<-function(x){

  4*x^2+2*x+1

}




nlat <- 100

nlon <- 100

lat <- seq(-180, 180, length.out = nlat)

lon <- seq(-90, 90, length.out = nlon)

lat <- matrix(rep(lat, nlon), nrow = nlat)

lon <- matrix(rep(lon, each = nlat), nrow = nlat)

pg <- list(nlat,nlon)

str(pg)

table(list = c(nlat,nlon))


#

LAND_ISO <- c("AUT","BEL","BGR","HRV","CYP","CZE","DNK","EST","FIN","FRA","DEU","GRC","HUN","IRL",

              "ITA","LVA","LTU","LUX","MLT","NLD","POL","PRT","ROU","SVK","SVN","ESP","SWE","GBR",

              "USA","CHN","KOR","JPN","EGY","ARE","JOR","SAU","AUS","KEN","NGA","BRA")

value <- runif(length(LAND_ISO), 1, 20)

df <- data.frame(LAND_ISO, value)



#

LAND_ISO <- c("USA")

value <- runif(length(LAND_ISO), 1, 10)

df <- data.frame(LAND_ISO, value)


#

LAND_ISO <- c("KOR","JPN","CHN")

value <- runif(length(LAND_ISO), 1, 10)

df <- data.frame(LAND_ISO, value)


g <- list(

  projection = list(type = 'orthographic'),

  showland = TRUE,

  landcolor = toRGB("LightGrey"),

  showocean = TRUE,

  oceancolor = toRGB("LightBlue"),

  showlakes = TRUE,

  lakecolor = toRGB("Blue"),

  showrivers = TRUE,

  rivercolor = toRGB("Blue"),

  resolution = 100,

  showcountries = TRUE,

  countrycolor = toRGB("Black"),

  showlon = TRUE,

  loncolor = toRGB("White"),

  showlat = TRUE,

  latcolor = toRGB("White"),

  showcities = TRUE,

  citycolor = toRGB("Red"),

  showmark = TRUE,

  markcolor = toRGB("Green")

)


x <- rnorm(177, mean = 5)

y <- rnorm(177, mean = -5)

z <- rnorm(177, mean = 5 )

x <- c(1:177)

y <- c(1:177)

z <- c(1:177)

df <- data.frame(x,y,z)


recruitment_info <- data.frame(Centre = c("CentreA", "CentreB", "CentreC"),

                               Lat = c(51.51770, 52.48947, 51.45451),

                               Long = c(-0.100400, -1.898575, -2.587910),

                               GroupA = c(907, 1910, 4419),

                               GroupB = c(47, 116, 277), stringsAsFactors = TRUE)

recruitment_info


recruitment_info <- recruitment_info %>% 

  gather(Group, values, Centre, Lat, Long)

recruitment_info


table(recruitment_info)

str(recruitment_info)


dat <- map_data(map = "world", region = "UK")

dat


##

table2%>%spread(key= 1,value = Group)



#1

fig <- plot_geo(bt)


fig1 <- fig %>% layout(geo = g)%>%

  add_trace(bt,y = trace_1, name = 'trace 0', mode = 'lines')%>%

  add_segments(x = cos(0), y = 180 ,xend = 360 ,yend = tan(89))%>%

  add_segments(x = sin(45), y = cos(720),xend = 180,yend = tan(89))

fig2 <- fig %>% layout(geo = g)%>%

  add_trace(bt,y = trace_2, name = 'trace 1', mode = 'lines')%>%

  add_segments(x = 180, y = cos(0),xend = 0,yend = tan(89))


print(fig1,fig2)



#2


fig <- plot_geo(type = 'scattergeo',group = bt,

                mode = "lines")%>%

  

  add_trace( colors = 'Greens',locations = 'world')%>%

  

  add_markers(x = 0,y = 90)%>%

  add_markers(x = 127, y = 37)%>%

  add_markers(x = 0, y = 0)%>%

  add_markers(x = 0, y = 51)%>%

  add_segments(x = sin(45), cos(45),xend = cos(45),yend = sin(45))%>%

  add_segments(x = 127, y = 37 ,xend = -360 ,yend = sin(45))%>%

  add_segments(x = -cos(15), y = -180 ,xend = -360 ,yend = sin(45))%>%

  add_segments(x = -cos(15), y = -180 ,xend = -360 ,yend = tan(15))%>%

  add_segments(x = -cos(90), y = -180 ,xend = -360 ,yend = tan(89))%>%

  add_segments(x = 0, y = -60 ,xend = -40 ,yend = tan(45))%>%

  add_segments(x = cos(90), y = 180 ,xend = 360 ,yend = tan(89))%>%

  add_segments(x = cos(15), y = 180 ,xend = 360 ,yend = sin(45))%>%

  add_segments(x = 0, y = 60 ,xend = 40 ,yend = tan(45))%>%

  add_segments(x = 0,y = 0, xend = 180, yend = tan(60))%>%

  add_segments(x = tan(45),y = 180 , xend = 90, yend = tan(15))%>%

  add_segments(x = 0,y = 90 , xend = 90, yend = tan(15))%>%

  add_segments(x = 0,y = sin(60) , xend = sin(60), yend = 0)%>%

  add_segments(x = sin(45),y = 0 , xend = 0, yend = -sin(45))%>%

  add_segments(x = -sin(45),y = 0 , xend = 0, yend = -sin(45))%>%

  add_segments(x = 0,y = 0 , xend = -sin(45), yend = -sin(45))%>%

  add_segments(x = 0,y = 0 , xend = -sin(45), yend = tan(45))%>%

  add_segments(x = 90,y = 90 , xend = -sin(45), yend = tan(45))%>%

  

  add_trace(

    x = ~nlon,y = ~nlat,group = bt,

    line = list(shape = "spline"),

    showlegend = TRUE,

    hoverinfo = "y") %>%

  add_trace(bt,y = trace_6, name = 'trace 6', mode = 'lines')%>%

  add_trace(bt,y = trace_7, name = 'trace 7', mode = 'lines')%>%

  

  

  

  layout( geo = g)


print(fig)



###3


fig <- plot_geo(dat,type = 'scattergeo', mode = 'markers')%>%

  

  add_trace( colors = 'Greens',locations = 'uk')%>%

  add_trace(recruitment_info,

            group_by = "Centre",

            line = list(shape = "spline"),

            showlegend = TRUE,

            hoverinfo = "region")%>%

  add_markers(y = 51, x = 0)%>%

  

  layout( geo = g )



fig





#4

fig <- plot_geo(type = 'scattergeo', mode = 'lines',

                lat = c(0,45,90,-45,0), lon = c(0,-45,-90,45,0))

fig <- fig %>% 

  add_surface(bt,

              x = cos(deg2rad(lon)) * cos(deg2rad(lat)),

              y = sin(deg2rad(lon)) * cos(deg2rad(lat)),

              z = sin(deg2rad(lat)),

              surfacecolor = matrix(bt, nrow = nlat, ncol = nlon),

              showscale = TRUE, hoverinfo = c("lon","lat"),

              contours = list(

                x = list(highlight = TRUE),

                y = list(highlight = TRUE),

                z = list(highlight = TRUE)

              ))%>%

  

  

  add_trace(bt,

            group = NULL,

            line = list(shape = "circle"),

            showlegend = TRUE,

            hoverinfo = "skip")%>%

  

  layout(geo = g)

fig





#5

fig <- plot_geo(bt,type = 'scattergeo', mode = 'lines')


fig <- fig %>% 

  add_lines(y = list(0,90,0,-90,90), x = list(0,-90,0,90,-90))%>%

  add_lines(y = list(90,0,-90,0), x = list(-90,0,90,0))%>%

  add_lines(x = list(0,45,90,-45,0,45,90), y = list(0,-45,-90,45,0,-45,-90))%>%

  add_trace(bt,x = x, y = y,

            line = list(shape = "circle"),showlegend = TRUE,

            hoverinfo = "skip")%>% 

  

  

  layout(geo = g)


fig


bbox(fig)





#6

fig <- plot_geo(df,type = 'scattergeo', mode = 'markers', fill = TRUE)


fig <- fig %>% 

  

  add_trace(x = ~lon, y = ~lat,

            line = list(shape = "circle"),showlegend = TRUE,hoverinfo = list("lon","lat","alt"))%>% 

  add_sf(

    data = sf::st_as_sf(maps::map("world", plot = TRUE, fill = TRUE)),

    x = ~ 1.001 * cos(deg2rad(x)) * cos(deg2rad(y)),

    y = ~ 1.001 * sin(deg2rad(x)) * cos(deg2rad(y)),

    z = ~ 1.001 * sin(deg2rad(y)),

    color = I("black"), size = I(1),

    hoverinfo = "skip"

    

  ) %>%

  

  add_surface(

    x = cos(deg2rad(lon)) * cos(deg2rad(lat)),

    y = sin(deg2rad(lon)) * cos(deg2rad(lat)),

    z = sin(deg2rad(lat)),

    surfacecolor = matrix(df, nrow = nlat, ncol = nlon),

    showscale = TRUE, hoverinfo = "skip",

    contours = list(

      x = list(highlight = TRUE),

      y = list(highlight = TRUE),

      z = list(highlight = TRUE)

    ))%>%          

  

  add_segments(x = -cos(15), y = -180 ,xend = -360 ,yend = sin(45))%>%

  add_segments(x = -cos(15), y = -180 ,xend = -360 ,yend = tan(15))%>%

  add_segments(x = -cos(90), y = -180 ,xend = -360 ,yend = tan(89))%>%

  #add_segments(x = sin(45), cos(45),xend = cos(45),yend = sin(45))%>%

  #add_segments(x = 90,y = 90 , xend = -sin(45), yend = tan(45))%>%

  #add_segments(x = tan(45),y = 180 , xend = 90, yend = tan(15))%>%

  #add_segments(x = 90,y = 90 , xend = -sin(45), yend = tan(45))%>%

  #add_segments(x = 0,y = 90 , xend = 90, yend = tan(15))%>%

  

  layout( geo = g, annotation = NULL)


print(fig)





##7

fig <- plot_geo(df,type = 'scattergeo', mode = 'lines') 


fig <- fig %>% 

  

  

  

  add_sf(

    data = sf::st_as_sf(maps::map("world", plot = TRUE, fill = TRUE)),

    x = ~ 1.001 * cos(deg2rad(x)) * cos(deg2rad(y)),

    y = ~ 1.001 * sin(deg2rad(x)) * cos(deg2rad(y)),

    z = ~ 1.001 * sin(deg2rad(y)),

    color = I("black"), size = I(1),

    hoverinfo = "skip"

  ) %>%

  

  add_surface(

    x = cos(deg2rad(lon)) * cos(deg2rad(lat)),

    y = sin(deg2rad(lon)) * cos(deg2rad(lat)),

    z = sin(deg2rad(lat)),

    surfacecolor = matrix(df, nrow = nlat, ncol = nlon),

    showscale = TRUE, hoverinfo = "skip",

    contours = list(

      x = list(highlight = TRUE),

      y = list(highlight = TRUE),

      z = list(highlight = TRUE)

    ))%>%

  

  add_trace(x = x, y = y, z = z,location = ~LAND_ISO,

            line = list(shape = "circle"),showlegend = TRUE,

            hoverinfo = "skip")%>% 

  

  add_trace(

    z = ~value, locations = ~LAND_ISO,

    color = ~value, colors = 'Purples' ) %>%

  

  

  add_trace(

    type = "choroplethmapbox",

    geojson = paste(c(

      "https://gist.githubusercontent.com/cpsievert/",

      "7cdcb444fb2670bd2767d349379ae886/raw/",

      "cf5631bfd2e385891bb0a9788a179d7f023bf6c8/", 

      "us-states.json"

    ), collapse = ""),

    locations = row.names(state.x77),

    z = state.x77[, "Population"] / state.x77[, "Area"],

    span = I(0)

  ) %>%

  

  add_trace(

    type = "choroplethmapbox",

    geojson = paste(c("https://raw.githubusercontent.com/mlampros/DataSets/master/california.geojson"),

                    collapse = ""),

    locations = row.names(state.x77),

    z = state.x77[, "Population"] / state.x77[, "Area"],

    span = I(1)

  ) %>%

  

  add_segments(x = -cos(15), y = -180 ,xend = -360 ,yend = sin(45))%>%

  

  add_segments(x = -100, xend = -50, y = 50, yend = 75) %>%

  

  layout( geo = g )



fig



#8


fig <- plot_geo(df) %>%

  add_trace(z = ~COUNTRY., color = ~CODE, colors = 'Reds',

            text = ~COUNTRY, locations = ~CODE) %>%

  add_trace(df,

            group_by = "CODE",

            line = list(shape = "markers"),

            showlegend = TRUE,

            hoverinfo = "skip")%>%

  colorbar(title = 'GDP (log)') %>%

  layout(title = '', geo = g)

print(fig)





#9

fig <- plot_geo(type = 'scattergeo', mode = 'splines')


fig <- plot_geo(co)%>%  

  add_trace(z = ~Population, color = ~Population, colors = 'Reds',

            text = ~Region, locations = ~Country) %>%

  colorbar(title = 'Population') %>%

  

  

  

  layout( geo = g )



fig





#10

fig <- plot_geo(qk,type = 'scattergeo', mode = 'markers')%>%

  

  add_trace(z = ~impact.magnitude, color = ~location.name, colors = 'Reds',

            text = ~location.depth, locations = c(~location.longitude,~location.latitude)) %>%

  colorbar(title = 'impact.magnitude') %>%

  

  add_trace(qk,

            group_by = "impact.magnitude",

            line = list(shape = "markers"),

            showlegend = TRUE,

            hoverinfo = "skip")%>%

  

  layout( geo = g )



fig



test <- read.OGR("https://raw.githubusercontent.com/mlampros/DataSets/master/california.geojson")

test


rt <- geojson_read("https://opendata.arcgis.com/datasets/772f3621fa354ec9abf3ba33f3ace59e_0.geojson")

rt                    



file <- system.file("examples", "california.geojson", package = "geojsonio")

(out <- geojson_read(file))

rt <- geojson_read("https://opendata.arcgis.com/datasets/772f3621fa354ec9abf3ba33f3ace59e_0.geojson")

rt                    )



library("rjson")

json_file <- "https://gist.githubusercontent.com/cpsievert/"

"7cdcb444fb2670bd2767d349379ae886/raw/"

"cf5631bfd2e385891bb0a9788a179d7f023bf6c8/" 

"us-states.json"

json_data <- fromJSON(paste(readLines(json_file), collapse=""))

json_data

str(json_data)



댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기
 
 
 

import processing.opengl.*;

import meter.*;

import blinkstick.*;

import vsync.*; 

import java.awt.event.KeyEvent;

import java.io.IOException;

import java.io.InputStream;

import java.util.List;

//import java.util.Arrays;

import java.util.*;

//import java.util.arrayList;

import processing.serial.*;

import java.io.File;

import java.io.FileReader;

import java.io.BufferedReader;

import java.io.DataInputStream;

import java.io.EOFException;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.InputStreamReader;


Serial myPort;

//초기값은 null값

String myString = null;

String serialAngle = null;

String serialDistance =null;

String serialData =null;

int objectDistance = 0;

int Angle, Distance;

int point;

int cx,cy;

int x,y;

float d;

int radius = 360;               // 목표물의 반지름                  

int degree = 0;                 // 모터회전각

int value = 0;                  // 초음파 시리얼 데이터

float motion = 0;                 // 모터구동              

int radarDist = 0;              // 레이더의 거리별 수치   

boolean signal = false;

int sizeIncrease = 10;

int initialSize = 70;

int count = 10;

PVector center;

float circleSize = 0;

float angle = 0;

float Radius = 0;

String Dist = null;

int duration = 0; 


 

void setup() 

{

  size (1280, 900,P3D);

  background(0);

  smooth();

  

 // println(Serial.list());

myPort = new Serial(this,"COM5", 19200);//Port 설정

myString = myPort.readStringUntil(',');

print(Serial.list());




}


    

         


void draw() //화면에 레이더를 띄움

{

  

 // draw();

  Radar();

  textDraw();

  drawRadar();

  drawPlot();

  serialEvent(myPort);

 

 

  center = new PVector(width/4, height/4);

  this.radius = 0;

   

  PVector point = new PVector(random(width/4), random(height/4));

  float deltaX = center.x - point.x;

  float deltaY = center.y - point.y;

  angle = atan2(deltaX, deltaY);


  float x = center.x + cos(degree)*180;

  float y = center.y + sin(degree)*180;


  ellipse(x, y, 5, 5);


  if(Distance<20){

  ellipse(center.x, center.y, 5, 5);  

  }

  

  if(Distance>40){

    ellipse(0,0,0,0);

    redraw();

  };


  

   //redraw(float x, float y, float deltaX, float deltaY, float radius){

   // center = PVector point(x, y, deltaX, deltaY);

   

  angle += PI/90;

  

   }


public class serialDistance {

        int serialDistance(int n) {

        int point ;


        while (n != 1) {  // n이 1이 되기 전까지 반복

            if (n % 2 == 1) {  // n이 홀수라면 순간 이동(2배) 불가

                point++;         // : 한 칸 점프해줌.

            }

          

            n /= 2;  // 순간 이동

        }

           

        return ++point;  // 현재 위치가 1이기 때문에 ans + 1을 반환

        exit();


        

}

###########################################################################################


void Radar() //화면구성

{

  

  noStroke();

  

 // fill(0,4); 

  rect(0, 0, 1280, 720);

  fill(10,255,10);

  

  translate(640,660,30); //화면의 좌표

  noFill();

  strokeWeight(1);//선굵기

  stroke(10,255,10);  //녹색선

  //반원을 그린다

  arc(0,0,1200,1200,PI,TWO_PI);

  arc(0,0,934,934,PI,TWO_PI);

  strokeWeight(1);

  stroke(255,10,10);

  arc(0,0,660,660,PI,TWO_PI);

  arc(0,0,400,400,PI,TWO_PI);

  arc(0,0,140,140,PI,TWO_PI);

  strokeWeight(1);

  //선들을 긋는다

  stroke(10,255,10);

  line(+(-640),0,640,0);

  line(0,0,+(-554),+(-320));

  line(0,0,+(-320),+(-554));

  line(0,0,0,+(-640));

  line(0,0,320,+(-554));

  line(0,0,554,+(-320));

  

  

}


void textDraw()

{

  pushMatrix();

  translate(640,660,30); //화면의 좌표

  fill(255);

  stroke(0,255,0);

  strokeWeight(1);

  textSize(25);  

  

  //글쓰기

text("0cm", cx, cy,cx-630,cy-700); 

text("20cm", cx, cy, cx-630,cy-1020); 

text("40cm", cx, cy, cx-630,cy-1280); 

text("Angle: " +Float.toString(Angle) +" °", cx-1200,cy-640,10);

text("Distance: "+Float.toString(Distance)+"cm", cx-900,cy-640); 


text("Ultrasonic Screen",cx-1200,cy-1250,10); 

text("Product by Woo Yong Kim",cx-1200,cy-1220,10);

  //cx와  cy로 좌표를 찾는다


if(Distance<40){

  noFill();

  stroke(255,0,0);

strokeWeight(4);

text("Alarm  : "+Boolean.compare(true,false)+" ",cx-250,cy-640);

}

if (Distance>40){

text("Alarm  : "+Boolean.compare(true,false)+"  ",cx+250,cy-640);

}


  popMatrix();

}


###################################################################################


void serialEvent(Serial p){

    

       

      myString = p.readStringUntil('.');

      if(myString != null){

       String[] list = split(myString, ',');

      }

     


    float length = 340*60;

    //  float Distance = (340*Length)/10000/2;

     // Distance = (duration / 2) * 0.0343;

      float  Distance= duration*0.034/2;

     

    String serialDistance = "Distance";

    String serialAngle = "Angle";

     Distance = Integer.parseInt(serialDistance); 

     Angle = Integer.parseInt(serialAngle); 

     System.out.println(Distance);

     System.out.println(Angle);

     

 //  float D = (width/2.0/30.0)*(float)Distance; //거리계산공식

 //  float circleSize = map(sin(frameCount * .01),-1.0,1.0,0.0,20.0);

    //for (int k = 0; k < count; k++) {

      serialDistance = "serialDistance";

              serialAngle = "Angle";

             int Distance = Integer.parseInt(serialDistance); 

             int Angle = Integer.parseInt(serialAngle);

           System.out.println(serialDistance);

           System.out.println(Angle);

    

      Angle = int(list[0]); 

   Distance = int(list[1]);

   

   stroke(0,255,0);

        println("Angle : "+Angle+"");

       // println(" Distance : "+Float.toString(serialDistance) + "cm");

        println(" Distance : "+Distance + "cm");

        println(" Alarm : "+Boolean.compare(true,false)+"");

    

    }

       

    

    //  float Distance = (width/2.0/30.0)*(float)Distance; //거리계산공식

//     ArrayList<Integer> lists = new ArrayList<>(Arrays.asList(0,1));


 //    if (lists.size() > 0) {

 //        System.out.println(lists.get(1));

//}


    // Distance = int(list[1]);

//serialDistance = int(list[1]);

           // signal = boolean(list[0]);   

    // signal = boolean(list[1].replace("",""));

         

 


 //###############################################################################################

 

  void drawRadar(){

 // pushMatrix();

  translate(cx,cy-10,30);

  strokeWeight(4);//선의 굵기

  stroke(255, 0, 0);//붉은선

  //float d = (width/2.0/30.0)*(float)Distance; //거리계산공식

  //line(0,0, width/2*cos(radians(radarAngle)), -width/2*sin(radians(radarAngle)));

  //int duration = Distance*2;

 // float Distance = duration / 29.0 / 2.0;

  float Distance= duration*0.034/2;

  float circleSize = map(sin(frameCount * .01),-1.0,1.0,0.0,20.0);

 

  // strokeWeight(4);

  //  stroke(0,255,0);

  if(Distance <40){

  stroke(0,255,0);

 line(0,0, width/2*cos(radians(Angle)), -width/2*sin(radians(Angle)));//부채꼴선

  } else{

   stroke(255,0,0);

   line(0,0, width/2*cos(radians(Angle)), -width/2*sin(radians(Angle)));

//  popMatrix();

  }

  

  

  

  for (int j = 0; j < count-8; j++){

    if(Distance<40){

   // circle(width/2, height/2, initialSize + i*sizeIncrease);

   circle(0,-200,(circleSize-5) + j*sizeIncrease);

  

  //balls();

 // ellipse(0,-200, circleSize,j*sizeIncrease);//????

 // balls.endDraw();

  }

  }


#################################################################################

Ball[] balls =  { 

  new Ball(100, 400, 5)

 // new Ball(700, 400, 50) 

};




  for (Ball b : balls) {

    b.update();

    b.display();

    b.checkBoundaryCollision();

  }

  

  balls[0].checkCollision(balls[0]);

}


//#######################################################################################################


void drawPlot()

{

  translate(640,666,30);

  strokeWeight(4);//선의 굵기

  stroke(255, 0, 0);//붉은선

  //float d = (width/2.0/30.0)*(float)Distance; //거리계산공식

 line(0,0,(height-height*0.12),-(height-height*0.12)); 

 // float d =  340*Distance/10000/2;

  float d = duration*0.034/2;

 if (motion == d) {                    

    for (float i = 0; d > Distance; d++) {     

      stroke(255.0, 0);              

      line(0, 0, radius + cos(radians(d)), radius + sin(radians(d))); // line(start x, start y, end x, end y)

    //  ellipse(radius,radius,cos(radians(d)),sin(radians(d)));

    }

  } else {                              

    for (float i = 0; d < Distance ; d--) {     

      stroke(0,200-(20*i), 0);          

      line(radius, radius, radius + cos(radians(360+i)), radius + sin(radians(360+i)));

    }

  } 

}


 //######################################################################################################


public class test {


void main(String args[]) { 


      Integer intObj=Integer.valueOf(args[args.length-2]);

      int i = intObj.intValue();


      if(args.length > 1) 

         System.out.println(i);

      if(args.length > 0)

         System.out.println(i - 1);

      else 

         System.out.println(i - 2);

   }

}


댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기
 
 
 

import processing.serial.*;     // 시리얼 라이브러리

Serial myPort;

String myString = null;// 시리얼 포트 null값

float x, y;                       

int radius = 360;               

int w = 300;                    //너비

int degree = 0;                 // 모터 회전각

int value = 0;                  // 목표값

int motion = 0;                 // 모터 회전방향

int[] newValue = new int[360];  // 새로 만들어진 각도

int[] oldValue = new int[360];  // 초기 시작값(부채꼴의 선을 만든다)

PFont f;                   // 폰트

int radarDist = 0;              // 거리

int firstRun = 0;               // 초기값에서 나온 각도

 


void setup(){

  // setup the background size, colour and font.

  size(830,800,P3D);

  background (0); // 0 = black

  PFont f;

  f = createFont("bold", 20);

  textFont(f, 20);

  

  //myPort = new Serial(this, Serial.list()[0], 9600);

  //myPort.bufferUntil('\n');

  myPort = new Serial(this,"COM8", 9600);//Port 설정

  myString = myPort.readStringUntil(',');//포트값 읽기

  

}

 


void draw(){

  

  serialEvent(myPort);//실행시키기

  

  

  fill(0);                              // 배경색

  noStroke();                           

  ellipse(radius, radius, 750, 750);    // 레이더 반경

  rectMode(CENTER);  // 레이더 중앙

  //rectMode(radius,radius,0,0);

  rect(350,402,800,100);                // 화면 크기

  if (degree <= 359) {                  // 시계방향으로 회전

    motion = 1;                         // 

  }

  if (degree <= 1) {                    // 반시계방향으로 회전

    motion = 0;                         // 

  }

 

  strokeWeight(7);                      // 회전하는 선굵기

  if (motion == 0) {                    // 시계방향으로 회전한다면

    for (int i = 0; i <= 60; i++) {     // 60개의 라인이 blip효과를 만든다

      stroke(0, 150, 0);             // 선의 색깔(RGB 컬러)

      line(radius, radius, radius + cos(radians(degree+(360+i)))*w, radius + sin(radians(degree+(360+i)))*w);

     // line(start x, start y, end x, end y)

    }

  } 

  else {                              // 반시계방향으로 회전

    for (int i = 0; i >= 20; i--) {     // 60개의 라인이 blip효과

      stroke(0,20-(10*i), 0);          // 0-255까지 RGB컬러

      line(radius, radius, radius + cos(radians(degree+(360+i)))*w, radius + sin(radians(degree+(360+i)))*w);

    }

 }

  

  noStroke();                           

  

  fill(0,50,0);                         

  beginShape();                         // 그리기 시작

   for (int i = 0; i < 60; i++) {     //360도까지 i만큼 증가

      x = radius + cos(radians((60+i)))*((oldValue[i]*2)); // x좌표

      y = radius + sin(radians((60+i)))*((oldValue[i]*2)); // y좌표

      vertex(x, y);                     // 수직선

    }

  endShape();                           

 

  

  fill(0,250,0);

  beginShape();

    for (int i = 0; i < 60; i+=30) {

      x = radius + cos(radians((degree+i)))*(((newValue[i]+oldValue[i])/2)*2); // 평균값(부채꼴 효과)

      y = radius + sin(radians((degree+i)))*(((newValue[i]+oldValue[i])/2)*2);

      vertex(x, y);

    }

  endShape();

  

  if (firstRun >= 360) {

    stroke(250,0,0);

    strokeWeight(1);

    noFill();

      for (int i = 0; i > 90; i+=5) {

        if (oldValue[i] - newValue[i] > 35 || newValue[i] - oldValue[i] > 5) {

          x = radius + cos(radians((degree+i)))*(newValue[i]*2);

          y = radius + sin(radians((degree+i)))*(newValue[i]*2);

          ellipse(x, y, 10, 10); 

        }

      }

  }



  //6개의 거리 표시

  for (int i = 0; i <=7; i++){

    noFill();

    strokeWeight(2);

   // stroke(0, 255-(30*i), 0);

    stroke(0, 205, 0);

    ellipse(radius, radius, (100*i), (100*i)); 

    fill(0, 255, 0);

    noStroke();

    text(Integer.toString(radarDist+25), 380, (310-(radarDist*2)), 30, 30); // 150cm까지 표시

    radarDist+=25; //거리 간격은 25cm

  }

  radarDist = 0; 

  

 

   for (int i = 0; i <= 12; i++) {  //30도 간격으로 12개의 각도표시(360도를 만든다)

    strokeWeight(2);

    stroke(0,255, 0);

    line(radius, radius, radius + cos(radians(360+(30*i)))*w, radius + sin(radians(360+(30*i)))*w);

   fill(0,255,0);

    //stroke(0,255,0);

   

  

 if (360+(30*i) >= 360) {

      stroke(255,0,0);

      text(Integer.toString(360+(30*i)) ,

         (radius+10) + cos(radians(30+(30*i)))*(w+20), (radius+10) + sin(radians(30+(30*i)))*(w+20), 20, 50);

    } else {

      text(Integer.toString(360+(30*i)), radius + cos(radians(360+(30*i)))*w, radius + sin(radians(360+(30*i)))*w, 60,40);

    }


   }



 

  strokeWeight(2);

  fill(0);

 // rect(350,402,800,100);

  fill(0, 255, 0);

  PFont f;

  f = createFont("Arial", 20);

  textFont(f, 20);

  textSize(20);

  text("Angle: "+Integer.toString(degree)+",", 100, 740);

  text("Distance: "+Integer.toString(value)+"cm", 100, 760);

  //integer값으로 표시

  

  textSize(20);

  rect(70,20,150,100);

  fill(0, 100, 0); 

  text("Radar Plot:", 100, 50, 150, 50);


}



void serialEvent (Serial myPort) {  //실행시키는 중요한 구문

  

   try{

      myString = myPort.readStringUntil('.');

      if(myString != null){

        String[] list = split(myString, ',');

        degree = int(list[0]);

        radarDist = int(list[1].replace(".",""));

         

        print("Angle : "+degree+",");

        println(" Distance : "+radarDist + "cm");

      }

    }catch(Exception e){

    }


        if (value > 330) {

          value = 330; 

        }

        if (value < 20) {

          value = 20;

        }

      oldValue[value] = newValue[value]; //

      newValue[value] = value;  

     // oldValue[value] = newValue[value];

      //newValue[degree] = radarDist;


      firstRun++;

      if (firstRun > 360) {

        firstRun = 360; // 

      }

  

  

}    


https://www.youtube.com/shorts/4BNVpKRxo34

 


댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기
 
 
 

library(tidyverse)

library(serial)

library(magrittr)

library(plotly)

library(dplyr)

library(GPSCDF)

library(geodata)

library(plot3D)

library(tibble)

library(ggplot2)

library(sf)

library(mapview)

library(ggmap)

library(PlotContour)

library(gganimate)

library(rnaturalearth)

library(rnaturalearthdata)

library(oce)

library(sf)

library(sp)

library(spData)

library(neuralnet)

library(rgdal)

library(rgeos)

library(maps)

library(tree)

library(GNSSseg)

library(scan)

library(vistime)

library(shiny)

library(ggfortify)

library(xts)

library(signal)

library(Rwave)

library(seewave)

library(tuneR)

library(tidyverse)

library(audio)

library(fftw)

library(cowplot)


listPorts()



rm(list = ls())

graphics.off()


##데이터연결

myArduino <-  serialConnection(

  name = "sketch_gps_up",

  port = "COM4",

  mode = "9600,n,8,1" ,

  buffering = "none",

  newline = TRUE,

  eof = "",

  translation = "cr",

  handshake = "none",

  buffersize = 4096

)


open(myArduino)


close(myArduino)



##데이터불러오기

stopTime <- Sys.time() +4

gpsdata <- " "

textSize <- 0



while(Sys.time() < stopTime)

{

  newText <- read.serialConnection(myArduino)

  if(0 < nchar(newText))

  {

    gpsdata <- paste(gpsdata, newText)

  }

}


cat(" \r\n\n", gpsdata, " \r\n\n")


##데이터형변환

myArduino$GPVTG<-as.numeric(myArduino$GPVTG)

myArduino$GPGGA<-as.numeric(myArduino$GPGGA)

myArduino$GPGSA<-as.numeric(myArduino$GPGSA)

myArduino$GPGSV<-as.numeric(myArduino$GPGSV)

myArduino$GPGLL<-as.numeric(myArduino$GPGLL)



comb<-stack(list(v1="GPVTG",v2="GPGGA",v3="GPGSA",v4="GPGSV",v5="GPGLL"))

comb

print(comb)

table(comb)

as.list(comb)


values<-c("$GPVTG","$GPGGA","$GPGSA","$GPGSV","$GPGLL")

ind<-c("v1","v2","v3","v4","v5")

lst<-list()

lst(ind)<-values

gps_values <- cat(values,ind)



class(comb)

mode(comb)

str(comb)


##상태보기

print(myArduino)

summary(myArduino)



table(myArduino)

table(gpsdata)



##결과저장

gps_table <- write.table(cat(gpsdata), "d://filebox/csv/gps_data_1.csv",

                      sep = ",",

                      row.names = FALSE,

                      quote = FALSE,

                      append = FALSE,

                      na = "NA"

                    )


gps_table <- read.csv("d://filebox/csv/gps_data_1.csv")

gps_table




str(gps_table)

table(gps_table)



pres <- data.frame(gpsdata,Position = rep(c("$GPVTG","$GPGGA","$GPGSA","$GPGSV","$GPGLL"),

                                             each = 12),

                   name =c("a","b"),

                   color = c('#cbb69d', '#603913', '#c69c6e'),

                   fontcolor = c("black", "white", "black"))


shinyApp(

  ui = plotOutput("gps_result"),

  server = function(input, output) {

    output$gps_result <- renderPlot({

      vistime(pres, col.event = "Position", col.group = "gpsdata")

      a    <- faithful[, 2]

      b <- seq(position, length.out = input$col + 1)

      hist(gpsdata, breaks = NULL, col = 'white', borde)

    })

  }

)







library(shiny)

shinyServer(


  function(input,output){


    datasetInput <- reactive({

      switch(input$gps_result,

             "$GPVTG"="$GPVTG",

             "$GPGGA"="$GPGGA",

             "$GPGSA"="$GPGSA",

             "$GPGSV"="$GPGSV",

             "$GPGLL"="$GPGLL")

    })


    output$summary <- renderPrint({

      gps_result <- datasetInput()

      summary(gps_result)

    })})


summary(gps_result)

gps_result


table(gps_result)

str(array(gps_result))


ggplot(data = gps_result,

       aes(x = ra, y = rb)) +

  geom_point()




gps_result_days <- xts(1:5,seq(Sys.Date(),date.length = 20,by = "days"))

gps_result_days



#####데이터저장

gps_table_sql <- read.csv("d://filebox/csv/gps_data_sql.csv")

gps_table_sql


str(gps_table_sql)

table(gps_table_sql)



gps_scan <- scan(gps_table,"d://filebox/csv/gps_data_1.csv",what=list(character(0)))

gps_scan


str(gps_scan)

table(gps_scan)


gps_scan<-data.frame(vals = 1:5)

gps_scan %>% mutate(new_vals=case_when(vals <= 1 ~ "$GPVTG",

                             vals <= 2 ~ "$GPGGA",

                             TRUE ~ "$GPGSA,$GPGSV,$GPGLL"))


date <- format(Sys.Date(),"%m-%d-%y")

xts(gps_scan,seq(Sys.Date("date")))


r1<-data.frame(a = "$GPVTG",b = "N*30")

r2<-data.frame(a = "$GPGGA",b = "0,00,99.99,,,,,,*48")

r3<-data.frame(a = "$GPGSA",b = "A,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30")

r4<-data.frame(a = "$GPGSV",b = "1,1,00*79")

r5<-data.frame(a = "$GPGLL",b = ",,,,,,V,N*64")


gps_result <- rbind(r1,r2,r3,r4,r5)

gps_result

arrange(gps_result,r1,r2,r3,r4,r5)


gps_result <- data.frame(ra=c("$GPVTG","$GPGGA","$GPGSA","$GPGSV","$GPGLL"),

                         rb=c("N*30","0,00,99.99,,,,,,*48",

                              "A,A,1,,,,,,,,,,,,,99.99,99.99,99.99*30","1,1,00*79",",,,,,,V,N*64"))


summary(table(gps_result))


gps_sheet<-table(array(data.frame(arrange(gps_result))))

gps_sheet


locations <-data(world)


gt <- outer(gps_scan,gps_result,paste,sep=",")

gt



table(array(data.frame(gt)))








fnx <- function(x, fn) sin(2 * pi * fn * x) * exp(-fn * abs(x))

ffs <- 1000

tp <- seq(gps_scan)

pp <- fnx(gps_scan, 30)

fs <- 2e3

t <- seq(0, 1.2, 1 / fs)

d <- seq(0,1.5, 1/3)

dd <- cbind(d, 4^-d)

z <- pulstran(t, dd, pp, ffs)

plot(t, z, type = "l", xlab = "", ylab = "",

     main = "gps")




data_wave <- read.csv("d://filebox/csv/gps_data_sql.csv")


summary(data_wave)





#############시그날 그래프

t <- seq(0, 3*pi, length.out = 100)


df = data.frame(x = gps_result$rb,1:10,

                y = gps_result$ra,sample(c(1,10), 10, replace = TRUE))

summary(df)


y = gps_result$ra

x =gps_result$rb


theme_set(theme_light())

wvfm <- ggplot(df,mapping = aes(x = seq_len(length(y)), y = y))+

  geom_step()+

  geom_line(color = 'blue')+


  labs(x = "Signal", y = "GPS_Proceed")+

  theme(plot.title = element_text(hjust = 0.5))


ggplotly(wvfm)




##################




which(is.na(gps_result$ra))


GNSSseg(

  gps_result,

  lyear = 365.25,

  lmin = 1,

  Kmax = 30,

  selection.K = "BM_BJ",

  S = 0.75,

  f = TRUE,

  selection.f = TRUE,

  threshold = 0.001,

  tol = 1e-04

)



gps_scan <- scan(gpsdata,"d://filebox/csv/gps_data_1.csv",what=list(character(0)))

gps_scan

lyear=365.25

Kmax=4

lmin=1

result=GNSSseg(gps_scan,lyear,Kmax=Kmax,selection.K="none")

plot_GNSS(gps_result$ra)


runif(gps_result)



flightplot(gps_result)

#######


library(keras)

install_keras()


gpsdata0 <- as.matrix(gps_result)

dimnames(gpsdata0) <- NULL


gpsdata0 <- normalize(gpsdata0[,1:3])



gpsdata_mat <- cbind(gpsdata0, comb[,1])

head(gpsdata_mat)



set.seed(1000)

test_gps = sample(1:nrow(gpsdata_mat),nrow(gpsdata_mat)+0.25)

test_gps



data <- matrix(runif(1000*100), nrow = 1000, ncol = 100)

labels <- matrix(round(runif(1000, min = 0, max = 1)), nrow = 1000, ncol = 1)



model %>% fit(data, labels, epochs=10, batch_size=32)


model <- keras_model_sequential()

model %>%

  layer_lstm(units = 32, return_sequences = TRUE, input_shape = c(timesteps, data_dim)) %>%

  layer_lstm(units = 32, return_sequences = TRUE) %>%

  layer_lstm(units = 32) %>% # return a single vector dimension 32

  layer_dense(units = 10, activation = 'softmax') %>%

  compile(

    loss = 'categorical_crossentropy',

    optimizer = 'rmsprop',

    metrics = c('accuracy')

  )


# generate dummy training data

x_train <- array(runif(1000 * timesteps * data_dim), dim = c(1000, timesteps, data_dim))

y_train <- matrix(runif(1000 * num_classes), nrow = 1000, ncol = num_classes)


# generate dummy validation data

x_val <- array(runif(100 * timesteps * data_dim), dim = c(100, timesteps, data_dim))

y_val <- matrix(runif(100 * num_classes), nrow = 100, ncol = num_classes)


# train

model %>% fit(

  x_train, y_train, batch_size = 64, epochs = 5, validation_data = list(x_val, y_val)

)




gpsdata0 <- keras_model_sequential()

gpsdata0 %>%

  layer_dense(units = 16, input_shape = c(12)) %>%

  layer_activation('sigmoid') %>%

  layer_dense(units = 6) %>%

  layer_activation('softmax')


gpsdata0 %>% compile(

  optimizer = 'rmsprop',

  loss = 'categorical_crossentropy',

  metrics = c('accuracy')

)


gpsdata0 <- keras_model_sequential(input_shape = c(12)) %>%

  layer_dense(units = 32) %>%

  layer_activation('sigmoid') %>%

  layer_dense(units = 10) %>%

  layer_activation('softmax')


gpsdata0 %>% fit(

  train.data,

  labels,

  epochs = 100,

  batch_size = 5,

  validation_split = 0.5

)



gpsdata0

history(gpsdata0$compiled_loss)

plot(gpsdata0)


class <- gpsdata0 %>% predict_classes(labels, batch_size = 128)


# 혼동행렬

table(gpsdata0, class)


score <- gpsdata0 %>% evaluate(test.data, gpsdata.testtarget, batch_size = 128)

print(score)








seoul <- ne_countries(scale = "medium", returnclass = "sf")


gps_sheet.animate <- ggplot(data=seoul)+

  geom_sf()+

  coord_sf(xlim= c(126.55,127.88), ylim= c(36.55,37.65), expand = TRUE)+

  geom_point(data = gps_sheet, aes(x = x, y = 0, size = 80),alpha = 3.8)+

  #geom_text(aes(x = min(lon), y = min(lat), label = as.factor(order)) , hjust= 10, vjust = 10, alpha = 0.5,  col = "red", size = 20)

  scale_color_gradientn(colours = oce::oceColors9A(120))+

  ggrepel::geom_text_repel(data = gps_sheet%>%slice(seq(3,20,25)),

                           aes(x = x, y = 0, label = x ))+

  #transition_states( state_length = 0, transition_length = 2) +

  transition_time(POSIXCT)+

  ease_aes("sine-in-out")+enter_fade() +

  exit_fade() +

  #ease_aes('quadratic-in-out')

  shadow_mark()



animate(gps_scan.animate,width=1020, height=880, res=35)

animate(gis_table.animate, width = 1020, height = 880, fps = 25, duration = 15, rewind = FALSE)





gps_line <- readLines("d://filebox/csv/gps_data.csv",n=21)

gps_line


str(gps_line)

table(gps_line)

summary(table(gps_line))



gps_scan <- scan("d://filebox/csv/gps_data.csv",what=list(character(0)))%>%mutate(x=108)

gps_scan


str(gps_scan)

table(gps_scan)



ftable(tapply(gps_scan,list("$GPVTG","$GPGGA","$GPGSA","$GPGSV","$GPGLL"),mean))






library(XLConnect)

writeWorksheetToFile("d://filebox/csv/gps_data_xl.xlsx", gpsdata, sheet="gps data")


library(readxl)

gps_xl <- read_xlsx("d://filebox/csv/gps_data_xl.xlsx")

gps_xl


seoul <- ne_countries(scale = "medium", returnclass = "sf")


gps_scan.animate <- ggplot(data=seoul)+

  geom_sf()+

  coord_sf(xlim= c(126.55,127.88), ylim= c(36.55,37.65), expand = TRUE)+

  geom_point(data = gps_scan, aes(x = x, y = 0, size = 80),alpha = 3.8)+

  #geom_text(aes(x = min(lon), y = min(lat), label = as.factor(order)) , hjust= 10, vjust = 10, alpha = 0.5,  col = "red", size = 20)

  scale_color_gradientn(colours = oce::oceColors9A(120))+

  ggrepel::geom_text_repel(data = gps_scan%>%slice(seq(3,108,25)),

                           aes(x = x, y = 0, label = x))+

  #transition_states( state_length = 0, transition_length = 2) +

  transition_time(POSIXct)+

  #seq.default(length.out = 2)+

  ease_aes("sine-in-out")+

  enter_fade() + exit_fade() +

  #ease_aes('quadratic-in-out')

  shadow_mark()



animate(gps_scan.animate,width=1020, height=880, res=35)


##데이터상태보기

for(gpsdata in 1:2){

  cat("\n",paste0(gpsdata,gps_scan))

}


str(gps_scan)

summary(gps_scan)


plot(gps_scan)


##

for(i in 1:2) {

array(comb)


  cat( "/n",paste0(i,comb))

  print(i)

  extent = "COM4"

  break()

}



str(comb)

summary(comb)

table(comb)

plot(comb)


summary(table(comb))

plot(values~ind,comb)



basemap <- get_openstreetmap("seoul", zoom = 12)

ggmap(basemap)








df<- ggplot(data=gps_line)+

  geom_sf(map(database = "world"))+

  coord_sf(xlim=Long, ylim=Lat, expand = "device")+

  geom_point(data = gps_line, aes(x = values, y = ind, colour = bathy))+

  scale_color_gradientn(colours = oce::oceColors9A(120))+

  ggrepel::geom_text_repel(data = gps_line,

                           aes(x = values, y = ind))+

  transition_time(gps_line)+

  ease_aes("sine-in-out")+

  shadow_mark()

df



seoul <- ne_countries(scale = "medium", returnclass = "sf")


df.animate(comb+

             #geom_point(aes(c("GPVTG","GPGGA","GPGSA","GPGSV","GPGLL")))+

             geom_point(gps_line)+

             add_segments(x=x,y=y))+

  #add_markers(x = ~x,y = ~y,z = ~z)+

  addNode(plot(myArduino),n)





df.animate <- ggplot(data=seoul)+

  geom_sf()+

  coord_sf(xlim= c(126.55,127.88), ylim= c(36.55,37.65), expand = TRUE)+

  geom_point(data = df, aes(x = lon, y = lat, size = 80),alpha = 3.8)+

  #geom_text(aes(x = min(lon), y = min(lat), label = as.factor(order)) , hjust= 10, vjust = 10, alpha = 0.5,  col = "red", size = 20)

  scale_color_gradientn(colours = oce::oceColors9A(120))+

  ggrepel::geom_text_repel(data = df%>%slice(6),

                           aes(x = x, y = y, label = c("GPVTG","GPGGA","GPGSA","GPGSV","GPGLL" )))+

  #transition_states( state_length.out = gps_table, transition_rane = 2) +

  transition_time(c("GPVTG","GPGGA","GPGSA","GPGSV","GPGLL"))+

  ease_aes("sine-in-out")+enter_fade() +

  exit_fade() +

  #ease_aes('quadratic-in-out')

  shadow_mark()



animate(df.animate,width=1020, height=880, res=35)

animate(df.animate, width = 1020, height = 880, fps = 25, duration = 15, rewind = FALSE)


#####

z <- Sys.time()

unclass(z)

floor(unclass(z)/86400)

(now <- as.POSIXlt(Sys.time()))

unlist(unclass(now))

now$year + 1900

months(now); weekdays(now)


z <- 1472562988


as.POSIXct(z, origin = "1960-01-01")

as.POSIXct(z, origin = "1960-01-01", tz = "GMT")


#z <- c(10485849600, 10477641600, 10561104000, 10562745600)

#as.Date(as.POSIXct(z, origin = "1582-10-14", tz = "GMT"))


z <- 1579598122120

op <- options(digits.secs = 3)


as.POSIXct((z+0.1)/1000, origin = "1960-01-01")

options(op)


z <- 7.343736909722223e5

as.POSIXct((z - 719529)*86400, origin = "1970-01-01", tz = "UTC")


as.POSIXlt(Sys.time(), "GMT")

as.POSIXlt(Sys.time(), "EST" )


cols <- c("code", "coordinates", "TZ", "comments")

tmp <- read.delim(file.path(R.home("share"), "zoneinfo", "zone.tab"),

                  header = FALSE, comment.char = "#", col.names = cols)

if(interactive())

  View(tmp)




################


library(ggmap)

library(tidyverse)


map_data <- read.table("d://filebox/csv/gps_data.csv")



map.view <- map_data %>%

  filter(127.26 <= lon & lon <= 127.20,

         36.85 <= lat & lat <= 36.91)



qmplot(x=lon, y=lat, data = map_data)

seoul <- get_map("seoul", color="bw",zoom=18)

ggmap(seoul)

ggmap(world) +

  geom_point(data=gps_line,aes(x=long,y=lat,color=n.trips),size=3,alpha=0.75)+

  scale_colour_gradient(high="red",low='green')+

  theme(axis.ticks = element_blank(),axis.text = element_blank())+

  xlab('')+ylab('')



##########example

library(lubridate)

library(forcats)

## Pick coordinates that approximates dropoffs near the Met

lat <- c(36.7785,36.780)

lon <- c(126.963,126.9615)


taxi <- read.csv('c://.csv') %>%

  mutate(weekday.pickup = wday(tpep_pickup_datetime,label=TRUE,abbr=TRUE),

         weekday.dropoff = wday(tpep_dropoff_datetime,label=TRUE,abbr=TRUE),

         hour.trip.start = factor(hour(tpep_pickup_datetime)),                                 # hour of day

         hour.trip.end = factor(hour(tpep_dropoff_datetime)),                                  # hour of day

         day = factor(mday(tpep_dropoff_datetime)),                                             # day of month

         trip.duration = as.numeric(difftime(tpep_dropoff_datetime,tpep_pickup_datetime,units="mins")),   # trip duration in minutes

         trip.speed = ifelse(trip.duration > 1, trip_distance/(trip.duration/60), NA),          # trip speed in miles/hour

         payment_type_label = fct_recode(factor(payment_type),

                                         "Credit Card"="1",

                                         "Cash"="2",

                                         "No Charge"="3",

                                         "Other"="4")) %>%

  filter(day %in% c(1:28))



## Filter data for drop-offs near the Met

seoul <- taxi %>%

  filter(dropoff_longitude > lon[1] & dropoff_longitude < lon[2],

         dropoff_latitude > lat[1] & dropoff_latitude < lat[2])


ggmap(seoul) +

  geom_point(data=gps_line,

             aes(x=dropoff_longitude,y=dropoff_latitude),size=.03,alpha=0.3,color="red")

######




df <- read.csv("d://filebox/csv/gps_data.csv") %>% mutate(df = 1:1)

df


table(df)

str(df)

summary(df)









plot(gps_line,

     type = "l", col = "blue", lwd = 3)


df <- neuralnet %>% cat(gps_table)

df


###

gpx_parsed <- htmlTreeParse(file = 'd://filebox/csv/gps_data.csv', useInternalNodes = TRUE)

gpx_parsed

dygraphs::dyPlotter(gps_data,pathSApply(doc = gpx_parsed,path = "/gps_data.csv", fun = xmlAttrs))




ggplot(df, aes(x = Lon, y = Lat)) +

  coord_quickmap() +

  geom_point()



#####

library(here)

library(XML)

library(lubridate)

library(Rwave)

library(rwavelet)

library(mathml)

library(zoo)


path_tmp <- paste0("d://filebox/csv/gps_data.csv")

parsed <- htmlTreeParse(file = "d://filebox/csv/gps_data.csv", useInternalNodes = TRUE)

parsed



coords <- xpathSApply(parsed, path = "//trkpt/Lat", xmlAttrs)

coords <- xpathSApply(parsed, path = "//trkpt/Lon", xmlAttrs)

#elev   <- xpathSApply(parsed, path = "//trkpt/ele", xmlValue)

#tser <- xpathSApply(parsed, path = "//trkpt/time", xmlValue)


A ="2023-01-01"

B ="2023-04-07"

zooser <- zoo(x=tser$time, order.by=as.POSIXct(tser$pTime, origin="2023-01-01"))

window(zooser, start=A, end=B)


#

path_tmp <- data.frame(parsed,

                    # ts_POSIXct = ymd_hms(tser$time, tz = "EST"),

                     lat = as.numeric(coords[latitude,]),

                     lon = as.numeric(coords[longitude,])

                    # elev = as.numeric(ele)

)

head(path_tmp)

plot(path_tmp)

#ts_POSIXct



#####

ggplot(gps_line,aes(x=Lat,y=Long))+

  geom_segment(aes(x=0,y=Date,xend=Lat,yend=Long))+

  geom_point()







#############

bbox <- make_bbox(range(gps_data$Longitude), range(gps_data$Longitude))

dat_df_map <- get_map(center = c(mean(range(gps_data$Longitude)), mean(range(gps_data$Longitude))), zoom = 15)


dat_df_dist_marks <-

  dat_df %>%

  mutate(dist_m_cumsum = cumsum(dist_to_lead_m)) %>%

  mutate(dist_m_cumsum_km_floor = floor(dist_m_cumsum / 1000)) %>%

  group_by(dist_m_cumsum_km_floor) %>%

  filter(row_number() == 1, dist_m_cumsum_km_floor > 0)


# generate plot

plt_path_fancy <-

  ggmap(dat_df_map) +

  geom_point(data = gps_data, aes(lon, lat, col = elev),

             size = 1, alpha = 0.5) +

  geom_path(data = dat_df, aes(lon, lat),

            size = 0.3) +

  geom_label(data = dat_df_dist_marks, aes(lon, lat, label = dist_m_cumsum_km_floor),

             size = 3) +

  labs(x = "Longitude",

       y = "Latitude",

       color = "Elev. [m]",

       title = "Track of one Marta's run on 2022-01-01")

plt_path_fancy




############


library(leaflet)

leaflet() %>%

  addTiles(group = "OSM") %>%

  add_trace(gps_line, weight = 1, fillColor = "grey", color = "black",

            opacity = 1, fillOpacity = 0.6)%>%

  add_markers(x = ~Longitude,y = ~Latitude, popup = gps_table)





##


##

library(maps)

data(world.cities)

library(rbokeh)

caps <- dplyr::filter("d://filebox/csv/gps_data.csv", x == 1)

caps <- prettyNum(gps_data$gps_line, big.mark = ",")

plot <- suppressWarnings(figure(width = 800, height = 450, padding_factor = 0) %>%

                           ly_map("world", col = "gray") %>%

                           ly_points(lon, lat, data = caps, size = 5,

                                     hover = c(gps_line,x)))


widgetframe::frameWidget(plot,width=1000,height=600)







isOpen(myArduino)



write.serialConnection(myArduino)

read.serialConnection(myArduino)


summary(myArduino)







write.serialConnection(myArduino, rawToChar(as.raw(15)) ) # 0x0F

write.serialConnection(myArduino, c(15,20) ) # 0x0F, 0x14

write.serialConnection(myArduino, c(0x6F,0x6C) )



tran <- read.serialConnection(myArduino)

print(tran)



close(myArduino)



##

library(DiagrammeR)

mermaid(str(gpsdata))



library()

vec <- rnorm(1200)

mat <- matrix(vec, nrow=30, ncol=40)

whitenoise <- im(mat)

whitenoise <- im(mat, xrange=c(0,1), yrange=c(0,1))

whitenoise <- im(mat, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))

whitenoise <- im(vec, xcol=seq(0,1,length=40), yrow=seq(0,1,length=30))

plot(whitenoise)



댓글(0) 먼댓글(0) 좋아요(0)
좋아요
l 공유하기 l 북마크하기찜하기