Button switch Arduino to Processing: serial output giving null - arduino

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");.

Related

How to control the display and non-display of sensor values ​in Arduino using Bluetooth?

I have a sensor that connects to the body and displays muscle signals.
In the setup guide of this sensor, it is said to upload the following code on Arduino, and when we open the Serial Monitor, the sensor values start to be displayed.
Now I want to control the display of these signals using Bluetooth.
So that when I click on the start button in my App, Serial.print() will start working. Also, when I click on the Stop button, the display of these signals and numbers will stop.
Sensor setup guide is this :
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(analogRead(A0));
}
And this is how it works properly :
But when I upload a piece of code that I wrote to my Arduino, it only shows me just on value.
this is my code :
#include <SoftwareSerial.h>
SoftwareSerial BTserial(0, 1); // RX | TX
char Incoming_value = 0;
void setup() {
Serial.begin(9600);
BTserial.begin(9600);
}
void loop() {
Incoming_value = Serial.read(); // "1" is for Start
if (Incoming_value == '1') {
Serial.println(Incoming_value);
StartSensor();
}
}
int StartSensor() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(200);
}
also please tell me How to write StopSensor Function for Stop print Sensor Value.
Try this code first (Without Bluetooth module)
#include <SoftwareSerial.h>
SoftwareSerial BTserial(0, 1); // RX | TX
char Incoming_value = 0;
int state = 0;
void setup() {
Serial.begin(9600);
//BTserial.begin(9600);
}
void loop() {
Incoming_value = Serial.read(); // "1" is for Start
if (Incoming_value == '1') {
state = 1;
}
else if (Incoming_value == '0') {
state = 0;
}
if (state == 1) {
StartSensor();
} else {
Serial.println(0);
}
}
int StartSensor() {
int sensorValue = analogRead(A0);
Serial.println(sensorValue);
delay(200);
}

Sending two arrays to Arduino from Processing

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.

Issues with serial communication between Arduino and Processing

I'm attempting to create a data exchange between sensors on an Arduino (well, actually an ATmega328PU-based clone built on a breadboard, but I don't believe that that's the source of my problem) and a Processing script, and I'm getting some unexpected results.
I was following the method of serial communication detailed here, but I get stuck with what appears to be no data actually traveling over the serial connection.
The Arduino code:
int buttonPin = 9, photodiodePin = A0;
char dataToSend;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, OUTPUT);
pinMode(photodiodePin, INPUT);
}
void loop() {
if (Serial.available() > 0)
{
dataToSend = Serial.read();
if (dataToSend == 'B')
{
Serial.println(digitalRead(buttonPin));
}
else if (dataToSend == 'L')
{
Serial.println(analogRead(photodiodePin));
}
}
}
And the relevant parts of the Processing code:
import processing.serial.*;
Serial myPort;
void setup()
{
size(1600, 900);
String portName = Serial.list()[1];
myPort = new Serial(this, portName, 9600);
}
void draw()
{
if(getButtonData() == 1)
{
// Do stuff
}
}
int getLightData()
{
myPort.write('L');
println("L");
while(!(myPort.available() > 0))
{
}
int lightValue = int(myPort.readStringUntil('\n'));
return lightValue;
}
int getButtonData()
{
myPort.write('B');
println("B");
while(!(myPort.available() > 0))
{
println("stuck in here");
delay(500);
}
int buttonValue = int(myPort.readStringUntil('\n'));
return buttonValue;
}
And in Processing I get an output of:
B
stuck in here
stuck in here
stuck in here
stuck in here
...
Note: I know I have the correct port selected from the list, so that is not the issue.
I've tried debugging the issue and searching the Internet for similar problems, both to no avail.
I would first check if simply sending a simple message from Arduino to Processing works. Try something like this in Arduino:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println("test");
delay(1000);
}
and this in Processing:
import processing.serial.*;
Serial arduino;
void setup(){
String portName = Serial.list()[1];
try{
arduino = new Serial(this, portName, 9600);
arduino.bufferUntil('\n');
}catch(Exception e){
System.err.println("Error initializing Serial port!\nPlease check connections and port settings");
e.printStackTrace();
}
}
void draw(){
}
void serialEvent(Serial s){
println("received arduino message: " + s.readString());
}
If this simple setup works, you should be fine to move on to the next step and have two way communication. If the above doesn't work then there's something else causing issues with serial communication (in which case please report what errors you're receiving, if any or what behaviour you're experiencing)
In case the above works, you can try two way communication. Notice I'm making use of serialEvent() and bufferUntil. It's best to avoid blocking while loops wherever possible.
Arduino code:
int buttonPin = 9, photodiodePin = A0;
char dataToSend;
void setup() {
Serial.begin(9600);
pinMode(buttonPin, OUTPUT);
pinMode(photodiodePin, INPUT);
}
void loop() {
}
void serialEvent(){
if(Serial.available() > 0){
char cmd = Serial.read();
if(cmd == 'B'){
Serial.println(digitalRead(buttonPin));
}
if(cmd == 'L'){
Serial.println(analogRead(photodiodePin));
}
}
}
Processing code:
import processing.serial.*;
Serial arduino;
int digitalValue;
int analogValue;
int lastCMD;
void setup(){
size(200,100);
String portName = Serial.list()[1];
try{
arduino = new Serial(this, portName, 9600);
arduino.bufferUntil('\n');
}catch(Exception e){
System.err.println("Error initializing Serial port!\nPlease check connections and port settings");
e.printStackTrace();
}
}
void draw(){
background(0);
text("Press 'B' to read digital pin\nPress 'L' to read analog pin\n\n"+
"digital pin: " + digitalValue + "\nanalog pin: " + analogValue,10,25);
}
void keyReleased(){
if(key == 'B' || key == 'L'){
lastCMD = key;
println("sending command" + lastCMD);
if(arduino != null){
arduino.write(lastCMD);
}else println("Arduino is not initializing, not writing to serial port");
}
}
void serialEvent(Serial s){
String rawString = s.readString();
println("received arduino message" + rawString);
try{
rawString = rawString.trim();//remove any white space characters (if present)
if(lastCMD == 'B') digitalValue = int(rawString);
if(lastCMD == 'L') analogValue = int(rawString);
}catch(Exception e){
println("Error parsing String from serial port:");
e.printStackTrace();
}
}

Sending IR signal from Arduino to F&D speakers

I am using below code to send an IR signal to my speaker but they don't respond.
#include <IRremote.h>
IRsend irsend;
const int buttonPin = 8; // the number of the pushbutton pin
//const int ledPin = 3;
int buttonState = 0; // variable for reading the pushbutton status
void setup()
{
// pinMode(ledPin, OUTPUT);
// initialize the pushbutton pin as an input:
pinMode(buttonPin, INPUT);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(buttonPin);
// check if the pushbutton is pressed.
// if it is, the buttonState is HIGH:
if (buttonState == HIGH) {
// turn LED on:
digitalWrite(7,HIGH);
irsend.sendNEC(0x1FE08F7,32);
}else{
digitalWrite(7,LOW);
}
}
IR Reciever on my other Arduino receives signal but also they vary sometime it shows UNKNOWN and sometime NEC. I am using below code:
#include <IRremote.h>
const int RECV_PIN = 11;
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
irrecv.blink13(true);
}
void loop() {
if (irrecv.decode(&results)) {
if (results.decode_type == NEC) {
Serial.print("NEC: ");
} else if (results.decode_type == SONY) {
Serial.print("SONY: ");
} else if (results.decode_type == RC5) {
Serial.print("RC5: ");
} else if (results.decode_type == RC6) {
Serial.print("RC6: ");
} else if (results.decode_type == UNKNOWN) {
Serial.print("UNKNOWN: ");
}
Serial.println(results.value, HEX);
Serial.println(results.value);
irrecv.resume(); // Receive the next value
}
}
The NEC code that I recieved is correct but on that code speaker does not respond. I double checked the HEX code with the remote that came along with speaker but nothing seem to work.
I think that you could have problem with the HEX literal.
From Arduino API:
By default, an integer constant is treated as an int with the attendant limitations in values. To specify an integer constant with another data type, follow it with:
a 'u' or 'U' to force the constant into an unsigned data format. Example: 33u
a 'l' or 'L' to force the constant into a long data format. Example: 100000L
a 'ul' or 'UL' to force the constant into an unsigned long constant. Example: 32767ul
And from GitHub:
void sendNEC (unsigned long data, int nbits) ;
So, try:
irsend.sendNEC(0x01FE08F7UL,32);

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.

Resources