diff --git a/.gitignore b/.gitignore index be0b393..f93018d 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,3 @@ -# IDE # -####### -*.wpr -*.wpu # Directories # ############### diff --git a/Arduino/__init__.py b/Arduino/__init__.py index 34ac945..ffc5252 100644 --- a/Arduino/__init__.py +++ b/Arduino/__init__.py @@ -1 +1,2 @@ +name="arduino-python3" from .arduino import Arduino, Shrimp diff --git a/Arduino/arduino.py b/Arduino/arduino.py old mode 100644 new mode 100755 index ac5e74d..e76a5b5 --- a/Arduino/arduino.py +++ b/Arduino/arduino.py @@ -5,11 +5,14 @@ import serial import time from serial.tools import list_ports -if platform.system() == 'Windows': - import _winreg as winreg + +import sys +if sys.platform.startswith('win'): + import winreg else: import glob +libraryVersion = 'V0.6' log = logging.getLogger(__name__) @@ -22,7 +25,7 @@ def enumerate_serial_ports(): path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM' try: key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path) - except WindowsError: + except OSError: raise Exception for i in itertools.count(): @@ -60,41 +63,60 @@ def find_port(baud, timeout): ports = enumerate_serial_ports() elif platform.system() == 'Darwin': ports = [i[0] for i in list_ports.comports()] + ports = ports[::-1] else: ports = glob.glob("/dev/ttyUSB*") + glob.glob("/dev/ttyACM*") for p in ports: log.debug('Found {0}, testing...'.format(p)) try: sr = serial.Serial(p, baud, timeout=timeout) - except serial.serialutil.SerialException as e: + except (serial.serialutil.SerialException, OSError) as e: log.debug(str(e)) continue - time.sleep(2) + + sr.readline() # wait for board to start up again + version = get_version(sr) - if version != 'version': + + if version != libraryVersion: + try: + ver = version[0] + except Exception: + ver = '' + + if ver == 'V' or version == "version": + print("You need to update the version of the Arduino-Python3", + "library running on your Arduino.") + print("The Arduino sketch is", version) + print("The Python installation is", libraryVersion) + print("Flash the prototype sketch again.") + return sr + + # established to be the wrong board log.debug('Bad version {0}. This is not a Shrimp/Arduino!'.format( version)) sr.close() continue + log.info('Using port {0}.'.format(p)) if sr: return sr return None - def get_version(sr): cmd_str = build_cmd_str("version") try: - sr.write(cmd_str) + sr.write(str.encode(cmd_str)) sr.flush() except Exception: return None - return sr.readline().replace("\r\n", "") + return sr.readline().decode("utf-8").replace("\r\n", "") class Arduino(object): - def __init__(self, baud=9600, port=None, timeout=2, sr=None): + + def __init__(self, baud=115200, port=None, timeout=2, sr=None): """ Initializes serial communication with Arduino if no connection is given. Attempts to self-select COM port, if not specified. @@ -106,10 +128,29 @@ def __init__(self, baud=9600, port=None, timeout=2, sr=None): raise ValueError("Could not find port.") else: sr = serial.Serial(port, baud, timeout=timeout) + sr.readline() # wait til board has rebooted and is connected + + version = get_version(sr) + + if version != libraryVersion: + # check version + try: + ver = version[0] + except Exception: + ver = '' + + if ver == 'V' or version == "version": + print("You need to update the version of the Arduino-Python3", + "library running on your Arduino.") + print("The Arduino sketch is", version) + print("The Python installation is", libraryVersion) + print("Flash the prototype sketch again.") + sr.flush() self.sr = sr self.SoftwareSerial = SoftwareSerial(self) self.Servos = Servos(self) + self.EEPROM = EEPROM(self) def version(self): return get_version(self.sr) @@ -123,13 +164,13 @@ def digitalWrite(self, pin, val): pin : digital pin number val : either "HIGH" or "LOW" """ - if val == "LOW": + if val.upper() == "LOW": pin_ = -pin else: pin_ = pin cmd_str = build_cmd_str("dw", (pin_,)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass @@ -149,7 +190,7 @@ def analogWrite(self, pin, val): val = 0 cmd_str = build_cmd_str("aw", (pin, val)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass @@ -165,11 +206,11 @@ def analogRead(self, pin): """ cmd_str = build_cmd_str("ar", (pin,)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass - rd = self.sr.readline().replace("\r\n", "") + rd = self.sr.readline().decode("utf-8").replace("\r\n", "") try: return int(rd) except: @@ -188,7 +229,7 @@ def pinMode(self, pin, val): pin_ = pin cmd_str = build_cmd_str("pm", (pin_,)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass @@ -202,17 +243,17 @@ def pulseIn(self, pin, val): returns: duration : pulse length measurement """ - if val == "LOW": + if val.upper() == "LOW": pin_ = -pin else: pin_ = pin cmd_str = build_cmd_str("pi", (pin_,)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass - rd = self.sr.readline().replace("\r\n", "") + rd = self.sr.readline().decode("utf-8").replace("\r\n", "") try: return float(rd) except: @@ -247,7 +288,7 @@ def pulseIn_set(self, pin, val, numTrials=5): pinMode(pin, INPUT); long duration = pulseIn(pin, HIGH); """ - if val == "LOW": + if val.upper() == "LOW": pin_ = -pin else: pin_ = pin @@ -255,11 +296,11 @@ def pulseIn_set(self, pin, val, numTrials=5): durations = [] for s in range(numTrials): try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass - rd = self.sr.readline().replace("\r\n", "") + rd = self.sr.readline().decode("utf-8").replace("\r\n", "") if rd.isdigit(): if (int(rd) > 1): durations.append(int(rd)) @@ -289,11 +330,11 @@ def digitalRead(self, pin): """ cmd_str = build_cmd_str("dr", (pin,)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass - rd = self.sr.readline().replace("\r\n", "") + rd = self.sr.readline().decode("utf-8").replace("\r\n", "") try: return int(rd) except: @@ -309,7 +350,7 @@ def Melody(self, pin, melody, durations): length of melody should be of same length as length of duration - Melodies of the following lenght, can cause trouble + Melodies of the following length, can cause trouble when playing it multiple times. board.Melody(9,["C4","G3","G3","A3","G3",0,"B3","C4"], [4,8,8,4,4,4,4,4]) @@ -334,18 +375,18 @@ def Melody(self, pin, melody, durations): cmd_args = [length, pin] if length == len(durations): cmd_args.extend([NOTES.get(melody[note]) - for note in range(length)]) + for note in range(length)]) cmd_args.extend([durations[duration] - for duration in range(len(durations))]) + for duration in range(len(durations))]) cmd_str = build_cmd_str("to", cmd_args) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass cmd_str = build_cmd_str("nto", [pin]) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass @@ -368,8 +409,8 @@ def capacitivePin(self, pin): the Arduino/Shrimp and any hardware attached to the pin. ''' cmd_str = build_cmd_str("cap", (pin,)) - self.sr.write(cmd_str) - rd = self.sr.readline().replace("\r\n", "") + self.sr.write(str.encode(cmd_str)) + rd = self.sr.readline().decode("utf-8").replace("\r\n", "") if rd.isdigit(): return int(rd) @@ -385,7 +426,7 @@ def shiftOut(self, dataPin, clockPin, pinOrder, value): """ cmd_str = build_cmd_str("so", (dataPin, clockPin, pinOrder, value)) - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() def shiftIn(self, dataPin, clockPin, pinOrder): @@ -400,9 +441,9 @@ def shiftIn(self, dataPin, clockPin, pinOrder): (int) an integer from 0 to 255 """ cmd_str = build_cmd_str("si", (dataPin, clockPin, pinOrder)) - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() - rd = self.sr.readline().replace("\r\n", "") + rd = self.sr.readline().decode("utf-8").replace("\r\n", "") if rd.isdigit(): return int(rd) @@ -440,10 +481,10 @@ def attach(self, pin, min=544, max=2400): cmd_str = build_cmd_str("sva", (pin, min, max)) while True: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() - rd = self.sr.readline().replace("\r\n", "") + rd = self.sr.readline().decode("utf-8").replace("\r\n", "") if rd: break else: @@ -456,7 +497,7 @@ def detach(self, pin): position = self.servo_pos[pin] cmd_str = build_cmd_str("svd", (position,)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass @@ -466,14 +507,14 @@ def write(self, pin, angle): position = self.servo_pos[pin] cmd_str = build_cmd_str("svw", (position, angle)) - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() def writeMicroseconds(self, pin, uS): position = self.servo_pos[pin] cmd_str = build_cmd_str("svwm", (position, uS)) - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() def read(self, pin): @@ -482,11 +523,11 @@ def read(self, pin): position = self.servo_pos[pin] cmd_str = build_cmd_str("svr", (position,)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass - rd = self.sr.readline().replace("\r\n", "") + rd = self.sr.readline().decode("utf-8").replace("\r\n", "") try: angle = int(rd) return angle @@ -494,6 +535,7 @@ def read(self, pin): return None + class SoftwareSerial(object): """ @@ -512,11 +554,11 @@ def begin(self, p1, p2, baud): """ cmd_str = build_cmd_str("ss", (p1, p2, baud)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass - response = self.sr.readline().replace("\r\n", "") + response = self.sr.readline().decode("utf-8").replace("\r\n", "") if response == "ss OK": self.connected = True return True @@ -532,11 +574,11 @@ def write(self, data): if self.connected: cmd_str = build_cmd_str("sw", (data,)) try: - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() except: pass - response = self.sr.readline().replace("\r\n", "") + response = self.sr.readline().decode("utf-8").replace("\r\n", "") if response == "ss OK": return True else: @@ -549,10 +591,67 @@ def read(self): """ if self.connected: cmd_str = build_cmd_str("sr") - self.sr.write(cmd_str) + self.sr.write(str.encode(cmd_str)) self.sr.flush() - response = self.sr.readline().replace("\r\n", "") + response = self.sr.readline().decode("utf-8").replace("\r\n", "") if response: return response else: return False + + +class EEPROM(object): + """ + Class for reading and writing to EEPROM. + """ + + def __init__(self, board): + self.board = board + self.sr = board.sr + + def size(self): + """ + Returns size of EEPROM memory. + """ + cmd_str = build_cmd_str("sz") + + try: + self.sr.write(str.encode(cmd_str)) + self.sr.flush() + response = self.sr.readline().decode("utf-8").replace("\r\n", "") + return int(response) + except: + return 0 + + def write(self, address, value=0): + """ Write a byte to the EEPROM. + + :address: the location to write to, starting from 0 (int) + :value: the value to write, from 0 to 255 (byte) + """ + + if value > 255: + value = 255 + elif value < 0: + value = 0 + cmd_str = build_cmd_str("eewr", (address, value)) + try: + self.sr.write(str.encode(cmd_str)) + self.sr.flush() + except: + pass + + def read(self, adrress): + """ Reads a byte from the EEPROM. + + :address: the location to write to, starting from 0 (int) + """ + cmd_str = build_cmd_str("eer", (adrress,)) + try: + self.sr.write(str.encode(cmd_str)) + self.sr.flush() + response = self.sr.readline().decode("utf-8").replace("\r\n", "") + if response: + return int(response) + except: + return 0 diff --git a/README.md b/README.md index be6fad6..903cc6f 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,17 @@ -# Python Arduino Command API +# Arduino-Python3 Command API -The Python Arduino Command API is a light-weight Python library for +This API is forked from the original [Python Arduino Command API](https://github.com/thearn/Python-Arduino-Command-API) to add support for Python 3. + +The Arduino-Python3 Command API is a lightweight Python library for communicating with [Arduino microcontroller boards](http://www.arduino.cc/) from a connected computer using -standard serial IO, either over a physical wire +standard serial IO, either over a physical wire or wirelessly. It is written using a custom protocol, similar to [Firmata](http://firmata.org/wiki/Main_Page). -This allows a user to quickly protoype programs for Arduino using Python code, or to +This allows a user to quickly prototype programs for Arduino using Python code, or to simply read/control/troubleshoot/experiment -with harware connected to an Arduino board without ever having to recompile and reload sketches to the board itself. +with hardware connected to an Arduino board without ever having to recompile and reload sketches to the board itself. -Method names within the Python Arduino Command API are designed to be as close +Method names within the Arduino-Python3 Command API are designed to be as close as possible to their Arduino programming language counterparts ## Simple usage example (LED blink) @@ -23,7 +25,8 @@ as possible to their Arduino programming language counterparts from Arduino import Arduino import time -board = Arduino('9600') #plugged in via USB, serial com at rate 9600 +board = Arduino() # plugged in via USB, serial com at rate 115200 +board.pinMode(13, "OUTPUT") while True: board.digitalWrite(13, "LOW") @@ -33,20 +36,20 @@ while True: ``` ## Requirements: -- [Python](http://python.org/) 2.3 or higher (Python 3.x not yet tested, but would probably work) +- [Python](http://python.org/) 3.7 tested on Windows and macOS. - [pyserial](http://pyserial.sourceforge.net/) 2.6 or higher - Any [Arduino compatible microcontroller](https://www.sparkfun.com/categories/242) with at least 14KB of flash memory ## Installation: -Either run `pip install arduino-python` from a command line, or run `python setup.py +Either run `pip install arduino-python3` from a command line, or run `python setup.py build install` from the source directory to install this library. ## Setup: 1. Verify that your Arduino board communicates at the baud rate specified in the -`setup()` function (line 348) in `prototype.ino`. Change it there if necessary. +`setup()` function (line 407) in `prototype.ino`. Change it there if necessary. 2. Load the `prototype.ino` sketch onto your Arduino board, using the Arduino IDE. 3. Set up some kind of serial I/O communication between the Arduino board and your computer (via physical USB cable, -bluetooth, xbee, etc + associated drivers) +Bluetooth, xbee, etc. + associated drivers) 4. Add `from Arduino import Arduino` into your python script to communicate with your Arduino For a collection of examples, see `examples.py`. This file contains methods which replicate @@ -73,7 +76,7 @@ $ python tests/test_arduino.py Arduino. ```python -board = Arduino("9600") #Example +board = Arduino("115200") #Example ``` The device name / COM port of the connected Arduino will be auto-detected. @@ -81,17 +84,17 @@ If there are more than one Arduino boards connected, the desired COM port can be also be passed as an optional argument: ```python -board = Arduino("9600", port = "COM3") #Windows example +board = Arduino("115200", port="COM3") #Windows example ``` ```python -board = Arduino("9600", port = "/dev/tty.usbmodemfa141") #OSX example +board = Arduino("115200", port="/dev/tty.usbmodemfa141") #OSX example ``` A time-out for reading from the Arduino can also be specified as an optional argument: ```python -board = Arduino("9600", timeout = 2) #Serial reading functions will +board = Arduino("115200", timeout=2) #Serial reading functions will #wait for no more than 2 seconds ``` @@ -142,7 +145,7 @@ board.analogWrite(11) #Set analog value (PWM) based on analog measurement **Servo Library Functionality** Support is included for up to 8 servos. -- `Arduino.Servos.attach(pin, min = 544, max = 2400)` Create servo instance. Only 8 servos can be used at one time. +- `Arduino.Servos.attach(pin, min=544, max=2400)` Create servo instance. Only 8 servos can be used at one time. - `Arduino.Servos.read(pin)` Returns the angle of the servo attached to the specified pin - `Arduino.Servos.write(pin, angle)` Move an attached servo on a pin to a specified angle - `Arduino.Servos.writeMicroseconds(pin, uS)` Write a value in microseconds to the servo on a specified pin @@ -158,21 +161,38 @@ board.Servos.detach(9) #free pin 9 **Software Serial Functionality** -- `Arduino.SoftwareSerial.begin(ss_rxPin,ss_txPin,ss_device_baud)` initialize software serial device on +- `Arduino.SoftwareSerial.begin(ss_rxPin, ss_txPin, ss_device_baud)` initialize software serial device on specified pins. -Only one sofware serial device can be used at a time. Existing software serial instance will -be be overwritten by calling this method, both in Python and on the arduino board. -- `Arduino.SoftwareSerial.write(data)` send data using the arduino 'write' function to the existing software +Only one software serial device can be used at a time. Existing software serial instance will +be overwritten by calling this method, both in Python and on the Arduino board. +- `Arduino.SoftwareSerial.write(data)` send data using the Arduino 'write' function to the existing software serial connection. - `Arduino.SoftwareSerial.read()` returns one byte from the existing software serial connection ```python #Software serial example -board.SoftwareSerial.begin(0,7,"19200") # Start software serial for transmit only (tx on pin 7) +board.SoftwareSerial.begin(0, 7, "19200") # Start software serial for transmit only (tx on pin 7) board.SoftwareSerial.write(" test ") #Send some data response_char = board.SoftwareSerial.read() #read response character ``` +**EEPROM** + +- `Arduino.EEPROM.read(address)` reads a byte from the EEPROM +- `Arduino.EEPROM.write(address, value)` writes a byte to the EEPROM +- `Arduino.EEPROM.size()` returns size of the EEPROM + +```python +#EEPROM read and write examples +location = 42 +value = 10 # 0-255(byte) + +board.EEPROM.write(location, 10) +print(board.EEPROM.read(location)) +print('EEPROM size {size}'.format(size=board.EEPROM.size())) +``` + + **Misc** - `Arduino.close()` closes serial connection to the Arduino. @@ -184,4 +204,3 @@ response_char = board.SoftwareSerial.read() #read response character - Include a wizard which generates 'prototype.ino' with selected serial baud rate and Arduino function support (to help reduce memory requirements). - Multi-serial support for Arduino mega (`Serial1.read()`, etc) - diff --git a/examples.py b/examples.py index 5a2e143..2da6906 100644 --- a/examples.py +++ b/examples.py @@ -8,7 +8,7 @@ def Blink(led_pin, baud, port=""): Blinks an LED in 1 sec intervals """ board = Arduino(baud, port=port) - board.pinMode(13, "OUTPUT") + board.pinMode(led_pin, "OUTPUT") while True: board.digitalWrite(led_pin, "LOW") print board.digitalRead(led_pin) # confirm LOW (0) @@ -73,4 +73,4 @@ def LCD(tx, baud, ssbaud, message, port=""): board.SoftwareSerial.write(" test ") if __name__ == "__main__": - Blink(13, '9600') + Blink(13, '115200') diff --git a/pypi_commands.txt b/pypi_commands.txt new file mode 100644 index 0000000..4b709a3 --- /dev/null +++ b/pypi_commands.txt @@ -0,0 +1,2 @@ +python3 setup.py sdist bdist_wheel +python3 -m twine upload dist/* diff --git a/setup.py b/setup.py index 0558d82..074671c 100644 --- a/setup.py +++ b/setup.py @@ -1,13 +1,19 @@ -from setuptools import setup +import setuptools -setup(name='arduino-python', - version='0.2', - install_requires=['pyserial'], - description="A light-weight Python library that provides a serial \ - bridge for communicating with Arduino microcontroller boards.", - author='Tristan Hearn', - author_email='tristanhearn@gmail.com', - url='https://github.com/thearn/Python-Arduino-Command-API', - license='Apache 2.0', - packages=['Arduino'], - ) +with open("README.md", "r") as fh: + long_description = fh.read() + +setuptools.setup( + name="arduino-python3", + version="0.6", + install_requires=['pyserial'], + author="Morten Kals", + author_email="morten@kals.no", + description="A light-weight Python library that provides a serial \ + bridge for communicating with Arduino microcontroller boards. Extended to work with Python 3", + long_description=long_description, + long_description_content_type="text/markdown", + url='https://github.com/mkals/Arduino-Python3-Command-API', + packages=['Arduino'], + license='MIT', +) diff --git a/sketches/prototype/prototype.ino b/sketches/prototype/prototype.ino index 867c360..9170196 100644 --- a/sketches/prototype/prototype.ino +++ b/sketches/prototype/prototype.ino @@ -1,6 +1,12 @@ #include #include #include +#include + +void Version(){ + Serial.println(F("V0.6")); +} + SoftwareSerial *sserial = NULL; Servo servos[8]; @@ -24,10 +30,6 @@ void split(String results[], int len, String input, char spChar) { } } -void Version(){ - Serial.println("version"); -} - uint8_t readCapacitivePin(String data) { int pinToMeasure = Str2int(data); // readCapacitivePin @@ -81,7 +83,7 @@ uint8_t readCapacitivePin(String data) { else if (*pin & bitmask) { cycles = 16;} // Discharge the pin again by setting it low and output - // It's important to leave the pins low if you want to + // It's important to leave the pins low if you want to // be able to touch more than 1 sensor at a time - if // the sensor is left pulled high, when you touch // two sensors, your body will transfer the charge between @@ -111,12 +113,12 @@ void Tone(String data){ delay(pause); noTone(pin); } -} +} void ToneNo(String data){ int pin = Str2int(data); noTone(pin); -} +} void DigitalHandler(int mode, String data){ int pin = Str2int(data); @@ -154,7 +156,7 @@ void ConfigurePinHandler(String data){ } } -void shiftOutHandler(String data) { +void shiftOutHandler(String data) { String sdata[4]; split(sdata, 4, data, '%'); int dataPin = sdata[0].toInt(); @@ -200,10 +202,10 @@ void SS_write(String data) { char buffer[len]; data.toCharArray(buffer,len); Serial.println("ss OK"); - sserial->write(buffer); + sserial->write(buffer); } void SS_read(String data) { - char c = sserial->read(); + char c = sserial->read(); Serial.println(c); } @@ -212,10 +214,10 @@ void pulseInHandler(String data){ long duration; if(pin <=0){ pinMode(-pin, INPUT); - duration = pulseIn(-pin, LOW); + duration = pulseIn(-pin, LOW); }else{ pinMode(pin, INPUT); - duration = pulseIn(pin, HIGH); + duration = pulseIn(pin, HIGH); } Serial.println(duration); } @@ -231,7 +233,7 @@ void pulseInSHandler(String data){ delayMicroseconds(5); digitalWrite(-pin, HIGH); pinMode(-pin, INPUT); - duration = pulseIn(-pin, LOW); + duration = pulseIn(-pin, LOW); }else{ pinMode(pin, OUTPUT); digitalWrite(pin, LOW); @@ -240,7 +242,7 @@ void pulseInSHandler(String data){ delayMicroseconds(5); digitalWrite(pin, LOW); pinMode(pin, INPUT); - duration = pulseIn(pin, HIGH); + duration = pulseIn(pin, HIGH); } Serial.println(duration); } @@ -301,6 +303,19 @@ void SV_write_ms(String data) { servos[pos].writeMicroseconds(uS); } +void sizeEEPROM() { + Serial.println(E2END + 1); +} + +void EEPROMHandler(int mode, String data) { + String sdata[2]; + split(sdata, 2, data, '%'); + if (mode == 0) { + EEPROM.write(Str2int(sdata[0]), Str2int(sdata[1])); + } else { + Serial.println(EEPROM.read(Str2int(sdata[0]))); + } +} void SerialParser(void) { char readChar[64]; @@ -312,64 +327,64 @@ void SerialParser(void) { // separate command from associated data String cmd = read_.substring(1,idx1); String data = read_.substring(idx1+1,idx2); - + // determine command sent if (cmd == "dw") { - DigitalHandler(1, data); + DigitalHandler(1, data); } else if (cmd == "dr") { - DigitalHandler(0, data); - } + DigitalHandler(0, data); + } else if (cmd == "aw") { - AnalogHandler(1, data); - } + AnalogHandler(1, data); + } else if (cmd == "ar") { - AnalogHandler(0, data); - } + AnalogHandler(0, data); + } else if (cmd == "pm") { - ConfigurePinHandler(data); - } + ConfigurePinHandler(data); + } else if (cmd == "ps") { - pulseInSHandler(data); - } + pulseInSHandler(data); + } else if (cmd == "pi") { - pulseInHandler(data); - } + pulseInHandler(data); + } else if (cmd == "ss") { - SS_set(data); + SS_set(data); } else if (cmd == "sw") { - SS_write(data); + SS_write(data); } else if (cmd == "sr") { - SS_read(data); - } + SS_read(data); + } else if (cmd == "sva") { - SV_add(data); - } + SV_add(data); + } else if (cmd == "svr") { - SV_read(data); - } + SV_read(data); + } else if (cmd == "svw") { - SV_write(data); - } + SV_write(data); + } else if (cmd == "svwm") { - SV_write_ms(data); - } + SV_write_ms(data); + } else if (cmd == "svd") { - SV_remove(data); - } + SV_remove(data); + } else if (cmd == "version") { - Version(); + Version(); } else if (cmd == "to") { - Tone(data); - } + Tone(data); + } else if (cmd == "nto") { - ToneNo(data); - } + ToneNo(data); + } else if (cmd == "cap") { - readCapacitivePin(data); + readCapacitivePin(data); } else if (cmd == "so") { shiftOutHandler(data); @@ -377,16 +392,25 @@ void SerialParser(void) { else if (cmd == "si") { shiftInHandler(data); } - + else if (cmd == "eewr") { + EEPROMHandler(0, data); + } + else if (cmd == "eer") { + EEPROMHandler(1, data); + } + else if (cmd == "sz") { + sizeEEPROM(); + } } void setup() { - Serial.begin(9600); + Serial.begin(115200); while (!Serial) { - ; // wait for serial port to connect. Needed for Leonardo only - } + ; // wait for serial port to connect. Needed for Leonardo only + } + Serial.println("connected"); } void loop() { - SerialParser(); - } + SerialParser(); +} diff --git a/tests/test_arduino.py b/tests/test_arduino.py index 51c138d..21e76e8 100644 --- a/tests/test_arduino.py +++ b/tests/test_arduino.py @@ -58,7 +58,7 @@ class ArduinoTestCase(unittest.TestCase): def setUp(self): from Arduino.arduino import Arduino - self.mock_serial = MockSerial(9600, '/dev/ttyACM0') + self.mock_serial = MockSerial(115200, '/dev/ttyACM0') self.board = Arduino(sr=self.mock_serial) @@ -85,21 +85,21 @@ def test_version(self): from Arduino.arduino import build_cmd_str expected_version = "version" self.mock_serial.push_line(expected_version) - self.assertEquals(self.board.version(), expected_version) - self.assertEquals(self.mock_serial.output[0], build_cmd_str('version')) + self.assertEqual(self.board.version(), expected_version) + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('version')) def test_pinMode_input(self): from Arduino.arduino import build_cmd_str pin = 9 self.board.pinMode(pin, INPUT) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('pm', (-pin,))) def test_pinMode_output(self): from Arduino.arduino import build_cmd_str pin = 9 self.board.pinMode(pin, OUTPUT) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('pm', (pin,))) def test_pulseIn_low(self): @@ -107,8 +107,8 @@ def test_pulseIn_low(self): expected_duration = 230 self.mock_serial.push_line(expected_duration) pin = 9 - self.assertEquals(self.board.pulseIn(pin, LOW), expected_duration) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.board.pulseIn(pin, LOW), expected_duration) + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('pi', (-pin,))) def test_pulseIn_high(self): @@ -116,27 +116,27 @@ def test_pulseIn_high(self): expected_duration = 230 pin = 9 self.mock_serial.push_line(expected_duration) - self.assertEquals(self.board.pulseIn(pin, HIGH), expected_duration) - self.assertEquals(self.mock_serial.output[0], build_cmd_str('pi', (pin,))) + self.assertEqual(self.board.pulseIn(pin, HIGH), expected_duration) + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('pi', (pin,))) def test_digitalRead(self): from Arduino.arduino import build_cmd_str pin = 9 self.mock_serial.push_line(READ_LOW) - self.assertEquals(self.board.digitalRead(pin), READ_LOW) - self.assertEquals(self.mock_serial.output[0], build_cmd_str('dr', (pin,))) + self.assertEqual(self.board.digitalRead(pin), READ_LOW) + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('dr', (pin,))) def test_digitalWrite_low(self): from Arduino.arduino import build_cmd_str pin = 9 self.board.digitalWrite(pin, LOW) - self.assertEquals(self.mock_serial.output[0], build_cmd_str('dw', (-pin,))) + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('dw', (-pin,))) def test_digitalWrite_high(self): from Arduino.arduino import build_cmd_str pin = 9 self.board.digitalWrite(pin, HIGH) - self.assertEquals(self.mock_serial.output[0], build_cmd_str('dw', (pin,))) + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('dw', (pin,))) def test_melody(self): from Arduino.arduino import build_cmd_str @@ -145,9 +145,9 @@ def test_melody(self): duration = 4 C4_NOTE = 262 self.board.Melody(pin, notes, [duration]) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('to', (len(notes), pin, C4_NOTE, duration))) - self.assertEquals(self.mock_serial.output[1], + self.assertEqual(self.mock_serial.output[1].decode('UTF-8'), build_cmd_str('nto', (pin,))) def test_shiftIn(self): @@ -157,9 +157,9 @@ def test_shiftIn(self): pinOrder = MSBFIRST expected = 0xff self.mock_serial.push_line(expected) - self.assertEquals(self.board.shiftIn(dataPin, clockPin, pinOrder), + self.assertEqual(self.board.shiftIn(dataPin, clockPin, pinOrder), expected) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('si', (dataPin, clockPin, pinOrder,))) def test_shiftOut(self): @@ -169,7 +169,7 @@ def test_shiftOut(self): pinOrder = MSBFIRST value = 0xff self.board.shiftOut(dataPin, clockPin, pinOrder, value) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('so', (dataPin, clockPin, pinOrder, value))) def test_analogRead(self): @@ -177,8 +177,8 @@ def test_analogRead(self): pin = 9 expected = 1023 self.mock_serial.push_line(expected) - self.assertEquals(self.board.analogRead(pin), expected) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.board.analogRead(pin), expected) + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('ar', (pin,))) def test_analogWrite(self): @@ -186,7 +186,7 @@ def test_analogWrite(self): pin = 9 value = 255 self.board.analogWrite(pin, value) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('aw', (pin, value))) @@ -200,7 +200,7 @@ def test_attach(self): servo_min = 544 servo_max = 2400 self.board.Servos.attach(pin, min=servo_min, max=servo_max) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('sva', (pin, servo_min, servo_max))) def test_detach(self): @@ -212,7 +212,7 @@ def test_detach(self): self.board.Servos.attach(pin) self.mock_serial.reset_mock() self.board.Servos.detach(pin) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str('svd', (position,))) def test_write(self): @@ -225,7 +225,7 @@ def test_write(self): self.board.Servos.attach(pin) self.mock_serial.reset_mock() self.board.Servos.write(pin, angle) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str("svw", (position, angle))) def test_writeMicroseconds(self): @@ -238,7 +238,7 @@ def test_writeMicroseconds(self): self.board.Servos.attach(pin) self.mock_serial.reset_mock() self.board.Servos.writeMicroseconds(pin, microseconds) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str("svwm", (position, microseconds))) def test_read(self): @@ -251,8 +251,8 @@ def test_read(self): self.board.Servos.attach(pin) self.mock_serial.reset_mock() self.mock_serial.push_line(angle) - self.assertEquals(self.board.Servos.read(pin), angle) - self.assertEquals(self.mock_serial.output[0], + self.assertEqual(self.board.Servos.read(pin), angle) + self.assertEqual(self.mock_serial.output[0].decode('UTF-8'), build_cmd_str("svr", (position,))) diff --git a/tests/test_main.py b/tests/test_main.py index 0ec221f..9f414b4 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -14,18 +14,24 @@ logging.basicConfig(level=logging.DEBUG) +# Bind raw_input to input in python 2.7 +try: + input = raw_input +except NameError: + pass + class TestBasics(unittest.TestCase): def test_find(self): """ Tests auto-connection/board detection. """ - raw_input( + input( 'Plug in Arduino board w/LED at pin 13, reset, then press enter') from Arduino import Arduino board = None try: # This will trigger automatic port resolution. - board = Arduino(9600) + board = Arduino(115200) finally: if board: board.close() @@ -34,15 +40,15 @@ def test_open(self): """ Tests connecting to an explicit port. """ port = None while not port: - port = raw_input( + port = input( 'Plug in Arduino board w/LED at pin 13, reset.\n'\ 'Enter the port where the Arduino is connected, then press enter:') if not port: - print 'You must enter a port.' + print('You must enter a port.') from Arduino import Arduino board = None try: - board = Arduino(9600, port=port) + board = Arduino(115200, port=port) finally: if board: board.close()