Basic DigitalWriteSerial or AnalogWriteSerial arduino example? Solved: Communications/PhysicalPixel.ino

While considering replying to some poster with a problem,
I was looking through the official examples for a basic sketch to do the inverse of these examples:

Maybe some serial communication to control a LED, something like:

const int LedPin=3;

void setup() {
  Serial.begin(115200);
  Serial.println("Enter characters + or - to control a LED.");
  pinMode(LedPin, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    int ch = Serial.read();
    if (ch == '+') {
      Serial.print("On ");
      digitalWrite(LedPin, HIGH);
    }
    else if (ch == '-') {
      Serial.print("Off ");
      digitalWrite(LedPin, LOW);
    }
  }
}

Most of the "Communications" examples on https://docs.arduino.cc/built-in-examples/ look confusingly processing based:

Here's the innocuously named Dimmer:

/*

  Dimmer

  Demonstrates sending data from the computer to the Arduino board, in this case

  to control the brightness of an LED. The data is sent in individual bytes,

  each of which ranges from 0 to 255. Arduino reads these bytes and uses them to

  set the brightness of the LED.

  The circuit:

  - LED attached from digital pin 9 to ground.

  - Serial connection to Processing, Max/MSP, or another serial application

  created 2006

  by David A. Mellis

  modified 30 Aug 2011

  by Tom Igoe and Scott Fitzgerald

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/Dimmer

*/

const int ledPin = 9;      // the pin that the LED is attached to

void setup() {

  // initialize the serial communication:

  Serial.begin(9600);

  // initialize the ledPin as an output:

  pinMode(ledPin, OUTPUT);
}

void loop() {

  byte brightness;

  // check if data has been sent from the computer:

  if (Serial.available()) {

    // read the most recent byte (which will be from 0 to 255):

    brightness = Serial.read();

    // set the brightness of the LED:

    analogWrite(ledPin, brightness);

  }
}

/* Processing code for this example

  // Dimmer - sends bytes over a serial port

  // by David A. Mellis

  // This example code is in the public domain.

  import processing.serial.*;

  Serial port;

  void setup() {

    size(256, 150);

    println("Available serial ports:");

    // if using Processing 2.1 or later, use Serial.printArray()

    println(Serial.list());

    // Uses the first port in this list (number 0). Change this to select the port

    // corresponding to your Arduino board. The last parameter (e.g. 9600) is the

    // speed of the communication. It has to correspond to the value passed to

    // Serial.begin() in your Arduino sketch.

    port = new Serial(this, Serial.list()[0], 9600);

    // If you know the name of the port used by the Arduino board, you can specify

    // it directly like this.

    //port = new Serial(this, "COM1", 9600);

  }

  void draw() {

    // draw a gradient from black to white

    for (int i = 0; i < 256; i++) {

      stroke(i);

      line(i, 0, i, 150);

    }

    // write the current X-position of the mouse to the serial port as

    // a single byte

    port.write(mouseX);

  }

*/

/* Max/MSP v5 patch for this example

----------begin_max5_patcher----------

1008.3ocuXszaiaCD9r8uhA5rqAeHIa0aAMaAVf1S6hdoYQAsDiL6JQZHQ2M

YWr+2KeX4vjnjXKKkKhhiGQ9MeyCNz+X9rnMp63sQvuB+MLa1OlOalSjUvrC

ymEUytKuh05TKJWUWyk5nE9eSyuS6jesvHu4F4MxOuUzB6X57sPKWVzBLXiP

xZtGj6q2vafaaT0.BzJfjj.p8ZPukazsQvpfcpFs8mXR3plh8BoBxURIOWyK

rxspZ0YI.eTCEh5Vqp+wGtFXZMKe6CZc3yWZwTdCmYW.BBkdiby8v0r+ST.W

sD9SdUkn8FYspPbqvnBNFtZWiUyLmleJWo0vuKzeuj2vpJLaWA7YiE7wREui

FpDFDp1KcbAFcP5sJoVxp4NB5Jq40ougIDxJt1wo3GDZHiNocKhiIExx+owv

AdOEAksDs.RRrOoww1Arc.9RvN2J9tamwjkcqknvAE0l+8WnjHqreNet8whK

z6mukIK4d+Xknv3jstvJs8EirMMhxsZIusET25jXbX8xczIl5xPVxhPcTGFu

xNDu9rXtUCg37g9Q8Yc+EuofIYmg8QdkPCrOnXsaHwYs3rWx9PGsO+pqueG2

uNQBqWFh1X7qQG+3.VHcHrfO1nyR2TlqpTM9MDsLKNCQVz6KO.+Sfc5j1Ykj

jzkn2jwNDRP7LVb3d9LtoWBAOnvB92Le6yRmZ4UF7YpQhiFi7A5Ka8zXhKdA

4r9TRGG7V4COiSbAJKdXrWNhhF0hNUh7uBa4Mba0l7JUK+omjDMwkSn95Izr

TOwkdp7W.oPRmNRQsiKeu4j3CkfVgt.NYPEYqMGvvJ48vIlPiyzrIuZskWIS

xGJPcmPiWOfLodybH3wjPbMYwlbFIMNHPHFOtLBNaLSa9sGk1TxMzCX5KTa6

WIH2ocxSdngM0QPqFRxyPHFsprrhGc9Gy9xoBjz0NWdR2yW9DUa2F85jG2v9

FgTO4Q8qiC7fzzQNpmNpsY3BrYPVJBMJQ1uVmoItRhw9NrVGO3NMNzYZ+zS7

3WTvTOnUydG5kHMKLqAOjTe7fN2bGSxOZDkMrBrGQ9J1gONBEy0k4gVo8qHc

cxmfxVihWz6a3yqY9NazzUYkua9UnynadOtogW.JfsVGRVNEbWF8I+eHtcwJ

+wLXqZeSdWLo+FQF6731Tva0BISKTx.cLwmgJsUTTvkg1YsnXmxDge.CDR7x

D6YmX6fMznaF7kdczmJXwm.XSOOrdoHhNA7GMiZYLZZR.+4lconMaJP6JOZ8

ftCs1YWHZI3o.sIXezX5ihMSuXzZtk3ai1mXRSczoCS32hAydeyXNEu5SHyS

xqZqbd3ZLdera1iPqYxOm++v7SUSz

-----------end_max5_patcher-----------
*/

Is there a basic AnalogWriteSerial-like example such as this?

const int LedPin = 3;

void setup() {
  Serial.begin(115200);
  Serial.println("Enter characters 0 through 9 to control a LED with analogWrite().");
  pinMode(LedPin, OUTPUT);
}

void loop() {
  if (Serial.available()) {
    int ch = Serial.read();
    switch (ch) {
      case '0': analogWrite(LedPin, 0); break;
      case '1': analogWrite(LedPin, 1); break;
      case '2': analogWrite(LedPin, 2); break;
      case '3': analogWrite(LedPin, 4); break;
      case '4': analogWrite(LedPin, 8); break;
      case '5': analogWrite(LedPin, 16); break;
      case '6': analogWrite(LedPin, 32); break;
      case '7': analogWrite(LedPin, 64); break;
      case '8': analogWrite(LedPin, 128); break;
      case '9': analogWrite(LedPin, 255); break;
      default:
        ; // ignore other characters
    }
  }
}

image
https://wokwi.com/projects/395348450321670145

Am I missing an obvious built-in example?

Here's a modification of File/Examples/Communication/ASCII Table to react to Serial.read()s:

/*
  ASCII table Serial

  Modified from File/Examples/Communication/ASCII Table 
  for https://forum.arduino.cc/t/basic-digitalwriteserial-or-analogwriteserial-arduino-examples/1248538/2?u=davex


  Prints out byte values in all possible formats:
  - as raw binary values
  - as ASCII-encoded decimal, hex, octal, and binary values

  For more on ASCII, see http://www.asciitable.com and http://en.wikipedia.org/wiki/ASCII

  The circuit: No external hardware needed.

  created 2006
  by Nicholas Zambetti <http://www.zambetti.com>
  modified 9 Apr 2012
  by Tom Igoe

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/ASCIITable

*/

void setup() {
  //Initialize serial and wait for port to open:
  Serial.begin(9600);
  while (!Serial) {
    ;  // wait for serial port to connect. Needed for native USB port only
  }

  // prints title with ending line break
  Serial.println("Serial.read() to ASCII Table ~ Character translation");
  Serial.println("Send a character to the Arduino and see the translation");

}

// first visible ASCIIcharacter '!' is number 33:
int thisByte = 33;
// you can also write ASCII characters in single quotes.
// for example, '!' is the same as 33, so you could also use this:
// int thisByte = '!';

void loop() {
  if (Serial.available()) {
    thisByte = Serial.read();

    // prints value unaltered, i.e. the raw binary version of the byte.
    // The Serial Monitor interprets all bytes as ASCII, so 33, the first number,
    // will show up as '!'
    Serial.write(thisByte);

    Serial.print(", dec: ");
    // prints value as string as an ASCII-encoded decimal (base 10).
    // Decimal is the default format for Serial.print() and Serial.println(),
    // so no modifier is needed:
    Serial.print(thisByte);
    // But you can declare the modifier for decimal if you want to.
    // this also works if you uncomment it:

    // Serial.print(thisByte, DEC);


    Serial.print(", hex: ");
    // prints value as string in hexadecimal (base 16):
    Serial.print(thisByte, HEX);

    Serial.print(", oct: ");
    // prints value as string in octal (base 8);
    Serial.print(thisByte, OCT);

    Serial.print(", bin: ");
    // prints value as string in binary (base 2) also prints ending line break:
    Serial.println(thisByte, BIN);

  }
}

image
https://wokwi.com/projects/395348223162336257

Outside of the Arduino built-in examples, one can find the excellent:

With @Robin2's most basic serial input example:

// Example 1 - Receiving single characters

char receivedChar;
boolean newData = false;

void setup() {
    Serial.begin(9600);
    Serial.println("<Arduino is ready>");
}

void loop() {
    recvOneChar();
    showNewData();
}

void recvOneChar() {
    if (Serial.available() > 0) {
        receivedChar = Serial.read();
        newData = true;
    }
}

void showNewData() {
    if (newData == true) {
        Serial.print("This just in ... ");
        Serial.println(receivedChar);
        newData = false;
    }
}

Why more examples? All problems have a first stage receiving a digital value from Serial, and a second stage sending that value by e.g. analogWrite(). You'll find enough examples for receiving data from some input device and for sending data to some output device.

If you can not split a task into such basic steps then you should change your hobby.

Even though they aren't best practices, I like pointing arduino folks at Arduino documentation/examples for troubleshooting their hardware.

In the specific serial case, someone recently had a large, copied, broken program that they were trying to make work over bluetooth, and I was looking for an Arduino built-in example in which the device recieved and reacted to a serial input character.

Is one of the built-in examples good at that?

As ever:

  1. receive
  2. react
1 Like

Reading through all the Communications examples, the "PhysicalPixel" is the example I was looking for:

https://docs.arduino.cc/built-in-examples/communication/PhysicalPixel/

/*
  Physical Pixel

  An example of using the Arduino board to receive data from the computer. In
  this case, the Arduino boards turns on an LED when it receives the character
  'H', and turns off the LED when it receives the character 'L'.

  The data can be sent from the Arduino Serial Monitor, or another program like
  Processing (see code below), Flash (via a serial-net proxy), PD, or Max/MSP.

  The circuit:
  - LED connected from digital pin 13 to ground through 220 ohm resistor

  created 2006
  by David A. Mellis
  modified 30 Aug 2011
  by Tom Igoe and Scott Fitzgerald

  This example code is in the public domain.

  https://www.arduino.cc/en/Tutorial/BuiltInExamples/PhysicalPixel
*/

const int ledPin = 13;  // the pin that the LED is attached to
int incomingByte;       // a variable to read incoming serial data into

void setup() {
  // initialize serial communication:
  Serial.begin(9600);
  // initialize the LED pin as an output:
  pinMode(ledPin, OUTPUT);
}

void loop() {
  // see if there's incoming serial data:
  if (Serial.available() > 0) {
    // read the oldest byte in the serial buffer:
    incomingByte = Serial.read();
    // if it's a capital H (ASCII 72), turn on the LED:
    if (incomingByte == 'H') {
      digitalWrite(ledPin, HIGH);
    }
    // if it's an L (ASCII 76) turn off the LED:
    if (incomingByte == 'L') {
      digitalWrite(ledPin, LOW);
    }
  }
}

/* Processing code for this example

  // Mouse over serial

  // Demonstrates how to send data to the Arduino I/O board, in order to turn ON
  // a light if the mouse is over a square and turn it off if the mouse is not.

  // created 2003-4
  // based on examples by Casey Reas and Hernando Barragan
  // modified 30 Aug 2011
  // by Tom Igoe
  // This example code is in the public domain.

  import processing.serial.*;

  float boxX;
  float boxY;
  int boxSize = 20;
  boolean mouseOverBox = false;

  Serial port;

  void setup() {
    size(200, 200);
    boxX = width / 2.0;
    boxY = height / 2.0;
    rectMode(RADIUS);

    // List all the available serial ports in the output pane.
    // You will need to choose the port that the Arduino board is connected to
    // from this list. The first port in the list is port #0 and the third port
    // in the list is port #2.
    // if using Processing 2.1 or later, use Serial.printArray()
    println(Serial.list());

    // Open the port that the Arduino board is connected to (in this case #0)
    // Make sure to open the port at the same speed Arduino is using (9600bps)
    port = new Serial(this, Serial.list()[0], 9600);
  }

  void draw() {
    background(0);

    // Test if the cursor is over the box
    if (mouseX > boxX - boxSize && mouseX < boxX + boxSize &&
        mouseY > boxY - boxSize && mouseY < boxY + boxSize) {
      mouseOverBox = true;
      // draw a line around the box and change its color:
      stroke(255);
      fill(153);
      // send an 'H' to indicate mouse is over square:
      port.write('H');
    }
    else {
      // return the box to its inactive state:
      stroke(153);
      fill(153);
      // send an 'L' to turn the LED off:
      port.write('L');
      mouseOverBox = false;
    }

    // Draw the box
    rect(boxX, boxY, boxSize, boxSize);
  }

*/

/* Max/MSP version 5 patch to run with this example:

  ----------begin_max5_patcher----------
  1672.3oc2ZszaaiCD9ryuBBebQVCQRYao8xhf1cQCPVfBzh8RRQ.sDsM2HSZ
  HQmlzh9eu7gjsjsEk7y0oWjiHoHm4aluYHGlueUmtiDuPy5B9Cv8fNc99Uc5
  XZR2Pm726zcF4knDRlYXciDylQ4xtWa6SReQZZ+iSeMiEQR.ej8BM4A9C7OO
  kkAlSjQSAYTdbFfvA27o2c6sfO.Doqd6NfXgDHmRUCKkol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  CvM7HI14Mpje6YRxHOSieTsJpvJORjxT1nERK6s7YTN7sr6rylNwf5zMiHI4
  meZ4rTYt2PpVettZERbjJ6PjfqN2loPSrUcusH01CegsGEE5467rnCdqT1ES
  QxtCvFq.cvGz+BaAHXKzRSfP+2Jf.KCvj5ZLJRAhwi+SWHvPyN3vXiaPn6JR
  3eoA.0TkFhTvpsDMIrL20nAkCI4EoYfSHAuiPBdmJRyd.IynYYjIzMvjOTKf
  3DLvnvRLDLpWeEOYXMfAZqfQ0.qsnlUdmA33t8CNJ7MZEb.u7fiZHLYzDkJp
  R7CqEVLGN75U+1JXxFUY.xEEBcRCqhOEkz2bENEWnh4pbh0wY25EefbD6EmW
  UA6Ip8wFLyuFXx+Wrp8m6iff1B86W7bqJO9+mx8er4E3.abCLrYdA16sBuHx
  vKT6BlpIGQIhL55W7oicf3ayv3ixQCm4aQuY1HZUPQWY+cASx2WZ3f1fICuz
  vj5R5ZbM1y8gXYN4dIXaYGq4NhQvS5MmcDADy+S.j8CQ78vk7Q7gtPDX3kFh
  3NGaAsYBUAO.8N1U4WKycxbQdrWxJdXd10gNIO+hkUMmm.CZwknu7JbNUYUq
  0sOsTsI1QudDtjw0t+xZ85wWZd80tMCiiMADNX4UzrcSeK23su87IANqmA7j
  tiRzoXi2YRh67ldAk79gPmTe3YKuoY0qdEDV3X8xylCJMTN45JIakB7uY8XW
  uVr3PO8wWwEoTW8lsfraX7ZqzZDDXCRqNkztHsGCYpIDDAOqxDpMVUMKcOrp
  942acPvx2NPocMC1wQZ8glRn3myTykVaEUNLoEeJjVaAevA4EAZnsNgkeyO+
  3rEZB7f0DTazDcQTNmdt8aACGi1QOWnMmd+.6YjMHH19OB5gKsMF877x8wsJ
  hN97JSnSfLUXGUoj6ujWXd6Pk1SAC+Pkogm.tZ.1lX1qL.pe6PE11DPeMMZ2
  .P0K+3peBt3NskC
  -----------end_max5_patcher-----------

*/

PhysicalPixel.ino does what I want, but has a terrible name and includes a lot of distracting info and warnings about dependence on processing.

Yes. This thread is more a complaint about the documentation & how you find Arduino' sketch to:

  1. receive (serial character)
  2. react (pin-wise)

The Arduino forum is for writing code,
Google is for finding code.

What are arduino's built in examples for?

I'd like to be able use them to say something like:

Are you sure that bluetooth setup of yours is working?

Use the IDE's File/Examples/Communication/PhysicalPixel example to check if your bluetooth is working.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.