Arduino To Processing Error For Capactive Sensor

Hello,

I have successfully drafted the Ardunio code for capacitive sensing. The serial Monitor shows right values.

Also, I have successful drafted the processing code which shows the exact same values from Arduino’s serial monitor on processing’s console.

However, on processing the drawing function is not doing by desired drawing when reading values. Moreover, both codes are working fine independently.

Please help.

Moreover, my processing code works fine with other ardunio example code. That is drawings change.

Thank you for helping

Arduino Code:

#include <CapacitiveSensor.h>

/*
 * CapitiveSense Library Demo Sketch
 * Paul Badger 2008
 * Uses a high value resistor e.g. 10 megohm between send pin and receive pin
 * Resistor effects sensitivity, experiment with values, 50 kilohm - 50 megohm. Larger resistor values yield larger sensor values.
 * Receive pin is the sensor pin - try different amounts of foil/metal on this pin
 * Best results are obtained if sensor foil and wire is covered with an insulator such as paper or plastic sheet
 */


CapacitiveSensor   cs_4_2 = CapacitiveSensor(A4,A2);        // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil


void setup()                    
{

   cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
   Serial.begin(9600);

}

void loop()                    
{
    long start = millis();
    long total1 =  cs_4_2.capacitiveSensor(30);
  

    //Serial.println(millis() - start);        // check on performance in milliseconds
    //Serial.println("\t");                    // tab character for debug window spacing

    Serial.println(total1);                  // print sensor output 1
    Serial.println("\t");


    delay(1000);                             // arbitrary delay to limit data to serial port 
}

Processing Code

import processing.serial.*;



import processing.serial.*; // import the Processing serial library
Serial myPort;  // The serial port
int sensor1;
int sensor2;
int sensor3;
float mappedSensor1;
float mappedSensor2;
float mappedSensor3;
PImage Gifimg;
PImage firstimg;
PImage secondimg;



PImage Frontimg;  // Declare variable "a" of type PImage

// Declare variable "a" of type PImage

void setup() {
  size(1080, 800);
  // List all the available serial ports in the console
  printArray(Serial.list());
   Gifimg = loadImage("secondsmall.png");  // Load the image into the program
   Frontimg = loadImage("Frontsmall.png");  // Load the image into the program  
   secondimg = loadImage("finalsmall.png");  // Load the image into the program  

   
   

  // Change the 0 to the appropriate number of the serial port
  // that your microcontroller is attached to.
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
  // read incoming bytes to a buffer
  // until you get a linefeed (ASCII 10):
  myPort.bufferUntil('\n');
}


void draw() {
  background(255);

  if (sensor1 == 0) {
image(secondimg, 0, 0);
image(Gifimg, 0, 0);



} 
else {
image(Frontimg, 0, 0);

 

  }

}


void serialEvent(Serial myPort) {
  // read the serial buffer:
  String myString = myPort.readStringUntil('\n');
  if (myString != null) {
    // println(myString);
    myString = trim(myString);

    // split the string at the commas
    // and convert the sections into integers:
    int sensors[] = int(split(myString, ','));
    for (int sensorNum = 0; sensorNum < sensors.length; sensorNum++) {
      print("Sensor " + sensorNum + ": " + sensors[sensorNum] + "\t");
    }
    // add a linefeed at the end:
    println();
    sensor1 = sensors[0];  
    
    mappedSensor1 = map(sensor1, 0, 1023, height, 0);
   
  }
}
1 Like

Hello,

Welcome to the community!

Try this for Arduino code for testing:

boolean toggle = false;

void setup()                    
  {
  Serial.begin(9600);
  }

void loop()                    
  {  
  long total1 =  271828182;
  long total2 =  314159265;

  if (toggle)
    {  
    Serial.print(0);
    Serial.print(',');
    Serial.println(total1);
    }
  else
    {
    Serial.print(1);
    Serial.print(',');
    Serial.println(total2);      
    }
    
  delay(1000);
  toggle = !toggle;                          
  }

You are sending a long as a String so receive as a String for now; you are converting to an int in your code.

String sensors[] = split(myString, ',');

My processing code (modified yours a bit) was able to receive “sensor number” and “data” and print with:

    sensor1 = int(sensors[0]);
    println(sensor1);
    long data = Long.parseLong(sensors[1]);
    println(data);

I then displayed a circle() to keep it simple and changed color depending on “sensor number”.

:slight_smile:

1 Like

Hi, Thank you so much for suggesting.

I understand you are saying that I’m sending string to processing rather than integers that’s processing is unable to read numbers?

Where in my code within processing, I shall put your modified code?

I’m new to this. Could you please put changes into my processing code and share it as a whole so i could test it please

You can try the suggestions I made:

  1. Receive as a String and print as a String for testing
  2. When you want to use the received data as a number you have to convert; see comments in my example code "Convert String to… "

I edited some errors in code above…

If you ask me to edit your code in future I will not assist you; this is your project.

:slight_smile:

Hi, sure.
So I understand that my current code is sending a string to processing and you want me to test string data. Which part of my processing code should i remove so my string doesnt convert into integer?

You are receiving Strings in the array; that is fine and works.
It is much more complicated to send “numbers” with Serial.write() (only sends a byte) and I would not do this.
You must convert the string you received (Strings are in array) to numbers if you want to use them as numbers.

I provided enough for you to get started.

:slight_smile:

Sure. So I get these points. Please correct if I m wrong:

  1. My arduino is sending string data
  2. My processing is converting string into integer
  3. You are suggesting that i should not do the second step and receive string on processing as well?

Is this correct

  1. You are sending a long data type as a String with Serial.print()
  2. You are receiving a String and converting it to an int in your code.
  3. Consider saving String in array initially until you get this working and then convert the String to a long data type when it is required.

Breaking into steps is easier to debug code.

Keep in mind that print() a String or a number (int, long, etc.) will show the same on the console but they are two different data types! You must keep track of them and use as per your requirements (data or string).

It is your code so you must decide how you want to do this.

:slight_smile:

Examples of conversions:

void setup() 
  {
  int num = 12345678;
  println(num);
  
  String s1 = "12345678";
  println(s1);
  
  int num2 = int(s1);
  println(num2);
  
  num2 = parseInt(s1); //Same as above
  println(num2);
  
  String s2 = "1234567890";
  println(s2);
  
  long num3 = 1234567890;
  println(num3); 
  
  long num4 = Long.parseLong(s2);
  println(num4); 
  }
1 Like

Thank you.
So now I’m sending “int” instead of string through Arduino and processing is receiving int without any conversion. But same issue, drawing function now working

Arduino:

#include <CapacitiveSensor.h>

/*
 * CapitiveSense Library Demo Sketch
 * Paul Badger 2008
 * Uses a high value resistor e.g. 10 megohm between send pin and receive pin
 * Resistor effects sensitivity, experiment with values, 50 kilohm - 50 megohm. Larger resistor values yield larger sensor values.
 * Receive pin is the sensor pin - try different amounts of foil/metal on this pin
 * Best results are obtained if sensor foil and wire is covered with an insulator such as paper or plastic sheet
 */


CapacitiveSensor   cs_4_2 = CapacitiveSensor(4,2);        // 10 megohm resistor between pins 4 & 2, pin 2 is sensor pin, add wire, foil


void setup()                    
{

   cs_4_2.set_CS_AutocaL_Millis(0xFFFFFFFF);     // turn off autocalibrate on channel 1 - just as an example
   Serial.begin(9600);

}

void loop()                    
{
    int start = millis();
    int total1 =  cs_4_2.capacitiveSensor(30);
  

    //Serial.println(millis() - start);        // check on performance in milliseconds
    //Serial.println("\t");                    // tab character for debug window spacing

    Serial.println(total1);                  // print sensor output 1
    Serial.println("\t");


    delay(1000);                             // arbitrary delay to limit data to serial port 
}

Processing Code

/**
 * Simple Read
 * 
 * Read data from the serial port and change the color of a rectangle
 * when a switch connected to a Wiring or Arduino board is pressed and released.
 * This example works with the Wiring / Arduino program that follows below.
 */


import processing.serial.*;

Serial myPort;  // Create object from Serial class
int val;      // Data received from the serial port

void setup() 
{
  size(200, 200);
  // I know that the first port in the serial list on my mac
  // is always my  FTDI adaptor, so I open Serial.list()[0].
  // On Windows machines, this generally opens COM1.
  // Open whatever port is the one you're using.
  String portName = Serial.list()[0];
  myPort = new Serial(this, portName, 9600);
}

void draw()
{
  if ( myPort.available() > 0) {  // If data is available,
    val = myPort.read();         // read it and store it in val
  }
  background(255);             // Set background to white
  if (val > 1000) {              // 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);
  println();
}

// Wiring / Arduino Code

// Code for sensing a switch status and writing the value to the serial port.

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 9600 bps
}

void loop() {
  if (digitalRead(switchPin) == HIGH) {  // If switch is ON,
    Serial.write(1);               // send 1 to Processing
  } else {                               // If the switch is not ON,
    Serial.write(0);               // send 0 to Processing
  }
  delay(100);                            // Wait 100 milliseconds
}
1 Like

You are now sending an int instead of a long and only sending a byte (0 to 255) with Serial.write()

When you use Serial.print() with Arduino it is sending the data as a string made of human-readable ASCII text and you can easily deal with this on Processing side and convert to an int.

:slight_smile:

1 Like

Hi,

Thank you.

Now in arduino, I have changed the data type to “int” and instead of serial.print, I’m using serial.write to avoid conversion from Arduino…

But still processing is unable to read and make changes

Please read the references to understand.

I always send Strings from Arduino using Serial.print() and receive them as Strings on Processing side and convert them to data type I require.

:slight_smile:

Sure.
So on arduino side, I should keep it as this

long start = millis();
long total1 = cs_4_2.capacitiveSensor(30);

How should I send string and recieve strings on processing?

I provided examples for you.

I modified your code as follows and it works with the Arduino example I provided:

void serialEvent(Serial myPort) {
  // read the serial buffer:
  String myString = myPort.readStringUntil('\n');
  if (myString != null) {
    myString = trim(myString);
    println(myString);

    String sensors[] = split(myString, ',');
    printArray(sensors);

// Process data from array here.

    }
  }

How you choose to code this is up to you.
This is your project.

:slight_smile:

This is output:

https://processing.org/reference/printArray_.html
Notice the quotes?
That is because it is a String array.

I converted “1” or “0” received to an int (see my previous example) so I could compare int data (0 or 1) in my code.

:slight_smile:

Hello,

This is one of the more difficult concepts for new programmers.
You have to work through it.

Keep it as simple as possible and build on that.
Send “known” data and see if you are receiving that; I did this with my example.

Once you are receiving and can print the data AND know the data type (String, int, long, byte etc) then you can process it and do cool stuff with it!

Happy coding!

:slight_smile:

2 Likes