Ubidots Community

Combining my own coding to example raspberry pi coding

hi , i new here and novice in python language. I already tried multiple times by combining 2 coding for installing machine in the device. can you help me ? im using adc3008 in myproject. here my coding that i tried success in python output shell but failed install at ubidots device management .

import time
import requests
import math
import random
import os
import RPi.GPIO as GPIO
import json

GPIO.setmode(GPIO.BCM)
DEBUG = 1

TOKEN = “BBFF-8dtojEOmf8VC4ywZyQJ7u0J1owPJPd” # Put your TOKEN here
DEVICE_LABEL = “machine4” # Put your device label here
VARIABLE_LABEL_1 = “pressure” # Put your first variable label here

def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 7) or (adcnum < 0)):
return -1
GPIO.output(cspin, True)

    GPIO.output(clockpin, False)  
    GPIO.output(cspin, False)     

    commandout = adcnum
    commandout |= 0x18  
    commandout <<= 3    
    for i in range(5):
            if (commandout & 0x80):
                    GPIO.output(mosipin, True)
            else:
                    GPIO.output(mosipin, False)
            commandout <<= 1
            GPIO.output(clockpin, True)
            GPIO.output(clockpin, False)

    adcout = 0
   
    for i in range(12):
            GPIO.output(clockpin, True)
            GPIO.output(clockpin, False)
            adcout <<= 1
            if (GPIO.input(misopin)):
                    adcout |= 0x1

    GPIO.output(cspin, True)
    
    adcout >>= 1       
    return adcout

SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25

GPIO.setup(SPIMOSI, GPIO.OUT)
GPIO.setup(SPIMISO, GPIO.IN)
GPIO.setup(SPICLK, GPIO.OUT)
GPIO.setup(SPICS, GPIO.OUT)

potentiometer_adc = 0;

last_read = 0
tolerance = 5

while True:
pressure_changed = False

    pressure = readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
    
    pressure_adjust = abs(pressure - last_read)
    
    if ( pressure_adjust > tolerance ):
           pressure_changed = True
           
           
    if  ( pressure_changed ):
            set_volume = pressure / 10.24           
            set_volume = round(set_volume)          
            set_volume = int(set_volume)           

            print ('Volume = {volume}%' .format(volume = set_volume))
            set_vol_cmd = 'sudo amixer cset numid=1 -- {volume}% > /dev/null' .format(volume = set_volume)
            os.system(set_vol_cmd)  # set volume

def build_payload(variable_1):

    payload= {variable_1: set_volume}
          
    last_read = pressure
    time.sleep(0.5)

    return payload

def post_request(payload):
# Creates the headers for the HTTP requests
url = “http://industrial.api.ubidots.com
url = “{}/api/v1.6/devices/{}”.format(url, DEVICE_LABEL)
headers = {“X-Auth-Token”: TOKEN, “Content-Type”: “application/json”}

# Makes the HTTP requests
status = 400
attempts = 0
while status >= 400 and attempts <= 5:
    req = requests.post(url=url, headers=headers, json=payload)
    status = req.status_code
    attempts += 1
    time.sleep(1)

# Processes results
if status >= 400:
    print("[ERROR] Could not send data after 5 attempts, please check \
        your token credentials and internet connection")
    return False

print("[INFO] request made properly, your device is updated")
return True

def main():
payload = build_payload(VARIABLE_LABEL_1,)

print("[INFO] Attemping to send data")
post_request(payload)
print("[INFO] finished")

if name == ‘main’:
while (True):
main()
time.sleep(1)

DELAY = 1 # Delay in seconds

for my own coding without substitute in example code;

import time
import os
import RPi.GPIO as GPIO
import json

GPIO.setmode(GPIO.BCM)
DEBUG = 1

read SPI data from MCP3008 chip, 8 possible adc’s (0 thru 7)

def readadc(adcnum, clockpin, mosipin, misopin, cspin):
if ((adcnum > 7) or (adcnum < 0)):
return -1
GPIO.output(cspin, True)

    GPIO.output(clockpin, False)  # start clock low
    GPIO.output(cspin, False)     # bring CS low

    commandout = adcnum
    commandout |= 0x18  # start bit + single-ended bit
    commandout <<= 3    # we only need to send 5 bits here
    for i in range(5):
            if (commandout & 0x80):
                    GPIO.output(mosipin, True)
            else:
                    GPIO.output(mosipin, False)
            commandout <<= 1
            GPIO.output(clockpin, True)
            GPIO.output(clockpin, False)

    adcout = 0
    # read in one empty bit, one null bit and 10 ADC bits
    for i in range(12):
            GPIO.output(clockpin, True)
            GPIO.output(clockpin, False)
            adcout <<= 1
            if (GPIO.input(misopin)):
                    adcout |= 0x1

    GPIO.output(cspin, True)
    
    adcout >>= 1       # first bit is 'null' so drop it
    return adcout

change these as desired - they’re the pins connected from the

SPI port on the ADC to the Cobbler

SPICLK = 18
SPIMISO = 23
SPIMOSI = 24
SPICS = 25

set up the SPI interface pins

GPIO.setup(SPIMOSI, GPIO.OUT)
GPIO.setup(SPIMISO, GPIO.IN)
GPIO.setup(SPICLK, GPIO.OUT)
GPIO.setup(SPICS, GPIO.OUT)

10k trim pot connected to adc #0

potentiometer_adc = 0;

last_read = 0 # this keeps track of the last potentiometer value
tolerance = 5 # to keep from being jittery we’ll only change
# volume when the pot has moved more than 5 ‘counts’

while True:
# we’ll assume that the pot didn’t move
pressure_changed = False

    # read the analog pin
    pressure = readadc(potentiometer_adc, SPICLK, SPIMOSI, SPIMISO, SPICS)
    # how much has it changed since the last read?
    pressure_adjust = abs(pressure - last_read)

  

    if ( pressure_adjust > tolerance ):
           pressure_changed = True
           
   
           
    if  ( pressure_changed ):
            set_volume = pressure / 10.24           # convert 10bit adc0 (0-1024) trim pot read into 0-100 volume level
            set_volume = round(set_volume)          # round out decimal value
            set_volume = int(set_volume)            # cast volume as integer

            print ('Volume = {volume}%' .format(volume = set_volume))
            set_vol_cmd = 'sudo amixer cset numid=1 -- {volume}% > /dev/null' .format(volume = set_volume)
            os.system(set_vol_cmd)  # set volume

          

            # save the potentiometer reading for the next loop
            last_read = pressure

    # hang out and do nothing for a half second
    time.sleep(0.5)

output_string = ‘{“Volume = {volume}%” : Volume = {volume}%}’

output_dict = json.load(output_string)

print(json.dumps(output_dict,indent=1,sort_keys= True))

please can you help me ??

Hi @azsyahirah,

Sending all of your code just as you did means that you’d be expecting someone in the community to actually give you a whole new script already working in return, but that’s kind of hard. Instead, the community forum is intended to solved specific questions. For example, my script si returning a 400 error response code when I try to send data to Ubidots, or my SPI analog reading section is not working well and it gives me this or that error.

With that in mind, here are my recommendation so ppl here can better help you:

  1. Test each section of your code: reading the analog ports in the adc 3008, printing out the results to check everything is ok, checking if the volume does change and then, attempt sending the data to Ubidots making sure that you understand that portion of the code and the expected data format of Ubidots API.

  2. Once you do that and still have issues, post the specific portion of the code given you trouble, and share, in detail, which is the error you’re getting.

  3. Although ppl here can usually help in general terms, some questions that are outside Ubidots Community Forum scope would be better handled in other Forums, say Stack Overflow, Adafriut. As an example, I did a quick search about the adc 3008 and Python and found a package that could possible make your life easier (note that it is only supported up to (Python v3.4).

  4. Make sure all of your code is wrapped in the code snippet format, that will make the reading easier.

–David