If you have followed last week's post on Adafruit's Circuit Playground, you now have a working communication between your computer and the board. In this example, I would like to establish the communication between my Raspberry Pi over the serial communication to the board. This way I can leverage everything the RasPi has while utilizing the sensors and outputs from the board.
The package I need is PySerial, which can be installed via 'sudo pip install pyserial'. It is used as the 'serial' package in Python code.
Here is the objective:
- The Arduino code will print out serial output when either the right or left button is pressed.
- When the B key is pressed, the LED light will light up one at a time.
- In the Python code we will send the letter B 9 times then wait for any serial input
Here is the Python code. Python Code. A few notes:
- Raspberry Pi the serial port is /dev/ttyACM0 and /dev/cu.usbmodem142 on Mac, therefore I comment out the line depending on if I am on the Mac or Raspberry Pi.
- The character is sent as Bytecode, so chr(0x42) is used for letter 'B'. Here is an ASCII table.
- Timeout of 1 second is used to gradually light up the LED.
import serialimport time#ser = serial.Serial('/dev/ttyACM0', 9600)ser = serial.Serial('/dev/cu.usbmodem1421', 9600)# ASCII character 'B'sendChr = chr(0x42)# Send character B which turns on light one at a timefor i in range(9):ser.write(sendChr)time.sleep(1)# Read the input from boardwhile True:message = ser.readline()print(message)
Here is the Arduino Code:
- I am using the Demo code provided by Adafruit:
- Use the library manager to install the Adafruit Circuit Playground Libraries
// Demo program for testing library and board - flip the switch to turn on/off buzzer#include <Adafruit_CircuitPlayground.h>#include <Wire.h>#include <SPI.h>// we light one pixel at a time, this is our counteruint8_t pixeln = 0;byte byteRead;void setup() {//while (!Serial);Serial.begin(9600);Serial.println("Circuit Playground test!");CircuitPlayground.begin();}void loop() {/************* TEST BOTH BUTTONS */if (CircuitPlayground.leftButton()) {Serial.println("Left button pressed!");}delay(100);if (CircuitPlayground.rightButton()) {Serial.println("Right button pressed!");}delay(100);/************** Read Serial In, 65 DEC ASCII is letter B */byteRead = Serial.read();if(byteRead == 66) {Serial.println("Letter B input, turn on light");//Serial.write(byteRead);CircuitPlayground.redLED(HIGH);delay(100);CircuitPlayground.redLED(LOW);delay(100);CircuitPlayground.setPixelColor(pixeln++, CircuitPlayground.colorWheel(25 * pixeln));if (pixeln == 11) {pixeln = 0;CircuitPlayground.clearPixels();}}}
Another screenshot for the IDE:
You can also use the serial monitor included with the Arduino IDE to test:
This is really fun, I cant wait to see all the possibilities when combining the two!
No comments:
Post a Comment