We want to communicate with an Arduino from Python / Matlab.
Questions to [David Rotermund](mailto:davrot@uni-bremen.de)
Get the environment ready
Before we can really interact with the Arduino board, we need to make the environment ready first:
Download and install the Arduino IDE.
Connect the Arduino via USB cable to the computer.
Open the Arduino IDE.
Open the Blink example. Files -> Examples -> 01. Basics -> Blink
Check the setting: Tools-> Board and Tools->Port
Get the board information as a test: Tools -> Get Board Info
Upload the sketch (means source code)
The Arduino led should blink now.
If you use Python for controlling the Arduino, make sure that the serial package is installed:
pip install pyserial
WARNING: If you open a communication channel with Python / Matlab then a reset signal is created that resets the Arduino. Thus only open the communication once and keep it open as long as you require a connection to the Arduino.
In the case that you are a VS code user, you want to add the Microsoft Arduino extension to VS code for editing the Arduino ino files in style and not like a caveperson with the Arduino IDE:
Controlling the LED
We want to control the LED on the Arduino board via an external software.
Note: I see it as a good style to make sure that we communicate in a fashion that reduces misunderstandings. Thus I will start any control sequence with the integer value 60 (the <symbolinASCII)andenditwiththeintegervalue62(the> symbol in ASCII). The source code is prepared to handle up to 32x 8 bit integer values as payload. However we will only evaluate the value at index 0 in the switch case construct.
The Arduino sketch
int rc;
boolean recvInProgress = false;
int startMarker = 60; // <
int endMarker = 62; // >
int numChars = 32;
int receivedChars[32];
int index = 0;
int Used = 0;
boolean newData = false;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
if ((Serial.available() > 0) && (newData == false)) {
rc = Serial.read();
if ((recvInProgress == true) && (rc == endMarker)){
fprintf(['Arduino-clock in ms: ' num2str(returned_value) '\n']);
end
end
end
end
clear ser
Sending the time on a rising interrupt
Via attachInterrupt() we attach a function to an interrupt which is triggered when a low -> high transition on a defined pin ocures. Not every pin is capable of doing so. I will use pin 2 on the Uno. Please check attachInterrupt() for list of pins.
The software side is the same as in the previous example.
|[abs()](https://www.arduino.cc/reference/en/language/functions/math/abs/)| Calculates the absolute value of a number. |
|[constrain() ](https://www.arduino.cc/reference/en/language/functions/math/constrain/)| Constrains a number to be within a range. |
|[map() ](https://www.arduino.cc/reference/en/language/functions/math/map/)| Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between, etc. |
|[max() ](https://www.arduino.cc/reference/en/language/functions/math/max/)| Calculates the maximum of two numbers. |
|[min() ](https://www.arduino.cc/reference/en/language/functions/math/min/)| Calculates the minimum of two numbers. |
|[pow() ](https://www.arduino.cc/reference/en/language/functions/math/pow/)| Calculates the value of a number raised to a power. pow() can be used to raise a number to a fractional power. This is useful for generating exponential mapping of values or curves.|
|[sq() ](https://www.arduino.cc/reference/en/language/functions/math/sq/)| Calculates the square of a number: the number multiplied by itself. |
|[sqrt() ](https://www.arduino.cc/reference/en/language/functions/math/sqrt/)| Calculates the square root of a number. |
|[cos() ](https://www.arduino.cc/reference/en/language/functions/trigonometry/cos/)| Calculates the cosine of an angle (in radians). The result will be between -1 and 1. |
|[sin() ](https://www.arduino.cc/reference/en/language/functions/trigonometry/sin/)| Calculates the sine of an angle (in radians). The result will be between -1 and 1. |
|[tan() ](https://www.arduino.cc/reference/en/language/functions/trigonometry/tan/)| Calculates the tangent of an angle (in radians). The result will be between negative infinity and infinity. |
|[random() ](https://www.arduino.cc/reference/en/language/functions/random-numbers/random/)| The random function generates pseudo-random numbers. |
|[randomSeed() ](https://www.arduino.cc/reference/en/language/functions/random-numbers/randomseed/)| randomSeed() initializes the pseudo-random number generator, causing it to start at an arbitrary point in its random sequence. This sequence, while very long, and random, is always the same. |
|[highByte() ](https://www.arduino.cc/reference/en/language/functions/bits-and-bytes/highbyte/)| Extracts the high-order (leftmost) byte of a word (or the second lowest byte of a larger data type). |
|[lowByte()](https://www.arduino.cc/reference/en/language/functions/bits-and-bytes/lowbyte/)| Extracts the low-order (rightmost) byte of a variable (e.g. a word). |
|[setup() ](https://www.arduino.cc/reference/en/language/structure/sketch/setup/)| "The setup() function is called when a sketch starts. Use it to initialize variables, pin modes, start using libraries, etc. The setup() function will only run once, after each powerup or reset of the Arduino board."|
|[loop() ](https://www.arduino.cc/reference/en/language/structure/sketch/loop/)| "After creating a [setup()](https://www.arduino.cc/reference/en/language/structure/sketch/setup/) function, which initializes and sets the initial values, the loop() function does precisely what its name suggests, and loops consecutively, allowing your program to change and respond. "|
|[pinMode() ](https://www.arduino.cc/reference/en/language/functions/digital-io/pinmode/)| "Configures the specified pin to behave either as an input or an output."|
|[digitalRead()](https://www.arduino.cc/reference/en/language/functions/digital-io/digitalread/)| "Reads the value from a specified digital pin, either HIGH or LOW."|
|[digitalWrite() ](https://www.arduino.cc/reference/en/language/functions/digital-io/digitalwrite/)| "Write a HIGH or a LOW value to a digital pin."|
|[analogRead() ](https://www.arduino.cc/reference/en/language/functions/analog-io/analogread/)| "Reads the value from the specified analog pin. Arduino boards contain a multichannel, 10-bit analog to digital converter. This means that it will map input voltages between 0 and the operating voltage(5V or 3.3V) into integer values between 0 and 1023."|
|[analogWrite() ](https://www.arduino.cc/reference/en/language/functions/analog-io/analogwrite/)| "Writes an analog value ([PWM wave](https://docs.arduino.cc/learn/microcontrollers/analog-output)) to a pin. Can be used to light a LED at varying brightnesses or drive a motor at various speeds. After a call to analogWrite(), the pin will generate a steady rectangular wave of the specified duty cycle until the next call to analogWrite() (or a call to digitalRead() or digitalWrite()) on the same pin."|
|[millis() ](https://www.arduino.cc/reference/en/language/functions/time/millis/)| "Returns the number of milliseconds passed since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 50 days."|
|[micros() ](https://www.arduino.cc/reference/en/language/functions/time/micros/)| "Returns the number of microseconds since the Arduino board began running the current program. This number will overflow (go back to zero), after approximately 70 minutes."|
|[delay() ](https://www.arduino.cc/reference/en/language/functions/time/delay/)| "Pauses the program for the amount of time (in milliseconds) specified as parameter."|
|[delayMicroseconds() ](https://www.arduino.cc/reference/en/language/functions/time/delaymicroseconds/)| "Pauses the program for the amount of time (in microseconds) specified by the parameter. [...] Currently, the largest value that will produce an accurate delay is 16383; larger values can produce an extremely short delay."|
|[map() ](https://www.arduino.cc/reference/en/language/functions/math/map/)| "Re-maps a number from one range to another. That is, a value of fromLow would get mapped to toLow, a value of fromHigh to toHigh, values in-between to values in-between"|
|[Serial.begin() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/begin/)| "Sets the data rate in bits per second (baud) for serial data transmission." **WARNING: What ever you use as a data rate, make sure that the data rate is set to the same value everywhere!**|
|[if(Serial) ](https://www.arduino.cc/reference/en/language/functions/communication/serial/ifserial/)| "Indicates if the specified Serial port is ready. On the boards with native USB, if (Serial) (or if(SerialUSB) on the Due) indicates whether or not the USB CDC serial connection is open. For all other boards, and the non-USB CDC ports, this will always return true."|
|[Serial.available() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/available/)| "Get the number of bytes (characters) available for reading from the serial port. This is data that’s already arrived and stored in the serial receive buffer (which holds 64 bytes)."|
|[Serial.read() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/read/)| "Reads incoming serial data." Note: Reads ONE byte into a int variable.|
|[Serial.readBytes() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/readbytes/)| "Serial.readBytes() reads characters from the serial port into a buffer. The function terminates if the determined length has been read, or it times out (see [Serial.setTimeout())](https://www.arduino.cc/reference/en/language/functions/communication/serial/settimeout/)."|
|[Serial.setTimeout() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/settimeout/)| "Serial.setTimeout() sets the maximum milliseconds to wait for serial data. It defaults to 1000 milliseconds."|
|[Serial.peek() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/peek/)| "Returns the next byte (character) of incoming serial data without removing it from the internal serial buffer. That is, successive calls to peek() will return the same character, as will the next call to read()."|
|[Serial.availableForWrite() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/availableforwrite/)| "Get the number of bytes (characters) available for writing in the serial buffer without blocking the write operation."|
|[Serial.write() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/write/)| "Writes binary data to the serial port. This data is sent as a byte or series of bytes; to send the characters representing the digits of a number use the [print()](https://www.arduino.cc/reference/en/language/functions/communication/serial/print/) function instead."|
|[Serial.print() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/print/)| "Prints data to the serial port as human-readable ASCII text. "|
|[Serial.println() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/println/)| "Prints data to the serial port as human-readable ASCII text followed by a carriage return character (ASCII 13, or '\r') and a newline character (ASCII 10, or '\n'). This command takes the same forms as [Serial.print()](https://www.arduino.cc/reference/en/language/functions/communication/serial/print/)."|
|[Serial.flush() ](https://www.arduino.cc/reference/en/language/functions/communication/serial/flush/)| "Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)"|
|[attachInterrupt() ](https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/)| Connect a function to one of the interrupt pins|
|[detachInterrupt() ](https://www.arduino.cc/reference/en/language/functions/external-interrupts/detachinterrupt/)| "Turns off the given interrupt."|
|[interrupts() ](https://www.arduino.cc/reference/en/language/functions/interrupts/interrupts/)| "Re-enables interrupts (after they’ve been disabled by [noInterrupts()](https://www.arduino.cc/reference/en/language/functions/interrupts/nointerrupts/). "|
|[noInterrupts() ](https://www.arduino.cc/reference/en/language/functions/interrupts/nointerrupts/)| "Disables interrupts (you can re-enable them with [interrupts()](https://www.arduino.cc/reference/en/language/functions/interrupts/interrupts/))."|