Hoang Bach in Discussions
上次活动时间: 2024-4-16

Hey, so I have a simple air quality measurement IoT system but the values are not arriving in my ThingSpeak channel. I use basic tutorials for it and tried some kind of variation but the code is so simple, I don't see any problem code-wise. Maybe someone here can help me? I am working with a Raspberry Pi 3 and the following code for a SDS011 sensor: import time from datetime import datetime import paho.mqtt.publish as publish import paho.mqtt.client as mqtt import psutil from sds011 import * import aqi sensor = SDS011("/dev/ttyUSB0", use_query_mode=True) def get_data(n=3): sensor.sleep(sleep=False) pmt_2_5 = 0 pmt_10 = 0 time.sleep(10) for i in range (n): x = sensor.query() pmt_2_5 = pmt_2_5 + x[0] pmt_10 = pmt_10 + x[1] time.sleep(2) pmt_2_5 = round(pmt_2_5/n, 1) pmt_10 = round(pmt_10/n, 1) sensor.sleep(sleep=True) time.sleep(2) return pmt_2_5, pmt_10 def conv_aqi(pmt_2_5, pmt_10): aqi_2_5 = aqi.to_iaqi(aqi.POLLUTANT_PM25, str(pmt_2_5)) aqi_10 = aqi.to_iaqi(aqi.POLLUTANT_PM10, str(pmt_10)) return aqi_2_5, aqi_10 def save_log(): with open("/YOUR PATH/air_quality.csv", "a") as log: dt = datetime.now() log.write("{},{},{},{},{}\n".format(dt, pmt_2_5, aqi_2_5, pmt_10, aqi_10)) log.close() channelID = "YOUR CHANNEL ID" apiKey = "YOUR WRITE KEY" clientID = "YOUR CLIENT ID" tUsername = "YOUR USERNAME" tPassword = "YOUR PASSWORD" topic = "channels/" + channelID + "/publish/" + apiKey mqttHost = "mqtt3.thingspeak.com" tTransport = "tcp" tPort = 1883 tTLS = None tProtocol = mqtt.MQTTv311 while True: pmt_2_5, pmt_10 = get_data() aqi_2_5, aqi_10 = conv_aqi(pmt_2_5, pmt_10) print ("AQI2.5 =", aqi_2_5," AQI10 =", aqi_10) tPayload = "field1=" + str(pmt_2_5)+ "&field2=" + str(aqi_2_5)+ "&field3=" + str(pmt_10)+ "&field4=" + str(aqi_10) try: publish.single(topic, payload=tPayload, hostname=mqttHost, port=tPort, client_id=clientID, auth={'username':tUsername, 'password':tPassword}, tls=tTLS, transport=tTransport, protocol=tProtocol) print ("[INFO] Published data") save_log() time.sleep(60) except Exception as e: print ("[INFO] Failure in sending data") print (e) time.sleep(60) Publish via Paho-MQTT publish.single but data is not arriving? Have a look at the documentation for MQTT and the provided examples. You are using syntax from the old broker, which was replaced in July 2021 and deprecated in April. Here is the new publish syntax for publish. The topic you are publishing to is incorrect. Take a look at the examples Christopher has linked to. So is this page in your documentation outdated then: https://se.mathworks.com/help/thingspeak/use-raspberry-pi-board-that-runs-python-websockets-to-publish-to-a-channel.html? Is there any way to use paho_mqtt to publish data in ThingSpeak or is the only option to use MQTT X? The code you reference should work. You can definitely still use paho, im pretty sure ive done it already on a pi. Just set up am MQTT device on the thingSpeak web UI, enable publishing from that device to your channel of interest, and copy the credentials to the pi. Can you tell us where it is failing for you? Now I found it: one extra /. Had f"channels/{channel_ID}/publish/ instead of f"channels/{channel_ID}/publish Damn, it was hard to find it. :P Thanks for help anyway! Ive had that one before, sorry I didnt look close enough to see that. We appreciate you sharing the solution! If its working, can you share an interesting plot from your monitor to inspire others who see this discussion? publish mqtt paho-mqtt air-quality sds011 raspberry pi 3
Milan Tomin in MATLAB Answers
上次活动时间: 2024-4-8

Having a bizarre problem subscribing to topic with sim7600 hat on raspberry pi. When i try subscribing i get: the following: OK CMQTTSUB: 0,6 CMQTTCONNLOST: 0,1. Code 6 in the CMQTTSUB means failed to receive message. Code 0 in CMQTTCONNLOST means socket closed passively. Why tho? Mqtt actions with sim7600 such as Acquire client, connect, and even publish works without any difficulties in the same project, sub however does not. I'm using thingspeak as a broker, and have tried broker.emqx.io to subscribe to and... it worked without any problem. Has anyone had any similar problem? I've tried subscribing to one or multiple fields, still no dice. Topic strings i've tried: channels/2429193/subscribe/fields/field1 channels/2429193/subscribe/fields/+ channels/2429193/subscribe I provide the code: def setup(self): isSerial2Available = True self.SentMessage('AT+CMQTTDISC=0,60\r\n') time.sleep(0.5) self.SentMessage('AT+CMQTTREL=0\r\n') time.sleep(0.5) self.SentMessage('AT+CMQTTSTART\r\n') # Enable MQTT service. time.sleep(1) connect_cmd = 'AT+CMQTTACCQ=0,"'+ self.ID +'",0,4' # Apply for MQTT client with client ID. self.SentMessage(connect_cmd + '\r\n') time.sleep(1) connect_cmd = 'AT+CMQTTCONNECT=0,"tcp://mqtt3.thingspeak.com",60,1,"'+ self.username +'","'+ self.password +'"' # Send MQTT connection request to the server. self.SentMessage(connect_cmd + '\r\n') time.sleep(2) dataLength = str(len(self.pub)) connect_cmd = "AT+CMQTTTOPIC=0,{}".format(dataLength) # Publish to the inputed topic. self.input_message(connect_cmd, self.pub) time.sleep(1.5) dataLength = str(len('channels/2429193/subscribe')) connect_cmd = "AT+CMQTTSUBTOPIC=0,{},0".format(dataLength) # Subscribe to the inputed topic. self.input_message(connect_cmd, "channels/2429193/subscribe") time.sleep(0.5) self.SentMessage('AT+CMQTTSUB=0\r\n') def SentMessage(self, p_char): global isSerial2Available towrite = p_char.encode() self.ser.write(towrite) time.sleep(1) response = self.ser.read_all().decode() print(response) responses = response.split('\r\n') for resp in responses: if "+CREG: 0," in resp: status = int(resp.split("+CREG: 0,")[1]) # Check if connected to the network. if status == 6: isSerial2Available = False print("\nNetWork Connected") elif "+CMQTTCONNECT: 0," in resp: status = int(resp.split("+CMQTTCONNECT: 0,")[1]) # Check if the client is connected. if status == 0: isSerial2Available = False print("\nMqtt Connected") elif resp == "+CMQTTSTART: 23": isSerial2Available = False print("\nMqtt is already Connected") def input_message(self, p_char, p_data): global startSent self.ser.write(p_char.encode() + b'\r\n') time.sleep(0.2) encodedstr = p_data.encode() + b'\r\n' self.ser.write(p_data.encode() + b'\r\n') time.sleep(1) response = self.ser.read_all().decode() responses = response.split('\r\n') for resp in responses: if "+CMQTTSUB: 0," in resp: status = int(resp.split("+CMQTTSUB: 0,")[1]) if status == 0: print("\nSubTopic Sub") startSent = True self.subThreadStart() def publishData(self, updateMsn): dataLength = str(len(self.pub)) connect_cmd = "AT+CMQTTTOPIC=0,{}".format(dataLength) # Publish to the inputed topic. self.input_message(connect_cmd, self.pub) dataLength = str(len(str(updateMsn))) connect_cmd = "AT+CMQTTPAYLOAD=0,{}".format(dataLength) # Input the publish message self.input_message(connect_cmd, str(updateMsn)) time.sleep(0.5) self.ser.write(b'AT+CMQTTPUB=0,0,120\r\n')
Ron in MATLAB Answers
上次活动时间: 2023-6-29

I work with many schools in townships with limited to no internet access. This means that these learners are excluded from using such wonderful tools as Thingspeak. Is there a site to assist in setting up such a server as I was only able to access one for Ubuntu 12 and Ubuntu 16 which require software from outdated sites?
HEMANTH KUMAR REDDY in Discussions
上次活动时间: 2023-2-21

I am sending my sensor readings to thingspeak channel using raspberrry pi board but i dont know how can we send some instruction back to the raspberry pi board to control an LED or Motor or some other things. Can anyone provide some information about this? How to send some inputs to a raspberry pi board from thingspeak There are a few methods. One polling methods is to use a channel to indicate the state you want the device to be in and have the device read that channel continuously. The cheer lights examples are a good demo this kind of process. (for arduino c here, no Rpi) Second polling method you can use is Talkback, which creates and stores a command list that your device can consume. The last method is MQTT subsccribe, where the device can subscribe to a channel and ThingSpeak will push channel updates to the device. All methods are accesible via Pi, I probably reccomend the third. This example shows publish in RPi, you can adapt for subscribe. If you created a REST interface on you PI, you could also use MATLAB webread and webwrite in ThingSpeak to send data to your device, but that is the most complex method. thingspeak raspberrypi iot control things sending instructions back to t
Mei Sing Wang in MATLAB Answers
上次活动时间: 2022-8-3

Current situation: I have saved my processed image in raspberry pi. I would like to upload the image to Thingspeak. However, I came across some posts saying that we cant upload image to Thingspeak. I wish to view my image at Thingspeak and also at Thingview(mobile app). Questions: 1) Can we upload image to Thingspeak? 2) Or can i upload the image to Google Drive then link it back to Thingspeak ? 3) If no, any way to do it? This is the example that show the image, but I not sure how it does. https://thingspeak.com/channels/276330
Steven Langston in MATLAB Answers
上次活动时间: 2021-11-27

In the example raspberry pi py script, which was working fine, now i am getting this error. Cant find any sililar issues on the net... any ideas peeps? import thingspeak import time channel_id = 1231234 # PUT CHANNEL ID HERE key = '123123123123' # PUT YOUR WRITE KEY HERE pin = 4 def measure(channel): try: # write response = channel.update({'field1': 2, 'field2': 1}) # read read = channel.get({}) print("Read:", read) except: print("connection failed") if __name__ == "__main__": channel = thingspeak.Channel(id=channel_id, api_key=key) while True: measure(channel) # free account has an api limit of 15sec time.sleep(15)
Tim Kendal in MATLAB Answers
上次活动时间: 2021-9-24

Since submitting my query below, I have run my code overnight and found that the data is in fact being uploaded corectly. It now shows in my channel. So my main problem has gone away. The remaining problem is in these lines of code which should print the response from Thingspeak in the console: print(str(response.status) + " " + str(response.reason) + " " + str(timenow) + " " + str(mBars)) #+ " " + str(temp)) print("\n") data = response.read() print(data) conn.close() except: print("connection failed") In short, the line conn.request("POST", "/update", params, headers) works, but lines relating to the response do not. This problem did not arise in my first Channel, mentioned below, where the response in the console is like this: 200 OK 2021-09-24 10:24:25 Any suggestions or help gratefully received! Thanks for looking at this. *********************************** Original post: I have successfully created my first Thingspeak channel and uploaded Mbar data (1 variable). This worked fine. This is the upload function that works - Python3 on my Raspberry Pi. def uploadData(pressure, cTemp): #upload to Thingspeak.com #ctemp is not used mBar = pressure timenow = datetime.now().strftime('%Y-%m-%d %H:%M:%S') params = urllib.parse.urlencode({'field1': mBar, 'key':key }) headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"} conn = http.client.HTTPConnection("api.thingspeak.com:80") try: conn.request("POST", "/update", params, headers) response = conn.getresponse() #print(mBar) print(str(response.status) + " " + str(response.reason) + " " + str(timenow) + " " + str(mBar)) #+ " " + str(temp)) #print("\n") data = response.read() conn.close() except: print("connection failed") I am now trying to upload to a new Channel I've created, with 4 variables, all from a BM688 Sensor, and get a "connection faiiled" error every time the code calls the Upload function. The reast of the code works fine, displaying all 4 variables in the Console, and also saving the data to a csv file. This is the upload function that does NOT work: def uploadData(temperature, pressure, humidity, air_quality_score): #upload to Thingspeak.com Mbars = pressure timenow = datetime.now().strftime('%Y-%m-%d %H:%M:%S') params = urllib.parse.urlencode({'field1': temperature, 'field2': Mbars,'field3': humidity,'field4': air_quality_score,'key':key }) headers = {"Content-typZZe": "application/x-www-form-urlencoded","Accept": "text/plain"} conn = http.client.HTTPConnection("api.thingspeak.com:80") try: conn.request("POST", "/update", params, headers) response = conn.getresponse() #print(mBar) print(str(response.status) + " " + str(response.reason) + " " + str(timenow) + " " + str(mBars)) #+ " " + str(temp)) #print("\n") data = response.read() conn.close() except: print("connection failed") I'm not certain the params line of code is correct, but it does not generate any syntax errors, so I think it should be ok. I did try changing the params line to just 1 variable, but that did not work either. The API key I'm using is correct. Can someone try to point me in the right direction to find what is wrong please! I would be very grateful! Tim Kendal
Vinicio Moya in MATLAB Answers
上次活动时间: 2021-6-29

Hello everybody! I need to use a Raspberry Pi that get data from a ThingSpeak channel in a standalone configuration, but the problem is that functions ThingSpeakRead and webread are not supported. What can I do? direccion=['https://api.thingspeak.com/channels/' chId '/feeds.json?api_key=' Read '&results=' cPoints]; datos=webread(direccion); Function 'webread' not supported for code generation
VISHAL SAWANT in MATLAB Answers
上次活动时间: 2021-5-17

Hello, I am working on raspberry pi with MQTT publish block. It is being used with Thingspeak Platform. I understood the example models for publiash and subscribe the fields. I want to use the MQTT publish and Subscribe block for multiple fields of channel. I am struggling with proper Topic argument for both publish and subscribe blocks. As I am bengineer, I will be happy to further explain the problem statement if the info given is insufficient. I used floowing links as refernece but not understood the specific argument. Publish message to update multiple channel fields simultaneously - MATLAB - MathWorks India Subscribe to updates from channel feed with MQTT - MATLAB - MathWorks India Regards
Tejaswini Suriyanarayanan in MATLAB Answers
上次活动时间: 2021-2-25

Hello, I was working on a project to contol an LED connected to the Pi 4 using the subscribe feature in ThingSpeak MQTT. While I was able to publish data to ThingSpeak MQTT using the Pi 4 without any issues, I faced trouble while trying to subscribe to a channel in ThingSpeak MQTT to read data from a field to control an LED connected to the Pi. Initially, I had interfaced both the LED and a BMP180 sensor to the same Pi and wanted to publish data from the BMP180 to a ThingSpeak channel and subscribe to the channel to control my LED based on the temperature values (I ran seperate scripts on the Pi 4 for the Publish and subscribe simuntaneously). Though the publish part worked, the subscribe part did not. I thought this was because I was using the same device (the Pi) to publish and subscribe to the channel. So later, I installed the MQTT.fx app in my PC and used it to publish values to a new private ThingSpeak channel. I then used the Pi to subscribe to the same channel, receive values and control the LED that was interfaced to it. This did not work either. I am unable to receive messages from the ThingSpeak MQTT channel when I subscribe to it from the Pi 4. I double checked the Channel ID and API keys were correct. I'm using the Paho MQTT library for publish and subscribe to ThingSpeak MQTT. I used port 1883. I will share the python code I used to subscribe to the ThingSpeak MQTT channel. I have the following doubts: Please help me resolve the above issue. (highlighted) Is it possible to use the same device to publish and subscribe to ThingSpeak MQTT, as I did in the first case? If yes, how? Code I used to subscribe to the ThingSpeak MQTT channel using the R Pi 4: import paho.mqtt.client as mqttClient import time from gpiozero import LED import random def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to broker") global Connected Connected = True else: print("Connection failed") def on_message(client, userdata, message): print (message.payload) Connected = False broker_address= "mqtt.thingspeak.com" #Broker address port = 1883 #Broker port user = "pi_led" #Connection username password = "XXXXXXXXXXXXXXXXX"#Connection password - Used my MQTT API key from My Profile client = mqttClient.Client("Python") #create new instance client.username_pw_set(user, password=password)#set username and password client.on_connect= on_connect #attach function to callback client.on_message= on_message #attach function to callback client.connect(broker_address, port=port) #connect to broker client.loop_start() #start the loop while Connected != True:#Wait for connection time.sleep(0.1) channelID = "1304227" READapiKey = "YYYYYYYYYYYYYYYY" topic = "channels/" + channelID + "/subscribe/field/field1/" + READapiKey #led = LED(27) client.subscribe(topic, qos=0) try: while True: time.sleep(1) except KeyboardInterrupt: print ("exiting") client.disconnect() client.loop_stop()
Barnard Richards in MATLAB Answers
上次活动时间: 2021-2-23

The example code Publish Using WebSockets in Python on a Raspberry Pi https://au.mathworks.com/help/thingspeak/use-raspberry-pi-board-that-runs-python-websockets-to-publish-to-a-channel.html does not work. my python 3 code executes to the last line of the ThingSpeak example code print ("There was an error while publishing the data.") I have been successfully using the same channelID, writeAPIKey and mqttAPIKey with a Arduino for some time using code at https://au.mathworks.com/help/thingspeak/use-arduino-client-to-publish-to-a-channel.html How do do I identify the error with the web sockets publish code. try: publish.single(topic,payload,... i can print on Terminal the topic and payload strings. they appear correct.
Multiplexer in MATLAB Answers
上次活动时间: 2020-12-19

Hello, First question, is "Deploy to Hardware" option when implementing model on Raspberry Pi B+ V1.2 with Simulink support for Raspberry Pi Hardware, meant to deploy the program in a way that it should run even when RPI is restarted? Because I'm experiencing issue when my application designed in Simulink stops working (can't tell if fully or partially) when i restart my RPI (power loss etc.) The application reads sensors over 1-wire, does some basic math and then sends data to ThingSpeak over wifi. All IP configuration is correct, I can bring up terminal on Matlab, I can deploy program, it works as intended. Now problematic part, say for any reason i turn off RPI power and turn it on again. RPI will boot up, it has valid internet connection, i can bring up terminal from Matlab yet previously deployed application will refuse to work (judging by the fact that 0 data is sent over to ThingSpeak). Is that behaviour intended (model not starting on RPI after reboot)? If yes, how do i make it run automatically? If no, what are the steps to troubleshoot this issue?
John Anderson in MATLAB Answers
上次活动时间: 2020-11-24

I am making use of the Matlab Coder to deploy Matlab functionality to a Raspberry pi. I would like to be able to deploy the ability to write to a ThingSpeak channel from the pi. I realise that this is possible using Simulink (via the ThingSpeak block) but was wondering if there is a simple way to do this via code deployed using the Matlab Coder. I have tried the obvious and found that the Matlab Coder does not recognise the ThingSpeakWrite command. However, it also doesn’t appear to be very straightforward to deploy http methods to enable updating the channel via the POST method. Any advice welcome.
Pankaj Thakur in MATLAB Answers
上次活动时间: 2020-7-25

Using a Nod-Red flow on my raspberry pi 3b+ model running on Rasbian, I setup a DHT11 sensor to send Temperatrure and Humidity values to first and second field of my channel on Thingspeak after every 10 minutes. But it is only uploading Temperature value or Humidity value at a time. Both are not updated.
Vinicio Moya in MATLAB Answers
上次活动时间: 2020-6-20

Hello everybody! I want to use a Raspberry Pi 3B+ to control a biorreactor. I have some sensors, and they give me data in an URL (http://plaato.blynk.cc/auth_token/get/pin). How can I make a call to thar URL in Simulink? I don´t want to use ThingSpeak, and I´m sure that Simulink could do this in a simple way. Could yo help me?
Roger Notknomuch in MATLAB Answers
上次活动时间: 2020-5-26

Hello Community, first of all let me admit, that I am - according to python - a "script-kiddie". I recently learned html5, css3 and javascript, but that is not helpful here. That is why I need your help. I found a script that is reading the data from my sds011 sensor. It passes its data to a webpage. So far so good. Now I would like to pass the data to thingspeak. After a couple of hours trying without really understanding I would appreciate help. I think the code line below ist the one I need for updating my channel in thingspeak. But the channel remains empty. No data shown. What have I done wrong? Help appreciated. Learning python is on my "To-Do-List" ;-) Kind regards, Roger Short code: import urllib .... urllib.request.urlopen("https://api.thingspeak.com/update?api_key=RJASGFLWRVM5JKHM&field1=pm25&field2=pm10") The entire code: #!/usr/bin/python -u # coding=utf-8 # "DATASHEET": http://cl.ly/ekot # https://gist.github.com/kadamski/92653913a53baf9dd1a8 from __future__ import print_function import serial, struct, sys, time, json, subprocess import urllib DEBUG = 0 CMD_MODE = 2 CMD_QUERY_DATA = 4 CMD_DEVICE_ID = 5 CMD_SLEEP = 6 CMD_FIRMWARE = 7 CMD_WORKING_PERIOD = 8 MODE_ACTIVE = 0 MODE_QUERY = 1 PERIOD_CONTINUOUS = 0 JSON_FILE = '/var/www/html/aqi.json' MQTT_HOST = '' MQTT_TOPIC = '/weather/particulatematter' ser = serial.Serial() ser.port = "/dev/ttyUSB0" ser.baudrate = 9600 ser.open() ser.flushInput() byte, data = 0, "" def dump(d, prefix=''): print(prefix + ' '.join(x.encode('hex') for x in d)) def construct_command(cmd, data=[]): assert len(data) <= 12 data += [0,]*(12-len(data)) checksum = (sum(data)+cmd-2)%256 ret = "\xaa\xb4" + chr(cmd) ret += ''.join(chr(x) for x in data) ret += "\xff\xff" + chr(checksum) + "\xab" if DEBUG: dump(ret, '> ') return ret def process_data(d): r = struct.unpack('<HHxxBB', d[2:]) pm25 = r[0]/10.0 pm10 = r[1]/10.0 checksum = sum(ord(v) for v in d[2:8])%256 return [pm25, pm10] #print("PM 2.5: {} μg/m^3 PM 10: {} μg/m^3 CRC={}".format(pm25, pm10, "OK" if (checksum==r[2] and r[3]==0xab) else "NOK")) def process_version(d): r = struct.unpack('<BBBHBB', d[3:]) checksum = sum(ord(v) for v in d[2:8])%256 print("Y: {}, M: {}, D: {}, ID: {}, CRC={}".format(r[0], r[1], r[2], hex(r[3]), "OK" if (checksum==r[4] and r[5]==0xab) else "NOK")) def read_response(): byte = 0 while byte != "\xaa": byte = ser.read(size=1) d = ser.read(size=9) if DEBUG: dump(d, '< ') return byte + d def cmd_set_mode(mode=MODE_QUERY): ser.write(construct_command(CMD_MODE, [0x1, mode])) read_response() def cmd_query_data(): ser.write(construct_command(CMD_QUERY_DATA)) d = read_response() values = [] if d[1] == "\xc0": values = process_data(d) return values def cmd_set_sleep(sleep): mode = 0 if sleep else 1 ser.write(construct_command(CMD_SLEEP, [0x1, mode])) read_response() def cmd_set_working_period(period): ser.write(construct_command(CMD_WORKING_PERIOD, [0x1, period])) read_response() def cmd_firmware_ver(): ser.write(construct_command(CMD_FIRMWARE)) d = read_response() process_version(d) def cmd_set_id(id): id_h = (id>>8) % 256 id_l = id % 256 ser.write(construct_command(CMD_DEVICE_ID, [0]*10+[id_l, id_h])) read_response() def pub_mqtt(jsonrow): cmd = ['mosquitto_pub', '-h', MQTT_HOST, '-t', MQTT_TOPIC, '-s'] print('Publishing using:', cmd) with subprocess.Popen(cmd, shell=False, bufsize=0, stdin=subprocess.PIPE).stdin as f: json.dump(jsonrow, f) if __name__ == "__main__": cmd_set_sleep(0) cmd_firmware_ver() cmd_set_working_period(PERIOD_CONTINUOUS) cmd_set_mode(MODE_QUERY); while True: cmd_set_sleep(0) for t in range(15): values = cmd_query_data(); if values is not None and len(values) == 2: print("PM2.5: ", values[0], ", PM10: ", values[1]) time.sleep(2) # open stored data try: with open(JSON_FILE) as json_data: data = json.load(json_data) except IOError as e: data = [] # check if length is more than 100 and delete first element if len(data) > 100: data.pop(0) # append new values jsonrow = {'pm25': values[0], 'pm10': values[1], 'time': time.strftime("%d.%m.%Y %H:%M:%S")} data.append(jsonrow) # save it with open(JSON_FILE, 'w') as outfile: json.dump(data, outfile) if MQTT_HOST != '': pub_mqtt(jsonrow) #!!!!!!!!!!!!!!!!!!! HERE urllib.request.urlopen("https://api.thingspeak.com/update?api_key=RJASGFLWRVM5JKHM&field1=pm25&field2=pm10") print("Going to sleep for 2 min...") # Alter time.sleep = 1200 cmd_set_sleep(1) time.sleep(120)
Mei Sing Wang in MATLAB Answers
上次活动时间: 2020-3-10

Can raspberry pi use talkback? or is it specially for arduino only
Jayanth Tadikonda in MATLAB Answers
上次活动时间: 2020-2-20

#!/usr/bin/python import smbus import math import requests import json power_mgmt_1 = 0x6b power_mgmt_2 = 0x6c def read_byte(reg): return bus.read_byte_data(address, reg) def read_word(reg): h = bus.read_byte_data(address, reg) l = bus.read_byte_data(address, reg+1) value = (h << 8) + l return value def read_word_2c(reg): val = read_word(reg) if (val >= 0x8000): return -((65535 - val) + 1) else: return val def dist(a,b): return math.sqrt((a*a)+(b*b)) def get_y_rotation(x,y,z): radians = math.atan2(x, dist(y,z)) return -math.degrees(radians) def get_x_rotation(x,y,z): radians = math.atan2(y, dist(x,z)) return math.degrees(radians) bus = smbus.SMBus(1) # bus = smbus.SMBus(0) fuer Revision 1 address = 0x68 # via i2cdetect bus.write_byte_data(address, power_mgmt_1, 0) print "Gyrosk op" print "--------" while(True): gyroskop_xout = read_word_2c(0x43) gyroskop_yout = read_word_2c(0x45) gyroskop_zout = read_word_2c(0x47) print "gyroscope_xout: ", ("%5d" % gyroskop_xout), " skaliert: ", (gyroskop_xout / 131) print "gyroscope_yout: ", ("%5d" % gyroskop_yout), " skaliert: ", (gyroskop_yout / 131) print "gyroscope_zout: ", ("%5d" % gyroskop_zout), " skaliert: ", (gyroskop_zout / 131) # How to send the above sensor data to ThingSpeak ? Please Help.
prechanon kumkratug in MATLAB Answers
上次活动时间: 2020-1-22

The method to publish one field(field1) to think speak is given by the John Anderson % raspberry pi object r = raspi(); % log file fid = fopen( 'logFile.log', 'w' ); % write random number to thingSpeak channel v = rand; commandStr = [ 'sudo curl -s "https://api.thingspeak.com/update.json?api_key=<your api key here>&field1=' sprintf( '%f', v ) '"' ]; result = system( r, commandStr ); % log command fprintf( fid, '%s \n', commandStr ); % log result fprintf( fid, '%s \n', result ); % close log fclose( fid ); https://www.mathworks.com/matlabcentral/answers/467879-how-do-i-write-to-a-thingspeak-channel-from-a-raspberry-pi-via-code-deployed-using-the-matlab-coder How to modify it to simultaneously publish the 2 data to 2 fields (field1 and field2) of thingspeak channel .
Claire McV in MATLAB Answers
上次活动时间: 2019-12-24

Hello I am hoping someone can help please. I have connected my raspberry pi 3 to a Thingspeak channel and set up two fields to be read and displayed, 'Temperature' and 'Accelerometer'. The temperator information is displayed as a field chart but the accelerometer is not. I know the raspberry pi is reading it as the values are printing and when I use 'export recent data' I can see the information there. Am I missing something in getting accelerometer information to display as a field? I am importing with 2 fields but I checked with another field (pressure) and it worked so I know the code for two fields is right. Any help greatly appreciated.
Student88 in MATLAB Answers
上次活动时间: 2018-7-29

Hello there :) I'm currently searching for possibilities to connect an raspi wireless to Matlab/Simulink. The aim is to read data from a sensor connected to the raspi. I saw tutorials describing how to do that via wifi. Would it also work with a usb bluetooth dongle connected to the raspi? Couldn't find anything about that on the internet, so I would be really thankful for any feedback. Kind regards :)
Oliver Mörth in MATLAB Answers
上次活动时间: 2018-7-25

Hello, I am using a webcam (LifeCam Studio, Microsoft) and a Simulink-model running on a Raspberry Pi model B to count moving objects (similar to the example "Analyzing Traffic Using a Webcam, a Raspberry Pi and ThingSpeak"). By increasing the resolution, I can identify more image errors (parts of the image are mixed up and not in the right position) and the counting doesn't work properly. Does anyone please know why this happens and how to solve this problem?
MathWorks Internet of Things Team in File Exchange
上次活动时间: 2018-1-5

Develop a traffic monitoring algorithm and analyze traffic data sent to ThingSpeak
Rajbir Singh in MATLAB Answers
上次活动时间: 2017-11-10

my question is that, is it possible to control pi's output say (i would like to control led ) via thingspeak channel.....as in simulink there is no block for receiving data from thingspeak channel. Please suggest any way to overcome this problem.

关于 ThingSpeak

The community for students, researchers, and engineers looking to use MATLAB, Simulink, and ThingSpeak for Internet of Things applications. You can find the latest ThingSpeak news, tutorials to jump-start your next IoT project, and a forum to engage in a discussion on your latest cloud-based project. You can see answers to problems other users have solved and share how you solved a problem.