Sending two arrays to Arduino from Processing - arduino

I'm trying to pass multiple variables (n number of strings and n number of ints) from processing to my Arduino. I found this tutorial online and managed to send a single value. Now I have two arrays that both need to be accessed by the Arduino filesTypes[] and filesSizes[]. filesTypes[] consists of a 3 char long strings while fileSizes[] is an array of different integers.
Here is my Processing code:
import processing.serial.*;
Serial myPort; // Create object from Serial class
String[] fileTypes;
int[] fileSizes;
String[][] lines;
void setup()
{
size(200,200); //make our canvas 200 x 200 pixels big
String portName = Serial.list()[1]; //change the 0 to a 1 or 2 etc. to
match your port
myPort = new Serial(this, portName, 9600);
launch( sketchPath("") + "/test.bat");
}
void draw() {
if (mousePressed == true)
{ //if we clicked in the window
txtToStrg();
myPort.write('1'); //send a 1
txtToStrg();
} else
{ //otherwise
myPort.write('0'); //send a 0
}
}
void txtToStrg(){
String[] lines = loadStrings("list.txt");
fileTypes = new String[lines.length];
fileSizes = new int[lines.length];
for (int i = 0 ; i < lines.length; i++) {
if(lines[i] != null) {
String[] splitLine = split(lines[i], ' ');
fileTypes[i] = splitLine[0];
fileSizes[i] = int(splitLine[1]);
println(fileTypes[i] + " = " + fileSizes[i]);
}
}
}
And here my Arduino code:
char val; // Data received from the serial port
int ledPin = 4 ; // Set the pin to digital I/O 13
void setup() {
pinMode(ledPin, OUTPUT); // Set pin as OUTPUT
Serial.begin(9600); // Start serial communication at 9600 bps
}
void loop() {
if (Serial.available())
{ // If data is available to read,
val = Serial.read(); // read it and store it in val
}
if (val == '1')
{ // If 1 was received
digitalWrite(ledPin, HIGH); // turn the LED on
} else {
digitalWrite(ledPin, LOW); // otherwise turn it off
Serial.print(val);
}
delay(10); // Wait 10 milliseconds for next reading
}
If a pass anything but a char it stops working.

Related

How to send a number over serial to an arduino?

I'm trying to send a number value over serial to an Arduino to control an Individually Addressable LEDstrip. Using the Arduino IDE "Serial Monitor" I'm able to send a number to the light strip with no issue. However when i try to do it externally by reading from a text file in processing it doesn't go through.
After some debugging I can see that Processing has the number right and its stored in the variable. However the lightstip will only ever light up on led, instead of the number given.
Processing Code:
import processing.serial.*;
import java.io.*;
Serial myPort; // Create object from Serial class
void setup()
{
size(200,200); //make our canvas 200 x 200 pixels big
String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
myPort = new Serial(this, portName, 9600);
}
void draw()
{
while(true) {
// Read data from the file
{
String[] lines = loadStrings("Lifenumber.txt");
int number = Integer.parseInt(lines[0]);
println(number);
myPort.write(number);
delay(5000);
}
}
}
Arduino Code:
if ( Serial.available()) // Check to see if at least one character is available
{
char ch = Serial.read();
if(index < 3 && ch >= '0' && ch <= '9'){
strValue[index++] = ch;
}
else
{
Lnum = atoi(strValue);
Serial.println(Lnum);
for(i = 0; i < 144; i++)
{
leds[i] = CRGB::Black;
FastLED.show();
delay(1);
}
re = 1;
index = 0;
strValue[index] = 0;
strValue[index+1] = 0;
strValue[index+2] = 0;
}
}
What I want the program to do is read a number from a text file and light up that number of LEDs on the 144led lightstrip.
Here are a couple of comments on your code that should help make improvements in the future. It's important to form good coding habits early on: it will make your life so much easier (I'm speaking a mostly self taught programmer that started with flash so I know what messy and hacky is ;) )
import processing.serial.*;
//import java.io.*; // don't include unused imports
Serial myPort; // Create object from Serial class
void setup()
{
size(200,200); //make our canvas 200 x 200 pixels big
String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
// handle error initialising Serial
try{
myPort = new Serial(this, portName, 9600);
}catch(Exception e){
println("Error initializing Serial port " + portName);
e.printStackTrace();
}
}
void draw()
{
// don't use blocking while, draw() already gets called continuously
//while(true) {
// Read data from the file
//{
// don't load the file over and over again
String[] lines = loadStrings("Lifenumber.txt");
int number = Integer.parseInt(lines[0]);// int(lines[0]) works in Processing, but the Java approach is ok too
println("parsed number: " + number);
if(myPort != null){
myPort.write(number);
}
// don't use blocking delays, ideally not even in Arduino
//delay(5000);
//}
//}
}
Here's a version of the Processing code that loads the text file, parses the integer then sends it to serial only once (if everything is ok, otherwise basic error checking should reveal debug friendly information):
import processing.serial.*;
Serial myPort; // Create object from Serial class
void setup()
{
size(200,200); //make our canvas 200 x 200 pixels big
String portName = Serial.list()[0]; //change the 0 to a 1 or 2 etc. to match your port
// handle error initialising Serial
try{
myPort = new Serial(this, portName, 9600);
}catch(Exception e){
println("Error initializing Serial port " + portName);
e.printStackTrace();
}
// Read data from the file
try{
String[] lines = loadStrings("Lifenumber.txt");
int number = Integer.parseInt(lines[0]);
println("parsed number: " + number);
// validate the data, just in case something went wrong
if(number < 0 && number > 255){
println("invalid number: " + number + ", expecting 0-255 byte sized values only");
return;
}
if(myPort != null){
myPort.write(number);
}
}catch(Exception e){
println("Error loading text file");
e.printStackTrace();
}
}
void draw()
{
// display the latest value if you want
}
// add a keyboard shortcut to reload if you need to
Your strip has 144 leds (less than 255) which fits nicely in a single byte which is what the Processing sketch sends
On the Arduino side there's nothing too crazy going on, so as long as you validate the data coming in should be fine:
#include "FastLED.h"
#define NUM_LEDS 64
#define DATA_PIN 7
#define CLOCK_PIN 13
// Define the array of leds
CRGB leds[NUM_LEDS];
int numLEDsLit = 0;
void setup() {
Serial.begin(9600);
Serial.println("resetting");
LEDS.addLeds<WS2812,DATA_PIN,RGB>(leds,NUM_LEDS);
LEDS.setBrightness(84);
}
void loop() {
updateSerial();
updateLEDs();
}
void updateSerial(){
// if there's at least one byte to read
if( Serial.available() > 0 )
{
// read it and assign it to the number of LEDs to light up
numLEDsLit = Serial.read();
// constrain to a valid range (just in case something goes funny and we get a -1, etc.)
numLEDsLit = constrain(numLEDsLit,0,NUM_LEDS);
}
}
// uses blacking delay
void updateLEDs(){
// for each LED
for(int i = 0; i < 144; i++)
{
// light up only the number of LEDs received via Serial, turn the LEDs off otherwise
if(i < numLEDsLit){
leds[i] = CRGB::White;
}else{
leds[i] = CRGB::Black;
}
FastLED.show();
delay(1);
}
}
Adjust the pins/LED chipsets/etc. based on your actual physical setup.

Button switch Arduino to Processing: serial output giving null

I am trying to use a button switch in Arduino to trigger a visual display in Processing. I used "HIGH" and "LOW" to identify whether the button is pressed.
However, my code is constantly giving null instead of giving "HIGH" or "LOW" depending on the button state. I think this is pretty basic but I'm just quite lost. Any helps or comments would be appreciated!
Below is my code for Arduino and Processing respectively.
const int buttonPin = 2;
const int LEDPin = 13;
int buttonState = 0;
void setup() {
pinMode(buttonPin, INPUT);
pinMode(LEDPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int analogValue = analogRead(A0)/4;
Serial.write(analogValue);
buttonState = digitalRead(buttonPin);
if (buttonState == HIGH) {
Serial.write(HIGH);
digitalWrite(LEDPin, HIGH);
} else {
Serial.write(LOW);
digitalWrite(LEDPin, LOW);
}
delay(100);
}
Processing code:
import processing.serial.*;
Serial myPort;
String val;
void setup() {
size(400,400);
String portName = Serial.list()[1];
myPort = new Serial(this, portName, 9600);
}
void draw() {
if (myPort.available() > 0) {
val = myPort.readStringUntil('\n');
println(val);
if (val == "HIGH") {
background(127,0,0);
}
if (val == "LOW") {
background(144, 26, 251);
}
}
}
write()
Writes binary data to the serial port. This data is sent as a byte or series of bytes.
Serial.write(str)
str: a string to send as a series of bytes
So when you use write HIGH and LOW in Serial.write, it will be send as a series of bytes. Edit your processing part to handle the incoming bytes. Just as follows :
import processing.serial.*;
Serial myPort;
String val;
int len; //length of byte array
void setup() {
size(400,400);
String portName = Serial.list()[1];
myPort = new Serial(this, portName, 9600);
}
void draw() {
if ((len=myPort.available()) > 0) {
for(i=0;i<len;i++)
myByteArray=myPort.read();
String val = String(myByteArray);
println(val);
if (val == "HIGH") {
background(127,0,0);
}
if (val == "LOW") {
background(144, 26, 251);
}
}
}
just change your buttonState variable type from integer to boolean, and then use
if(buttonState) {
Serial.println("HIGH");
}
else {
Serial.println("LOW");
}
In Arduino, HIGH and LOW are defined as 1 and 0.
By executing Serial.write(HIGH); and Serial.write(LOW); you are just sending a single byte 1 or 0.
But according to your Processing code, you are expecting Serial.write(HIGH); to send 'H', 'I', 'G', 'H' and '\n' characters.
In your Arduino code, you need to replace Serial.write(HIGH); and Serial.write(LOW); with Serial.print("HIGH\n"); and Serial.print("LOW\n");.

Serial communication on Arduino

I have an assignment for school where I need to turn on a led with the serial message #ON%, and turn the led off with #OFF%. The # and % are the identifiers for the correct string. So I made this code:
(bericht means message in Dutch)
String readString = "";
int recievedCharacter;
String bericht = "";
int ledPin = 6;
void setup() {
Serial.begin(9600); // opens serial port, sets data rate to 9600 bps
pinMode(ledPin, OUTPUT);
}
void loop()
{
while (Serial.available() > 0)
{
delay(4);
char readChar = (char) Serial.read(); // 'Convert' to needed type
bericht += + readChar; // concatenate char to message
}
if(bericht.startsWith("#"))
{
if(bericht == "#ON%")
{
Serial.println(bericht);
Serial.println("goed");
digitalWrite(ledPin, HIGH);
//message = "";
}
if(bericht == "#OFF%")
{
Serial.println("goed");
digitalWrite(ledPin, LOW);
//message = "";
}
}
}
The problem is the program will never get into the if(bericht == "#ON%") section...
Sorry if this is a silly question but with a lot of googling I just can't figure it out...
The problem is here:
bericht += + readChar; // concatenate char to message // XXX '+ char' => int
this actually appends an integer to the message. Remove the +:
bericht += readChar; // concatenate char to message // Goed!

Making a Game With Arduino and Processing

I am trying to form a two player game which requires an audio reflex to a visual. by using littebits sound trigger for sound input and littbits arduino to connect it to the computer. But I am new to this and don't know how to connect arduino to processing and use the input from sound trigger to effect the score when a black square appears.
here is my code in processing and a sample arduino code I have taken from littlebits website and tried to modify a little.
thanks in advance!
float dice;
int playerOne = 0; //player 1 score (left paddle)
int playerTwo = 0; //player 2 score (right paddle)
boolean oneWins = false;
boolean twoWins = false;
void setup(){
size(500, 500);
smooth();
noStroke();
frameRate(2.5);
}
void draw() {
background(255);
showGUI();
dice = random(0, 3);
if (dice < 1.000001 && dice > 0.1){
fill ((0), (255), (0));
ellipse (250,250,100,100);
} else if (dice < 2.000001 && dice > 1.000001){
rectMode(RADIUS);
fill ((255), (0), (0));
rect (250,250,50,50);
} else if (dice < 3.000000 && dice > 1.000000){
rectMode(RADIUS);
fill ((0), (0), (255));
rect (250,250,50,50);
} else if (dice < 0.1){
rectMode(RADIUS);
fill(0);
rect(250,250,50,50);
}
}
----------arduino------
void setup() {
Serial.begin(9600); //Establish rate of Serial communication
establishContact(); //See function below
}
void loop() {
if (Serial.available() > 0) {
int inByte = Serial.read();
int leftTrigger = analogRead(A0);
Serial.print(leftTrigger, DEC);
Serial.print(",");
int rightTrigger = analogRead(A1);
Serial.println(rightTrigger, DEC);
}
}
void establishContact() {
while (Serial.available() <= 0) {
Serial.println("hello");
delay(300);
}
}
You need two pieces of code for this to work: one on the Arduino that sends commands, and one for Processing to receive and parse those commands.
I haven't used the littlebits modules, but here's a button example from this very detailed tutorial.
Arduino code:
int switchPin = 4; // switch connected to pin 4
void setup() {
pinMode(switchPin, INPUT); // set pin 0 as an input
Serial.begin(9600); // start serial communication at 9600bps
}
void loop() {
if (digitalRead(switchPin) == HIGH) { // if switch is ON,
Serial.print(1, BYTE); // send 1 to Processing
} else { // if the switch is not ON,
Serial.print(0, BYTE); // send 0 to Processing
}
delay(100); // wait 100 milliseconds
}
And the matching Processing code:
import processing.serial.*;
Serial port; // create object from Serial class
int val; // data received from the serial port
void setup() {
size(200, 200);
frameRate(10);
// open the port that the board is connected to
// and use the same speed (9600bps)
port = new Serial(this, 9600);
}
void draw() {
if (0 < port.available()) { // if data is available,
val = port.read(); // read it and store it in val
}
background(255); // set background to white
if (val == 0) { // if the serial value is 0,
fill(0); // set fill to black
} else { // if the serial value is not 0,
fill(204); // set fill to light gray
}
rect(50, 50, 100, 100);
}
Notice that the Arduino sends a value that Processing looks for and interprets. You can also look at the PhysicalPixel example from the Arduino IDE for an example on sending data from Processing to Arduino.

Arduino Communicate with android through bluetooth

Currently i success to build the communication between the android device and arduino through bluetooth. As arduino will send string "ON" or "OFF" depend on the LED condition to Android through bluetooth and my android able to receive the string "LED:ARE:OFF" and "LED:ARE:ON" through the read() function. But currently i want to read a data by split the string into 3 from the LED, for example: "LED:ARE:OFF" into "LED" , "Are", "OFF" , but i failed to received the data. I had tried the String.split(":") to split out the aaa:bbb:ccc into 3 part, and it unable to read the data as well. Please help
Arduino Code:
#include <SoftwareSerial.h>// import the serial library
SoftwareSerial Genotronex(10, 11); // RX, TX
int ledpin=8; // led on D13 will show blink on / off
long previousMillis = 0; // will store last time LED was updated
long interval = 1000; // interval at which to blink (milliseconds)
int ledState = LOW; // ledState used to set the LED
long Counter=0; // counter will increase every 1 second
void setup() {
// put your setup code here, to run once:
Genotronex.begin(9600);
Genotronex.println("Bluetooth On please wait....");
pinMode(ledpin,OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
unsigned long currentMillis = millis();
if(currentMillis - previousMillis > interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
Counter+=1;
delay(4000);
// if the LED is off turn it on and vice-versa:
if (ledState == LOW){
ledState = HIGH;
Genotronex.print("LED:ARE:ON");
digitalWrite(ledpin, ledState);
}
else{
ledState = LOW;
Genotronex.print("LED:ARE:OFF");
digitalWrite(ledpin, ledState);
}
// set the LED with the ledState of the variable:
}
}
Android Code:
btnSend.setOnClickListener(this);
int delay = 1000; // delay in ms
int period = 100; // repeat in ms
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
if (flag)
{
final byte data = read();
readMessageHandler.post(new Runnable()
{
public void run()
{
if (data != 1){
message = txtReceived.getText().toString() + (char)data;}
else{
message = "";
}
String message;
//New Code for split the data
String[] parts = message.split(":"); // escape .
String part0 = parts[0];
String part1 = parts[1];
String part2 = parts[2];
txtReceived.setText(part0);
//End of Split
// txtReceived.setText(Message);
}
});
}
}
}, delay, period);
private byte read()
{
byte dataRead = 0;
try
{
dataRead = (byte) inputStream.read();
}
catch(IOException readException)
{
toastText = "Failed to read from input stream: " + readException.getMessage();
Toast.makeText(Blood_Pressure.this, toastText, Toast.LENGTH_SHORT).show();
}
return dataRead;
}

Resources