How do I change the background in Processing from an Arduino - arduino

I am trying to use three potentiometers that are connected to an Arduino to adjust the color background of Processing. I am super new at this.
Here is my Arduino code:
int potPin = 0;
int potPinB = 1;
int potPinC = 2;
void setup()
{
Serial.begin(9600);
}
void loop()
{
int val = map(analogRead(potPin), 0, 1023, 0, 255);
Serial.print(val);
delay(500);
Serial.print(",");
int valB = map(analogRead(potPinB), 0, 1023, 0, 255);
Serial.print(valB);
delay(500);
Serial.print(",");
int valC = map(analogRead(potPinC), 0, 1023, 0, 255);
Serial.println(valC);
delay(500);
}
Here is my processing code:
Which I know is wrong. My screen just shows up black.
import processing.serial.*;
Serial myPort;
float val = 0;
void setup()
{
size(500, 500);
port = new Serial(this, "/dev/cu.usbmodem1451", 9600);
//port.bufferUntil('\n');
if (frame != null);
frame.setResizable(true);
}
void draw ()
{
background(val);
}
void serialEvent (Serial port)
{
val = float(port.readStringUntil('\n'));
}

It looks like you might be using linux, you may want to check this:
"/dev/cu.usbmodem1451" -> mine is -> "/dev/ttyUSB0"
Here's an example I made from your posted code. It works on my machine, let me know if you have any difficulties.
Arduino Sketch (same)
int potPin = 0;
int potPinB = 1;
int potPinC = 2;
void setup()
{
Serial.begin(9600);
}
void loop()
{
int val = map(analogRead(potPin), 0, 1023, 0, 255);
Serial.print(val);
delay(500);
Serial.print(",");
int valB = map(analogRead(potPinB), 0, 1023, 0, 255);
Serial.print(valB);
delay(500);
Serial.print(",");
int valC = map(analogRead(potPinC), 0, 1023, 0, 255);
Serial.println(valC);
delay(500);
}
Processing Sketch
The processing sketch has been changed, some code was taken from the Arduino - Graph tutorial.
import processing.serial.*;
Serial myPort; // The serial port
int xPos = 1; // horizontal position of the graph
void setup () {
// set the window size:
size(400, 300);
// List all the available serial ports
println(Serial.list());
// Open whatever port is the one you're using.
myPort = new Serial(this, "/dev/ttyUSB0", 9600);
// don't generate a serialEvent() unless you get a newline character:
myPort.bufferUntil('\n');
// set inital background:
background(0);
}
void draw () {
// everything happens in the serialEvent()
}
void serialEvent (Serial myPort) {
// read first string
String inStringA = myPort.readStringUntil(',');
// make sure it's not empty
if (inStringA != null){
// read following strings
String inStringB = myPort.readStringUntil(',');
String inStringC = myPort.readStringUntil('\n');
// convert to an int and map to the screen height:
float valA = float(inStringA);
float valB = float(inStringB);
float valC = float(inStringC);
// assign to rgb background
background(valA,valB,valC);
}
}

Related

How do I get Arduino to communicate with Processing?

I wanted to make my Arduino communicate with Processing.
On Arduino, I use the code taken from the Processing site (Example 1A):
int switchPin = 4; // Switch connected to pin 4
void setup()
{
pinMode(switchPin, INPUT); // Set pin 0 as an input
Serial.begin(9600); // Initialize serial communications at a 9600 baud rate
}
void loop()
{
if (digitalRead(switchPin) == HIGH) // If switch is ON,
// send 1 to Processing
{
Serial.write(1);
}
else
{ // If the switch is not ON,
Serial.write(0); // send 0 to Processing
}
delay(100);
}
While in Processing I use this code:
import processing.serial.*;
Serial myPort; // Create object from Serial class
String val = "0"; // Data received from the serial port
void setup()
{
size(200, 200);
frameRate(10);
String portName = Serial.list()[0]; // Change the 0 to a 1, 2,
// etc. to match your port.
myPort = new Serial(this, portName, 9600);
}
void draw()
{
if (myPort.available() > 0)
{
// If data is available,
val = myPort.readStringUntil('\n'); // Read it and store it in val
}
background(255);
if(val.equals("0"))
{
fill(0);
}
else
{
fill(204);
}
rect(50, 50, 100, 100);
}
The program gives me the error NullPointerException on line 22 in the Processing program.
How can I solve it?
There is a delay in the communication and it is possible that the first time when the draw function is called, the serial port doesn't send any data, and the value received is null. That might be the reason you get the NullPointerException.
Try this:
void draw()
{
while (myPort.available() > 0)
{
// If data is available,
val = myPort.readStringUntil('\n'); // Read it and store it in val
}
background(255);
if(val != null)
{
if(val.equals("0"))
{
fill(0);
}
else
{
fill(204);
}
}
rect(50, 50, 100, 100);
}

Using an Arduino LDR Sensor to switch backgrounds in Processing

Using a LDR sensor for Arduino, I want to switch between two gif backgrounds in Processing depending on the intensity of light that the LDR senses. My Arduino set-up works and I can see a range of numbers in the Serial Monitor depending on the amount of light shined on the sensor - however I'm having trouble in Processing with making the switch between backgrounds. This is my first project combining Arduino with Processing so please forgive me if I've made any super obvious mistakes.
Arduino Code
int sensorPin = A0; // select the input pin for LDR
int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
Serial.begin(9600); //sets serial port for communication
}
void loop() {
sensorValue = analogRead(sensorPin); // read the value from the sensor
Serial.println(sensorValue); //prints the values coming from the sensor on the screen
delay(100);
}
Processing Code
//loads gif library for background
import gifAnimation.*;
Gif batmanGotham;
Gif batmanLair;
//loads Arduino
import processing.serial.*;
Serial myPort;
int sensorValue = 0;
void setup() {
size(1067, 800); //size of canvas
batmanGotham = new Gif(this, "background.gif"); //set gif
batmanGotham.play();
batmanLair = new Gif(this, "batman_lab.gif"); //set second gif
batmanLair.play();
String portName = "/dev/cu.usbmodem14201";
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}
void draw() {
}
void serialEvent (Serial myPort) {
if (sensorValue > 300) {
image(batmanLair, 0, 0); //lays down gif background
} else {
image(batmanGotham, 0, 0); //lays down gif background
}
}
You forgot to read data from the serial port, try adding the following line on your serialEvent() routine:
byte[] buffer = new byte[2];
sensorValue = myPort.readBytes(buffer);
at the very beginning.
As you see you have to recover data from the buffer yourself. The event is triggered automatically whenever there is something to read but you have to take is yourself from there and store it or process it.
You should be reading two bytes at a time to account for the size of the int you are sending from your Arduino.
Marcos is right, through you will be sending more than two bytes.
Let's assume you're sending 1023, that is actually 4 characters (bytes) + another new line (from println).
You can draw continuously and simply update the image based on the data read, ideally with some error checking:
//loads gif library for background
import gifAnimation.*;
Gif batmanGotham;
Gif batmanLair;
//loads Arduino
import processing.serial.*;
Serial myPort;
int sensorValue = 0;
void setup() {
size(1067, 800); //size of canvas
batmanGotham = new Gif(this, "background.gif"); //set gif
batmanGotham.play();
batmanLair = new Gif(this, "batman_lab.gif"); //set second gif
batmanLair.play();
String portName = "/dev/cu.usbmodem14201";
try{
myPort = new Serial(this, portName, 9600);
myPort.bufferUntil('\n');
}catch(Exception e){
println("error opening serial port: double check the cable is connected, the portName is right and SerialMonitor anything else trying to access the port is closed");
e.printStackTrace();
}
}
void draw() {
if (sensorValue > 300) {
image(batmanLair, 0, 0); //lays down gif background
} else {
image(batmanGotham, 0, 0); //lays down gif background
}
}
void serialEvent (Serial myPort) {
try{
String rawString = myPort.readString();
if(rawString != null && rawString.length() > 0){
// remove newline
rawString = rawString.trim();
// parse value
sensorValue = int(rawString);
}
}catch(Exception e){
println("error parsing serial data");
e.printStackTrace();
}
}
If you want to keep the Processing Serial part simpler, you can do the threshold logic on arduino and simply send a single byte to Processing, like 1 or 0 depending on which image you want to display:
int sensorPin = A0; // select the input pin for LDR
int sensorValue = 0; // variable to store the value coming from the sensor
void setup() {
Serial.begin(9600); //sets serial port for communication
}
void loop() {
sensorValue = analogRead(sensorPin); // read the value from the sensor
if(sensorValue > 0){
Serial.print('1');
}else{
Serial.print('0');
}
delay(100);
}
Then in Processing:
//loads gif library for background
import gifAnimation.*;
Gif batmanGotham;
Gif batmanLair;
//loads Arduino
import processing.serial.*;
Serial myPort;
boolean showLair;
void setup() {
size(1067, 800); //size of canvas
batmanGotham = new Gif(this, "background.gif"); //set gif
batmanGotham.play();
batmanLair = new Gif(this, "batman_lab.gif"); //set second gif
batmanLair.play();
String portName = "/dev/cu.usbmodem14201";
try{
myPort = new Serial(this, portName, 9600);
}catch(Exception e){
println("error opening serial port: double check the cable is connected, the portName is right and SerialMonitor anything else trying to access the port is closed");
e.printStackTrace();
}
}
void draw() {
// read 1 char
if(myPort != null && myPort.available() > 0){
char fromArduino = myPort.read();
showLair = (fromArduino == '1');
}
// update content
if (showLair) {
image(batmanLair, 0, 0); //lays down gif background
} else {
image(batmanGotham, 0, 0); //lays down gif background
}
}

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.

Controlling a motor with potentiometer

I am trying to use my arduino and a potentiometer to make a motor spin one way when the potentiometer is past 0 and spin the other when the potentiometer is past 0 the other direction. The code is working on the SensorValue < 512 side but not on the >507 side.
const int analogInPin = A1; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; //
const int analogOutPin_2 = 11; //
int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
}
void loop() {
sensorValue = analogRead(analogInPin);
if (sensorValue < 507) {
analogWrite(analogOutPin, LOW);
outputValue = map(sensorValue, 0, 512, 0, 255);
analogWrite(analogOutPin_2, outputValue);
}
if (512 > sensorValue) {
analogWrite(analogOutPin_2, LOW);
outputValue = map(sensorValue, 512, 1023, 0, 255);
analogWrite(analogOutPin, outputValue);
}
else {
}
delay(2);
}
For solving issues such as this. I recommend a few strategic prints and a for loop to simulate the data range, reveals the following code with a few tweaks works better
const int analogInPin = A1; // Analog input pin that the potentiometer is attached to
const int analogOutPin = 9; //
const int analogOutPin_2 = 11; //
int sensorValue = 0; // value read from the pot
int outputValue = 0; // value output to the PWM (analog out)
void setup() {
// initialize serial communications at 9600 bps:
Serial.begin(9600);
delay(1000);
Serial.println("Begin1");
}
void loop() {
// sensorValue = analogRead(analogInPin);
for (sensorValue = 0; sensorValue < 1024; sensorValue++) {
Serial.print("sensorValue = ");
Serial.print(sensorValue);
if (sensorValue < 507) {
outputValue = map(sensorValue, 0, 512, 255, 0);
Serial.print(" Forward : ");
Serial.print(outputValue);
analogWrite(analogOutPin, LOW);
analogWrite(analogOutPin_2, outputValue);
} else if (512 < sensorValue) {
outputValue = map(sensorValue, 512, 1023, 0, 255);
Serial.print(" Reverse : ");
Serial.print(outputValue);
analogWrite(analogOutPin_2, LOW);
analogWrite(analogOutPin, outputValue);
}
Serial.println();
}
while(1);
delay(1000);
}

Using Arduino light sensor value to jump video on Processing

My project is to create a robot Arduino flower with two sensors: light and pressure, that opens and closes according to the values in those two sensors, and at the same time plays different videos through Processing according to those values.
I've been having a really hard time passing on the value from the analog sensors in Arduino too processing. This is what I have so far:
Arduino
#include <Servo.h>
Servo myservo;
int pressure = 0;
int light = 1;
int pre;
int val;
void setup()
{
Serial.begin(9600);
myservo.attach(2);
}
void loop() {
pre = analogRead(pressure);
pre = map(pre, 918, 1023, 255, 0);
val = analogRead(light);
val = map(val, 0, 255, 0, 127);
Serial.print(val, DEC);
/*if (val>50) {
Serial.print(1);
}
else {
Serial.print(0);
}*/
myservo.write(val);
}
Processing
import processing.video.*;
import processing.serial.*; //arduino
Serial myPort; // Create object from Serial class
int val;
Movie movie;
void setup() {
String portName = Serial.list()[0];
myPort = new Serial(this, portName, 9600);
size(640, 360);
background(0);
movie = new Movie(this, "transit.mov");
movie.loop();
}
void movieEvent(Movie m) {
m.read();
}
void draw() {
val = myPort.read();
println(val);
//if (movie.available() == true) {
// movie.read();
//}
image(movie, 0, 0, width, height);
if (val==49) {
movie.jump(1);
}
}
For now I'm just trying to make the video react to the light sensor, but haven't been able. All I get from the Processing readings is 48. The motor reacts fine to the sensors.
What output do you get from a simpler Processing sketch like this? What output would you expect?
import processing.serial.*;
Serial myPort; // The serial port
void setup() {
// List all the available serial ports
println(Serial.list());
// Open the port you are using at the rate you want:
myPort = new Serial(this, Serial.list()[0], 9600);
}
void draw() {
while (myPort.available() > 0) {
int inByte = myPort.read();
println(inByte);
}
}
Also, why is your map function in your Arduino code pre = map(pre, 918, 1023, 255, 0); using 250 and 0 as your lower bound and upper bound respectively? That seems backwards. Should it not read pre = map(pre, 918, 1023, 0, 255);?

Resources