How to Use Raspberry Pi With Arduino Via USB Serial

Arduino and Raspberry Pi serial collaboration!
게시자

Arduino and Raspberry Pi boards seem similar at first glance–small computer-ish devices with a number of IO pins. As you likely know, however, Raspberry Pi boards (with the exception of the Arduino-like Pico, which is put aside for the purposes of this article) can function as an actual computer, in addition to their IO capabilities. Arduinos, however, are microcontroller development boards, making it easy to receive inputs and turn signal bits on and off.

Why Both? Projects Using Arduino and Raspberry Pi

While you might be tempted to use a Raspberry Pi for your project and call it a day, there are many instances where you’d want to use both in tandem. While non-Pico Pi boards feature much more processing power than your average Arduino, they’re also burdened with an entire operating system. So, unlike an Arduino, ensuring that it does X in response to Y in a reasonable amount of time depends on more than just the code that you write.

Arduino boards also feature analog input capabilities, something that Raspberry Pi single-board computers lack. Additionally, there is a wide range of ready-made Arduino peripherals in the form of shields, allowing these boards to control motors, relays, displays, and more. If you’re using both together, you can offload the low-level tasks to the Arduino for interfacing with motors and the like, freeing up your Raspberry Pi “big picture” controller to perform more complex calculations.

This kind of setup also means you can put the Arduino closer to harm’s way instead of the Pi, which can be advantageous at times.

 

Arduino and Raspberry Pi Connection: Serial Interface & More Options

While we’ll deal with serial here, there are a number of other ways to interface boards together for a “Pi-duino” control package:

·   I2C

·   Node Red

·   Serial via Firmata

·   Wireless via Bluetooth or WiFi

·   Discreet IO signals wired through GPIO

While these other methods certainly have their place, serial seems to be a good combination of being standard and simple to implement. One must simply connect the two and write code to allow each board to send and receive signals and respond appropriately.

Here we’ll be using USB ports to simplify connections. However, it is also possible to wire GPIO together directly, potentially involving level shifting if using a 5V Arduino.

 

Serial Interface Basics: How to Connect Raspberry Pi and Arduino

Pi with Arduino R1 Image 2

Open the Arduino IDE and load Example > Communication > SerialCallResponse onto your board. Here we’ll be using an Arduino Uno, but other Arduino boards will work in a similar manner. Plug it in to your Raspberry Pi via USB. It’s also possible to load the Arduino IDE on a Raspberry Pi if you prefer to program it that way.

Open the Thonny Python IDE on Raspberry Pi (which uses Python 3) and enter the following code:

import serial

ser = serial.Serial(‘dev/tty/ACM0’, 9600)

while True:

            input = ser.read()

            print (input.decode(“utf-8”))

With this set up, you’ll get a repeating line that says “A” in the shell, corresponding to the Serial.print statement on line 62 of the Arduino program. Change this around if you like to ensure it’s getting a proper signal.

What’s happening here is that the RPi starts up a serial monitor at 9600 baud to match the Arduino’s signal. The while True statement makes the lines underneath it loop continuously, which reads and prints the serial input. It’s not the most interesting program every written, and the SerialCallResponse program can do much more, but it proves that the two devices are indeed communicating.

Note that if you get a “could not open port error” you may need to specify where the port is. To do this, in the terminal enter ls /dev/tty*, which will list a number of devices. With the device plugged in, toward the end of this list you’ll see something like /dev/ttyACM0 that is input on the “ser” line. This could also be slightly different, such as /dev/ttyACM1. Unplug the Arduino and this command again to see what drops off. Finally, plug it in, run ls /dev/tty* yet again to confirm the device, and enter that into your Python code.

 

Blink Arduino Via Raspberry Pi Serial Connection

We’ve proven that we can send data from the Arduino to the Raspberry Pi. What about getting the Pi to blink the onboard LED on the Arduino as a sort of serial blinky “hello world?” Yes, this is entirely possible.

On the Raspberry Pi/Thonny IDE side, enter the following:

import serial

import time

serial1 = serial.Serial(‘/dev/ttyACM0’, 9600)

while True:

            serial1.write(b’0’)

            time.sleep(1)

            serial1.write(b’9’)

            time.sleep(1)

On the Arduino IDE, enter the following and load it onto your board:

int inByte = '0';

void setup() {

  Serial.begin(9600);

  pinMode(LED_BUILTIN, OUTPUT);

}

void loop() {

  if (Serial.available() > 0) {

    inByte = (Serial.read());

    Serial.print("inByte "); Serial.println(inByte);

    if (inByte == '0') {

      digitalWrite(LED_BUILTIN, HIGH);

    }

    if (inByte == '9') {

      digitalWrite(LED_BUILTIN, LOW);

    }

  }

}

 

Connect the Arduino as before, noting that the “ACM0” portion may change as noted above, and run the Python script. This will cause the Raspberry Pi to send the ASCII character 0 or 9 to your Arduino board. In response, the Arduino’s if statements will either turn the built-in LED on (HIGH) if this serial input is 0, or turn it off (LOW) if it’s 9.

 

Conclusion: Basic Serial Interfacing for Pi & Arduino

This outlines only the very basics when it comes to serial interfacing, but should be an approachable intro for those that are new to the concept. Notably, you can also hook your Arduino up to the Arduino IDE serial monitor, and enter 0 and 9 manually to see it blink, proving that there’s nothing magic about what’s going on here.

Once you have this simple serial interface concept in your toolset, it’s easy enough to send a wide variety of characters to your Arduino to have it respond with actions. Just as with “solo” Arduino programming, you can build on this blinky hardware “hello world” to accomplish all sorts of amazing tasks!

perks 1

최신 뉴스

Sorry, your filter selection returned no results.

개인정보 보호정책이 업데이트되었습니다. 잠시 시간을 내어 변경사항을 검토하시기 바랍니다. 동의를 클릭하면 Arrow Electronics 개인정보 보호정책 및 이용 조건에 동의하는 것입니다.

당사의 웹사이트에서는 사용자의 경험 향상과 사이트 개선을 위해 사용자의 기기에 쿠키를 저장합니다. 당사에서 사용하는 쿠키 및 쿠키 비활성화 방법에 대해 자세히 알아보십시오. 쿠키와 추적 기술은 마케팅 목적으로 사용될 수 있습니다. '동의'를 클릭하면 기기에 쿠키를 배치하고 추적 기술을 사용하는 데 동의하는 것입니다. 쿠키 및 추적 기술을 해제하는 방법에 대한 자세한 내용과 지침을 알아보려면 아래의 '자세히 알아보기'를 클릭하십시오. 쿠키 및 추적 기술 수락은 사용자의 자발적 선택이지만, 웹사이트가 제대로 작동하지 않을 수 있으며 사용자와 관련이 적은 광고가 표시될 수 있습니다. Arrow는 사용자의 개인정보를 존중합니다. 여기에서 당사의 개인정보 보호정책을 읽을 수 있습니다.