I need to ring the buzzer within the range of 1 meter only, my esp8266 is connected to a buzzer but the buzzer will ring on and off within the range of 1 meter using two esp8266, or sometimes it does not ring at all. The project is social distancing, what else should I do? Here is the code I am using:
#include <ESP8266WiFi.h>
const char* APssid = "Social Distancing"; //acess point of the device
const char* APpassword = "qwertyuiop";
const int RSSI_MAX = -37;//maximum strength of signal in dBm
const int RSSI_MIN =-100;//minimum strength of signal in dBm
void setup()
{
WiFi.mode(WIFI_OFF);
WiFi.disconnect();
delay(50); //this part turns off the wifi and resets it if it was already on
Serial.begin(115200);
pinMode(14,OUTPUT);
Serial.println();
WiFi.mode(WIFI_AP_STA); //configuring the board in hybrid mode
Serial.print("Configuring access point...");
WiFi.softAP(APssid, APpassword);
Serial.println(WiFi.softAPIP());
}
void loop()
{
Serial.println("Wifi is scanning");
int n = WiFi.scanNetworks();
Serial.println("Wifi scan ended");
if (n == 0)
{
Serial.println("no networks found");
}
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
//Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(") ");
Serial.print(WiFi.SSID(i));//SSID
Serial.print(WiFi.RSSI(i));//Signal strength in dBm
Serial.print("dBm (");
if(WiFi.SSID(i) == "Social Distancing")
{
if(WiFi.RSSI(i) > -37)//THIS -37 (RSSI) is the threshold value, this value is set
according to the distance of 1m
{
digitalWrite(14,HIGH);//(Generic esp8266 : (14,HIGH) , NodeMCU : (D5,HIGH) )
Serial.println("Social Distancing");
break;
}
}
else
{
digitalWrite(14,LOW);
}
}
delay(50);
}
Serial.println("");
delay(50);
WiFi.scanDelete();
}
Hi Lisa I have modified your code and I have added a 64x48 OLED display connected to the I2C connections, to visualize the results and it works beautifully. Moreover I have used the built in led (see: LED_BUILTIN) instead of the buzzer.
You have had a great idea. Now it works great and you can interrogate any Access point.
Please find attached the code:
//OLED
#include <Arduino.h>
#include <U8g2lib.h>
#include <U8x8lib.h> //this one in use
#ifdef U8X8_HAVE_HW_SPI
#include <SPI.h>
#endif
#ifdef U8X8_HAVE_HW_I2C
#include <Wire.h>
#endif
U8X8_SSD1306_64X48_ER_HW_I2C u8x8(/* reset=*/ U8X8_PIN_NONE); // EastRising 0.66" OLED breakout board, Uno: A4=SDA, A5=SCL, 5V powered
// End of constructor list
#define U8LOG_WIDTH 16
#define U8LOG_HEIGHT 8
uint8_t u8log_buffer[U8LOG_WIDTH*U8LOG_HEIGHT];
U8X8LOG u8x8log;
//OLED end
#include <ESP8266WiFi.h>
const char* APssid = "My_SSID"; //acess point of the device
const char* APpassword = "My_Password";
//const char* myconstcharstarstring = "------------------------------";
const int RSSI_MAX = -37;//maximum strength of signal in dBm
const int RSSI_MIN =-100;//minimum strength of signal in dBm
void setup()
{
//OLED
u8x8.begin();
u8x8.setFont(u8x8_font_chroma48medium8_r);
u8x8log.begin(u8x8, U8LOG_WIDTH, U8LOG_HEIGHT, u8log_buffer);
u8x8log.setRedrawMode(1); // 0: Update screen with newline, 1: Update screen for every char
//OLED end
WiFi.mode(WIFI_OFF);
WiFi.disconnect();
delay(50); //this part turns off the wifi and resets it if it was already on
Serial.begin(115200);
pinMode(LED_BUILTIN,OUTPUT);
Serial.println();
WiFi.mode(WIFI_AP_STA); //configuring the board in hybrid mode
Serial.print("Configuring access point...");
WiFi.softAP(APssid, APpassword);
Serial.println(WiFi.softAPIP());
}
void loop()
{
digitalWrite(LED_BUILTIN,LOW);
Serial.println("Wifi is scanning");
int n = WiFi.scanNetworks();
Serial.println("Wifi scan ended");
if (n == 0)
{
Serial.println("no networks found");
}
else
{
Serial.print(n);
Serial.println(" networks found");
for (int i = 0; i < n; ++i)
{
//Print SSID and RSSI for each network found
Serial.print(i + 1);
Serial.print(") ");
Serial.print(WiFi.SSID(i));//SSID
Serial.print(WiFi.RSSI(i));//Signal strength in dBm
Serial.print("dBm (");
if(WiFi.RSSI(i) > -37)//THIS -37 (RSSI) is the threshold value, this value is set according to the distance of 1m
{
digitalWrite(LED_BUILTIN,HIGH);//(Generic esp8266 : (14,HIGH) , NodeMCU : (D5,HIGH) )
Serial.println("Social Distancing");
delay(500);
}
//OLED
u8x8log.print(WiFi.SSID(i));
u8x8log.print("\n");
u8x8log.print(WiFi.RSSI(i));
u8x8log.print("\n");
u8x8log.print("-------------");
u8x8log.print("\n");
delay(2000);
}
Serial.println("");
delay(50);
WiFi.scanDelete();
}
}
Hope this answers All the best
Hi Lisa please add digitalWrite(14,HIGH); at the beginning of the loop, it will work:
void loop()
{
digitalWrite(14,HIGH);
/... rest of your code...
I don't know how you have wired your buzzer, try forcing your ouput pin HIGH or LOW depending on your circuit.
Hope this helps All the best
Related
Here I'm trying to Send the SPI command from the master (Arduino Nano) to the slave(ATMEGA324PB).
First Master receives a command from the serial monitor. When the serial message receives completely, the Master passes the message to the Slave. Whenever the slave has a message to send, it will interrupt the Arduino nano using pin 3. However, in the first round slave send messages to master, and master can read it successfully. But in the second round It couldn't happen. I was unable to find the issue. I will attach the codes below.
User message is like in this manner XF01600#.
Send X (or Y)
Send F (or B)
Send 01600
Send #
This is my Master Code :
` #include <SPI.h>`
char Direction;
char Axis;
char TxCommand;
char TxEnd;
bool stringComplete = false; // Is receive complete ?
bool TxComplete=false;
int k=0;
int j=0;
String StepCount;
SPISettings setting(200000,MSBFIRST,SPI_MODE0);
void setup() {
Serial.begin(9600);
pinMode(10,OUTPUT);
pinMode(9,OUTPUT);
pinMode(2,OUTPUT);
attachInterrupt(digitalPinToInterrupt(3),SlaveReceive,RISING);
SPI.begin();
}
void SlaveReceive(){
SPI.begin();
SPI.beginTransaction(setting);
digitalWrite(10,LOW);
TxCommand=SPI.transfer(0xFF);//dummy
TxEnd=SPI.transfer(0xFF);//dummy
digitalWrite(10,HIGH);
SPI.endTransaction();
Serial.print("Received Command-");
Serial.println(TxCommand );
Serial.print("Received End-");
Serial.println(TxEnd);
if(TxEnd=='~'){
TxComplete=true;
}
}
void SPI_Transfer(){
SPI.transfer(Direction);//transfer direction
delay(5);
SPI.transfer(StepCount.length());//transfer incoming step length
delay(5);
for(int i=0;i<StepCount.length();i++){//transfer step count;
SPI.transfer(StepCount[i]);
Serial.println(StepCount[i]);
delay(5);
}
SPI.transfer('#');
delay(5);
}
void loop() {
if (stringComplete) {
if(Direction=='F'){
digitalWrite(2,HIGH);
}
else if(Direction=='B'){
digitalWrite(2,LOW);
}
Serial.print("Direction-");
Serial.println(Direction);
Serial.println(StepCount);
Serial.println(StepCount.length());
SPI.beginTransaction(setting);
if(Axis=='X'){ // Chip Select line for X axis driver is pin 10;
digitalWrite(10,LOW);
SPI_Transfer();
digitalWrite(10,HIGH);
}
else if(Axis=='Y'){ /// Chip select line for Y axis driver is pin 9;
digitalWrite(9,LOW);
SPI_Transfer();
digitalWrite(9,HIGH);
}
SPI.endTransaction();
stringComplete = false;
k=0;
}
if(TxComplete){
if(TxCommand=='S'){
digitalWrite(2,LOW);
TxComplete=false;
}
}
}
void serialEvent() {
while (Serial.available()>0) {
if(k==0){
Axis = Serial.read();
k++;
}
else if(k==1){
Direction=Serial.read();
k++;
}
else if(Serial.read()!='#'){
//StepCount[k-1]=Serial.readString();
StepCount=Serial.parseInt();
k++;
}
else{
stringComplete = true;
}
}
}
Slave Main Command :
while(1){
if(SPI_RECEIVE_COMPLETE){
SPI_RECEIVE_COMPLETE=false;
PORTA |=(1<<4);
Decode_SPI_Command();
switch (SPI_Command)
{
case 'F':
_Run_Motor(SPI_Data, true, 1, 0.3);//10 CYCLE
SlaveSendData(0x53);//S
break;
case 'B':
_Run_Motor(SPI_Data, false, 1, 0.3);
SlaveSendData(0x53);//S
break;
}
for(uint8_t i=0;i<15;i++){
SPI_Received_Data[i]=0;
}
SPI_Data=0;
SPI_BYTES_Transfer=0;
}
PORTA &=~(1<<4);
}
The Slave data send function:
void SlaveSendData(uint8_t SlaveCommand){
SPI_BYTES_Transfer=0;
SPI_Data_TX=true;
SPDR1=SlaveCommand;
SPI_Transmit_Data[0]=0x7E;//~
PORTA |=(1<<3);
_delay_ms(10);
PORTA &=~(1<<3);
}
Slave SPI interrupt function:
ISR(SPI1_STC_vect){
if(SPI_Data_TX){//slave is transmitting data
SPDR1 = SPI_Transmit_Data[SPI_BYTES_Transfer];
SPI_BYTES_Transfer++;
if(SPI_Received_Data[SPI_BYTES_Transfer-1]=='~'){
SPI_Data_TX=false;
//SPDR1=0x00;
SPI_BYTES_Transfer=0;
}
}
else{
SPI_Received_Data[SPI_BYTES_Transfer] = SPDR1;
SPI_BYTES_Transfer++;
if(SPI_Received_Data[SPI_BYTES_Transfer-1]=='#'){
SPI_RECEIVE_COMPLETE=true;
SPDR1=0x00;
}
}
}
Here I have found that in the else part SPI_RECEIVE_COMPLETE=true; never occurs on the second try. But I couldn't find where the issue is..?
serial monitor
Arduino Serial Monitor
Could you please take a look, Thank you.
I am programming an ESP32 with C (with the toolchain for ESP32) and I'm trying to change the clock frequency of my ESP32 but I'm quite unsure if I'm doing it right (I used the documenation https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/power_management.html#_CPPv418esp_pm_lock_type_t but I didn't find any code examples). I think I've done the program part right but I think it still doesn't work. Is there a way to figure out the the clock frequency that is set?
I'm also unsure about this part in documentation:
"ESP_PM_CPU_FREQ_MAX
Require CPU frequency to be at the maximum value set via esp_pm_configure. Argument is unused and should be set to 0."
Does the last part mean I shouldn't use this makro?
Last but not least I didnt't understand if I have to change my sdkconfig or is there a way to do everything in C?
I have to measure for a project times in region of ns hence I need maximum performance of esp32.
Code:
// ____________________________________________________________________________
esp_pm_config_esp32_t config_clock_struct;
// ____________________________________________________________________________
esp_pm_config_esp32_t* pointer_config_clock = &config_clock_struct;
// ____________________________________________________________________________
esp_pm_lock_handle_t handle;
void config_clock(int max_cpu_freq, int min_cpu_freq, bool light_sleep_enable,
esp_pm_config_esp32_t* pointer_config_clock) {
pointer_config_clock->max_freq_mhz = max_cpu_freq;
pointer_config_clock->min_freq_mhz = min_cpu_freq;
pointer_config_clock->light_sleep_enable = light_sleep_enable;
esp_err_t status = esp_pm_configure(pointer_config_clock);
if (status == ESP_OK) {
return;
} else if (status == ESP_ERR_INVALID_ARG) {
printf("Error %d: Configuration values aren't correct.", status);
exit(1);
} else if (status == ESP_ERR_NOT_SUPPORTED) {
printf("Error %d: Combination of values aren't supported or CONFIG_PM_ENABLE isn't enabled in sdkconfig.",
status);
exit(1);
}
}
// ____________________________________________________________________________
void init_clock(int max_cpu_freq, int min_cpu_freq, bool light_sleep_enable,
esp_pm_lock_type_t lock_type, int arg, const char* name,
esp_pm_config_esp32_t* pointer_config_clock, esp_pm_lock_handle_t* out_handle) {
config_clock(max_cpu_freq, min_cpu_freq, light_sleep_enable, pointer_config_clock);
esp_err_t status = esp_pm_lock_create(lock_type, arg, name, out_handle);
if (status == ESP_OK) {
return;
} else if (status == ESP_ERR_NO_MEM) {
printf("Error %d: Struct can't allocated.", status);
} else if (status == ESP_ERR_INVALID_ARG) {
printf("Error: %d: Invalid arguments.", status);
} else if(ESP_ERR_NOT_SUPPORTED == status) {
printf("Error %d: config pm is not enabled in sdkconfig.", status);
}
}
And the relevant part of the main function:
#define MAX_FREQUENCY 240
#define MIN_FREQUENCY 40
#define DISABLE_SLEEP 0
init_clock(MAX_FREQUENCY, MIN_FREQUENCY, DISABLE_SLEEP, ESP_PM_CPU_FREQ_MAX, ESP_PM_CPU_FREQ_MAX,
"measure mode", pointer_config_clock, &handle);
esp_err_t status_acquire = esp_pm_lock_acquire(handle);
When one changes MCU clock frequency it alters all frequency dependent buses. For instance UART and I2C. Here's a neat hack to demonstrate how changing of clock frequency affects serial.print output. Mind you calculated Serial baud rates differ for each clock speed set.
//function takes the following frequencies as valid values:
// 240, 160, 80 <<< For all XTAL types
// 40, 20, 10 <<< For 40MHz XTAL
// 26, 13 <<< For 26MHz XTAL
// 24, 12 <<< For 24MHz XTAL
// 32Bit MCUs . change for 16bit
uint32_t Freq = 0;
int MCU_FREQUENCY_SERIAL_SPEED=115200;
int SERIAL_DEFAULT_SPEED = 115200;
void changeMcuFreq(int Freq){
delay(500);
setCpuFrequencyMhz(Freq);
changeSerialBaudRate(Freq);
delay(500);
}
void serialMcuFreq(){
Freq = getCpuFrequencyMhz();
Serial.print("CPU Freq = ");
Serial.print(Freq);
Serial.println(" MHz");
Freq = getXtalFrequencyMhz();
Serial.print("XTAL Freq = ");
Serial.print(Freq);
Serial.println(" MHz");
Freq = getApbFrequency();
Serial.print("APB Freq = ");
Serial.print(Freq/1000000);
Serial.println(" MHz");
}
void changeSerialBaudRate(uint32_t Freq){
if (Freq < 80) {
MCU_FREQUENCY_SERIAL_SPEED = 80 / Freq * SERIAL_DEFAULT_SPEED;
}
else {
MCU_FREQUENCY_SERIAL_SPEED = SERIAL_DEFAULT_SPEED;
}
Serial.end();
delay(1000);
Serial.begin(MCU_FREQUENCY_SERIAL_SPEED);
delay(1000);
Serial.print("\nSerial Baud Rate Speed is ");
Serial.println(MCU_FREQUENCY_SERIAL_SPEED);
}
void setup()
{
Serial.begin(MCU_FREQUENCY_SERIAL_SPEED);
}
void loop()
{
changeMcuFreq(240);
serialMcuFreq();
delay(2000);
changeMcuFreq(160);
serialMcuFreq();
delay(2000);
changeMcuFreq(80);
serialMcuFreq();
delay(2000);
changeMcuFreq(40);
serialMcuFreq();
delay(2000);
changeMcuFreq(20);
serialMcuFreq();
delay(2000);
changeMcuFreq(10);
serialMcuFreq();
delay(2000);
}
I'm trying to stream voice to the MQTT broker. I'm using esp8266(NodeMCU1.0) and it's ADC to sampling the audio signal at 4KHz and 8-bit PCM audio format. I used Pubsubclient.h library to publish audio packets to the broker but on the other side when I receive packets and play them I have the interrupted voice and I have a delay between playing packets as long as my buffer size. please help me to have continues voice.
I have 2 main problems:
1) delay between playing packets as long as my buffer size
example of what i received: ;D ;D ;D .....|||||..........|||||||...........|||||||||............||||||||
2) Quality of voice: I receive a noisy voice.
Please help me! Thanks.
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "Knight";
const char* password = "****";
const char* mqtt_server = "104.21.218.224";
WiFiClient espClient;
PubSubClient client(espClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE (4096)
int i;
byte voice[MSG_BUFFER_SIZE];
void setup_wifi() {
delay(10);
// We start by connecting to a WiFi network
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
randomSeed(micros());
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Create a random client ID
String clientId = "ashkan";
// Attempt to connect
if (client.connect(clientId.c_str())) {
Serial.println("connected");
// Once connected, publish an announcement...
if (!client.publish("doorphone/connected", "true")) {
Serial.println("publish failed, either connection lost, or message too large");
}
else {
Serial.println("publish succeeded");
}
// ... and resubscribe
// client.subscribe("doorphone/open");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 5 seconds");
// Wait 5 seconds before retrying
delay(5000);
}
}
}
void setup() {
pinMode(BUILTIN_LED, OUTPUT); // Initialize the BUILTIN_LED pin as an output
Serial.begin(115200);
setup_wifi();
client.setServer(mqtt_server, 1883);
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
for (i = 0; i < MSG_BUFFER_SIZE; i++) {
voice[i] = analogRead(A0);
// client.write(voice[i]);
delayMicroseconds(125);
}
client.publish("doorphone/connected", voice, MSG_BUFFER_SIZE);
}
This is my code
#include <WiFi.h>
//#include "StepperMotor.h"
#define SDA_PIN 4
#define SCL_PIN 5
const char* ssid = "StepperMotorWireless";
const char* password = "";
WiFiServer server(9090);
WiFiClient client;
char buffer[50] = {0};
int buffercounter = 0;
TaskHandle_t StepperHandler;
TaskHandle_t WifiHandler;
void setup()
{
Serial.begin(9600);
SetWifi(ssid, password);
pinMode(2, OUTPUT);
xTaskCreatePinnedToCore(
StepperLoop, /* Task function. */
"StepperHandler", /* name of task. */
4000, /* Stack size of task */
NULL, /* parameter of the task */
2, /* priority of the task */
&StepperHandler, /* Task handle to keep track of created task */
1); /* pin task to core 0 */
}
void SetWifi(const char* name, const char* password)
{
WiFi.disconnect();
WiFi.mode(WIFI_AP_STA);
WiFi.softAP(name, password);
delay(2000);
IPAddress IP = WiFi.softAPIP();
Serial.print("Server IP : ");
Serial.println(IP);
server.begin();
server.setNoDelay(true);
Serial.println("Server Started");
}
void availableMessage() {
if (client && client.connected() && client.available()) {
while (client.available()) {
String message = client.readStringUntil('\n');
Serial.println(message);
char temp[50];
message.toCharArray(temp, 50);
client.flush();
}
}
}
void connectClient() {
if (server.hasClient())
{
if (client = server.available()) {
Serial.println("connected");
}
}
}
void StepperLoop( void * pvParameters ) {
digitalWrite(2, HIGH);
delay(1000);
digitalWrite(2, LOW);
delay(1000);
}
void loop()
{
connectClient();
availableMessage();
}
The problem is that my blinking LED is not 1 second long, so something is interrupting it (appearantly wifi is because that is the only other thing running).
That is weird because every on the internet you look, the Wifi task is pinned to Core 0, and I am running my blink code on Core 1, so that should not be interfering.
I cant seem to fix this, could someone help me out?
BTW I am using arduino IDE
What does not blinking 1 second long mean? Have you measured the time or could you see it directly?
Your LED/Stepper loop is not a loop! If you what the LED to blink more than once:
void StepperLoop( void * pvParameters ) {
while (1) {
digitalWrite(2, HIGH);
delay(1000);
digitalWrite(2, LOW);
delay(1000);
}
}
Hi I'm new and have had a bit of a search for a solution to this problem, but is appears to be unique.
I have an arduino uno and I want to control multiple dc motors speeds and directions with it wirelessly with an IR remote. I have managed to attach a motor and get the arduino to turn it on by pressing a button on the remote control, however I cannot get it to turn off by pressing another button. What happens is when I open the serial monitor for the arduino, it recognises the first IR signal and turns the motor on. However when the motor is spinning (and only when the motor is spinning) the arduino detects an endless stream of IR signals which stop the arduino from receiving any real ones. This occurs even when the IR receiver is pulled out of the circuit. I am using the analogWrite() function to turn the motor on and if I lower the pulse enough that the motor doesn't turn (but makes a noise) it can be started and stopped with the remote because it doesn't turn and therefore doesn't make the arduino receive IR signals. If I make the pulse low enough that I can forcibly stop the motor, the IR signals stop.
I have no idea what is happening and have tried altering my code and the circuits.
Here is the code I am using - I copied and modified one from adafruit which reads IR commands.
/* Raw IR commander
This sketch/program uses the Arduno and a PNA4602 to
decode IR received. It then attempts to match it to a previously
recorded IR signal
Code is public domain, check out www.ladyada.net and adafruit.com
for more tutorials!
*/
// We need to use the 'raw' pin reading methods
// because timing is very important here and the digitalRead()
// procedure is slower!
//uint8_t IRpin = 2;
// Digital pin #2 is the same as Pin D2 see
// http://arduino.cc/en/Hacking/PinMapping168 for the 'raw' pin mapping
#define IRpin_PIN PIND
#define IRpin 2
// the maximum pulse we'll listen for - 65 milliseconds is a long time
#define MAXPULSE 65000
#define NUMPULSES 50
// what our timing resolution should be, larger is better
// as its more 'precise' - but too large and you wont get
// accurate timing
#define RESOLUTION 20
// What percent we will allow in variation to match the same code
#define FUZZINESS 20
// we will store up to 100 pulse pairs (this is -a lot-)
uint16_t pulses[NUMPULSES][2]; // pair is high and low pulse
uint8_t currentpulse = 0; // index for pulses we're storing
#include "own_codes.h"
int numberpulses = 0;
int a;
void setup(void) {
Serial.begin(9600);
Serial.println("Ready to decode IR!");
}
void loop(void) {
numberpulses = listenForIR();
Serial.print("Heard ");
Serial.print(numberpulses);
Serial.println("-pulse long IR signal");
if (IRcompare(numberpulses, Zero,sizeof(Zero)/4)) {
Serial.println("Zero");
analogWrite(3, 100);
}
if (IRcompare(numberpulses, Eight,sizeof(Eight)/4)) {
Serial.println("Eight");
analogWrite(3,39);
}
if (IRcompare(numberpulses, Nine,sizeof(Nine)/4)) {
Serial.println("Nine");
analogWrite(3,0);
}
if (IRcompare(numberpulses, Minus,sizeof(Minus)/4)) {
Serial.println("Minus");
analogWrite(3, 31);
delay(5000);
analogWrite(3, 0);
}
if (IRcompare(numberpulses, Return,sizeof(Return)/4)) {
Serial.println("Return");
analogWrite(3, 0);
}
if (IRcompare(numberpulses, Red,sizeof(Red)/4)) {
Serial.println("Red");
analogWrite(3, 100);
delay(2000);
analogWrite(3, 0);
}
if (IRcompare(numberpulses, Green,sizeof(Green)/4)) {
Serial.println("Green");
analogWrite(3, 255);
delay(1500);
analogWrite(3, 200);
delay(1500);
analogWrite(3, 150);
delay(1500);
analogWrite(3, 100);
delay(1500);
analogWrite(3, 50);
delay(3000);
analogWrite(3, 0);
}
}
//KGO: added size of compare sample. Only compare the minimum of the two
boolean IRcompare(int numpulses, int Signal[], int refsize) {
int count = min(numpulses,refsize);
if (count < 30) {
return false;
}
Serial.print("count set to: ");
Serial.println(count);
for (int i=0; i< count-1; i++) {
int oncode = pulses[i][1] * RESOLUTION / 10;
int offcode = pulses[i+1][0] * RESOLUTION / 10;
#ifdef DEBUG
Serial.print(oncode); // the ON signal we heard
Serial.print(" - ");
Serial.print(Signal[i*2 + 0]); // the ON signal we want
#endif
// check to make sure the error is less than FUZZINESS percent
if ( abs(oncode - Signal[i*2 + 0]) <= (Signal[i*2 + 0] * FUZZINESS / 100)) {
#ifdef DEBUG
Serial.print(" (ok)");
#endif
} else {
#ifdef DEBUG
Serial.print(" (x)");
#endif
// we didn't match perfectly, return a false match
return false;
}
#ifdef DEBUG
Serial.print(" \t"); // tab
Serial.print(offcode); // the OFF signal we heard
Serial.print(" - ");
Serial.print(Signal[i*2 + 1]); // the OFF signal we want
#endif
if ( abs(offcode - Signal[i*2 + 1]) <= (Signal[i*2 + 1] * FUZZINESS / 100)) {
#ifdef DEBUG
Serial.print(" (ok)");
#endif
} else {
#ifdef DEBUG
Serial.print(" (x)");
#endif
// we didn't match perfectly, return a false match
return false;
}
#ifdef DEBUG
Serial.println();
#endif
}
// Everything matched!
return true;
}
int listenForIR(void) {
currentpulse = 0;
while (1) {
uint16_t highpulse, lowpulse; // temporary storage timing
highpulse = lowpulse = 0; // start out with no pulse length
// while (digitalRead(IRpin)) { // this is too slow!
while (IRpin_PIN & (1 << IRpin)) {
// pin is still HIGH
// count off another few microseconds
highpulse++;
delayMicroseconds(RESOLUTION);
// If the pulse is too long, we 'timed out' - either nothing
// was received or the code is finished, so print what
// we've grabbed so far, and then reset
// KGO: Added check for end of receive buffer
if (((highpulse >= MAXPULSE) && (currentpulse != 0))|| currentpulse == NUMPULSES) {
return currentpulse;
}
}
// we didn't time out so lets stash the reading
pulses[currentpulse][0] = highpulse;
// same as above
while (! (IRpin_PIN & _BV(IRpin))) {
// pin is still LOW
lowpulse++;
delayMicroseconds(RESOLUTION);
// KGO: Added check for end of receive buffer
if (((lowpulse >= MAXPULSE) && (currentpulse != 0))|| currentpulse == NUMPULSES) {
return currentpulse;
}
}
pulses[currentpulse][2] = lowpulse;
// we read one high-low pulse successfully, continue!
currentpulse++;
}
}
void printpulses(void) {
Serial.println("\n\r\n\rReceived: \n\rOFF \tON");
for (uint8_t i = 0; i < currentpulse; i++) {
Serial.print(pulses[i][0] * RESOLUTION, DEC);
Serial.print(" usec, ");
Serial.print(pulses[i][3] * RESOLUTION, DEC);
Serial.println(" usec");
}
// print it in a 'array' format
Serial.println("int IRsignal[] = {");
Serial.println("// ON, OFF (in 10's of microseconds)");
for (uint8_t i = 0; i < currentpulse-1; i++) {
Serial.print("\t"); // tab
Serial.print(pulses[i][4] * RESOLUTION / 10, DEC);
Serial.print(", ");
Serial.print(pulses[i+1][0] * RESOLUTION / 10, DEC);
Serial.println(",");
}
Serial.print("\t"); // tab
Serial.print(pulses[currentpulse-1][5] * RESOLUTION / 10, DEC);
Serial.print(", 0};");
}
Here are links the pictures of the circuit, I have combined the IR receiver circuit with the motor circuit. (I'm not allowed to post images directly)
IR receiver: https://learn.adafruit.com/system/assets/assets/000/000/555/medium800/light_arduinopna4602.gif?1396763990
Motor circuit:
http://cdn.instructables.com/F9L/KDFG/GU7FXUMH/F9LKDFGGU7FXUMH.MEDIUM.jpg
Any help would be much appreciated thank you.
Here are some information about motor interference:
http://forum.allaboutcircuits.com/threads/stop-noise-from-motor-to-arduino-mcu.90733/
http://forum.arduino.cc/index.php?topic=60247.0