1

I'm pretty newbie to C++. I'm trying to write a simple, workable code for interfacing my potentiometer and MCP3008 with my raspberry pi. I've written this python script which works nicely. However I also read that writing code in C/C++ makes the code run significantly faster and ideally I'd like to start porting my code to C++. Any help is greatly appreciated!

#!/usr/bin/env python2.7
# Simple example of reading the MCP3008 analog input channels and printing
# them all out.
import time
import sys

# Import SPI library (for hardware SPI) and MCP3008 library.
import Adafruit_GPIO.SPI as SPI
import Adafruit_MCP3008

# a class used to control the MCP3008 values
class Flex_Sensors():
    def __init__(self):
        software=1

        # Run using software SPI configuration:
        if software==1:

            CLK  = 11
            MOSI = 10
            MISO = 9
            CEO_mcp_1   = 22
            CEO_mcp_2   = 27

            #the ones provided by adafruit
            #~ CLK=18
            #~ MOSI =24
            #~ MISO=23
            #~ CEO=25

            self.mcp_1 = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CEO_mcp_1, miso=MISO, mosi=MOSI)
            self.mcp_2 = Adafruit_MCP3008.MCP3008(clk=CLK, cs=CEO_mcp_2, miso=MISO, mosi=MOSI)

        # unused Hardware SPI configuration
        elif software==0:
            raise NotImplementedError("Software condition not implemented")

            SPI_PORT   = 0
            SPI_DEVICE = 0

            self.mcp_1 = Adafruit_MCP3008.MCP3008(spi=SPI.SpiDev(SPI_PORT, SPI_DEVICE))

    # The read_adc function will get the value of the specified channel of mcp_1 (0-7).
    def read_adc_1(self,i):
        return self.mcp_1.read_adc(i)
    
    # The read_adc function will get the value of the specified channel mcp_2 (0-7).
    def read_adc_2(self,i):

        return self.mcp_2.read_adc(i)

    def WeightValues(self,oldValue,newValue):
        
        if (oldValue == 0): 
            return newValue

        oldWeight = 0.9
        newWeight = (1-oldWeight)

        oldValueWeighted = oldValue * oldWeight
        newValueWeighted = newValue * newWeight

        addedValues = oldValueWeighted+newValueWeighted
        return int(addedValues)

if __name__ == "__main__":
    potentiometer_list=Flex_Sensors()
    print('Reading MCP3008 values, press Ctrl-C to quit...')
    
    # Print nice channel column headers.
    print(('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*list(range(8)))))
    print(('-' * 57))

    values_1 = [0] * 8
    values_2 = [0] * 8

    try:

        while True:
            # Read all the ADC channel values in a list.
            for i in range(8):
                
                #~ values[i] = mcp.read_adc(i)
                
                values_1[i] = potentiometer_list.read_adc_1(i)
                values_2[i] = potentiometer_list.read_adc_2(i)

            # skip one line for each print
            # for i in range(2):
                # #back to previous lines and clear line
                # sys.stdout.write("\033[F\033[K")


            mcp1_printout = ('mcp1:| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} '.format(*values_1))
            mcp2_printout = ('mcp2:| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values_2))
            
            print(mcp1_printout,"|||| ",mcp2_printout)
            
            # # Print the ADC values.
            # print(('mcp1:| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values_1)))
            # print(('mcp2:| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values_2)))
            
            

            time.sleep(0.05)
        time.sleep(2)

    except KeyboardInterrupt:
        print ('KeyboardInterrupt exception is caught')
5
  • Why are you using an obsolete Python V2? It isn't even included in current Raspberry Pi OS ?
    – Milliways
    Nov 17, 2022 at 11:18
  • 1
    Porting MCP3008 will NOT make it run faster (unless you are looking at <1% savings) because it is limited by the convert time limitations of the ADC.
    – Milliways
    Nov 17, 2022 at 11:22
  • Despite its popularity Adafruit DOES NOT produce great code. There are plenty of better exiting open source libraries in Python and C. If you want something better (and easier to understand) don't start with Adafruit.
    – Milliways
    Nov 17, 2022 at 11:26
  • The code runs fine even in python 3. But I'm interested in those other alternatives you mentioned. Could you please share an example for each of those libraries? Thanks in advance. Nov 17, 2022 at 11:28
  • 1
    If you are a c beginner I suggest you don't start with SPI which is difficult for an experienced programmer and the MCP3008 isn't the easiest chip to program.
    – Milliways
    Nov 17, 2022 at 22:21

2 Answers 2

1

Your premise is wrong. Rewriting the Python code in C++ will not make the code run significantly faster.

All the Python functions you call are probably actually written in C.

All that will speed up is the little bit of Python outside the function calls. Any time saving will be swamped by the time taken by the rest of the code.

0

https://gpiozero.readthedocs.io/en/v1.6.2/api_spi.html?highlight=mcp3008#gpiozero.MCP3008.channel is probably the easiest. It has a number of examples.

There are examples using the SPI kernel driver which I have used (but don't have links to hand)

I use my own c library pi-gpio for SPI support and have a MCP3002 example https://github.com/Milliways2/pi-gpio/blob/main/examples/aread.c which uses the SPI kernel driver (but don't recommend as a starting point - this was mainly to test SPI interface).

I am sure there is pigpio code http://abyz.me.uk/rpi/pigpio/examples.html

There is WiringPi code (but as this is deprecated)

https://tutorials-raspberrypi.com/mcp3008-read-out-analog-signals-on-the-raspberry-pi/ is a simple example using spidev

1
  • Thank you, that is very useful! Some of those links I already know but for once it's good to see C and C++ libraries! Nov 17, 2022 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.