Proof of Concept#
Using just the board without any extra electronic hardware, we can communicate directly with the board, and on receiving our message it can interpret this information and send back processed information. This sleight of hand relies on the fact that characters can be addressed by their character number.
Show/Hide Code sendASCII.ino
1// sendASCII.ino
2// echos request for ascii characters
3// no hardware setup
4
5void setup() {
6 Serial.begin(9600); // set the baud rate
7 Serial.println("Ready"); // print "Ready" once
8 }
9
10void loop() {
11 char inByte = ' ';
12 if(Serial.available()){ // only send data back if data has been received
13 char inByte = Serial.read(); // read the incoming data
14 Serial.println(inByte); // send the data back in a new line
15 //so that it is not all one long line
16 }
17
18 delay(100); // delay for 1/10 of a second
19}
Note
Scripts and Sketches
The python scripts can be found in the scripts directory, the ino sketches in the sketches directory, each in its own subdirectory. You may find it useful to put the python scripts in the subdirectory of the associated sketch.
As you can see we are using the standard format for the Arduino sketch. No libraries are required, so straight in with the setup where just the serial port needs to be installed. After that the loop function, where we hold the board back until after the serial port becomes available. Plug the Arduino into the serial port and compile the program, which stays on the Arduino until the next program is compiled, even when the power source is disconnected.
Now sort out the Python part, you can leave the Arduino on or off the serial port.
Show/Hide Code sendASCII.py
1# sendASCII.py
2# has problem with ASCII 127
3# if strip left off have space between lines
4
5from time import sleep
6import serial
7
8def byte2utf(x):
9 # strip before or after decode works
10 return(x.decode('utf-8').strip())
11
12ser = serial.Serial('com3', 9600) # Establish the connection on a specific port
13counter = 32 # Below 32 everything in ASCII is gibberish
14while True:
15 counter +=1
16 # str.encode(my_str) convert string to bytes
17 # Convert the decimal number to ASCII then send it to the Arduino
18 ser.write(str.encode(chr(counter)))
19 # Read the newest output from the Arduino
20 print (ser.readline().decode('utf-8'))
21 sleep(.1) # Delay for one tenth of a second
22 if counter == 126: # originally 255
23 counter = 32
After importing serial and time we open the serial port - adjust to suit your operating system - there is no need to start the Arduino, just plug in the serial port to the Aeduino, it automatically detects the receiver on the serial port. Once the Arduino starts to transmit the computer in turn starts to transmit information which is then returned before printing the received information. You will notice that the main computer is encoding and decoding the data, leaving the Arduino simply to read and retransmit the same data.