Showing posts with label example code. Show all posts
Showing posts with label example code. Show all posts

Thursday, November 14, 2013

Hello World using C on Raspberry Pi

The post show how to use the editor nano to create a C's source code of "Hello World", then compile with gcc, and run it. All tools, nano and gcc, are come with Raspbian.

- Create a text file helloworld.c with nano, Ctrl-X to Exit and save the file.
$ nano helloworld.c

- Enter the code:
#include <stdio.h>

int main() {
    printf("Hello World\n");
    return 0;
}

- Compile the code and set output as helloworld
$ gcc -o helloworld helloworld.c

- Run the generated helloworld
$ ./helloworld

The words "Hello World" will be printed.

Wednesday, November 13, 2013

Communication between Raspberry Pi and Arduino via USB, using Python

Last post show how to coding in Arduino Due to send out data to USB. In this post, I will show the code of Python on Raspberry Pi side to receive data from USB, and print it on screen.

In this exercise, Raspberry Pi act as host to support power, and Arduino Due act as device. To connect Arduino board to Raspberry Pi, you need a USB cable. It will be the same cable you use to program Arduino board on PC.

Before we start coding, you need to know the actual device port assigned to Arduino, It should be ttyACMx, x may 0, 1, 2... Refer to the post "Arduino recognized as ttyACMx in Raspberry Pi" to check the port assignment.

In Python, we will use the library of pySerial. Check the post "Install pySerial on Ubuntu" in my another blog, the steps is same in Raspberry Pi.

Start idle, the IDE of Python, in Raspberry Pi. Enter the code in new Python module.

import serial
ser = serial.Serial('/dev/ttyACM0', 9600)

while 1:
    print(ser.readline())


Run Module. It should print the received words, "Hello Pi", on Python Shell window.
data output to Python Shell

Tuesday, November 12, 2013

Prepare Arduino to send data to Raspberry Pi via USB

It's a example to send data from Arduino to Raspberry Pi via USB. In this post, I will show a simple program in Arduino side (tested on Arduino Due), to send something out to USB, and also toggle the on-board LED. In the next post, I will show how to receive in Raspberry Pi Board, from USB, using Python.

The code in Arduino Due to send "Hello Pi" to USB and toggle LED repeatly every second.

int pinLED = 13;
boolean ledon;

void setup() {
  Serial.begin(9600);
  pinMode(pinLED, OUTPUT);
  ledon = true;
}
 
void loop() {
  Serial.print("Hello Pi\n");
  digitalWrite(pinLED, ledon = !ledon);
  delay(1000);
}


The code simple send "Hello Pi" to Serial port (USB) repeatly. After download to your Arduino board, you can use the build-in Tools > Serial Monitor to varify it.