xiejirui666 发表于 2023-8-4 16:48:22

今日任务:继续实现人体感应功能。请教陈大佬,教我多线程方法,实现了具体功能。
1.需要新建线程:
static void ExampleEntry(void)
{
        evt_id2 = osEventFlagsNew(NULL);
        if (evt_id2 == NULL)
        {
                printf("Falied to create EventFlags!\n");
        }
        osThreadAttr_t attr;

        attr.name = "Example_Task";
        attr.attr_bits = 0U;
        attr.cb_mem = NULL;
        attr.cb_size = 0U;
        attr.stack_mem = NULL;
        attr.stack_size = TASK_STACK_SIZE;
        attr.priority = TASK_PRIO;

        if (osThreadNew((osThreadFunc_t)Example_Task, NULL, &attr) == NULL)
        {
                printf("Falied to create Example_Task!\n");
        }
}
(注意:要定义在入口线程前)
2.在入口线程末端加入本线程入口ExampleEntry()
3.本线程会执行Example_Task,此处就是传感器代码:
static void Example_Task(void)
{
        // E53_IS1_Init();
        // E53_IS1_Read_Data(Beep_Alarm);

        while (1)
        {
                osEventFlagsWait(evt_id2, FLAGS_MSK1, osFlagsWaitAny, osWaitForever);
                Beep_StatusSet(ON);
                char data1 = "true";
                send(new_fd, data1, strlen(data1), 0);
                bzero(recvbuf, sizeof(recvbuf));
                GpioSetOutputVal(WIFI_IOT_GPIO_IDX_2, 1);
                osDelay(200);
                Beep_StatusSet(OFF);
                GpioSetOutputVal(WIFI_IOT_GPIO_IDX_2, 0);
        }
}
4:此线程会等待阻塞,等待设备端发送信号打开传感器,并监听物体靠近,标志位FLAGS_MSK1变化后执行之后函数。
osEventFlagsWait(evt_id2, FLAGS_MSK1, osFlagsWaitAny, osWaitForever);
5:所以主线程tcp发送消息,标志位会随物体靠近变化,主线程判断与相应语句:
                        if (strcmp(recvbuf, "rentiganyingon") == 0)
                        {

                                E53_IS1_Init();
                                E53_IS1_Read_Data(Beep_Alarm);
                        }
6:有物体靠近时发送true消息,前端利用消息判断并改变UI状态

xiejirui666 发表于 2023-8-4 17:13:18

BQ3568前端实现报警代码如下,点击开启后,有人靠近会报警,记录靠近次数,靠近会有图片与文字同步变化:
import router from '@ohos.router'
import promptAction from '@ohos.promptAction'
@Component
struct PageTitle {
build() {
    Row() {
      Image($r('app.media.back'))
      .width(20)
      .height(20)
      .onClick(() => {
          router.back()
      })
      Text("人体感应")
      .fontSize(22)
      .margin({ left: 20 })
    }
    .padding(12)
    .width('100%')
}
}



@Component
struct oneTable {
@State message: string = ''
@State imageBgColorA: number = 0
@StorageProp('currentBreakpoint') currentBreakpoint: string = 'sm'
@State jingbao: number = 0
@State cishu: number = 0
private timer: number = 0
@Builder IngredientItem() {



    Stack({ alignContent: Alignment.BottomStart }) {

      Image(this.jingbao? $r("app.media.ren_youren") : $r("app.media.ren_wuren0"))
      .backgroundColor(`rgba(255, 255, 255, ${this.imageBgColorA})`)
      .objectFit(ImageFit.Contain)
      Text(this.jingbao ? "有人靠近" :"无人靠近" )
      .align(Alignment.Center).width('50%').fontSize(25).height('10%')

    }
    .height(this.currentBreakpoint == 'lg' ? 166 : 280)
    Column() {
      Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.Center }) {
      Column() {
          Row() {

            Text("人体感应")
            .fontSize(18)
            .fontWeight(FontWeight.Bold)
            .layoutWeight(1)
            .align(Alignment.Start)
            Row() {
            Button('开', { type: ButtonType.Normal, stateEffect: true })
                .borderRadius(8)
                .backgroundColor(0x317aff)
                .width(90)
                .onClick(() => {
                  promptAction.showToast({
                  message: '人体感应已打开',
                  duration: 1500
                  });

                  globalThis.tcp.connect({ address: globalThis.mixeraddr , timeout: 6000 }, () => {
                  //   电脑ip
                  //   tcp.connect({ address: { address: '192.168.2.125', port: 3861, family: 1 }, timeout: 6000 }, () => {
                  console.log('connect success');
                  globalThis.tcp.send({
                      data: 'rentiganyingon'
                      //此处省略encoding, 默认为utf-8编码格式
                  }, err => {
                      if (err) {
                        console.log('send fail' + JSON.stringify(err));
                        return;
                      }
                      console.log('send success');
                  })
                  })

                  globalThis.tcp.on('message', value => {
                  console.log("on message")
                  let buffer = value.message
                  let dataView = new DataView(buffer)
                  let str = ""
/*                  clearInterval(this.timer)
                  this.timer = setTimeout(() => {

                  }, 500)*/
                  for (let i = 0; i < dataView.byteLength; ++i) {
                      str += String.fromCharCode(dataView.getUint8(i))
                  }
                  console.log("on connect received:" + str)
                  if(Boolean(str)){
                      this.cishu ++;
                      this.jingbao = 1;
                      clearInterval(this.timer)
                      this.timer = setTimeout(() => {
                        this.jingbao = 0
                      }, 2000)
                  }
                      //                  else{

//                  }

                  });



                })
            Blank()
            Button('关', { type: ButtonType.Normal, stateEffect: true })
                .borderRadius(8)
                .backgroundColor(0x317aff)
                .width(90)
                .onClick(() => {

                  promptAction.showToast({
                  message: '人体感应已关闭',
                  duration: 1500
                  });
                  globalThis.tcp.connect({ address: globalThis.mixeraddr , timeout: 6000 }, () => {
                  //   电脑ip
                  //   tcp.connect({ address: { address: '192.168.2.125', port: 3861, family: 1 }, timeout: 6000 }, () => {
                  console.log('connect success');
                  globalThis.tcp.send({
                      data: 'rentiganyingoff'
                      //此处省略encoding, 默认为utf-8编码格式
                  }, err => {
                      if (err) {
                        console.log('send fail' + JSON.stringify(err));
                        return;
                      }
                      console.log('send success');
                  })
                  })
                })
            }
            .width('100%')
            .layoutWeight(2)
          }
          .padding(20)
          .margin({ bottom: 20 })

          Row(){
            Text('报警日志:')
            .align(Alignment.Center)
            .width('40%')
            Text(this.cishu.toString()+"次")
            .width('40%').align(Alignment.Center)

          }

      }

      }

    }.height('50%')
    .backgroundColor(Color.White)

}

build() {

    Column() {
      this.IngredientItem()
    }
}
}


@Entry
@Component
struct fengshan {
build() {
    Scroll() {
      Column() {
      PageTitle()
      Swiper() {
          oneTable()
      }
      .clip(new Rect().width('100%').height('100%').radiusWidth(15).radiusHeight(15))
      .itemSpace(20)
      .height(630)
      .indicatorStyle({ selectedColor: Color.Green })
      .margin({ top: 10, right: 10, left: 10 })

      }
      .alignItems(HorizontalAlign.Center)
    }
    .backgroundColor('#EDF2F5')
    .height('100%')
    .align(Alignment.Top)
}
}









xiejirui666 发表于 2023-8-4 17:17:50

学习线程连续打印:
void thread1(void)
{
    int sum=0;
    while (1)
    {
      /* code */
      printf("This is BearPi-HM_Nano Thread1----%d\r\n",sum++);
      usleep(1000000);
    }
}

void thread2(void)
{
    int sum=0;
    while (1)
    {
      /* code */
      printf("This is BearPi-HM_Nano Thread2----%d\r\n",sum++);
      usleep(500000);
    }   
}

static void Thread_example(void)
{
    osThreadAttr_t attr;

    attr.name = "thread1";
    attr.attr_bits = 0U;
    attr.cb_mem = NULL;
    attr.cb_size = 0U;
    attr.stack_mem = NULL;
    attr.stack_size = 1024*4;
    attr.priority = 25;

    if (osThreadNew((osThreadFunc_t)thread1, NULL, &attr) == NULL) {
      printf("Falied to create thread1!\n");
    }

    attr.name = "thread2";
   
    if (osThreadNew((osThreadFunc_t)thread2, NULL, &attr) == NULL) {
      printf("Falied to create thread2!\n");
    }
}

页: 1 2 [3]
查看完整版本: 我司BQ3568-HM开发板与3861开发板实现TCP通讯