Skip to content
Snippets Groups Projects
Commit bc192a54 authored by hz5's avatar hz5
Browse files

code cleanup

parent 34c058de
No related branches found
No related tags found
No related merge requests found
...@@ -7,10 +7,8 @@ ...@@ -7,10 +7,8 @@
long unsigned int rxId; long unsigned int rxId;
unsigned char len = 0; unsigned char len = 0;
unsigned char distance[2]; unsigned char distance[2];
// Enter a MAC address and IP address for your controller below.
// The IP address will be dependent on your local network:
byte mac[] = { byte mac[] = {
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED
}; };
...@@ -18,21 +16,21 @@ IPAddress remote_ip(192, 168, 0, 100); ...@@ -18,21 +16,21 @@ IPAddress remote_ip(192, 168, 0, 100);
int remote_port = 3491; int remote_port = 3491;
int local_port = 3495; int local_port = 3495;
char packetBuffer[UDP_TX_PACKET_MAX_SIZE]; // buffer to hold incoming packet, char packetBuffer[UDP_TX_PACKET_MAX_SIZE];
MCP_CAN CAN0(9); // Set CS to pin 9 MCP_CAN CAN0(9);
EthernetUDP udp; EthernetUDP udp;
void setup() void setup()
{ {
Serial.begin(115200); Serial.begin(115200);
// Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled. // Initialize MCP2515 running at 16MHz with a baudrate of 500kb/s and the masks and filters disabled.
if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK) if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
Serial.println("MCP2515 Initialized Successfully!"); Serial.println("MCP2515 Initialized Successfully!");
else else
Serial.println("Error Initializing MCP2515..."); Serial.println("Error Initializing MCP2515...");
CAN0.setMode(MCP_NORMAL); // Set operation mode to normal so the MCP2515 sends acks to received data. CAN0.setMode(MCP_NORMAL); // Set operation mode to normal so the MCP2515 sends acks to received data.
pinMode(CAN0_INT, INPUT); // Configuring pin for /INT input pinMode(CAN0_INT, INPUT); // Configuring pin for /INT input
...@@ -62,7 +60,7 @@ void loop() ...@@ -62,7 +60,7 @@ void loop()
int result = distance[0]+distance[1]*256; int result = distance[0]+distance[1]*256;
Serial.println(result); Serial.println(result);
} }
// send the message via udp // send the message via udp
udp.beginPacket(remote_ip, remote_port); udp.beginPacket(remote_ip, remote_port);
udp.write((char *)distance); udp.write((char *)distance);
...@@ -90,6 +88,6 @@ void loop() ...@@ -90,6 +88,6 @@ void loop()
} }
//send signal to LED //send signal to LED
byte sndStat = CAN0.sendMsgBuf(0x100, 0, 1, (byte*)&packetBuffer); byte sndStat = CAN0.sendMsgBuf(0x100, 0, 1, (byte*)&packetBuffer);
delay(500); delay(500);
} }
...@@ -12,22 +12,22 @@ int distance; ...@@ -12,22 +12,22 @@ int distance;
long unsigned int rxId; long unsigned int rxId;
unsigned char len = 0; unsigned char len = 0;
unsigned char rxBuf[8]; unsigned char rxBuf[8];
char msgString[128]; // Array to store serial string char msgString[128];
unsigned long previousMillis = 0; // will store last time LED was updated unsigned long previousMillis = 0;
const long interval = 300; // interval at which to blink (milliseconds) const long interval = 300; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED int ledState = LOW; // ledState used to set the LED
MCP_CAN CAN0(10); // Set CS to pin 10 MCP_CAN CAN0(10); // Set CS to pin 10
void setup() { void setup() {
pinMode(trigPin, OUTPUT); pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT); pinMode(echoPin, INPUT);
pinMode(ledPin, OUTPUT); pinMode(ledPin, OUTPUT);
Serial.begin(115200); Serial.begin(115200);
if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK) if(CAN0.begin(MCP_ANY, CAN_500KBPS, MCP_16MHZ) == CAN_OK)
Serial.println("MCP2515 Initialized Successfully!"); Serial.println("MCP2515 Initialized Successfully!");
else else
Serial.println("Error Initializing MCP2515..."); Serial.println("Error Initializing MCP2515...");
CAN0.setMode(MCP_NORMAL); // Change to normal mode to allow messages to be transmitted CAN0.setMode(MCP_NORMAL); // Change to normal mode to allow messages to be transmitted
...@@ -53,7 +53,7 @@ void loop() { ...@@ -53,7 +53,7 @@ void loop() {
byte sndStat = CAN0.sendMsgBuf(0x100, 0, 2, (byte*)&distance); byte sndStat = CAN0.sendMsgBuf(0x100, 0, 2, (byte*)&distance);
delayMicroseconds(150); delayMicroseconds(150);
if(!digitalRead(CAN0_INT)) // If CAN0_INT pin is low, read receive buffer if(!digitalRead(CAN0_INT)) // If CAN0_INT pin is low, read receive buffer
...@@ -62,21 +62,21 @@ void loop() { ...@@ -62,21 +62,21 @@ void loop() {
//receive yes /no //receive yes /no
Serial.println(rxBuf[0]); Serial.println(rxBuf[0]);
} }
if(rxBuf[0] == 'y') if(rxBuf[0] == 'y')
{ {
unsigned long currentMillis = millis(); unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) { if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED // save the last time you blinked the LED
previousMillis = currentMillis; previousMillis = currentMillis;
// if the LED is off turn it on and vice-versa: // if the LED is off turn it on and vice-versa:
if (ledState == LOW) { if (ledState == LOW) {
ledState = HIGH; ledState = HIGH;
} else { } else {
ledState = LOW; ledState = LOW;
} }
// set the LED with the ledState of the variable: // set the LED with the ledState of the variable:
digitalWrite(ledPin, ledState); digitalWrite(ledPin, ledState);
} }
......
import os import os
import cv2 import cv2
import numpy as np import numpy as np
from picamera.array import PiRGBArray
from picamera import PiCamera
import tensorflow as tf import tensorflow as tf
import argparse import argparse
import sys import sys
import socket import socket
import errno import errno
from picamera.array import PiRGBArray
from picamera import PiCamera
IM_WIDTH = 1280 IM_WIDTH = 1280
IM_HEIGHT = 720 IM_HEIGHT = 720
# local port and ip # local port and ip
IP = "192.168.0.100" IP = "192.168.0.100" # need to change to ip assigned by switch
PORT = 3491 PORT = 3491
TCP_PORT = 3490 TCP_PORT = 3490
...@@ -26,20 +26,15 @@ sys.path.append('..') ...@@ -26,20 +26,15 @@ sys.path.append('..')
from utils import label_map_util from utils import label_map_util
from utils import visualization_utils as vis_util from utils import visualization_utils as vis_util
# Name of the directory containing the object detection module we're using
MODEL_NAME = 'ssdlite_mobilenet_v2_coco_2018_05_09'
# Grab path to current working directory # Grab path to current working directory
CWD_PATH = os.getcwd() CWD_PATH = os.getcwd()
PATH_TO_CKPT = "/home/pi/Documents/ssd_mobilenet_v1_coco_2018_01_28/frozen_inference_graph.pb"
PATH_TO_LABELS = os.path.join(CWD_PATH,'data','mscoco_label_map.pbtxt') PATH_TO_LABELS = os.path.join(CWD_PATH,'data','mscoco_label_map.pbtxt')
# Number of classes the object detector can identify # Number of classes the object detector can identify
NUM_CLASSES = 90 NUM_CLASSES = 90
# Load the label map. # Load the label map.
label_map = label_map_util.load_labelmap(PATH_TO_LABELS) label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True) categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories) category_index = label_map_util.create_category_index(categories)
...@@ -48,7 +43,7 @@ category_index = label_map_util.create_category_index(categories) ...@@ -48,7 +43,7 @@ category_index = label_map_util.create_category_index(categories)
detection_graph = tf.Graph() detection_graph = tf.Graph()
with detection_graph.as_default(): with detection_graph.as_default():
od_graph_def = tf.GraphDef() od_graph_def = tf.GraphDef()
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: with tf.gfile.GFile('/home/pi/Documents/ssd_mobilenet_v1_coco_2018_01_28/frozen_inference_graph.pb', 'rb') as fid:
serialized_graph = fid.read() serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph) od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='') tf.import_graph_def(od_graph_def, name='')
...@@ -82,10 +77,9 @@ freq = cv2.getTickFrequency() ...@@ -82,10 +77,9 @@ freq = cv2.getTickFrequency()
font = cv2.FONT_HERSHEY_SIMPLEX font = cv2.FONT_HERSHEY_SIMPLEX
for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True): for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=True):
t1 = cv2.getTickCount() t1 = cv2.getTickCount()
# Acquire frame and expand frame dimensions to have shape: [1, None, None, 3]
# i.e. a single-column array, where each item in the column has the pixel RGB value
frame = np.copy(frame1.array) frame = np.copy(frame1.array)
frame.setflags(write=1) frame.setflags(write=1)
frame_expanded = np.expand_dims(frame, axis=0) frame_expanded = np.expand_dims(frame, axis=0)
...@@ -96,19 +90,18 @@ for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port= ...@@ -96,19 +90,18 @@ for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=
feed_dict={image_tensor: frame_expanded}) feed_dict={image_tensor: frame_expanded})
# receive signal from ECU # receive signal from ECU
distance = 1000 distance = 1000
while True: while True:
try: try:
data,addr = serverSock.recvfrom(10) data,addr = serverSock.recvfrom(10)
distance = int.from_bytes(data, "big") distance = int.from_bytes(data, "big")
except socket.error as error: except socket.error as error:
if error.errno == errno.EAGAIN: if error.errno == errno.EAGAIN:
break break
else: else:
print(error.errno) print(error.errno)
print(distance) print(distance)
# Send signal back to ECU # Send signal back to ECU
if num > 0 and distance < 150: if num > 0 and distance < 150:
...@@ -118,7 +111,6 @@ for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port= ...@@ -118,7 +111,6 @@ for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=
serverSock.sendto(b"n", addr) serverSock.sendto(b"n", addr)
led_status = 'OFF' led_status = 'OFF'
# Draw the results of the detection (aka 'visulaize the results')
vis_util.visualize_boxes_and_labels_on_image_array( vis_util.visualize_boxes_and_labels_on_image_array(
frame, frame,
np.squeeze(boxes), np.squeeze(boxes),
...@@ -129,29 +121,25 @@ for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port= ...@@ -129,29 +121,25 @@ for frame1 in camera.capture_continuous(rawCapture, format="bgr",use_video_port=
line_thickness=8, line_thickness=8,
min_score_thresh=0.40) min_score_thresh=0.40)
# All the results have been drawn on the frame, so it's time to display it.
# cv2.imshow('Object detector', frame)
cv2.putText(frame,"FPS: {0:.2f}".format(frame_rate_calc), (30,50),font,1,(255,255,0),2,cv2.LINE_AA) cv2.putText(frame,"FPS: {0:.2f}".format(frame_rate_calc), (30,50),font,1,(255,255,0),2,cv2.LINE_AA)
t2 = cv2.getTickCount() t2 = cv2.getTickCount()
time1 = (t2-t1)/freq time1 = (t2-t1)/freq
frame_rate_calc = 1/time1 frame_rate_calc = 1/time1
# save image locally and send to host running dashboard
cv2.imwrite("/home/pi/Documents/img.png", frame) cv2.imwrite("/home/pi/Documents/img.png", frame)
sendSock = socket.socket() sendSock = socket.socket()
sendSock.connect(("192.168.0.103", 3490)) sendSock.connect(("192.168.0.103", 3490))
with open("/home/pi/Documents/img.png", "rb") as img: with open("/home/pi/Documents/img.png", "rb") as img:
output = str(distance)+"&"+str(led_status)+"&"+"data=" output = str(distance)+"&"+str(led_status)+"&"+"data="
output = output.encode() output = output.encode()
output += img.read() output += img.read()
sendSock.send(output) sendSock.send(output)
sendSock.close() sendSock.close()
# Press 'q' to quit
if cv2.waitKey(1) == ord('q'):
break
rawCapture.truncate(0) rawCapture.truncate(0)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment