Example #1
0
def serialConfig(configFileName, dataPortName, userPortName):
    try:
        cliPort = serial.serial(userPortName, 115200)
        dataPort = serial.serial(dataPortName, 921600)
    except serial.SerialException as se:
        print("Serial Port 0ccupied,error = ")
        print(str(se))
        return

    config = [line.rstrip('\r\n') for line in open(configFileName)]
    for i in config:
        cliPort.write((i + '\n').encode())
        print(i)

    return cliPort, dataPort
Example #2
0
    def __init__(self, host, port):

        # シリアル通信の設定(
        ser = serial.serial("/dev/ttyacm0", 9600, timeout=1)

        serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        serversock.bind((host,port)) #IPとPORTを指定してバインドします
        serversock.listen(10) #接続の待ち受けをします(キューの最大数を指定)

        clientsock, client_address = serversock.accept() #接続されればデータを格納
def print_time(threadName, _, port_to_use):

    port=serial.serial(port_to_use,115200, timeout=3)
    data_packet=[]
    mark=True
    while mark:
        line =port.readline()
        #print(line)
        x=line.decode("utf-8")
        print(threadName)
        print(x)
    #print("#############")
    #print(port_to_use)
    #print(x)
    #print("#############")
    port.close()
def main():
    #declare port, baud, and file path
    serial_port = '/dexy/ttyACME'
    baud_rate = 9600
    write_to_file_path = "waterquality.csv"

    #open file for writing and get serial feed
    output_file = open(write_to_file_path, 'w+')
    ser = serial.serial(serial_port, baud_rate)

    #write serial output to a csv file
    output_file.write('distance\n')
    n = 0
    while n < 20:  #amount of iterations and typing onto csv
        line = ser.readline()
        line = line.decode('utf-8')
        output_file.write(line)
        n += 1

    output_file.close()
        output = model.forward()
        for detection in output[0, 0, :, :]:
            confidence = detection[2]
            if confidence > .5:
                class_id = detection[1]
                if class_id == 1: #if human is detected?!
                    averageArray[index] += 1
    return round(sum(averageArray)/len(averageArray))


""" ****************************************************************************************************************** """

#Gps functions:
#Initiate UART:
port = "/dev/ttyAMA0"
ser=serial.serial(port, baudrate=9600, timeout=0.5)
def getLocation():
    lat = 0
    lng = 0
    dataout = pynmea2.NMEAStreamReader()
    newdata= ser.readline()
    if newdata[0:6] == "$GPRMC":
        newmsg = pynmea2.parse(newdata)
        lat = newmsg.latitude
        lng = newmsg.longitude
        gps = "Latitude="+ str(lat)+ "and Longitude="+ str(lng)
        print(gps)
        createTxtFile(lat, lng)

def createTxtFile(lat, lng):
    txtIndex +=1 
Example #6
0
import serial
serialA = serial.serial('/dev/ttyACM0', 115200)
serialA.open()

serialA.write("hola desde raspi")
try:
    while 1:
        response = serilA.readLine()
        print(response)

except KeyboardInterrupt:
    serialA.close()
Example #7
0
import serial
import xlrd as x

wb = x.open_workbook('ttax.xlsx')
s = serial.serial('/dev/ttyUSB0')
s.close()
d = wb.sheet_by_index(0)
c = d.col_values(1)
while (1):
    s.open
    print('port open')
    d = s.read(12)
    print(d)
    s.close()
    for i in range(0, len[c]):
        if (d == c[i]):
            print('access allowed')
        else:
            print('access denied')
Example #8
0
    def callbefore(self, pid, call, args):
        flags = self.allflags[pid]

        # FIX: backward compat for pre-2.4 kernels, remove later
        if flags.has_key('skipstop'):
            del flags['skipstop']

        if call == 'rt_sigaction' or call == 'sigaction' or call == 'signal':
            sig = args[0]
            if ((sig == signal.SIGTSTP or sig == signal.SIGTTIN
                 or sig == signal.SIGTTOU
                 or (sig == signal.SIGCHLD and call != 'signal'))
                and (call == 'signal' or args[1] != 0)):
                return (args, None, None, None)
        elif call == 'wait4' or call == 'waitpid':
            # waitpid is just wait4 with no args[3]
            if call == 'waitpid':
                args = args + (0, )
            # XXX: if this rewrites args and call is 'waitpid', the new arg
            # list will be longer.  this will be slower, but harmless (?)
            return self._callbefore_wait(pid, args, flags)

        elif call == 'fork' or call == 'clone' or call == 'vfork':
            assert not flags.has_key('newchild')

            # If a process does several forks before any of the new children
            # report, it has to be able to tell the children apart when they
            # start reporting.  This kludge saves a unique tag in the regs for
            # the 6th arg, which seems to survive across the clone call.
            # (Note that we can't poke this info into memory, because memory
            # might be shared with the parent.)
            #
            # The original parent pid is also saved in the 5th arg, as this
            # info is hard to get at elsewhere.
            tag = serial()

            ppid = pid
            if call == 'clone':
                assert len(args) == 2
                assert not args[0] & clone.CLONE_PTRACE, "oops: CLONE_PTRACE not yet implemented"
                assert not args[0] & clone.CLONE_THREAD, "oops: CLONE_THREAD not yet implemented"
                if args[0] & clone.CLONE_PARENT:
                    ppid = flags['parent']
                newcall = None
                newargs = (args[0] | clone.CLONE_PTRACE, args[1], 0, 0, ppid, tag)
            else:
                # rewrite to an equivalent clone, but with PTRACE
                # (2nd arg = 0 means use same stack pointer)
                f = signal.SIGCHLD | clone.CLONE_PTRACE
                if call == 'vfork':
                    f = f | clone.CLONE_VFORK | clone.CLONE_VM
                newcall = 'clone'
                newargs = (f, 0, 0, 0, ppid, tag)
            flags['newchild'] = (ppid, tag)
            return ((ppid, tag), None, newcall, newargs)

        elif call == 'execve':
            flags['exectrappending'] = 1
        elif call == 'setpgid':
            # XXX: this is to track the pgid, but maybe we should just read /proc?
            return (args, None, None, None)
Example #9
0
# -*- coding: utf-8 -*-
import serial
import socket
import sys
import threading
import binascii

# シリアル通信の設定(
ser = serial.serial("/dev/ttyacm0", 9600, timeout=1)


def react_formula(ir_value):
    sma_val = ir_value * 1 / 3
    if ir_value > 30:
        sma_val = 30
    else:
        sma_val = 0
    return sma_val


if __name__ == '__main__':
    host = "192.168.146.128"  #お使いのサーバーのホスト名を入れます
    port = 50000  #クライアントと同じPORTをしてあげます

    serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    serversock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    serversock.bind((host, port))  #IPとPORTを指定してバインドします
    serversock.listen(10)  #接続の待ち受けをします(キューの最大数を指定)

    print 'Waiting for connections...'
    clientsock, client_address = serversock.accept()  #接続されればデータを格納
Example #10
0
import sys
import termios

import serial

fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

ser = serial.serial(port='/dev/rfcomm', boudrate=9600)
print(ser.name)

robot_keys = {
    'stop': '#b=0#',
    'forward': '#b=1#',
    'backward': '#b=2#',
    'left': '#b=3#',
    'right': '#b=4#',
    'break0': '#b=9#',
    'break1': '#b=19#',
    'break2': '#b=29#',
    'break3': '#b=39#',
    'break4': '#b=49#',
    'melody': '+DISC',
}
Example #11
0
        motorBaudRate = 9600
        keypadSerial = "64936333037351E0E1E1"
        motorSerial = "64932343938351119122"

        keypadLocation = getHardwareLocation(keypadSerial)
        motorLocation = getHardwareLocation(motorSerial)

    if motorLocation != "notConnected":
        motorPath = "/dev/" + motorLocation
        motors = serial.Serial(motorPath, motorBaudRate)
    else:
        print("Motor not connected")

    if keypadLocation != "notConnected":
        keypadPath = "/dev/" + keypadLocation
        keypad = serial.serial(keypadPath,keypadBaudRate)
    else:
        print("Keypad not connected")
    
def getHardwareLocation(serialNumber):
        cmd = "dmesg | grep " + serialNumber + " -A 1 | tail -n 1 | grep -o 'ttyACM[[:digit:]]'"
        cmdOutput = commands.getstatusoutput(cmd)[1]
        if cmdOutput == "/" or cmdOutput == " ":
            return "notConnected"
        else:
            devLocation = cmdOutput
            connectionCheck = "cat /dev/" + devLocation
            connectionCheckOutput = commands.getstatusoutput(connectionCheck)[1]
            #print(connectionCheckOutput)
            if connectionCheckOutput == "/" or connectionCheckOutput == " " or connectionCheckOutput.strip() == "N":
                return devLocation
Example #12
0
 def __init__( port_name, baud ):
     self.port_name = port_name
     self.baud = baud
     self.ser = serial.serial(port_name, baud, timeout=0.1)
Example #13
0
import serial as ser
import struct, time

a = 'z'
c = a.encode('utf-8')
b = 678
se = ser.serial('dev/ttyTHS1', 115200, timeout=0.5)


def recv(serial):
    while True:
        data = serial.read(64)
        if data == ' ':
            continue
        else:
            break
    return data


while True:
    data = recv(se)
    if data != ' ':
        print(data)
    se.write(str(b).encode('utf-8'))
    se.write(a.encode('utf-8'))
    time.sleep(1)
Example #14
0
import serial 
ser=serial.serial("/dev/tty/COM10",9600)
i=0
while(i<200):
    i=i+1
    ser.write(int('1'))


    
## Serial . parseint() in arudinoto read values
Example #15
0
import os
import RPi.GPIO as GPIO
import time
import serial
import wiringpi

ser = serial.serial(
	port='/dev/serial0',
	baudrate = 9600,
	parity=serial.parity_none,
	stopbits=serial.stopbits_one,
	bytesize=serial.eightbits,
	timeout=1
)

#wiringpi.wiringPiSetup()
#serial = wiringpi.serialOpen('/dev/ttyAMA0',9600)
#wiringpi.serialPuts(serial,0x02)
#GPIO.setup(6, GPIO.OUT)
try:
	while True:
		GPIO.setmode(GPIO.BCM)
		GPIO.setup(13, GPIO.OUT)
		GPIO.setup(19, GPIO.OUT)
		GPIO.setup(26, GPIO.OUT)

		GPIO.setmode(GPIO.BCM)
		print(" ")
		print("1. Show Camera")
		print("2. Fire Turret")
		print("3. Rotate Left")
#!/usr/bin/env python

import sys
import time
import serial

ser = serial.serial(port='/dev/ttyAMA0',
                    baudrate=9600,
                    parity=serial.PARITY_NONE,
                    stopbits=serial.STOPBITS_ONE,
                    bytesize=serial.EIGHTBITS,
                    timeout=1)
counter = 0

while 1:
    x = ser.readline()
    print(x)
Example #17
0
import serial
import time

ser=serial.serial(port=ttyUSB0, baudrate=9600,parity=serial.PARITY_ONE,
stopbits=serial.STOPBITS_ONE,bytesize=serial.EIGHTBITS,
timeout=0)

while (1):
	energy=ser.readline()
	print(" current energy value in kwhr: ",energy)
Example #18
0
from flask import Flask
from serial import Serial as serial
from serial.tools import list_ports as ports

# awesome magic hack (filter arduino outta all available ports)
arduino_port = ports.grep("VID:PID=2341:0043").next()

# initialize communication with arduino
arduino = serial(arduino_port.device)

# initialize http server
app = Flask(__name__)


@app.route("/arduino/send/<message>")
def hello(message):
    # send message
    arduino.write(message.encode("ascii"))
    return "successful"


if __name__ == "__main__":
    app.run()
Example #19
0
import hostname
import qtd_ports
import serial
import show_version
import restart
import model
import json
#dados = open("Dados.txt", 'w')
hostes = ""
por = 'Model number                    : WS-C3560-24PS-E'  #sh version | inc Model num
seri = "System serial number            : "
versio = "uptime is 74 years, 40 weeks, 1 day, 19 hours, 59 minutes"
reset = "System restarted at 04:16:12 gmt Sat Feb 29 2020"
hostnameResult = hostname.host_name(hostes)
resetResult = restart.restarte(reset)
portasResult = qtd_ports.qtd_ports(por)
serialResult = serial.serial(seri)
versionResult = show_version.show_version(versio)
modelResult = model.mod(por)
up = {}
up.update(hostnameResult)
up.update(versionResult)
up.update(resetResult)
up.update(serialResult)
up.update(portasResult)
info = json.dumps(up, ensure_ascii=False)  #indent=4
#dados.write(info)
#dados.close()
print(info)
Example #20
0
# 5.20 Communicating with Serial Ports

# Use pySerial package

import serial
ser = serial.serial('/dev/tty')
Example #21
0
def serialopen(comnum='com5',baudrate=115200):
    ser=serial.serial(comnum,baudrate,timeout=0.5)
    print(comnum)
    print('已打开')
Example #22
0
# import the necessary packages
from collections import deque
import numpy as np
import argparse
import imutils
import cv2
import serial

teensy = serial.serial("COM6", 9600)

# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video", help="path to the (optional) video file")
ap.add_argument("-b", "--buffer", type=int, default=64, help="max buffer size")
args = vars(ap.parse_args())

# define the lower and upper boundaries of the "yellow object"
# (or "ball") in the HSV color space, then initialize the
# list of tracked points
colorLower = (99, 115, 150)
colorUpper = (110, 255, 255)
pts = deque(maxlen=args["buffer"])

# if a video path was not supplied, grab the reference
# to the webcam
if not args.get("video", False):
    camera = cv2.VideoCapture(0)

# otherwise, grab a reference to the video file
else:
    camera = cv2.VideoCapture(args["video"])
Example #23
0
import serial
ser serial.serial('com3',baudrate = 9600, timeout=1)
while 1:
	arduinoData = ser.readline();
	print(arduinoData);
	
f = open("demofile.txt", "w")
f.write("Woops! I have deleted the content!")
Example #24
0
#from serial import serial
import time
import serial
memfile = "payload.jpeg"
open(memfile, 'w').close()  #update physical memory
st = serial.serial('COM15', 115200)
#st = serial.Serial('/dev/ttyACM0',115200, timeout=None,parity=serial.PARITY_NONE, rtscts=0)

# payload=chr(0b01100001)+chr(len(message))+message
################################################################
timep = 10
payload = chr(0b01100010) + chr(0) * 8 + chr(timep) + "000fire0"
size = len(payload)
print(size)

out = chr(size) + payload
print(out)
st.write(out.encode())
# time.sleep(3)

size = st.read(1)
size = ord(size)
if (size == 0): size = 256
print(size)
cmd = st.read(size)
print(cmd)
time.sleep(3)

################################################################
payload = chr(0b01100010) + chr(1) + "000fire0"
size = len(payload)
                        default=115200,
                        help="Baudrate of serial port")
    parser.add_argument("--db-file",
                        default="bank.json",
                        help="Name of bank database file")
    parser.add_argument("--admin-db-file",
                        default="admin-bank.json",
                        help="Name of bank admin database file")
    args = parser.parse_args()
    return args.port, args.baudrate, args.db_file, args.admin_db_file


if __name__ == "__main__":
    port, baudrate, db_file, admin_db_file = parse_args()

    atm = serial.serial(port, baudrate, timeout=5)

    try:
        while True:
            print("Listening for provisioning info...")
            while atm.read() != "p":
                continue

            print("Reading provisioning info...")
            pkt = atm.read(1088)
            # card_num, inner_layer_public_key, inner_layer_private_key, outer_layer_public_key, outer_layer_private_key, balance = struct.unpack(">36I256I256I256I256I32I", pkt)

            struct.unpack()

            card_num = int.from_bytes(ciphers.generate_salt(32))
Example #26
0
    else:
        return 0


if __name__ == '__main__':
    myip = '192.168.2.10'   #改
    myport1 = 8080   #改
    bufsize = 65535   #改
    udpClient1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)   #改
    udpClient1.bind((myip,myport1))   #改
    port=read_ports()   #改
    if port:
        ser=serial.Serial(port[0],9600)
        time.sleep(3)
        time.sleep(1.0)
    #server.handle_request()        改
    while True:   #改
        if not ser.isOpen():
            ser.close()
            port = read_ports()
            ser = serial.serial(port[0],9600)
            time.sleep(1)
        msg, addr1 = udpClient1.recvfrom(bufsize)   #改
        message = msg.decode('utf-8')   #改
        if message :
           mes = sendMessage(ser,message)
           print(message)
           print(mes)
           time.sleep(0.1)
        else:
            print("connect error")
Example #27
0
import serial
ser=serial.serial('/dev/ttyACM0', 9600)
#/dev/ttyAMC0 is an example of the port.
while 1:
	n=input('Input instruction: ')
	ser.write(n)
	print n
Example #28
0
    # Create a new receive buffer
    receive_buffer = ""

    while not wait_string in receive_buffer:
        # Flush the receive buffer
        receive_buffer += shell.recv(1024)

    # Print the receive buffer, if necessary
    if should_print:
        print receive_buffer

    return receive_buffer


client = serial.serial(
    4
)  #,9600,'EIGHTBITS','PARITY_NONE','STOPBITS_ONE',None,False,None,False,None)
client.open()
#client.load_system_host_keys()
##client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
##ip = raw_input("Enter the ip for the switch : ")
##user = raw_input("Enter your remote account: ")
##password = getpass.getpass()
##
##client.connect(ip, 22, username = user, password = password,allow_agent = False)
##shell = client.invoke_shell()
##send_and_get_string("", ">", True)
##send_and_get_string("enable", ":", True)
##send_and_get_string("switch", "#", True)
##send_and_get_string("configure terminal","#",True)
##for cmd in basic_security_cmds:
Example #29
0
def tryExcepError():
    try:
        ser = serial.serial('COM5', 9600)
        print(ser.readline().decode("utf-8").strip('\n').strip('\r'))
    except TypeError:
        print("Terjadi ketidaksamaan type")
# Install pyserial from http://sourceforge.net/projects/pyserial/files/
# Install Vphyton from http://vpython.org/contents/download_windows.html

from visual import *
import serial
import string
import math
import sys
import datetime

# LeafLabs Maple serial port
serialport = '/dev/ttyacm0'

# Check your COM port and baud rate
try:
    ser = serial.serial(serialport)
except serial.SerialException:
    print "Serial port not found"
    sys.exit(0)

# Main scene
scene=display(title="9DOF Razor IMU test")
scene.range=(1.2,1.2,1.2)
#scene.forward = (0,-1,-0.25)
scene.forward = (1,0,-0.25)
scene.up=(0,0,1)

# Second scene (Roll, Pitch, Yaw)
scene2 = display(title='9DOF Razor IMU test',x=0, y=0, width=500, height=200,center=(0,0,0), background=(0,0,0))
scene2.range=(1,1,1)
scene.width=500