当前位置: 首页>>代码示例>>Python>>正文


Python Arduino.output方法代码示例

本文整理汇总了Python中arduino.Arduino.output方法的典型用法代码示例。如果您正苦于以下问题:Python Arduino.output方法的具体用法?Python Arduino.output怎么用?Python Arduino.output使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在arduino.Arduino的用法示例。


在下文中一共展示了Arduino.output方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: pollj

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
def pollj():
	ret = []
	pin = 1	
	try:
		b = Arduino('/dev/ttyACM0')
		b.output([])
	except:
		print 'couldnt create b'

	for i in range(10):
		val = None
		try:
			val = b.analogRead(pin)
		except:
			print 'couldnt analogread ' + str(i)
		ret.append(val)
		print val
		time.sleep(0.5)
	return " | ".join(ret)
开发者ID:sutt,项目名称:robojune,代码行数:21,代码来源:flaskread.py

示例2: __init__

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
class RGBLamp:
  def __init__(self,vDev):
    # Set arduino pins mode
    self.redPin = 5
    self.greenPin = 6
    self.bluePin = 9

    self.redVal = 0
    self.greenVal = 0
    self.blueVal = 0
   
    self.prevR = 0
    self.prevB = 0
    self.prevG = 0

    self.wait = 0.05
    self.hold = 0

    self.repeat = 0
    self.j = 0

    self.myArduino = Arduino(vDev)
    self.myArduino.output([self.redPin,self.greenPin,self.bluePin])
    
    print self.myArduino
  
	
  def calculateStep(self,prevValue, endValue):
    step = endValue - prevValue
    
    if (step != 0):
      step = 1020 / step			
    return step
	
  def calculateVal(self,step,val,i):
    if ((step != 0) and (i % step == 0)):
      if (step >= 0):
	val += 1
    elif (step < 0):
	val -= 1
		
    # PWM safe range: (0,255)
    if (val > 255):
      val = 255
		
    if (val < 0):
      val = 0

    return val
       
  def crossFade(self,(r,g,b)):		
    stepR = self.calculateStep(self.prevR, r)
    stepG = self.calculateStep(self.prevG, g)
    stepB = self.calculateStep(self.prevB, b)
		
    for i in range(1020):
      self.redVal = self.calculateVal(stepR, self.redVal, i)
      self.greenVal = self.calculateVal(stepG, self.greenVal, i)
      self.blueVal = self.calculateVal(stepB, self.blueVal, i)
	
      self.myArduino.analogWrite(self.redPin, self.redVal)
      self.myArduino.analogWrite(self.greenPin, self.greenVal)
      self.myArduino.analogWrite(self.bluePin, self.blueVal)
      
    
      time.sleep(self.wait)
    
    # update values for next iteration
    self.prevR = self.redVal
    self.prevG = self.greenVal
    self.prevB = self.blueVal

    time.sleep(self.hold)
开发者ID:n0w,项目名称:rgblamp,代码行数:75,代码来源:rgblamp.py

示例3: __init__

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
class Assay:
    # Initialize the pumps
    def __init__(self, fname, nrepeat=10, ard_port="/dev/ttyACM0", pump_port="/dev/ttyUSB0"):
        self.__observers = []  # define an observer
        self.step = -1  # before execution
        self.conf_label = "R" + "CUCI" * nrepeat
        print(self.conf_label)
        self.n_session = 1 + nrepeat * 4
        self.sessions = len(self.conf_label)  # the number of steps
        self.__construct__()
        self.time_flag = pd.Series(np.zeros(self.n_session), index=list(self.conf_label))
        ard_reset(ard_port)
        self.ard = Arduino(ard_port)
        self.ard.output([pin_LED, pin_Servo])
        self.ard.setLow(pin_LED)  # Initial
        self.fname = fname
        self.pump_init(pump_port)

    def blink_start(self, nblink=5):
        # give a blinking start, the LED blinks at 1 Hz
        for ii in range(nblink):
            self.ard.setHigh(pin_LED)
            time.sleep(0.50)
            self.ard.setLow(pin_LED)
            time.sleep(0.50)
            print(ii + 1)

        millis = int(round(time.time() * 1000))
        self.onset = millis

    def pump_init(self, pump_port):
        self.pser = serial.Serial(pump_port, 19200, timeout=0.1)
        print("connected to", self.pser.name)
        pumps = new_era.find_pumps(self.pser)
        self.pump = pumps[0]
        self.infuse = False
        new_era.set_diameter(self.pser, self.pump, dia_1ml)
        new_era.set_direct(self.pser, self.pump, 1)
        new_era.set_rate(self.pser, self.pump, flowrate)

    def register_observer(self, observer):
        self.__observers.append(observer)

    def notify_observers(self, *args, **kwargs):
        for observer in self.__observers:
            observer.notify(self, *args, **kwargs)

    def __construct__(self):
        # construct the configuration array
        self.CS_config = np.zeros([self.n_session, 4])
        ii = 0
        for ch in self.conf_label:
            if ch == "R":
                self.CS_config[ii] = CONFIG_REST
            elif ch == "C":
                self.CS_config[ii] = CONFIG_CS
            elif ch == "U":
                self.CS_config[ii] = CONFIG_US
            else:
                self.CS_config[ii] = CONFIG_INTER
            ii += 1
        # then, we need to update duration of intersessions
        inter_pos = self.CS_config[:, 0] < 0  # take out the positions of intersessions, a boolean array
        inter_dur = self.CS_config[inter_pos, 0]
        self.CS_config[inter_pos, 0] = np.random.randint(40, 70, size=len(inter_dur))

        print(self.CS_config)
        self.duration = self.CS_config[:, 0].sum() / 60.0
        print("Total experimental time: %4.1f min" % self.duration)

    def blink(self, duration, freq=2):
        # blink the LED
        # duration: the duration of blinking
        nblink = int(duration * freq)
        thp = 1 / (freq * 2.0)  # half-period

        for ii in range(nblink):
            self.ard.setHigh(pin_LED)
            time.sleep(thp)
            self.ard.setLow(pin_LED)
            time.sleep(thp)

    def run_step(self, sblink=False):
        millis = int(round(time.time() * 1000))
        self.step += 1
        self.time_flag[self.step] = millis
        self.notify_observers(self.step)
        config_list = self.CS_config[self.step]
        print(config_list[0])
        # take the row
        # turn on or off all the stimuli

        # turn on or off the delivery
        if config_list[2] == 0:
            if self.infuse == True:
                new_era.stop_pump(self.pser, self.pump)
                self.infuse = False
        elif config_list[2] == 1:
            if self.infuse == False:
                new_era.set_rate(self.pser, self.pump, flowrate)
#.........这里部分代码省略.........
开发者ID:danustc,项目名称:Behavior,代码行数:103,代码来源:LED_para.py

示例4: Arduino

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
from bottle import route, run, template, get, view
from Queue import Queue
import threading
from arduino import Arduino
import time


b = Arduino("/dev/tty.usbmodemfd121")
b.output([])
input_pin = 1
max_threshold = 0
min_threshold = 0

for y in range(100):
    x = int(b.analogRead(input_pin))
    print x
    max_threshold = max([max_threshold, x])
    min_threshold = min([min_threshold, x])

print "+++++++++++++++++++++++"
print max_threshold
print min_threshold
print "+++++++++++++++++++++++"


@route("/")
@view("main_template")
def index(name="Michel"):
    return dict()

开发者ID:varunrau,项目名称:PenguinGrader,代码行数:31,代码来源:penguingrader.py

示例5: Arduino

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
 #the blink program

#import the lib
from arduino import Arduino

import time

#specify the port as an argument
my_board = Arduino('/dev/ttyUSB0')

#declare output pins as a list/tuple
my_board.output([11,12,13])

#perform operations
i=0
while(i<10):
    my_board.setHigh(13)
    time.sleep(1)
    my_board.setLow(13)
    i+=1

开发者ID:zerohours,项目名称:ardu-mrua,代码行数:22,代码来源:test.py

示例6: str

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]


try:
    for p in serial.tools.list_ports.comports():
        if re.search('Arduino',str(p[1])):
            portString = str(p[0])
except:
    print "Could not open port!"
    sys.exit()

b = Arduino(portString)
pin = (1, 2, 3, 4, 5, 6, 7, 8)

#declare output pins as a list/tuple
b.output([pin])
b.turnOff()

try:
    while True:
        i=0
        while (i<8):
            b.setHigh(pin[i])
            time.sleep(.1)
            b.setLow(pin[i])
            time.sleep(.01)
            i+=1

except KeyboardInterrupt:
    while (i<8):
        b.setLow(pin[i])
开发者ID:cap10subtext,项目名称:PingCanal,代码行数:32,代码来源:sample_blink.py

示例7: Arduino

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
import sys, os, optparse, time, math
from arduino import Arduino

p = optparse.OptionParser()
#p.add_option(

A = Arduino('/dev/ttyACM0')
A.output([])

def poll_ardu(ardu,pin):    
    return ardu.analogRead(pin)

def sd(obs):
    """returns sd [float] from obs [list] """
    n = len(obs)
    mean = float(sum(obs)) /  float(n)
    sd = map(lambda x: (x - mean)**2, m)
    retlsurn float(math.sqrt( float(sum(sd)) / float(n) ))

def calibrate(ardu, **kwargs):
    """returns tolerance [int] from Ardu sample """
    cal_time = kwargs.get('cal_period',3)
    t_interval = kwargs.get('t_interval',.5)
    kwargs = kwargs.get('sigma',3)
    cal_steps = int( float(cal_time) / float(t_interval))
    
    m = []
    for i in range(cal_steps):
        d = poll_ardu(ardu,1)
        m.append(int(d))
        time.sleep(t_interval)
开发者ID:sutt,项目名称:robojune,代码行数:33,代码来源:sut1.py

示例8: main

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
def main():
    global board
    global firstWireCut
    board = Arduino("/dev/cu.usbmodem1411")
    log("experiment type: " + experimentType)
    startTime = time.time()
    # declare output pins as a list/tuple
    # these correspond to the 3 different LED colors for the eyes
    # board.output([14])
    # board.output([10])
    board.output([9, 10, 11])
    # board.on9()
    # board.on10()
    # board.on11()
    # board.output([10])
    # board.analogWrite(10,0)
    # board.output([10])
    # time.sleep(2)
    # board.output([10])
    # board.analogWrite(10, 10)

    # can set any of those as high/low using
    # board.setHigh(9)
    # board.setLow(9)
    # obviously switch number for pin it corresponds to

    # 2 through 6 correspond to the white wires
    # 15 to 19 are the black wires (on the breadboard)
    wirePins = [2, 3, 4, 5, 6, 15, 16, 17, 18, 19]
    # wirePins = [6]
    goodWires = 5  # number of good wires remaining
    badWires = 5  # number of good wires remaining

    # load robot speech recordings (none of these exist yet obviously)
    recordings = {
        "2": "2.wav",
        "3": "3.wav",
        "4": "4.wav",
        "5": "5.wav",
        "6": "6.wav",
        "15": "15.wav",
        "16": "16.wav",
        "17": "17.wav",
        "18": "18.wav",
        "19": "19.wav",
    }

    try:  # need this to close the log file
        while True:
            # ellapsedSeconds(startTime)
            # play the intro sounds
            # firstWireCut = False
            if not firstWireCut and ellapsedSeconds(startTime) % 20 == 0:
                playIntroSound()

            for pin in wirePins:
                state = board.getState(pin)  # this is either true/false
                # true = high (uncut wire), false = low (cut)
                if state == False:  # this wire was cut
                    firstWireCut = True  # mark that a wire has been cut

                    # remove from pins
                    wirePins.remove(pin)

                    # see if its a good wire or bad wire and
                    # call the appropriate function
                    if pin <= 6:
                        goodWires -= 1
                        onGoodWireCut(goodWires)
                    else:
                        badWires -= 1
                        onBadWireCut(badWires)
    except (KeyboardInterrupt, SystemExit):
        f.close()
开发者ID:jackm321,项目名称:hri_project,代码行数:76,代码来源:main.py

示例9: Arduino

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
from arduino import Arduino
import time

b = Arduino("/dev/tty.usbmodem1421")
pin = 13

# declare output pins as a list/tuple
b.output([pin, 13])
b.input([8])
b.servos([])

# for i in xrange(18):
#     # b.setHigh(pin)
#     # time.sleep(1)
#     # print b.getState(pin)
#     # b.setLow(pin)
#     # print b.getState(pin)
#     # time.sleep(1)
#     an = 3.14/180 * i * 10
#     an = i*10
#     print an
#     b.setAngle(12,an)

# time.sleep(1)
pos = 1
d = 1
s = 20
while 1:
    button = b.digitalRead(8)

    # if (button!=u'0\r'):
开发者ID:dmanfly,项目名称:geecon2015,代码行数:33,代码来源:click.py

示例10: main

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
def main():
    ard_reset()
    ard = Arduino('/dev/ttyACM0')
    ard.output([13])
    on_off(ard)
开发者ID:danr94,项目名称:Behavior,代码行数:7,代码来源:Arduino_chip.py

示例11: int

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
        p1 = (width - rec_thick / 2, height)
        p2 = (width - rec_thick / 2, height - int(right_sense * scale))
        cv2.rectangle(display_img, (width - rec_thick / 2, height),
                      (width - rec_thick / 2, height - int(right_sense * scale)),
                      rec_color, rec_thick)

        # Display the resulting frame
        # cv2.imshow('frame', frame)
        cv2.imshow('display_image', display_img)

        # if cv2.waitKey(1) & 0xFF == ord('q'):
        #     return True
        # else:
        #     return False


if __name__ == '__main__':
    try:
        arduino = Arduino('/dev/ttyACM0')
    except:
        arduino = Arduino('/dev/ttyACM1')
    arduino.output([2]) # This is a default to keep from hanging in setup


    print "Starting the arm thread"
    arm = armThread(1, "Arm thread", arduino)
    print "Starting the sensor thread"
    sensor = sensorThread(2, "Sensor thread", arduino)
    
    sensor.start()
    arm.start()
开发者ID:eschneider1992,项目名称:cardboard-robots-proto,代码行数:33,代码来源:arm_control_code.py

示例12: MainWindow

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]

#.........这里部分代码省略.........
        sizer_SwitchBar.Add(sizer_Switch_7_Slot, 1, wx.LEFT|wx.RIGHT|wx.EXPAND, 12)
        sizer_Switch_8_Slot.Add(self.choice_Switch_8, 0, wx.EXPAND, 0)
        sizer_Switch_8_Slot.Add(self.label_1_copy_6, 0, wx.ALIGN_CENTER_HORIZONTAL|wx.ALIGN_CENTER_VERTICAL, 0)
        sizer_SwitchBar.Add(sizer_Switch_8_Slot, 1, wx.LEFT|wx.RIGHT|wx.EXPAND, 12)
        sizer_Main.Add(sizer_SwitchBar, 1, wx.ALL|wx.EXPAND, 3)
        sizer_Main.Add(self.static_line_1, 0, wx.TOP|wx.BOTTOM|wx.EXPAND|wx.ALIGN_CENTER_HORIZONTAL, 5)
        sizer_Main.Add(self.text_ctrl_Status, 2, wx.LEFT|wx.RIGHT|wx.EXPAND, 20)
        sizer_ButtonBar.Add(self.button_ReadConfig, 0, wx.LEFT|wx.RIGHT, 10)
        sizer_ButtonBar.Add(self.button_ApplyConfig, 0, wx.LEFT|wx.RIGHT, 10)
        sizer_Main.Add(sizer_ButtonBar, 1, wx.LEFT|wx.RIGHT|wx.TOP|wx.ALIGN_CENTER_HORIZONTAL, 10)
        sizer_Main.Add((20, 10), 0, wx.EXPAND, 0)
        self.SetSizer(sizer_Main)
        sizer_Main.Fit(self)
        sizer_Main.SetSizeHints(self)
        self.Layout()
        # end wxGlade

    def windowPrintLn(self, text):
        """Print a string to the terminal within the main window and a newline character"""
        self.text_ctrl_Status.WriteText(text + "\n")
            
    def OnAbout(self, event): # wxGlade: MainWindow.<event_handler>
        #self.windowPrintLn('Event handler "OnAbout" not implemented!')
        event.Skip()

    def OnExit(self, event): # wxGlade: MainWindow.<event_handler>
        if self.arduino is not None:
            self.arduino.close()
        dlg = wx.MessageDialog(self, 
            "Do you really want to close this application?",
            "Confirm Exit", wx.OK|wx.CANCEL|wx.ICON_QUESTION)
        result = dlg.ShowModal()
        dlg.Destroy()
        if result == wx.ID_OK:
            self.Destroy()
    
    def OnContent(self, event): # wxGlade: MainWindow.<event_handler>
        #self.windowPrintLn("Event handler `OnContent' not implemented!")
        event.Skip()

    def OnReadConfig(self, event): # wxGlade: MainWindow.<event_handler>
        self.windowPrintLn('')
        if self.arduino is None:
            self.windowPrintLn("Must connect to the arduino first! (File->Change Serial Port)")
            return
        for pin, value in zip(self.arduinoPinMap, self.switchList):
            if self.arduino.getState(pin) is False:
                self.windowPrintLn("Pin " + str(pin) + " is LOW")
                value.SetSelection(0)
            else:
                self.windowPrintLn("Pin " + str(pin) + " is HIGH")
                value.SetSelection(1)
            
    
    def OnApplyConfig(self, event): # wxGlade: MainWindow.<event_handler>
        self.windowPrintLn('')
        if self.arduino is None:
            self.windowPrintLn("Must connect to the arduino first! (File->Change Serial Port)")
            return
        for pin, value in zip(self.arduinoPinMap, self.switchList):
            if value.GetSelection() is 0:
                self.windowPrintLn(''.join(['Set pin ', str(pin), ' to LOW']))
                self.arduino.setLow(pin)
            else:
                self.windowPrintLn(''.join(['Set pin ', str(pin), ' to HIGH']))
                self.arduino.setHigh(pin)

    def OnChangeSerialPort(self, event): # wxGlade: MainWindow.<event_handler>
        self.windowPrintLn('')
        self.windowPrintLn("Searching for available serial ports...")
        #scan for available ports. return a list of tuples (num, name)
        available = []
        for i in range(256):
            try:
                s = serial.Serial(i)
                available.append( (i, s.portstr))
                s.close()   # explicit close because of delayed GC in java
            except serial.SerialException:
                pass
        self.windowPrintLn("Found the following avilable ports:")
        for nu, na in available: self.windowPrintLn(na)
        dlg = wx.SingleChoiceDialog(self, "Select the correct serial port", 'Serial Port Selection',
                [na for nu, na in available], wx.CHOICEDLG_STYLE)
        if dlg.ShowModal() == wx.ID_OK:
            self.serialPort = dlg.GetStringSelection()
            self.windowPrintLn('Selected ' + self.serialPort)
        self.windowPrintLn("Attempting to connect to arduino over " + self.serialPort + ".....")

        try:
            self.arduino = Arduino(self.serialPort)
            self.arduino.output(self.arduinoPinMap)
            self.arduino.turnOff()
            self.windowPrintLn(str(self.arduino))
        except serial.serialutil.SerialException:
            self.windowPrintLn("Failed to connect to port " + self.serialPort + "!")
            self.arduino = None
        except TimeoutException:
            self.windowPrintLn("5 second timeout: Failed to communicate with arduino over " + self.serialPort)
            self.windowPrintLn("Reset arduino and try again, or try different port.")
            self.arduino = None
开发者ID:webbhorn,项目名称:Arduino-Switch-Controller,代码行数:104,代码来源:MainWindow.py

示例13: Arduino

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
from arduino import Arduino
import time

try:
    b = Arduino('/dev/tty.usbmodem1421')
    print "Connected to usbmodem1421"
except:
    try:
    	b = Arduino('/dev/ttyACM0')
	print "Connected to ttyACM0"
    except:
        b = Arduino('/dev/ttyUSB0')
	print "Connected to ttyUSB0"

led_pin = 13
b.output([led_pin])
b.input([])
b.servos([])   
print "Pin setup done"

for i in xrange(18):
    b.setHigh(led_pin)
    time.sleep(1)
    print b.getState(led_pin)
    b.setLow(led_pin)
    print b.getState(led_pin)
    time.sleep(1)



#servo1 = 13
开发者ID:dmanfly,项目名称:geecon2015,代码行数:33,代码来源:sample_blink.py

示例14: Arduino

# 需要导入模块: from arduino import Arduino [as 别名]
# 或者: from arduino.Arduino import output [as 别名]
import unittest
from arduino import Arduino

b = Arduino('COM4')
pin_out = 5
pin_in  = 9

#declare output pins as a list/tuple
b.output([pin_out])

class MyTestCase(unittest.TestCase):
    def test_something(self):
        b.setHigh(pin_out)
        self.assertEqual(b.getState(pin_in), True)

        b.setLow(pin_out)
        self.assertEqual(b.getState(pin_in), False)


if __name__ == '__main__':
    unittest.main()
开发者ID:basejumpa,项目名称:DIYPlayground,代码行数:23,代码来源:someTesting.py


注:本文中的arduino.Arduino.output方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。