树莓派4b+串口实现MQTT通信发送消息(C语言)

这段时间在整理树莓派的资料,正巧前段时间学习了串口和MQTT协议的知识,于是就整理了一段程序,将这两者结合起来。

最终实现的效果是,树莓派开发板作为MQTT发送方,发送的数据来源为树莓派连接的电脑,通过串口线将数据先传送给树莓派,再由树莓派发送至接收端。

过程比较繁琐而且怪没必要的哈哈哈,不过作为学习也蛮有意义的。

硬件与软件环境准备

硬件准备

·PC
·树莓派4b
·网线,电源线
·USB转TTL模块

软件准备

·烧录好的raspbian系统(其他树莓派系统也可)
·树莓派端安装mosquitto(具体可参见有关博客或登录官网下载http://mosquitto.org/
·MQTT.fx(安装在PC端)
·串口调试助手(安装在PC端)

硬件连接

首先将USB转TTL模块与树莓派进行连接。需要连接的有三根引脚,其中:
模块的RX端接树莓派的TX端;
模块的TX端接树莓派的RX端;
模块的GND端接树莓派的GND端;

注意RX和TX端的接法不要搞混,在串口中接收的一端(RX)对应连接发送的一端(TX)
为了方便大家接线在这里放一张树莓派4b的管脚图:
在这里插入图片描述
之后将模块的USB一端接在电脑上:
在这里插入图片描述

代码部分

在树莓派系统中编辑C语言代码,文件名称为comm_GPIO.c,主要有以下几点参数,可根据自己的需要灵活修改:

·IP地址为自己的IP地址,博主的IP地址假设为127.0.0.1
·端口号为1883
·订阅的主题名为GPIO_message
·串口地址为/dev/ttyAMA0
·波特率为9600
·每隔两秒发送一次消息

接下来放代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <stdbool.h>
#include <mosquitto.h>
#include <wiringPi.h>
#include <signal.h>
#include <wiringSerial.h>

#define HOST "127.0.0.1"
#define PORT  1883
#define KEEP_ALIVE 60
#define session true

int pinNumber = 1;
int running = 1;
char buff[64];
int fd;

struct mosquitto *mosq = NULL;

void Sig_Handle(int sig)
{
   if(sig == SIGINT)   
   running = 0;
}

int Service_Start()
{
    signal(SIGINT, Sig_Handle);    
    if(wiringPiSetup() < 0)
    {
        printf("wiringPi setup failed.\n");
        return 1;
    }
    
    int baudrate = 9600;
    
    if((fd = serialOpen("/dev/ttyAMA0",baudrate)) < 0)
    {
        printf("serial open failed.\n");
        return 1;
    }

    mosquitto_lib_init();   
    return 0;
}

int Comm_Gpio(struct mosquitto *mosq, int *mid, const char *topic, int payloadlen, const void *payload, int qos, bool retain)
{
    int sz = serialDataAvail(fd); 
    if(sz > 0)
    {
        printf("Receiving gpio data...\n");
        char *buff =(char*)malloc(sz);
        for(int i = 0; i < sz; i++)
        {
            int c = serialGetchar(fd); 
            buff[i] = c;  
        }
    mosquitto_publish(mosq,NULL,"GPIO_message",strlen(buff),buff,0,0);
    free(buff);	
    }
    else
    {
        usleep(50000);
    }
    return 0;
}

int main()
{
    mosq = mosquitto_new(NULL,session,NULL);   
    Service_Start();
    
    if(mosquitto_connect(mosq, HOST, PORT, KEEP_ALIVE)){
		fprintf(stderr, "Unable to connect.\n");
		return 1;
    }
    
    int loop = mosquitto_loop_start(mosq); 
    if(loop != MOSQ_ERR_SUCCESS){
        printf("mosquitto loop error\n");
        return 1;
    }
    
    while(Service_Start() != 1)
    {
		Comm_Gpio(mosq,NULL,"GPIO_message",strlen(buff),buff,0,0);
		memset(buff,0,sizeof(buff));
		sleep(2);
    }
	
	mosquitto_loop_stop(mosq,false);
	mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();
	
    return 0;
}

编译与运行

打开终端输入编译命令,记得在指令后加上-lmosquitto与-lwiringPi选项,完成第三方库的链接:

gcc comm_GPIO.c -o comm_GPIO -lmosquitto -lwiringPi

之后在电脑上打开串口调试助手与MQTT.fx,绑定IP地址,订阅GPIO_message的主题
完成以上步骤后在树莓派终端输入指令运行代码:

./comm_GPIO

这个时候就可以在串口助手输入任何消息,之后MQTT.fx端便可以收到串口助手编辑的消息了:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

好的,我可以为您简单介绍一下SpringBoot集成ActiveMQ和MQTT实现消息发送和接收。 首先,您需要在SpringBoot项目中添加ActiveMQ和MQTT的依赖,可以在pom.xml文件中添加如下代码: ```xml <!-- ActiveMQ --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-activemq</artifactId> </dependency> <!-- MQTT --> <dependency> <groupId>org.springframework.integration</groupId> <artifactId>spring-integration-mqtt</artifactId> <version>5.5.0</version> </dependency> ``` 接下来,您需要在application.properties中配置ActiveMQ和MQTT的连接信息,例如: ```properties # ActiveMQ spring.activemq.broker-url=tcp://localhost:61616 spring.activemq.user=admin spring.activemq.password=admin # MQTT spring.mqtt.username=admin spring.mqtt.password=admin spring.mqtt.url=tcp://localhost:1883 ``` 然后,您可以通过注入JmsTemplate和MqttPahoMessageHandler来实现消息发送和接收。例如: ```java // ActiveMQ @Autowired private JmsTemplate jmsTemplate; public void sendMessage(String destination, String message) { jmsTemplate.convertAndSend(destination, message); } @JmsListener(destination = "testQueue") public void receiveMessage(String message) { System.out.println("Received message: " + message); } // MQTT @Autowired private MqttPahoMessageHandler mqttHandler; public void sendMessage(String topic, String message) { mqttHandler.setDefaultTopic(topic); mqttHandler.handleMessage(MessageBuilder.withPayload(message).build()); } @MessageEndpoint public class MqttMessageReceiver { @ServiceActivator(inputChannel = "mqttInputChannel") public void receiveMessage(String message) { System.out.println("Received message: " + message); } } ``` 以上代码中,sendMessage方法用于发送消息,receiveMessage方法用于接收消息。使用JmsTemplate可以很方便地发送和接收ActiveMQ消息,使用MqttPahoMessageHandler和MqttMessageReceiver可以很方便地发送和接收MQTT消息。 这就是SpringBoot集成ActiveMQ和MQTT实现消息发送和接收的基本流程,希望对您有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值