Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
USB Serial Communication Between Arduino and Raspberry Pi
#define BUTTON 2
#define LED1 3
#define LED2 4
#define LED3 5
#define PIEZO 8
#define NOTE_D4 294
#define NOTE_G4 392
#define NOTE_B4 494
void setup()
{
pinMode(BUTTON, INPUT_PULLUP);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
Serial.begin(9600);
}
void loop()
{
if (digitalRead(BUTTON) == LOW) {
Serial.print("Button Pressed");
while (digitalRead(BUTTON) == LOW);
delay(100);
}
if (Serial.available()) {
delay(100);
String inString = "";
while (Serial.available()) {
char inChar = (char)Serial.read();
inString += inChar;
}
if (inString == "SW1 Pressed") {
digitalWrite(LED1, HIGH);
playTone(NOTE_D4);
digitalWrite(LED1, LOW);
}
else if (inString == "SW2 Pressed") {
digitalWrite(LED2, HIGH);
playTone(NOTE_G4);
digitalWrite(LED2, LOW);
}
else if (inString == "SW3 Pressed") {
digitalWrite(LED3, HIGH);
playTone(NOTE_B4);
digitalWrite(LED3, LOW);
}
}
}
void playTone(int note)
{
tone(PIEZO, note, 200);
delay(200);
noTone(PIEZO);
}
from gpiozero import LED, Button, Buzzer
import serial
led1 = LED(17)
sw1 = Button(21)
sw2 = Button(16)
sw3 = Button(20)
buzzer = Buzzer(26)
serialPort = serial.Serial("/dev/ttyUSB0", 9600, timeout=0.5)
def sw1Pressed():
serialPort.write("SW1 Pressed".encode('utf-8'))
def sw2Pressed():
serialPort.write("SW2 Pressed".encode('utf-8'))
def sw3Pressed():
serialPort.write("SW3 Pressed".encode('utf-8'))
sw1.when_pressed = sw1Pressed
sw2.when_pressed = sw2Pressed
sw3.when_pressed = sw3Pressed
try:
while True:
command = serialPort.read_until('\0', size=None)
commandString = command.decode('utf-8')
if len(commandString) > 0:
print(commandString)
if commandString == "Button Pressed":
led1.on()
buzzer.beep(0.1, 0.1, 2)
led1.off()
except KeyboardInterrupt:
led1.off()
buzzer.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment