Arduino PINs not behaving equally - arduino

I have burned this code on my arduino:
#include <SPI.h>
#include <Ethernet.h>
#include <stdlib.h>
using namespace std;
#define BUFFSIZE 16
#define PIN0 0
#define PIN1 1
#define PIN2 2
#define PIN3 3
#define PIN4 4
#define PIN5 5
#define PIN6 6
#define PIN7 7
#define PIN8 8
#define PIN9 9
#define PIN10 10
#define PIN11 11
#define PIN12 12
#define PIN13 13
// For mac address please view the Ethernet shield.
byte mac[] = {0x90, 0xA2, 0xDA, 0x0D, 0x85, 0xD5};
IPAddress server(192, 168, 0, 61); // IP address of RAAS server
// Set the static IP address to use if the DHCP fails to assign
IPAddress ip(192, 168, 0, 62);
// Initialize the Ethernet client library
// with the IP address and port of the server
// that you want to connect to (port 8 is selected for RAAS):
EthernetClient client;
String GetNextCommand()
{
int count,i;
int temp;
String command;
Serial.println("Waiting for next Command.");
while((count = client.available()) < 1 );
for(i = 0; i < count ; i++)
command += (char) client.read();
command.replace("\r","");
command.replace("\n","");
Serial.println(command);
return command;
}
bool ConnectServer() {
int resCount,i;
String response;
Serial.println("Trying to connect...");
// if you get a connection, report back via serial:
if (client.connect(server, 8)) {
Serial.println("connected");
// Make a Handshake request:
client.println("EHLO");
response = GetNextCommand();
if (response == "EHLO" ) {
Serial.println("Server Response OKAY");
return true;
}
} else {
// kf you didn't get a connection to the server:
Serial.println("connection failed");
}
return false;
}
void InitializeBoard() {
pinMode(PIN1, OUTPUT);
pinMode(PIN2, OUTPUT);
pinMode(PIN3, OUTPUT);
pinMode(PIN4, OUTPUT);
pinMode(PIN5, OUTPUT);
pinMode(PIN6, OUTPUT);
pinMode(PIN7, OUTPUT);
pinMode(PIN8, OUTPUT);
pinMode(PIN9, OUTPUT);
pinMode(PIN10, OUTPUT);
pinMode(PIN11, OUTPUT);
pinMode(PIN12, OUTPUT);
pinMode(PIN13, OUTPUT);
digitalWrite(PIN1, LOW);
digitalWrite(PIN2, LOW);
digitalWrite(PIN3, LOW);
digitalWrite(PIN4, LOW);
digitalWrite(PIN5, LOW);
digitalWrite(PIN6, LOW);
digitalWrite(PIN7, LOW);
digitalWrite(PIN8, LOW);
digitalWrite(PIN9, LOW);
digitalWrite(PIN10, LOW);
digitalWrite(PIN11, LOW);
digitalWrite(PIN12, LOW);
digitalWrite(PIN13, LOW);
}
void ParseCommand(String str) {
int pinNum;
int pinState = LOW;
String switchNo,operation;
int temp;
temp=0;
temp = str.indexOf(':',temp);
switchNo = str.substring(0,temp);
operation = str.substring(temp+1);//,str.length()-temp-2);
Serial.println("Port: " + switchNo);
Serial.println("Operation: " + operation);
if(operation == "OFF;")
pinState = LOW;
else if(operation == "ON;")
pinState = HIGH;
else Serial.println("Invalid Command from server!");
pinNum = str.toInt();
Serial.print("Setting ");
Serial.print( pinNum);
Serial.print( " to ");
Serial.println( pinState);
switch (pinNum){
case PIN1:
digitalWrite(PIN1, pinState);
break;
case PIN2:
digitalWrite(PIN2, pinState);
break;
case PIN3:
digitalWrite(PIN3, pinState);
break;
case PIN4:
digitalWrite(PIN4, pinState);
break;
case PIN5:
digitalWrite(PIN5, pinState);
break;
case PIN6:
digitalWrite(PIN6, pinState);
break;
case PIN7:
digitalWrite(PIN7, pinState);
break;
case PIN8:
digitalWrite(PIN8, pinState);
break;
case PIN9:
digitalWrite(PIN9, pinState);
break;
case PIN10:
digitalWrite(PIN10, pinState);
break;
case PIN11:
digitalWrite(PIN11, pinState);
break;
case PIN12:
digitalWrite(PIN12, pinState);
break;
case PIN13:
digitalWrite(PIN13, pinState);
break;
default:
Serial.println("Invalid Pin Address!");
}
}
void setup() {
// Open serial communications and wait for port to open:
Serial.begin(9600);
// start the Ethernet connection:
if (Ethernet.begin(mac) == 0) {
Serial.println("Failed to configure Ethernet using DHCP");
// no point in carrying on, so do nothing forevermore:
// try to congifure using IP address instead of DHCP:
Ethernet.begin(mac, ip);
} else {
Serial.println("Bound on given Mac");
}
// give the Ethernet shield a second to initialize:
delay(1000);
}
void loop() {
//Keep trying to connect to the server until the server response okay!
while (!ConnectServer());
//While Server is connected, keep listening for incoming commands from server.
while (client.connected()) {
String command;
command = GetNextCommand();
ParseCommand(command);
}
// if the server's disconnected, stop the client:
if (!client.connected()) {
Serial.println();
Serial.println("Server Disconnected.");
client.stop();
}
}
Now I have to connect Relays on all the pins from 1-13. But pins are not behaving properly. When I send command 13:ON; or 13:OFF; pins on my Ethernet shield does not change its state in each case. But when I send 03:ON; or 03:OFF; it changes its state exactly w.r.t the command. Similarly some pins are responding like pin 3 and other pins are not (like pin13). Is this some thing to do with the code?

The issue is the Ethernet shield uses pins 13, 12, 11, as SPI . Also 10 and 4, to select SD or ethernet.
pinNum = str.toInt();
And then you have a switch statement to mach pinNum with the correct operation.
I would like to see how the value of str looks before "ParseCommand()" function. Can you show me what prints in the "GetNextCommand()"

Related

Sending an array from one Nodemcu to another Nodemcu?

I am working on a gesture control car project and I find everyone on the internet using RF modules or Bluetooth modules to do it, I had two NodeMCU lying around so I thought why not use them and bring a change. But I am finding difficulty in sending the accelerometer values from one Nodemcu to another, For connecting the two Nodemcu I took help from here
https://www.instructables.com/id/WiFi-Communication-Between-Two-ESP8266-Based-MCU-T/
So instead of a string (which they use), I tried sending an array of two variables, but I fail to send/receive it from the transmitter to the receiver. I have spent a lot of time on it, but I think I need help.
I now know ( just this morning ) that Nodemcu has only one analog pin, I have ordered for a 74HC4051 IC. So I haven't changed the code for that, so please bear that in mind. Also, I have used the xAxis only now just to test if the data is being sent, but it is not.
If there is any other easier way of sending the two variable values, please do suggest.
This is the actual project, I asked the author for help, but no reply yet.
https://www.youtube.com/watch?v=svJwmjplm4c
I have given below the edited code that I have now
Transmitter code
#include <SPI.h>
#include <ESP8266WiFi.h>
int xAxis = A0;
int yAxis = D2;
int data[1];
int x;
int ledPin = D8;
char ssid[] = "********"; // SSID
char pass[] = "********"; // password I removed them while posting the question
WiFiServer server(80);
IPAddress ip(192, 168,1, 80); // IP address of the server
IPAddress gateway(192,168,1,1); // gateway of your network
IPAddress subnet(255,255,255,0); // subnet mask of your network
void setup() {
Serial.begin(115200); // only for debug
WiFi.config(ip, gateway, subnet); // forces to use the fix IP
WiFi.begin(ssid, pass); // connects to the WiFi router
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
server.begin(); // starts the server
Serial.println("Connected to wifi");
Serial.print("Status: "); Serial.println(WiFi.status()); // some parameters from the network
Serial.print("IP: "); Serial.println(WiFi.localIP());
Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
Serial.print("SSID: "); Serial.println(WiFi.SSID());
Serial.print("Signal: "); Serial.println(WiFi.RSSI());
Serial.print("Networks: "); Serial.println(WiFi.scanNetworks());
pinMode(ledPin, OUTPUT);
}
void loop () {
WiFiClient client = server.available();
if (client) {
if (client.connected()) {
digitalWrite(ledPin, LOW); // to show the communication only (inverted logic)
Serial.println(".");
client.flush();
Serial.println("Data send");
x= analogRead(xAxis);
data[0]= analogRead(xAxis);
client.println(data[x,yAxis]);
Serial.println(x);
Serial.println(data[0]); //This appears on the screen only if i have the line data[0]= analogRead(xAxis);
digitalWrite(ledPin, HIGH);
}
client.stop(); // tarminates the connection with the client
}delay(2000);
}
Receiver Code
#include <SPI.h>
#include <ESP8266WiFi.h>
int ENA = D1;
int ENB = D2;
int MotorA1 = D3;
int MotorA2 = D4;
int MotorB1 = D5;
int MotorB2 = D6;
int data[1];
int xAxis;
int yAxis;
int ledPin = D8;
char ssid[] = "*****";
char pass[] = "*****";
unsigned long askTimer = 0;
IPAddress server(192,168,1,80); // the fix IP address of the server
WiFiClient client;
void setup() {
Serial.begin(115200); // only for debug
WiFi.begin(ssid, pass); // connects to the WiFi router
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
/* Serial.println("Connected to wifi");
Serial.print("Status: "); Serial.println(WiFi.status()); // Network parameters
Serial.print("IP: "); Serial.println(WiFi.localIP());
Serial.print("Subnet: "); Serial.println(WiFi.subnetMask());
Serial.print("Gateway: "); Serial.println(WiFi.gatewayIP());
Serial.print("SSID: "); Serial.println(WiFi.SSID());
Serial.print("Signal: "); Serial.println(WiFi.RSSI());*/
pinMode(ledPin, OUTPUT);
pinMode(ENA, OUTPUT);
pinMode(ENB, OUTPUT);
pinMode(MotorA1, OUTPUT);
pinMode(MotorA2, OUTPUT);
pinMode(MotorB1, OUTPUT);
pinMode(MotorB2, OUTPUT);
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
analogWrite(ENA, 0);
analogWrite(ENB, 0);
}
void loop () {
client.connect(server, 80); // Connection to the server
digitalWrite(ledPin, LOW); // to show the communication only (inverted logic)
Serial.println(".");
data[xAxis,yAxis] = client.read(); // receives the answer from the sever
Serial.println(" Received from Server ");
client.flush();
digitalWrite(ledPin, HIGH);
Serial.println(xAxis);
if(yAxis > 400) {
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
analogWrite(ENA, 150);
analogWrite(ENB, 150);
}else if(yAxis < 320) {
digitalWrite(MotorA1, HIGH);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, HIGH);
analogWrite(ENA, 150);
analogWrite(ENB, 150);
} else if(xAxis < 320){
digitalWrite(MotorA1, HIGH);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, HIGH);
digitalWrite(MotorB2, LOW);
analogWrite(ENA, 150);
analogWrite(ENB, 150);
}else if(xAxis > 400){
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, HIGH);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, HIGH);
analogWrite(ENA, 150);
analogWrite(ENB, 150);
}else {
digitalWrite(MotorA1, LOW);
digitalWrite(MotorA2, LOW);
digitalWrite(MotorB1, LOW);
digitalWrite(MotorB2, LOW);
analogWrite(ENA, 0);
analogWrite(ENB, 0);
}
delay(2000); // client will trigger the communication after two seconds
}

Go to link using if condition using Arduino IDE

I'm just trying to get myself here "http://192.168.1.103:30000/?k=23&v=capture" when an if condition meet its requirement.
#include <ESP8266WiFi.h>
// I purposely don't include the ssid and ssid1 here
WiFiServer server(80);
void setup() {
pinMode(1, INPUT);
Serial.begin(115200);
delay(10);
Serial.println();
WiFi.softAP(ssid1, password1);
Serial.println(WiFi.localIP());
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_AP_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Start the server
server.begin();
Serial.println("Server started");
}
void loop() {
String link = "http://192.168.1.103:30000/?k=23&v=capture";
WiFiClient client = server.available();
if (!client) {
return;
}
int var = digitalRead(1);
if (var == HIGH) {
client.print(link);
}
Let's say:
I already run Chrome.
How can that link above be called without even typing it on Chrome? I want to connect to it automatically.
Any method you could teach? I got the feeling this code itself is wrong.
Thanks.
-- EDIT --
NEW CODE FOR UNO
//language c++
#include <Servo.h>
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#define I2C_ADDR 0x3F // Scanning address
LiquidCrystal_I2C lcd(I2C_ADDR, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE); // Set the LCD I2C address
Servo Servo1;
int servopin = 9;
void setup() {
Serial.begin(9600);
lcd.begin(16, 2);
// initialize the lcd for 16 chars 2 lines, turn on backlight
lcd.backlight(); // finish with backlight on
lcd.setCursor(3, 0); //Start at character 4 on line 0
lcd.print("WAITING...");
pinMode(12, OUTPUT); // pin LaserLight
pinMode(11, INPUT); // pin LaserDetector
pinMode(10, INPUT); // pin PIR
pinMode(9, OUTPUT); // pin Servo
pinMode(8, OUTPUT); // MCU PIN GPIO2
Servo1.attach(servopin);
}
void loop() {
digitalWrite(12, HIGH);
boolean inputlaser = digitalRead(11);
boolean inputpir = digitalRead(10);
Serial.println(inputlaser);
Serial.println(inputpir);
if (inputlaser < 1) {
digitalWrite(8, HIGH);
lcd.setCursor(0, 0);
lcd.print("camera on");
lcd.setCursor(0, 1);
lcd.print("robber!");
delay(5000);
Servo1.write(180);
} else if (inputpir > 0) {
Servo1.write(180);
lcd.setCursor(0, 0);
lcd.print("robber inside!");
lcd.setCursor(0, 1);
lcd.print("HELP ROBBER!");
delay(500);
} else {
lcd.clear();
lcd.setCursor(3, 0);
lcd.print("standby...");
delay(500);
}
}
NEW CODE FOR MCU
#include <ESP8266WiFi.h>
char server[] = "192.168.1.103";
WiFiClient client;
void setup() {
pinMode(4, INPUT);
digitalWrite(4, LOW);
Serial.begin(115200);
delay(10);
Serial.println();
WiFi.softAP(ssid1, password1);
Serial.println(WiFi.localIP());
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_AP_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
boolean var = digitalRead(4);
if (var == HIGH) {
client.connect(server, 30000);
Serial.println("connected");
// Make your API request:
client.println("GET /?k=23&v=capture");
client.println("Host: 192.168.1.103");
client.println("Connection: close");
client.println();
} else {
// if you didn't get a connection to the server:
Serial.println("connection failed");
}
Serial.println(digitalRead(4));
}
First understand a fact that you doesn't need google chrome for requesting a website.
client.println("GET /?k=23&v=capture");
client.println("Host: 192.168.1.103");
What you do in the above line is that you request for /?k=23&v=capture addressed content in the ip address 192.168.1.103, Actully this is what you do when you use a google chrome. On PC you require a google chrome (or any other browser) for web site request because its difficult to request using commands each time (Think of requesting for a single page using a hell of http commands instead of using chrome, Ohh that's mess). So understand chrome isn't needed to access a site.

Arduino returning wrong integer value

I have some code, that turns a LED on/off based on a value on a website (blank page containing a number. The number on the page indicate the number of times the LED should flash.
The problem is that the loop keep running.
I can fix the problem by setting the integer value manually (int c = 3).
Not sure what my problem is.
Maybe one of you can point me in the right direction.
Url: http://b2b.as/lan.php?pid=8855
Code:
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "b2b.as";
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println(Ethernet.localIP());
Serial.println();
// Set digital pin as output
// 5V
pinMode(8, OUTPUT);
}
void loop()
{
//
Serial.print("\n-----\n");
// Connect to the server
Serial.print("connecting to URL ...");
// Start LAN connection
EthernetClient client;
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /lan.php?pid=8855");
client.println();
} else {
Serial.println("connection failed");
}
// Wait a moment for data to arrive
// Note: This is NOT a reliable way of doing this!
delay(1000);
if (client.available() > 0) {
char c = atoi(client.read());
Serial.print("page value (pick): ");
Serial.print(c, DEC);
Serial.print("\n");
for (int x = 1; x <= int(c); x++) {
Serial.print("picking: #");
Serial.println(x);
digitalWrite(8, HIGH);
Serial.println("8 HIGH ...");
delay(5000); // Add switch
digitalWrite(8, LOW);
Serial.println("8 LOW ...");
delay(1000);
}
Serial.print("end");
}
// Disconnect the client
if (client.connected()) {
//Serial.println();
Serial.print("disconnecting");
client.stop();
}
// Wait another 9s, which will give us a delay of roughly 10s
delay(9000);
}
I assume that the call to lan.php?pid=8855 will just return the value without any formatting, e.g., HTML, XML, JSON. Then your code basically converts the ASCII character 3 to an integer which gives you the integer value 33 (see ASCII Table). Therefore, your loop won't stop.
Solution
Just use the atoi function to convert it to an integer.
char c = atoi(client.read());
It seems that toInt() was the function I was looking for. It convert a string to integer and fixes the loop.
https://www.arduino.cc/en/Reference/StringToInt
Code has been updated and it seems to work:
#include <Ethernet.h>
#include <SPI.h>
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
byte ip[] = { 192, 168, 1, 104 };
char server[] = "b2b.as";
void setup()
{
Ethernet.begin(mac, ip);
Serial.begin(9600);
delay(1000);
Serial.println(Ethernet.localIP());
Serial.println();
// Set digital pin as output
// 5V
pinMode(8, OUTPUT);
}
void loop()
{
//
Serial.print("\n-----\n");
// Connect to the server
Serial.print("connecting to URL ...");
// Start LAN connection
EthernetClient client;
if (client.connect(server, 80)) {
Serial.println("connected");
client.println("GET /lan.php?pid=8855");
client.println();
} else {
Serial.println("connection failed");
}
// Wait a moment for data to arrive
// Note: This is NOT a reliable way of doing this!
delay(1000);
if (client.available() > 0) {
String pickNum;
while (client.available()) {
char c = client.read(); // gets one byte from serial buffer
pickNum += c; // count
delay(2); // delay for buffer
}
Serial.print("page value (pick): ");
Serial.println(pickNum);
for (int x = 1; x <= pickNum.toInt(); x++) {
Serial.print("picking: #");
Serial.println(x);
digitalWrite(8, HIGH);
Serial.println("8 HIGH ...");
delay(1000); // Add switch
digitalWrite(8, LOW);
Serial.println("8 LOW ...");
delay(1000);
}
Serial.print("end");
}
// Disconnect the client
if (client.connected()) {
//Serial.println();
Serial.print("disconnecting");
client.stop();
}
// Wait another 9s, which will give us a delay of roughly 10s
delay(9000);
}

RFid click board with CR95HF microcontroller refuses to respond

I have an Arduino with a RFid click board from Mikro Electronika. The click board has a microcontroller CR95HF microcontroller. According to the datasheet when I send the ECHO command I should poll and then read the returned value 0x55. If I use the command IDN (0x01) and send a datalength of zero, I should get the ID of the controller back.
According to the serial monitor it only returns zero (is there something wrong with the variable?).
According to the logic analyzer it returns the exact same thing as what was send
(when I send 3, it returns 3, when i send 55, it returns 55).
It seems the microcontroller doesn't react anything I send it or it does and it's just broken?
So right now it looks like it is able to send something through the spi.transfer() function, but the retrieve seems to be a problem.
Here's my code:
#include <SPI.h>
// CR95HF: Write, poll, read, reset
#define CMD 0x00
#define POLL 0x03
#define READ 0x02
#define RESET 0x01
#define ECHO 0x55
const int _SSpin = 10; // CS
const int _IRQpin = 6; // INT_out : 2, INT_in : 6, tried both, barely to no difference
//const int _SI0pin = A3;
//const int _SI1pin = A0;
void WakeupCR95HF()
{
//Serial.println("Wake up!");
digitalWrite(_IRQpin, LOW);
delay(100);
digitalWrite(_IRQpin, HIGH);
delay(100);
}
bool EchoResponse()
{
byte len = 0;
// write to CR95HF
digitalWrite(_SSpin, LOW);
delay(100);
SPI.transfer(0x00);
// Serial.print("echo code: ");
// Serial.println(ECHO);
SPI.transfer(0x55);
//SPI.transfer(0x00);
digitalWrite(_SSpin, HIGH);
//delay(1000);
// poll to CR95HF, is it ready?
byte tmp = 0;
digitalWrite(_SSpin, LOW);
while (!tmp)
{
delay(100);
//Note: whatever I send, I get the same thing back. I send 3, then tmp is 3. I send 8, tmp is 8.
SPI.transfer(0x03);
tmp = SPI.transfer(0);
// Serial.print("Polling: ");
Serial.println(tmp, BIN);
tmp = (tmp & 0x08) >> 3;
delay(100);
}
digitalWrite(_SSpin, HIGH);
delay(20);
// ready to write
byte res = 0;
digitalWrite(_SSpin, LOW);
delay(100);
SPI.transfer(0x02);
res = SPI.transfer(0);
// Serial.print("reading: ");
// Serial.println(res);
delay(100);
digitalWrite(_SSpin, HIGH);
delay(100);
if (res == ECHO)
{
return true;
}
return false;
}
void setup() {
Serial.begin(9600);
// I believe this is not possible on Arduino or not nessaccery, tried it anyway, no change
// pinMode(_SI0pin, OUTPUT);
// pinMode(_SI1pin, OUTPUT);
pinMode(_SSpin, OUTPUT);
pinMode(_IRQpin, OUTPUT);
// digitalWrite(_SI0pin, HIGH);
// digitalWrite(_SI1pin, LOW);
digitalWrite(_IRQpin, HIGH); // wakeup
delay(20);
digitalWrite(_SSpin, HIGH); // slave select, low = ready to write/read
delay(20);
SPI.begin();
// 2 MHz max clock speed, Most Significant Bit first, SPI_MODE unknown (probably 0, all were tried)
SPI.beginTransaction(SPISettings(2000000, MSBFIRST, SPI_MODE0));
WakeupCR95HF();
while(!EchoResponse())
{
WakeupCR95HF();
}
// Serial.println("Connection established");
}
void loop() {
}

Why is my Arduino freezing when using a relay board?

I'm working on a project where I use midi notes to switch 8 old lamps using the Arduino Uno. I've built a case with 8 wall sockets that are linked up to a relay board for the Arduino. I am using the Hairless midi serial bridge to send midi notes via USB to the Arduino.
This all works until I put power on the sockets with my Uno. After about 5~10 seconds the Arduino freezes. The relay shield stays in it's current state and the indication lights for serial communication stop flashing. When there isn't 220 volts going through the relays it all works great.
(My schematics are below.) The Arduino is powered via USB. I also tried powering the Arduino with an additional adapter of 5V and 500mA but that didn't make a difference.
Code:
#include <digitalWriteFast.h>
byte incomingByte=0;
byte notebyte=0;
byte velocitybyte=0;
byte statusbuffer=0;
byte NOTE_ON = 144;
byte NOTE_OFF = 128;
boolean arp_triggernext=false;
boolean firstbyte;
void MIDI_Poll(){
if (Serial.available() > 0) {
do {
// read the incoming byte:
incomingByte = Serial.read();
if (incomingByte>247) {
// this is where MIDI clock stuff is done
switch (incomingByte){
}
}
else if (incomingByte>240) {
statusbuffer = 0;
//sysex stuff done here
}
else if (incomingByte>127) {
statusbuffer = incomingByte;
firstbyte = true;
notebyte = 0;
velocitybyte = 0;
}
else if (statusbuffer!=0) {
if (firstbyte == true) {
// must be first byte
notebyte = incomingByte;
firstbyte = false;
}
else {
// so must be second byte then
velocitybyte = incomingByte;
//process the message here
if (statusbuffer == NOTE_ON && velocitybyte != 0) {
switch (notebyte) {
case 60:
digitalWriteFast2(2, HIGH);
break;
case 61:
digitalWriteFast2(3, HIGH);
break;
case 62:
digitalWriteFast2(4, HIGH);
break;
case 63:
digitalWriteFast2(5, HIGH);
break;
case 64:
digitalWriteFast2(6, HIGH);
break;
case 65:
digitalWriteFast2(7, HIGH);
break;
case 66:
digitalWriteFast2(8, HIGH);
break;
case 67:
digitalWriteFast2(9, HIGH);
break;
}
}
else if (statusbuffer == NOTE_OFF || (statusbuffer == NOTE_ON && velocitybyte == 0)) {
switch (notebyte){
case 60:
digitalWriteFast2(2, LOW);
break;
case 61:
digitalWriteFast2(3, LOW);
break;
case 62:
digitalWriteFast2(4, LOW);
break;
case 63:
digitalWriteFast2(5, LOW);
break;
case 64:
digitalWriteFast2(6, LOW);
break;
case 65:
digitalWriteFast2(7, LOW);
break;
case 66:
digitalWriteFast2(8, LOW);
break;
case 67:
digitalWriteFast2(9, LOW);
break;
}
}
//now clear them for next note
notebyte = 0;
velocitybyte = 0;
firstbyte = true;
}
}
} while (Serial.available() > 0);
}
}
void setup() {
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
pinMode(8, OUTPUT);
pinMode(9, OUTPUT);
Serial.begin(9600);
}
void loop() {
MIDI_Poll();
}
It's based on code I've found for processing serial midi.
I'm really confused as to why this happens. I want to know why my Arduino and relay board freeze when there is 220 volts going through the relays.
Materials:
Arduino Uno revision 3
Relay board with 8 relays switched with 5 volt. Capable of handling 10A. Bought here: https://iprototype.nl/products/components/buttons-switches/relay-board-8-channels-5v
8 normal wallsockets powered with 220 volts
8 light bulbs with E27 fitting
As I am seeing here is some circuit issues so i am going to explain them 1 by 1
1. you should not run relay directly from Arduino pin so use appropriate circuit with transistor to run a relay and use arduino pin as a sink not a source will be better.
2.use a freewheeling diode with relay coil.
3.use optoisolator at Rx and Tx.

Resources