8051/boards/rs485relay.c
Jochen Friedrich d4e346c5a0 Sync work
2025-11-08 19:26:58 +01:00

127 lines
2.3 KiB
C

#include <nuvoton/functions.h>
#include <nuvoton/N76E003.h>
#include <nuvoton/Common.h>
#include <nuvoton/SFR_Macro.h>
#include <string.h>
#include "MySensors.h"
#define RS485_DIR P14
#define IN1 P05
#define IN2 P15
#define RELAY1 P13
#define RELAY2 P01
#define MAXCMD 64
unsigned char relay;
unsigned char crc;
void rs485_in(void) {
RS485_DIR = 0;
}
void rs485_out(void) {
RS485_DIR = 1;
}
void send_state(void) {
MyMessage state;
state.data[0] = 0;
state.version_length = (1 << 3) + V2_MYS_HEADER_PROTOCOL_VERSION;
state.sensor = 0;
state.type = V_TRIPPED;
send(&state, P_BYTE);
state.sensor = 1;
send(&state, P_BYTE);
state.data[0] = RELAY1;
state.sensor = 2;
state.type = V_STATUS;
send(&state, P_BYTE);
state.data[0] = RELAY2;
state.sensor = 3;
send(&state, P_BYTE);
sendBattery(100);
}
void receive(const MyMessage* mymsg)
{
uint8_t sensor;
// We only expect one type of message from controller. But we better check anyway.
if (mymsg->type == V_STATUS) {
sensor = mymsg->sensor;
if (sensor == 2)
RELAY1 = (mymsg->data[0]=='1')?1:0;
if (sensor == 3)
RELAY2 = (mymsg->data[0]=='1')?1:0;
}
}
void present_node(void) {
present(NODE_SENSOR_ID, S_ARDUINO_NODE,"2.3.2");
sendSketchInfo("Relay_Nuvoton", "1.2");
present(0, S_DOOR, "IN1");
present(1, S_DOOR, "IN2");
present(2, S_BINARY, "Relay 1");
present(3, S_BINARY, "Relay 2");
registerNode();
delay(20);
send_state();
}
void uart_loop() {
transportProcess();
}
void uart_init(UINT32 u32Baudrate) //T1M = 1, SMOD = 1
{
P06_PushPull_Mode;
P07_Input_Mode;
SCON = 0x50; //UART0 Mode1,REN=1,TI=1
TMOD |= 0x20; //Timer1 Mode1
set_SMOD; //UART0 Double Rate Enable
set_T1M;
clr_BRCK; //Serial port 0 baud rate clock source = Timer1
#ifdef FOSC_160000
TH1 = 256 - (1000000 / u32Baudrate + 1); /*16 MHz */
#endif
#ifdef FOSC_166000
TH1 = 256 - (1037500 / u32Baudrate); /*16.6 MHz */
#endif
set_TR1;
set_TI; //For printf function must setting TI = 1
}
int main()
{
uart_init(9600);
RS485_DIR = 0;
P14_PushPull_Mode;
/* Relays */
RELAY1 = 0;
RELAY2 = 0;
P01_PushPull_Mode;
P13_PushPull_Mode;
/* Inputs */
P05_Input_Mode;
P15_Input_Mode;
transportInitialise();
while (1)
{
uart_loop();
}
}