Week 11: Computer Programming

This week, we focused on computer programming.

We were tasked with sending data to a computer and writing code to display the results. I completed the assignment by following a tutorial on the PHYSCSI 70 website linked here and another tutorial linked on the PHYSCI website. Click here to go to the second tutorial. Documentation and code for both tutorials is provided below.

Tutorial 1: Serial Input to P5.js

The first tutorial involves talking to a p5 sketch over Serial. The instructions were pretty straightforward. I created a new folder, and in it I created the "index.html" and "sketch.js" files by saving the code below into Notepad.

Click here for the code for the "index.html" file

Here is the code for the "script.js" file:



          let serial;                             // variable to hold an instance of the serialport library
          let portName = '/dev/cu.usbmodem1412301';  // fill in your serial port name here
          let inData;                             // for incoming serial data
          let serialDiv;                        // an HTML div to show incoming serial data

          function setup() {
            createCanvas(400, 300);
            createHTML();                       // make some HTML to place incoming data into
            serial = new p5.SerialPort();       // make a new instance of the serialport library
            serial.on('list', printList);       // set a callback function for the serialport list event
            serial.on('connected', serverConnected); // callback for connecting to the server
            serial.on('open', portOpen);        // callback for the port opening
            serial.on('data', serialEvent);     // callback for when new data arrives
            serial.on('error', serialError);    // callback for errors
            serial.on('close', portClose);      // callback for the port closing

            serial.list();                      // list the serial ports
            serial.open(portName);              // open a serial port
          }

          function draw() {
            // black background, white text:
            background(0);
            fill(255);
            // display the incoming serial data as a string:
            text("sensor value: " + inData, 30, 30);
            printData("sensor value: " + inData);
          }
          // get the list of ports:
          function printList(portList) {
            // portList is an array of serial port names
            for (var i = 0; i < portList.length; i++) {
              // Display the list the console:
              console.log(i + " " + portList[i]);
            }
          }

          function serverConnected() {
            console.log('connected to server.');
          }

          function portOpen() {
            console.log('the serial port opened.')
          }

          function serialEvent() {
            // read a byte from the serial port, convert it to a number:
            inData = Number(serial.read());
          }

          function serialError(err) {
            console.log('Something went wrong with the serial port. ' + err);
          }

          function portClose() {
            console.log('The serial port closed.');
          }

          // create some HTML elements in the sketch:
          function createHTML() {
            serialDiv = createElement('p', 'incoming data goes here');
            serialDiv.attribute('aria-label', 'incoming data');
            serialDiv.attribute('aria-role', 'alert');
            serialDiv.attribute('aria-live', 'polite');
            serialDiv.style('color', 'white');
            serialDiv.position(10, 40);
          }

          function printData(inString) {
            // put the input in the serialDiv div:
            serialDiv.html('log: ' + inString);
            // print it to the console as well
           // console.log(inString);
          }

          
And here is the code I uploaded to the microcontroller:


          const int sensorPin = A0;    // analog pin A0

          void setup() {
            // initialize the serial port for communication
            Serial.begin(9600);
          }

          void loop() {
            // read from potentiometer
            int sensorValue = analogRead(sensorPin);
            
            // write the value to p5.js
            Serial.write(sensorValue);
            delay(10);
          }
          

I also downloaded and unzipped "p5.serialcontrol" from this website. This is a separate program that allows us to create a server. With that done, we are ready to talk to a p5 sketch over Serial.

Here is the result:

I did not particularly like the result because the numbers are not consistent and show a wide range every second, but you can see that when I turn the potentiometer all the way a third digit is added to the end of the number, which means that the value is increasing as I turn the potentiometer as expected.

Tutorial 2: Visualization of Serial Input Data to P5.js

For the second tutorial, I followed the instructions and got the following results:

The result from the first tutorial makes a little more sense now. The number ten kept popping up in the display and there was a wide range of numbers every second, and we see that in the graphical representation as well. The blips where we saw three-digit numbers are represented here by the momentary peaks that show when I turn the potentiometer. I am unsure why this was the case and why ten specifically was the baseline, but nonetheless the general trends are what we expected.

Click here for the code for the "index.html" file

Here is the code for the "script.js" file:



        let serial; // variable to hold an instance of the serialport library
        let portName = 'COM5';  // fill in your serial port name here
        let inData;                             // for incoming serial data
         let xPos = 0;                     // x position of the graph

        function setup() {
          serial = new p5.SerialPort(); // make a new instance of the serialport library
          serial.on('list', printList); // set a callback function for the serialport list event
          serial.list(); // list the serial ports
          createCanvas(400, 300);
          background(0x08, 0x16, 0x40);
          serial = new p5.SerialPort();       // make a new instance of the serialport library
          serial.on('list', printList);  // set a callback function for the serialport list event
          serial.on('connected', serverConnected); // callback for connecting to the server
          serial.on('open', portOpen);        // callback for the port opening
          serial.on('data', serialEvent);     // callback for when new data arrives
          serial.on('error', serialError);    // callback for errors
          serial.on('close', portClose);      // callback for the port closing
          serial.list();                      // list the serial ports
          serial.open(portName);              // open a serial port
        }
         
        // get the list of ports:
        function printList(portList) {
          // portList is an array of serial port names
          for (var i = 0; i < portList.length; i++) {
            // Display the list the console:
            console.log(i + portList[i]);
          }

        }

        function serverConnected() {
          console.log('connected to server.');
        }
         
        function portOpen() {
          console.log('the serial port opened.')
        }
         
        function serialEvent() {
          inData = Number(serial.read());
        }
         
        function serialError(err) {
          console.log('Something went wrong with the serial port. ' + err);
        }
         
        function portClose() {
          console.log('The serial port closed.');
        }

        function draw() {
           graphData(inData);
        }

        function graphData(newData) {
          // map the range of the input to the window height:
          var yPos = map(newData, 0, 255, 0, height);
          // draw the line in a pretty color:
          stroke(0xA8, 0xD9, 0xA7);
          line(xPos, height, xPos, height - yPos);
          // at the edge of the screen, go back to the beginning:
          if (xPos >= width) {
            xPos = 0;
            // clear the screen by resetting the background:
            background(0x08, 0x16, 0x40);
          } else {
            // increment the horizontal position for the next reading:
            xPos++;
          }
        }
        

And here is the code I uploaded to the microcontroller:


          void setup() {
            Serial.begin(9600); // initialize serial communications
          }
           
          void loop() {
            // read the input pin:
            int potentiometer = analogRead(A0);                  
            // remap the pot value to fit in 1 byte:
            int mappedPot = map(potentiometer, 0, 1023, 0, 255); 
            // print it out the serial port:
            Serial.write(mappedPot);                             
            // slight delay to stabilize the ADC:
            delay(1);                                            
          }
        

And that is all for this week!

Powered by w3.css

Mohammed Mutaher 2022