Showing posts with label Arduino. Show all posts
Showing posts with label Arduino. Show all posts

Monday, July 12, 2021

RPi Pico (Arduino framework) + 128x160 ST7735 SPI TFT, using TFT_eSPI library.


With Arduino Mbed OS RP2040 Boards on Arduino IDE, this post show how to connect 128x160 ST7735 SPI TFT to Raspberry Pi Pico, and control with TFT_eSPI library in Arduino framework.


The TFT Display:

The TFT display used here is a 1.8 inch 128x160 ST7735 SPI TFT. The product page is here: 1.8inch SPI Module ST7735S SKU:MSP1803.



Connection between Raspberry Pi Pico and 128x160 ST7735 SPI TFT:

The connection follow the default setup in TFT_eSPI library, Setup60_RP2040_ILI9341.h.


ST7735 TFT			Pico
Pin#	name				
1	VCC	5V/3.3V		3V3	(pin 36)
2	GND	Ground		GND	(pin 38)
3	CS	chip select	20	(pin 26)
4	RESET	reset		19	(pin 25)
5	A0	reg/data	18	(pin 24)
6	SDA	SPI data	3	(pin 5)
7	SCK	SPI clock	2	(pin 4)
8	LED	Backlight	3V3
Prepare Library, TFT_eSPI:

The library used is Bodmer/TFT_eSPI, a Arduino and PlatformIO IDE compatible TFT library optimised for the Raspberry Pi Pico (RP2040), STM32, ESP8266 and ESP32 that supports different driver chips.

To install TFT_eSPI in Arduino IDE, simple open Library Manager, search and install TFT_eSPI by Bodmer.

Take a note on the Tips section in the TFT_eSPI Library page: 
 If you load a new copy of TFT_eSPI then it will overwrite your setups if they are kept within the TFT_eSPI folder. One way around this is to create a new folder in your Arduino library folder called "TFT_eSPI_Setups". You then place your custom setup.h files in there. After an upgrade simply edit the User_Setup_Select.h file to point to your custom setup file.


Here is how I practice it:
- create a new folder in your Arduino library folder called "TFT_eSPI_Setups".
- copy TFT_eSPI/User_Setups/Setup60_RP2040_ILI9341.h to new created "TFT_eSPI_Setups" folder, rename as Setup60_RP2040_ST7735.h.


- Edit Setup60_RP2040_ST7735.h for ST7735:
//                            USER DEFINED SETTINGS
//   Set driver type, fonts to be loaded, pins used and SPI control method etc
//
//   See the User_Setup_Select.h file if you wish to be able to define multiple
//   setups and then easily select which setup file is used by the compiler.
//
//   If this file is edited correctly then all the library example sketches should
//   run without the need to make any more changes for a particular hardware setup!
//   Note that some sketches are designed for a particular TFT pixel width/height


// ##################################################################################
//
// Section 1. Call up the right driver file and any options for it
//
// ##################################################################################

// Tell the library to use 8 bit parallel mode (otherwise SPI is assumed)
//#define TFT_PARALLEL_8_BIT

// Display type -  only define if RPi display
#define RPI_DISPLAY_TYPE // 20MHz maximum SPI

// Only define one driver, the other ones must be commented out
//#define ILI9341_DRIVER
#define ST7735_DRIVER      // Define additional parameters below for this display
//#define ILI9163_DRIVER     // Define additional parameters below for this display
//#define S6D02A1_DRIVER
//#define RPI_ILI9486_DRIVER // 20MHz maximum SPI
//#define HX8357D_DRIVER
//#define ILI9481_DRIVER
//#define ILI9486_DRIVER
//#define ILI9488_DRIVER     // WARNING: Do not connect ILI9488 display SDO to MISO if other devices share the SPI bus (TFT SDO does NOT tristate when CS is high)
//#define ST7789_DRIVER      // Full configuration option, define additional parameters below for this display
//#define ST7789_2_DRIVER    // Minimal configuration option, define additional parameters below for this display
//#define R61581_DRIVER
//#define RM68140_DRIVER
//#define ST7796_DRIVER
//#define SSD1963_480_DRIVER
//#define SSD1963_800_DRIVER
//#define SSD1963_800ALT_DRIVER
//#define ILI9225_DRIVER

// Some displays support SPI reads via the MISO pin, other displays have a single
// bi-directional SDA pin and the library will try to read this via the MOSI line.
// To use the SDA line for reading data from the TFT uncomment the following line:

// #define TFT_SDA_READ      // This option is for ESP32 ONLY, tested with ST7789 display only

// For ST7735, ST7789 and ILI9341 ONLY, define the colour order IF the blue and red are swapped on your display
// Try ONE option at a time to find the correct colour order for your display

#define TFT_RGB_ORDER TFT_RGB  // Colour order Red-Green-Blue
//  #define TFT_RGB_ORDER TFT_BGR  // Colour order Blue-Green-Red

// For ST7789, ST7735 and ILI9163 ONLY, define the pixel width and height in portrait orientation
// #define TFT_WIDTH  80
#define TFT_WIDTH  128
// #define TFT_WIDTH  240 // ST7789 240 x 240 and 240 x 320
#define TFT_HEIGHT 160
// #define TFT_HEIGHT 128
// #define TFT_HEIGHT 240 // ST7789 240 x 240
// #define TFT_HEIGHT 320 // ST7789 240 x 320

// For ST7735 ONLY, define the type of display, originally this was based on the
// colour of the tab on the screen protector film but this is not always true, so try
// out the different options below if the screen does not display graphics correctly,
// e.g. colours wrong, mirror images, or tray pixels at the edges.
// Comment out ALL BUT ONE of these options for a ST7735 display driver, save this
// this User_Setup file, then rebuild and upload the sketch to the board again:

//#define ST7735_INITB
#define ST7735_GREENTAB
// #define ST7735_GREENTAB2
// #define ST7735_GREENTAB3
// #define ST7735_GREENTAB128    // For 128 x 128 display
// #define ST7735_GREENTAB160x80 // For 160 x 80 display (BGR, inverted, 26 offset)
// #define ST7735_REDTAB
// #define ST7735_BLACKTAB
// #define ST7735_REDTAB160x80   // For 160 x 80 display with 24 pixel offset

// If colours are inverted (white shows as black) then uncomment one of the next
// 2 lines try both options, one of the options should correct the inversion.

// #define TFT_INVERSION_ON
// #define TFT_INVERSION_OFF


// ##################################################################################
//
// Section 2. Define the pins that are used to interface with the display here
//
// ##################################################################################

// If a backlight control signal is available then define the TFT_BL pin in Section 2
// below. The backlight will be turned ON when tft.begin() is called, but the library
// needs to know if the LEDs are ON with the pin HIGH or LOW. If the LEDs are to be
// driven with a PWM signal or turned OFF/ON then this must be handled by the user
// sketch. e.g. with digitalWrite(TFT_BL, LOW);

// #define TFT_BL   32            // LED back-light control pin
// #define TFT_BACKLIGHT_ON HIGH  // Level to turn ON back-light (HIGH or LOW)

// We must use hardware SPI, a minimum of 3 GPIO pins is needed.
// Typical setup for the RP2040 is :
//
// Display SDO/MISO  to RP2040 pin D0 (or leave disconnected if not reading TFT)
// Display LED       to RP2040 pin 3V3 or 5V
// Display SCK       to RP2040 pin D2
// Display SDI/MOSI  to RP2040 pin D3
// Display DC (RS/AO)to RP2040 pin D18 (can use another pin if desired)
// Display RESET     to RP2040 pin D19 (can use another pin if desired)
// Display CS        to RP2040 pin D20 (can use another pin if desired, or GND, see below)
// Display GND       to RP2040 pin GND (0V)
// Display VCC       to RP2040 5V or 3.3V (5v if display has a 5V to 3.3V regulator fitted)
//
// The DC (Data Command) pin may be labelled AO or RS (Register Select)
//
// With some displays such as the ILI9341 the TFT CS pin can be connected to GND if no more
// SPI devices (e.g. an SD Card) are connected, in this case comment out the #define TFT_CS
// line below so it is NOT defined. Other displays such at the ST7735 require the TFT CS pin
// to be toggled during setup, so in these cases the TFT_CS line must be defined and connected.

// For the Pico use these #define lines
#define TFT_MISO  0
#define TFT_MOSI  3
#define TFT_SCLK  2
#define TFT_CS   20  // Chip select control pin
#define TFT_DC   18  // Data Command control pin
#define TFT_RST  19  // Reset pin (could connect to Arduino RESET pin)
//#define TFT_BL     // LED back-light

//#define TOUCH_CS 21     // Chip select pin (T_CS) of touch screen

// ##################################################################################
//
// Section 3. Define the fonts that are to be used here
//
// ##################################################################################

// Comment out the #defines below with // to stop that font being loaded
// The ESP8366 and ESP32 have plenty of memory so commenting out fonts is not
// normally necessary. If all fonts are loaded the extra FLASH space required is
// about 17Kbytes. To save FLASH space only enable the fonts you need!

#define LOAD_GLCD   // Font 1. Original Adafruit 8 pixel font needs ~1820 bytes in FLASH
#define LOAD_FONT2  // Font 2. Small 16 pixel high font, needs ~3534 bytes in FLASH, 96 characters
#define LOAD_FONT4  // Font 4. Medium 26 pixel high font, needs ~5848 bytes in FLASH, 96 characters
#define LOAD_FONT6  // Font 6. Large 48 pixel font, needs ~2666 bytes in FLASH, only characters 1234567890:-.apm
#define LOAD_FONT7  // Font 7. 7 segment 48 pixel font, needs ~2438 bytes in FLASH, only characters 1234567890:-.
#define LOAD_FONT8  // Font 8. Large 75 pixel font needs ~3256 bytes in FLASH, only characters 1234567890:-.
//#define LOAD_FONT8N // Font 8. Alternative to Font 8 above, slightly narrower, so 3 digits fit a 160 pixel TFT
#define LOAD_GFXFF  // FreeFonts. Include access to the 48 Adafruit_GFX free fonts FF1 to FF48 and custom fonts

// Comment out the #define below to stop the SPIFFS filing system and smooth font code being loaded
// this will save ~20kbytes of FLASH
#define SMOOTH_FONT


// ##################################################################################
//
// Section 4. Other options
//
// ##################################################################################

// Define the SPI clock frequency, this affects the graphics rendering speed. Too
// fast and the TFT driver will not keep up and display corruption appears.
// With an ILI9341 display 40MHz works OK, 80MHz sometimes fails
// With a ST7735 display more than 27MHz may not work (spurious pixels and lines)
// With an ILI9163 display 27 MHz works OK.

// #define SPI_FREQUENCY   1000000
// #define SPI_FREQUENCY   5000000
// #define SPI_FREQUENCY  10000000
// #define SPI_FREQUENCY  20000000
// #define SPI_FREQUENCY  32000000
 #define SPI_FREQUENCY  70000000

// Optional reduced SPI frequency for reading TFT
#define SPI_READ_FREQUENCY  20000000

// The XPT2046 requires a lower SPI clock rate of 2.5MHz so we define that here:
#define SPI_TOUCH_FREQUENCY  2500000


- Edit the User_Setup_Select.h file to point to the custom setup file, Setup60_RP2040_ST7735.h.


//#include <User_Setup.h>           // Default setup is root library folder
#include <../TFT_eSPI_Setups/Setup60_RP2040_ST7735.h>
After then, you can try examples installed with TFT_eSPI, or your own exercises.

My exercise: Pico_ST7735_SPI_128x160_.ino
/*
 * Test 128x160 ST7735 SPI TFT Display,
 * using TFT_eSPI library
 */

#include <TFT_eSPI.h>
#include <SPI.h>

TFT_eSPI tft = TFT_eSPI(); 

void setup() {
    tft.init();
    tft.setRotation(0);
    tft.setTextSize(1);
}

void loop() {
    tft.setRotation(0);
    tft.fillScreen(TFT_BLACK);

    tft.drawPixel(10, 10, TFT_WHITE);
    tft.drawPixel(10, 150, TFT_WHITE);
    tft.drawPixel(118, 150, TFT_WHITE);
    tft.drawPixel(118, 10, TFT_WHITE);
    delay(1000);
    
    int margin = 10;
    for(int x=margin; x<=TFT_WIDTH-margin; x++){
       tft.drawPixel(x, margin, TFT_WHITE);
       delay(10);
    }
    for(int y=margin; y<=TFT_HEIGHT-margin; y++){
       tft.drawPixel(TFT_WIDTH-margin, y, TFT_WHITE);
       delay(10);
    }
    for(int x=TFT_WIDTH-margin; x>=margin; x--){
       tft.drawPixel(x, TFT_HEIGHT-margin, TFT_WHITE);
       delay(10);
    }
    for(int y=TFT_HEIGHT-margin; y>=margin; y--){
       tft.drawPixel(margin, y, TFT_WHITE);
       delay(10);
    }
    delay(500);
    
    tft.setRotation(1);
    //tft.fillScreen(TFT_BLACK);
    tft.setTextColor(TFT_RED, TFT_BLACK);
    tft.drawString("RED", 10, 10, 4);
    delay(1000);

    tft.setRotation(2);
    //tft.fillScreen(TFT_BLACK);
    tft.setTextColor(TFT_GREEN, TFT_BLACK);
    tft.drawString("GREEN", 10, 10, 4);
    delay(1000);

    tft.setRotation(3);
    //tft.fillScreen(TFT_BLACK);
    tft.setTextColor(TFT_BLUE, TFT_BLACK);
    tft.drawString("BLUE", 10, 10, 4);
    delay(1000);

    
    
    delay(3000);
}


Tuesday, February 19, 2019

Install Arduino IDE on Raspberry Pi/Raspbian Stretch

This video show how to Install Arduino IDE 1.8.8 on Raspberry Pi 3 B+/Raspbian Stretch. Such that you can program Arduino board on Raspberry Pi.


Setup under test:
Board - Raspberry Pi 3 B+
OS - Raspbian Stretch with desktop and recommended software (Version:November 2018, Release date:2018-11-13)
IDE: Arduino IDE 1.8.8 (Linux ARM)
Arduino Board: Mega 2560

In order to capture the screen action, I remote control the Raspberry Pi from Windows 10 via VNC viewer.

The steps is very straightforward:

- Visit Arduino Download page, download Arduino IDE of Linux ARM.

- After download completed, extract the downloaded file.

- Run the install script:
$ sudo ./install.sh

- After finished, you can run the Arduino IDE in Raspbian desktop Menu -> Programming -> Arduino IDE.

In my case the following error reported when run install.sh:
touch: cannot touch '/root/.local/share/applications/mimeapps.list': No such file or directory
/usr/bin/xdg-mime: 803: /usr/bin/xdg-mime: cannot create /root/.local/share/applications/mimeapps.list.new: Directory nonexistent

It may be caused by mis-located of the file mimeapps.list. Actually the install.sh only add the desktop shortcut, menu item and file associations for Arduino IDE. This error should not affect the functionality. Alternatively, you can run the IDE by switch to the extracted directory, and run the arduino directly.


Add Arduino core for ESP8266 WiFi chip to Arduino IDE:

Arduino core for ESP8266 WiFi chip brings support for ESP8266 chip to the Arduino environment. It lets you write sketches using familiar Arduino functions and libraries, and run them directly on ESP8266, no external microcontroller required.

ESP8266 Arduino core comes with libraries to communicate over WiFi using TCP and UDP, set up HTTP, mDNS, SSDP, and DNS servers, do OTA updates, use a file system in flash memory, work with SD cards, servos, SPI and I2C peripherals.

Once Arduino IDE installed, you can follow the same steps in my old post to "Add Arduino core for ESP8266 to Arduino IDE (run on Raspberry Pi/Raspbian Jessie with PIXEL)".


reference:
Arduino core for ESP8266 WiFi chip project page: https://github.com/esp8266/arduino
Additional Board Manager URLs:
http://arduino.esp8266.com/stable/package_esp8266com_index.json


Arduino core for ESP32 WiFi chip is another similar project to bring support of ESP32 to Arduino IDE. It can be installed to Arduino IDE by following the same step on normal PC. But, I tried to install it to Arduino IDE on Raspberry Pi, it fail due to "Tool xtensa-esp32-elf-gcc is not available for your operating system"!


reference:
Arduino core for ESP32 WiFi chip project page: https://github.com/espressif/arduino-esp32
Additional Board Manager URLs:
https://dl.espressif.com/dl/package_esp32_index.json




Wednesday, July 20, 2016

Check the Vendor ID and Product ID of attached USB devices in Raspberry Pi/Raspbian

To check the Vendor ID and Product ID of attached USB devices in Raspberry Pi/Raspbian Jessie (and also other Linux), we can use the commands dmesg and lsusb.


This video show how to do it in case Arduino Uno is connected to Raspberry Pi 2/Raspbian jessie. Also show the device name, ttyACM0.



Tuesday, April 12, 2016

Install and run Arduino IDE on Raspberry Pi/Raspbian Jessie


Now Arduino IDE for Linux ARM Preview is provided in Arduino - Software -  HOURLY BUILDS. You can install on Raspberry Pi.

This video show how to install Arduino IDE for Linux ARM (1.6.9 currently) on Raspberry Pi 3/Raspbian Jessie.



Insert Arduino UNO to Raspberry Pi, run and program UNO. No more setting needed:)



remark:
Intel Curie Boards for Arduino/Genuino 101 is not supported currently!




Updated@2017-06-14:
~ Re-tried again on Raspberry Pi 3 with Raspbian Jessie with PIXEL (2017-04-10 release).

Updated@2019-02-19:
Please check the updated post: Install Arduino IDE 1.8.8 on Raspberry Pi/Raspbian Stretch release 2018-11-13.


Wednesday, January 7, 2015

Raspberry Pi + Arduino i2c communication, Wire.write() multi-byte from Arduino requestEvent

Last exercise show Raspberry Pi master + Arduino slave i2c communication, write block of data from Pi to Arduino Uno, and read a single byte from Arduino Uno. In this post show how to echo multi-byte from Arduino in requestEvent, by calling Wire.write().


In Raspberry Pi, i2c master, it send block of data to Arduino Uno, i2c slave, by calling bus.write_i2c_block_data(), to trigger receiveEvent in Arduino.
then call number of bus.read_byte() to trigger requestEvent in Arduino. The first byte echo from Arduino is the number of byte to sent, then echo the data in reversed sequency.

i2c_uno.py run on Raspberry Pi
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
import os

# display system info
print os.uname()

bus = smbus.SMBus(1)

# I2C address of Arduino Slave
i2c_address = 0x07
i2c_cmd_write = 0x01
i2c_cmd_read = 0x02

def ConvertStringToBytes(src):
    converted = []
    for b in src:
        converted.append(ord(b))
    return converted

# send welcome message at start-up
bytesToSend = ConvertStringToBytes("Hello Uno")
bus.write_i2c_block_data(i2c_address, i2c_cmd_write, bytesToSend)

# loop to send message
exit = False
while not exit:
    r = raw_input('Enter something, "q" to quit"')
    print(r)
    
    bytesToSend = ConvertStringToBytes(r)
    bus.write_i2c_block_data(i2c_address, i2c_cmd_write, bytesToSend)
    
    # delay 0.1 second
    # with delay will cause error of:
    # IOError: [Error 5] Input/output error
    time.sleep(0.1)
    
    data = ""
    numOfByte = bus.read_byte(i2c_address)
    print numOfByte
    
    for i in range(0, numOfByte):
        data += chr(bus.read_byte(i2c_address));
    print data
    
    if r=='q':
        exit=True


i2c_slave_12x6LCD.ino, run on Arduino Uno
/*
 LCD part reference to:
 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

#include <LiquidCrystal.h>
#include <Wire.h>

#define LED_PIN 13
boolean ledon = HIGH;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

byte slave_address = 7;
int echonum = 0;

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print startup message to the LCD.
  lcd.print("Arduino Uno");
  
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  
  Wire.begin(slave_address);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);

}

void loop() {

}

char echo[32];
int index = 0;

void requestEvent(){
  toggleLED();
  if(index==0){
    Wire.write(echonum);
  }else{
    Wire.write(echo[echonum-1-(index-1)]);
  }
  index++;
}

void receiveEvent(int howMany) {
  
  lcd.clear();
  
  int numOfBytes = Wire.available();
  //display number of bytes and cmd received, as bytes
  lcd.setCursor(0, 0);
  lcd.print("len:");
  lcd.print(numOfBytes);
  lcd.print(" ");
  
  byte b = Wire.read();  //cmd
  lcd.print("cmd:");
  lcd.print(b);
  lcd.print(" ");
  
  index = 0;

  //display message received, as char
  lcd.setCursor(0, 1);
  for(int i=0; i<numOfBytes-1; i++){
    char data = Wire.read();
    lcd.print(data);
    
    echo[i] = data;
  }
  
  echonum = numOfBytes-1;
}

void toggleLED(){
  ledon = !ledon;
  if(ledon){
    digitalWrite(LED_PIN, HIGH);
  }else{
    digitalWrite(LED_PIN, LOW);
  }
}

Thursday, December 25, 2014

Raspberry Pi + Arduino i2c communication, write block and read byte

This example extends work on last example "Raspberry Pi send block of data to Arduino using I2C"; the Raspberry Pi read byte from Arduino Uno after block sent, and the Arduino always send back length of data received.


i2c_slave_12x6LCD.ino sketch run on Arduino Uno.
/*
 LCD part reference to:
 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

#include <LiquidCrystal.h>
#include <Wire.h>

#define LED_PIN 13
boolean ledon = HIGH;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

byte slave_address = 7;
int echonum = 0;

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print startup message to the LCD.
  lcd.print("Arduino Uno");
  
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  
  Wire.begin(slave_address);
  Wire.onReceive(receiveEvent);
  Wire.onRequest(requestEvent);

}

void loop() {

}

void requestEvent(){
  Wire.write(echonum);
  toggleLED();
}


void receiveEvent(int howMany) {
  lcd.clear();
  
  int numOfBytes = Wire.available();
  //display number of bytes and cmd received, as bytes
  lcd.setCursor(0, 0);
  lcd.print("len:");
  lcd.print(numOfBytes);
  lcd.print(" ");
  
  byte b = Wire.read();  //cmd
  lcd.print("cmd:");
  lcd.print(b);
  lcd.print(" ");

  //display message received, as char
  lcd.setCursor(0, 1);
  for(int i=0; i<numOfBytes-1; i++){
    char data = Wire.read();
    lcd.print(data);
  }
  
  echonum = numOfBytes-1;
}

void toggleLED(){
  ledon = !ledon;
  if(ledon){
    digitalWrite(LED_PIN, HIGH);
  }else{
    digitalWrite(LED_PIN, LOW);
  }
}

i2c_uno.py, python program run on Raspberry Pi.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
import os

# display system info
print os.uname()

bus = smbus.SMBus(1)

# I2C address of Arduino Slave
i2c_address = 0x07
i2c_cmd = 0x01

def ConvertStringToBytes(src):
    converted = []
    for b in src:
        converted.append(ord(b))
    return converted

# send welcome message at start-up
bytesToSend = ConvertStringToBytes("Hello Uno")
bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)

# loop to send message
exit = False
while not exit:
    r = raw_input('Enter something, "q" to quit"')
    print(r)
    
    bytesToSend = ConvertStringToBytes(r)
    bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)
    
    # delay 0.1 second
    # with delay will cause error of:
    # IOError: [Error 5] Input/output error
    time.sleep(0.1)
    number = bus.read_byte(i2c_address)
    print('echo: ' + str(number))
    
    if r=='q':
        exit=True


Next:
Wire.write() multi-byte from Arduino requestEvent


WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.

Sunday, December 14, 2014

Raspberry Pi send block of data to Arduino using I2C

In this example, Raspberry Pi programmed using Python with smbus library, act as I2C master, ask user enter something as string, then send to Arduino Uno in blocks of data. In Arduino side, act as I2C slave, interpret received data in number of bytes, command, and body of data, to display on 16x2 LCD display.


Prepare on Raspberry Pi for I2C communication, refer to previous post "Communication between Raspberry Pi and Arduino via I2C, using Python".

Connection between Raspberry Pi, Arduino Uno and 16x2 LCD:


i2c_slave_12x6LCD.ino sketch run on Arduino Uno.
/*
 LCD part reference to:
 http://www.arduino.cc/en/Tutorial/LiquidCrystal
 */

#include <LiquidCrystal.h>
#include <Wire.h>

#define LED_PIN 13
boolean ledon = HIGH;
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(12, 11, 5, 4, 3, 2);

byte slave_address = 7;

void setup() {
  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  // Print startup message to the LCD.
  lcd.print("Arduino Uno");
  
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, HIGH);
  
  Wire.begin(slave_address);
  Wire.onReceive(receiveEvent);
}

void loop() {

}

void receiveEvent(int howMany) {
  lcd.clear();
  
  int numOfBytes = Wire.available();
  //display number of bytes and cmd received, as bytes
  lcd.setCursor(0, 0);
  lcd.print("len:");
  lcd.print(numOfBytes);
  lcd.print(" ");
  
  byte b = Wire.read();  //cmd
  lcd.print("cmd:");
  lcd.print(b);
  lcd.print(" ");

  //display message received, as char
  lcd.setCursor(0, 1);
  for(int i=0; i<numOfBytes-1; i++){
    char data = Wire.read();
    lcd.print(data);
  }
  
  toggleLED();
}

void toggleLED(){
  ledon = !ledon;
  if(ledon){
    digitalWrite(LED_PIN, HIGH);
  }else{
    digitalWrite(LED_PIN, LOW);
  }
}

i2c_uno.py, python program run on Raspberry Pi.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
import os

# display system info
print os.uname()

bus = smbus.SMBus(1)

# I2C address of Arduino Slave
i2c_address = 0x07
i2c_cmd = 0x01

def ConvertStringToBytes(src):
    converted = []
    for b in src:
        converted.append(ord(b))
    return converted

# send welcome message at start-up
bytesToSend = ConvertStringToBytes("Hello Uno")
bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)

# loop to send message
exit = False
while not exit:
    r = raw_input('Enter something, "q" to quit"')
    print(r)
    
    bytesToSend = ConvertStringToBytes(r)
    bus.write_i2c_block_data(i2c_address, i2c_cmd, bytesToSend)
    
    if r=='q':
        exit=True


next:
- Raspberry Pi + Arduino i2c communication, write block and read byte


WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.

Saturday, December 13, 2014

Communication between Raspberry Pi and Arduino via I2C, using Python.

This exercise implement communiation between Raspberry Pi and Arduino using I2C. Here Raspberry Pi, programmed with Python, act as I2C host and Arduino Uno act as slave.

Download the sketch (I2CSlave.ino) to Arduino Uno. It receive I2C data, turn ON LED if 0x00 received, turn OFF LED if 0x01 received.
#include <Wire.h>

#define LED_PIN 13

byte slave_address = 7;
byte CMD_ON = 0x00;
byte CMD_OFF = 0x01;

void setup() {
  // Start I2C Bus as Slave
  Wire.begin(slave_address);
  Wire.onReceive(receiveEvent);
  
  pinMode(LED_PIN, OUTPUT);
  digitalWrite(LED_PIN, LOW);  

}

void loop() {

}

void receiveEvent(int howMany) {
  byte cmd = Wire.read();
  if (cmd == CMD_ON){
    digitalWrite(LED_PIN, HIGH);
  }else if(cmd == CMD_OFF){
    digitalWrite(LED_PIN, LOW);
  }
}

Prepare on Raspberry Pi, refer to last post "Enable I2C and install tools on Raspberry Pi".

Connection between Raspberry Pi and Arduino.


Then you can varify the I2C connection using i2cdetect command. Refer to below video, the I2C device with address 07 match with slave_address = 7 defined in Arduino sketch.


On Raspberry Pi, run the command to install smbus for Python, in order to use I2C bus.
sudo apt-get install python-smbus


Now create a Python program (i2c_uno.py), act as I2C master to write series of data to Arduino Uno, to turn ON/OFF the LED on Arduino Uno. Where address = 0x07 have to match with the slave_address in Arduino side.
#have to run 'sudo apt-get install python-smbus'
#in Terminal to install smbus
import smbus
import time
bus = smbus.SMBus(1)

# I2C address of Arduino Slave
address = 0x07

LEDst = [0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x01, 0x01]
for s in LEDst:
    bus.write_byte(address, s)
    time.sleep(1)

Finally, run with command:
$ sudo python i2c_uno.py



Next:
Raspberry Pi send block of data to Arduino using I2C
Write block and read byte
Wire.write() multi-byte from Arduino requestEvent


WARNING:
Somebody advise to use I2C Logic Level Converter between Raspberry Pi and Arduino, otherwise the RPi's ports will be burnt! So, please think about it and take your own risk.

Wednesday, September 3, 2014

Java serial communication with Arduino Uno with jSSC, on Raspberry Pi

jSSC (Java Simple Serial Connector) - library for working with serial ports from Java. jSSC support Win32(Win98-Win8), Win64, Linux(x86, x86-64, ARM), Solaris(x86, x86-64), Mac OS X 10.5 and higher(x86, x86-64, PPC, PPC64).

This post show a Java program run on Raspberry Pi, using jSSC library, to send message to USB connected Arduino Uno board.


The development platform is a PC running Ubuntu with Netbeans 8, and deploy the program to Raspberry Pi remotely.

- To add jSSC library to our Netbeans Java project, read the post "Install and test java-simple-serial-connector with Arduino".

- The program code is almost same as the code on the page. With 3 seconds delay after serialPort.openPort(), to wait Automatic (Software) Reset on Arduino Uno board.
package java_jssc_uno;

import java.util.logging.Level;
import java.util.logging.Logger;
import jssc.SerialPort;
import jssc.SerialPortException;

public class Java_jSSC_Uno {

    public static void main(String[] args) {
        SerialPort serialPort = new SerialPort("/dev/ttyACM0");
        try {
            System.out.println("Port opened: " + serialPort.openPort());

            try {
                Thread.sleep(3000);
            } catch (InterruptedException ex) {
                Logger.getLogger(Java_jSSC_Uno.class.getName()).log(Level.SEVERE, null, ex);
            }
            
            System.out.println("Params setted: " + serialPort.setParams(9600, 8, 1, 0));
            System.out.println("\"Hello World!!!\" successfully writen to port: " + serialPort.writeBytes("Java_jSSC_Uno".getBytes()));
            System.out.println("Port closed: " + serialPort.closePort());
        }
        catch (SerialPortException ex){
            System.out.println(ex);
        }
    }
    
}

- To deploy to Raspberry Pi remotely with Netbeans 8, refer to the post "Set up Java SE 8 Remote Platform on Netbeans 8 for Raspberry Pi".


For the sketch (and extra info) on Arduino Uno, read the post in my Arduino blog.


Node.js Chat Server on RPi, send msg to Arduino Uno, display on LCD Module

This example combine the last post of "Node.js Chat application using socket.io, run on Raspberry Pi", and "Node.js send string to Arduino Uno" in my another blog for Arduino. To create a Chat server, and send the received messages to USB connected Arduino Uno board, then display on the equipped 2x16 LCD Module on Arduino.


In order to use serialport in Node.js to send message to serial port, enter the command on Raspberry Pi command line to install serialport.
$ npm install serialport

Modify index.js in last post to add handles for serialport.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

var SerialPort = require("serialport").SerialPort
var serialPort = new SerialPort('/dev/ttyACM0', 
    {   baudrate: 9600
    });
    
serialPort.on("open", function () {
    console.log('open');
});

app.get('/', function(req, res){
  res.sendfile('index.html');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
    
    serialPort.write(msg, function(err, results) {
            console.log('err ' + err);
            console.log('results ' + results);
        });
    
  });
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

For the sketch on Arduino Uno, refer to the post "Read from Arduino Serial port, and write to 2x16 LCD".

Tuesday, August 26, 2014

Arduino IDE on Raspberry Pi

Updated@2019-02-19:
Please check the updated post: Install Arduino IDE 1.8.8 on Raspberry Pi/Raspbian Stretch release 2018-11-13.

To install Arduino IDE on Raspberry Pi, enter the command:

$ sudo apt-get install arduino

After installed, run it with command:

$ arduino

This video show how to, and also show how Raspberry Pi connected Arduino Uno run.



Cross post with Arduino-er.

Thursday, March 20, 2014

Node.js+socket.io+serialport = web app to control Pi connected Arduino

This is a example to implement a web app with Node.js running on Raspberry Pi, to receive command from client, and control connected Arduino Esplora's LED. All clients share a common hardware: when a client toggle the LED, all clients will be updated accordingly.


This example should be run on any other Node.js supported platform, with changing SerialPort name. The tablet is used to log-in Raspberry Pi to start the app, for demonstrate only, not a part of the example.

You have to install socket.io and serialport modules for Node.js:
$ npm install socket.io
$ npm install serialport

app.js
var app = require('http').createServer(handler), 
    io = require('socket.io').listen(app), 
    fs = require('fs'),
    os = require('os'),
    sp = require("serialport");
  
//init for SerialPort connected to Arduino
var SerialPort = sp.SerialPort
var serialPort = new SerialPort('/dev/ttyACM0', 
    {   baudrate: 9600,
        dataBits: 8,
        parity: 'none',
        stopBits: 1,
        flowControl: false
    });
    
serialPort.on("open", function () {
    console.log('serialPort open');
    serialPort.write("LEDOFF\n");
});
    
//Display my IP
var networkInterfaces=os.networkInterfaces();

for (var interface in networkInterfaces) {
    
    networkInterfaces[interface].forEach(
        function(details){
            
            if (details.family=='IPv4' 
                && details.internal==false) {
                    console.log(interface, details.address);  
        }
    });
}

//All clients have a common status
var commonStatus = 'ON';

app.listen(8080);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
    if (err) {
      res.writeHead(500);
      return res.end('Error loading index.html');
    }

    res.writeHead(200);
    res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
    
    //Send client with his socket id
    socket.emit('your id', 
        { id: socket.id});
    
    //Info all clients a new client caaonnected
    io.sockets.emit('on connection', 
        { client: socket.id,
          clientCount: io.sockets.clients().length,
        });
        
    //Set the current common status to the new client
    socket.emit('ack button status', { status: commonStatus });
    
    socket.on('button update event', function (data) {
        console.log(data.status);
        
        //acknowledge with inverted status, 
        //to toggle button text in client
        if(data.status == 'ON'){
            console.log("ON->OFF");
            commonStatus = 'OFF';
            serialPort.write("LEDON\n");
        }else{
            console.log("OFF->ON");
            commonStatus = 'ON';
            serialPort.write("LEDOFF\n");
        }
        io.sockets.emit('ack button status', 
            { status: commonStatus,
              by: socket.id
            });
    });
    
    //Info all clients if this client disconnect
    socket.on('disconnect', function () {
        io.sockets.emit('on disconnect', 
            { client: socket.id,
              clientCount: io.sockets.clients().length-1,
            });
    });
});

index.html
<html>
<meta name="viewport" content="width=device-width, user-scalable=no">
<head></head>
<body>
<hi>Test Node.js with socket.io</hi>
<form action="">
<input type="button" id="buttonToggle" value="ON" style="color:blue"
       onclick="toggle(this);">
</form>
<script src="/https/helloraspberrypi.blogspot.com/socket.io/socket.io.js"></script>
<script>
var socket = io.connect(document.location.href);
var myId;

socket.on('on connection', function (data) {
    console.log("on connection: " + data.client);
    console.log("Number of client connected: " + data.clientCount);
});

socket.on('on disconnect',function(data) {
    console.log("on disconnect: " + data.client);
    console.log("Number of client connected: " + data.clientCount);
});

socket.on('your id',function(data) {
    console.log("your id: " + data.id);
    myId = data.id;
});

socket.on('ack button status', function (data) {
    console.log("status: " + data.status);
    
    if(myId==data.by){
        console.log("by YOU");
    }else{
        console.log("by: " + data.by);
    }
    
    if(data.status =='ON'){
        document.getElementById("buttonToggle").value="ON";
    }else{
        document.getElementById("buttonToggle").value="OFF";
    }
});

function toggle(button)
{
 if(document.getElementById("buttonToggle").value=="OFF"){
  socket.emit('button update event', { status: 'OFF' });
 }
 else if(document.getElementById("buttonToggle").value=="ON"){
  socket.emit('button update event', { status: 'ON' });
 }
}
</script>

</body>
</html>

Arduino code
#include <Esplora.h>
#include <TFT.h>
#include <SPI.h>

int MAX_CMD_LENGTH = 10;
char cmd[10];
int cmdIndex;
char incomingByte;

void setup() {
  
    EsploraTFT.begin();  
    EsploraTFT.background(0,0,0);
    EsploraTFT.stroke(255,255,255);  //preset stroke color
     
    //Setup Serial Port with baud rate of 9600
    Serial.begin(9600);
    
    //indicate start
    Esplora.writeRGB(255, 255, 255);
    delay(250);
    Esplora.writeRGB(0, 0, 0);
    
    cmdIndex = 0;
    
}
 
void loop() {
    
    if (incomingByte=Serial.available()>0) {
      
      char byteIn = Serial.read();
      cmd[cmdIndex] = byteIn;
      
      if(byteIn=='\n'){
        //command finished
        cmd[cmdIndex] = '\0';
        Serial.println(cmd);
        cmdIndex = 0;
        
        if(strcmp(cmd, "LEDON")  == 0){
          Serial.println("Command received: LEDON");
          Esplora.writeRGB(255, 255, 255);
        }else if (strcmp(cmd, "LEDOFF")  == 0) {
          Serial.println("Command received: LEDOFF");
          Esplora.writeRGB(0, 0, 0);
        }else{
          Serial.println("Command received: unknown!");
        }
        
      }else{
        if(cmdIndex++ >= MAX_CMD_LENGTH){
          cmdIndex = 0;
        }
      }
    }
    
}

Cross post with Arduino-er

Next: Bi-directional control between Raspberry Pi + Node.js + Arduino

Thursday, December 12, 2013

Programming an Arduino from Raspberry Pi

Updated@2019-02-19:
Please check the updated post: Install Arduino IDE 1.8.8 on Raspberry Pi/Raspbian Stretch release 2018-11-13.

Learn how to install the Arduino IDE on your Raspberry Pi so that you can write and upload programs onto an Arduino.



Thursday, December 5, 2013

Install Arduino IDE on Raspberry Pi

Updated@2019-02-19:
Please check the updated post: Install Arduino IDE 1.8.8 on Raspberry Pi/Raspbian Stretch release 2018-11-13.

To install Arduino IDE running on Raspberry Pi, enter the command:
$ sudo apt-get install arduino


After installed, you can start Arduino IDE from Start menu of Raspberry Pi desktop > Electronics > Arduino IDE.



Or enter the command in Terminal:
$ arduino

The install version is 1.0.1.

Cross post with Arduino-er.

Updated@2013-12-13: more details to Learn how to install the Arduino IDE on your Raspberry Pi so that you can write and upload programs onto an Arduino.

Updated@2016-01-07:
There is a thread on the Pi forum discussing installation of later versions of the Arduino IDE: Arduino_IDE-1.6.7/github on the Raspberry Pi


Friday, November 15, 2013

Send and receive from Raspberry Pi to and from Arduino, with Python

This example show how to write a simple Python program on Raspberry Pi to get keyboard input and send to Arduino via USB. In Arduino, send back the received chars to Raspberry Pi, then print on screen in Pi side.



In this example, Raspberry Pi act as host and Arduino Due act as device, and connect with USB on Programming USB Port.

Python code in Raspberry Pi:
import serial
ser = serial.Serial('/dev/ttyACM1', 9600)

name_out = raw_input("Who are you?\n")
ser.write(name_out + "\n")
name_return = ser.readline()
print(name_return)

Code in Arduino side:
int pinLED = 13;
boolean ledon;

void setup() {
  Serial.begin(9600);
  pinMode(pinLED, OUTPUT);
  ledon = true;
  digitalWrite(pinLED, ledon = !ledon);
}
 
void loop() {
  if(Serial.available() > 0){
    Serial.print("Hello ");
    
    while(Serial.available()>0){
      char charIn = (char)Serial.read();
      Serial.print(charIn);
      if (charIn == '\n')
        break;
    }
    
    digitalWrite(pinLED, ledon = !ledon);
  }
}

Cross post with my another blog: Arduino-er

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.

Arduino recognized as ttyACMx in Raspberry Pi

Arduino devices (after UNO) connected to Raspberry Pi, or most Linux,  via USB, will be recognized as ttyACMx. It can be ttyACM0, ttyACM1, ttyACM2...etc.

To check the assigned number (ttyACMx) in Raspberry Pi, or Linux, enter the command after Arduino inserted.
$ dmesg|tail
Arduino Due recognized as ttyACM0 in the example

It can be noticed that ttyACM0 is added under /dev folder.
$ ls /dev/tty*

And more entries added in usb list.
$ lsusb