Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Fixed auto-connect, decode bug and added firmware version check
  • Loading branch information
mkals committed Apr 21, 2019
commit c1f426507602aa82aedc02a723789c10174304c3
46 changes: 32 additions & 14 deletions Arduino/arduino.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
else:
import glob

libraryVersion = 'V0.4'

log = logging.getLogger(__name__)

Expand Down Expand Up @@ -62,6 +63,7 @@ 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:
Expand All @@ -71,31 +73,40 @@ def find_port(baud, timeout):
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':
log.debug('Bad version {0}. This is not a Shrimp/Arduino!'.format(
version))
sr.close()
continue

if version != libraryVersion:
if version[0] == 'V' or version == "version":
print("You need to update the version of the Arduino-Python3 ",
"library running on your Arduino. ",
"Flash the prototype sketch again.")
return sr
else:
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(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=115200, port=None, timeout=2, sr=None):
"""
Initializes serial communication with Arduino if no connection is
Expand All @@ -108,7 +119,14 @@ def __init__(self, baud=115200, port=None, timeout=2, sr=None):
raise ValueError("Could not find port.")
else:
sr = serial.Serial(port, baud, timeout=timeout)
sr.readline()
sr.readline() # wait til board has rebooted and is connected

# check version
if get_version(sr) != libraryVersion:
print("You need to update the version of the Arduino-Python3 ",
"library running on your Arduino. ",
"Flash the prototype sketch again.")

sr.flush()
self.sr = sr
self.SoftwareSerial = SoftwareSerial(self)
Expand Down Expand Up @@ -572,7 +590,7 @@ def begin(self, p1, p2, baud):
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
Expand All @@ -592,7 +610,7 @@ def write(self, data):
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:
Expand All @@ -607,7 +625,7 @@ def read(self):
cmd_str = build_cmd_str("sr")
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:
Expand All @@ -632,7 +650,7 @@ def size(self):
try:
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", "")
return int(response)
except:
return 0
Expand Down Expand Up @@ -664,7 +682,7 @@ def read(self, adrress):
try:
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 int(response)
except:
Expand Down
25 changes: 25 additions & 0 deletions Arduino/temp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

from arduino import Arduino

board = Arduino()

#from Arduino import Arduino
#import time
#
#PORT_NAME = '/dev/tty.usbserial-1410' # MUST BE UPDATED TO USE THE CORRECT PORT
#PIN_SENSE = 12 # pin where ultrasic sensor is connected
#
## connect to Arduino
#board = Arduino(port=PORT_NAME)
#print('Connected')
#
#try:
# while True:
# # make distance measurement
# pulseTime = board.pulseIn_set(PIN_SENSE, 'HIGH')
# print(pulseTime)
#
# time.sleep(1) # delay to keep UART bus for getting overloaded
#
#except KeyboardInterrupt:
# board.close() # close serial connection
15 changes: 9 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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 Python Arduino Command API is a lightweight Python library for
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
or wirelessly. It is written using a custom protocol, similar to [Firmata](http://firmata.org/wiki/Main_Page).
Expand All @@ -11,7 +11,7 @@ This allows a user to quickly prototype programs for Arduino using Python code,
simply read/control/troubleshoot/experiment
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)
Expand All @@ -25,7 +25,7 @@ as possible to their Arduino programming language counterparts
from Arduino import Arduino
import time

board = Arduino('115200') #plugged in via USB, serial com at rate 115200
board = Arduino() # plugged in via USB, serial com at rate 115200
board.pinMode(13, "OUTPUT")

while True:
Expand Down Expand Up @@ -193,6 +193,9 @@ print('EEPROM size {size}'.format(size=board.EEPROM.size()))
```

**DHT**

- `Arduino.dht(pin, module)` reads sensor values from the DHT sensor connected at the specified pin.

Read data from DHT temperature and humidity sensors based on the
Adafruit [DHT sensor library](https://github.com/adafruit/DHT-sensor-library).

Expand All @@ -207,10 +210,10 @@ There are five sensors that work with this library:

The function returns an array of three elements:
1. humidity (in %)
2. temperature (in celcius)
3. heat index (in celcius)
2. temperature (in Celsius)
3. heat index (in Celsius)

If there is an error with the reading (eg. the selected sensor is wrong) all values will return as zero.
If there is an error with the reading (e.g., the selected sensor is wrong) all values will return as zero.

```python
#DHT sensor example
Expand Down
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,15 @@

setuptools.setup(
name="arduino-python3",
version="0.3",
version="0.4",
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/Python-Arduino-Command-API',
url='https://github.com/mkals/Arduino-Python3-Command-API',
packages=['Arduino'],
license='MIT',
)
9 changes: 5 additions & 4 deletions sketches/prototype/prototype.ino
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
#include <EEPROM.h>
#include <DHT.h>

void Version(){
Serial.println(F("V0.4"));
}


SoftwareSerial *sserial = NULL;
Servo servos[8];
int servo_pins[] = {0, 0, 0, 0, 0, 0, 0, 0};
Expand All @@ -26,10 +31,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
Expand Down