How to connect an Arduino to a raspberry pi via USB bidirectional.
The raspberry reads all from the serial and prints it. Next it reads a textile from a webpage and sends the text (one word) to serial, next a random car to the Arduino. Arduino got a LCD attached and shows the data it got via serial. It sends back the seconds it run and a string. The example is at this time without real use, it is just for testing the bidirectional serial connection.
Using Python on the raspberry side. Change the port to what you find out:
import serial import time import random import urllib2 import feedparser def read_all(port, chunk_size=200): """Read all characters on the serial port and return them.""" if not port.timeout: raise TypeError('Port needs to have a timeout set!') read_buffer = b'' while True: # Read in chunks. Each chunk will wait as long as specified by # timeout. Increase chunk_size to fail quicker byte_chunk = port.read(size=chunk_size) read_buffer += byte_chunk if not len(byte_chunk) == chunk_size: break return read_buffer #end def cars = ["Ford", "Volvo", "BMW", "VW"] ser = serial.Serial( port = '/dev/ttyACM0', baudrate = 9600, parity = serial.PARITY_NONE, stopbits = serial.STOPBITS_ONE, bytesize = serial.EIGHTBITS, timeout=0.5, # IMPORTANT, can be lower or higher ) #s = serial.Serial('/dev/ttyACM0', 9600) # Namen ggf. anpassen #s.flushInput() #s.open() time.sleep(2) # der Arduino resettet nach einer Seriellen Verbindung, daher ser.write("xyx") d = feedparser.parse('http://www.reddit.com/r/news/.rss') dlen = len(d['entries']) dnr = 0 try: while True: nb = "01234567890123456789012345678901" text = "nn.mm" data_str = [] data_str = read_all(ser) print(data_str) #nb = raw_input('Choose it: ') #nb = cars[random.randint(0,3)] + "x" try: #nb = d['entries'][dnr]['title'].encode('utf-8').strip() + "x" nb = d['entries'][dnr]['title'].encode('utf-8').strip() dnr += 1 if (dnr > dlen -1): d = feedparser.parse('http://www.reddit.com/r/news/.rss') dlen = len(d['entries']) dnr = 0 #ser.write(nb) except: print("fehler1") try: response = urllib2.urlopen('http://4johannes.de/weather/lowest.txt') text = response.read().strip() print(text) except: print("fehler2") ll = len(text) text2 = text + " " + nb[0:33-ll] + "\n" #print(text2) #ser.write(text2) #time.sleep(5) #text2 = nb[16-ll:33-ll] + "y" print(text2) print(nb) ser.write(text2) time.sleep(5) except KeyboardInterrupt: ser.close()
And this is the Arduino part:
/********************* Example code for the Adafruit RGB Character LCD Shield and Library This code displays text on the shield, and also reads the buttons on the keypad. When a button is pressed, the backlight changes color. **********************/ // include the library code: #include <Wire.h> #include <Adafruit_RGBLCDShield.h> #include <utility/Adafruit_MCP23017.h> // The shield uses the I2C SCL and SDA pins. On classic Arduinos // this is Analog 4 and 5 so you can't use those for analogRead() anymore // However, you can connect other I2C sensors to the I2C bus and share // the I2C bus. Adafruit_RGBLCDShield lcd = Adafruit_RGBLCDShield(); // These #defines make it easy to set the backlight color #define RED 0x1 #define YELLOW 0x3 #define GREEN 0x2 #define TEAL 0x6 #define BLUE 0x4 #define VIOLET 0x5 #define WHITE 0x7 byte nr; char myString[] = "Hello MArius"; String readString; long previousMillis = 0; long interval = 1000; void setup() { // Debugging output Serial.begin(9600); // set up the LCD's number of columns and rows: lcd.begin(16, 2); // Print a message to the LCD. We track how long it takes since // this library has been optimized a bit and we're proud of it :) int time = millis(); lcd.print("Hello, Marius!"); time = millis() - time; //Serial.print("Took "); Serial.print(time); Serial.println(" ms"); lcd.setBacklight(WHITE); lcd.setCursor(0, 1); } uint8_t i=0; void loop() { // set the cursor to column 0, line 1 // (note: line 1 is the second row, since counting begins with 0): //lcd.setCursor(0, 1); // print the number of seconds since reset: //lcd.print(millis()/1000); unsigned long currentMillis = millis(); if(currentMillis - previousMillis > interval) { // save the last time you blinked the LED previousMillis = currentMillis; //do nothing at the moment //Serial.println(millis()/1000); } nr = 1; if (Serial.available() > 0) { //nr = Serial.read(); //myString = Serial.readln(); //Serial.print("Folgender char wurde empfangen: "); //Serial.println(nr, DEC); char c = Serial.read(); //gets one byte from serial buffer readString += c; //makes the string readString //lcd.setCursor(5,1); //lcd.print(readString); //lcd.print(c); //readString = ""; if (c == 'x') { lcd.setCursor(0,1); lcd.print(" <"); lcd.setCursor(0,1); lcd.print(readString); Serial.println(millis()/1000); Serial.println("x/n"); readString = ""; } } uint8_t buttons = lcd.readButtons(); if (buttons) { lcd.clear(); lcd.setCursor(0,0); if (buttons & BUTTON_UP) { lcd.print("UP "); lcd.setBacklight(RED); } if (buttons & BUTTON_DOWN) { lcd.print("DOWN "); lcd.setBacklight(YELLOW); } if (buttons & BUTTON_LEFT) { lcd.print("LEFT Marius"); lcd.print(nr); lcd.setBacklight(GREEN); } if (buttons & BUTTON_RIGHT) { lcd.print("RIGHT Paulina"); lcd.setBacklight(TEAL); } if (buttons & BUTTON_SELECT) { lcd.print("SELECT "); lcd.setBacklight(VIOLET); } } }